@tanay-wispr/webflow-package 6.7.3 → 6.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/signup.js CHANGED
@@ -1 +1 @@
1
- "use strict";(()=>{var li=Object.create;var _t=Object.defineProperty;var ui=Object.getOwnPropertyDescriptor;var hi=Object.getOwnPropertyNames;var di=Object.getPrototypeOf,fi=Object.prototype.hasOwnProperty;var pi=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),mi=(s,e)=>{for(var t in e)_t(s,t,{get:e[t],enumerable:!0})},Hr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hi(e))!fi.call(s,i)&&i!==t&&_t(s,i,{get:()=>e[i],enumerable:!(r=ui(e,i))||r.enumerable});return s};var Wr=(s,e,t)=>(t=s!=null?li(di(s)):{},Hr(e||!s||!s.__esModule?_t(t,"default",{value:s,enumerable:!0}):t,s)),gi=s=>Hr(_t({},"__esModule",{value:!0}),s);var le={};mi(le,{Headers:()=>er,Request:()=>bi,Response:()=>ki,default:()=>Zt,fetch:()=>vi});var wi,xe,vi,Zt,er,bi,ki,ne=pi(()=>{"use strict";wi=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")},xe=wi(),vi=xe.fetch,Zt=xe.fetch.bind(xe),er=xe.Headers,bi=xe.Request,ki=xe.Response});var Qr=z(rr=>{"use strict";Object.defineProperty(rr,"__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}};rr.default=tr});var ir=z(Ge=>{"use strict";var Xr=Ge&&Ge.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ge,"__esModule",{value:!0});var Ei=Xr((ne(),gi(le))),Ti=Xr(Qr()),sr=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Ei.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let 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,c;let u=null,l=null,h=null,d=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let T=await n.text();T===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=T:l=JSON.parse(T))}let E=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");E&&y&&y.length>1&&(h=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,h=null,d=406,m="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let E=await n.text();try{u=JSON.parse(E),Array.isArray(u)&&n.status===404&&(l=[],u=null,d=200,m="OK")}catch{n.status===404&&E===""?(d=204,m="No Content"):u={message:E}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,d=200,m="OK"),u&&this.shouldThrowOnError)throw new Ti.default(u)}return{error:u,data:l,count:h,status:d,statusText:m}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};Ge.default=sr});var or=z(Ve=>{"use strict";var xi=Ve&&Ve.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ve,"__esModule",{value:!0});var Ai=xi(ir()),nr=class extends Ai.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 c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Ve.default=nr});var Tt=z(Ke=>{"use strict";var Pi=Ke&&Ke.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ke,"__esModule",{value:!0});var Ci=Pi(or()),ar=class extends Ci.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}};Ke.default=ar});var lr=z(Qe=>{"use strict";var Ri=Qe&&Qe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qe,"__esModule",{value:!0});var Ye=Ri(Tt()),cr=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 Ye.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,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new Ye.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 c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new Ye.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 Ye.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 Ye.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Qe.default=cr});var Zr=z(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.version=void 0;xt.version="0.0.0-automated"});var es=z(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.DEFAULT_HEADERS=void 0;var Oi=Zr();At.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Oi.version}`}});var rs=z(Xe=>{"use strict";var ts=Xe&&Xe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Xe,"__esModule",{value:!0});var Li=ts(lr()),Ii=ts(Tt()),ji=es(),ur=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ji.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Li.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}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([l,h])=>h!==void 0).map(([l,h])=>[l,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([l,h])=>{a.searchParams.append(l,h)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new Ii.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Xe.default=ur});var cs=z($=>{"use strict";var Ze=$&&$.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($,"__esModule",{value:!0});$.PostgrestBuilder=$.PostgrestTransformBuilder=$.PostgrestFilterBuilder=$.PostgrestQueryBuilder=$.PostgrestClient=void 0;var ss=Ze(rs());$.PostgrestClient=ss.default;var is=Ze(lr());$.PostgrestQueryBuilder=is.default;var ns=Ze(Tt());$.PostgrestFilterBuilder=ns.default;var os=Ze(or());$.PostgrestTransformBuilder=os.default;var as=Ze(ir());$.PostgrestBuilder=as.default;$.default={PostgrestClient:ss.default,PostgrestQueryBuilder:is.default,PostgrestFilterBuilder:ns.default,PostgrestTransformBuilder:os.default,PostgrestBuilder:as.default}});var ys=z((_o,gs)=>{"use strict";gs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var We=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,I="https://api.wisprflow.ai",Q=class extends Error{constructor(t,r,i){super(i);this.status=t;this.code=r;this.name="AriaAuthError"}},D=s=>s.trim().toLowerCase(),Br=(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"},He=(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."),yi=(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)??He(e,t),Ee=(s,e)=>{let t=Br(s,e);return new Q(e,t,yi(s,t,e))},_i=(s,e)=>{let t=Br(s,e);return new Q(e,t,He(t,e))},Kt=class{static async signupUser(e){try{let t=`${I}/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(`${I}/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(`${I}/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(`${I}/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(`${I}/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=D(e),r=await fetch(`${I}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw Ee(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${I}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:D(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw Ee(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${I}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:D(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ee(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${I}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:D(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ee(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${I}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:D(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ee(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new Q(422,"invalid_code",He("invalid_code",422));let t=await fetch(`${I}/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=_i(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new Q(t.status,"verification_failed",He("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new Q(t.status,"authentication_failed",He("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${I}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:D(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ee(r,t.status);return r}static async getSubscriptionStatus(e){return await fetch(`${I}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${I}/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=`${I}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`&currency=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${I}/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(`${I}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${I}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${I}/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(`${I}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function Yt(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var J=Kt;var wt=null;function se(){return new URLSearchParams(window.location.search).get("dev-mode")==="true"}var zr=(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},vt=()=>{wt!==null&&(window.clearInterval(wt),wt=null)};function ce(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),vt()}function Jr(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]"),c=document.querySelector("[otp-resend-countdown]"),u=document.querySelector("[otp-resend-seconds]"),l=document.querySelector("[otp-reset]");t.forEach(p=>{p.value="",p.removeAttribute("disabled"),p.setAttribute("inputmode","numeric"),p.setAttribute("autocomplete","one-time-code"),p.setAttribute("data-ph-no-capture",""),p.setAttribute("data-1p-ignore",""),p.setAttribute("data-private",""),p.classList.add("ph-no-capture")}),n&&(n.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),vt(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let h=p=>{n&&(n.style.display="block"),o&&(o.textContent=p)},d=()=>{n&&(n.style.display="none")},m=!1,b=!1,E=p=>{i&&(i.style.pointerEvents=p?"none":"",p?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=p),a&&a.style.display!=="none"&&(a.style.pointerEvents=p?"none":"",p?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},y=async()=>{if(m)return;let p=t.map(P=>P.value).join("");if(p.length!==6){h("Please enter all 6 digits.");return}m=!0,E(!0),t.forEach(P=>P.setAttribute("disabled","true")),d();try{await s.onVerify(p),d(),i&&(i.textContent="Verified \u2705")}catch(P){m=!1,E(!1),t.forEach(R=>{R.value="",R.removeAttribute("disabled")}),h(zr(P,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((p,P)=>{p.oninput=()=>{p.value=p.value.replace(/\D/g,"").slice(0,1),p.value&&P<t.length-1&&t[P+1].focus(),d()},p.onkeydown=R=>{R.key==="Backspace"&&!p.value&&P>0?t[P-1].focus():R.key==="Enter"&&(R.preventDefault(),y())},p.onpaste=R=>{R.preventDefault();let O=(R.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((A,De)=>{t[De]&&(t[De].value=A)});let w=Math.min(O.length,t.length-1);t[w]?.focus(),d()}}),i&&(i.onclick=p=>{p.preventDefault(),y()});let T=()=>{let p=30;a&&(a.style.display="none"),c&&(c.style.display="block"),u&&(u.textContent=String(p)),vt(),wt=window.setInterval(()=>{p-=1,u&&(u.textContent=String(p)),p<=0&&(vt(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async p=>{if(p.preventDefault(),!(b||a.style.display==="none")){b=!0,t.forEach(P=>{P.value="",P.removeAttribute("disabled")}),t[0]?.focus(),d(),T();try{await s.onResend?.()}catch(P){h(zr(P,"We couldn't send a new code. Please try again when the timer ends."))}finally{b=!1}}}),l&&(l.onclick=p=>{p.preventDefault(),ce(),s.onReset?.()})}var ie=()=>window.hcaptcha,Be=async()=>{let s=ie();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},Te=(s,e)=>s instanceof Error?s.message:e,Qt=(s,e)=>s instanceof Q?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,Xt=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:D(r.email)},s.beforeShow(),Jr({email:e.email,onVerify:async i=>{if(!e)throw ce(),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 ce(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await Be();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{ie()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var Gr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Vr=()=>{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 Kr=()=>{let{access_token:s,refresh_token:e}=Vr(),t=s,r=e;if(!t||!r){let i=Gr();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var Yr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ne(),le)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ze=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},bt=class extends ze{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},kt=class extends ze{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},St=class extends ze{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Et;(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"})(Et||(Et={}));var Si=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Je=class{constructor(e,{headers:t={},customFetch:r,region:i=Et.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Yr(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return Si(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(b=>{throw new bt(b)}),h=l.headers.get("x-relay-error");if(h&&h==="true")throw new kt(l);if(!l.ok)throw new St(l);let d=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return d==="application/json"?m=yield l.json():d==="application/octet-stream"?m=yield l.blob():d==="text/event-stream"?m=l:d==="multipart/form-data"?m=yield l.formData():m=yield l.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}};var ls=Wr(cs(),1),{PostgrestClient:us,PostgrestQueryBuilder:Xn,PostgrestFilterBuilder:Zn,PostgrestTransformBuilder:eo,PostgrestBuilder:to}=ls.default;var hs="2.10.2";var ds={"X-Client-Info":`realtime-js/${hs}`},fs="1.0.0",Ct=1e4,ps=1e3,ue;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(ue||(ue={}));var U;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(U||(U={}));var M;(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"})(M||(M={}));var Pt;(function(s){s.websocket="websocket"})(Pt||(Pt={}));var oe;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(oe||(oe={}));var et=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 c=r.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var he=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 C;(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"})(C||(C={}));var dr=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=$i(o,s,e,i),n),{})},$i=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?ms(n,o):hr(o)},ms=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return Ni(e,t)}switch(s){case C.bool:return Ui(e);case C.float4:case C.float8:case C.int2:case C.int4:case C.int8:case C.numeric:case C.oid:return Di(e);case C.json:case C.jsonb:return Mi(e);case C.timestamp:return qi(e);case C.abstime:case C.date:case C.daterange:case C.int4range:case C.int8range:case C.money:case C.reltime:case C.text:case C.time:case C.timestamptz:case C.timetz:case C.tsrange:case C.tstzrange:return hr(e);default:return hr(e)}},hr=s=>s,Ui=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Di=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Mi=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Ni=(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=>ms(e,a))}return s},qi=s=>typeof s=="string"?s.replace(" ","T"):s,Rt=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var de=class{constructor(e,t,r={},i=Ct){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 fr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(fr||(fr={}));var Ae=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(c=>{this.state=s.syncDiff(this.state,c,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={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let h=n[u];if(h){let d=l.map(y=>y.presence_ref),m=h.map(y=>y.presence_ref),b=l.filter(y=>m.indexOf(y.presence_ref)<0),E=h.filter(y=>d.indexOf(y.presence_ref)<0);b.length>0&&(a[u]=b),E.length>0&&(c[u]=E)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},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,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let h=e[a].map(m=>m.presence_ref),d=l.filter(m=>h.indexOf(m.presence_ref)<0);e[a].unshift(...d)}r(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(h=>h.presence_ref);u=u.filter(h=>l.indexOf(h.presence_ref)<0),e[a]=u,i(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(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 pr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(pr||(pr={}));var mr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(mr||(mr={}));var gr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(gr||(gr={}));var Pe=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=U.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 de(this,M.join,this.params,this.timeout),this.rejoinTimer=new he(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=U.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=U.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=U.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=U.errored,this.rejoinTimer.scheduleTimeout())}),this._on(M.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Ae(this),this.broadcastEndpointURL=Rt(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(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var h;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,m=(h=d?.length)!==null&&h!==void 0?h:0,b=[];for(let E=0;E<m;E++){let y=d[E],{filter:{event:T,schema:p,table:P,filter:R}}=y,O=l&&l[E];if(O&&O.event===T&&O.schema===p&&O.table===P&&O.filter===R)b.push(Object.assign(Object.assign({},y),{id:O.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=U.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(M.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new de(this,M.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 de(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:c,leave:u,join:l}=M;if(r&&[a,c,u,l].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var b,E,y;return((b=m.filter)===null||b===void 0?void 0:b.event)==="*"||((y=(E=m.filter)===null||E===void 0?void 0:E.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(m=>m.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var b,E,y,T,p,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let R=m.id,O=(b=m.filter)===null||b===void 0?void 0:b.event;return R&&((E=t.ids)===null||E===void 0?void 0:E.includes(R))&&(O==="*"||O?.toLocaleLowerCase()===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{let R=(p=(T=m?.filter)===null||T===void 0?void 0:T.event)===null||p===void 0?void 0:p.toLocaleLowerCase();return R==="*"||R===((P=t?.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof d=="object"&&"ids"in d){let b=d.data,{schema:E,table:y,commit_timestamp:T,type:p,errors:P}=b;d=Object.assign(Object.assign({},{schema:E,table:y,commit_timestamp:T,eventType:p,new:{},old:{},errors:P}),this._getPayloadRecords(b))}m.callback(d,r)})}_isClosed(){return this.state===U.closed}_isJoined(){return this.state===U.joined}_isJoining(){return this.state===U.joining}_isLeaving(){return this.state===U.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(M.close,{},e)}_onError(e){this._on(M.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=U.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=dr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=dr(e.columns,e.old_record)),t}};var Hi=()=>{},Wi=typeof WebSocket<"u",Ce=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ds,this.params={},this.timeout=Ct,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Hi,this.conn=null,this.sendBuffer=[],this.serializer=new et,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(ne(),le)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Pt.websocket}`,this.httpEndpoint=Rt(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 he(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Wi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new yr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Wr(ys())).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 ue.connecting:return oe.Connecting;case ue.open:return oe.Open;case ue.closing:return oe.Closing;default:return oe.Closed}}isConnected(){return this.connectionState()===oe.Open}channel(e,t={config:{}}){let r=new Pe(`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 c;(c=this.conn)===null||c===void 0||c.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(M.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:fs}))}_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(M.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(ps,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},yr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ue.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Re=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function j(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Ot=class extends Re{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},tt=class extends Re{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Bi=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Lt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ne(),le)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},_s=()=>Bi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ne(),le))).Response:Response});var Oe=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},_r=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),zi=(s,e)=>Oe(void 0,void 0,void 0,function*(){let t=yield _s();s instanceof t?s.json().then(r=>{e(new Ot(_r(r),s.status||500))}).catch(r=>{e(new tt(_r(r),r))}):e(new tt(_r(s),s))}),Ji=(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 It(s,e,t,r,i,n){return Oe(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,Ji(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>zi(c,a))})})}function rt(s,e,t,r){return Oe(this,void 0,void 0,function*(){return It(s,"GET",e,t,r)})}function G(s,e,t,r,i){return Oe(this,void 0,void 0,function*(){return It(s,"POST",e,r,i,t)})}function ws(s,e,t,r,i){return Oe(this,void 0,void 0,function*(){return It(s,"PUT",e,r,i,t)})}function jt(s,e,t,r,i){return Oe(this,void 0,void 0,function*(){return It(s,"DELETE",e,r,i,t)})}var F=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Gi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},vs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},st=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Lt(i)}uploadOrUpdate(e,t,r,i){return F(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},vs),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 c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),h=yield l.json();return l.ok?{data:{path:c,id:h.Id,fullPath:h.Key},error:null}:{data:null,error:h}}catch(n){if(j(n))return{data:null,error:n};throw n}})}upload(e,t,r){return F(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return F(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,u=Object.assign({upsert:vs.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let h=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield h.json();return h.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(j(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return F(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 G(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 Re("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}update(e,t,r){return F(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return F(this,void 0,void 0,function*(){try{return{data:yield G(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}copy(e,t,r){return F(this,void 0,void 0,function*(){try{return{data:{path:(yield G(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(j(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return F(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield G(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(j(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return F(this,void 0,void 0,function*(){try{let i=yield G(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(j(i))return{data:null,error:i};throw i}})}download(e,t){return F(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 rt(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(j(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",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${u}`)}}}remove(e){return F(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(j(t))return{data:null,error:t};throw t}})}list(e,t,r){return F(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Gi),t),{prefix:e||""});return{data:yield G(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(j(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 bs="2.6.0";var ks={"X-Client-Info":`storage-js/${bs}`};var Le=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},it=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},ks),t),this.fetch=Lt(r)}listBuckets(){return Le(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}})}getBucket(e){return Le(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Le(this,void 0,void 0,function*(){try{return{data:yield G(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(j(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Le(this,void 0,void 0,function*(){try{return{data:yield ws(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(j(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Le(this,void 0,void 0,function*(){try{return{data:yield G(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Le(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(j(t))return{data:null,error:t};throw t}})}};var nt=class extends it{constructor(e,t={},r){super(e,t,r)}from(e){return new st(this.url,this.headers,e,this.fetch)}};var Ss="2.44.4";var ot="";typeof Deno<"u"?ot="deno":typeof document<"u"?ot="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ot="react-native":ot="node";var Vi={"X-Client-Info":`supabase-js-${ot}/${Ss}`},Es={headers:Vi},Ts={schema:"public"},xs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},As={};ne();var Ki=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Yi=s=>{let e;return s?e=s:typeof fetch>"u"?e=Zt:e=fetch,(...t)=>e(...t)},Qi=()=>typeof Headers>"u"?er:Headers,Ps=(s,e,t)=>{let r=Yi(t),i=Qi();return(n,o)=>Ki(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",s),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:u}))})};function Cs(s){return s.replace(/\/$/,"")}function Rs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var $t="2.64.4";var Os="http://localhost:9999",Ls="supabase.auth.token";var Is={"X-Client-Info":`gotrue-js/${$t}`},wr=10;var at="X-Supabase-Api-Version",vr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function js(s){return Math.round(Date.now()/1e3)+s}function $s(){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 H=()=>typeof document<"u",fe={tested:!1,writable:!1},ae=()=>{if(!H())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(fe.tested)return fe.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),fe.tested=!0,fe.writable=!0}catch{fe.tested=!0,fe.writable=!1}return fe.writable};function Ut(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 Dt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ne(),le)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Us=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))},lt=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Mt=async(s,e)=>{await s.removeItem(e)};function Xi(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,u,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),u=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var ct=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ct.promiseConstructor=Promise;function kr(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(Xi(r))}async function Ds(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Ms(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 Zi(s){return("0"+s.toString(16)).substr(-2)}function en(){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,Zi).join("")}async function tn(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 rn(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function sn(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 tn(s);return rn(t)}async function pe(s,e,t=!1){let r=en(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await br(s,`${e}-code-verifier`,i);let n=await sn(r);return[n,r===n?"plain":"s256"]}var nn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ns(s){let e=s.headers.get(at);if(!e||!e.match(nn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ut=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function _(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var Nt=class extends ut{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function qs(s){return _(s)&&s.name==="AuthApiError"}var Ie=class extends ut{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},X=class extends ut{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},V=class extends X{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},je=class extends X{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},me=class extends X{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ge=class extends X{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}}},ht=class extends X{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}}},$e=class extends X{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function qt(s){return _(s)&&s.name==="AuthRetryableFetchError"}var dt=class extends X{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var on=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},ye=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),an=[502,503,504];async function Fs(s){var e;if(!Us(s))throw new $e(ye(s),0);if(an.includes(s.status))throw new $e(ye(s),s.status);let t;try{t=await s.json()}catch(n){throw new Ie(ye(n),n)}let r,i=Ns(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 dt(ye(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 dt(ye(t),s.status,t.weak_password.reasons);throw new Nt(ye(t),s.status||500,r)}var cn=(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 k(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[at]||(n[at]=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():"",c=await ln(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function ln(s,e,t,r,i,n){let o=cn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new $e(ye(c),0)}if(a.ok||await Fs(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await Fs(c)}}function Z(s){var e;let t=null;un(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=js(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Sr(s){let e=Z(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 K(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Hs(s){return{data:s,error:null}}function Ws(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=on(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},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Bs(s){return s}function un(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},_e=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Dt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await k(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await k(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:K})}catch(r){if(_(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 k(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Ws,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await k(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:K})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await k(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:Bs});if(l.error)throw l.error;let h=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return m.length>0&&(m.forEach(b=>{let E=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(b.split(";")[1].split("=")[1]);u[`${y}Page`]=E}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(_(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await k(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:K})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await k(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:K})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:K})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await k(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(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await k(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var zs={getItem:s=>ae()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{ae()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{ae()&&globalThis.localStorage.removeItem(s)}};function Er(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function Js(){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 we={debug:!!(globalThis&&ae()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ft=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Ft=class extends ft{};async function Tr(s,e,t){we.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),we.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){we.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{we.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw we.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new Ft(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(we.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()}})}Js();var dn={url:Os,storageKey:Ls,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Is,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},pt=30*1e3,Gs=3;async function Vs(s,e,t){return await t()}var ve=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&&H()&&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({},dn),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 _e({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Dt(i.fetch),this.lock=i.lock||Vs,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:H()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Tr:this.lock=Vs,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:ae()?this.storage=zs:(this.memoryStorage={},this.storage=Er(this.memoryStorage)):(this.memoryStorage={},this.storage=Er(this.memoryStorage)),H()&&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} (${$t}) ${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=H()?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)?{error:e}:{error:new Ie("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await k(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:Z}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:l,password:h,options:d}=e,m=null,b=null;this.flowType==="pkce"&&([m,b]=await pe(this.storage,this.storageKey)),n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:h,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:m,code_challenge_method:b},xform:Z})}else if("phone"in e){let{phone:l,password:h,options:d}=e;n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:h,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:Z})}else throw new me("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await k(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:Sr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await k(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:Sr})}else throw new me("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 je}:(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(_(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 lt(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await k(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Z});return await Mt(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 je}:(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 k(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:Z}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new je}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await pe(this.storage,this.storageKey));let{error:h}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:l}}throw new me("You must provide either an email or phone number.")}catch(a){if(_(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let 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 k(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:Z});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(_(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await pe(this.storage,this.storageKey)),await k(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:Hs})}catch(n){if(_(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new V;let{error:i}=await k(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(_(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await k(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 k(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 me("You must provide either an email or phone number and a type")}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),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 lt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,u,l)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:K}):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 V}:await k(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:K})})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new V;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await pe(this.storage,this.storageKey));let{data:u,error:l}=await k(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:K});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return kr(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 V;let t=Date.now()/1e3,r=t,i=!0,n=null,o=kr(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new V;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!H())throw new ge("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ge("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new ht("Not a valid PKCE flow url.");let t=Ut(window.location.href);if(e){if(!t.code)throw new ht("No code detected.");let{data:p,error:P}=await this._exchangeCodeForSession(t.code);if(P)throw P;let R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:p.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ge(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:c,token_type:u}=t;if(!n||!a||!o||!u)throw new ge("No session defined in URL");let l=Math.round(Date.now()/1e3),h=parseInt(a),d=l+h;c&&(d=parseInt(c));let m=d-l;m*1e3<=pt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${h}s`);let b=d-h;l-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,d,l):l-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",b,d,l);let{data:E,error:y}=await this._getUser(n);if(y)throw y;let T={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:u,user:E.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:T,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Ut(window.location.href);return!!(H()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Ut(window.location.href),t=await lt(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&&!(qs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Mt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=$s(),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 pe(this.storage,this.storageKey,!0));try{return await k(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(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,c,u,l;let{data:h,error:d}=n;if(d)throw d;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:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await k(this.fetch,"GET",m,{headers:this.headers,jwt:(l=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return H()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(_(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await k(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(_(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 Ms(async i=>(i>0&&await Ds(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await k(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Z})),(i,n)=>{let o=200*Math.pow(2,i);return n&&qt(n)&&Date.now()+o-r<pt})}catch(r){if(this._debug(t,"error",r),_(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),H()&&!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 lt(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),qt(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 V;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ct;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new V;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),_(n)){let o={session:null,error:n};return qt(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(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await br(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Mt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&H()&&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(),pt);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)/pt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${pt}ms, refresh threshold is ${Gs} ticks`),i<=Gs&&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 ft)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!H()||!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 pe(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 k(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(_(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:c}=await k(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await k(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(_(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 k(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(_(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 c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(h=>h.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};ve.nextInstanceID=0;var fn=ve,xr=fn;var Ht=class extends xr{constructor(e){super(e)}};var pn=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((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=Cs(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:Ts,realtime:As,auth:Object.assign(Object.assign({},xs),{storageKey:c}),global:Es},l=Rs(r??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Ps(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new us(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Je(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new nt(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:i,storageKey:n,flowType:o,debug:a},c,u){var l;let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ht({url:this.authUrl,headers:Object.assign(Object.assign({},h),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new Ce(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 Ks=(s,e,t)=>new mt(s,e,t);var ee={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var mn=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Wt=s=>{let[e,t]=s.split(".");return!e||!t?null:mn(t)},Ys=s=>{let e=Wt(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 gn="https://api.workos.com",yn=60,Ue=(s,e)=>typeof s[e]=="string"?s[e]:void 0,Qs=(s,e,t)=>{let r=Wt(s);if(!r)return null;let i=Ue(r,"urn:wispr:user_external_id")??Ue(r,"sub"),n=t?.email??Ue(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,c={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},_n=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):gn,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()},Xs=async(s,e)=>{let t=Wt(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=Ue(t,"client_id");if(i-r<yn&&n){let c=await _n(e,n,Ue(t,"iss"),Ue(t,"org_id")),u=Qs(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=r)throw new Error("WorkOS session expired");let a=Qs(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var gt=class{constructor(){this.sessionData=null;this.supabase=Ks(ee.supaBaseUrl,ee.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ee.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||ee.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||ee.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(Ys(t)==="workos"){this.sessionData=await Xs(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||ee.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||ee.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(We(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||ee.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 Y=null;function Bt(s,e=30,t){Y&&(clearInterval(Y),Y=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,Y=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",Y&&(clearInterval(Y),Y=null),t&&t())},1e3)}function Ar(){Y&&(clearInterval(Y),Y=null)}var Zs=/^[\p{L}\p{M}\s\-'.]+$/u;function wn(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Zs.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 zt(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Zs.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 Pr(s,e,t){let r="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let u=document.getElementById(r);u||(u=document.createElement("div"),u.id=r,u.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",u)),u.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let c=wn(e.value,s.value);c?i(c):n()},a=()=>{let c=zt(e.value,s.value);c?i(c):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var Jt=(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(()=>Jt(s,e,t-1),200)};var vn="wisprjam.com",bn="wispr.ai";var kn=s=>s.trim().toLowerCase().split("@")[1]??"",Cr=s=>{let e=kn(s);return e===vn||e===bn};var ei=s=>se()&&Cr(s);window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=localStorage.getItem("checkout_debug");if(s){try{let f=JSON.parse(s);Jt("checkout_debug",{...f,reported_from:"get_started",ms_since_error:Date.now()-(f.timestamp??Date.now())})}catch{}localStorage.removeItem("checkout_debug")}let e=!1,t=setTimeout(()=>{e||(document.body.style.visibility="visible")},4e3),r=new gt,i=null,n=()=>{i?.clear()},{accessToken:o,refreshToken:a}=Kr(),c=document.querySelector("#email-form"),u=document.querySelector("#email-input"),l=document.querySelector("#password-input"),h=document.querySelector("#full-name"),d=document.querySelector("#google-login"),m=document.querySelector("#apple-login"),b=document.querySelector("#microsoft-login"),E;(x=>(x.EMAIL_INPUT="email_input",x.LOGIN="login",x.SIGNUP="signup",x.OAUTH_USER="oauth_user",x.UNVERIFIED_EMAIL="unverified_email"))(E||(E={}));let y="email_input",T=document.querySelector("[email-element]"),p=document.querySelector("[different-provider]"),P=document.querySelector("[different-provider-name]"),R=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),w=document.querySelector("[email-signup-error]"),A=document.querySelector("[error-message]"),De=document.querySelector("[verification-email]"),Me=document.querySelector("[email-signup-retry]"),Rr=document.querySelector("[email-signup-reset]"),be=document.querySelector("[scim-div]"),Or=document.querySelector("[scim-reset]"),N=document.querySelector("[forgot-password]"),yt=document.querySelector("[forgot-password-success]"),Lr=document.querySelector("[forgot-password-email]"),te=document.querySelector("[unverified-email]"),Ir=document.querySelector("[unverified-email-address]"),W=document.querySelector("[resend-verification-email]"),jr=document.querySelector("[unverified-email-reset]"),ti=localStorage.getItem("email"),$r=localStorage.getItem("last_authed_provider");$r&&{google:d,apple:m,microsoft:b,sso:document.querySelector("#sso-login"),email:u}[$r]?.classList.add("last-used");let ke=new URLSearchParams(window.location.search),Ur=ke.get("referral"),Dr=ke.get("plan"),Mr=ke.get("utm_source"),ri=ke.get("redirect"),Nr=ke.get("team_invite_code"),Sn=ke.get("code"),si=ri==="android-waitlist"?"/android-waitlist":"/downloads",q=`${window.location.origin}${si}`,Se=new URLSearchParams;Ur&&Se.append("referral",Ur),Dr&&Se.append("plan",Dr),Mr&&Se.append("utm_source",Mr),Nr&&Se.append("team_invite_code",Nr),Se.toString()&&(q+=`?${Se.toString()}`);let ii=()=>{try{let f=document.cookie.split("; ");for(let g of f){let S=g.indexOf("=");if(S===-1||g.slice(0,S)!=="wispr_auth")continue;let L=g.slice(S+1),x=decodeURIComponent(L);return JSON.parse(x)}return null}catch{return null}};if(o&&a)try{r.setCookies(o,a);let f=r.checkAndSetSession(),g=new Promise((v,L)=>setTimeout(()=>L(new Error("Session timeout")),3e3));await Promise.race([f,g]),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token);let S=r.sessionData?.user.email;localStorage.setItem("email",S),e=!0,clearTimeout(t),window.location.href=q}catch(f){console.error("Error during session setup:",f),document.body.style.visibility="visible"}else{let f=ii();if(f?.access_token&&f?.refresh_token)try{r.setCookies(f.access_token,f.refresh_token);let g=r.checkAndSetSession(),S=new Promise((x,B)=>setTimeout(()=>B(new Error("Session timeout")),3e3));await Promise.race([g,S]),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token);let v=r.sessionData?.user.email,L=r.sessionData?.user.app_metadata.provider||"typing_test";localStorage.setItem("email",v),localStorage.setItem("signin_provider",L),e=!0,clearTimeout(t),window.location.href=q}catch(g){console.error("Error authenticating from typing test session:",g),f.email&&(u.value=f.email),document.body.style.visibility="visible"}else f?.email?(u.value=f.email,document.body.style.visibility="visible"):(ti&&localStorage.removeItem("email"),document.body.style.visibility="visible")}d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await r.signInWithGoogle(q)}catch(f){console.error("Error during sign-in:",f)}}),m.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await r.signInWithApple(q)}catch(f){console.error("Error during sign-in:",f)}}),b.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await r.signInWithMicrosoft(q)}catch(f){console.error("Error during sign-in:",f)}});let Ne=()=>{n(),p&&(p.style.display="none"),O&&(O.style.display="none"),w&&(w.style.display="none"),te&&(te.style.display="none"),be&&(be.style.display="none"),N&&(N.style.display="none"),yt&&(yt.style.display="none"),ce();let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="block"),T&&(T.style.display="flex"),u.value="",u.removeAttribute("readonly"),u.classList.remove("disabled"),l.value="",l.style.display="none",l.removeAttribute("required"),h.value="",h.style.display="none",h.removeAttribute("required");let g=document.querySelector("[captcha-embed]"),S=document.querySelector("#h-captcha-container");g&&(g.style.display="none"),S&&(S.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),y="email_input",u.focus()},qe=()=>{T&&(T.style.display="flex"),u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),l.focus(),h.style.display="none",h.removeAttribute("required");let f=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),g&&(g.style.display="block"),N&&(N.style.display="block",N.onclick=async()=>{let S=u.value,v=N.textContent||"";try{let{hcaptcha:L}=window;if(!L)throw new Error("Verification system not loaded. Please refresh the page.");N.style.pointerEvents="none",N.textContent="Sending...";let{response:x}=await L.execute({async:!0});if(!x)throw new Error("Verification cancelled");await J.requestPasswordReset(S,x),L.reset(),T&&(T.style.display="none"),N&&(N.style.display="none"),yt&&(yt.style.display="block"),Lr&&(Lr.textContent=S)}catch(L){console.error("\u274C Error sending password reset email:",L),N.textContent=v,N.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),w&&(w.style.display="block",A&&(A.textContent=L instanceof Error?L.message:"Failed to send reset email"))}}),y="login",console.log("\u2705 Existing user detected - showing login form")},qr=()=>{u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),h.style.display="block",h.setAttribute("required","true"),l.focus();let f=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),g&&(g.style.display="block"),y="signup",console.log("\u2705 New user detected - showing signup form")},Fr=()=>{let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="none"),be&&(be.style.display="block"),Or&&(Or.onclick=()=>{be&&(be.style.display="none"),f&&(f.style.display="block"),Ne()})},Gt=f=>{n();let g=Yt(f);T&&(T.style.display="none"),p&&(p.style.display="block"),P&&(P.textContent=g),R&&(R.onclick=()=>{p&&(p.style.display="none"),Ne()}),y="oauth_user"};i=Xt({client:r,redirectUrl:q,isWorkosCapable:se,beforeShow:()=>{T&&(T.style.display="none"),te&&(te.style.display="none")},onAuthenticated:async f=>{n(),r.setCookies(f.access_token,f.refresh_token),localStorage.setItem("email",f.email),localStorage.setItem("user_id",f.user_id),localStorage.setItem("signin_provider","email"),e=!0,clearTimeout(t),window.location.href=q},onMissingChallenge:qe,onReset:Ne});let ni=f=>{T&&(T.style.display="none"),te&&(te.style.display="block"),Ir&&(Ir.textContent=f),W&&(W.onclick=async()=>{let g=W.textContent||"";try{W.textContent="Verifying...",W.style.pointerEvents="none";let S=await Be();W.textContent="Sending...",await r.resendVerificationEmail(f,q,S),W.textContent="Verification email resent! \u2705",W.style.textDecoration="none",w&&(w.style.display="none")}catch(S){W.textContent=g,W.style.pointerEvents="auto",w&&(w.style.display="block"),A&&(A.textContent=Te(S,"Unable to resend verification."))}finally{ie()?.reset()}}),jr&&(jr.onclick=()=>{te&&(te.style.display="none"),Ne()}),y="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},Vt=f=>Qt(f,{showSso:()=>Gt("workos"),showScim:Fr,showLogin:qe,showError:g=>{w&&(w.style.display="block"),A&&(A.textContent=g)}}),oi=async(f,g)=>{let S=g.value;g.classList.add("loading"),g.value="";try{let v=await J.checkUserStatus(f);console.log("User status check:",v),g.classList.remove("loading"),g.value=S,!v.exists&&v.scim_managed?Fr():v.enforce_sso?Gt("workos"):v.exists&&v.provider&&v.provider!=="email"&&v.provider!=="workos"?Gt(v.provider):v.exists&&ei(f)||v.exists&&v.provider==="workos"?qe():v.exists&&v.provider==="email"&&!v.verified?ni(f):v.exists&&v.provider==="email"?qe():qr()}catch(v){console.error("\u274C Error checking user status:",v),g.classList.remove("loading"),g.value=S,Vt(v)||qr()}},ai=async(f,g,S,v)=>{if(!g||g.length<8){w&&(w.style.display="block",A&&(A.textContent="Password must be at least 8 characters"));return}let L=window.hcaptcha?.getResponse()||"";if(!L){w&&(w.style.display="block",A&&(A.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{let x=await r.signInWithPassword(f,g,L,{workosCapable:Cr(f),provision:!1});if(x.kind==="otp"){if(!se())throw new Error("OTP challenge returned outside dev mode");let B={pendingAuthenticationToken:x.challenge.pending_authentication_token,email:D(x.challenge.email||f)};ie()?.reset(),S.classList.remove("loading"),S.value=v,i?.show(B);return}r.setCookies(x.accessToken,x.refreshToken),localStorage.setItem("email",f),e=!0,clearTimeout(t),window.location.href=q}catch(x){window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=v,!Vt(x)&&w&&(w.style.display="block",A&&(A.textContent=Te(x,"Unable to sign in. Please try again.")))}},ci=async(f,g,S,v,L)=>{if(!g||g.length<8){w&&(w.style.display="block",A&&(A.textContent="Password must be at least 8 characters"));return}if(!S||S.trim().length<2){w&&(w.style.display="block",A&&(A.textContent="Please enter your full name"));return}let x=zt(S,g);if(x){w&&(w.style.display="block",A&&(A.textContent=x));return}let B=window.hcaptcha?.getResponse()||"";if(!B){w&&(w.style.display="block",A&&(A.textContent="Please complete the verification"));return}v.classList.add("loading"),v.value="";try{let re=await r.signUpWithPassword(f,g,S,q,B,{workosCapable:se()});if(window.hcaptcha&&window.hcaptcha.reset(),v.classList.remove("loading"),v.value=L,T&&(T.style.display="none"),w&&(w.style.display="none"),We(re)){if(!se())throw new Error("OTP challenge returned outside dev mode");let Fe={pendingAuthenticationToken:re.pending_authentication_token,email:D(re.email||f)};i?.show(Fe);return}O&&(O.style.display="block"),De&&(De.textContent=f),Me&&(Bt(Me,30),Me.onclick=async()=>{if(Me.style.pointerEvents!=="none")try{let Fe=await Be();await r.resendVerificationEmail(f,q,Fe,{workosCapable:se()}),Bt(Me,30)}catch(Fe){w&&(w.style.display="block"),A&&(A.textContent=Te(Fe,"Unable to resend verification. Please try again."))}finally{ie()?.reset()}}),Rr&&(Rr.onclick=()=>{O&&(O.style.display="none"),Ar(),Ne()})}catch(re){v.classList.remove("loading"),v.value=L,ie()?.reset(),!Vt(re)&&w&&(w.style.display="block",A&&(A.textContent=Te(re,"Unable to create the account. Please try again.")))}};Pr(l,h,c.querySelector('[type="submit"]')),c.addEventListener("submit",async f=>{f.stopPropagation(),f.preventDefault();let g=D(u.value);u.value=g;let S=l?.value||"",v=h?.value||"";if(!g||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g)){console.error("\u274C Email invalid"),w&&(w.style.display="block",A&&(A.textContent="Please enter a valid email address"));return}w&&(w.style.display="none"),A&&(A.textContent="");let x=c.querySelector('[type="submit"]'),B=x?.value||"";localStorage.setItem("signin_provider","email");try{y==="email_input"?await oi(g,x):y==="login"?await ai(g,S,x,B):y==="signup"&&await ci(g,S,v,x,B)}catch(re){console.error("\u274C Signup error:",re),x&&(x.classList.remove("loading"),x.value=B),w&&(w.style.display="block")}})});})();
1
+ "use strict";(()=>{var ai=Object.create;var yt=Object.defineProperty;var ci=Object.getOwnPropertyDescriptor;var li=Object.getOwnPropertyNames;var ui=Object.getPrototypeOf,hi=Object.prototype.hasOwnProperty;var di=(s,e)=>()=>(s&&(e=s(s=0)),e);var J=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),fi=(s,e)=>{for(var t in e)yt(s,t,{get:e[t],enumerable:!0})},qr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of li(e))!hi.call(s,i)&&i!==t&&yt(s,i,{get:()=>e[i],enumerable:!(r=ci(e,i))||r.enumerable});return s};var Fr=(s,e,t)=>(t=s!=null?ai(ui(s)):{},qr(e||!s||!s.__esModule?yt(t,"default",{value:s,enumerable:!0}):t,s)),pi=s=>qr(yt({},"__esModule",{value:!0}),s);var ce={};fi(ce,{Headers:()=>Zt,Request:()=>wi,Response:()=>vi,default:()=>Xt,fetch:()=>_i});var yi,Te,_i,Xt,Zt,wi,vi,ie=di(()=>{"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")},Te=yi(),_i=Te.fetch,Xt=Te.fetch.bind(Te),Zt=Te.Headers,wi=Te.Request,vi=Te.Response});var Kr=J(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});var er=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};tr.default=er});var sr=J(ze=>{"use strict";var Yr=ze&&ze.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ze,"__esModule",{value:!0});var ki=Yr((ie(),pi(ce))),Si=Yr(Kr()),rr=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=ki.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,c;let u=null,l=null,h=null,d=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let T=await n.text();T===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=T:l=JSON.parse(T))}let E=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");E&&y&&y.length>1&&(h=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,h=null,d=406,m="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let E=await n.text();try{u=JSON.parse(E),Array.isArray(u)&&n.status===404&&(l=[],u=null,d=200,m="OK")}catch{n.status===404&&E===""?(d=204,m="No Content"):u={message:E}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,d=200,m="OK"),u&&this.shouldThrowOnError)throw new Si.default(u)}return{error:u,data:l,count:h,status:d,statusText:m}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};ze.default=rr});var nr=J(Je=>{"use strict";var Ei=Je&&Je.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Je,"__esModule",{value:!0});var Ti=Ei(sr()),ir=class extends Ti.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 c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Je.default=ir});var Et=J(Ge=>{"use strict";var xi=Ge&&Ge.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ge,"__esModule",{value:!0});var Ai=xi(nr()),or=class extends Ai.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let 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}};Ge.default=or});var cr=J(Ke=>{"use strict";var Ci=Ke&&Ke.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ke,"__esModule",{value:!0});var Ve=Ci(Et()),ar=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 Ve.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,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new Ve.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 c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new Ve.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 Ve.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 Ve.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ke.default=ar});var Qr=J(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.version=void 0;Tt.version="0.0.0-automated"});var Xr=J(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.DEFAULT_HEADERS=void 0;var Pi=Qr();xt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Pi.version}`}});var es=J(Ye=>{"use strict";var Zr=Ye&&Ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ye,"__esModule",{value:!0});var Ri=Zr(cr()),Oi=Zr(Et()),Li=Xr(),lr=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},Li.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Ri.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}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([l,h])=>h!==void 0).map(([l,h])=>[l,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([l,h])=>{a.searchParams.append(l,h)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new Oi.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Ye.default=lr});var os=J($=>{"use strict";var Qe=$&&$.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($,"__esModule",{value:!0});$.PostgrestBuilder=$.PostgrestTransformBuilder=$.PostgrestFilterBuilder=$.PostgrestQueryBuilder=$.PostgrestClient=void 0;var ts=Qe(es());$.PostgrestClient=ts.default;var rs=Qe(cr());$.PostgrestQueryBuilder=rs.default;var ss=Qe(Et());$.PostgrestFilterBuilder=ss.default;var is=Qe(nr());$.PostgrestTransformBuilder=is.default;var ns=Qe(sr());$.PostgrestBuilder=ns.default;$.default={PostgrestClient:ts.default,PostgrestQueryBuilder:rs.default,PostgrestFilterBuilder:ss.default,PostgrestTransformBuilder:is.default,PostgrestBuilder:ns.default}});var ms=J((go,ps)=>{"use strict";ps.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Fe=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,I="https://api.wisprflow.ai",X=class extends Error{constructor(t,r,i){super(i);this.status=t;this.code=r;this.name="AriaAuthError"}},M=s=>s.trim().toLowerCase(),Hr=(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"},qe=(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."),mi=(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)??qe(e,t),Se=(s,e)=>{let t=Hr(s,e);return new X(e,t,mi(s,t,e))},gi=(s,e)=>{let t=Hr(s,e);return new X(e,t,qe(t,e))},Vt=class{static async signupUser(e){try{let t=`${I}/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(`${I}/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(`${I}/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(`${I}/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(`${I}/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=M(e),r=await fetch(`${I}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw Se(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${I}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:M(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw Se(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${I}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:M(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Se(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${I}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:M(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Se(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${I}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:M(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Se(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new X(422,"invalid_code",qe("invalid_code",422));let t=await fetch(`${I}/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=gi(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new X(t.status,"verification_failed",qe("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new X(t.status,"authentication_failed",qe("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${I}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:M(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Se(r,t.status);return r}static async getSubscriptionStatus(e){return await fetch(`${I}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${I}/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=`${I}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`&currency=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${I}/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(`${I}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${I}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${I}/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(`${I}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function Kt(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var G=Vt;var _t=null,Wr=(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},wt=()=>{_t!==null&&(window.clearInterval(_t),_t=null)};function ae(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),wt()}function Br(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]"),c=document.querySelector("[otp-resend-countdown]"),u=document.querySelector("[otp-resend-seconds]"),l=document.querySelector("[otp-reset]");t.forEach(p=>{p.value="",p.removeAttribute("disabled"),p.setAttribute("inputmode","numeric"),p.setAttribute("autocomplete","one-time-code"),p.setAttribute("data-ph-no-capture",""),p.setAttribute("data-1p-ignore",""),p.setAttribute("data-private",""),p.classList.add("ph-no-capture")}),n&&(n.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),wt(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let h=p=>{n&&(n.style.display="block"),o&&(o.textContent=p)},d=()=>{n&&(n.style.display="none")},m=!1,v=!1,E=p=>{i&&(i.style.pointerEvents=p?"none":"",p?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=p),a&&a.style.display!=="none"&&(a.style.pointerEvents=p?"none":"",p?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},y=async()=>{if(m)return;let p=t.map(A=>A.value).join("");if(p.length!==6){h("Please enter all 6 digits.");return}m=!0,E(!0),t.forEach(A=>A.setAttribute("disabled","true")),d();try{await s.onVerify(p),d(),i&&(i.textContent="Verified \u2705")}catch(A){m=!1,E(!1),t.forEach(R=>{R.value="",R.removeAttribute("disabled")}),h(Wr(A,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((p,A)=>{p.oninput=()=>{p.value=p.value.replace(/\D/g,"").slice(0,1),p.value&&A<t.length-1&&t[A+1].focus(),d()},p.onkeydown=R=>{R.key==="Backspace"&&!p.value&&A>0?t[A-1].focus():R.key==="Enter"&&(R.preventDefault(),y())},p.onpaste=R=>{R.preventDefault();let O=(R.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((x,Ue)=>{t[Ue]&&(t[Ue].value=x)});let w=Math.min(O.length,t.length-1);t[w]?.focus(),d()}}),i&&(i.onclick=p=>{p.preventDefault(),y()});let T=()=>{let p=30;a&&(a.style.display="none"),c&&(c.style.display="block"),u&&(u.textContent=String(p)),wt(),_t=window.setInterval(()=>{p-=1,u&&(u.textContent=String(p)),p<=0&&(wt(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async p=>{if(p.preventDefault(),!(v||a.style.display==="none")){v=!0,t.forEach(A=>{A.value="",A.removeAttribute("disabled")}),t[0]?.focus(),d(),T();try{await s.onResend?.()}catch(A){h(Wr(A,"We couldn't send a new code. Please try again when the timer ends."))}finally{v=!1}}}),l&&(l.onclick=p=>{p.preventDefault(),ae(),s.onReset?.()})}var se=()=>window.hcaptcha,He=async()=>{let s=se();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},Ee=(s,e)=>s instanceof Error?s.message:e,Yt=(s,e)=>s instanceof X?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,Qt=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:M(r.email)},s.beforeShow(),Br({email:e.email,onVerify:async i=>{if(!e)throw ae(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await G.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await s.onAuthenticated(n)},onResend:async()=>{if(!e)throw ae(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await He();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{se()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var zr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Jr=()=>{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 Gr=()=>{let{access_token:s,refresh_token:e}=Jr(),t=s,r=e;if(!t||!r){let i=zr();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var Vr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ie(),ce)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var We=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},vt=class extends We{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},bt=class extends We{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},kt=class extends We{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},St;(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"})(St||(St={}));var bi=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Be=class{constructor(e,{headers:t={},customFetch:r,region:i=St.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Vr(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return bi(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(v=>{throw new vt(v)}),h=l.headers.get("x-relay-error");if(h&&h==="true")throw new bt(l);if(!l.ok)throw new kt(l);let d=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return d==="application/json"?m=yield l.json():d==="application/octet-stream"?m=yield l.blob():d==="text/event-stream"?m=l:d==="multipart/form-data"?m=yield l.formData():m=yield l.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}};var as=Fr(os(),1),{PostgrestClient:cs,PostgrestQueryBuilder:Yn,PostgrestFilterBuilder:Qn,PostgrestTransformBuilder:Xn,PostgrestBuilder:Zn}=as.default;var ls="2.10.2";var us={"X-Client-Info":`realtime-js/${ls}`},hs="1.0.0",Ct=1e4,ds=1e3,le;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(le||(le={}));var D;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(D||(D={}));var N;(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"})(N||(N={}));var At;(function(s){s.websocket="websocket"})(At||(At={}));var ne;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(ne||(ne={}));var Xe=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 c=r.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var ue=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var P;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(P||(P={}));var hr=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ii(o,s,e,i),n),{})},Ii=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?fs(n,o):ur(o)},fs=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return Di(e,t)}switch(s){case P.bool:return ji(e);case P.float4:case P.float8:case P.int2:case P.int4:case P.int8:case P.numeric:case P.oid:return $i(e);case P.json:case P.jsonb:return Ui(e);case P.timestamp:return Mi(e);case P.abstime:case P.date:case P.daterange:case P.int4range:case P.int8range:case P.money:case P.reltime:case P.text:case P.time:case P.timestamptz:case P.timetz:case P.tsrange:case P.tstzrange:return ur(e);default:return ur(e)}},ur=s=>s,ji=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},$i=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Ui=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Di=(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=>fs(e,a))}return s},Mi=s=>typeof s=="string"?s.replace(" ","T"):s,Pt=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var he=class{constructor(e,t,r={},i=Ct){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 dr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(dr||(dr={}));var xe=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(c=>{this.state=s.syncDiff(this.state,c,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={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let h=n[u];if(h){let d=l.map(y=>y.presence_ref),m=h.map(y=>y.presence_ref),v=l.filter(y=>m.indexOf(y.presence_ref)<0),E=h.filter(y=>d.indexOf(y.presence_ref)<0);v.length>0&&(a[u]=v),E.length>0&&(c[u]=E)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},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,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let h=e[a].map(m=>m.presence_ref),d=l.filter(m=>h.indexOf(m.presence_ref)<0);e[a].unshift(...d)}r(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(h=>h.presence_ref);u=u.filter(h=>l.indexOf(h.presence_ref)<0),e[a]=u,i(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(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 fr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(fr||(fr={}));var pr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(pr||(pr={}));var mr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(mr||(mr={}));var Ae=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=D.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 he(this,N.join,this.params,this.timeout),this.rejoinTimer=new ue(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=D.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=D.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=D.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=D.errored,this.rejoinTimer.scheduleTimeout())}),this._on(N.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new xe(this),this.broadcastEndpointURL=Pt(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(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var h;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,m=(h=d?.length)!==null&&h!==void 0?h:0,v=[];for(let E=0;E<m;E++){let y=d[E],{filter:{event:T,schema:p,table:A,filter:R}}=y,O=l&&l[E];if(O&&O.event===T&&O.schema===p&&O.table===A&&O.filter===R)v.push(Object.assign(Object.assign({},y),{id:O.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=D.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(N.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new he(this,N.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 he(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:c,leave:u,join:l}=N;if(r&&[a,c,u,l].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var v,E,y;return((v=m.filter)===null||v===void 0?void 0:v.event)==="*"||((y=(E=m.filter)===null||E===void 0?void 0:E.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(m=>m.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var v,E,y,T,p,A;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let R=m.id,O=(v=m.filter)===null||v===void 0?void 0:v.event;return R&&((E=t.ids)===null||E===void 0?void 0:E.includes(R))&&(O==="*"||O?.toLocaleLowerCase()===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{let R=(p=(T=m?.filter)===null||T===void 0?void 0:T.event)===null||p===void 0?void 0:p.toLocaleLowerCase();return R==="*"||R===((A=t?.event)===null||A===void 0?void 0:A.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof d=="object"&&"ids"in d){let v=d.data,{schema:E,table:y,commit_timestamp:T,type:p,errors:A}=v;d=Object.assign(Object.assign({},{schema:E,table:y,commit_timestamp:T,eventType:p,new:{},old:{},errors:A}),this._getPayloadRecords(v))}m.callback(d,r)})}_isClosed(){return this.state===D.closed}_isJoined(){return this.state===D.joined}_isJoining(){return this.state===D.joining}_isLeaving(){return this.state===D.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(N.close,{},e)}_onError(e){this._on(N.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=D.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=hr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=hr(e.columns,e.old_record)),t}};var qi=()=>{},Fi=typeof WebSocket<"u",Ce=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=us,this.params={},this.timeout=Ct,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=qi,this.conn=null,this.sendBuffer=[],this.serializer=new Xe,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(ie(),ce)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${At.websocket}`,this.httpEndpoint=Pt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(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 ue(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(Fi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new gr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Fr(ms())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case le.connecting:return ne.Connecting;case le.open:return ne.Open;case le.closing:return ne.Closing;default:return ne.Closed}}isConnected(){return this.connectionState()===ne.Open}channel(e,t={config:{}}){let r=new Ae(`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 c;(c=this.conn)===null||c===void 0||c.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(N.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:hs}))}_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(N.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(ds,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},gr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=le.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Pe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function j(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Rt=class extends Pe{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Ze=class extends Pe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Hi=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Ot=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ie(),ce)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},gs=()=>Hi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ie(),ce))).Response:Response});var Re=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},yr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Wi=(s,e)=>Re(void 0,void 0,void 0,function*(){let t=yield gs();s instanceof t?s.json().then(r=>{e(new Rt(yr(r),s.status||500))}).catch(r=>{e(new Ze(yr(r),r))}):e(new Ze(yr(s),s))}),Bi=(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 Lt(s,e,t,r,i,n){return Re(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,Bi(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Wi(c,a))})})}function et(s,e,t,r){return Re(this,void 0,void 0,function*(){return Lt(s,"GET",e,t,r)})}function V(s,e,t,r,i){return Re(this,void 0,void 0,function*(){return Lt(s,"POST",e,r,i,t)})}function ys(s,e,t,r,i){return Re(this,void 0,void 0,function*(){return Lt(s,"PUT",e,r,i,t)})}function It(s,e,t,r,i){return Re(this,void 0,void 0,function*(){return Lt(s,"DELETE",e,r,i,t)})}var H=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},zi={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=Ot(i)}uploadOrUpdate(e,t,r,i){return H(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 c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),h=yield l.json();return l.ok?{data:{path:c,id:h.Id,fullPath:h.Key},error:null}:{data:null,error:h}}catch(n){if(j(n))return{data:null,error:n};throw n}})}upload(e,t,r){return H(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return H(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,u=Object.assign({upsert:_s.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let h=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield h.json();return h.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(j(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return H(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 V(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 Pe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}update(e,t,r){return H(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return H(this,void 0,void 0,function*(){try{return{data:yield V(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}copy(e,t,r){return H(this,void 0,void 0,function*(){try{return{data:{path:(yield V(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(j(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return H(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield V(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(j(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return H(this,void 0,void 0,function*(){try{let i=yield V(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(j(i))return{data:null,error:i};throw i}})}download(e,t){return H(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(j(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",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${u}`)}}}remove(e){return H(this,void 0,void 0,function*(){try{return{data:yield It(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}list(e,t,r){return H(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},zi),t),{prefix:e||""});return{data:yield V(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(j(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 ws="2.6.0";var vs={"X-Client-Info":`storage-js/${ws}`};var Oe=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},rt=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},vs),t),this.fetch=Ot(r)}listBuckets(){return Oe(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}})}getBucket(e){return Oe(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(j(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Oe(this,void 0,void 0,function*(){try{return{data:yield V(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(j(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Oe(this,void 0,void 0,function*(){try{return{data:yield ys(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Oe(this,void 0,void 0,function*(){try{return{data:yield V(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Oe(this,void 0,void 0,function*(){try{return{data:yield It(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}};var st=class extends rt{constructor(e,t={},r){super(e,t,r)}from(e){return new tt(this.url,this.headers,e,this.fetch)}};var bs="2.44.4";var it="";typeof Deno<"u"?it="deno":typeof document<"u"?it="web":typeof navigator<"u"&&navigator.product==="ReactNative"?it="react-native":it="node";var Ji={"X-Client-Info":`supabase-js-${it}/${bs}`},ks={headers:Ji},Ss={schema:"public"},Es={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ts={};ie();var Gi=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Vi=s=>{let e;return s?e=s:typeof fetch>"u"?e=Xt:e=fetch,(...t)=>e(...t)},Ki=()=>typeof Headers>"u"?Zt:Headers,xs=(s,e,t)=>{let r=Vi(t),i=Ki();return(n,o)=>Gi(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",s),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:u}))})};function As(s){return s.replace(/\/$/,"")}function Cs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var jt="2.64.4";var Ps="http://localhost:9999",Rs="supabase.auth.token";var Os={"X-Client-Info":`gotrue-js/${jt}`},_r=10;var nt="X-Supabase-Api-Version",wr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ls(s){return Math.round(Date.now()/1e3)+s}function Is(){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 W=()=>typeof document<"u",de={tested:!1,writable:!1},oe=()=>{if(!W())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(de.tested)return de.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),de.tested=!0,de.writable=!0}catch{de.tested=!0,de.writable=!1}return de.writable};function $t(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 Ut=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ie(),ce)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},js=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",vr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},at=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Dt=async(s,e)=>{await s.removeItem(e)};function Yi(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,u,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),u=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var ot=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ot.promiseConstructor=Promise;function br(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(Yi(r))}async function $s(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Us(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 Qi(s){return("0"+s.toString(16)).substr(-2)}function Xi(){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,Qi).join("")}async function Zi(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 en(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function tn(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 Zi(s);return en(t)}async function fe(s,e,t=!1){let r=Xi(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await vr(s,`${e}-code-verifier`,i);let n=await tn(r);return[n,r===n?"plain":"s256"]}var rn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ds(s){let e=s.headers.get(nt);if(!e||!e.match(rn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ct=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function _(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var Mt=class extends ct{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Ms(s){return _(s)&&s.name==="AuthApiError"}var Le=class extends ct{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Z=class extends ct{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},K=class extends Z{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ie=class extends Z{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},pe=class extends Z{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},me=class extends Z{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}}},lt=class extends Z{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}}},je=class extends Z{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Nt(s){return _(s)&&s.name==="AuthRetryableFetchError"}var ut=class extends Z{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var sn=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},ge=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),nn=[502,503,504];async function Ns(s){var e;if(!js(s))throw new je(ge(s),0);if(nn.includes(s.status))throw new je(ge(s),s.status);let t;try{t=await s.json()}catch(n){throw new Le(ge(n),n)}let r,i=Ds(s);if(i&&i.getTime()>=wr["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new ut(ge(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 ut(ge(t),s.status,t.weak_password.reasons);throw new Mt(ge(t),s.status||500,r)}var on=(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 k(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[nt]||(n[nt]=wr["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():"",c=await an(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function an(s,e,t,r,i,n){let o=on(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new je(ge(c),0)}if(a.ok||await Ns(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await Ns(c)}}function ee(s){var e;let t=null;cn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ls(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function kr(s){let e=ee(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 Y(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function qs(s){return{data:s,error:null}}function Fs(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=sn(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},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Hs(s){return s}function cn(s){return s.access_token&&s.refresh_token&&s.expires_in}var ln=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},ye=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Ut(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await k(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await k(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Y})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=ln(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await k(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Fs,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await k(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Y})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await k(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:Hs});if(l.error)throw l.error;let h=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return m.length>0&&(m.forEach(v=>{let E=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(v.split(";")[1].split("=")[1]);u[`${y}Page`]=E}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(_(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await k(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Y})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await k(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Y})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Y})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await k(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(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await k(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var Ws={getItem:s=>oe()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{oe()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{oe()&&globalThis.localStorage.removeItem(s)}};function Sr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function Bs(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var _e={debug:!!(globalThis&&oe()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ht=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},qt=class extends ht{};async function Er(s,e,t){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),_e.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new qt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(_e.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Bs();var un={url:Ps,storageKey:Rs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Os,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},dt=30*1e3,zs=3;async function Js(s,e,t){return await t()}var we=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&&W()&&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({},un),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 ye({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Ut(i.fetch),this.lock=i.lock||Js,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:W()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Er:this.lock=Js,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:oe()?this.storage=Ws:(this.memoryStorage={},this.storage=Sr(this.memoryStorage)):(this.memoryStorage={},this.storage=Sr(this.memoryStorage)),W()&&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} (${jt}) ${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=W()?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)?{error:e}:{error:new Le("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await k(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:ee}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:l,password:h,options:d}=e,m=null,v=null;this.flowType==="pkce"&&([m,v]=await fe(this.storage,this.storageKey)),n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:h,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:m,code_challenge_method:v},xform:ee})}else if("phone"in e){let{phone:l,password:h,options:d}=e;n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:h,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:ee})}else throw new pe("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await k(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:kr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await k(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:kr})}else throw new pe("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Ie}:(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(_(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 at(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await k(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:ee});return await Dt(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 Ie}:(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 k(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:ee}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Ie}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await fe(this.storage,this.storageKey));let{error:h}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:l}}throw new pe("You must provide either an email or phone number.")}catch(a){if(_(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let 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 k(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:ee});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(_(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await fe(this.storage,this.storageKey)),await k(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:qs})}catch(n){if(_(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new K;let{error:i}=await k(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(_(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await k(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 k(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new pe("You must provide either an email or phone number and a type")}catch(t){if(_(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 at(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,u,l)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Y}):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 K}:await k(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:Y})})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new K;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await fe(this.storage,this.storageKey));let{data:u,error:l}=await k(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:Y});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return br(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new K;let t=Date.now()/1e3,r=t,i=!0,n=null,o=br(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new K;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!W())throw new me("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new me("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new lt("Not a valid PKCE flow url.");let t=$t(window.location.href);if(e){if(!t.code)throw new lt("No code detected.");let{data:p,error:A}=await this._exchangeCodeForSession(t.code);if(A)throw A;let R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:p.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new me(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:c,token_type:u}=t;if(!n||!a||!o||!u)throw new me("No session defined in URL");let l=Math.round(Date.now()/1e3),h=parseInt(a),d=l+h;c&&(d=parseInt(c));let m=d-l;m*1e3<=dt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${h}s`);let v=d-h;l-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,d,l):l-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",v,d,l);let{data:E,error:y}=await this._getUser(n);if(y)throw y;let T={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:u,user:E.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:T,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=$t(window.location.href);return!!(W()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=$t(window.location.href),t=await at(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&&!(Ms(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Dt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Is(),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 fe(this.storage,this.storageKey,!0));try{return await k(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(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,c,u,l;let{data:h,error:d}=n;if(d)throw d;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:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await k(this.fetch,"GET",m,{headers:this.headers,jwt:(l=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return W()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(_(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await k(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(_(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 Us(async i=>(i>0&&await $s(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await k(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ee})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Nt(n)&&Date.now()+o-r<dt})}catch(r){if(this._debug(t,"error",r),_(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),W()&&!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 at(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+_r;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${_r}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Nt(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 K;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ot;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new K;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),_(n)){let o={session:null,error:n};return Nt(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(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await vr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Dt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&W()&&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(),dt);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)/dt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${dt}ms, refresh threshold is ${zs} ticks`),i<=zs&&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 ht)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!W()||!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 fe(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 k(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(_(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:c}=await k(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await k(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(_(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 k(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(_(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 c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(h=>h.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};we.nextInstanceID=0;var hn=we,Tr=hn;var Ft=class extends Tr{constructor(e){super(e)}};var dn=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(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},ft=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=As(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:Ss,realtime:Ts,auth:Object.assign(Object.assign({},Es),{storageKey:c}),global:ks},l=Cs(r??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=xs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new cs(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Be(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new st(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 dn(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},c,u){var l;let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ft({url:this.authUrl,headers:Object.assign(Object.assign({},h),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new Ce(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 Gs=(s,e,t)=>new ft(s,e,t);var te={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var fn=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Ht=s=>{let[e,t]=s.split(".");return!e||!t?null:fn(t)},Vs=s=>{let e=Ht(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 pn="https://api.workos.com",mn=60,$e=(s,e)=>typeof s[e]=="string"?s[e]:void 0,Ks=(s,e,t)=>{let r=Ht(s);if(!r)return null;let i=$e(r,"urn:wispr:user_external_id")??$e(r,"sub"),n=t?.email??$e(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,c={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},gn=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):pn,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()},Ys=async(s,e)=>{let t=Ht(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=$e(t,"client_id");if(i-r<mn&&n){let c=await gn(e,n,$e(t,"iss"),$e(t,"org_id")),u=Ks(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=r)throw new Error("WorkOS session expired");let a=Ks(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var pt=class{constructor(){this.sessionData=null;this.supabase=Gs(te.supaBaseUrl,te.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||te.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||te.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||te.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(Vs(t)==="workos"){this.sessionData=await Ys(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||te.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 G.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:i||te.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 G.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(Fe(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 G.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||te.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 Q=null;function Wt(s,e=30,t){Q&&(clearInterval(Q),Q=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,Q=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",Q&&(clearInterval(Q),Q=null),t&&t())},1e3)}function xr(){Q&&(clearInterval(Q),Q=null)}var Qs=/^[\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":Qs.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 Bt(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Qs.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 Ar(s,e,t){let r="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let u=document.getElementById(r);u||(u=document.createElement("div"),u.id=r,u.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",u)),u.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let c=yn(e.value,s.value);c?i(c):n()},a=()=>{let c=Bt(e.value,s.value);c?i(c):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var zt=(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(()=>zt(s,e,t-1),200)};var _n="wisprjam.com",wn="wispr.ai";var vn=s=>s.trim().toLowerCase().split("@")[1]??"",Xs=s=>{let e=vn(s);return e===_n||e===wn};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=localStorage.getItem("checkout_debug");if(s){try{let f=JSON.parse(s);zt("checkout_debug",{...f,reported_from:"get_started",ms_since_error:Date.now()-(f.timestamp??Date.now())})}catch{}localStorage.removeItem("checkout_debug")}let e=!1,t=setTimeout(()=>{e||(document.body.style.visibility="visible")},4e3),r=new pt,i=null,n=()=>{i?.clear()},{accessToken:o,refreshToken:a}=Gr(),c=document.querySelector("#email-form"),u=document.querySelector("#email-input"),l=document.querySelector("#password-input"),h=document.querySelector("#full-name"),d=document.querySelector("#google-login"),m=document.querySelector("#apple-login"),v=document.querySelector("#microsoft-login"),E;(C=>(C.EMAIL_INPUT="email_input",C.LOGIN="login",C.SIGNUP="signup",C.OAUTH_USER="oauth_user",C.UNVERIFIED_EMAIL="unverified_email"))(E||(E={}));let y="email_input",T=document.querySelector("[email-element]"),p=document.querySelector("[different-provider]"),A=document.querySelector("[different-provider-name]"),R=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),w=document.querySelector("[email-signup-error]"),x=document.querySelector("[error-message]"),Ue=document.querySelector("[verification-email]"),De=document.querySelector("[email-signup-retry]"),Cr=document.querySelector("[email-signup-reset]"),ve=document.querySelector("[scim-div]"),Pr=document.querySelector("[scim-reset]"),q=document.querySelector("[forgot-password]"),mt=document.querySelector("[forgot-password-success]"),Rr=document.querySelector("[forgot-password-email]"),re=document.querySelector("[unverified-email]"),Or=document.querySelector("[unverified-email-address]"),B=document.querySelector("[resend-verification-email]"),Lr=document.querySelector("[unverified-email-reset]"),Zs=localStorage.getItem("email"),Ir=localStorage.getItem("last_authed_provider");Ir&&{google:d,apple:m,microsoft:v,sso:document.querySelector("#sso-login"),email:u}[Ir]?.classList.add("last-used");let be=new URLSearchParams(window.location.search),jr=be.get("referral"),$r=be.get("plan"),Ur=be.get("utm_source"),ei=be.get("redirect"),Dr=be.get("team_invite_code"),bn=be.get("code"),ti=ei==="android-waitlist"?"/android-waitlist":"/downloads",F=`${window.location.origin}${ti}`,ke=new URLSearchParams;jr&&ke.append("referral",jr),$r&&ke.append("plan",$r),Ur&&ke.append("utm_source",Ur),Dr&&ke.append("team_invite_code",Dr),ke.toString()&&(F+=`?${ke.toString()}`);let ri=()=>{try{let f=document.cookie.split("; ");for(let g of f){let S=g.indexOf("=");if(S===-1||g.slice(0,S)!=="wispr_auth")continue;let L=g.slice(S+1),C=decodeURIComponent(L);return JSON.parse(C)}return null}catch{return null}};if(o&&a)try{r.setCookies(o,a);let f=r.checkAndSetSession(),g=new Promise((b,L)=>setTimeout(()=>L(new Error("Session timeout")),3e3));await Promise.race([f,g]),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token);let S=r.sessionData?.user.email;localStorage.setItem("email",S),e=!0,clearTimeout(t),window.location.href=F}catch(f){console.error("Error during session setup:",f),document.body.style.visibility="visible"}else{let f=ri();if(f?.access_token&&f?.refresh_token)try{r.setCookies(f.access_token,f.refresh_token);let g=r.checkAndSetSession(),S=new Promise((C,U)=>setTimeout(()=>U(new Error("Session timeout")),3e3));await Promise.race([g,S]),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token);let b=r.sessionData?.user.email,L=r.sessionData?.user.app_metadata.provider||"typing_test";localStorage.setItem("email",b),localStorage.setItem("signin_provider",L),e=!0,clearTimeout(t),window.location.href=F}catch(g){console.error("Error authenticating from typing test session:",g),f.email&&(u.value=f.email),document.body.style.visibility="visible"}else f?.email?(u.value=f.email,document.body.style.visibility="visible"):(Zs&&localStorage.removeItem("email"),document.body.style.visibility="visible")}d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await r.signInWithGoogle(F)}catch(f){console.error("Error during sign-in:",f)}}),m.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await r.signInWithApple(F)}catch(f){console.error("Error during sign-in:",f)}}),v.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await r.signInWithMicrosoft(F)}catch(f){console.error("Error during sign-in:",f)}});let Me=()=>{n(),p&&(p.style.display="none"),O&&(O.style.display="none"),w&&(w.style.display="none"),re&&(re.style.display="none"),ve&&(ve.style.display="none"),q&&(q.style.display="none"),mt&&(mt.style.display="none"),ae();let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="block"),T&&(T.style.display="flex"),u.value="",u.removeAttribute("readonly"),u.classList.remove("disabled"),l.value="",l.style.display="none",l.removeAttribute("required"),h.value="",h.style.display="none",h.removeAttribute("required");let g=document.querySelector("[captcha-embed]"),S=document.querySelector("#h-captcha-container");g&&(g.style.display="none"),S&&(S.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),y="email_input",u.focus()},gt=()=>{T&&(T.style.display="flex"),u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),l.focus(),h.style.display="none",h.removeAttribute("required");let f=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),g&&(g.style.display="block"),q&&(q.style.display="block",q.onclick=async()=>{let S=u.value,b=q.textContent||"";try{let{hcaptcha:L}=window;if(!L)throw new Error("Verification system not loaded. Please refresh the page.");q.style.pointerEvents="none",q.textContent="Sending...";let{response:C}=await L.execute({async:!0});if(!C)throw new Error("Verification cancelled");await G.requestPasswordReset(S,C),L.reset(),T&&(T.style.display="none"),q&&(q.style.display="none"),mt&&(mt.style.display="block"),Rr&&(Rr.textContent=S)}catch(L){console.error("\u274C Error sending password reset email:",L),q.textContent=b,q.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),w&&(w.style.display="block",x&&(x.textContent=L instanceof Error?L.message:"Failed to send reset email"))}}),y="login",console.log("\u2705 Existing user detected - showing login form")},Mr=()=>{u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),h.style.display="block",h.setAttribute("required","true"),l.focus();let f=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),g&&(g.style.display="block"),y="signup",console.log("\u2705 New user detected - showing signup form")},Nr=()=>{let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="none"),ve&&(ve.style.display="block"),Pr&&(Pr.onclick=()=>{ve&&(ve.style.display="none"),f&&(f.style.display="block"),Me()})},Jt=f=>{n();let g=Kt(f);T&&(T.style.display="none"),p&&(p.style.display="block"),A&&(A.textContent=g),R&&(R.onclick=()=>{p&&(p.style.display="none"),Me()}),y="oauth_user"};i=Qt({client:r,redirectUrl:F,isWorkosCapable:()=>!0,beforeShow:()=>{T&&(T.style.display="none"),re&&(re.style.display="none")},onAuthenticated:async f=>{n(),r.setCookies(f.access_token,f.refresh_token),localStorage.setItem("email",f.email),localStorage.setItem("user_id",f.user_id),localStorage.setItem("signin_provider","email"),e=!0,clearTimeout(t),window.location.href=F},onMissingChallenge:gt,onReset:Me});let si=f=>{T&&(T.style.display="none"),re&&(re.style.display="block"),Or&&(Or.textContent=f),B&&(B.onclick=async()=>{let g=B.textContent||"";try{B.textContent="Verifying...",B.style.pointerEvents="none";let S=await He();B.textContent="Sending...",await r.resendVerificationEmail(f,F,S),B.textContent="Verification email resent! \u2705",B.style.textDecoration="none",w&&(w.style.display="none")}catch(S){B.textContent=g,B.style.pointerEvents="auto",w&&(w.style.display="block"),x&&(x.textContent=Ee(S,"Unable to resend verification."))}finally{se()?.reset()}}),Lr&&(Lr.onclick=()=>{re&&(re.style.display="none"),Me()}),y="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},Gt=f=>Yt(f,{showSso:()=>Jt("workos"),showScim:Nr,showLogin:gt,showError:g=>{w&&(w.style.display="block"),x&&(x.textContent=g)}}),ii=async(f,g)=>{let S=g.value;g.classList.add("loading"),g.value="";try{let b=await G.checkUserStatus(f);console.log("User status check:",b),g.classList.remove("loading"),g.value=S,!b.exists&&b.scim_managed?Nr():b.enforce_sso?Jt("workos"):b.exists&&b.provider&&b.provider!=="email"&&b.provider!=="workos"?Jt(b.provider):b.exists&&b.provider==="workos"?gt():b.exists&&b.provider==="email"&&!b.verified?si(f):b.exists&&b.provider==="email"?gt():Mr()}catch(b){console.error("\u274C Error checking user status:",b),g.classList.remove("loading"),g.value=S,Gt(b)||Mr()}},ni=async(f,g,S,b)=>{if(!g||g.length<8){w&&(w.style.display="block",x&&(x.textContent="Password must be at least 8 characters"));return}let L=window.hcaptcha?.getResponse()||"";if(!L){w&&(w.style.display="block",x&&(x.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{let C=Xs(f),U=await r.signInWithPassword(f,g,L,{workosCapable:C,provision:!1});if(U.kind==="otp"){if(!C)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let z={pendingAuthenticationToken:U.challenge.pending_authentication_token,email:M(U.challenge.email||f)};se()?.reset(),S.classList.remove("loading"),S.value=b,i?.show(z);return}r.setCookies(U.accessToken,U.refreshToken),localStorage.setItem("email",f),e=!0,clearTimeout(t),window.location.href=F}catch(C){window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=b,!Gt(C)&&w&&(w.style.display="block",x&&(x.textContent=Ee(C,"Unable to sign in. Please try again.")))}},oi=async(f,g,S,b,L)=>{if(!g||g.length<8){w&&(w.style.display="block",x&&(x.textContent="Password must be at least 8 characters"));return}if(!S||S.trim().length<2){w&&(w.style.display="block",x&&(x.textContent="Please enter your full name"));return}let C=Bt(S,g);if(C){w&&(w.style.display="block",x&&(x.textContent=C));return}let U=window.hcaptcha?.getResponse()||"";if(!U){w&&(w.style.display="block",x&&(x.textContent="Please complete the verification"));return}b.classList.add("loading"),b.value="";try{let z=await r.signUpWithPassword(f,g,S,F,U,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),b.classList.remove("loading"),b.value=L,T&&(T.style.display="none"),w&&(w.style.display="none"),Fe(z)){let Ne={pendingAuthenticationToken:z.pending_authentication_token,email:M(z.email||f)};i?.show(Ne);return}O&&(O.style.display="block"),Ue&&(Ue.textContent=f),De&&(Wt(De,30),De.onclick=async()=>{if(De.style.pointerEvents!=="none")try{let Ne=await He();await r.resendVerificationEmail(f,F,Ne,{workosCapable:!0}),Wt(De,30)}catch(Ne){w&&(w.style.display="block"),x&&(x.textContent=Ee(Ne,"Unable to resend verification. Please try again."))}finally{se()?.reset()}}),Cr&&(Cr.onclick=()=>{O&&(O.style.display="none"),xr(),Me()})}catch(z){b.classList.remove("loading"),b.value=L,se()?.reset(),!Gt(z)&&w&&(w.style.display="block",x&&(x.textContent=Ee(z,"Unable to create the account. Please try again.")))}};Ar(l,h,c.querySelector('[type="submit"]')),c.addEventListener("submit",async f=>{f.stopPropagation(),f.preventDefault();let g=M(u.value);u.value=g;let S=l?.value||"",b=h?.value||"";if(!g||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g)){console.error("\u274C Email invalid"),w&&(w.style.display="block",x&&(x.textContent="Please enter a valid email address"));return}w&&(w.style.display="none"),x&&(x.textContent="");let C=c.querySelector('[type="submit"]'),U=C?.value||"";localStorage.setItem("signin_provider","email");try{y==="email_input"?await ii(g,C):y==="login"?await ni(g,S,C,U):y==="signup"&&await oi(g,S,b,C,U)}catch(z){console.error("\u274C Signup error:",z),C&&(C.classList.remove("loading"),C.value=U),w&&(w.style.display="block")}})});})();