@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/androidWaitlist.js +1 -1
- package/dist/login.js +1 -1
- package/dist/signup.js +1 -1
- package/package.json +1 -1
package/dist/login.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var Zr=Object.create;var St=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ti=Object.getOwnPropertyNames;var si=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var ii=(r,e)=>()=>(r&&(e=r(r=0)),e);var Q=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ni=(r,e)=>{for(var t in e)St(r,t,{get:e[t],enumerable:!0})},Is=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ti(e))!ri.call(r,i)&&i!==t&&St(r,i,{get:()=>e[i],enumerable:!(s=ei(e,i))||s.enumerable});return r};var Ls=(r,e,t)=>(t=r!=null?Zr(si(r)):{},Is(e||!r||!r.__esModule?St(t,"default",{value:r,enumerable:!0}):t,r)),oi=r=>Is(St({},"__esModule",{value:!0}),r);var pe={};ni(pe,{Headers:()=>ts,Request:()=>di,Response:()=>hi,default:()=>es,fetch:()=>ui});var li,Oe,ui,es,ts,di,hi,de=ii(()=>{"use strict";li=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")},Oe=li(),ui=Oe.fetch,es=Oe.fetch.bind(Oe),ts=Oe.Headers,di=Oe.Request,hi=Oe.Response});var Ns=Q(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var ss=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};rs.default=ss});var ns=Q(Ze=>{"use strict";var Ms=Ze&&Ze.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ze,"__esModule",{value:!0});var pi=Ms((de(),oi(pe))),gi=Ms(Ns()),is=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=pi.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let l=null,u=null,d=null,f=n.status,g=n.statusText;if(n.ok){if(this.method!=="HEAD"){let R=await n.text();R===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=R:u=JSON.parse(R))}let T=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),v=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");T&&v&&v.length>1&&(d=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(l={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,d=null,f=406,g="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{let T=await n.text();try{l=JSON.parse(T),Array.isArray(l)&&n.status===404&&(u=[],l=null,f=200,g="OK")}catch{n.status===404&&T===""?(f=204,g="No Content"):l={message:T}}if(l&&this.isMaybeSingle&&(!((c=l?.details)===null||c===void 0)&&c.includes("0 rows"))&&(l=null,f=200,g="OK"),l&&this.shouldThrowOnError)throw new gi.default(l)}return{error:l,data:u,count:d,status:f,statusText:g}});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=is});var as=Q(et=>{"use strict";var mi=et&&et.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(et,"__esModule",{value:!0});var _i=mi(ns()),os=class extends _i.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable: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"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){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:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${l}"; 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}};et.default=os});var Rt=Q(tt=>{"use strict";var yi=tt&&tt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tt,"__esModule",{value:!0});var wi=yi(as()),cs=class extends wi.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};tt.default=cs});var us=Q(rt=>{"use strict";var vi=rt&&rt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rt,"__esModule",{value:!0});var st=vi(Rt()),ls=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){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),s&&(this.headers.Prefer=`count=${s}`),new st.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new st.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",l.join(","))}}return new st.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new st.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new st.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};rt.default=ls});var qs=Q(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.version=void 0;Pt.version="0.0.0-automated"});var Fs=Q(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.DEFAULT_HEADERS=void 0;var bi=qs();Ot.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${bi.version}`}});var Ws=Q(it=>{"use strict";var Hs=it&&it.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(it,"__esModule",{value:!0});var ki=Hs(us()),Si=Hs(Rt()),Ei=Fs(),ds=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},Ei.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ki.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([u,d])=>d!==void 0).map(([u,d])=>[u,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([u,d])=>{a.searchParams.append(u,d)})):(o="POST",c=t);let l=Object.assign({},this.headers);return n&&(l.Prefer=`count=${n}`),new Si.default({method:o,url:a,headers:l,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};it.default=ds});var Ks=Q(M=>{"use strict";var nt=M&&M.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(M,"__esModule",{value:!0});M.PostgrestBuilder=M.PostgrestTransformBuilder=M.PostgrestFilterBuilder=M.PostgrestQueryBuilder=M.PostgrestClient=void 0;var Bs=nt(Ws());M.PostgrestClient=Bs.default;var zs=nt(us());M.PostgrestQueryBuilder=zs.default;var Gs=nt(Rt());M.PostgrestFilterBuilder=Gs.default;var Js=nt(as());M.PostgrestTransformBuilder=Js.default;var Vs=nt(ns());M.PostgrestBuilder=Vs.default;M.default={PostgrestClient:Bs.default,PostgrestQueryBuilder:zs.default,PostgrestFilterBuilder:Gs.default,PostgrestTransformBuilder:Js.default,PostgrestBuilder:Vs.default}});var ir=Q((so,rr)=>{"use strict";rr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Et=r=>r.verification_method==="email_otp"&&typeof r.pending_authentication_token=="string"&&r.pending_authentication_token.length>0,$="https://api.wisprflow.ai",oe=class extends Error{constructor(t,s,i){super(i);this.status=t;this.code=s;this.name="AriaAuthError"}},G=r=>r.trim().toLowerCase(),js=(r,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 r.code=="string"?r.code:r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:typeof r.detail=="string"&&t.has(r.detail)?r.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},Ye=(r,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."})[r]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),ai=(r,e,t)=>[r.message,r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"?r.detail.message:null,typeof r.detail=="string"?r.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??Ye(e,t),Pe=(r,e)=>{let t=js(r,e);return new oe(e,t,ai(r,t,e))},ci=(r,e)=>{let t=js(r,e);return new oe(e,t,Ye(t,e))},Zt=class{static async signupUser(e){try{let t=`${$}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${$}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${$}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${$}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch(`${$}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){let t=G(e),s=await fetch(`${$}/user_status?email=${encodeURIComponent(t)}`),i=await s.json().catch(()=>({}));if(!s.ok)throw Pe(i,s.status);return i}static async requestPasswordReset(e,t){let s=await fetch(`${$}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:G(e),captcha_token:t})});if(!s.ok){let i=await s.json().catch(()=>({}));throw Pe(i,s.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${$}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:G(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async signInWithCaptcha(e){let t=await fetch(`${$}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:G(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${$}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:G(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new oe(422,"invalid_code",Ye("invalid_code",422));let t=await fetch(`${$}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok){let i=ci(s,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new oe(t.status,"verification_failed",Ye("verification_failed",t.status))}if(s.provider!=="workos"||!s.access_token||!s.refresh_token||!s.user_id||!s.email)throw new oe(t.status,"authentication_failed",Ye("authentication_failed",t.status));return s}static async signInWithEmail(e){let t=await fetch(`${$}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:G(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async getSubscriptionStatus(e){return await fetch(`${$}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${$}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let i=`${$}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(i+=`¤cy=${s}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${$}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch(`${$}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${$}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${$}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let i=new FormData;return i.append("screenshot",e),await fetch(`${$}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function $s(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function Us(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var J=Zt;var Ds=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(de(),pe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Xe=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Tt=class extends Xe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},At=class extends Xe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},xt=class extends Xe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ct;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(Ct||(Ct={}));var fi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Qe=class{constructor(e,{headers:t={},customFetch:s,region:i=Ct.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Ds(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return fi(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 l;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",l=o):typeof o=="string"?(a["Content-Type"]="text/plain",l=o):typeof FormData<"u"&&o instanceof FormData?l=o:(a["Content-Type"]="application/json",l=JSON.stringify(o)));let u=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:l}).catch(y=>{throw new Tt(y)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new At(u);if(!u.ok)throw new xt(u);let f=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield u.json():f==="application/octet-stream"?g=yield u.blob():f==="text/event-stream"?g=u:f==="multipart/form-data"?g=yield u.formData():g=yield u.text(),{data:g,error:null}}catch(i){return{data:null,error:i}}})}};var Ys=Ls(Ks(),1),{PostgrestClient:Xs,PostgrestQueryBuilder:Dn,PostgrestFilterBuilder:Nn,PostgrestTransformBuilder:Mn,PostgrestBuilder:qn}=Ys.default;var Qs="2.10.2";var Zs={"X-Client-Info":`realtime-js/${Qs}`},er="1.0.0",Lt=1e4,tr=1e3,ge;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(ge||(ge={}));var F;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(F||(F={}));var W;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(W||(W={}));var It;(function(r){r.websocket="websocket"})(It||(It={}));var he;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(he||(he={}));var ot=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let l=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:l}}};var me=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 L;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(L||(L={}));var fs=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ti(o,r,e,i),n),{})},Ti=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?sr(n,o):hs(o)},sr=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Ri(e,t)}switch(r){case L.bool:return Ai(e);case L.float4:case L.float8:case L.int2:case L.int4:case L.int8:case L.numeric:case L.oid:return xi(e);case L.json:case L.jsonb:return Ci(e);case L.timestamp:return Pi(e);case L.abstime:case L.date:case L.daterange:case L.int4range:case L.int8range:case L.money:case L.reltime:case L.text:case L.time:case L.timestamptz:case L.timetz:case L.tsrange:case L.tstzrange:return hs(e);default:return hs(e)}},hs=r=>r,Ai=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},xi=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Ci=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Ri=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n,o=r.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>sr(e,a))}return r},Pi=r=>typeof r=="string"?r.replace(" ","T"):r,jt=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var _e=class{constructor(e,t,s={},i=Lt){this.channel=e,this.event=t,this.payload=s,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 s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var ps;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(ps||(ps={}));var Ie=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.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,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(l,u)=>{o[l]||(c[l]=u)}),this.map(o,(l,u)=>{let d=n[l];if(d){let f=u.map(v=>v.presence_ref),g=d.map(v=>v.presence_ref),y=u.filter(v=>g.indexOf(v.presence_ref)<0),T=d.filter(v=>f.indexOf(v.presence_ref)<0);y.length>0&&(a[l]=y),T.length>0&&(c[l]=T)}else a[l]=u}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var l;let u=(l=e[a])!==null&&l!==void 0?l:[];if(e[a]=this.cloneDeep(c),u.length>0){let d=e[a].map(g=>g.presence_ref),f=u.filter(g=>d.indexOf(g.presence_ref)<0);e[a].unshift(...f)}s(a,u,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.map(d=>d.presence_ref);l=l.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=l,i(a,l,c),l.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=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 gs;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(gs||(gs={}));var ms;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(ms||(ms={}));var _s;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(_s||(_s={}));var Le=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=F.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 _e(this,W.join,this.params,this.timeout),this.rejoinTimer=new me(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=F.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=F.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this._on(W.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Ie(this),this.broadcastEndpointURL=jt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,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(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("CLOSED"));let c={},l={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(u=>u.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:u})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,g=(d=f?.length)!==null&&d!==void 0?d:0,y=[];for(let T=0;T<g;T++){let v=f[T],{filter:{event:R,schema:h,table:m,filter:P}}=v,O=u&&u[T];if(O&&O.event===R&&O.schema===h&&O.table===m&&O.filter===P)y.push(Object.assign(Object.assign({},v),{id:O.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,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,(s=t.timeout)!==null&&s!==void 0?s: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 l=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"),l.receive("ok",()=>n("ok")),l.receive("error",()=>n("error")),l.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=F.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(W.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new _e(this,W.leave,{},e);i.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let i=new AbortController,n=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new _e(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:l,join:u}=W;if(s&&[a,c,l,u].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,t,s);if(t&&!f)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(g=>{var y,T,v;return((y=g.filter)===null||y===void 0?void 0:y.event)==="*"||((v=(T=g.filter)===null||T===void 0?void 0:T.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===o}).map(g=>g.callback(f,s)):(n=this.bindings[o])===null||n===void 0||n.filter(g=>{var y,T,v,R,h,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){let P=g.id,O=(y=g.filter)===null||y===void 0?void 0:y.event;return P&&((T=t.ids)===null||T===void 0?void 0:T.includes(P))&&(O==="*"||O?.toLocaleLowerCase()===((v=t.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{let P=(h=(R=g?.filter)===null||R===void 0?void 0:R.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return P==="*"||P===((m=t?.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof f=="object"&&"ids"in f){let y=f.data,{schema:T,table:v,commit_timestamp:R,type:h,errors:m}=y;f=Object.assign(Object.assign({},{schema:T,table:v,commit_timestamp:R,eventType:h,new:{},old:{},errors:m}),this._getPayloadRecords(y))}g.callback(f,s)})}_isClosed(){return this.state===F.closed}_isJoined(){return this.state===F.joined}_isJoining(){return this.state===F.joining}_isLeaving(){return this.state===F.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(W.close,{},e)}_onError(e){this._on(W.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=F.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=fs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=fs(e.columns,e.old_record)),t}};var Ii=()=>{},Li=typeof WebSocket<"u",je=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Zs,this.params={},this.timeout=Lt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Ii,this.conn=null,this.sendBuffer=[],this.serializer=new ot,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(de(),pe)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${It.websocket}`,this.httpEndpoint=jt(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=(s=t?.params)===null||s===void 0?void 0:s.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 me(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(Li){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new ys(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ls(ir())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case ge.connecting:return he.Connecting;case ge.open:return he.Open;case ge.closing:return he.Closing;default:return he.Closed}}isConnected(){return this.connectionState()===he.Open}channel(e,t={config:{}}){let s=new Le(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,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} ${s} (${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(W.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:er}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).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(W.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${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(tr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},ys=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ge.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var $e=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function D(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var $t=class extends $e{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},at=class extends $e{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var ji=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Ut=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(de(),pe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},nr=()=>ji(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(de(),pe))).Response:Response});var Ue=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ws=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),$i=(r,e)=>Ue(void 0,void 0,void 0,function*(){let t=yield nr();r instanceof t?r.json().then(s=>{e(new $t(ws(s),r.status||500))}).catch(s=>{e(new at(ws(s),s))}):e(new at(ws(r),r))}),Ui=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};function Dt(r,e,t,s,i,n){return Ue(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,Ui(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>$i(c,a))})})}function ct(r,e,t,s){return Ue(this,void 0,void 0,function*(){return Dt(r,"GET",e,t,s)})}function Z(r,e,t,s,i){return Ue(this,void 0,void 0,function*(){return Dt(r,"POST",e,s,i,t)})}function or(r,e,t,s,i){return Ue(this,void 0,void 0,function*(){return Dt(r,"PUT",e,s,i,t)})}function Nt(r,e,t,s,i){return Ue(this,void 0,void 0,function*(){return Dt(r,"DELETE",e,s,i,t)})}var V=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Di={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ar={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},lt=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Ut(i)}uploadOrUpdate(e,t,s,i){return V(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},ar),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(D(n))return{data:null,error:n};throw n}})}upload(e,t,s){return V(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return V(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,l=Object.assign({upsert:ar.upsert},i),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",l.cacheControl)):(c=s,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:u}),f=yield d.json();return d.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(D(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return V(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield Z(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new $e("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(D(s))return{data:null,error:s};throw s}})}update(e,t,s){return V(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return V(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}copy(e,t,s){return V(this,void 0,void 0,function*(){try{return{data:{path:(yield Z(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return V(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield Z(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return V(this,void 0,void 0,function*(){try{let i=yield Z(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}download(e,t){return V(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 ct(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(D(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=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 l=i.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${l}`)}}}remove(e){return V(this,void 0,void 0,function*(){try{return{data:yield Nt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}list(e,t,s){return V(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Di),t),{prefix:e||""});return{data:yield Z(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(D(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 cr="2.6.0";var lr={"X-Client-Info":`storage-js/${cr}`};var De=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ut=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},lr),t),this.fetch=Ut(s)}listBuckets(){return De(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(D(e))return{data:null,error:e};throw e}})}getBucket(e){return De(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return De(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(D(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return De(this,void 0,void 0,function*(){try{return{data:yield or(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(D(s))return{data:null,error:s};throw s}})}emptyBucket(e){return De(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}deleteBucket(e){return De(this,void 0,void 0,function*(){try{return{data:yield Nt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}};var dt=class extends ut{constructor(e,t={},s){super(e,t,s)}from(e){return new lt(this.url,this.headers,e,this.fetch)}};var ur="2.44.4";var ht="";typeof Deno<"u"?ht="deno":typeof document<"u"?ht="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ht="react-native":ht="node";var Ni={"X-Client-Info":`supabase-js-${ht}/${ur}`},dr={headers:Ni},hr={schema:"public"},fr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},pr={};de();var Mi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},qi=r=>{let e;return r?e=r:typeof fetch>"u"?e=es:e=fetch,(...t)=>e(...t)},Fi=()=>typeof Headers>"u"?ts:Headers,gr=(r,e,t)=>{let s=qi(t),i=Fi();return(n,o)=>Mi(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,l=new i(o?.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:l}))})};function mr(r){return r.replace(/\/$/,"")}function _r(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:l}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},l),n)}}var Mt="2.64.4";var yr="http://localhost:9999",wr="supabase.auth.token";var vr={"X-Client-Info":`gotrue-js/${Mt}`},vs=10;var ft="X-Supabase-Api-Version",bs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function br(r){return Math.round(Date.now()/1e3)+r}function kr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var K=()=>typeof document<"u",ye={tested:!1,writable:!1},fe=()=>{if(!K())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ye.tested)return ye.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),ye.tested=!0,ye.writable=!0}catch{ye.tested=!0,ye.writable=!1}return ye.writable};function qt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var Ft=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(de(),pe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Sr=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",ks=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},gt=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Ht=async(r,e)=>{await r.removeItem(e)};function Hi(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,l,u=0;for(r=r.replace("-","+").replace("_","/");u<r.length;)o=e.indexOf(r.charAt(u++)),a=e.indexOf(r.charAt(u++)),c=e.indexOf(r.charAt(u++)),l=e.indexOf(r.charAt(u++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|l,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),l!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var pt=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};pt.promiseConstructor=Promise;function Ss(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(Hi(s))}async function Er(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Tr(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await r(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Wi(r){return("0"+r.toString(16)).substr(-2)}function Bi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,Wi).join("")}async function zi(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Gi(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ji(r){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."),r;let t=await zi(r);return Gi(t)}async function we(r,e,t=!1){let s=Bi(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await ks(r,`${e}-code-verifier`,i);let n=await Ji(s);return[n,s===n?"plain":"s256"]}var Vi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ar(r){let e=r.headers.get(ft);if(!e||!e.match(Vi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var mt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function S(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Wt=class extends mt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function xr(r){return S(r)&&r.name==="AuthApiError"}var Ne=class extends mt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ae=class extends mt{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},ee=class extends ae{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Me=class extends ae{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ve=class extends ae{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},be=class extends ae{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}}},_t=class extends ae{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}}},qe=class extends ae{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Bt(r){return S(r)&&r.name==="AuthRetryableFetchError"}var yt=class extends ae{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Ki=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},ke=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Yi=[502,503,504];async function Cr(r){var e;if(!Sr(r))throw new qe(ke(r),0);if(Yi.includes(r.status))throw new qe(ke(r),r.status);let t;try{t=await r.json()}catch(n){throw new Ne(ke(n),n)}let s,i=Ar(r);if(i&&i.getTime()>=bs["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new yt(ke(t),r.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 yt(ke(t),r.status,t.weak_password.reasons);throw new Wt(ke(t),r.status||500,s)}var Xi=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function E(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[ft]||(n[ft]=bs["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Qi(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Qi(r,e,t,s,i,n){let o=Xi(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new qe(ke(c),0)}if(a.ok||await Cr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await Cr(c)}}function ce(r){var e;let t=null;Zi(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=br(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Es(r){let e=ce(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function te(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Rr(r){return{data:r,error:null}}function Pr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Ki(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Or(r){return r}function Zi(r){return r.access_token&&r.refresh_token&&r.expires_in}var en=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},Se=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Ft(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(S(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:te})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=en(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Pr,redirectTo:t?.redirectTo})}catch(t){if(S(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:te})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Or});if(u.error)throw u.error;let d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return g.length>0&&(g.forEach(y=>{let T=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(y.split(";")[1].split("=")[1]);l[`${v}Page`]=T}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(S(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:te})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:te})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:te})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(S(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}}};var Ir={getItem:r=>fe()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{fe()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{fe()&&globalThis.localStorage.removeItem(r)}};function Ts(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Lr(){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 Ee={debug:!!(globalThis&&fe()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},wt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},zt=class extends wt{};async function As(r,e,t){Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new zt(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Ee.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()}})}Lr();var tn={url:yr,storageKey:wr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:vr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},vt=30*1e3,jr=3;async function $r(r,e,t){return await t()}var Te=class r{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&K()&&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({},tn),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 Se({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Ft(i.fetch),this.lock=i.lock||$r,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:K()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=As:this.lock=$r,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:fe()?this.storage=Ir:(this.memoryStorage={},this.storage=Ts(this.memoryStorage)):(this.memoryStorage={},this.storage=Ts(this.memoryStorage)),K()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Mt}) ${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=K()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session: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 S(e)?{error:e}:{error:new Ne("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:ce}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(n){if(S(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:u,password:d,options:f}=e,g=null,y=null;this.flowType==="pkce"&&([g,y]=await we(this.storage,this.storageKey)),n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:g,code_challenge_method:y},xform:ce})}else if("phone"in e){let{phone:u,password:d,options:f}=e;n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(i=f?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ce})}else throw new ve("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,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(n){if(S(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Es})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Es})}else throw new ve("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Me}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(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 gt(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ce});return await Ht(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 Me}:(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:s,token:i,access_token:n,nonce:o}=e,a=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ce}),{data:c,error:l}=a;return l?{data:{user:null,session:null},error:l}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Me}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:l})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await we(this.storage,this.storageKey));let{error:d}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await E(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:l?.message_id},error:u}}throw new ve("You must provide either an email or phone number.")}catch(a){if(S(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:ce});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(S(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await we(this.storage,this.storageKey)),await E(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s: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:Rr})}catch(n){if(S(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new ee;let{error:i}=await E(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(S(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await E(this.fetch,"POST",t,{headers:this.headers,body:{email:s,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:s,type:i,options:n}=e,{data:o,error:a}=await E(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new ve("You must provide either an email or phone number and a type")}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,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 s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await gt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,l,u)=>(!o&&l==="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,l,u))})}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 E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:te}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ee}:await E(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:te})})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new ee;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await we(this.storage,this.storageKey));let{data:l,error:u}=await E(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:te});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Ss(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 ee;let t=Date.now()/1e3,s=t,i=!0,n=null,o=Ss(e.access_token);if(o.exp&&(s=o.exp,i=s<=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:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(S(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new ee;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(S(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!K())throw new be("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new be("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new _t("Not a valid PKCE flow url.");let t=qt(window.location.href);if(e){if(!t.code)throw new _t("No code detected.");let{data:h,error:m}=await this._exchangeCodeForSession(t.code);if(m)throw m;let P=new URL(window.location.href);return P.searchParams.delete("code"),window.history.replaceState(window.history.state,"",P.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new be(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:l}=t;if(!n||!a||!o||!l)throw new be("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;c&&(f=parseInt(c));let g=f-u;g*1e3<=vt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${d}s`);let y=f-d;u-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,f,u):u-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,f,u);let{data:T,error:v}=await this._getUser(n);if(v)throw v;let R={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:o,token_type:l,user:T.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:R,redirectType:t.type},error:null}}catch(t){if(S(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=qt(window.location.href);return!!(K()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=qt(window.location.href),t=await gt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{error:n};let o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(xr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Ht(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=kr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((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 s=null,i=null;this.flowType==="pkce"&&([s,i]=await we(this.storage,this.storageKey,!0));try{return await E(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(S(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,l,u;let{data:d,error:f}=n;if(f)throw f;let g=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await E(this.fetch,"GET",g,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return K()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(S(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Tr(async i=>(i>0&&await Er(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ce})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Bt(n)&&Date.now()+o-s<vt})}catch(s){if(this._debug(t,"error",s),S(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),K()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await gt(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<i+vs;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${vs}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Bt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new ee;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new pt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new ee;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),S(n)){let o={session:null,error:n};return Bt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await ks(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Ht(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&K()&&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(),vt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((s.expires_at*1e3-e)/vt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${vt}ms, refresh threshold is ${jr} ticks`),i<=jr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof wt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!K()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await we(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await E(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((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(S(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(S(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(S(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;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;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let u=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}};Te.nextInstanceID=0;var sn=Te,xs=sn;var Gt=class extends xs{constructor(e){super(e)}};var rn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},bt=class{constructor(e,t,s){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=mr(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`,l={db:hr,realtime:pr,auth:Object.assign(Object.assign({},fr),{storageKey:c}),global:dr},u=_r(s??{},l);this.storageKey=(i=u.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=u.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=gr(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},u.realtime)),this.rest=new Xs(`${a}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Qe(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new dt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return rn(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,storageKey:n,flowType:o,debug:a},c,l){var u;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Gt({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:l,hasCustomAuthorizationHeader:(u="Authorization"in this.headers)!==null&&u!==void 0?u:!1})}_initRealtimeClient(e){return new je(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Ur=(r,e,t)=>new bt(r,e,t);var le={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var nn=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Jt=r=>{let[e,t]=r.split(".");return!e||!t?null:nn(t)},Fe=r=>{let e=Jt(r);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 on="https://api.workos.com",an=60,He=(r,e)=>typeof r[e]=="string"?r[e]:void 0,Dr=(r,e,t)=>{let s=Jt(r);if(!s)return null;let i=He(s,"urn:wispr:user_external_id")??He(s,"sub"),n=t?.email??He(s,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof s.exp=="number"?s.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:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},cn=async(r,e,t,s)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):on,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:r,organization_id:s})});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()},Nr=async(r,e)=>{let t=Jt(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=He(t,"client_id");if(i-s<an&&n){let c=await cn(e,n,He(t,"iss"),He(t,"org_id")),l=Dr(c.access_token,c.refresh_token,c.user);if(!l)throw new Error("WorkOS refresh returned an invalid access token");return l}if(i<=s)throw new Error("WorkOS session expired");let a=Dr(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var We=class{constructor(){this.sessionData=null;this.supabase=Ur(le.supaBaseUrl,le.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||le.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||le.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||le.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let i=new Date;i.setTime(i.getTime()+s*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,s=e.refresh_token;if(t&&s)try{if(Fe(t)==="workos"){this.sessionData=await Nr(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,i]=t.split("=");return e[s]=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:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||le.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=await J.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:n,redirect_url:i||le.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,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await J.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(Et(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,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await J.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||le.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 Vt=null;function Ae(){return new URLSearchParams(window.location.search).get("dev-mode")==="true"}var Mr=(r,e)=>{if(!(r instanceof Error)||r.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:s}=r;return s&&t[s]||e},Kt=()=>{Vt!==null&&(window.clearInterval(Vt),Vt=null)};function Be(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),Kt()}function qr(r){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]")),s=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]"),l=document.querySelector("[otp-resend-seconds]"),u=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),n&&(n.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),Kt(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let d=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},f=()=>{n&&(n.style.display="none")},g=!1,y=!1,T=h=>{i&&(i.style.pointerEvents=h?"none":"",h?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},v=async()=>{if(g)return;let h=t.map(m=>m.value).join("");if(h.length!==6){d("Please enter all 6 digits.");return}g=!0,T(!0),t.forEach(m=>m.setAttribute("disabled","true")),f();try{await r.onVerify(h),f(),i&&(i.textContent="Verified \u2705")}catch(m){g=!1,T(!1),t.forEach(P=>{P.value="",P.removeAttribute("disabled")}),d(Mr(m,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,m)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&m<t.length-1&&t[m+1].focus(),f()},h.onkeydown=P=>{P.key==="Backspace"&&!h.value&&m>0?t[m-1].focus():P.key==="Enter"&&(P.preventDefault(),v())},h.onpaste=P=>{P.preventDefault();let O=(P.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((Y,X)=>{t[X]&&(t[X].value=Y)});let re=Math.min(O.length,t.length-1);t[re]?.focus(),f()}}),i&&(i.onclick=h=>{h.preventDefault(),v()});let R=()=>{let h=30;a&&(a.style.display="none"),c&&(c.style.display="block"),l&&(l.textContent=String(h)),Kt(),Vt=window.setInterval(()=>{h-=1,l&&(l.textContent=String(h)),h<=0&&(Kt(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(y||a.style.display==="none")){y=!0,t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),t[0]?.focus(),f(),R();try{await r.onResend?.()}catch(m){d(Mr(m,"We couldn't send a new code. Please try again when the timer ends."))}finally{y=!1}}}),u&&(u.onclick=h=>{h.preventDefault(),Be(),r.onReset?.()})}var xe=()=>window.hcaptcha,Yt=async()=>{let r=xe();if(!r)throw new Error("Verification system not loaded");let e=await r.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},kt=(r,e)=>r instanceof Error?r.message:e,Fr=(r,e)=>r instanceof oe?r.code==="sso_required"?(e.showSso(),!0):r.code==="scim_managed_domain"?(e.showScim(),!0):(r.code==="sign_in_to_continue"&&e.showLogin(),e.showError(r.message),!0):!1,Hr=r=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(s){e={pendingAuthenticationToken:s.pendingAuthenticationToken,email:G(s.email)},r.beforeShow(),qr({email:e.email,onVerify:async i=>{if(!e)throw Be(),r.onMissingChallenge(),new Error("Missing OTP challenge");let n=await J.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await r.onAuthenticated(n)},onResend:async()=>{if(!e)throw Be(),r.onMissingChallenge(),new Error("Missing OTP challenge");let i=await Yt();try{await r.client.resendVerificationEmail(e.email,r.redirectUrl,i,{workosCapable:r.isWorkosCapable(e.email)})}finally{xe()?.reset()}},onReset:()=>{t(),r.onReset()}})}}};var se=null;function Cs(r,e=30,t){se&&(clearInterval(se),se=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,se=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",se&&(clearInterval(se),se=null),t&&t())},1e3)}function Wr(){se&&(clearInterval(se),se=null)}var Br=/^[\p{L}\p{M}\s\-'.]+$/u;function ln(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Br.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 Rs(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Br.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 zr(r,e,t){let s="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let l=document.getElementById(s);l||(l=document.createElement("div"),l.id=s,l.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",l)),l.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=ln(e.value,r.value);c?i(c):n()},a=()=>{let c=Rs(e.value,r.value);c?i(c):n()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var j=(r,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:r,retry_attempt:10-t}),window.posthog.capture(r,e)):t>0&&setTimeout(()=>j(r,e,t-1),200)};var un="wisprjam.com",dn="wispr.ai",hn="wispr_workos_capable",fn=r=>r.trim().toLowerCase().split("@")[1]??"",Ps=r=>{let e=fn(r);return e===un||e===dn},Gr=()=>{try{return window.sessionStorage.getItem(hn)==="true"}catch{return!1}},pn=r=>Ae()&&Ps(r);function Jr(r,e){let t=new We,s="email_input",i=null,n=()=>{i?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),l=document.querySelector("#full-name"),u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),g=document.querySelector("[email-element]"),y=document.querySelector("[different-provider]"),T=document.querySelector("[different-provider-name]"),v=document.querySelector("[different-provider-reset]"),R=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),P=document.querySelector("[verification-email]"),O=document.querySelector("[email-signup-retry]"),re=document.querySelector("[email-signup-reset]"),Y=document.querySelector("[scim-div]"),X=document.querySelector("[scim-reset]"),I=document.querySelector("[forgot-password]"),ie=document.querySelector("[forgot-password-success]"),ze=document.querySelector("[forgot-password-email]"),H=document.querySelector("[unverified-email]"),Ge=document.querySelector("[unverified-email-address]"),ne=document.querySelector("[resend-verification-email]"),B=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(p){console.error("Error during Google sign-in:",p)}}),d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(p){console.error("Error during Apple sign-in:",p)}}),f&&f.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(p){console.error("Error during Microsoft sign-in:",p)}}));let q=()=>{n(),y&&(y.style.display="none"),R&&(R.style.display="none"),h&&(h.style.display="none"),H&&(H.style.display="none"),Y&&(Y.style.display="none"),I&&(I.style.display="none"),ie&&(ie.style.display="none"),Be();let p=document.querySelector(".gs-hero_form-block");p&&(p.style.display="block"),g&&(g.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),c&&(c.value="",c.style.display="none",c.removeAttribute("required")),l&&(l.value="",l.style.display="none",l.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");_&&(_.style.display="none"),A&&(A.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",a&&a.focus()},z=()=>{g&&(g.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="none",l.removeAttribute("required"));let p=document.querySelector("[captcha-embed]"),_=document.querySelector("#h-captcha-container");p&&(p.style.display="block"),_&&(_.style.display="block"),I&&(I.style.display="block",I.onclick=async()=>{let A=a?.value||"",k=I.textContent||"";try{let{hcaptcha:U}=window;if(!U)throw new Error("Verification system not loaded. Please refresh the page.");I.style.pointerEvents="none",I.textContent="Sending...";let{response:C}=await U.execute({async:!0});if(!C)throw new Error("Verification cancelled");await J.requestPasswordReset(A,C),U.reset(),g&&(g.style.display="none"),I&&(I.style.display="none"),ie&&(ie.style.display="block"),ze&&(ze.textContent=A)}catch(U){console.error("Error sending password reset email:",U),I.textContent=k,I.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",m&&(m.textContent=U instanceof Error?U.message:"Failed to send reset email"))}}),s="login"},Ce=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="block",l.setAttribute("required","true"));let p=document.querySelector("[captcha-embed]"),_=document.querySelector("#h-captcha-container");p&&(p.style.display="block"),_&&(_.style.display="block"),s="signup"},Re=()=>{let p=document.querySelector(".gs-hero_form-block");p&&(p.style.display="none"),Y&&(Y.style.display="block"),X&&(X.onclick=()=>{Y&&(Y.style.display="none"),p&&(p.style.display="block"),q()})},Je=p=>{n();let _=Us(p);g&&(g.style.display="none"),y&&(y.style.display="block"),T&&(T.textContent=_),v&&(v.onclick=()=>{y&&(y.style.display="none"),q()}),s="oauth_user"};i=Hr({client:t,redirectUrl:r,isWorkosCapable:Ae,beforeShow:()=>{g&&(g.style.display="none"),H&&(H.style.display="none")},onAuthenticated:async p=>{n(),t.setCookies(p.access_token,p.refresh_token),localStorage.setItem("email",p.email),localStorage.setItem("user_id",p.user_id),localStorage.setItem("signin_provider","email");let _=[p.first_name,p.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(p.access_token,p.refresh_token,_):window.location.href=r},onMissingChallenge:z,onReset:q});let Qt=p=>{g&&(g.style.display="none"),H&&(H.style.display="block"),Ge&&(Ge.textContent=p),ne&&(ne.onclick=async()=>{let _=ne.textContent||"";try{let A=await Yt();await t.resendVerificationEmail(p,r,A),ne.textContent="Verification email resent! \u2705",ne.style.textDecoration="none"}catch(A){ne.textContent=_,h&&(h.style.display="block"),m&&(m.textContent=kt(A,"Unable to resend verification."))}finally{xe()?.reset()}}),B&&(B.onclick=()=>{H&&(H.style.display="none"),q()}),s="unverified_email"},Ve=p=>Fr(p,{showSso:()=>Je("workos"),showScim:Re,showLogin:z,showError:_=>{h&&(h.style.display="block"),m&&(m.textContent=_)}}),w=async(p,_)=>{let A=_.value;_.classList.add("loading"),_.value="";try{let k=await J.checkUserStatus(p);_.classList.remove("loading"),_.value=A,!k.exists&&k.scim_managed?Re():k.enforce_sso?Je("workos"):k.exists&&k.provider&&k.provider!=="email"&&k.provider!=="workos"?Je(k.provider):k.exists&&pn(p)||k.exists&&k.provider==="workos"?z():k.exists&&k.provider==="email"&&!k.verified?Qt(p):k.exists&&k.provider==="email"?z():Ce()}catch(k){console.error("Error checking user status:",k),_.classList.remove("loading"),_.value=A,Ve(k)||Ce()}},b=async(p,_,A,k)=>{if(!_||_.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let U=window.hcaptcha?.getResponse()||"";if(!U){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let N=await J.signInWithEmail({email:p,password:_,mcp_login_state:e.mcpLoginState,workos_capable:Gr()});if(!N.redirect_url)throw new Error(N.error||"Unable to continue connector login. Please try again.");j("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=N.redirect_url;return}let C=await t.signInWithPassword(p,_,U,{workosCapable:Gr(),provision:!1});if(C.kind==="otp"){if(!Ae())throw new Error("OTP challenge returned outside dev mode");let N={pendingAuthenticationToken:C.challenge.pending_authentication_token,email:G(C.challenge.email||p)};xe()?.reset(),A.classList.remove("loading"),A.value=k,i?.show(N);return}t.setCookies(C.accessToken,C.refreshToken),localStorage.setItem("email",p),e?.onLoginSuccess?await e.onLoginSuccess(C.accessToken,C.refreshToken,C.fullName):window.location.href=r}catch(C){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=k,!Ve(C)&&h&&(h.style.display="block",m&&(m.textContent=kt(C,"Unable to sign in. Please try again.")))}},x=async(p,_,A,k,U)=>{if(!_||_.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(!A||A.trim().length<2){h&&(h.style.display="block",m&&(m.textContent="Please enter your full name"));return}let C=Rs(A,_);if(C){h&&(h.style.display="block",m&&(m.textContent=C));return}let N=window.hcaptcha?.getResponse()||"";if(!N){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}k.classList.add("loading"),k.value="";try{let ue=await t.signUpWithPassword(p,_,A,r,N,{workosCapable:Ae()});if(window.hcaptcha&&window.hcaptcha.reset(),k.classList.remove("loading"),k.value=U,g&&(g.style.display="none"),h&&(h.style.display="none"),Et(ue)){if(!Ae())throw new Error("OTP challenge returned outside dev mode");let Ke={pendingAuthenticationToken:ue.pending_authentication_token,email:G(ue.email||p)};i?.show(Ke);return}R&&(R.style.display="block"),P&&(P.textContent=p),O&&(Cs(O,30),O.onclick=async()=>{if(O.style.pointerEvents!=="none")try{let Ke=await Yt();await t.resendVerificationEmail(p,r,Ke,{workosCapable:Ae()}),Cs(O,30)}catch(Ke){h&&(h.style.display="block"),m&&(m.textContent=kt(Ke,"Unable to resend verification. Please try again."))}finally{xe()?.reset()}}),re&&(re.onclick=()=>{R&&(R.style.display="none"),Wr(),q()})}catch(ue){k.classList.remove("loading"),k.value=U,xe()?.reset(),!Ve(ue)&&h&&(h.style.display="block",m&&(m.textContent=kt(ue,"Unable to create the account. Please try again.")))}};return o&&c&&l&&zr(c,l,o.querySelector('[type="submit"]')),o&&o.addEventListener("submit",async p=>{p.stopPropagation(),p.preventDefault();let _=G(a?.value||"");a&&(a.value=_);let A=c?.value||"",k=l?.value||"";if(!_||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(_)){h&&(h.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),m&&(m.textContent="");let C=o.querySelector('[type="submit"]'),N=C?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await w(_,C):s==="login"?await b(_,A,C,N):s==="signup"&&await x(_,A,k,C,N)}catch(ue){console.error("Auth flow error:",ue),C&&(C.classList.remove("loading"),C.value=N),h&&(h.style.display="block")}}),{reset:q}}var gn=/google ads|google adservices|adwords/i,mn=/marketing|advertising/i,Vr=r=>{let e=r.filter(s=>gn.test(s.name??""));if(e.length>0)return e.every(s=>s.decision===!0)?{ad_user_data:!0,ad_personalization:!0}:e.every(s=>s.decision===!1)?{ad_user_data:!1,ad_personalization:!1}:void 0;let t=r.filter(s=>mn.test(s.category??""));if(t.length!==0){if(t.some(s=>s.decision===!0))return{ad_user_data:!0,ad_personalization:!0};if(t.every(s=>s.decision===!1))return{ad_user_data:!1,ad_personalization:!1}}},_n=async()=>{try{let{__ucCmp:r,UC_UI:e}=window;if(r?.getConsentDetails){let t=await r.getConsentDetails();return Vr(Object.values(t?.services??{}).map(s=>({name:s?.name,category:s?.category,decision:s?.consent?.type==="EXPLICIT"&&typeof s.consent.given=="boolean"?s.consent.given:void 0})))}if(e?.getServicesBaseInfo)return Vr((e.getServicesBaseInfo()??[]).map(t=>({name:t?.name,category:t?.categorySlug,decision:t?.consent?.history?.some(s=>s?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0})))}catch{}},Kr=()=>{let r=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([_n(),r])};function Yr(r){try{let e=r._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let s=t.split(".");if(s.length>=3){let i=s.slice(2).join(".");if(i)return i}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var Xr=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Os="https://api.wisprflow.ai",Qr="https://wisprflow.ai",yn="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new We,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),s=document.querySelector("[error-div]"),i=document.querySelector("[error-message-api]"),n=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),l=c?.value??"",u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),g=localStorage.getItem("last_authed_provider");g&&{google:u,apple:d,microsoft:f,sso:document.querySelector("#sso-login"),email:document.querySelector("#email-input")}[g]?.classList.add("last-used");let y=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},T=()=>{let b=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";j("desktop_login_auto_launch",{deep_link:b}),window.location.href=b},v=()=>{let w=localStorage.getItem("signin_provider");w&&localStorage.setItem("last_authed_provider",w),e&&(e.style.display="none"),t&&(t.style.display="block"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",T()},R=w=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),i&&(i.textContent=w),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},h=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},m=null,P=document.querySelector("[retry-button]");P&&P.addEventListener("click",()=>O());let O=()=>{e&&(e.style.display="none"),a&&(a.style.display="none"),n&&(n.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=l),m&&m()},re=async(w,b)=>{try{let[x,p]=$s(b||" "),_=J.signupUser({access_token:w,first_name:x,last_name:p}),A=new Promise((k,U)=>setTimeout(()=>U(new Error("signup timeout")),4e3));await Promise.race([_,A])}catch(x){j("signup_sync_error",{error_message:x instanceof Error?x.message:String(x)})}},Y=()=>{let w=sessionStorage.getItem("wispr_fbclid");return w?`fb.1.${Date.now()}.${w}`:null},X=async(w,b)=>{let x=sessionStorage.getItem("wispr_device_code");if(!x)throw new Error("Device code not found. Please restart authentication from desktop app.");let p=Xr(),_=await Kr(),A=localStorage.getItem("wf_utm_source")||void 0,k=localStorage.getItem("wf_utm_medium")||void 0,U=localStorage.getItem("wf_utm_campaign")||void 0,C=await fetch(`${Os}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${w}`},body:JSON.stringify({device_code:x,access_token:w,refresh_token:b,fbp:p._fbp||void 0,fbc:p._fbc||Y()||void 0,gclid:Yr(p),utm:A||k||U?{utm_source:A,utm_medium:k,utm_campaign:U}:void 0,ad_user_data:_?.ad_user_data,ad_personalization:_?.ad_personalization})});if(!C.ok){let N=await C.json().catch(()=>({}));throw C.status===403&&N?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(N?.detail?.message||N.message||`Server error: ${C.status}`)}console.log("Device authentication complete"),sessionStorage.removeItem("wispr_device_code"),Fe(w)==="workos"&&r.setCookie("refresh_token",b,30/86400)},I=new URLSearchParams(window.location.search),ie=I.get("device_code"),ze=I.get("workos_capable");ze==="true"?sessionStorage.setItem("wispr_workos_capable","true"):ze==="false"&&sessionStorage.removeItem("wispr_workos_capable");let H=sessionStorage.getItem("wispr_workos_capable")==="true",Ge=I.get("auto_signin")==="true",ne=new URLSearchParams(window.location.hash.slice(1)),B=I.get("access_token")||ne.get("access_token"),q=I.get("refresh_token")||ne.get("refresh_token"),z=I.get("mcp_login_state");if(!ie&&!B&&!q&&!z&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),j("desktop_login_no_device_code"),window.location.href="/get-started";return}if(j("desktop_login_page_view",{auto_signin:Ge,workos_capable:H}),ie){sessionStorage.setItem("wispr_device_code",ie);let w=I.get("fbclid");w&&sessionStorage.setItem("wispr_fbclid",w);let b=I.get("skip_default_trial"),x=I.get("grant_weekly_bonus");b&&sessionStorage.setItem("wispr_skip_default_trial",b),x&&sessionStorage.setItem("wispr_grant_weekly_bonus",x)}(ie||B||q)&&window.history.replaceState({},"",I.get("dev-mode")==="true"?"/login?dev-mode=true":"/login");let Ce="wispr_workos_second_hop_attempted";if(B&&q){console.log("OAuth callback detected - handling tokens");let w=Fe(B);if(j("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:w}),y(),w==="workos"){sessionStorage.removeItem(Ce);try{r.setCookies(B,q);let b=I.get("email");b&&localStorage.setItem("email",b);let x=I.get("user_id");x&&localStorage.setItem("user_id",x),await re(B,I.get("name")??void 0),await X(B,q),j("desktop_login_complete_success",{method:"oauth",provider:"workos"}),v()}catch(b){if(b instanceof Error&&b.message==="enterprise_ip_not_allowed"){j("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),h();return}let x=b instanceof Error?b.message:"Failed to complete authentication. Please try again.";j("desktop_login_complete_error",{method:"oauth",provider:"workos",error:x}),console.error("Error completing WorkOS device authentication:",b),R(x)}return}try{let b=B,x=q;try{r.setCookies(B,q),await r.checkAndSetSession(),r.sessionData&&(b=r.sessionData.access_token,x=r.sessionData.refresh_token,r.setCookies(b,x),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}let p=r.sessionData?.user.email;if(H&&p&&Ps(p)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(Ce)){sessionStorage.setItem(Ce,"true"),j("desktop_login_workos_second_hop",{email_domain:p.split("@")[1]??"unknown"}),window.location.href=`${Os}/authkit/google/sign_in?source=${Qr}`;return}await re(b,r.sessionData?.user.user_metadata?.full_name),await X(b,x),j("desktop_login_complete_success",{method:"oauth"}),v()}catch(b){if(b instanceof Error&&b.message==="enterprise_ip_not_allowed"){j("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),h();return}let x=b instanceof Error?b.message:"Failed to complete authentication. Please try again.";j("desktop_login_complete_error",{method:"oauth",error:x}),console.error("Error completing device authentication:",b),R(x)}return}if(Ge){console.log("Auto-signin enabled - checking existing session"),y();try{let w=r.checkAndSetSession(),b=new Promise((x,p)=>setTimeout(()=>p(new Error("Session timeout")),3e3));if(await Promise.race([w,b]),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token),r.sessionData?.access_token&&r.sessionData?.refresh_token){console.log("Existing session found - auto-completing authentication"),await re(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await X(r.sessionData.access_token,r.sessionData.refresh_token),j("desktop_login_auto_signin_success",{token_provider:Fe(r.sessionData.access_token)}),v();return}console.log("No existing session - showing login form"),j("desktop_login_auto_signin_no_session"),O()}catch(w){if(console.error("Auto-signin error:",w),w instanceof Error&&w.message==="enterprise_ip_not_allowed"){j("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),h();return}let b=w instanceof Error?w.message:"Auto-signin failed. Please try logging in manually.";j("desktop_login_auto_signin_error",{error:b}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),O()}}else z?(j("desktop_login_mcp_entry"),O()):(j("desktop_login_manual_signout"),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status"),O());let Re=w=>{console.log(`Redirecting to ${w} OAuth`);let b=window.posthog?.getFeatureFlag?.(yn)===!0,x=(w==="google"||w==="apple")&&H&&b;j("desktop_login_oauth_click",{provider:x?"workos":w,idp:w,mcp:!!z,workos_capable:H,workos_enabled_webflow:b}),localStorage.setItem("signin_provider",w);let p=x?`authkit/${w}/sign_in`:`${w}/sign_in`,_=`${Os}/${p}?source=${Qr}`,A=sessionStorage.getItem("wispr_skip_default_trial"),k=sessionStorage.getItem("wispr_grant_weekly_bonus");A&&(_+=`&skip_default_trial=${encodeURIComponent(A)}`),k&&(_+=`&grant_weekly_bonus=${encodeURIComponent(k)}`),z&&(_+=`&mcp_login_state=${encodeURIComponent(z)}`),window.location.href=_};u&&u.addEventListener("click",()=>{Re("google")}),d&&d.addEventListener("click",()=>{Re("apple")}),f&&f.addEventListener("click",()=>{Re("microsoft")});let Je=async(w,b,x)=>{try{await re(w,x),await X(w,b)}catch(p){if(p instanceof Error&&p.message==="enterprise_ip_not_allowed"){j("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),h();return}let _=p instanceof Error?p.message:"Failed to complete authentication. Please try again.";j("desktop_login_complete_error",{method:"email",error:_}),R(_);return}j("desktop_login_complete_success",{method:"email"}),v()},Xt=sessionStorage.getItem("wispr_device_code"),Qt=Xt?`${window.location.origin}/login?device_code=${Xt}`:`${window.location.origin}/login`,{reset:Ve}=Jr(Qt,{onLoginSuccess:Je,mcpLoginState:z,skipOAuthButtons:!0});m=Ve,console.log("Desktop login page initialized")});})();
|
|
1
|
+
"use strict";(()=>{var Qr=Object.create;var kt=Object.defineProperty;var Zr=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var ri=(r,e)=>()=>(r&&(e=r(r=0)),e);var X=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ii=(r,e)=>{for(var t in e)kt(r,t,{get:e[t],enumerable:!0})},Ps=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ei(e))!si.call(r,i)&&i!==t&&kt(r,i,{get:()=>e[i],enumerable:!(s=Zr(e,i))||s.enumerable});return r};var Os=(r,e,t)=>(t=r!=null?Qr(ti(r)):{},Ps(e||!r||!r.__esModule?kt(t,"default",{value:r,enumerable:!0}):t,r)),ni=r=>Ps(kt({},"__esModule",{value:!0}),r);var ge={};ii(ge,{Headers:()=>Zt,Request:()=>ui,Response:()=>di,default:()=>Qt,fetch:()=>li});var ci,Oe,li,Qt,Zt,ui,di,ue=ri(()=>{"use strict";ci=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")},Oe=ci(),li=Oe.fetch,Qt=Oe.fetch.bind(Oe),Zt=Oe.Headers,ui=Oe.Request,di=Oe.Response});var Us=X(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});var es=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ts.default=es});var rs=X(Xe=>{"use strict";var Ds=Xe&&Xe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xe,"__esModule",{value:!0});var fi=Ds((ue(),ni(ge))),pi=Ds(Us()),ss=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=fi.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let l=null,u=null,d=null,p=n.status,g=n.statusText;if(n.ok){if(this.method!=="HEAD"){let x=await n.text();x===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=x:u=JSON.parse(x))}let A=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),w=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");A&&w&&w.length>1&&(d=parseInt(w[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(l={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,d=null,p=406,g="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{let A=await n.text();try{l=JSON.parse(A),Array.isArray(l)&&n.status===404&&(u=[],l=null,p=200,g="OK")}catch{n.status===404&&A===""?(p=204,g="No Content"):l={message:A}}if(l&&this.isMaybeSingle&&(!((c=l?.details)===null||c===void 0)&&c.includes("0 rows"))&&(l=null,p=200,g="OK"),l&&this.shouldThrowOnError)throw new pi.default(l)}return{error:l,data:u,count:d,status:p,statusText:g}});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)}};Xe.default=ss});var ns=X(Qe=>{"use strict";var gi=Qe&&Qe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qe,"__esModule",{value:!0});var mi=gi(rs()),is=class extends mi.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable: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"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){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:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${l}"; 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}};Qe.default=is});var Ct=X(Ze=>{"use strict";var _i=Ze&&Ze.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ze,"__esModule",{value:!0});var yi=_i(ns()),os=class extends yi.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};Ze.default=os});var cs=X(tt=>{"use strict";var wi=tt&&tt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tt,"__esModule",{value:!0});var et=wi(Ct()),as=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){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),s&&(this.headers.Prefer=`count=${s}`),new et.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new et.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",l.join(","))}}return new et.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new et.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new et.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};tt.default=as});var Ns=X(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.version=void 0;Rt.version="0.0.0-automated"});var Ms=X(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.DEFAULT_HEADERS=void 0;var vi=Ns();Pt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${vi.version}`}});var Fs=X(st=>{"use strict";var qs=st&&st.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(st,"__esModule",{value:!0});var bi=qs(cs()),ki=qs(Ct()),Si=Ms(),ls=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},Si.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new bi.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([u,d])=>d!==void 0).map(([u,d])=>[u,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([u,d])=>{a.searchParams.append(u,d)})):(o="POST",c=t);let l=Object.assign({},this.headers);return n&&(l.Prefer=`count=${n}`),new ki.default({method:o,url:a,headers:l,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};st.default=ls});var Js=X(q=>{"use strict";var rt=q&&q.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(q,"__esModule",{value:!0});q.PostgrestBuilder=q.PostgrestTransformBuilder=q.PostgrestFilterBuilder=q.PostgrestQueryBuilder=q.PostgrestClient=void 0;var Hs=rt(Fs());q.PostgrestClient=Hs.default;var Ws=rt(cs());q.PostgrestQueryBuilder=Ws.default;var Bs=rt(Ct());q.PostgrestFilterBuilder=Bs.default;var zs=rt(ns());q.PostgrestTransformBuilder=zs.default;var Gs=rt(rs());q.PostgrestBuilder=Gs.default;q.default={PostgrestClient:Hs.default,PostgrestQueryBuilder:Ws.default,PostgrestFilterBuilder:Bs.default,PostgrestTransformBuilder:zs.default,PostgrestBuilder:Gs.default}});var sr=X((eo,tr)=>{"use strict";tr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var St=r=>r.verification_method==="email_otp"&&typeof r.pending_authentication_token=="string"&&r.pending_authentication_token.length>0,U="https://api.wisprflow.ai",oe=class extends Error{constructor(t,s,i){super(i);this.status=t;this.code=s;this.name="AriaAuthError"}},B=r=>r.trim().toLowerCase(),Is=(r,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 r.code=="string"?r.code:r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:typeof r.detail=="string"&&t.has(r.detail)?r.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},Ve=(r,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."})[r]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),oi=(r,e,t)=>[r.message,r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"?r.detail.message:null,typeof r.detail=="string"?r.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??Ve(e,t),Pe=(r,e)=>{let t=Is(r,e);return new oe(e,t,oi(r,t,e))},ai=(r,e)=>{let t=Is(r,e);return new oe(e,t,Ve(t,e))},Xt=class{static async signupUser(e){try{let t=`${U}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${U}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${U}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${U}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch(`${U}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){let t=B(e),s=await fetch(`${U}/user_status?email=${encodeURIComponent(t)}`),i=await s.json().catch(()=>({}));if(!s.ok)throw Pe(i,s.status);return i}static async requestPasswordReset(e,t){let s=await fetch(`${U}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:B(e),captcha_token:t})});if(!s.ok){let i=await s.json().catch(()=>({}));throw Pe(i,s.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${U}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:B(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async signInWithCaptcha(e){let t=await fetch(`${U}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:B(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${U}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:B(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new oe(422,"invalid_code",Ve("invalid_code",422));let t=await fetch(`${U}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok){let i=ai(s,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new oe(t.status,"verification_failed",Ve("verification_failed",t.status))}if(s.provider!=="workos"||!s.access_token||!s.refresh_token||!s.user_id||!s.email)throw new oe(t.status,"authentication_failed",Ve("authentication_failed",t.status));return s}static async signInWithEmail(e){let t=await fetch(`${U}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:B(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async getSubscriptionStatus(e){return await fetch(`${U}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${U}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let i=`${U}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(i+=`¤cy=${s}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${U}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch(`${U}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${U}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${U}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let i=new FormData;return i.append("screenshot",e),await fetch(`${U}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function Ls(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function js(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var z=Xt;var $s=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ue(),ge)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Ke=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Et=class extends Ke{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Tt=class extends Ke{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},At=class extends Ke{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},xt;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(xt||(xt={}));var hi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Ye=class{constructor(e,{headers:t={},customFetch:s,region:i=xt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=$s(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return hi(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 l;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",l=o):typeof o=="string"?(a["Content-Type"]="text/plain",l=o):typeof FormData<"u"&&o instanceof FormData?l=o:(a["Content-Type"]="application/json",l=JSON.stringify(o)));let u=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:l}).catch(y=>{throw new Et(y)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new Tt(u);if(!u.ok)throw new At(u);let p=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),g;return p==="application/json"?g=yield u.json():p==="application/octet-stream"?g=yield u.blob():p==="text/event-stream"?g=u:p==="multipart/form-data"?g=yield u.formData():g=yield u.text(),{data:g,error:null}}catch(i){return{data:null,error:i}}})}};var Vs=Os(Js(),1),{PostgrestClient:Ks,PostgrestQueryBuilder:$n,PostgrestFilterBuilder:Un,PostgrestTransformBuilder:Dn,PostgrestBuilder:Nn}=Vs.default;var Ys="2.10.2";var Xs={"X-Client-Info":`realtime-js/${Ys}`},Qs="1.0.0",It=1e4,Zs=1e3,me;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(me||(me={}));var F;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(F||(F={}));var H;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(H||(H={}));var Ot;(function(r){r.websocket="websocket"})(Ot||(Ot={}));var de;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(de||(de={}));var it=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let l=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:l}}};var _e=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 I;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(I||(I={}));var ds=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ei(o,r,e,i),n),{})},Ei=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?er(n,o):us(o)},er=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Ci(e,t)}switch(r){case I.bool:return Ti(e);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return Ai(e);case I.json:case I.jsonb:return xi(e);case I.timestamp:return Ri(e);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:return us(e);default:return us(e)}},us=r=>r,Ti=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Ai=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},xi=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Ci=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n,o=r.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>er(e,a))}return r},Ri=r=>typeof r=="string"?r.replace(" ","T"):r,Lt=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ye=class{constructor(e,t,s={},i=It){this.channel=e,this.event=t,this.payload=s,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 s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var hs;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(hs||(hs={}));var Ie=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.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,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(l,u)=>{o[l]||(c[l]=u)}),this.map(o,(l,u)=>{let d=n[l];if(d){let p=u.map(w=>w.presence_ref),g=d.map(w=>w.presence_ref),y=u.filter(w=>g.indexOf(w.presence_ref)<0),A=d.filter(w=>p.indexOf(w.presence_ref)<0);y.length>0&&(a[l]=y),A.length>0&&(c[l]=A)}else a[l]=u}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var l;let u=(l=e[a])!==null&&l!==void 0?l:[];if(e[a]=this.cloneDeep(c),u.length>0){let d=e[a].map(g=>g.presence_ref),p=u.filter(g=>d.indexOf(g.presence_ref)<0);e[a].unshift(...p)}s(a,u,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.map(d=>d.presence_ref);l=l.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=l,i(a,l,c),l.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=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 fs;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(fs||(fs={}));var ps;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(ps||(ps={}));var gs;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(gs||(gs={}));var Le=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=F.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 ye(this,H.join,this.params,this.timeout),this.rejoinTimer=new _e(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=F.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=F.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this._on(H.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Ie(this),this.broadcastEndpointURL=Lt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,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(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("CLOSED"));let c={},l={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(u=>u.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:u})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{let p=this.bindings.postgres_changes,g=(d=p?.length)!==null&&d!==void 0?d:0,y=[];for(let A=0;A<g;A++){let w=p[A],{filter:{event:x,schema:h,table:_,filter:C}}=w,P=u&&u[A];if(P&&P.event===x&&P.schema===h&&P.table===_&&P.filter===C)y.push(Object.assign(Object.assign({},w),{id:P.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,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,(s=t.timeout)!==null&&s!==void 0?s: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 l=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"),l.receive("ok",()=>n("ok")),l.receive("error",()=>n("error")),l.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=F.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(H.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new ye(this,H.leave,{},e);i.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let i=new AbortController,n=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new ye(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:l,join:u}=H;if(s&&[a,c,l,u].indexOf(o)>=0&&s!==this._joinRef())return;let p=this._onMessage(o,t,s);if(t&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(g=>{var y,A,w;return((y=g.filter)===null||y===void 0?void 0:y.event)==="*"||((w=(A=g.filter)===null||A===void 0?void 0:A.event)===null||w===void 0?void 0:w.toLocaleLowerCase())===o}).map(g=>g.callback(p,s)):(n=this.bindings[o])===null||n===void 0||n.filter(g=>{var y,A,w,x,h,_;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){let C=g.id,P=(y=g.filter)===null||y===void 0?void 0:y.event;return C&&((A=t.ids)===null||A===void 0?void 0:A.includes(C))&&(P==="*"||P?.toLocaleLowerCase()===((w=t.data)===null||w===void 0?void 0:w.type.toLocaleLowerCase()))}else{let C=(h=(x=g?.filter)===null||x===void 0?void 0:x.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return C==="*"||C===((_=t?.event)===null||_===void 0?void 0:_.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof p=="object"&&"ids"in p){let y=p.data,{schema:A,table:w,commit_timestamp:x,type:h,errors:_}=y;p=Object.assign(Object.assign({},{schema:A,table:w,commit_timestamp:x,eventType:h,new:{},old:{},errors:_}),this._getPayloadRecords(y))}g.callback(p,s)})}_isClosed(){return this.state===F.closed}_isJoined(){return this.state===F.joined}_isJoining(){return this.state===F.joining}_isLeaving(){return this.state===F.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(H.close,{},e)}_onError(e){this._on(H.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=F.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ds(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ds(e.columns,e.old_record)),t}};var Oi=()=>{},Ii=typeof WebSocket<"u",je=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Xs,this.params={},this.timeout=It,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Oi,this.conn=null,this.sendBuffer=[],this.serializer=new it,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(ue(),ge)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Ot.websocket}`,this.httpEndpoint=Lt(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=(s=t?.params)===null||s===void 0?void 0:s.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 _e(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(Ii){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new ms(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Os(sr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case me.connecting:return de.Connecting;case me.open:return de.Open;case me.closing:return de.Closing;default:return de.Closed}}isConnected(){return this.connectionState()===de.Open}channel(e,t={config:{}}){let s=new Le(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,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} ${s} (${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(H.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Qs}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).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(H.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${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(Zs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},ms=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=me.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var $e=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function N(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var jt=class extends $e{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},nt=class extends $e{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Li=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},$t=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ue(),ge)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},rr=()=>Li(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ue(),ge))).Response:Response});var Ue=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},_s=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),ji=(r,e)=>Ue(void 0,void 0,void 0,function*(){let t=yield rr();r instanceof t?r.json().then(s=>{e(new jt(_s(s),r.status||500))}).catch(s=>{e(new nt(_s(s),s))}):e(new nt(_s(r),r))}),$i=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};function Ut(r,e,t,s,i,n){return Ue(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,$i(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>ji(c,a))})})}function ot(r,e,t,s){return Ue(this,void 0,void 0,function*(){return Ut(r,"GET",e,t,s)})}function Q(r,e,t,s,i){return Ue(this,void 0,void 0,function*(){return Ut(r,"POST",e,s,i,t)})}function ir(r,e,t,s,i){return Ue(this,void 0,void 0,function*(){return Ut(r,"PUT",e,s,i,t)})}function Dt(r,e,t,s,i){return Ue(this,void 0,void 0,function*(){return Ut(r,"DELETE",e,s,i,t)})}var G=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Ui={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},nr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},at=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=$t(i)}uploadOrUpdate(e,t,s,i){return G(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},nr),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(N(n))return{data:null,error:n};throw n}})}upload(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return G(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,l=Object.assign({upsert:nr.upsert},i),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",l.cacheControl)):(c=s,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:u}),p=yield d.json();return d.ok?{data:{path:n,fullPath:p.Key},error:null}:{data:null,error:p}}catch(c){if(N(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return G(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield Q(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new $e("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}update(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:yield Q(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(N(i))return{data:null,error:i};throw i}})}copy(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:{path:(yield Q(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(N(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return G(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield Q(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(N(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return G(this,void 0,void 0,function*(){try{let i=yield Q(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(N(i))return{data:null,error:i};throw i}})}download(e,t){return G(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 ot(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(N(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=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 l=i.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${l}`)}}}remove(e){return G(this,void 0,void 0,function*(){try{return{data:yield Dt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}list(e,t,s){return G(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Ui),t),{prefix:e||""});return{data:yield Q(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(N(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 or="2.6.0";var ar={"X-Client-Info":`storage-js/${or}`};var De=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ct=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},ar),t),this.fetch=$t(s)}listBuckets(){return De(this,void 0,void 0,function*(){try{return{data:yield ot(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(N(e))return{data:null,error:e};throw e}})}getBucket(e){return De(this,void 0,void 0,function*(){try{return{data:yield ot(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return De(this,void 0,void 0,function*(){try{return{data:yield Q(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return De(this,void 0,void 0,function*(){try{return{data:yield ir(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}emptyBucket(e){return De(this,void 0,void 0,function*(){try{return{data:yield Q(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}deleteBucket(e){return De(this,void 0,void 0,function*(){try{return{data:yield Dt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}};var lt=class extends ct{constructor(e,t={},s){super(e,t,s)}from(e){return new at(this.url,this.headers,e,this.fetch)}};var cr="2.44.4";var ut="";typeof Deno<"u"?ut="deno":typeof document<"u"?ut="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ut="react-native":ut="node";var Di={"X-Client-Info":`supabase-js-${ut}/${cr}`},lr={headers:Di},ur={schema:"public"},dr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},hr={};ue();var Ni=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Mi=r=>{let e;return r?e=r:typeof fetch>"u"?e=Qt:e=fetch,(...t)=>e(...t)},qi=()=>typeof Headers>"u"?Zt:Headers,fr=(r,e,t)=>{let s=Mi(t),i=qi();return(n,o)=>Ni(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,l=new i(o?.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:l}))})};function pr(r){return r.replace(/\/$/,"")}function gr(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:l}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},l),n)}}var Nt="2.64.4";var mr="http://localhost:9999",_r="supabase.auth.token";var yr={"X-Client-Info":`gotrue-js/${Nt}`},ys=10;var dt="X-Supabase-Api-Version",ws={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function wr(r){return Math.round(Date.now()/1e3)+r}function vr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var J=()=>typeof document<"u",we={tested:!1,writable:!1},he=()=>{if(!J())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(we.tested)return we.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),we.tested=!0,we.writable=!0}catch{we.tested=!0,we.writable=!1}return we.writable};function Mt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var qt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ue(),ge)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},br=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",vs=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ft=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Ft=async(r,e)=>{await r.removeItem(e)};function Fi(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,l,u=0;for(r=r.replace("-","+").replace("_","/");u<r.length;)o=e.indexOf(r.charAt(u++)),a=e.indexOf(r.charAt(u++)),c=e.indexOf(r.charAt(u++)),l=e.indexOf(r.charAt(u++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|l,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),l!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var ht=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ht.promiseConstructor=Promise;function bs(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(Fi(s))}async function kr(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Sr(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await r(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Hi(r){return("0"+r.toString(16)).substr(-2)}function Wi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,Hi).join("")}async function Bi(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function zi(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Gi(r){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."),r;let t=await Bi(r);return zi(t)}async function ve(r,e,t=!1){let s=Wi(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await vs(r,`${e}-code-verifier`,i);let n=await Gi(s);return[n,s===n?"plain":"s256"]}var Ji=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Er(r){let e=r.headers.get(dt);if(!e||!e.match(Ji))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var pt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function E(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Ht=class extends pt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Tr(r){return E(r)&&r.name==="AuthApiError"}var Ne=class extends pt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ae=class extends pt{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},Z=class extends ae{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Me=class extends ae{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},be=class extends ae{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ke=class extends ae{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}}},gt=class extends ae{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}}},qe=class extends ae{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Wt(r){return E(r)&&r.name==="AuthRetryableFetchError"}var mt=class extends ae{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Vi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},Se=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Ki=[502,503,504];async function Ar(r){var e;if(!br(r))throw new qe(Se(r),0);if(Ki.includes(r.status))throw new qe(Se(r),r.status);let t;try{t=await r.json()}catch(n){throw new Ne(Se(n),n)}let s,i=Er(r);if(i&&i.getTime()>=ws["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new mt(Se(t),r.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 mt(Se(t),r.status,t.weak_password.reasons);throw new Ht(Se(t),r.status||500,s)}var Yi=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function T(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[dt]||(n[dt]=ws["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Xi(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Xi(r,e,t,s,i,n){let o=Yi(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new qe(Se(c),0)}if(a.ok||await Ar(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await Ar(c)}}function ce(r){var e;let t=null;Qi(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=wr(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function ks(r){let e=ce(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function ee(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function xr(r){return{data:r,error:null}}function Cr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Vi(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Rr(r){return r}function Qi(r){return r.access_token&&r.refresh_token&&r.expires_in}var Zi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},Ee=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=qt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await T(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(E(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await T(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ee})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Zi(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Cr,redirectTo:t?.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await T(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ee})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await T(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Rr});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return g.length>0&&(g.forEach(y=>{let A=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);l[`${w}Page`]=A}),l.total=parseInt(p)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(E(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ee})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await T(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ee})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await T(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ee})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await T(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await T(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}};var Pr={getItem:r=>he()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{he()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{he()&&globalThis.localStorage.removeItem(r)}};function Ss(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Or(){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 Te={debug:!!(globalThis&&he()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},_t=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Bt=class extends _t{};async function Es(r,e,t){Te.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Te.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){Te.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Te.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Te.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Bt(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Te.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()}})}Or();var en={url:mr,storageKey:_r,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:yr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},yt=30*1e3,Ir=3;async function Lr(r,e,t){return await t()}var Ae=class r{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&J()&&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({},en),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 Ee({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=qt(i.fetch),this.lock=i.lock||Lr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:J()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Es:this.lock=Lr,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:he()?this.storage=Pr:(this.memoryStorage={},this.storage=Ss(this.memoryStorage)):(this.memoryStorage={},this.storage=Ss(this.memoryStorage)),J()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Nt}) ${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=J()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return E(e)?{error:e}:{error:new Ne("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:ce}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:u,password:d,options:p}=e,g=null,y=null;this.flowType==="pkce"&&([g,y]=await ve(this.storage,this.storageKey)),n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:u,password:d,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:g,code_challenge_method:y},xform:ce})}else if("phone"in e){let{phone:u,password:d,options:p}=e;n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=p?.data)!==null&&s!==void 0?s:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:ce})}else throw new be("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,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ks})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ks})}else throw new be("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Me}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(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 ft(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ce});return await Ft(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Me}:(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:s,token:i,access_token:n,nonce:o}=e,a=await T(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ce}),{data:c,error:l}=a;return l?{data:{user:null,session:null},error:l}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Me}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:l})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await ve(this.storage,this.storageKey));let{error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await T(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:l?.message_id},error:u}}throw new be("You must provide either an email or phone number.")}catch(a){if(E(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:ce});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await ve(this.storage,this.storageKey)),await T(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s: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:xr})}catch(n){if(E(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new Z;let{error:i}=await T(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(E(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await T(this.fetch,"POST",t,{headers:this.headers,body:{email:s,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:s,type:i,options:n}=e,{data:o,error:a}=await T(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new be("You must provide either an email or phone number and a type")}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,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 s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await ft(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,l,u)=>(!o&&l==="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,l,u))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ee}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Z}:await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:ee})})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new Z;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await ve(this.storage,this.storageKey));let{data:l,error:u}=await T(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:ee});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return bs(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 Z;let t=Date.now()/1e3,s=t,i=!0,n=null,o=bs(e.access_token);if(o.exp&&(s=o.exp,i=s<=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:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(E(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new Z;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!J())throw new ke("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ke("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new gt("Not a valid PKCE flow url.");let t=Mt(window.location.href);if(e){if(!t.code)throw new gt("No code detected.");let{data:h,error:_}=await this._exchangeCodeForSession(t.code);if(_)throw _;let C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ke(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:l}=t;if(!n||!a||!o||!l)throw new ke("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),p=u+d;c&&(p=parseInt(c));let g=p-u;g*1e3<=yt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${d}s`);let y=p-d;u-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,u):u-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,p,u);let{data:A,error:w}=await this._getUser(n);if(w)throw w;let x={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:p,refresh_token:o,token_type:l,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:x,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Mt(window.location.href);return!!(J()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Mt(window.location.href),t=await ft(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{error:n};let o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Tr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Ft(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=vr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((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 s=null,i=null;this.flowType==="pkce"&&([s,i]=await ve(this.storage,this.storageKey,!0));try{return await T(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(E(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,l,u;let{data:d,error:p}=n;if(p)throw p;let g=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",g,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return J()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(E(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await T(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Sr(async i=>(i>0&&await kr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ce})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Wt(n)&&Date.now()+o-s<yt})}catch(s){if(this._debug(t,"error",s),E(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),J()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await ft(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<i+ys;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${ys}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Wt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new Z;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ht;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new Z;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),E(n)){let o={session:null,error:n};return Wt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await vs(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Ft(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&J()&&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(),yt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((s.expires_at*1e3-e)/yt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${yt}ms, refresh threshold is ${Ir} ticks`),i<=Ir&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof _t)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!J()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await ve(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await T(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;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;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let u=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}};Ae.nextInstanceID=0;var tn=Ae,Ts=tn;var zt=class extends Ts{constructor(e){super(e)}};var sn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},wt=class{constructor(e,t,s){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=pr(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`,l={db:ur,realtime:hr,auth:Object.assign(Object.assign({},dr),{storageKey:c}),global:lr},u=gr(s??{},l);this.storageKey=(i=u.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=u.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=fr(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},u.realtime)),this.rest=new Ks(`${a}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Ye(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new lt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return sn(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,storageKey:n,flowType:o,debug:a},c,l){var u;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new zt({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:l,hasCustomAuthorizationHeader:(u="Authorization"in this.headers)!==null&&u!==void 0?u:!1})}_initRealtimeClient(e){return new je(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var jr=(r,e,t)=>new wt(r,e,t);var le={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var rn=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Gt=r=>{let[e,t]=r.split(".");return!e||!t?null:rn(t)},Fe=r=>{let e=Gt(r);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 nn="https://api.workos.com",on=60,He=(r,e)=>typeof r[e]=="string"?r[e]:void 0,$r=(r,e,t)=>{let s=Gt(r);if(!s)return null;let i=He(s,"urn:wispr:user_external_id")??He(s,"sub"),n=t?.email??He(s,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof s.exp=="number"?s.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:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},an=async(r,e,t,s)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):nn,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:r,organization_id:s})});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()},Ur=async(r,e)=>{let t=Gt(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=He(t,"client_id");if(i-s<on&&n){let c=await an(e,n,He(t,"iss"),He(t,"org_id")),l=$r(c.access_token,c.refresh_token,c.user);if(!l)throw new Error("WorkOS refresh returned an invalid access token");return l}if(i<=s)throw new Error("WorkOS session expired");let a=$r(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var We=class{constructor(){this.sessionData=null;this.supabase=jr(le.supaBaseUrl,le.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||le.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||le.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||le.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let i=new Date;i.setTime(i.getTime()+s*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,s=e.refresh_token;if(t&&s)try{if(Fe(t)==="workos"){this.sessionData=await Ur(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,i]=t.split("=");return e[s]=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:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||le.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=await z.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:n,redirect_url:i||le.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,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await z.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(St(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,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await z.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||le.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 Jt=null,Dr=(r,e)=>{if(!(r instanceof Error)||r.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:s}=r;return s&&t[s]||e},Vt=()=>{Jt!==null&&(window.clearInterval(Jt),Jt=null)};function Be(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),Vt()}function Nr(r){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]")),s=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]"),l=document.querySelector("[otp-resend-seconds]"),u=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),n&&(n.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),Vt(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let d=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},p=()=>{n&&(n.style.display="none")},g=!1,y=!1,A=h=>{i&&(i.style.pointerEvents=h?"none":"",h?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},w=async()=>{if(g)return;let h=t.map(_=>_.value).join("");if(h.length!==6){d("Please enter all 6 digits.");return}g=!0,A(!0),t.forEach(_=>_.setAttribute("disabled","true")),p();try{await r.onVerify(h),p(),i&&(i.textContent="Verified \u2705")}catch(_){g=!1,A(!1),t.forEach(C=>{C.value="",C.removeAttribute("disabled")}),d(Dr(_,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,_)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&_<t.length-1&&t[_+1].focus(),p()},h.onkeydown=C=>{C.key==="Backspace"&&!h.value&&_>0?t[_-1].focus():C.key==="Enter"&&(C.preventDefault(),w())},h.onpaste=C=>{C.preventDefault();let P=(C.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);P.split("").forEach((K,Y)=>{t[Y]&&(t[Y].value=K)});let se=Math.min(P.length,t.length-1);t[se]?.focus(),p()}}),i&&(i.onclick=h=>{h.preventDefault(),w()});let x=()=>{let h=30;a&&(a.style.display="none"),c&&(c.style.display="block"),l&&(l.textContent=String(h)),Vt(),Jt=window.setInterval(()=>{h-=1,l&&(l.textContent=String(h)),h<=0&&(Vt(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(y||a.style.display==="none")){y=!0,t.forEach(_=>{_.value="",_.removeAttribute("disabled")}),t[0]?.focus(),p(),x();try{await r.onResend?.()}catch(_){d(Dr(_,"We couldn't send a new code. Please try again when the timer ends."))}finally{y=!1}}}),u&&(u.onclick=h=>{h.preventDefault(),Be(),r.onReset?.()})}var xe=()=>window.hcaptcha,Kt=async()=>{let r=xe();if(!r)throw new Error("Verification system not loaded");let e=await r.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},vt=(r,e)=>r instanceof Error?r.message:e,Mr=(r,e)=>r instanceof oe?r.code==="sso_required"?(e.showSso(),!0):r.code==="scim_managed_domain"?(e.showScim(),!0):(r.code==="sign_in_to_continue"&&e.showLogin(),e.showError(r.message),!0):!1,qr=r=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(s){e={pendingAuthenticationToken:s.pendingAuthenticationToken,email:B(s.email)},r.beforeShow(),Nr({email:e.email,onVerify:async i=>{if(!e)throw Be(),r.onMissingChallenge(),new Error("Missing OTP challenge");let n=await z.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await r.onAuthenticated(n)},onResend:async()=>{if(!e)throw Be(),r.onMissingChallenge(),new Error("Missing OTP challenge");let i=await Kt();try{await r.client.resendVerificationEmail(e.email,r.redirectUrl,i,{workosCapable:r.isWorkosCapable(e.email)})}finally{xe()?.reset()}},onReset:()=>{t(),r.onReset()}})}}};var te=null;function As(r,e=30,t){te&&(clearInterval(te),te=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,te=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",te&&(clearInterval(te),te=null),t&&t())},1e3)}function Fr(){te&&(clearInterval(te),te=null)}var Hr=/^[\p{L}\p{M}\s\-'.]+$/u;function cn(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Hr.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 xs(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Hr.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 Wr(r,e,t){let s="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let l=document.getElementById(s);l||(l=document.createElement("div"),l.id=s,l.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",l)),l.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=cn(e.value,r.value);c?i(c):n()},a=()=>{let c=xs(e.value,r.value);c?i(c):n()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var R=(r,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:r,retry_attempt:10-t}),window.posthog.capture(r,e)):t>0&&setTimeout(()=>R(r,e,t-1),200)};var ln="wisprjam.com",un="wispr.ai",dn="wispr_workos_capable",hn=r=>r.trim().toLowerCase().split("@")[1]??"",zr=r=>{let e=hn(r);return e===ln||e===un},Br=()=>{try{return window.sessionStorage.getItem(dn)==="true"}catch{return!1}};function Gr(r,e){let t=new We,s="email_input",i=null,n=()=>{i?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),l=document.querySelector("#full-name"),u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),p=document.querySelector("#microsoft-login"),g=document.querySelector("[email-element]"),y=document.querySelector("[different-provider]"),A=document.querySelector("[different-provider-name]"),w=document.querySelector("[different-provider-reset]"),x=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),_=document.querySelector("[error-message]"),C=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),se=document.querySelector("[email-signup-reset]"),K=document.querySelector("[scim-div]"),Y=document.querySelector("[scim-reset]"),O=document.querySelector("[forgot-password]"),re=document.querySelector("[forgot-password-success]"),Ce=document.querySelector("[forgot-password-email]"),V=document.querySelector("[unverified-email]"),fe=document.querySelector("[unverified-email-address]"),ie=document.querySelector("[resend-verification-email]"),ze=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(f){console.error("Error during Google sign-in:",f)}}),d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(f){console.error("Error during Apple sign-in:",f)}}),p&&p.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(f){console.error("Error during Microsoft sign-in:",f)}}));let M=()=>{n(),y&&(y.style.display="none"),x&&(x.style.display="none"),h&&(h.style.display="none"),V&&(V.style.display="none"),K&&(K.style.display="none"),O&&(O.style.display="none"),re&&(re.style.display="none"),Be();let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="block"),g&&(g.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),c&&(c.value="",c.style.display="none",c.removeAttribute("required")),l&&(l.value="",l.style.display="none",l.removeAttribute("required"));let m=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");m&&(m.style.display="none"),k&&(k.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",a&&a.focus()},W=()=>{g&&(g.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="none",l.removeAttribute("required"));let f=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),m&&(m.style.display="block"),O&&(O.style.display="block",O.onclick=async()=>{let k=a?.value||"",S=O.textContent||"";try{let{hcaptcha:j}=window;if(!j)throw new Error("Verification system not loaded. Please refresh the page.");O.style.pointerEvents="none",O.textContent="Sending...";let{response:L}=await j.execute({async:!0});if(!L)throw new Error("Verification cancelled");await z.requestPasswordReset(k,L),j.reset(),g&&(g.style.display="none"),O&&(O.style.display="none"),re&&(re.style.display="block"),Ce&&(Ce.textContent=k)}catch(j){console.error("Error sending password reset email:",j),O.textContent=S,O.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",_&&(_.textContent=j instanceof Error?j.message:"Failed to send reset email"))}}),s="login"},ne=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="block",l.setAttribute("required","true"));let f=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),m&&(m.style.display="block"),s="signup"},Re=()=>{let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="none"),K&&(K.style.display="block"),Y&&(Y.onclick=()=>{K&&(K.style.display="none"),f&&(f.style.display="block"),M()})},pe=f=>{n();let m=js(f);g&&(g.style.display="none"),y&&(y.style.display="block"),A&&(A.textContent=m),w&&(w.onclick=()=>{y&&(y.style.display="none"),M()}),s="oauth_user"};i=qr({client:t,redirectUrl:r,isWorkosCapable:()=>!0,beforeShow:()=>{g&&(g.style.display="none"),V&&(V.style.display="none")},onAuthenticated:async f=>{n(),t.setCookies(f.access_token,f.refresh_token),localStorage.setItem("email",f.email),localStorage.setItem("user_id",f.user_id),localStorage.setItem("signin_provider","email");let m=[f.first_name,f.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(f.access_token,f.refresh_token,m):window.location.href=r},onMissingChallenge:W,onReset:M});let bt=f=>{g&&(g.style.display="none"),V&&(V.style.display="block"),fe&&(fe.textContent=f),ie&&(ie.onclick=async()=>{let m=ie.textContent||"";try{let k=await Kt();await t.resendVerificationEmail(f,r,k),ie.textContent="Verification email resent! \u2705",ie.style.textDecoration="none"}catch(k){ie.textContent=m,h&&(h.style.display="block"),_&&(_.textContent=vt(k,"Unable to resend verification."))}finally{xe()?.reset()}}),ze&&(ze.onclick=()=>{V&&(V.style.display="none"),M()}),s="unverified_email"},Ge=f=>Mr(f,{showSso:()=>pe("workos"),showScim:Re,showLogin:W,showError:m=>{h&&(h.style.display="block"),_&&(_.textContent=m)}}),Yt=async(f,m)=>{let k=m.value;m.classList.add("loading"),m.value="";try{let S=await z.checkUserStatus(f);m.classList.remove("loading"),m.value=k,!S.exists&&S.scim_managed?Re():S.enforce_sso?pe("workos"):S.exists&&S.provider&&S.provider!=="email"&&S.provider!=="workos"?pe(S.provider):S.exists&&S.provider==="workos"?W():S.exists&&S.provider==="email"&&!S.verified?bt(f):S.exists&&S.provider==="email"?W():ne()}catch(S){console.error("Error checking user status:",S),m.classList.remove("loading"),m.value=k,Ge(S)||ne()}},v=async(f,m,k,S)=>{if(!m||m.length<8){h&&(h.style.display="block",_&&(_.textContent="Password must be at least 8 characters"));return}let j=window.hcaptcha?.getResponse()||"";if(!j){h&&(h.style.display="block",_&&(_.textContent="Please complete the verification"));return}k.classList.add("loading"),k.value="";try{if(e?.mcpLoginState){let D=await z.signInWithEmail({email:f,password:m,mcp_login_state:e.mcpLoginState,workos_capable:Br()});if(!D.redirect_url)throw new Error(D.error||"Unable to continue connector login. Please try again.");R("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=D.redirect_url;return}let L=Br(),$=await t.signInWithPassword(f,m,j,{workosCapable:L,provision:!1});if($.kind==="otp"){if(!L)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let D={pendingAuthenticationToken:$.challenge.pending_authentication_token,email:B($.challenge.email||f)};xe()?.reset(),k.classList.remove("loading"),k.value=S,i?.show(D);return}t.setCookies($.accessToken,$.refreshToken),localStorage.setItem("email",f),e?.onLoginSuccess?await e.onLoginSuccess($.accessToken,$.refreshToken,$.fullName):window.location.href=r}catch(L){window.hcaptcha&&window.hcaptcha.reset(),k.classList.remove("loading"),k.value=S,!Ge(L)&&h&&(h.style.display="block",_&&(_.textContent=vt(L,"Unable to sign in. Please try again.")))}},b=async(f,m,k,S,j)=>{if(!m||m.length<8){h&&(h.style.display="block",_&&(_.textContent="Password must be at least 8 characters"));return}if(!k||k.trim().length<2){h&&(h.style.display="block",_&&(_.textContent="Please enter your full name"));return}let L=xs(k,m);if(L){h&&(h.style.display="block",_&&(_.textContent=L));return}let $=window.hcaptcha?.getResponse()||"";if(!$){h&&(h.style.display="block",_&&(_.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{let D=await t.signUpWithPassword(f,m,k,r,$,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=j,g&&(g.style.display="none"),h&&(h.style.display="none"),St(D)){let Je={pendingAuthenticationToken:D.pending_authentication_token,email:B(D.email||f)};i?.show(Je);return}x&&(x.style.display="block"),C&&(C.textContent=f),P&&(As(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let Je=await Kt();await t.resendVerificationEmail(f,r,Je,{workosCapable:!0}),As(P,30)}catch(Je){h&&(h.style.display="block"),_&&(_.textContent=vt(Je,"Unable to resend verification. Please try again."))}finally{xe()?.reset()}}),se&&(se.onclick=()=>{x&&(x.style.display="none"),Fr(),M()})}catch(D){S.classList.remove("loading"),S.value=j,xe()?.reset(),!Ge(D)&&h&&(h.style.display="block",_&&(_.textContent=vt(D,"Unable to create the account. Please try again.")))}};return o&&c&&l&&Wr(c,l,o.querySelector('[type="submit"]')),o&&o.addEventListener("submit",async f=>{f.stopPropagation(),f.preventDefault();let m=B(a?.value||"");a&&(a.value=m);let k=c?.value||"",S=l?.value||"";if(!m||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m)){h&&(h.style.display="block",_&&(_.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),_&&(_.textContent="");let L=o.querySelector('[type="submit"]'),$=L?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await Yt(m,L):s==="login"?await v(m,k,L,$):s==="signup"&&await b(m,k,S,L,$)}catch(D){console.error("Auth flow error:",D),L&&(L.classList.remove("loading"),L.value=$),h&&(h.style.display="block")}}),{reset:M}}var fn=/google ads|google adservices|adwords/i,pn=/marketing|advertising/i,Jr=r=>{let e=r.filter(s=>fn.test(s.name??""));if(e.length>0)return e.every(s=>s.decision===!0)?{ad_user_data:!0,ad_personalization:!0}:e.every(s=>s.decision===!1)?{ad_user_data:!1,ad_personalization:!1}:void 0;let t=r.filter(s=>pn.test(s.category??""));if(t.length!==0){if(t.some(s=>s.decision===!0))return{ad_user_data:!0,ad_personalization:!0};if(t.every(s=>s.decision===!1))return{ad_user_data:!1,ad_personalization:!1}}},gn=async()=>{try{let{__ucCmp:r,UC_UI:e}=window;if(r?.getConsentDetails){let t=await r.getConsentDetails();return Jr(Object.values(t?.services??{}).map(s=>({name:s?.name,category:s?.category,decision:s?.consent?.type==="EXPLICIT"&&typeof s.consent.given=="boolean"?s.consent.given:void 0})))}if(e?.getServicesBaseInfo)return Jr((e.getServicesBaseInfo()??[]).map(t=>({name:t?.name,category:t?.categorySlug,decision:t?.consent?.history?.some(s=>s?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0})))}catch{}},Vr=()=>{let r=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([gn(),r])};function Kr(r){try{let e=r._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let s=t.split(".");if(s.length>=3){let i=s.slice(2).join(".");if(i)return i}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var Yr=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Cs="https://api.wisprflow.ai",Xr="https://wisprflow.ai",mn="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new We,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),s=document.querySelector("[error-div]"),i=document.querySelector("[error-message-api]"),n=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),l=c?.value??"",u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),p=document.querySelector("#microsoft-login"),g=localStorage.getItem("last_authed_provider");g&&{google:u,apple:d,microsoft:p,sso:document.querySelector("#sso-login"),email:document.querySelector("#email-input")}[g]?.classList.add("last-used");let y=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},A=()=>{let b=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";R("desktop_login_auto_launch",{deep_link:b}),window.location.href=b},w=()=>{let v=localStorage.getItem("signin_provider");v&&localStorage.setItem("last_authed_provider",v),e&&(e.style.display="none"),t&&(t.style.display="block"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",A()},x=v=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),i&&(i.textContent=v),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},h=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},_=null,C=document.querySelector("[retry-button]");C&&C.addEventListener("click",()=>P());let P=()=>{e&&(e.style.display="none"),s&&(s.style.display="none"),a&&(a.style.display="none"),n&&(n.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=l),_&&_()},se=async(v,b)=>{try{let[f,m]=Ls(b||" "),k=z.signupUser({access_token:v,first_name:f,last_name:m}),S=new Promise((j,L)=>setTimeout(()=>L(new Error("signup timeout")),4e3));await Promise.race([k,S])}catch(f){R("signup_sync_error",{error_message:f instanceof Error?f.message:String(f)})}},K=()=>{let v=sessionStorage.getItem("wispr_fbclid");return v?`fb.1.${Date.now()}.${v}`:null},Y=async(v,b)=>{let f=sessionStorage.getItem("wispr_device_code");if(!f)throw new Error("Device code not found. Please restart authentication from desktop app.");let m=Yr(),k=await Vr(),S=localStorage.getItem("wf_utm_source")||void 0,j=localStorage.getItem("wf_utm_medium")||void 0,L=localStorage.getItem("wf_utm_campaign")||void 0,$=await fetch(`${Cs}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${v}`},body:JSON.stringify({device_code:f,access_token:v,refresh_token:b,fbp:m._fbp||void 0,fbc:m._fbc||K()||void 0,gclid:Kr(m),utm:S||j||L?{utm_source:S,utm_medium:j,utm_campaign:L}:void 0,ad_user_data:k?.ad_user_data,ad_personalization:k?.ad_personalization})});if(!$.ok){let D=await $.json().catch(()=>({}));throw $.status===403&&D?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(D?.detail?.message||D.message||`Server error: ${$.status}`)}console.log("Device authentication complete"),sessionStorage.removeItem("wispr_device_code"),Fe(v)==="workos"&&r.setCookie("refresh_token",b,30/86400)},O=new URLSearchParams(window.location.search),re=O.get("device_code"),Ce=O.get("error"),V=O.get("workos_capable");V==="true"?sessionStorage.setItem("wispr_workos_capable","true"):V==="false"&&sessionStorage.removeItem("wispr_workos_capable");let fe=sessionStorage.getItem("wispr_workos_capable")==="true",ie=O.get("auto_signin")==="true",ze=new URLSearchParams(window.location.hash.slice(1)),M=O.get("access_token")||ze.get("access_token"),W=O.get("refresh_token")||ze.get("refresh_token"),ne=O.get("mcp_login_state");if(!re&&!M&&!W&&!ne&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),R("desktop_login_no_device_code"),window.location.href="/get-started";return}if(R("desktop_login_page_view",{auto_signin:ie,workos_capable:fe}),re){sessionStorage.setItem("wispr_device_code",re);let v=O.get("fbclid");v&&sessionStorage.setItem("wispr_fbclid",v);let b=O.get("skip_default_trial"),f=O.get("grant_weekly_bonus");b&&sessionStorage.setItem("wispr_skip_default_trial",b),f&&sessionStorage.setItem("wispr_grant_weekly_bonus",f)}(re||M||W||Ce)&&window.history.replaceState({},"","/login");let Re="wispr_workos_second_hop_attempted";if(M&&W){console.log("OAuth callback detected - handling tokens");let v=Fe(M);if(R("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:v}),y(),v==="workos"){sessionStorage.removeItem(Re);try{r.setCookies(M,W);let b=O.get("email");b&&localStorage.setItem("email",b);let f=O.get("user_id");f&&localStorage.setItem("user_id",f),await se(M,O.get("name")??void 0),await Y(M,W),R("desktop_login_complete_success",{method:"oauth",provider:"workos"}),w()}catch(b){if(b instanceof Error&&b.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),h();return}let f=b instanceof Error?b.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"oauth",provider:"workos",error:f}),console.error("Error completing WorkOS device authentication:",b),x(f)}return}try{let b=M,f=W;try{r.setCookies(M,W),await r.checkAndSetSession(),r.sessionData&&(b=r.sessionData.access_token,f=r.sessionData.refresh_token,r.setCookies(b,f),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}let m=r.sessionData?.user.email;if(fe&&m&&zr(m)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(Re)){sessionStorage.setItem(Re,"true"),R("desktop_login_workos_second_hop",{email_domain:m.split("@")[1]??"unknown"}),window.location.href=`${Cs}/authkit/google/sign_in?source=${Xr}`;return}await se(b,r.sessionData?.user.user_metadata?.full_name),await Y(b,f),R("desktop_login_complete_success",{method:"oauth"}),w()}catch(b){if(b instanceof Error&&b.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),h();return}let f=b instanceof Error?b.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"oauth",error:f}),console.error("Error completing device authentication:",b),x(f)}return}if(ie){console.log("Auto-signin enabled - checking existing session"),y();try{let v=r.checkAndSetSession(),b=new Promise((f,m)=>setTimeout(()=>m(new Error("Session timeout")),3e3));if(await Promise.race([v,b]),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token),r.sessionData?.access_token&&r.sessionData?.refresh_token){console.log("Existing session found - auto-completing authentication"),await se(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await Y(r.sessionData.access_token,r.sessionData.refresh_token),R("desktop_login_auto_signin_success",{token_provider:Fe(r.sessionData.access_token)}),w();return}console.log("No existing session - showing login form"),R("desktop_login_auto_signin_no_session"),P()}catch(v){if(console.error("Auto-signin error:",v),v instanceof Error&&v.message==="enterprise_ip_not_allowed"){R("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),h();return}let b=v instanceof Error?v.message:"Auto-signin failed. Please try logging in manually.";R("desktop_login_auto_signin_error",{error:b}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),P()}}else ne?(R("desktop_login_mcp_entry"),P()):(R("desktop_login_manual_signout"),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status"),P());let pe=v=>{console.log(`Redirecting to ${v} OAuth`);let b=window.posthog?.getFeatureFlag?.(mn)===!0,f=fe&&b;R("desktop_login_oauth_click",{provider:f?"workos":v,idp:v,mcp:!!ne,workos_capable:fe,workos_enabled_webflow:b}),localStorage.setItem("signin_provider",v);let m=f?`authkit/${v}/sign_in`:`${v}/sign_in`,k=`${Cs}/${m}?source=${Xr}`,S=sessionStorage.getItem("wispr_skip_default_trial"),j=sessionStorage.getItem("wispr_grant_weekly_bonus");S&&(k+=`&skip_default_trial=${encodeURIComponent(S)}`),j&&(k+=`&grant_weekly_bonus=${encodeURIComponent(j)}`),ne&&(k+=`&mcp_login_state=${encodeURIComponent(ne)}`),window.location.href=k};u&&u.addEventListener("click",()=>{pe("google")}),d&&d.addEventListener("click",()=>{pe("apple")}),p&&p.addEventListener("click",()=>{pe("microsoft")});let Rs=async(v,b,f)=>{try{await se(v,f),await Y(v,b)}catch(m){if(m instanceof Error&&m.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),h();return}let k=m instanceof Error?m.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"email",error:k}),x(k);return}R("desktop_login_complete_success",{method:"email"}),w()},bt=sessionStorage.getItem("wispr_device_code"),Ge=bt?`${window.location.origin}/login?device_code=${bt}`:`${window.location.origin}/login`,{reset:Yt}=Gr(Ge,{onLoginSuccess:Rs,mcpLoginState:ne,skipOAuthButtons:!0});_=Yt,Ce==="account_unsupported"&&(R("desktop_login_oauth_error",{error:Ce}),x("This account is not supported. Try signing in with another account.")),console.log("Desktop login page initialized")});})();
|