@tanay-wispr/webflow-package 6.7.1 → 6.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/androidWaitlist.js +1 -1
- package/dist/calculator-business.js +1 -1
- package/dist/calculator.js +1 -1
- package/dist/desktopAuth.js +1 -1
- package/dist/downloads.js +2 -2
- package/dist/global.js +2 -2
- package/dist/login.js +1 -1
- package/dist/pricing.js +1 -1
- package/dist/signup.js +1 -1
- package/package.json +1 -1
package/dist/androidWaitlist.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var Ai=Object.create;var jt=Object.defineProperty;var Ri=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var Pi=Object.getPrototypeOf,Oi=Object.prototype.hasOwnProperty;var Ii=(i,e)=>()=>(i&&(e=i(i=0)),e);var ee=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),ji=(i,e)=>{for(var t in e)jt(i,t,{get:e[t],enumerable:!0})},Xr=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ci(e))!Oi.call(i,s)&&s!==t&&jt(i,s,{get:()=>e[s],enumerable:!(r=Ri(e,s))||r.enumerable});return i};var Qr=(i,e,t)=>(t=i!=null?Ai(Pi(i)):{},Xr(e||!i||!i.__esModule?jt(t,"default",{value:i,enumerable:!0}):t,i)),$i=i=>Xr(jt({},"__esModule",{value:!0}),i);var ve={};ji(ve,{Headers:()=>hr,Request:()=>Ni,Response:()=>Di,default:()=>ur,fetch:()=>Mi});var Ui,Me,Mi,ur,hr,Ni,Di,me=Ii(()=>{"use strict";Ui=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},Me=Ui(),Mi=Me.fetch,ur=Me.fetch.bind(Me),hr=Me.Headers,Ni=Me.Request,Di=Me.Response});var ns=ee(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});var fr=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};pr.default=fr});var gr=ee(it=>{"use strict";var os=it&&it.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(it,"__esModule",{value:!0});var Fi=os((me(),$i(ve))),Hi=os(ns()),mr=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=Fi.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,s=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let d=null,c=null,u=null,f=n.status,g=n.statusText;if(n.ok){if(this.method!=="HEAD"){let y=await n.text();y===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=y:c=JSON.parse(y))}let m=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),p=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");m&&p&&p.length>1&&(u=parseInt(p[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(d={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,u=null,f=406,g="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{let m=await n.text();try{d=JSON.parse(m),Array.isArray(d)&&n.status===404&&(c=[],d=null,f=200,g="OK")}catch{n.status===404&&m===""?(f=204,g="No Content"):d={message:m}}if(d&&this.isMaybeSingle&&(!((l=d?.details)===null||l===void 0)&&l.includes("0 rows"))&&(d=null,f=200,g="OK"),d&&this.shouldThrowOnError)throw new Hi.default(d)}return{error:d,data:c,count:u,status:f,statusText:g}});return this.shouldThrowOnError||(s=s.catch(n=>{var o,a,l;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}};it.default=mr});var yr=ee(nt=>{"use strict";var Vi=nt&&nt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(nt,"__esModule",{value:!0});var Bi=Vi(gr()),_r=class extends Bi.default{select(e){let t=!1,r=(e??"*").split("").map(s=>/\s/.test(s)&&!t?"":(s==='"'&&(t=!t),s)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let n=typeof s>"u"?"offset":`${s}.offset`,o=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),d=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${d}"; 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}};nt.default=_r});var Dt=ee(ot=>{"use strict";var Wi=ot&&ot.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ot,"__esModule",{value:!0});var zi=Wi(yr()),wr=class extends zi.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(s=>typeof s=="string"&&new RegExp("[,()]").test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};ot.default=wr});var br=ee(lt=>{"use strict";var Gi=lt&<.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(lt,"__esModule",{value:!0});var at=Gi(Dt()),vr=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=t,this.schema=r,this.fetch=s}select(e,{head:t=!1,count:r}={}){let s=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new at.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let s="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new at.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),s&&a.push(`count=${s}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((d,c)=>d.concat(Object.keys(c)),[]);if(l.length>0){let d=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",d.join(","))}}return new at.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",s=[];return this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),this.headers.Prefer=s.join(","),new at.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 at.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};lt.default=vr});var as=ee(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.version=void 0;qt.version="0.0.0-automated"});var ls=ee(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.DEFAULT_HEADERS=void 0;var Ji=as();Ft.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Ji.version}`}});var ds=ee(ct=>{"use strict";var cs=ct&&ct.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ct,"__esModule",{value:!0});var Ki=cs(br()),Yi=cs(Dt()),Xi=ls(),kr=class i{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},Xi.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new Ki.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||s?(o=r?"HEAD":"GET",Object.entries(t).filter(([c,u])=>u!==void 0).map(([c,u])=>[c,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([c,u])=>{a.searchParams.append(c,u)})):(o="POST",l=t);let d=Object.assign({},this.headers);return n&&(d.Prefer=`count=${n}`),new Yi.default({method:o,url:a,headers:d,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};ct.default=kr});var gs=ee(V=>{"use strict";var dt=V&&V.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(V,"__esModule",{value:!0});V.PostgrestBuilder=V.PostgrestTransformBuilder=V.PostgrestFilterBuilder=V.PostgrestQueryBuilder=V.PostgrestClient=void 0;var us=dt(ds());V.PostgrestClient=us.default;var hs=dt(br());V.PostgrestQueryBuilder=hs.default;var fs=dt(Dt());V.PostgrestFilterBuilder=fs.default;var ps=dt(yr());V.PostgrestTransformBuilder=ps.default;var ms=dt(gr());V.PostgrestBuilder=ms.default;V.default={PostgrestClient:us.default,PostgrestQueryBuilder:hs.default,PostgrestFilterBuilder:fs.default,PostgrestTransformBuilder:ps.default,PostgrestBuilder:ms.default}});var Ts=ee((Io,Es)=>{"use strict";Es.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var $="https://api.wisprflow.ai";function tt(i,e){return typeof i.message=="string"&&i.message||typeof i.error=="string"&&i.error||typeof i.detail=="string"&&i.detail||`Request failed with status ${e}`}var dr=class{static async signupUser(e){try{let t=`${$}/signup`,s=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=s&&s.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${$}/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){return await(await fetch(`${$}/user_status?email=${encodeURIComponent(e)}`)).json()}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:e,captcha_token:t})});if(!r.ok){let s=await r.json().catch(()=>({}));throw new Error(tt(s,r.status))}}static async signUpWithCaptcha(e){let t=await fetch(`${$}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok)throw new Error(tt(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)}),r=await t.json().catch(()=>({}));if(!t.ok)throw new Error(tt(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)});if(!t.ok){let r=await t.json().catch(()=>({}));throw new Error(tt(r,t.status))}}static async signInWithEmail(e){let t=await fetch(`${$}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok)throw new Error(tt(r,t.status));return r}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 s=`${$}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(s+=`¤cy=${r}`),await(await fetch(s,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${$}/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 s=new FormData;return s.append("screenshot",e),await fetch(`${$}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:s,signal:r})}};function Zr(i){let[e,...t]=i.split(" "),r=t.join(" ");return[e,r]}function es(i){return i==="azure"?"Microsoft":i==="workos"?"SSO":i.charAt(0).toUpperCase()+i.slice(1)}var U=dr;var ts=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,r]=e.split("=");return i[t]=r,i},{});var rs=()=>{let i=window.location.hash.substring(1),e=new URLSearchParams(i);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var ss=()=>{let{access_token:i,refresh_token:e}=rs(),t=i,r=e;if(!t||!r){let s=ts();t=s.access_token,r=s.refresh_token}return{accessToken:t,refreshToken:r}};var is=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(me(),ve)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var rt=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},$t=class extends rt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Ut=class extends rt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Mt=class extends rt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Nt;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(Nt||(Nt={}));var qi=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(r.next(c))}catch(u){o(u)}}function l(c){try{d(r.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):s(c.value).then(a,l)}d((r=r.apply(i,e||[])).next())})},st=class{constructor(e,{headers:t={},customFetch:r,region:s=Nt.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=is(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return qi(this,void 0,void 0,function*(){try{let{headers:s,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let d;o&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",d=o):typeof o=="string"?(a["Content-Type"]="text/plain",d=o):typeof FormData<"u"&&o instanceof FormData?d=o:(a["Content-Type"]="application/json",d=JSON.stringify(o)));let c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),s),body:d}).catch(v=>{throw new $t(v)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new Ut(c);if(!c.ok)throw new Mt(c);let f=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield c.json():f==="application/octet-stream"?g=yield c.blob():f==="text/event-stream"?g=c:f==="multipart/form-data"?g=yield c.formData():g=yield c.text(),{data:g,error:null}}catch(s){return{data:null,error:s}}})}};var _s=Qr(gs(),1),{PostgrestClient:ys,PostgrestQueryBuilder:po,PostgrestFilterBuilder:mo,PostgrestTransformBuilder:go,PostgrestBuilder:_o}=_s.default;var ws="2.10.2";var vs={"X-Client-Info":`realtime-js/${ws}`},bs="1.0.0",Vt=1e4,ks=1e3,be;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(be||(be={}));var W;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(W||(W={}));var J;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(J||(J={}));var Ht;(function(i){i.websocket="websocket"})(Ht||(Ht={}));var ge;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(ge||(ge={}));var ut=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+s));o=o+s;let l=r.decode(e.slice(o,o+n));o=o+n;let d=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:d}}};var ke=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 A;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(A||(A={}));var Er=(i,e,t={})=>{var r;let s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Qi(o,i,e,s),n),{})},Qi=(i,e,t,r)=>{let s=e.find(a=>a.name===i),n=s?.type,o=t[i];return n&&!r.includes(n)?Ss(n,o):Sr(o)},Ss=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return rn(e,t)}switch(i){case A.bool:return Zi(e);case A.float4:case A.float8:case A.int2:case A.int4:case A.int8:case A.numeric:case A.oid:return en(e);case A.json:case A.jsonb:return tn(e);case A.timestamp:return sn(e);case A.abstime:case A.date:case A.daterange:case A.int4range:case A.int8range:case A.money:case A.reltime:case A.text:case A.time:case A.timestamptz:case A.timetz:case A.tsrange:case A.tstzrange:return Sr(e);default:return Sr(e)}},Sr=i=>i,Zi=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},en=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},tn=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},rn=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,r=i[t];if(i[0]==="{"&&r==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Ss(e,a))}return i},sn=i=>typeof i=="string"?i.replace(" ","T"):i,Bt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Se=class{constructor(e,t,r={},s=Vt){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Tr;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Tr||(Tr={}));var Ne=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,s,n,o),this.pendingDiffs.forEach(l=>{this.state=i.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=i.syncDiff(this.state,s,n,o),a())}),this.onJoin((s,n,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:n,newPresences:o})}),this.onLeave((s,n,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(d,c)=>{o[d]||(l[d]=c)}),this.map(o,(d,c)=>{let u=n[d];if(u){let f=c.map(p=>p.presence_ref),g=u.map(p=>p.presence_ref),v=c.filter(p=>g.indexOf(p.presence_ref)<0),m=u.filter(p=>f.indexOf(p.presence_ref)<0);v.length>0&&(a[d]=v),m.length>0&&(l[d]=m)}else a[d]=c}),this.syncDiff(n,{joins:a,leaves:l},r,s)}static syncDiff(e,t,r,s){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(a,l)=>{var d;let c=(d=e[a])!==null&&d!==void 0?d:[];if(e[a]=this.cloneDeep(l),c.length>0){let u=e[a].map(g=>g.presence_ref),f=c.filter(g=>u.indexOf(g.presence_ref)<0);e[a].unshift(...f)}r(a,c,l)}),this.map(o,(a,l)=>{let d=e[a];if(!d)return;let c=l.map(u=>u.presence_ref);d=d.filter(u=>c.indexOf(u.presence_ref)<0),e[a]=d,s(a,d,l),d.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let s=e[r];return"metas"in s?t[r]=s.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var xr;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(xr||(xr={}));var Lr;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Lr||(Lr={}));var Ar;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(Ar||(Ar={}));var De=class i{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=W.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 Se(this,J.join,this.params,this.timeout),this.rejoinTimer=new ke(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=W.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=W.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=W.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=W.errored,this.rejoinTimer.scheduleTimeout())}),this._on(J.reply,{},(s,n)=>{this._trigger(this._replyEventName(n),s)}),this.presence=new Ne(this),this.broadcastEndpointURL=Bt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,s;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},d={broadcast:n,presence:o,postgres_changes:(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(c=>c.filter))!==null&&s!==void 0?s:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:d},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:c})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),c===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,g=(u=f?.length)!==null&&u!==void 0?u:0,v=[];for(let m=0;m<g;m++){let p=f[m],{filter:{event:y,schema:I,table:P,filter:O}}=p,L=c&&c[m];if(L&&L.event===y&&L.schema===I&&L.table===P&&L.filter===O)v.push(Object.assign(Object.assign({},p),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,s;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=l.body)===null||s===void 0?void 0:s.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let d=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"),d.receive("ok",()=>n("ok")),d.receive("error",()=>n("error")),d.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=W.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(J.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let s=new Se(this,J.leave,{},e);s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Se(this,e,t,r);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:d,join:c}=J;if(r&&[a,l,d,c].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,t,r);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(g=>{var v,m,p;return((v=g.filter)===null||v===void 0?void 0:v.event)==="*"||((p=(m=g.filter)===null||m===void 0?void 0:m.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(g=>g.callback(f,r)):(n=this.bindings[o])===null||n===void 0||n.filter(g=>{var v,m,p,y,I,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){let O=g.id,L=(v=g.filter)===null||v===void 0?void 0:v.event;return O&&((m=t.ids)===null||m===void 0?void 0:m.includes(O))&&(L==="*"||L?.toLocaleLowerCase()===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{let O=(I=(y=g?.filter)===null||y===void 0?void 0:y.event)===null||I===void 0?void 0:I.toLocaleLowerCase();return O==="*"||O===((P=t?.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof f=="object"&&"ids"in f){let v=f.data,{schema:m,table:p,commit_timestamp:y,type:I,errors:P}=v;f=Object.assign(Object.assign({},{schema:m,table:p,commit_timestamp:y,eventType:I,new:{},old:{},errors:P}),this._getPayloadRecords(v))}g.callback(f,r)})}_isClosed(){return this.state===W.closed}_isJoined(){return this.state===W.joined}_isJoining(){return this.state===W.joining}_isLeaving(){return this.state===W.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(s=>{var n;return!(((n=s.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&i.isEqual(s.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(J.close,{},e)}_onError(e){this._on(J.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=W.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Er(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Er(e.columns,e.old_record)),t}};var on=()=>{},an=typeof WebSocket<"u",qe=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=vs,this.params={},this.timeout=Vt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=on,this.conn=null,this.sendBuffer=[],this.serializer=new ut,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(me(),ve)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Ht.websocket}`,this.httpEndpoint=Bt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let s=(r=t?.params)===null||r===void 0?void 0:r.apikey;s&&(this.accessToken=s,this.apiKey=s),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ke(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(an){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Rr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Qr(Ts())).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 be.connecting:return ge.Connecting;case be.open:return ge.Open;case be.closing:return ge.Closing;default:return ge.Closed}}isConnected(){return this.connectionState()===ge.Open}channel(e,t={config:{}}){let r=new De(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:s,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(J.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(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:bs}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:s,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||s===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${s} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(s,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(J.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(ks,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Rr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=be.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Fe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function N(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var Wt=class extends Fe{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ht=class extends Fe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var ln=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(r.next(c))}catch(u){o(u)}}function l(c){try{d(r.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):s(c.value).then(a,l)}d((r=r.apply(i,e||[])).next())})},zt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(me(),ve)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},xs=()=>ln(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(me(),ve))).Response:Response});var He=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(r.next(c))}catch(u){o(u)}}function l(c){try{d(r.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):s(c.value).then(a,l)}d((r=r.apply(i,e||[])).next())})},Cr=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),cn=(i,e)=>He(void 0,void 0,void 0,function*(){let t=yield xs();i instanceof t?i.json().then(r=>{e(new Wt(Cr(r),i.status||500))}).catch(r=>{e(new ht(Cr(r),r))}):e(new ht(Cr(i),i))}),dn=(i,e,t,r)=>{let s={method:i,headers:e?.headers||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};function Gt(i,e,t,r,s,n){return He(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,dn(e,r,s,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>cn(l,a))})})}function ft(i,e,t,r){return He(this,void 0,void 0,function*(){return Gt(i,"GET",e,t,r)})}function te(i,e,t,r,s){return He(this,void 0,void 0,function*(){return Gt(i,"POST",e,r,s,t)})}function Ls(i,e,t,r,s){return He(this,void 0,void 0,function*(){return Gt(i,"PUT",e,r,s,t)})}function Jt(i,e,t,r,s){return He(this,void 0,void 0,function*(){return Gt(i,"DELETE",e,r,s,t)})}var K=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(r.next(c))}catch(u){o(u)}}function l(c){try{d(r.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):s(c.value).then(a,l)}d((r=r.apply(i,e||[])).next())})},un={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},As={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},pt=class{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=zt(s)}uploadOrUpdate(e,t,r,s){return K(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},As),s),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),d=this._getFinalPath(l),c=yield this.fetch(`${this.url}/object/${d}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield c.json();return c.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(N(n))return{data:null,error:n};throw n}})}upload(e,t,r){return K(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return K(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,d=Object.assign({upsert:As.upsert},s),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",d.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",d.cacheControl)):(l=r,c["cache-control"]=`max-age=${d.cacheControl}`,c["content-type"]=d.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),f=yield u.json();return u.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(l){if(N(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return K(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),s=Object.assign({},this.headers);t?.upsert&&(s["x-upsert"]="true");let n=yield te(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Fe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(N(r))return{data:null,error:r};throw r}})}update(e,t,r){return K(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return K(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}copy(e,t,r){return K(this,void 0,void 0,function*(){try{return{data:{path:(yield te(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,r){return K(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=yield te(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return K(this,void 0,void 0,function*(){try{let s=yield te(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}download(e,t){return K(this,void 0,void 0,function*(){let s=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield ft(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(N(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&s.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&s.push(l);let d=s.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${d}`)}}}remove(e){return K(this,void 0,void 0,function*(){try{return{data:yield Jt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}list(e,t,r){return K(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},un),t),{prefix:e||""});return{data:yield te(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Rs="2.6.0";var Cs={"X-Client-Info":`storage-js/${Rs}`};var Ve=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(r.next(c))}catch(u){o(u)}}function l(c){try{d(r.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):s(c.value).then(a,l)}d((r=r.apply(i,e||[])).next())})},mt=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Cs),t),this.fetch=zt(r)}listBuckets(){return Ve(this,void 0,void 0,function*(){try{return{data:yield ft(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(N(e))return{data:null,error:e};throw e}})}getBucket(e){return Ve(this,void 0,void 0,function*(){try{return{data:yield ft(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Ve(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(N(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Ve(this,void 0,void 0,function*(){try{return{data:yield Ls(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(N(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Ve(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Ve(this,void 0,void 0,function*(){try{return{data:yield Jt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}};var gt=class extends mt{constructor(e,t={},r){super(e,t,r)}from(e){return new pt(this.url,this.headers,e,this.fetch)}};var Ps="2.44.4";var _t="";typeof Deno<"u"?_t="deno":typeof document<"u"?_t="web":typeof navigator<"u"&&navigator.product==="ReactNative"?_t="react-native":_t="node";var hn={"X-Client-Info":`supabase-js-${_t}/${Ps}`},Os={headers:hn},Is={schema:"public"},js={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},$s={};me();var fn=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(r.next(c))}catch(u){o(u)}}function l(c){try{d(r.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):s(c.value).then(a,l)}d((r=r.apply(i,e||[])).next())})},pn=i=>{let e;return i?e=i:typeof fetch>"u"?e=ur:e=fetch,(...t)=>e(...t)},mn=()=>typeof Headers>"u"?hr:Headers,Us=(i,e,t)=>{let r=pn(t),s=mn();return(n,o)=>fn(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:i,d=new s(o?.headers);return d.has("apikey")||d.set("apikey",i),d.has("Authorization")||d.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:d}))})};function Ms(i){return i.replace(/\/$/,"")}function Ns(i,e){let{db:t,auth:r,realtime:s,global:n}=i,{db:o,auth:a,realtime:l,global:d}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),s),global:Object.assign(Object.assign({},d),n)}}var Kt="2.64.4";var Ds="http://localhost:9999",qs="supabase.auth.token";var Fs={"X-Client-Info":`gotrue-js/${Kt}`},Pr=10;var yt="X-Supabase-Api-Version",Or={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Hs(i){return Math.round(Date.now()/1e3)+i}function Vs(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}var Y=()=>typeof document<"u",Ee={tested:!1,writable:!1},_e=()=>{if(!Y())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ee.tested)return Ee.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),Ee.tested=!0,Ee.writable=!0}catch{Ee.tested=!0,Ee.writable=!1}return Ee.writable};function Yt(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,n)=>{e[n]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var Xt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(me(),ve)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Bs=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",Ir=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},vt=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Qt=async(i,e)=>{await i.removeItem(e)};function gn(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,s,n,o,a,l,d,c=0;for(i=i.replace("-","+").replace("_","/");c<i.length;)o=e.indexOf(i.charAt(c++)),a=e.indexOf(i.charAt(c++)),l=e.indexOf(i.charAt(c++)),d=e.indexOf(i.charAt(c++)),r=o<<2|a>>4,s=(a&15)<<4|l>>2,n=(l&3)<<6|d,t=t+String.fromCharCode(r),l!=64&&s!=0&&(t=t+String.fromCharCode(s)),d!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var wt=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};wt.promiseConstructor=Promise;function jr(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(gn(r))}async function Ws(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function zs(i,e){return new Promise((r,s)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){s(o);return}}})()})}function _n(i){return("0"+i.toString(16)).substr(-2)}function yn(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let n=0;n<56;n++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,_n).join("")}async function wn(i){let t=new TextEncoder().encode(i),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(n=>String.fromCharCode(n)).join("")}function vn(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function bn(i){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),i;let t=await wn(i);return vn(t)}async function Te(i,e,t=!1){let r=yn(),s=r;t&&(s+="/PASSWORD_RECOVERY"),await Ir(i,`${e}-code-verifier`,s);let n=await bn(r);return[n,r===n?"plain":"s256"]}var kn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Gs(i){let e=i.headers.get(yt);if(!e||!e.match(kn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var bt=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function S(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var Zt=class extends bt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Js(i){return S(i)&&i.name==="AuthApiError"}var Be=class extends bt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ce=class extends bt{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},re=class extends ce{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},We=class extends ce{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},xe=class extends ce{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Le=class extends ce{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}}},kt=class extends ce{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},ze=class extends ce{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function er(i){return S(i)&&i.name==="AuthRetryableFetchError"}var St=class extends ce{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Sn=function(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t},Ae=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),En=[502,503,504];async function Ks(i){var e;if(!Bs(i))throw new ze(Ae(i),0);if(En.includes(i.status))throw new ze(Ae(i),i.status);let t;try{t=await i.json()}catch(n){throw new Be(Ae(n),n)}let r,s=Gs(i);if(s&&s.getTime()>=Or["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 St(Ae(t),i.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new St(Ae(t),i.status,t.weak_password.reasons);throw new Zt(Ae(t),i.status||500,r)}var Tn=(i,e,t,r)=>{let s={method:i,headers:e?.headers||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function E(i,e,t,r){var s;let n=Object.assign({},r?.headers);n[yt]||(n[yt]=Or["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await xn(i,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function xn(i,e,t,r,s,n){let o=Tn(e,r,s,n),a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new ze(Ae(l),0)}if(a.ok||await Ks(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await Ks(l)}}function de(i){var e;let t=null;Ln(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Hs(i.expires_in)));let r=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:r},error:null}}function $r(i){let e=de(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=i.weak_password),e}function se(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function Ys(i){return{data:i,error:null}}function Xs(i){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n}=i,o=Sn(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Qs(i){return i}function Ln(i){return i.access_token&&i.refresh_token&&i.expires_in}var An=function(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t},Re=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Xt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:se})}catch(r){if(S(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=An(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Xs,redirectTo:t?.redirectTo})}catch(t){if(S(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:se})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,n,o,a,l;try{let d={nextPage:null,lastPage:0,total:0},c=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&n!==void 0?n:""},xform:Qs});if(c.error)throw c.error;let u=await c.json(),f=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return g.length>0&&(g.forEach(v=>{let m=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(v.split(";")[1].split("=")[1]);d[`${p}Page`]=m}),d.total=parseInt(f)),{data:Object.assign(Object.assign({},u),d),error:null}}catch(d){if(S(d))return{data:{users:[]},error:d};throw d}}async getUserById(e){try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:se})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:se})}catch(r){if(S(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:se})}catch(r){if(S(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(S(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}}};var Zs={getItem:i=>_e()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{_e()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{_e()&&globalThis.localStorage.removeItem(i)}};function Ur(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function ei(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var Ce={debug:!!(globalThis&&_e()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Et=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},tr=class extends Et{};async function Mr(i,e,t){Ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Ce.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){Ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,s.name);try{return await t()}finally{Ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,s.name)}}else{if(e===0)throw Ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new tr(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(Ce.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}ei();var Rn={url:Ds,storageKey:qs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Fs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Tt=30*1e3,ti=3;async function ri(i,e,t){return await t()}var Pe=class i{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&Y()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let s=Object.assign(Object.assign({},Rn),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Re({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Xt(s.fetch),this.lock=s.lock||ri,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Y()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Mr:this.lock=ri,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?s.storage?this.storage=s.storage:_e()?this.storage=Zs:(this.memoryStorage={},this.storage=Ur(this.memoryStorage)):(this.memoryStorage={},this.storage=Ur(this.memoryStorage)),Y()&&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} (${Kt}) ${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=Y()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:s,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",s,"redirect type",n),await this._saveSession(s),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return S(e)?{error:e}:{error:new Be("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:de}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(n){if(S(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,s;try{let n;if("email"in e){let{email:c,password:u,options:f}=e,g=null,v=null;this.flowType==="pkce"&&([g,v]=await Te(this.storage,this.storageKey)),n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:u,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:g,code_challenge_method:v},xform:de})}else if("phone"in e){let{phone:c,password:u,options:f}=e;n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(r=f?.data)!==null&&r!==void 0?r:{},channel:(s=f?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:de})}else throw new xe("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,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(n){if(S(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 E(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:$r})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await E(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:$r})}else throw new xe("You must provide either an email or phone number and a password");let{data:r,error:s}=t;return s?{data:{user:null,session:null},error:s}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new We}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await vt(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(t??"").split("/"),{data:n,error:o}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:de});return await Qt(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 We}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:s??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:n,nonce:o}=e,a=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:de}),{data:l,error:d}=a;return d?{data:{user:null,session:null},error:d}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new We}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:d})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,s,n,o;try{if("email"in e){let{email:a,options:l}=e,d=null,c=null;this.flowType==="pkce"&&([d,c]=await Te(this.storage,this.storageKey));let{error:u}=await E(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:d,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:d,error:c}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:d?.message_id},error:c}}throw new xe("You must provide either an email or phone number.")}catch(a){if(S(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:de});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,d=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(s){if(S(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,r,s;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Te(this.storage,this.storageKey)),await E(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Ys})}catch(n){if(S(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 re;let{error:s}=await E(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(S(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:n}=e,{error:o}=await E(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:s,options:n}=e,{data:o,error:a}=await E(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new xe("You must provide either an email or phone number and a type")}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await vt(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,d,c)=>(!o&&d==="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,d,c))})}return{data:{session:e},error:null}}let{session:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:se}):await this._useSession(async t=>{var r,s,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new re}:await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0,xform:se})})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new re;let o=s.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Te(this.storage,this.storageKey));let{data:d,error:c}=await E(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:se});if(c)throw c;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(S(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 re;let t=Date.now()/1e3,r=t,s=!0,n=null,o=jr(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(S(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 re;let{session:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!Y())throw new Le("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Le("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new kt("Not a valid PKCE flow url.");let t=Yt(window.location.href);if(e){if(!t.code)throw new kt("No code detected.");let{data:I,error:P}=await this._exchangeCodeForSession(t.code);if(P)throw P;let O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:I.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Le(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:d}=t;if(!n||!a||!o||!d)throw new Le("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),f=c+u;l&&(f=parseInt(l));let g=f-c;g*1e3<=Tt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${u}s`);let v=f-u;c-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,c):c-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",v,f,c);let{data:m,error:p}=await this._getUser(n);if(p)throw p;let y={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:u,expires_at:f,refresh_token:o,token_type:d,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:t.type},error:null}}catch(t){if(S(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Yt(window.location.href);return!!(Y()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Yt(window.location.href),t=await vt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return{error:n};let o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Js(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Qt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Vs(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await Te(this.storage,this.storageKey,!0));try{return await E(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(S(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(S(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:s}=await this._useSession(async n=>{var o,a,l,d,c;let{data:u,error:f}=n;if(f)throw f;let g=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 E(this.fetch,"GET",g,{headers:this.headers,jwt:(c=(d=u.session)===null||d===void 0?void 0:d.access_token)!==null&&c!==void 0?c:void 0})});if(s)throw s;return Y()&&!(!((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(S(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:o}=t;if(o)throw o;return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await zs(async s=>(s>0&&await Ws(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:de})),(s,n)=>{let o=200*Math.pow(2,s);return n&&er(n)&&Date.now()+o-r<Tt})}catch(r){if(this._debug(t,"error",r),S(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),Y()&&!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 vt(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let s=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<s+Pr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Pr}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),er(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 re;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new wt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new re;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(s,"error",n),S(n)){let o={session:null,error:n};return er(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ir(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Qt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Y()&&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(),Tt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/Tt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Tt}ms, refresh threshold is ${ti} ticks`),s<=ti&&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 Et)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Y()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await Te(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);s.push(n.toString())}return r?.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await E(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(!((s=a?.totp)===null||s===void 0)&&s.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(S(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(S(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],s=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:s},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:s},error:n}=e;if(n)return{data:null,error:n};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(s.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=s.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};Pe.nextInstanceID=0;var Cn=Pe,Nr=Cn;var rr=class extends Nr{constructor(e){super(e)}};var Pn=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(r.next(c))}catch(u){o(u)}}function l(c){try{d(r.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):s(c.value).then(a,l)}d((r=r.apply(i,e||[])).next())})},xt=class{constructor(e,t,r){var s,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=Ms(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`,d={db:Is,realtime:$s,auth:Object.assign(Object.assign({},js),{storageKey:l}),global:Os},c=Ns(r??{},d);this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Us(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new ys(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new st(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new gt(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 Pn(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,storageKey:n,flowType:o,debug:a},l,d){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new rr({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,flowType:o,debug:a,fetch:d,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new qe(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 si=(i,e,t)=>new xt(i,e,t);var ue={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var On=i=>{try{let e=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(i.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},sr=i=>{let[e,t]=i.split(".");return!e||!t?null:On(t)},ii=i=>{let e=sr(i);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var In="https://api.workos.com",jn=60,Ge=(i,e)=>typeof i[e]=="string"?i[e]:void 0,ni=(i,e,t)=>{let r=sr(i);if(!r)return null;let s=Ge(r,"urn:wispr:user_external_id")??Ge(r,"sub"),n=t?.email??Ge(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,l={id:s??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:i,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:l}},$n=async(i,e,t,r)=>{let s=t?.startsWith("https://")?t.replace(/\/$/,""):In,n=await fetch(`${s}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:i,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},oi=async(i,e)=>{let t=sr(i);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),s=typeof t.exp=="number"?t.exp:0,n=Ge(t,"client_id");if(s-r<jn&&n){let l=await $n(e,n,Ge(t,"iss"),Ge(t,"org_id")),d=ni(l.access_token,l.refresh_token,l.user);if(!d)throw new Error("WorkOS refresh returned an invalid access token");return d}if(s<=r)throw new Error("WorkOS session expired");let a=ni(i,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Je=class{constructor(){this.sessionData=null;this.supabase=si(ue.supaBaseUrl,ue.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ue.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||ue.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||ue.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:r,error:s}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(s)throw s;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let s=new Date;s.setTime(s.getTime()+r*24*60*60*1e3);let n=`expires=${s.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{if(ii(t)==="workos"){this.sessionData=await oi(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,r)}catch(s){throw s}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,s]=t.split("=");return e[r]=s,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ue.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,s,n){try{if(!n)throw new Error("Please complete the verification");await U.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:s||ue.redirectUri}),console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,r,s){try{if(!r)throw new Error("Please complete the verification");let n=await U.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:s?.provision??!1,workos_capable:s?.workosCapable});if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in successful for:",e),{accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r){try{if(!r)throw new Error("Please complete the verification");await U.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||ue.redirectUri}),console.log("Verification email resent to:",e)}catch(s){throw console.error("Error resending verification email:",s),s}}async getUser(){let{data:e,error:t}=await this.supabase.auth.getUser();if(t)throw t;return e.user}async getSession(){let{data:e,error:t}=await this.supabase.auth.getSession();if(t)throw t;return e.session}};var ie=null;function Dr(i,e=30,t){ie&&(clearInterval(ie),ie=null);let r=e;i.style.pointerEvents="none",i.textContent=`Resend (${r}s)`,ie=setInterval(()=>{r=r-1,i.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(i.style.pointerEvents="auto",ie&&(clearInterval(ie),ie=null),t&&t())},1e3)}function ai(){ie&&(clearInterval(ie),ie=null)}var li=/^[\p{L}\p{M}\s\-'.]+$/u;function Un(i,e){let t=i.trim();return t?/\d/.test(t)?"Your name can't include numbers":li.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function qr(i,e){let t=i.trim();return t?/\d/.test(t)?"Your name can't include numbers":li.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 ci(i,e,t){let r="full-name-match-error",s=l=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let d=document.getElementById(r);d||(d=document.createElement("div"),d.id=r,d.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",d)),d.textContent=l},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let l=Un(e.value,i.value);l?s(l):n()},a=()=>{let l=qr(e.value,i.value);l?s(l):n()};i.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var Mn="123456",ir=null;function Fr(){return new URLSearchParams(window.location.search).get("dev-mode")==="true"}var nr=()=>{ir!==null&&(window.clearInterval(ir),ir=null)};function Hr(){let i=document.querySelector("[otp-verification]");i&&(i.style.display="none"),nr()}function Vr(i){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),r=document.querySelector("[otp-email]"),s=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),l=document.querySelector("[otp-resend-countdown]"),d=document.querySelector("[otp-resend-seconds]"),c=document.querySelector("[otp-reset]");t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),n&&(n.style.display="none"),l&&(l.style.display="none"),a&&(a.style.display=""),s&&(s.textContent="Verify",s.style.pointerEvents=""),nr(),r&&(r.textContent=i.email),e.style.display="block",t[0]?.focus();let u=m=>{n&&(n.style.display="block"),o&&(o.textContent=m)},f=()=>{n&&(n.style.display="none")},g=async()=>{let m=t.map(p=>p.value).join("");if(m.length!==6){u("Please enter all 6 digits.");return}m===Mn?(f(),s&&(s.textContent="Verified \u2705",s.style.pointerEvents="none"),t.forEach(p=>p.setAttribute("disabled","true")),await i.onVerifySuccess?.()):u("Incorrect or expired code. Try again.")};t.forEach((m,p)=>{m.oninput=()=>{m.value=m.value.replace(/\D/g,"").slice(0,1),m.value&&p<t.length-1&&t[p+1].focus(),f()},m.onkeydown=y=>{y.key==="Backspace"&&!m.value&&p>0?t[p-1].focus():y.key==="Enter"&&(y.preventDefault(),g())},m.onpaste=y=>{y.preventDefault();let I=(y.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);I.split("").forEach((O,L)=>{t[L]&&(t[L].value=O)});let P=Math.min(I.length,t.length-1);t[P]?.focus(),f()}}),s&&(s.onclick=m=>{m.preventDefault(),g()});let v=()=>{let m=60;a&&(a.style.display="none"),l&&(l.style.display="block"),d&&(d.textContent=String(m)),nr(),ir=window.setInterval(()=>{m-=1,d&&(d.textContent=String(m)),m<=0&&(nr(),a&&(a.style.display=""),l&&(l.style.display="none"))},1e3)};a&&(a.onclick=async m=>{m.preventDefault(),t.forEach(p=>{p.value="",p.removeAttribute("disabled")}),t[0]?.focus(),f(),v(),await i.onResend?.()}),c&&(c.onclick=m=>{m.preventDefault(),Hr(),i.onReset?.()})}var R=(i,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:i,retry_attempt:10-t}),window.posthog.capture(i,e)):t>0&&setTimeout(()=>R(i,e,t-1),200)},di=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};var Nn="wisprjam.com",Dn="wispr.ai",qn=i=>i.trim().toLowerCase().split("@")[1]??"",Fn=i=>{let e=qn(i);return e===Nn||e===Dn};function ui(i,e){let t=new Je,r="email_input",s=document.querySelector("#email-form"),n=document.querySelector("#email-input"),o=document.querySelector("#password-input"),a=document.querySelector("#full-name"),l=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),c=document.querySelector("#microsoft-login"),u=document.querySelector("[email-element]"),f=document.querySelector("[different-provider]"),g=document.querySelector("[different-provider-name]"),v=document.querySelector("[different-provider-reset]"),m=document.querySelector("[email-signup-success]"),p=document.querySelector("[email-signup-error]"),y=document.querySelector("[error-message]"),I=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),O=document.querySelector("[email-signup-reset]"),L=document.querySelector("[scim-div]"),ye=document.querySelector("[scim-reset]"),D=document.querySelector("[forgot-password]"),ne=document.querySelector("[forgot-password-success]"),we=document.querySelector("[forgot-password-email]"),X=document.querySelector("[unverified-email]"),Ke=document.querySelector("[unverified-email-address]"),oe=document.querySelector("[resend-verification-email]"),Ye=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(i)}catch(w){console.error("Error during Google sign-in:",w)}}),d&&d.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(i)}catch(w){console.error("Error during Apple sign-in:",w)}}),c&&c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(i)}catch(w){console.error("Error during Microsoft sign-in:",w)}}));let Z=()=>{f&&(f.style.display="none"),m&&(m.style.display="none"),p&&(p.style.display="none"),X&&(X.style.display="none"),L&&(L.style.display="none"),D&&(D.style.display="none"),ne&&(ne.style.display="none"),Hr();let w=document.querySelector(".gs-hero_form-block");w&&(w.style.display="block"),u&&(u.style.display="flex"),n&&(n.value="",n.removeAttribute("readonly"),n.classList.remove("disabled")),o&&(o.value="",o.style.display="none",o.removeAttribute("required")),a&&(a.value="",a.style.display="none",a.removeAttribute("required"));let k=document.querySelector("[captcha-embed]"),x=document.querySelector("#h-captcha-container");k&&(k.style.display="none"),x&&(x.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),r="email_input",n&&n.focus()},Oe=()=>{n&&(n.setAttribute("readonly","true"),n.classList.add("disabled")),o&&(o.style.display="block",o.setAttribute("required","true"),o.focus()),a&&(a.style.display="none",a.removeAttribute("required"));let w=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");w&&(w.style.display="block"),k&&(k.style.display="block"),D&&(D.style.display="block",D.onclick=async()=>{let x=n?.value||"",T=D.textContent||"";try{let{hcaptcha:M}=window;if(!M)throw new Error("Verification system not loaded. Please refresh the page.");D.style.pointerEvents="none",D.textContent="Sending...";let{response:C}=await M.execute({async:!0});if(!C)throw new Error("Verification cancelled");await U.requestPasswordReset(x,C),M.reset(),u&&(u.style.display="none"),D&&(D.style.display="none"),ne&&(ne.style.display="block"),we&&(we.textContent=x)}catch(M){console.error("Error sending password reset email:",M),D.textContent=T,D.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),p&&(p.style.display="block",y&&(y.textContent=M instanceof Error?M.message:"Failed to send reset email"))}}),r="login"},he=()=>{n&&(n.setAttribute("readonly","true"),n.classList.add("disabled")),o&&(o.style.display="block",o.setAttribute("required","true"),o.focus()),a&&(a.style.display="block",a.setAttribute("required","true"));let w=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");w&&(w.style.display="block"),k&&(k.style.display="block"),r="signup"},Lt=()=>{let w=document.querySelector(".gs-hero_form-block");w&&(w.style.display="none"),L&&(L.style.display="block"),ye&&(ye.onclick=()=>{L&&(L.style.display="none"),w&&(w.style.display="block"),Z()})},Xe=w=>{let k=es(w);u&&(u.style.display="none"),f&&(f.style.display="block"),g&&(g.textContent=k),v&&(v.onclick=()=>{f&&(f.style.display="none"),Z()}),r="oauth_user"},At=w=>{u&&(u.style.display="none"),X&&(X.style.display="block"),Ke&&(Ke.textContent=w),oe&&(oe.onclick=async()=>{if(Fr()){X&&(X.style.display="none"),Vr({email:w,onVerifySuccess:()=>{console.log("[dev-mode] OTP verified for",w)},onResend:()=>{console.log("[dev-mode] resend clicked for",w)},onReset:()=>{Z()}});return}let k=oe.textContent||"";try{let x=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(w,i,x),oe.textContent="Verification email resent! \u2705",oe.style.textDecoration="none"}catch(x){console.error("Error resending verification email:",x),oe.textContent=k}}),Ye&&(Ye.onclick=()=>{X&&(X.style.display="none"),Z()}),r="unverified_email"},Rt=async(w,k)=>{let x=k.value;k.classList.add("loading"),k.value="";try{let T=await U.checkUserStatus(w);k.classList.remove("loading"),k.value=x,!T.exists&&T.scim_managed?Lt():T.enforce_sso?Xe("workos"):T.exists&&T.provider&&T.provider!=="email"?Xe(T.provider):T.exists&&T.provider==="email"&&!T.verified?At(w):T.exists&&T.provider==="email"?Oe():he()}catch(T){console.error("Error checking user status:",T),k.classList.remove("loading"),k.value=x,he()}},Ct=async(w,k,x,T)=>{if(!k||k.length<8){p&&(p.style.display="block",y&&(y.textContent="Password must be at least 8 characters"));return}let M=window.hcaptcha?.getResponse()||"";if(!M){p&&(p.style.display="block",y&&(y.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{if(e?.mcpLoginState){let fe=await U.signInWithEmail({email:w,password:k,mcp_login_state:e.mcpLoginState});if(!fe.redirect_url)throw new Error(fe.error||"Unable to continue connector login. Please try again.");R("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=fe.redirect_url;return}let{accessToken:C,refreshToken:F,fullName:H}=await t.signInWithPassword(w,k,M,{workosCapable:Fn(w),provision:!1});t.setCookies(C,F),localStorage.setItem("email",w),e?.onLoginSuccess?await e.onLoginSuccess(C,F,H):window.location.href=i}catch(C){if(console.error("Login error:",C),window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=T,p&&(p.style.display="block",y)){let F=C instanceof Error?C.message:"Invalid login credentials";y.textContent=F}}},Ie=async(w,k,x,T,M)=>{if(!k||k.length<8){p&&(p.style.display="block",y&&(y.textContent="Password must be at least 8 characters"));return}if(!x||x.trim().length<2){p&&(p.style.display="block",y&&(y.textContent="Please enter your full name"));return}let C=qr(x,k);if(C){p&&(p.style.display="block",y&&(y.textContent=C));return}let F=window.hcaptcha?.getResponse()||"";if(!F){p&&(p.style.display="block",y&&(y.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{if(await t.signUpWithPassword(w,k,x,i,F),window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=M,u&&(u.style.display="none"),p&&(p.style.display="none"),Fr()){Vr({email:w,onVerifySuccess:()=>{console.log("[dev-mode] OTP verified for signup",w)},onResend:()=>{console.log("[dev-mode] resend clicked for signup",w)},onReset:()=>{Z()}});return}m&&(m.style.display="block"),I&&(I.textContent=w),P&&(Dr(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let H=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(w,i,H),window.hcaptcha&&window.hcaptcha.reset(),Dr(P,30)}catch(H){console.error("Error resending verification email:",H)}}),O&&(O.onclick=()=>{m&&(m.style.display="none"),ai(),Z()})}catch(H){if(console.error("Signup error:",H),T.classList.remove("loading"),T.value=M,p&&(p.style.display="block",y)){let fe=H instanceof Error?H.message:"Signup failed";y.textContent=fe}}};return s&&o&&a&&ci(o,a,s.querySelector('[type="submit"]')),s&&s.addEventListener("submit",async w=>{w.stopPropagation(),w.preventDefault();let k=n?.value||"",x=o?.value||"",T=a?.value||"";if(!k||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){p&&(p.style.display="block",y&&(y.textContent="Please enter a valid email address"));return}p&&(p.style.display="none"),y&&(y.textContent="");let C=s.querySelector('[type="submit"]'),F=C?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await Rt(k,C):r==="login"?await Ct(k,x,C,F):r==="signup"&&await Ie(k,x,T,C,F)}catch(H){console.error("Auth flow error:",H),C&&(C.classList.remove("loading"),C.value=F),p&&(p.style.display="block")}}),{reset:Z}}var or=function(){return or=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++)for(var s in e=arguments[t])Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=e[s]);return i},or.apply(this,arguments)},hi=function(){function i(e,t,r){var s=this;this.endVal=t,this.options=r,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){s.startTime||(s.startTime=n);var o=n-s.startTime;s.remaining=s.duration-o,s.useEasing?s.countDown?s.frameVal=s.startVal-s.easingFn(o,0,s.startVal-s.endVal,s.duration):s.frameVal=s.easingFn(o,s.startVal,s.endVal-s.startVal,s.duration):s.frameVal=s.startVal+(s.endVal-s.startVal)*(o/s.duration);var a=s.countDown?s.frameVal<s.endVal:s.frameVal>s.endVal;s.frameVal=a?s.endVal:s.frameVal,s.frameVal=Number(s.frameVal.toFixed(s.options.decimalPlaces)),s.printValue(s.frameVal),o<s.duration?s.rAF=requestAnimationFrame(s.count):s.finalEndVal!==null?s.update(s.finalEndVal):s.options.onCompleteCallback&&s.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,d,c=n<0?"-":"";o=Math.abs(n).toFixed(s.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?s.options.decimal+u[1]:"",s.options.useGrouping){d="";for(var f=3,g=0,v=0,m=a.length;v<m;++v)s.options.useIndianSeparators&&v===4&&(f=2,g=1),v!==0&&g%f==0&&(d=s.options.separator+d),g++,d=a[m-v-1]+d;a=d}return s.options.numerals&&s.options.numerals.length&&(a=a.replace(/[0-9]/g,function(p){return s.options.numerals[+p]}),l=l.replace(/[0-9]/g,function(p){return s.options.numerals[+p]})),c+s.options.prefix+a+l+s.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=or(or({},this.defaults),r),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return s.handleScroll(s)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,r=e.el.getBoundingClientRect(),s=r.top+window.pageYOffset,n=r.top+r.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||s>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var r=this.countDown?1:-1;this.endVal=e+r*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var r=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,r):this.el.tagName==="INPUT"?this.el.value=r:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=r:this.el.innerHTML=r}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,' ])/g,"\\$1")},r=t(this.options.separator),s=t(this.options.decimal),n=e.replace(new RegExp(r,"g"),"").replace(new RegExp(s,"g"),".");return parseFloat(n)},i}();var fi=!1;function pi(){if(fi)return;fi=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(r=>{if(r.isIntersecting){let s=r.target;e.unobserve(s);let n=s.dataset.countDirection||"up",o=parseFloat(s.dataset.countOffset||"10")/100,a=parseFloat(s.dataset.countDuration||"2"),l=5,d=s.dataset.countTarget||s.textContent?.trim()||"0",c=parseFloat(d.replace(/,/g,""));if(isNaN(c))return;let u=c*o,f=Math.max(u,l),g=n==="down"?c+f:Math.max(0,c-f);new hi(s,c,{startVal:Math.round(g),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var mi=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,r]=e.split("=");return i[t]=r,i},{});async function Hn(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new Je,{accessToken:t,refreshToken:r}=ss(),s=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),d=document.querySelector("[error-div]"),c=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),f=document.querySelector("[spots]"),g=document.querySelectorAll("[referral-code]"),v=document.querySelector("[referral-count]"),m=document.querySelector("[desktop-bonus-remaining]"),p=document.querySelector("[desktop-bonus-complete]"),y=document.querySelector("[climbed-dropped]"),I=document.querySelector("[keep-moving]"),P=document.querySelector("[rank-arrow-wrap]"),O=document.querySelector("[cohort-text]"),L=document.querySelector("[top-100]"),ye=document.querySelector("[top-1000]"),D=document.querySelector("[top-100k]"),ne=document.querySelector("[sms-bonus-remaining]"),we=document.querySelector("[sms-bonus-complete]"),X=document.querySelector("[total-boost]"),Ke=document.querySelector("[social-media-details]"),oe=document.querySelector("[sms-popup-button]"),Ye=document.querySelector("[app-download]"),Z=document.querySelector("[file-upload]"),Oe=document.querySelector("[file-input]"),he=document.querySelector("[file-validation-error]"),Lt=document.querySelector("[file-upload-loading]"),Xe=document.querySelector("[cancel-upload-button]"),At=document.querySelector("[file-upload-verified]"),Rt=document.querySelector("[boost-earned]"),Ct=document.querySelector("[boost-earned-location]"),Ie=document.querySelector("[woohoo-button]"),w=document.querySelector("[file-upload-failed]"),k=document.querySelector("[upload-failed-text]"),x=document.querySelector("[close-button]"),T=document.querySelector("[share-on-x]"),M=document.querySelector("[share-on-linkedin]"),C=document.querySelector("[share-on-whatsapp]"),F=document.querySelector("[share-on-slack]"),H=document.querySelector("[share-on-discord]"),fe=document.querySelector("[social-media-bonus-remaining]"),Br=document.querySelector("[social-media-bonus-complete]"),Wr=document.querySelector("[share-on-other-channel]");Ke&&Ke.addEventListener("click",()=>{R("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),oe&&oe.addEventListener("click",()=>{R("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),Ye&&Ye.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 zr=async()=>{clearTimeout(i),document.body.style.visibility="visible",o.forEach(Ot=>{Ot.style.display="none"}),n&&(n.style.display="block");let je=window.__abVariantPromise?await window.__abVariantPromise:"control",$e=document.querySelector("[auth-hero-default]"),z=document.querySelector("[auth-hero-v1]"),Q=document.querySelector("[auth-hero-v2]");$e&&($e.style.display="none"),z&&(z.style.display="none"),Q&&(Q.style.display="none"),je==="dictation-broken"&&z?z.style.display="block":je==="smartest"&&Q?Q.style.display="block":$e&&($e.style.display="block"),n&&(n.style.display="none"),s&&(s.style.display="block");let Pt=document.querySelector("[reusable-section-wrap]");Pt&&s&&s.appendChild(Pt);let Qe=document.querySelector(".wl_cohort-spot-wrap");Qe&&(Qe.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"}),ui(`${window.location.origin}/android-waitlist`)};if(!t||!r){await zr();return}try{e.setCookies(t,r);let je=e.checkAndSetSession(),$e=new Promise((h,b)=>setTimeout(()=>b(new Error("Session timeout")),3e3));await Promise.race([je,$e]),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(i),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(h=>{h.style.display="flex",h.dataset.bound||(h.dataset.bound="true",h.addEventListener("click",async b=>{b.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let z=e.sessionData?.access_token,Q=e.sessionData?.user.email,Pt=e.sessionData?.user.user_metadata.full_name||" ",[Qe,Ot]=Zr(Pt),Ze=e.sessionData?.user.id;localStorage.setItem("email",Q),Ze&&localStorage.setItem("user_id",Ze),Ze&&di(Ze,{email:Q,firstName:Qe,lastName:Ot});let gi=mi(),{dub_id:ar,referral:lr,promo_code:Gr}=gi,_i=!!localStorage.getItem("conversion_sent"),Ue=!localStorage.getItem("android_waitlist_joined"),j={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},yi={access_token:z,first_name:Qe,last_name:Ot,dub_click_id:ar||void 0,referral:lr||void 0,promo_code:Gr||void 0};try{await U.signupUser(yi),j.signup.success=!0}catch(h){j.signup.success=!1,j.signup.error=h instanceof Error?h.message:"Unknown error"}try{let h=await U.ensureReferralCode(z);if(j.referral.success=h.ok,!h.ok){let b=await h.json().catch(()=>({}));j.referral.error=b.detail||b.message||`Status ${h.status}`}}catch(h){j.referral.success=!1,j.referral.error=h instanceof Error?h.message:"Network error"}_i||(R("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:ar||void 0,referral:lr||void 0,email:Q,user_id:Ze||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 wi={email:Q,device_type:"android"},Jr=!1;try{await U.addToWaitlist(wi),j.waitlist.success=!0,Jr=!0}catch(h){j.waitlist.success=!1,j.waitlist.error=h instanceof Error?h.message:"Unknown error"}Ue&&Jr&&(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(z);if(G.status===404&&!Ue){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 h={email:Q,device_type:"android"};await U.addToWaitlist(h),localStorage.setItem("android_waitlist_joined","true"),G=await U.getAndroidWaitlistStats(z),G.ok&&(R("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(h){console.error("Recovery addToWaitlist failed:",h)}}let vi=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if(j.stats.success=G.ok,G.status===401||G.status===429||!G.ok){let h="";try{let b=await G.json();h=JSON.stringify(b),j.stats.error=b.detail||b.message||h,c&&(c.textContent=`Status: ${G.status} | ${h}`)}catch{h="Could not parse response",j.stats.error=h,c&&(c.textContent=`Status: ${G.status} | ${h}`)}R("android_waitlist_api_error",{status:G.status,error:h,signup_success:j.signup.success,signup_error:j.signup.error,referral_success:j.referral.success,referral_error:j.referral.error,waitlist_success:j.waitlist.success,waitlist_error:j.waitlist.error,stats_error:j.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:G.status,error:h}),a&&(a.style.display="none"),d&&(d.style.display="block");return}let q=await G.json();if(Ue){let h=await Hn(Q);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:q.current_rank,user_email_hash:h})}let Kr=localStorage.getItem("android_waitlist_last_rank");if(Kr&&!Ue){let h=parseInt(Kr,10);q.current_rank<h&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:q.current_rank,positions_gained:h-q.current_rank,referral_count:q.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",q.current_rank.toString());let cr=h=>{let b=h.current_rank;if(u){let _=b.toLocaleString("en-US");u.textContent=_,u instanceof HTMLElement&&(u.dataset.countTarget=_)}if(h.starting_rank!==null){let _=h.starting_rank-b;f&&(f.textContent=Math.abs(_).toLocaleString()),_<0?(y&&(y.textContent="fell"),I&&(I.style.display="none"),P&&P.classList.add("invert")):(y&&(y.textContent="climbed"),I&&(I.style.display="inline-block"),P&&P.classList.remove("invert"))}if(L&&L.classList.remove("active"),ye&&ye.classList.remove("active"),D&&D.classList.remove("active"),b<=100?L&&L.classList.add("active"):b<=1e3?ye&&ye.classList.add("active"):b<=1e5&&D&&D.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(_=>{_.style.display="none"}),b<=100){let _=document.querySelector('[cohort-wins="top-100"]');_&&(_.style.display="block")}else if(b<=1e3){let _=document.querySelector('[cohort-wins="top-1000"]');_&&(_.style.display="block")}else if(b<=1e5){let _=document.querySelector('[cohort-wins="top-100k"]');_&&(_.style.display="block")}if(O)if(b<=100)O.innerHTML="You're in the <strong>top 100!</strong>";else if(b<=1e3){let _=b-100;O.innerHTML=`<strong>Only ${_.toLocaleString()} spots</strong> to top 100`}else if(b<=1e5){let _=b-1e3;O.innerHTML=`<strong>Only ${_.toLocaleString()} spots</strong> to top 1,000`}else{let _=b-1e5;O.innerHTML=`<strong>Only ${_.toLocaleString()} spots</strong> to top 100,000`}g.forEach(_=>{_.textContent=h.referral_code}),v&&(v.textContent=h.referrals_count.toString()),h.desktop_dictation_bonus_earned?(m&&(m.style.display="none"),p&&(p.style.display="block")):(m&&(m.style.display="block"),p&&(p.style.display="none")),h.phone_number_bonus_earned?(ne&&(ne.style.display="none"),we&&(we.style.display="block")):(ne&&(ne.style.display="block"),we&&(we.style.display="none")),h.verified_share_twitter&&T&&T.classList.add("verified"),h.verified_share_linkedin&&M&&M.classList.add("verified"),h.verified_share_whatsapp&&C&&C.classList.add("verified"),h.verified_share_slack&&F&&F.classList.add("verified"),h.verified_share_discord&&H&&H.classList.add("verified");let B=h.verified_share_twitter&&h.verified_share_linkedin&&h.verified_share_whatsapp&&h.verified_share_slack&&h.verified_share_discord;if(B&&(fe&&(fe.style.display="none"),Br&&(Br.style.display="block")),X){let _=[h.phone_number_bonus_earned,h.desktop_dictation_bonus_earned,B].filter(Boolean).length;X.textContent=`${_} of 3`}};cr(q);let Yr=h=>h<=100?"top-100":h<=1e3?"top-1000":h<=1e5?"top-100k":"below-100k";R("android_waitlist_page_view",{rank:q.current_rank,total_boost:q.total_boost,referrals_count:q.referrals_count,cohort:Yr(q.current_rank),is_first_visit:Ue}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:q.current_rank,total_boost:q.total_boost,referrals_count:q.referrals_count,cohort:Yr(q.current_rank),is_first_visit:Ue});let bi=`https://wisprflow.ai/waitlist?${q.referral_code}`;document.querySelectorAll("[share]").forEach(h=>{let b=h.getAttribute("share");if(!b)return;let _=document.querySelector(`[share-content="${b}"]`)?.textContent||"";h.addEventListener("click",async()=>{switch(R("android_waitlist_share_clicked",{platform:b}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:b}),b){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(_)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(_),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(bi)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(_)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(_),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(_),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async h=>{let b=h,{phoneNumber:B}=b.detail;try{let _=await U.submitPhoneNumber(B,z),ae=await _.json();if(!_.ok||!ae.success){let It=ae.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:It}})),R("android_waitlist_sms_error",{error:It}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:It});return}window.dispatchEvent(new CustomEvent("sms:success"));let le=await U.getAndroidWaitlistStats(z);le.ok&&cr(await le.json()),R("android_waitlist_sms_submitted",{boost_earned:ae.boost_earned,new_rank:ae.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:ae.boost_earned,new_rank:ae.current_rank})}catch(_){console.error("SMS submission error:",_),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 pe=h=>{Z&&(Z.style.display=h==="idle"?"block":"none"),Lt&&(Lt.style.display=h==="loading"?"block":"none"),At&&(At.style.display=h==="verified"?"block":"none"),w&&(w.style.display=h==="failed"?"block":"none"),he&&(he.style.display="none")},ki=h=>{let B=["image/png","image/jpeg","image/jpg"];return h.size>20971520?"File too large. Maximum size is 20MB.":B.includes(h.type)?null:"Please upload a PNG or JPEG image."},Si={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},Ei=h=>Si[h]||"Social Media",Ti={social_share_x:T,social_share_linkedin:M,social_share_whatsapp:C,social_share_slack:F,social_share_discord:H},xi=h=>{let b=Ti[h];b&&b.classList.add("verified")},Li=h=>({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)"})[h??""]??`Verification failed. (${h})`,et=null;Oe&&Oe.addEventListener("change",async()=>{let h=Oe.files?.[0];if(!h)return;Oe.value="";let b=ki(h);if(b){he&&(he.textContent=b,he.style.display="block"),R("android_waitlist_social_validation_error",{error:b}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:b});return}R("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),pe("loading"),et=new AbortController;try{let B=await U.submitSocialShare(h,z,et.signal),_=await B.json();if(!B.ok||!_.success){pe("failed"),k&&(k.textContent=Li(_.error)),R("android_waitlist_social_upload_failed",{error:_.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:_.error});return}pe("verified"),Rt&&(Rt.textContent=_.boost_earned.toLocaleString()),Ct&&(Ct.textContent=Ei(_.action)),xi(_.action);let ae=await U.getAndroidWaitlistStats(z);if(ae.ok){let le=await ae.json();cr(le),le.verified_share_twitter&&le.verified_share_linkedin&&le.verified_share_whatsapp&&le.verified_share_slack&&le.verified_share_discord&&(Ie&&(Ie.style.display="none"),Wr&&(Wr.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:_.action,boost_earned:_.boost_earned,new_rank:_.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:_.action,boost_earned:_.boost_earned,new_rank:_.current_rank})}catch(B){if(B instanceof Error&&B.name==="AbortError"){pe("idle");return}console.error("Social share upload error:",B),pe("failed"),k&&(k.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{et=null}}),Xe&&Xe.addEventListener("click",()=>{et&&et.abort(),pe("idle"),R("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),Ie&&Ie.addEventListener("click",()=>{pe("idle")}),x&&x.addEventListener("click",()=>{pe("idle")}),vi(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),pi()}catch(je){console.error("Error on android-waitlist page:",je),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await zr()}});})();
|
|
1
|
+
"use strict";(()=>{var Di=Object.create;var Wt=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var Hi=Object.getOwnPropertyNames;var Wi=Object.getPrototypeOf,Vi=Object.prototype.hasOwnProperty;var Bi=(s,e)=>()=>(s&&(e=s(s=0)),e);var ie=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),zi=(s,e)=>{for(var t in e)Wt(s,t,{get:e[t],enumerable:!0})},ss=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Hi(e))!Vi.call(s,i)&&i!==t&&Wt(s,i,{get:()=>e[i],enumerable:!(r=Fi(e,i))||r.enumerable});return s};var is=(s,e,t)=>(t=s!=null?Di(Wi(s)):{},ss(e||!s||!s.__esModule?Wt(t,"default",{value:s,enumerable:!0}):t,s)),Ji=s=>ss(Wt({},"__esModule",{value:!0}),s);var Ee={};zi(Ee,{Headers:()=>Er,Request:()=>Qi,Response:()=>Zi,default:()=>Sr,fetch:()=>Xi});var Yi,Be,Xi,Sr,Er,Qi,Zi,we=Bi(()=>{"use strict";Yi=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},Be=Yi(),Xi=Be.fetch,Sr=Be.fetch.bind(Be),Er=Be.Headers,Qi=Be.Request,Zi=Be.Response});var hs=ie(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});var Tr=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};xr.default=Tr});var Lr=ie(mt=>{"use strict";var fs=mt&&mt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(mt,"__esModule",{value:!0});var tn=fs((we(),Ji(Ee))),rn=fs(hs()),Ar=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=tn.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let c=null,d=null,u=null,p=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let C=await n.text();C===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?d=C:d=JSON.parse(C))}let S=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),v=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");S&&v&&v.length>1&&(u=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(c={code:"PGRST116",details:`Results contain ${d.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},d=null,u=null,p=406,m="Not Acceptable"):d.length===1?d=d[0]:d=null)}else{let S=await n.text();try{c=JSON.parse(S),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,m="OK")}catch{n.status===404&&S===""?(p=204,m="No Content"):c={message:S}}if(c&&this.isMaybeSingle&&(!((l=c?.details)===null||l===void 0)&&l.includes("0 rows"))&&(c=null,p=200,m="OK"),c&&this.shouldThrowOnError)throw new rn.default(c)}return{error:c,data:d,count:u,status:p,statusText:m}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};mt.default=Ar});var Rr=ie(gt=>{"use strict";var sn=gt&>.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(gt,"__esModule",{value:!0});var nn=sn(Lr()),Cr=class extends nn.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};gt.default=Cr});var Kt=ie(_t=>{"use strict";var on=_t&&_t.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_t,"__esModule",{value:!0});var an=on(Rr()),Or=class extends an.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};_t.default=Or});var Ir=ie(wt=>{"use strict";var ln=wt&&wt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(wt,"__esModule",{value:!0});var yt=ln(Kt()),Pr=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new yt.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new yt.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){let c=[...new Set(l)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new yt.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new yt.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new yt.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};wt.default=Pr});var ps=ie(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.version=void 0;Yt.version="0.0.0-automated"});var ms=ie(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DEFAULT_HEADERS=void 0;var cn=ps();Xt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${cn.version}`}});var _s=ie(vt=>{"use strict";var gs=vt&&vt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(vt,"__esModule",{value:!0});var dn=gs(Ir()),un=gs(Kt()),hn=ms(),jr=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},hn.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new dn.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([d,u])=>u!==void 0).map(([d,u])=>[d,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([d,u])=>{a.searchParams.append(d,u)})):(o="POST",l=t);let c=Object.assign({},this.headers);return n&&(c.Prefer=`count=${n}`),new un.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};vt.default=jr});var Ss=ie(H=>{"use strict";var bt=H&&H.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(H,"__esModule",{value:!0});H.PostgrestBuilder=H.PostgrestTransformBuilder=H.PostgrestFilterBuilder=H.PostgrestQueryBuilder=H.PostgrestClient=void 0;var ys=bt(_s());H.PostgrestClient=ys.default;var ws=bt(Ir());H.PostgrestQueryBuilder=ws.default;var vs=bt(Kt());H.PostgrestFilterBuilder=vs.default;var bs=bt(Rr());H.PostgrestTransformBuilder=bs.default;var ks=bt(Lr());H.PostgrestBuilder=ks.default;H.default={PostgrestClient:ys.default,PostgrestQueryBuilder:ws.default,PostgrestFilterBuilder:vs.default,PostgrestTransformBuilder:bs.default,PostgrestBuilder:ks.default}});var Ps=ie((Go,Os)=>{"use strict";Os.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Vt=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,U="https://api.wisprflow.ai",fe=class extends Error{constructor(t,r,i){super(i);this.status=t;this.code=r;this.name="AriaAuthError"}},X=s=>s.trim().toLowerCase(),ns=(s,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof s.code=="string"?s.code:s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:typeof s.detail=="string"&&t.has(s.detail)?s.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},ht=(s,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[s]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Gi=(s,e,t)=>[s.message,s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"?s.detail.message:null,typeof s.detail=="string"?s.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??ht(e,t),Ve=(s,e)=>{let t=ns(s,e);return new fe(e,t,Gi(s,t,e))},Ki=(s,e)=>{let t=ns(s,e);return new fe(e,t,ht(t,e))},kr=class{static async signupUser(e){try{let t=`${U}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${U}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${U}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${U}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch(`${U}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){let t=X(e),r=await fetch(`${U}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw Ve(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${U}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:X(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw Ve(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${U}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${U}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${U}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new fe(422,"invalid_code",ht("invalid_code",422));let t=await fetch(`${U}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok){let i=Ki(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new fe(t.status,"verification_failed",ht("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new fe(t.status,"authentication_failed",ht("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${U}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async getSubscriptionStatus(e){return await fetch(`${U}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${U}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,r){let i=`${U}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`¤cy=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${U}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch(`${U}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${U}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${U}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,r){let i=new FormData;return i.append("screenshot",e),await fetch(`${U}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function os(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}function as(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var j=kr;var ls=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var cs=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var ds=()=>{let{access_token:s,refresh_token:e}=cs(),t=s,r=e;if(!t||!r){let i=ls();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var us=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ft=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Bt=class extends ft{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},zt=class extends ft{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Jt=class extends ft{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Gt;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Gt||(Gt={}));var en=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},pt=class{constructor(e,{headers:t={},customFetch:r,region:i=Gt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=us(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return en(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let c;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(a["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(a["Content-Type"]="application/json",c=JSON.stringify(o)));let d=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:c}).catch(y=>{throw new Bt(y)}),u=d.headers.get("x-relay-error");if(u&&u==="true")throw new zt(d);if(!d.ok)throw new Jt(d);let p=((r=d.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return p==="application/json"?m=yield d.json():p==="application/octet-stream"?m=yield d.blob():p==="text/event-stream"?m=d:p==="multipart/form-data"?m=yield d.formData():m=yield d.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}};var Es=is(Ss(),1),{PostgrestClient:Ts,PostgrestQueryBuilder:Co,PostgrestFilterBuilder:Ro,PostgrestTransformBuilder:Oo,PostgrestBuilder:Po}=Es.default;var xs="2.10.2";var As={"X-Client-Info":`realtime-js/${xs}`},Ls="1.0.0",Zt=1e4,Cs=1e3,Te;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(Te||(Te={}));var V;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(V||(V={}));var G;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(G||(G={}));var Qt;(function(s){s.websocket="websocket"})(Qt||(Qt={}));var ve;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(ve||(ve={}));var kt=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let l=r.decode(e.slice(o,o+n));o=o+n;let c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}};var xe=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var O;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(O||(O={}));var Ur=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=fn(o,s,e,i),n),{})},fn=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?Rs(n,o):$r(o)},Rs=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return _n(e,t)}switch(s){case O.bool:return pn(e);case O.float4:case O.float8:case O.int2:case O.int4:case O.int8:case O.numeric:case O.oid:return mn(e);case O.json:case O.jsonb:return gn(e);case O.timestamp:return yn(e);case O.abstime:case O.date:case O.daterange:case O.int4range:case O.int8range:case O.money:case O.reltime:case O.text:case O.time:case O.timestamptz:case O.timetz:case O.tsrange:case O.tstzrange:return $r(e);default:return $r(e)}},$r=s=>s,pn=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},mn=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},gn=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},_n=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Rs(e,a))}return s},yn=s=>typeof s=="string"?s.replace(" ","T"):s,er=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Ae=class{constructor(e,t,r={},i=Zt){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Mr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Mr||(Mr={}));var ze=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=s.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(c,d)=>{o[c]||(l[c]=d)}),this.map(o,(c,d)=>{let u=n[c];if(u){let p=d.map(v=>v.presence_ref),m=u.map(v=>v.presence_ref),y=d.filter(v=>m.indexOf(v.presence_ref)<0),S=u.filter(v=>p.indexOf(v.presence_ref)<0);y.length>0&&(a[c]=y),S.length>0&&(l[c]=S)}else a[c]=d}),this.syncDiff(n,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var c;let d=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),d.length>0){let u=e[a].map(m=>m.presence_ref),p=d.filter(m=>u.indexOf(m.presence_ref)<0);e[a].unshift(...p)}r(a,d,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let d=l.map(u=>u.presence_ref);c=c.filter(u=>d.indexOf(u.presence_ref)<0),e[a]=c,i(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Nr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Nr||(Nr={}));var qr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(qr||(qr={}));var Dr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Dr||(Dr={}));var Je=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=V.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Ae(this,G.join,this.params,this.timeout),this.rejoinTimer=new xe(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=V.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=V.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=V.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=V.errored,this.rejoinTimer.scheduleTimeout())}),this._on(G.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new ze(this),this.broadcastEndpointURL=er(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(d=>e&&e("CHANNEL_ERROR",d)),this._onClose(()=>e&&e("CLOSED"));let l={},c={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(d=>d.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:c},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:d})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),d===void 0){e&&e("SUBSCRIBED");return}else{let p=this.bindings.postgres_changes,m=(u=p?.length)!==null&&u!==void 0?u:0,y=[];for(let S=0;S<m;S++){let v=p[S],{filter:{event:C,schema:h,table:g,filter:L}}=v,P=d&&d[S];if(P&&P.event===C&&P.schema===h&&P.table===g&&P.filter===L)y.push(Object.assign(Object.assign({},v),{id:P.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",d=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(d).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=V.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(G.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new Ae(this,G.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Ae(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:d}=G;if(r&&[a,l,c,d].indexOf(o)>=0&&r!==this._joinRef())return;let p=this._onMessage(o,t,r);if(t&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var y,S,v;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((v=(S=m.filter)===null||S===void 0?void 0:S.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===o}).map(m=>m.callback(p,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var y,S,v,C,h,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let L=m.id,P=(y=m.filter)===null||y===void 0?void 0:y.event;return L&&((S=t.ids)===null||S===void 0?void 0:S.includes(L))&&(P==="*"||P?.toLocaleLowerCase()===((v=t.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{let L=(h=(C=m?.filter)===null||C===void 0?void 0:C.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return L==="*"||L===((g=t?.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof p=="object"&&"ids"in p){let y=p.data,{schema:S,table:v,commit_timestamp:C,type:h,errors:g}=y;p=Object.assign(Object.assign({},{schema:S,table:v,commit_timestamp:C,eventType:h,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(p,r)})}_isClosed(){return this.state===V.closed}_isJoined(){return this.state===V.joined}_isJoining(){return this.state===V.joining}_isLeaving(){return this.state===V.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(G.close,{},e)}_onError(e){this._on(G.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=V.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Ur(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Ur(e.columns,e.old_record)),t}};var vn=()=>{},bn=typeof WebSocket<"u",Ge=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=As,this.params={},this.timeout=Zt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=vn,this.conn=null,this.sendBuffer=[],this.serializer=new kt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Qt.websocket}`,this.httpEndpoint=er(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new xe(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(bn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Fr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>is(Ps())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Te.connecting:return ve.Connecting;case Te.open:return ve.Open;case Te.closing:return ve.Closing;default:return ve.Closed}}isConnected(){return this.connectionState()===ve.Open}channel(e,t={config:{}}){let r=new Je(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(G.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Ls}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(G.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Cs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Fr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Te.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Ke=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function M(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var tr=class extends Ke{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},St=class extends Ke{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var kn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},rr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Is=()=>kn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(we(),Ee))).Response:Response});var Ye=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Hr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Sn=(s,e)=>Ye(void 0,void 0,void 0,function*(){let t=yield Is();s instanceof t?s.json().then(r=>{e(new tr(Hr(r),s.status||500))}).catch(r=>{e(new St(Hr(r),r))}):e(new St(Hr(s),s))}),En=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function sr(s,e,t,r,i,n){return Ye(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,En(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Sn(l,a))})})}function Et(s,e,t,r){return Ye(this,void 0,void 0,function*(){return sr(s,"GET",e,t,r)})}function ne(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return sr(s,"POST",e,r,i,t)})}function js(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return sr(s,"PUT",e,r,i,t)})}function ir(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return sr(s,"DELETE",e,r,i,t)})}var Q=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Tn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},$s={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Tt=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=rr(i)}uploadOrUpdate(e,t,r,i){return Q(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},$s),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),c=this._getFinalPath(l),d=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield d.json();return d.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(M(n))return{data:null,error:n};throw n}})}upload(e,t,r){return Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return Q(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l,c=Object.assign({upsert:$s.upsert},i),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:d}),p=yield u.json();return u.ok?{data:{path:n,fullPath:p.Key},error:null}:{data:null,error:p}}catch(l){if(M(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return Q(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield ne(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ke("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(M(r))return{data:null,error:r};throw r}})}update(e,t,r){return Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return Q(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}copy(e,t,r){return Q(this,void 0,void 0,function*(){try{return{data:{path:(yield ne(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield ne(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=yield ne(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}download(e,t){return Q(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Et(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(M(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let c=i.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return Q(this,void 0,void 0,function*(){try{return{data:yield ir(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}list(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Tn),t),{prefix:e||""});return{data:yield ne(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Us="2.6.0";var Ms={"X-Client-Info":`storage-js/${Us}`};var Xe=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},xt=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Ms),t),this.fetch=rr(r)}listBuckets(){return Xe(this,void 0,void 0,function*(){try{return{data:yield Et(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(M(e))return{data:null,error:e};throw e}})}getBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield Et(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Xe(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(M(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Xe(this,void 0,void 0,function*(){try{return{data:yield js(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(M(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield ir(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}};var At=class extends xt{constructor(e,t={},r){super(e,t,r)}from(e){return new Tt(this.url,this.headers,e,this.fetch)}};var Ns="2.44.4";var Lt="";typeof Deno<"u"?Lt="deno":typeof document<"u"?Lt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Lt="react-native":Lt="node";var xn={"X-Client-Info":`supabase-js-${Lt}/${Ns}`},qs={headers:xn},Ds={schema:"public"},Fs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Hs={};we();var An=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Ln=s=>{let e;return s?e=s:typeof fetch>"u"?e=Sr:e=fetch,(...t)=>e(...t)},Cn=()=>typeof Headers>"u"?Er:Headers,Ws=(s,e,t)=>{let r=Ln(t),i=Cn();return(n,o)=>An(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:s,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",s),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:c}))})};function Vs(s){return s.replace(/\/$/,"")}function Bs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:l,global:c}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},c),n)}}var nr="2.64.4";var zs="http://localhost:9999",Js="supabase.auth.token";var Gs={"X-Client-Info":`gotrue-js/${nr}`},Wr=10;var Ct="X-Supabase-Api-Version",Vr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ks(s){return Math.round(Date.now()/1e3)+s}function Ys(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var Z=()=>typeof document<"u",Le={tested:!1,writable:!1},be=()=>{if(!Z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Le.tested)return Le.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Le.tested=!0,Le.writable=!0}catch{Le.tested=!0,Le.writable=!1}return Le.writable};function or(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var ar=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Xs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Br=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ot=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},lr=async(s,e)=>{await s.removeItem(e)};function Rn(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,l,c,d=0;for(s=s.replace("-","+").replace("_","/");d<s.length;)o=e.indexOf(s.charAt(d++)),a=e.indexOf(s.charAt(d++)),l=e.indexOf(s.charAt(d++)),c=e.indexOf(s.charAt(d++)),r=o<<2|a>>4,i=(a&15)<<4|l>>2,n=(l&3)<<6|c,t=t+String.fromCharCode(r),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),c!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Rt=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Rt.promiseConstructor=Promise;function zr(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Rn(r))}async function Qs(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Zs(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function On(s){return("0"+s.toString(16)).substr(-2)}function Pn(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,On).join("")}async function In(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function jn(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function $n(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;let t=await In(s);return jn(t)}async function Ce(s,e,t=!1){let r=Pn(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Br(s,`${e}-code-verifier`,i);let n=await $n(r);return[n,r===n?"plain":"s256"]}var Un=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ei(s){let e=s.headers.get(Ct);if(!e||!e.match(Un))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Pt=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function E(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var cr=class extends Pt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function ti(s){return E(s)&&s.name==="AuthApiError"}var Qe=class extends Pt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},pe=class extends Pt{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},oe=class extends pe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ze=class extends pe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Re=class extends pe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Oe=class extends pe{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},It=class extends pe{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},et=class extends pe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function dr(s){return E(s)&&s.name==="AuthRetryableFetchError"}var jt=class extends pe{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Mn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Pe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Nn=[502,503,504];async function ri(s){var e;if(!Xs(s))throw new et(Pe(s),0);if(Nn.includes(s.status))throw new et(Pe(s),s.status);let t;try{t=await s.json()}catch(n){throw new Qe(Pe(n),n)}let r,i=ei(s);if(i&&i.getTime()>=Vr["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new jt(Pe(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new jt(Pe(t),s.status,t.weak_password.reasons);throw new cr(Pe(t),s.status||500,r)}var qn=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function x(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Ct]||(n[Ct]=Vr["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Dn(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function Dn(s,e,t,r,i,n){let o=qn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new et(Pe(l),0)}if(a.ok||await ri(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await ri(l)}}function me(s){var e;let t=null;Fn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ks(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Jr(s){let e=me(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function ae(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function si(s){return{data:s,error:null}}function ii(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Mn(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function ni(s){return s}function Fn(s){return s.access_token&&s.refresh_token&&s.expires_in}var Hn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Ie=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ar(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await x(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(E(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await x(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Hn(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await x(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ii,redirectTo:t?.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await x(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},d=await x(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:ni});if(d.error)throw d.error;let u=await d.json(),p=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=d.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{let S=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(y.split(";")[1].split("=")[1]);c[`${v}Page`]=S}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(E(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await x(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await x(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await x(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await x(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await x(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}};var oi={getItem:s=>be()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{be()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{be()&&globalThis.localStorage.removeItem(s)}};function Gr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function ai(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var je={debug:!!(globalThis&&be()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},$t=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ur=class extends $t{};async function Kr(s,e,t){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),je.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{je.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw je.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ur(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(je.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}ai();var Wn={url:zs,storageKey:Js,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Gs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ut=30*1e3,li=3;async function ci(s,e,t){return await t()}var $e=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&Z()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},Wn),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Ie({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ar(i.fetch),this.lock=i.lock||ci,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Z()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Kr:this.lock=ci,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:be()?this.storage=oi:(this.memoryStorage={},this.storage=Gr(this.memoryStorage)):(this.memoryStorage={},this.storage=Gr(this.memoryStorage)),Z()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${nr}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=Z()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return E(e)?{error:e}:{error:new Qe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await x(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:me}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:d,password:u,options:p}=e,m=null,y=null;this.flowType==="pkce"&&([m,y]=await Ce(this.storage,this.storageKey)),n=await x(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:d,password:u,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:m,code_challenge_method:y},xform:me})}else if("phone"in e){let{phone:d,password:u,options:p}=e;n=await x(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:u,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:me})}else throw new Re("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await x(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Jr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await x(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Jr})}else throw new Re("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Ze}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ot(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await x(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:me});return await lr(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Ze}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await x(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:me}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Ze}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:l}=e,c=null,d=null;this.flowType==="pkce"&&([c,d]=await Ce(this.storage,this.storageKey));let{error:u}=await x(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:d},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:d}=await x(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:d}}throw new Re("You must provide either an email or phone number.")}catch(a){if(E(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await x(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:me});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Ce(this.storage,this.storageKey)),await x(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:si})}catch(n){if(E(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new oe;let{error:i}=await x(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(E(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await x(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await x(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Re("You must provide either an email or phone number and a type")}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ot(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,d)=>(!o&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,c,d))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await x(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ae}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new oe}:await x(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:ae})})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new oe;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Ce(this.storage,this.storageKey));let{data:c,error:d}=await x(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:ae});if(d)throw d;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return zr(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new oe;let t=Date.now()/1e3,r=t,i=!0,n=null,o=zr(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(E(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new oe;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!Z())throw new Oe("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Oe("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new It("Not a valid PKCE flow url.");let t=or(window.location.href);if(e){if(!t.code)throw new It("No code detected.");let{data:h,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;let L=new URL(window.location.href);return L.searchParams.delete("code"),window.history.replaceState(window.history.state,"",L.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Oe(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=t;if(!n||!a||!o||!c)throw new Oe("No session defined in URL");let d=Math.round(Date.now()/1e3),u=parseInt(a),p=d+u;l&&(p=parseInt(l));let m=p-d;m*1e3<=Ut&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${u}s`);let y=p-u;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,p,d);let{data:S,error:v}=await this._getUser(n);if(v)throw v;let C={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:p,refresh_token:o,token_type:c,user:S.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:C,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=or(window.location.href);return!!(Z()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=or(window.location.href),t=await Ot(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(ti(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await lr(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ys(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Ce(this.storage,this.storageKey,!0));try{return await x(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(E(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,l,c,d;let{data:u,error:p}=n;if(p)throw p;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await x(this.fetch,"GET",m,{headers:this.headers,jwt:(d=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&d!==void 0?d:void 0})});if(i)throw i;return Z()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(E(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await x(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Zs(async i=>(i>0&&await Qs(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await x(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:me})),(i,n)=>{let o=200*Math.pow(2,i);return n&&dr(n)&&Date.now()+o-r<Ut})}catch(r){if(this._debug(t,"error",r),E(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Z()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ot(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Wr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Wr}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),dr(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Rt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new oe;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),E(n)){let o={session:null,error:n};return dr(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Br(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await lr(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Z()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Ut);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/Ut);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ut}ms, refresh threshold is ${li} ticks`),i<=li&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof $t)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Z()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await Ce(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await x(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await x(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await x(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await x(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let d=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:d},error:null}}))}};$e.nextInstanceID=0;var Vn=$e,Yr=Vn;var hr=class extends Yr{constructor(e){super(e)}};var Bn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Mt=class{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=Vs(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,c={db:Ds,realtime:Hs,auth:Object.assign(Object.assign({},Fs),{storageKey:l}),global:qs},d=Bs(r??{},c);this.storageKey=(i=d.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=d.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=d.auth)!==null&&o!==void 0?o:{},this.headers,d.global.fetch),this.fetch=Ws(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},d.realtime)),this.rest=new Ts(`${a}/rest/v1`,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new pt(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new At(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Bn(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},l,c){var d;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new hr({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:c,hasCustomAuthorizationHeader:(d="Authorization"in this.headers)!==null&&d!==void 0?d:!1})}_initRealtimeClient(e){return new Ge(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var di=(s,e,t)=>new Mt(s,e,t);var ge={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var zn=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},fr=s=>{let[e,t]=s.split(".");return!e||!t?null:zn(t)},ui=s=>{let e=fr(s);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Jn="https://api.workos.com",Gn=60,tt=(s,e)=>typeof s[e]=="string"?s[e]:void 0,hi=(s,e,t)=>{let r=fr(s);if(!r)return null;let i=tt(r,"urn:wispr:user_external_id")??tt(r,"sub"),n=t?.email??tt(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,l={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:l}},Kn=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Jn,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:s,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},fi=async(s,e)=>{let t=fr(s);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=tt(t,"client_id");if(i-r<Gn&&n){let l=await Kn(e,n,tt(t,"iss"),tt(t,"org_id")),c=hi(l.access_token,l.refresh_token,l.user);if(!c)throw new Error("WorkOS refresh returned an invalid access token");return c}if(i<=r)throw new Error("WorkOS session expired");let a=hi(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var rt=class{constructor(){this.sessionData=null;this.supabase=di(ge.supaBaseUrl,ge.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ge.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||ge.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||ge.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{if(ui(t)==="workos"){this.sessionData=await fi(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ge.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=await j.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:i||ge.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),a}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await j.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(Vt(n))return{kind:"otp",challenge:n};if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0,provider:n.provider||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await j.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||ge.redirectUri,workos_capable:i?.workosCapable||void 0});return console.log("Verification request completed"),n}catch(n){throw console.error("Error resending verification email:",n),n}}async getUser(){let{data:e,error:t}=await this.supabase.auth.getUser();if(t)throw t;return e.user}async getSession(){let{data:e,error:t}=await this.supabase.auth.getSession();if(t)throw t;return e.session}};var pr=null;function Ue(){return new URLSearchParams(window.location.search).get("dev-mode")==="true"}var pi=(s,e)=>{if(!(s instanceof Error)||s.name!=="AriaAuthError")return e;let t={verification_failed:"Incorrect or expired code. Try again.",invalid_code:"Enter the six-digit code.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again."},{code:r}=s;return r&&t[r]||e},mr=()=>{pr!==null&&(window.clearInterval(pr),pr=null)};function st(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),mr()}function mi(s){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),r=document.querySelector("[otp-email]"),i=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),l=document.querySelector("[otp-resend-countdown]"),c=document.querySelector("[otp-resend-seconds]"),d=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),n&&(n.style.display="none"),l&&(l.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),mr(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let u=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},p=()=>{n&&(n.style.display="none")},m=!1,y=!1,S=h=>{i&&(i.style.pointerEvents=h?"none":"",h?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},v=async()=>{if(m)return;let h=t.map(g=>g.value).join("");if(h.length!==6){u("Please enter all 6 digits.");return}m=!0,S(!0),t.forEach(g=>g.setAttribute("disabled","true")),p();try{await s.onVerify(h),p(),i&&(i.textContent="Verified \u2705")}catch(g){m=!1,S(!1),t.forEach(L=>{L.value="",L.removeAttribute("disabled")}),u(pi(g,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,g)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&g<t.length-1&&t[g+1].focus(),p()},h.onkeydown=L=>{L.key==="Backspace"&&!h.value&&g>0?t[g-1].focus():L.key==="Enter"&&(L.preventDefault(),v())},h.onpaste=L=>{L.preventDefault();let P=(L.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);P.split("").forEach((B,se)=>{t[se]&&(t[se].value=B)});let ce=Math.min(P.length,t.length-1);t[ce]?.focus(),p()}}),i&&(i.onclick=h=>{h.preventDefault(),v()});let C=()=>{let h=30;a&&(a.style.display="none"),l&&(l.style.display="block"),c&&(c.textContent=String(h)),mr(),pr=window.setInterval(()=>{h-=1,c&&(c.textContent=String(h)),h<=0&&(mr(),a&&(a.style.display=""),l&&(l.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(y||a.style.display==="none")){y=!0,t.forEach(g=>{g.value="",g.removeAttribute("disabled")}),t[0]?.focus(),p(),C();try{await s.onResend?.()}catch(g){u(pi(g,"We couldn't send a new code. Please try again when the timer ends."))}finally{y=!1}}}),d&&(d.onclick=h=>{h.preventDefault(),st(),s.onReset?.()})}var Me=()=>window.hcaptcha,gr=async()=>{let s=Me();if(!s)throw new Error("Verification system not loaded");let e=await s.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Nt=(s,e)=>s instanceof Error?s.message:e,gi=(s,e)=>s instanceof fe?s.code==="sso_required"?(e.showSso(),!0):s.code==="scim_managed_domain"?(e.showScim(),!0):(s.code==="sign_in_to_continue"&&e.showLogin(),e.showError(s.message),!0):!1,_i=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:X(r.email)},s.beforeShow(),mi({email:e.email,onVerify:async i=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await j.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await s.onAuthenticated(n)},onResend:async()=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await gr();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{Me()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var le=null;function Xr(s,e=30,t){le&&(clearInterval(le),le=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,le=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",le&&(clearInterval(le),le=null),t&&t())},1e3)}function yi(){le&&(clearInterval(le),le=null)}var wi=/^[\p{L}\p{M}\s\-'.]+$/u;function Yn(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":wi.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Qr(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":wi.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function vi(s,e,t){let r="full-name-match-error",i=l=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let c=document.getElementById(r);c||(c=document.createElement("div"),c.id=r,c.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",c)),c.textContent=l},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let l=Yn(e.value,s.value);l?i(l):n()},a=()=>{let l=Qr(e.value,s.value);l?i(l):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var I=(s,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:s,retry_attempt:10-t}),window.posthog.capture(s,e)):t>0&&setTimeout(()=>I(s,e,t-1),200)},bi=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var Xn="wisprjam.com",Qn="wispr.ai",Zn="wispr_workos_capable",eo=s=>s.trim().toLowerCase().split("@")[1]??"",to=s=>{let e=eo(s);return e===Xn||e===Qn},ki=()=>{try{return window.sessionStorage.getItem(Zn)==="true"}catch{return!1}},ro=s=>Ue()&&to(s);function Si(s,e){let t=new rt,r="email_input",i=null,n=()=>{i?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),l=document.querySelector("#password-input"),c=document.querySelector("#full-name"),d=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),p=document.querySelector("#microsoft-login"),m=document.querySelector("[email-element]"),y=document.querySelector("[different-provider]"),S=document.querySelector("[different-provider-name]"),v=document.querySelector("[different-provider-reset]"),C=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),g=document.querySelector("[error-message]"),L=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),ce=document.querySelector("[email-signup-reset]"),B=document.querySelector("[scim-div]"),se=document.querySelector("[scim-reset]"),N=document.querySelector("[forgot-password]"),ke=document.querySelector("[forgot-password-success]"),it=document.querySelector("[forgot-password-email]"),ee=document.querySelector("[unverified-email]"),nt=document.querySelector("[unverified-email-address]"),de=document.querySelector("[resend-verification-email]"),Se=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(s)}catch(_){console.error("Error during Google sign-in:",_)}}),u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(s)}catch(_){console.error("Error during Apple sign-in:",_)}}),p&&p.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(s)}catch(_){console.error("Error during Microsoft sign-in:",_)}}));let K=()=>{n(),y&&(y.style.display="none"),C&&(C.style.display="none"),h&&(h.style.display="none"),ee&&(ee.style.display="none"),B&&(B.style.display="none"),N&&(N.style.display="none"),ke&&(ke.style.display="none"),st();let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="block"),m&&(m.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),l&&(l.value="",l.style.display="none",l.removeAttribute("required")),c&&(c.value="",c.style.display="none",c.removeAttribute("required"));let b=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");b&&(b.style.display="none"),A&&(A.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),r="email_input",a&&a.focus()},_e=()=>{m&&(m.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="none",c.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),N&&(N.style.display="block",N.onclick=async()=>{let A=a?.value||"",T=N.textContent||"";try{let{hcaptcha:q}=window;if(!q)throw new Error("Verification system not loaded. Please refresh the page.");N.style.pointerEvents="none",N.textContent="Sending...";let{response:R}=await q.execute({async:!0});if(!R)throw new Error("Verification cancelled");await j.requestPasswordReset(A,R),q.reset(),m&&(m.style.display="none"),N&&(N.style.display="none"),ke&&(ke.style.display="block"),it&&(it.textContent=A)}catch(q){console.error("Error sending password reset email:",q),N.textContent=T,N.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",g&&(g.textContent=q instanceof Error?q.message:"Failed to send reset email"))}}),r="login"},ot=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="block",c.setAttribute("required","true"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),r="signup"},at=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),B&&(B.style.display="block"),se&&(se.onclick=()=>{B&&(B.style.display="none"),_&&(_.style.display="block"),K()})},Ne=_=>{n();let b=as(_);m&&(m.style.display="none"),y&&(y.style.display="block"),S&&(S.textContent=b),v&&(v.onclick=()=>{y&&(y.style.display="none"),K()}),r="oauth_user"};i=_i({client:t,redirectUrl:s,isWorkosCapable:Ue,beforeShow:()=>{m&&(m.style.display="none"),ee&&(ee.style.display="none")},onAuthenticated:async _=>{n(),t.setCookies(_.access_token,_.refresh_token),localStorage.setItem("email",_.email),localStorage.setItem("user_id",_.user_id),localStorage.setItem("signin_provider","email");let b=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,b):window.location.href=s},onMissingChallenge:_e,onReset:K});let qe=_=>{m&&(m.style.display="none"),ee&&(ee.style.display="block"),nt&&(nt.textContent=_),de&&(de.onclick=async()=>{let b=de.textContent||"";try{let A=await gr();await t.resendVerificationEmail(_,s,A),de.textContent="Verification email resent! \u2705",de.style.textDecoration="none"}catch(A){de.textContent=b,h&&(h.style.display="block"),g&&(g.textContent=Nt(A,"Unable to resend verification."))}finally{Me()?.reset()}}),Se&&(Se.onclick=()=>{ee&&(ee.style.display="none"),K()}),r="unverified_email"},De=_=>gi(_,{showSso:()=>Ne("workos"),showScim:at,showLogin:_e,showError:b=>{h&&(h.style.display="block"),g&&(g.textContent=b)}}),Fe=async(_,b)=>{let A=b.value;b.classList.add("loading"),b.value="";try{let T=await j.checkUserStatus(_);b.classList.remove("loading"),b.value=A,!T.exists&&T.scim_managed?at():T.enforce_sso?Ne("workos"):T.exists&&T.provider&&T.provider!=="email"&&T.provider!=="workos"?Ne(T.provider):T.exists&&ro(_)||T.exists&&T.provider==="workos"?_e():T.exists&&T.provider==="email"&&!T.verified?qe(_):T.exists&&T.provider==="email"?_e():ot()}catch(T){console.error("Error checking user status:",T),b.classList.remove("loading"),b.value=A,De(T)||ot()}},qt=async(_,b,A,T)=>{if(!b||b.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}let q=window.hcaptcha?.getResponse()||"";if(!q){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let F=await j.signInWithEmail({email:_,password:b,mcp_login_state:e.mcpLoginState,workos_capable:ki()});if(!F.redirect_url)throw new Error(F.error||"Unable to continue connector login. Please try again.");I("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=F.redirect_url;return}let R=await t.signInWithPassword(_,b,q,{workosCapable:ki(),provision:!1});if(R.kind==="otp"){if(!Ue())throw new Error("OTP challenge returned outside dev mode");let F={pendingAuthenticationToken:R.challenge.pending_authentication_token,email:X(R.challenge.email||_)};Me()?.reset(),A.classList.remove("loading"),A.value=T,i?.show(F);return}t.setCookies(R.accessToken,R.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(R.accessToken,R.refreshToken,R.fullName):window.location.href=s}catch(R){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=T,!De(R)&&h&&(h.style.display="block",g&&(g.textContent=Nt(R,"Unable to sign in. Please try again.")))}},lt=async(_,b,A,T,q)=>{if(!b||b.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}if(!A||A.trim().length<2){h&&(h.style.display="block",g&&(g.textContent="Please enter your full name"));return}let R=Qr(A,b);if(R){h&&(h.style.display="block",g&&(g.textContent=R));return}let F=window.hcaptcha?.getResponse()||"";if(!F){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{let te=await t.signUpWithPassword(_,b,A,s,F,{workosCapable:Ue()});if(window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=q,m&&(m.style.display="none"),h&&(h.style.display="none"),Vt(te)){if(!Ue())throw new Error("OTP challenge returned outside dev mode");let Y={pendingAuthenticationToken:te.pending_authentication_token,email:X(te.email||_)};i?.show(Y);return}C&&(C.style.display="block"),L&&(L.textContent=_),P&&(Xr(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let Y=await gr();await t.resendVerificationEmail(_,s,Y,{workosCapable:Ue()}),Xr(P,30)}catch(Y){h&&(h.style.display="block"),g&&(g.textContent=Nt(Y,"Unable to resend verification. Please try again."))}finally{Me()?.reset()}}),ce&&(ce.onclick=()=>{C&&(C.style.display="none"),yi(),K()})}catch(te){T.classList.remove("loading"),T.value=q,Me()?.reset(),!De(te)&&h&&(h.style.display="block",g&&(g.textContent=Nt(te,"Unable to create the account. Please try again.")))}};return o&&l&&c&&vi(l,c,o.querySelector('[type="submit"]')),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let b=X(a?.value||"");a&&(a.value=b);let A=l?.value||"",T=c?.value||"";if(!b||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b)){h&&(h.style.display="block",g&&(g.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),g&&(g.textContent="");let R=o.querySelector('[type="submit"]'),F=R?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await Fe(b,R):r==="login"?await qt(b,A,R,F):r==="signup"&&await lt(b,A,T,R,F)}catch(te){console.error("Auth flow error:",te),R&&(R.classList.remove("loading"),R.value=F),h&&(h.style.display="block")}}),{reset:K}}var _r=function(){return _r=Object.assign||function(s){for(var e,t=1,r=arguments.length;t<r;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i]);return s},_r.apply(this,arguments)},Ei=function(){function s(e,t,r){var i=this;this.endVal=t,this.options=r,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){i.startTime||(i.startTime=n);var o=n-i.startTime;i.remaining=i.duration-o,i.useEasing?i.countDown?i.frameVal=i.startVal-i.easingFn(o,0,i.startVal-i.endVal,i.duration):i.frameVal=i.easingFn(o,i.startVal,i.endVal-i.startVal,i.duration):i.frameVal=i.startVal+(i.endVal-i.startVal)*(o/i.duration);var a=i.countDown?i.frameVal<i.endVal:i.frameVal>i.endVal;i.frameVal=a?i.endVal:i.frameVal,i.frameVal=Number(i.frameVal.toFixed(i.options.decimalPlaces)),i.printValue(i.frameVal),o<i.duration?i.rAF=requestAnimationFrame(i.count):i.finalEndVal!==null?i.update(i.finalEndVal):i.options.onCompleteCallback&&i.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,c,d=n<0?"-":"";o=Math.abs(n).toFixed(i.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?i.options.decimal+u[1]:"",i.options.useGrouping){c="";for(var p=3,m=0,y=0,S=a.length;y<S;++y)i.options.useIndianSeparators&&y===4&&(p=2,m=1),y!==0&&m%p==0&&(c=i.options.separator+c),m++,c=a[S-y-1]+c;a=c}return i.options.numerals&&i.options.numerals.length&&(a=a.replace(/[0-9]/g,function(v){return i.options.numerals[+v]}),l=l.replace(/[0-9]/g,function(v){return i.options.numerals[+v]})),d+i.options.prefix+a+l+i.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=_r(_r({},this.defaults),r),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return i.handleScroll(i)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return s.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,r=e.el.getBoundingClientRect(),i=r.top+window.pageYOffset,n=r.top+r.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||i>t)&&!e.paused&&e.reset()}},s.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var r=this.countDown?1:-1;this.endVal=e+r*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},s.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},s.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},s.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},s.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},s.prototype.printValue=function(e){var t;if(this.el){var r=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,r):this.el.tagName==="INPUT"?this.el.value=r:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=r:this.el.innerHTML=r}},s.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},s.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},s.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},s.prototype.parse=function(e){var t=function(o){return o.replace(/([.,' ])/g,"\\$1")},r=t(this.options.separator),i=t(this.options.decimal),n=e.replace(new RegExp(r,"g"),"").replace(new RegExp(i,"g"),".");return parseFloat(n)},s}();var Ti=!1;function xi(){if(Ti)return;Ti=!0;let s=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(r=>{if(r.isIntersecting){let i=r.target;e.unobserve(i);let n=i.dataset.countDirection||"up",o=parseFloat(i.dataset.countOffset||"10")/100,a=parseFloat(i.dataset.countDuration||"2"),l=5,c=i.dataset.countTarget||i.textContent?.trim()||"0",d=parseFloat(c.replace(/,/g,""));if(isNaN(d))return;let u=d*o,p=Math.max(u,l),m=n==="down"?d+p:Math.max(0,d-p);new Ei(i,d,{startVal:Math.round(m),duration:a,useGrouping:!0}).start()}})},{threshold:0});s.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var Ai=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});async function so(s){let t=new TextEncoder().encode(s.toLowerCase().trim()),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new rt,{accessToken:t,refreshToken:r}=ds(),i=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),c=document.querySelector("[error-div]"),d=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),p=document.querySelector("[spots]"),m=document.querySelectorAll("[referral-code]"),y=document.querySelector("[referral-count]"),S=document.querySelector("[desktop-bonus-remaining]"),v=document.querySelector("[desktop-bonus-complete]"),C=document.querySelector("[climbed-dropped]"),h=document.querySelector("[keep-moving]"),g=document.querySelector("[rank-arrow-wrap]"),L=document.querySelector("[cohort-text]"),P=document.querySelector("[top-100]"),ce=document.querySelector("[top-1000]"),B=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),N=document.querySelector("[sms-bonus-complete]"),ke=document.querySelector("[total-boost]"),it=document.querySelector("[social-media-details]"),ee=document.querySelector("[sms-popup-button]"),nt=document.querySelector("[app-download]"),de=document.querySelector("[file-upload]"),Se=document.querySelector("[file-input]"),K=document.querySelector("[file-validation-error]"),_e=document.querySelector("[file-upload-loading]"),ot=document.querySelector("[cancel-upload-button]"),at=document.querySelector("[file-upload-verified]"),Ne=document.querySelector("[boost-earned]"),yr=document.querySelector("[boost-earned-location]"),qe=document.querySelector("[woohoo-button]"),De=document.querySelector("[file-upload-failed]"),Fe=document.querySelector("[upload-failed-text]"),qt=document.querySelector("[close-button]"),lt=document.querySelector("[share-on-x]"),_=document.querySelector("[share-on-linkedin]"),b=document.querySelector("[share-on-whatsapp]"),A=document.querySelector("[share-on-slack]"),T=document.querySelector("[share-on-discord]"),q=document.querySelector("[social-media-bonus-remaining]"),R=document.querySelector("[social-media-bonus-complete]"),F=document.querySelector("[share-on-other-channel]");it&&it.addEventListener("click",()=>{I("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),ee&&ee.addEventListener("click",()=>{I("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),nt&&nt.addEventListener("click",()=>{window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_app_download",source:"android-waitlist-page"}),I("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let te=async()=>{clearTimeout(s),document.body.style.visibility="visible",o.forEach(Ft=>{Ft.style.display="none"}),n&&(n.style.display="block");let Y=window.__abVariantPromise?await window.__abVariantPromise:"control",He=document.querySelector("[auth-hero-default]"),z=document.querySelector("[auth-hero-v1]"),re=document.querySelector("[auth-hero-v2]");He&&(He.style.display="none"),z&&(z.style.display="none"),re&&(re.style.display="none"),Y==="dictation-broken"&&z?z.style.display="block":Y==="smartest"&&re?re.style.display="block":He&&(He.style.display="block"),n&&(n.style.display="none"),i&&(i.style.display="block");let Dt=document.querySelector("[reusable-section-wrap]");Dt&&i&&i.appendChild(Dt);let ct=document.querySelector(".wl_cohort-spot-wrap");ct&&(ct.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),I("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),Si(`${window.location.origin}/android-waitlist`)};if(!t||!r){await te();return}try{e.setCookies(t,r);let Y=e.checkAndSetSession(),He=new Promise((f,k)=>setTimeout(()=>k(new Error("Session timeout")),3e3));await Promise.race([Y,He]),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(s),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(f=>{f.style.display="flex",f.dataset.bound||(f.dataset.bound="true",f.addEventListener("click",async k=>{k.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let z=e.sessionData?.access_token,re=e.sessionData?.user.email,Dt=e.sessionData?.user.user_metadata.full_name||" ",[ct,Ft]=os(Dt),dt=e.sessionData?.user.id;localStorage.setItem("email",re),dt&&localStorage.setItem("user_id",dt),dt&&bi(dt,{email:re,firstName:ct,lastName:Ft});let Li=Ai(),{dub_id:wr,referral:vr,promo_code:Zr}=Li,Ci=!!localStorage.getItem("conversion_sent"),We=!localStorage.getItem("android_waitlist_joined"),$={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},Ri={access_token:z,first_name:ct,last_name:Ft,dub_click_id:wr||void 0,referral:vr||void 0,promo_code:Zr||void 0};try{await j.signupUser(Ri),$.signup.success=!0}catch(f){$.signup.success=!1,$.signup.error=f instanceof Error?f.message:"Unknown error"}try{let f=await j.ensureReferralCode(z);if($.referral.success=f.ok,!f.ok){let k=await f.json().catch(()=>({}));$.referral.error=k.detail||k.message||`Status ${f.status}`}}catch(f){$.referral.success=!1,$.referral.error=f instanceof Error?f.message:"Network error"}Ci||(I("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:wr||void 0,referral:vr||void 0,email:re,user_id:dt||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"));let Oi={email:re,device_type:"android"},es=!1;try{await j.addToWaitlist(Oi),$.waitlist.success=!0,es=!0}catch(f){$.waitlist.success=!1,$.waitlist.error=f instanceof Error?f.message:"Unknown error"}We&&es&&(localStorage.setItem("android_waitlist_joined","true"),I("app_waitlist",{device_type:"android",source:"android-waitlist-page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:"android",source:"android-waitlist-page"}));let J=await j.getAndroidWaitlistStats(z);if(J.status===404&&!We){I("android_waitlist_recovery_attempted",{reason:"localStorage flag set but 404 from stats API"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_attempted",reason:"localStorage flag set but 404 from stats API"}),localStorage.removeItem("android_waitlist_joined");try{let f={email:re,device_type:"android"};await j.addToWaitlist(f),localStorage.setItem("android_waitlist_joined","true"),J=await j.getAndroidWaitlistStats(z),J.ok&&(I("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(f){console.error("Recovery addToWaitlist failed:",f)}}let Pi=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if($.stats.success=J.ok,J.status===401||J.status===429||!J.ok){let f="";try{let k=await J.json();f=JSON.stringify(k),$.stats.error=k.detail||k.message||f,d&&(d.textContent=`Status: ${J.status} | ${f}`)}catch{f="Could not parse response",$.stats.error=f,d&&(d.textContent=`Status: ${J.status} | ${f}`)}I("android_waitlist_api_error",{status:J.status,error:f,signup_success:$.signup.success,signup_error:$.signup.error,referral_success:$.referral.success,referral_error:$.referral.error,waitlist_success:$.waitlist.success,waitlist_error:$.waitlist.error,stats_error:$.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:J.status,error:f}),a&&(a.style.display="none"),c&&(c.style.display="block");return}let D=await J.json();if(We){let f=await so(re);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:D.current_rank,user_email_hash:f})}let ts=localStorage.getItem("android_waitlist_last_rank");if(ts&&!We){let f=parseInt(ts,10);D.current_rank<f&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:D.current_rank,positions_gained:f-D.current_rank,referral_count:D.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",D.current_rank.toString());let br=f=>{let k=f.current_rank;if(u){let w=k.toLocaleString("en-US");u.textContent=w,u instanceof HTMLElement&&(u.dataset.countTarget=w)}if(f.starting_rank!==null){let w=f.starting_rank-k;p&&(p.textContent=Math.abs(w).toLocaleString()),w<0?(C&&(C.textContent="fell"),h&&(h.style.display="none"),g&&g.classList.add("invert")):(C&&(C.textContent="climbed"),h&&(h.style.display="inline-block"),g&&g.classList.remove("invert"))}if(P&&P.classList.remove("active"),ce&&ce.classList.remove("active"),B&&B.classList.remove("active"),k<=100?P&&P.classList.add("active"):k<=1e3?ce&&ce.classList.add("active"):k<=1e5&&B&&B.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(w=>{w.style.display="none"}),k<=100){let w=document.querySelector('[cohort-wins="top-100"]');w&&(w.style.display="block")}else if(k<=1e3){let w=document.querySelector('[cohort-wins="top-1000"]');w&&(w.style.display="block")}else if(k<=1e5){let w=document.querySelector('[cohort-wins="top-100k"]');w&&(w.style.display="block")}if(L)if(k<=100)L.innerHTML="You're in the <strong>top 100!</strong>";else if(k<=1e3){let w=k-100;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100`}else if(k<=1e5){let w=k-1e3;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 1,000`}else{let w=k-1e5;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100,000`}m.forEach(w=>{w.textContent=f.referral_code}),y&&(y.textContent=f.referrals_count.toString()),f.desktop_dictation_bonus_earned?(S&&(S.style.display="none"),v&&(v.style.display="block")):(S&&(S.style.display="block"),v&&(v.style.display="none")),f.phone_number_bonus_earned?(se&&(se.style.display="none"),N&&(N.style.display="block")):(se&&(se.style.display="block"),N&&(N.style.display="none")),f.verified_share_twitter&<&<.classList.add("verified"),f.verified_share_linkedin&&_&&_.classList.add("verified"),f.verified_share_whatsapp&&b&&b.classList.add("verified"),f.verified_share_slack&&A&&A.classList.add("verified"),f.verified_share_discord&&T&&T.classList.add("verified");let W=f.verified_share_twitter&&f.verified_share_linkedin&&f.verified_share_whatsapp&&f.verified_share_slack&&f.verified_share_discord;if(W&&(q&&(q.style.display="none"),R&&(R.style.display="block")),ke){let w=[f.phone_number_bonus_earned,f.desktop_dictation_bonus_earned,W].filter(Boolean).length;ke.textContent=`${w} of 3`}};br(D);let rs=f=>f<=100?"top-100":f<=1e3?"top-1000":f<=1e5?"top-100k":"below-100k";I("android_waitlist_page_view",{rank:D.current_rank,total_boost:D.total_boost,referrals_count:D.referrals_count,cohort:rs(D.current_rank),is_first_visit:We}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:D.current_rank,total_boost:D.total_boost,referrals_count:D.referrals_count,cohort:rs(D.current_rank),is_first_visit:We});let Ii=`https://wisprflow.ai/waitlist?${D.referral_code}`;document.querySelectorAll("[share]").forEach(f=>{let k=f.getAttribute("share");if(!k)return;let w=document.querySelector(`[share-content="${k}"]`)?.textContent||"";f.addEventListener("click",async()=>{switch(I("android_waitlist_share_clicked",{platform:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:k}),k){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(w)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(w),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(Ii)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(w)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(w),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(w),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async f=>{let k=f,{phoneNumber:W}=k.detail;try{let w=await j.submitPhoneNumber(W,z),ue=await w.json();if(!w.ok||!ue.success){let Ht=ue.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:Ht}})),I("android_waitlist_sms_error",{error:Ht}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:Ht});return}window.dispatchEvent(new CustomEvent("sms:success"));let he=await j.getAndroidWaitlistStats(z);he.ok&&br(await he.json()),I("android_waitlist_sms_submitted",{boost_earned:ue.boost_earned,new_rank:ue.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:ue.boost_earned,new_rank:ue.current_rank})}catch(w){console.error("SMS submission error:",w),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}})),I("android_waitlist_sms_error",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:"network_error"})}});let ye=f=>{de&&(de.style.display=f==="idle"?"block":"none"),_e&&(_e.style.display=f==="loading"?"block":"none"),at&&(at.style.display=f==="verified"?"block":"none"),De&&(De.style.display=f==="failed"?"block":"none"),K&&(K.style.display="none")},ji=f=>{let W=["image/png","image/jpeg","image/jpg"];return f.size>20971520?"File too large. Maximum size is 20MB.":W.includes(f.type)?null:"Please upload a PNG or JPEG image."},$i={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},Ui=f=>$i[f]||"Social Media",Mi={social_share_x:lt,social_share_linkedin:_,social_share_whatsapp:b,social_share_slack:A,social_share_discord:T},Ni=f=>{let k=Mi[f];k&&k.classList.add("verified")},qi=f=>({file_too_large:"File exceeds 20MB limit. (file_too_large)",invalid_file_type:"Please upload a PNG or JPEG. (invalid_file_type)","User not on Android waitlist":"Please join the waitlist first. (User not on Android waitlist)",all_platforms_already_claimed:"You've claimed all social share bonuses! (all_platforms_already_claimed)",x_already_claimed:"You've already received the X bonus. (x_already_claimed)",linkedin_already_claimed:"You've already received the LinkedIn bonus. (linkedin_already_claimed)",whatsapp_already_claimed:"You've already received the WhatsApp bonus. (whatsapp_already_claimed)",slack_already_claimed:"You've already received the Slack bonus. (slack_already_claimed)",discord_already_claimed:"You've already received the Discord bonus. (discord_already_claimed)",not_posted:"This looks like a draft, not a published post. (not_posted)",no_wispr_mention:"Post must mention Wispr Flow or wisprflow.ai. (no_wispr_mention)",invalid:"We couldn't verify this screenshot. Try a clearer image. (invalid)","An error occurred":"Something went wrong. Please try again. (An error occurred)"})[f??""]??`Verification failed. (${f})`,ut=null;Se&&Se.addEventListener("change",async()=>{let f=Se.files?.[0];if(!f)return;Se.value="";let k=ji(f);if(k){K&&(K.textContent=k,K.style.display="block"),I("android_waitlist_social_validation_error",{error:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:k});return}I("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),ye("loading"),ut=new AbortController;try{let W=await j.submitSocialShare(f,z,ut.signal),w=await W.json();if(!W.ok||!w.success){ye("failed"),Fe&&(Fe.textContent=qi(w.error)),I("android_waitlist_social_upload_failed",{error:w.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:w.error});return}ye("verified"),Ne&&(Ne.textContent=w.boost_earned.toLocaleString()),yr&&(yr.textContent=Ui(w.action)),Ni(w.action);let ue=await j.getAndroidWaitlistStats(z);if(ue.ok){let he=await ue.json();br(he),he.verified_share_twitter&&he.verified_share_linkedin&&he.verified_share_whatsapp&&he.verified_share_slack&&he.verified_share_discord&&(qe&&(qe.style.display="none"),F&&(F.style.display="none"),I("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}I("android_waitlist_social_share_verified",{platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank})}catch(W){if(W instanceof Error&&W.name==="AbortError"){ye("idle");return}console.error("Social share upload error:",W),ye("failed"),Fe&&(Fe.textContent="Network error. Please try again."),I("android_waitlist_social_upload_failed",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:"network_error"})}finally{ut=null}}),ot&&ot.addEventListener("click",()=>{ut&&ut.abort(),ye("idle"),I("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),qe&&qe.addEventListener("click",()=>{ye("idle")}),qt&&qt.addEventListener("click",()=>{ye("idle")}),Pi(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),xi()}catch(Y){console.error("Error on android-waitlist page:",Y),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await te()}});})();
|