@tanay-wispr/webflow-package 6.8.6 → 6.8.8

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/downloads.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";(()=>{var Is=Object.create;var it=Object.defineProperty;var js=Object.getOwnPropertyDescriptor;var Ls=Object.getOwnPropertyNames;var $s=Object.getPrototypeOf,Us=Object.prototype.hasOwnProperty;var Ds=(s,e)=>()=>(s&&(e=s(s=0)),e);var W=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ns=(s,e)=>{for(var t in e)it(s,t,{get:e[t],enumerable:!0})},dr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ls(e))!Us.call(s,i)&&i!==t&&it(s,i,{get:()=>e[i],enumerable:!(r=js(e,i))||r.enumerable});return s};var hr=(s,e,t)=>(t=s!=null?Is($s(s)):{},dr(e||!s||!s.__esModule?it(t,"default",{value:s,enumerable:!0}):t,s)),qs=s=>dr(it({},"__esModule",{value:!0}),s);var se={};Ns(se,{Headers:()=>Lt,Request:()=>Ks,Response:()=>Vs,default:()=>jt,fetch:()=>Gs});var zs,_e,Gs,jt,Lt,Ks,Vs,Y=Ds(()=>{"use strict";zs=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")},_e=zs(),Gs=_e.fetch,jt=_e.fetch.bind(_e),Lt=_e.Headers,Ks=_e.Request,Vs=_e.Response});var Sr=W(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});var $t=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ut.default=$t});var Nt=W(Le=>{"use strict";var Er=Le&&Le.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Le,"__esModule",{value:!0});var Xs=Er((Y(),qs(se))),Qs=Er(Sr()),Dt=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=Xs.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let u=null,l=null,d=null,h=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=k:l=JSON.parse(k))}let y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");y&&_&&_.length>1&&(d=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,d=null,h=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{u=JSON.parse(y),Array.isArray(u)&&n.status===404&&(l=[],u=null,h=200,f="OK")}catch{n.status===404&&y===""?(h=204,f="No Content"):u={message:y}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,h=200,f="OK"),u&&this.shouldThrowOnError)throw new Qs.default(u)}return{error:u,data:l,count:d,status:h,statusText:f}});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)}};Le.default=Dt});var Mt=W($e=>{"use strict";var Zs=$e&&$e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($e,"__esModule",{value:!0});var ei=Zs(Nt()),qt=class extends ei.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};$e.default=qt});var ut=W(Ue=>{"use strict";var ti=Ue&&Ue.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ue,"__esModule",{value:!0});var ri=ti(Mt()),Ft=class extends ri.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};Ue.default=Ft});var Ht=W(Ne=>{"use strict";var si=Ne&&Ne.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ne,"__esModule",{value:!0});var De=si(ut()),Wt=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new De.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new De.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new De.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new De.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new De.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ne.default=Wt});var Tr=W(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.version=void 0;dt.version="0.0.0-automated"});var xr=W(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.DEFAULT_HEADERS=void 0;var ii=Tr();ht.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ii.version}`}});var Rr=W(qe=>{"use strict";var Ar=qe&&qe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(qe,"__esModule",{value:!0});var ni=Ar(Ht()),oi=Ar(ut()),ai=xr(),Bt=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ai.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ni.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([l,d])=>d!==void 0).map(([l,d])=>[l,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([l,d])=>{a.searchParams.append(l,d)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new oi.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};qe.default=Bt});var Lr=W(R=>{"use strict";var Me=R&&R.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(R,"__esModule",{value:!0});R.PostgrestBuilder=R.PostgrestTransformBuilder=R.PostgrestFilterBuilder=R.PostgrestQueryBuilder=R.PostgrestClient=void 0;var Pr=Me(Rr());R.PostgrestClient=Pr.default;var Or=Me(Ht());R.PostgrestQueryBuilder=Or.default;var Cr=Me(ut());R.PostgrestFilterBuilder=Cr.default;var Ir=Me(Mt());R.PostgrestTransformBuilder=Ir.default;var jr=Me(Nt());R.PostgrestBuilder=jr.default;R.default={PostgrestClient:Pr.default,PostgrestQueryBuilder:Or.default,PostgrestFilterBuilder:Cr.default,PostgrestTransformBuilder:Ir.default,PostgrestBuilder:jr.default}});var Hr=W((Jn,Wr)=>{"use strict";Wr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Oe=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var T=(s,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:s,retry_attempt:10-t}),window.posthog.capture(s,e)):t>0&&setTimeout(()=>T(s,e,t-1),200)},fr=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var pr=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,b="https://api.wisprflow.ai",re=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},ge=s=>s.trim().toLowerCase(),gr=(s,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof s.code=="string"?s.code:s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:typeof s.detail=="string"&&t.has(s.detail)?s.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},Ce=(s,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[s]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Ms=(s,e,t)=>[s.message,s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"?s.detail.message:null,typeof s.detail=="string"?s.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??Ce(e,t),me=(s,e)=>{let t=gr(s,e);return new re(e,t,Ms(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},Fs=(s,e)=>{let t=gr(s,e);return new re(e,t,Ce(t,e))},nt="promo_code",Ws=4e3,Hs=new Set([200,400,403,404,409,422]),mr=s=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},_r=s=>{if(!s)return"";try{return decodeURIComponent(s).trim()}catch{return""}},Ct=()=>{let s=Oe()[nt];if(s===void 0)return"";let e=_r(s);return e||mr(nt),e},It=s=>{_r(Oe()[nt])===s&&mr(nt)},Bs=s=>s instanceof DOMException&&(s.name==="TimeoutError"||s.name==="AbortError"),Js=(s,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:e===422?"validation_error":"unknown",Ot=class{static async signupUser(e){try{let t=`${b}/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(`${b}/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(`${b}/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(`${b}/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(`${b}/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=ge(e),r=await fetch(`${b}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw me(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${b}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:ge(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw me(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${b}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${b}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${b}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new re(422,"invalid_code",Ce("invalid_code",422));let t=await fetch(`${b}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok){let i=Fs(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new re(t.status,"verification_failed",Ce("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new re(t.status,"authentication_failed",Ce("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${b}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async applyPromoCodeFromCookie(e,t=Ct()){if(t)try{let r=await fetch(`${b}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(Ws)}),{status:i}=r;if(!Hs.has(i)){T("promo_cookie_apply",{outcome:"deferred",status:i});return}if(It(t),r.ok){T("promo_cookie_apply",{outcome:"attached",status:i});return}let n=await r.json().catch(()=>({}));T("promo_cookie_apply",{outcome:"rejected",status:i,reason:Js(n,i)})}catch(r){console.error("Promo cookie apply deferred:",r),T("promo_cookie_apply",Bs(r)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${b}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${b}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,r){let i=`${b}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`&currency=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${b}/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(`${b}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${b}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${b}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,r){let i=new FormData;return i.append("screenshot",e),await fetch(`${b}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function wr(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}var P=Ot;var yr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var vr=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var br=()=>{let{access_token:s,refresh_token:e}=vr(),t=s,r=e;if(!t||!r){let i=yr();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var kr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Y(),se)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var Ie=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},ot=class extends Ie{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},at=class extends Ie{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ct=class extends Ie{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},lt;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(lt||(lt={}));var Ys=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},je=class{constructor(e,{headers:t={},customFetch:r,region:i=lt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=kr(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return Ys(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(w=>{throw new ot(w)}),d=l.headers.get("x-relay-error");if(d&&d==="true")throw new at(l);if(!l.ok)throw new ct(l);let h=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return h==="application/json"?f=yield l.json():h==="application/octet-stream"?f=yield l.blob():h==="text/event-stream"?f=l:h==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var $r=hr(Lr(),1),{PostgrestClient:Ur,PostgrestQueryBuilder:xn,PostgrestFilterBuilder:An,PostgrestTransformBuilder:Rn,PostgrestBuilder:Pn}=$r.default;var Dr="2.10.2";var Nr={"X-Client-Info":`realtime-js/${Dr}`},qr="1.0.0",pt=1e4,Mr=1e3,ie;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(ie||(ie={}));var O;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(O||(O={}));var j;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(j||(j={}));var ft;(function(s){s.websocket="websocket"})(ft||(ft={}));var X;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(X||(X={}));var Fe=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let c=r.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var ne=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 v;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(v||(v={}));var zt=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=ci(o,s,e,i),n),{})},ci=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?Fr(n,o):Jt(o)},Fr=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return hi(e,t)}switch(s){case v.bool:return li(e);case v.float4:case v.float8:case v.int2:case v.int4:case v.int8:case v.numeric:case v.oid:return ui(e);case v.json:case v.jsonb:return di(e);case v.timestamp:return fi(e);case v.abstime:case v.date:case v.daterange:case v.int4range:case v.int8range:case v.money:case v.reltime:case v.text:case v.time:case v.timestamptz:case v.timetz:case v.tsrange:case v.tstzrange:return Jt(e);default:return Jt(e)}},Jt=s=>s,li=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},ui=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},di=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},hi=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Fr(e,a))}return s},fi=s=>typeof s=="string"?s.replace(" ","T"):s,gt=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var oe=class{constructor(e,t,r={},i=pt){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Gt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Gt||(Gt={}));var we=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=s.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let d=n[u];if(d){let h=l.map(_=>_.presence_ref),f=d.map(_=>_.presence_ref),w=l.filter(_=>f.indexOf(_.presence_ref)<0),y=d.filter(_=>h.indexOf(_.presence_ref)<0);w.length>0&&(a[u]=w),y.length>0&&(c[u]=y)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let d=e[a].map(f=>f.presence_ref),h=l.filter(f=>d.indexOf(f.presence_ref)<0);e[a].unshift(...h)}r(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(d=>d.presence_ref);u=u.filter(d=>l.indexOf(d.presence_ref)<0),e[a]=u,i(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Kt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Kt||(Kt={}));var Vt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(Vt||(Vt={}));var Yt;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Yt||(Yt={}));var ye=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=O.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 oe(this,j.join,this.params,this.timeout),this.rejoinTimer=new ne(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=O.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=O.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=O.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=O.errored,this.rejoinTimer.scheduleTimeout())}),this._on(j.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new we(this),this.broadcastEndpointURL=gt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let h=this.bindings.postgres_changes,f=(d=h?.length)!==null&&d!==void 0?d:0,w=[];for(let y=0;y<f;y++){let _=h[y],{filter:{event:k,schema:C,table:x,filter:L}}=_,$=l&&l[y];if($&&$.event===k&&$.schema===C&&$.table===x&&$.filter===L)w.push(Object.assign(Object.assign({},_),{id:$.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=w,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=O.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(j.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new oe(this,j.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new oe(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:u,join:l}=j;if(r&&[a,c,u,l].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,t,r);if(t&&!h)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(f=>{var w,y,_;return((w=f.filter)===null||w===void 0?void 0:w.event)==="*"||((_=(y=f.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(h,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var w,y,_,k,C,x;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let L=f.id,$=(w=f.filter)===null||w===void 0?void 0:w.event;return L&&((y=t.ids)===null||y===void 0?void 0:y.includes(L))&&($==="*"||$?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{let L=(C=(k=f?.filter)===null||k===void 0?void 0:k.event)===null||C===void 0?void 0:C.toLocaleLowerCase();return L==="*"||L===((x=t?.event)===null||x===void 0?void 0:x.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof h=="object"&&"ids"in h){let w=h.data,{schema:y,table:_,commit_timestamp:k,type:C,errors:x}=w;h=Object.assign(Object.assign({},{schema:y,table:_,commit_timestamp:k,eventType:C,new:{},old:{},errors:x}),this._getPayloadRecords(w))}f.callback(h,r)})}_isClosed(){return this.state===O.closed}_isJoined(){return this.state===O.joined}_isJoining(){return this.state===O.joining}_isLeaving(){return this.state===O.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(j.close,{},e)}_onError(e){this._on(j.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=O.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=zt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=zt(e.columns,e.old_record)),t}};var gi=()=>{},mi=typeof WebSocket<"u",ve=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Nr,this.params={},this.timeout=pt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=gi,this.conn=null,this.sendBuffer=[],this.serializer=new Fe,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(Y(),se)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${ft.websocket}`,this.httpEndpoint=gt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ne(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(mi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Xt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>hr(Hr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case ie.connecting:return X.Connecting;case ie.open:return X.Open;case ie.closing:return X.Closing;default:return X.Closed}}isConnected(){return this.connectionState()===X.Open}channel(e,t={config:{}}){let r=new ye(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(j.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:qr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(j.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Mr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Xt=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ie.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var be=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function S(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var mt=class extends be{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},We=class extends be{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var _i=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},_t=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Y(),se)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Br=()=>_i(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(Y(),se))).Response:Response});var ke=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Qt=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),wi=(s,e)=>ke(void 0,void 0,void 0,function*(){let t=yield Br();s instanceof t?s.json().then(r=>{e(new mt(Qt(r),s.status||500))}).catch(r=>{e(new We(Qt(r),r))}):e(new We(Qt(s),s))}),yi=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function wt(s,e,t,r,i,n){return ke(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,yi(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>wi(c,a))})})}function He(s,e,t,r){return ke(this,void 0,void 0,function*(){return wt(s,"GET",e,t,r)})}function H(s,e,t,r,i){return ke(this,void 0,void 0,function*(){return wt(s,"POST",e,r,i,t)})}function Jr(s,e,t,r,i){return ke(this,void 0,void 0,function*(){return wt(s,"PUT",e,r,i,t)})}function yt(s,e,t,r,i){return ke(this,void 0,void 0,function*(){return wt(s,"DELETE",e,r,i,t)})}var U=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},vi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},zr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Be=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=_t(i)}uploadOrUpdate(e,t,r,i){return U(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},zr),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield l.json();return l.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(S(n))return{data:null,error:n};throw n}})}upload(e,t,r){return U(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return U(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,u=Object.assign({upsert:zr.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),h=yield d.json();return d.ok?{data:{path:n,fullPath:h.Key},error:null}:{data:null,error:h}}catch(c){if(S(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return U(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield H(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new be("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}})}update(e,t,r){return U(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return U(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}copy(e,t,r){return U(this,void 0,void 0,function*(){try{return{data:{path:(yield H(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return U(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield H(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return U(this,void 0,void 0,function*(){try{let i=yield H(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}download(e,t){return U(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 He(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(S(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${u}`)}}}remove(e){return U(this,void 0,void 0,function*(){try{return{data:yield yt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}list(e,t,r){return U(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},vi),t),{prefix:e||""});return{data:yield H(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(S(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 Gr="2.6.0";var Kr={"X-Client-Info":`storage-js/${Gr}`};var Se=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Je=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Kr),t),this.fetch=_t(r)}listBuckets(){return Se(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(S(e))return{data:null,error:e};throw e}})}getBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Se(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Se(this,void 0,void 0,function*(){try{return{data:yield Jr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield yt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}};var ze=class extends Je{constructor(e,t={},r){super(e,t,r)}from(e){return new Be(this.url,this.headers,e,this.fetch)}};var Vr="2.44.4";var Ge="";typeof Deno<"u"?Ge="deno":typeof document<"u"?Ge="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ge="react-native":Ge="node";var bi={"X-Client-Info":`supabase-js-${Ge}/${Vr}`},Yr={headers:bi},Xr={schema:"public"},Qr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Zr={};Y();var ki=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Si=s=>{let e;return s?e=s:typeof fetch>"u"?e=jt:e=fetch,(...t)=>e(...t)},Ei=()=>typeof Headers>"u"?Lt:Headers,es=(s,e,t)=>{let r=Si(t),i=Ei();return(n,o)=>ki(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",s),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:u}))})};function ts(s){return s.replace(/\/$/,"")}function rs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var vt="2.64.4";var ss="http://localhost:9999",is="supabase.auth.token";var ns={"X-Client-Info":`gotrue-js/${vt}`},Zt=10;var Ke="X-Supabase-Api-Version",er={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function os(s){return Math.round(Date.now()/1e3)+s}function as(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var D=()=>typeof document<"u",ae={tested:!1,writable:!1},Q=()=>{if(!D())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ae.tested)return ae.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),ae.tested=!0,ae.writable=!0}catch{ae.tested=!0,ae.writable=!1}return ae.writable};function bt(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var kt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Y(),se)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},cs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",tr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ye=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},St=async(s,e)=>{await s.removeItem(e)};function Ti(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,u,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),u=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Ve=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Ve.promiseConstructor=Promise;function rr(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Ti(r))}async function ls(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function us(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function xi(s){return("0"+s.toString(16)).substr(-2)}function Ai(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,xi).join("")}async function Ri(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Pi(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Oi(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;let t=await Ri(s);return Pi(t)}async function ce(s,e,t=!1){let r=Ai(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await tr(s,`${e}-code-verifier`,i);let n=await Oi(r);return[n,r===n?"plain":"s256"]}var Ci=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ds(s){let e=s.headers.get(Ke);if(!e||!e.match(Ci))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Xe=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function p(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var Et=class extends Xe{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function hs(s){return p(s)&&s.name==="AuthApiError"}var Ee=class extends Xe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},G=class extends Xe{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},B=class extends G{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Te=class extends G{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},le=class extends G{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ue=class extends G{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}}},Qe=class extends G{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}}},xe=class extends G{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Tt(s){return p(s)&&s.name==="AuthRetryableFetchError"}var Ze=class extends G{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Ii=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},de=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ji=[502,503,504];async function fs(s){var e;if(!cs(s))throw new xe(de(s),0);if(ji.includes(s.status))throw new xe(de(s),s.status);let t;try{t=await s.json()}catch(n){throw new Ee(de(n),n)}let r,i=ds(s);if(i&&i.getTime()>=er["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Ze(de(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new Ze(de(t),s.status,t.weak_password.reasons);throw new Et(de(t),s.status||500,r)}var Li=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function m(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Ke]||(n[Ke]=er["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await $i(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function $i(s,e,t,r,i,n){let o=Li(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new xe(de(c),0)}if(a.ok||await fs(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await fs(c)}}function K(s){var e;let t=null;Ui(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=os(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function sr(s){let e=K(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function J(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function ps(s){return{data:s,error:null}}function gs(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Ii(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function ms(s){return s}function Ui(s){return s.access_token&&s.refresh_token&&s.expires_in}var Di=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},he=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=kt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(p(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:J})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Di(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:gs,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:J})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:ms});if(l.error)throw l.error;let d=await l.json(),h=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(w=>{let y=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(w.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(p(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:J})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:J})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:J})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var _s={getItem:s=>Q()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{Q()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{Q()&&globalThis.localStorage.removeItem(s)}};function ir(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function ws(){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 fe={debug:!!(globalThis&&Q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},et=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},xt=class extends et{};async function nr(s,e,t){fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),fe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new xt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(fe.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()}})}ws();var Ni={url:ss,storageKey:is,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ns,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},tt=30*1e3,ys=3;async function vs(s,e,t){return await t()}var pe=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&D()&&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({},Ni),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 he({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=kt(i.fetch),this.lock=i.lock||vs,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:D()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=nr:this.lock=vs,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:Q()?this.storage=_s:(this.memoryStorage={},this.storage=ir(this.memoryStorage)):(this.memoryStorage={},this.storage=ir(this.memoryStorage)),D()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${vt}) ${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=D()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return p(e)?{error:e}:{error:new Ee("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:K}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:l,password:d,options:h}=e,f=null,w=null;this.flowType==="pkce"&&([f,w]=await ce(this.storage,this.storageKey)),n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h?.emailRedirectTo,body:{email:l,password:d,data:(t=h?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:f,code_challenge_method:w},xform:K})}else if("phone"in e){let{phone:l,password:d,options:h}=e;n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:d,data:(r=h?.data)!==null&&r!==void 0?r:{},channel:(i=h?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:K})}else throw new le("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(p(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 m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:sr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:sr})}else throw new le("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Te}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ye(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:K});return await St(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 Te}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:K}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Te}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await ce(this.storage,this.storageKey));let{error:d}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:l}}throw new le("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:K});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await ce(this.storage,this.storageKey)),await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:ps})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new B;let{error:i}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await m(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await m(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new le("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ye(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,u,l)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:J}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new B}:await m(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:J})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new B;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await ce(this.storage,this.storageKey));let{data:u,error:l}=await m(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:J});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return rr(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 B;let t=Date.now()/1e3,r=t,i=!0,n=null,o=rr(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new B;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(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!D())throw new ue("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ue("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Qe("Not a valid PKCE flow url.");let t=bt(window.location.href);if(e){if(!t.code)throw new Qe("No code detected.");let{data:C,error:x}=await this._exchangeCodeForSession(t.code);if(x)throw x;let L=new URL(window.location.href);return L.searchParams.delete("code"),window.history.replaceState(window.history.state,"",L.toString()),{data:{session:C.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ue(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:u}=t;if(!n||!a||!o||!u)throw new ue("No session defined in URL");let l=Math.round(Date.now()/1e3),d=parseInt(a),h=l+d;c&&(h=parseInt(c));let f=h-l;f*1e3<=tt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${d}s`);let w=h-d;l-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,h,l):l-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",w,h,l);let{data:y,error:_}=await this._getUser(n);if(_)throw _;let k={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:h,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=bt(window.location.href);return!!(D()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=bt(window.location.href),t=await Ye(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(hs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await St(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=as(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await ce(this.storage,this.storageKey,!0));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,c,u,l;let{data:d,error:h}=n;if(h)throw h;let f=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 m(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return D()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(p(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await us(async i=>(i>0&&await ls(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:K})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Tt(n)&&Date.now()+o-r<tt})}catch(r){if(this._debug(t,"error",r),p(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),D()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ye(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Zt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Zt}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Tt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new B;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Ve;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new B;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),p(n)){let o={session:null,error:n};return Tt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await tr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await St(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&D()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),tt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/tt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${tt}ms, refresh threshold is ${ys} ticks`),i<=ys&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof et)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await ce(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await m(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};pe.nextInstanceID=0;var qi=pe,or=qi;var At=class extends or{constructor(e){super(e)}};var Mi=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},rt=class{constructor(e,t,r){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=ts(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:Xr,realtime:Zr,auth:Object.assign(Object.assign({},Qr),{storageKey:c}),global:Yr},l=rs(r??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=es(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Ur(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new je(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ze(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Mi(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},c,u){var l;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new At({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new ve(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var bs=(s,e,t)=>new rt(s,e,t);var V={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Fi=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Rt=s=>{let[e,t]=s.split(".");return!e||!t?null:Fi(t)},ks=s=>{let e=Rt(s);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Wi="https://api.workos.com",Hi=60,Ae=(s,e)=>typeof s[e]=="string"?s[e]:void 0,Ss=(s,e,t)=>{let r=Rt(s);if(!r)return null;let i=Ae(r,"urn:wispr:user_external_id")??Ae(r,"sub"),n=t?.email??Ae(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,c={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},Bi=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Wi,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:s,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},Es=async(s,e)=>{let t=Rt(s);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=Ae(t,"client_id");if(i-r<Hi&&n){let c=await Bi(e,n,Ae(t,"iss"),Ae(t,"org_id")),u=Ss(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=r)throw new Error("WorkOS session expired");let a=Ss(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Pt=class{constructor(){this.sessionData=null;this.supabase=bs(V.supaBaseUrl,V.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||V.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||V.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||V.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{if(ks(t)==="workos"){this.sessionData=await Es(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||V.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=o?.deviceCode,c=a&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?a:void 0,u=await P.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,device_code:c,redirect_url:i||V.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),u}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await P.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(pr(n))return{kind:"otp",challenge:n};if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0,provider:n.provider||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await P.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||V.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 Ji="wf_first_landing_url";var Ts=()=>{try{return localStorage.getItem(Ji)||void 0}catch{return}};function xs(s){try{let e=s._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let r=t.split(".");if(r.length>=3){let i=r.slice(2).join(".");if(i)return i}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}function zi(){try{let s=document.createElement("canvas"),e=s.getContext("webgl")||s.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info");if(!t)return"mac_unknown";let r=e.getParameter(t.UNMASKED_RENDERER_WEBGL);console.log(`WebGL Renderer: ${r}`);let i=String(r||"").toLowerCase();return i.includes("apple gpu")?"mac_unknown":i.includes("apple")?"mac_m1":i.includes("intel")||i.includes("amd")||i.includes("nvidia")?"mac_intel":"mac_unknown"}}catch{}return"mac_unknown"}var As=async()=>{if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return"iOS";try{let s=await navigator.userAgentData.getHighEntropyValues(["architecture","platform"]);if(s.platform==="Chrome OS")return"ChromeOS";if(s.platform==="macOS")return s.architecture&&s.architecture.includes("arm")?"mac_m1":s.architecture&&s.architecture.includes("x86")?"mac_intel":"mac_unknown";if(s.platform==="Windows"){if(s.architecture&&s.architecture.includes("x86"))return"Windows";if(s.architecture&&s.architecture.includes("arm"))return"win_unknown";if(!s.architecture){let{userAgent:e}=navigator;return/ARM64/i.test(e)?"win_unknown":/(Win64;\s*x64|WOW64)/i.test(e)?"Windows":"win_unknown"}return"win_unknown"}return s.platform}catch{let{userAgent:s}=navigator;return s.includes("CrOS")?"ChromeOS":s.includes("Macintosh")?zi():s.includes("Windows")?/ARM64/i.test(s)?"win_unknown":"Windows":s.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(s)?"iOS":/Android/.test(s)?"Android":"Unknown"}};var Re=!1;window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=sessionStorage.getItem("referral_status");s&&console.log("raw email signup:",JSON.parse(s));let e=new URLSearchParams(window.location.search),t=e.get("referral"),r=e.get("plan"),i=e.get("stripe_checkout_success"),n=e.get("team_invite_code");console.log("Referral queryparam:",t),console.log("Plan queryparam:",r);let o=!1,a=setTimeout(()=>{o||(document.body.style.visibility="visible")},4e3),c=new Pt,{accessToken:u,refreshToken:l}=br(),d=window.location.hash.includes("access_token="),h;try{h=await As()}catch(g){console.error("Platform detection failed:",g),h="Unknown"}let f=localStorage.getItem("email");if((t||r)&&f&&(!u||!l)){window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"early_exit_email_no_tokens",plan:r,referral:t,stored_email:f,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),timestamp:Date.now()})),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),window.location.href=`/get-started${window.location.search}`;return}if(i==="true"){let g=await P.getSubscriptionStatus(u);if(g.ok&&(await g.json()).is_subscribed){document.querySelectorAll("[payment-success]").forEach(A=>{A.style.display="block"});let I=document.querySelector("[default-h1]");I&&(I.textContent="Congrats, Flow Pro user, your download has started!");let F=localStorage.getItem("email");F&&document.querySelectorAll("[email-address]").forEach(A=>{A.textContent=F}),T("stripe_checkout_success",{email:F,device_type:h,source:"downloads_page",plan:localStorage.getItem("checkout_plan")}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"stripe_checkout_success",device_type:h,source:"downloads_page",plan:localStorage.getItem("checkout_plan"),user_external_id:localStorage.getItem("wispr_visitor_id")||void 0})}localStorage.removeItem("checkout_plan")}else localStorage.removeItem("checkout_plan");let w=document.querySelector("#hello-text"),y=document.querySelector("#logout-button");y.style.display="none";let _=Oe(),{dub_id:k,referral:C}=_,x=Ct();if(u&&l)try{c.setCookies(u,l),await c.checkAndSetSession(),c.sessionData&&c.setCookies(c.sessionData.access_token,c.sessionData.refresh_token);let g=c.sessionData?.access_token??u,E=c.sessionData?.user.email,z=c.sessionData?.user.user_metadata.full_name||" ",[I,F]=wr(z),A=c.sessionData?.user.id,ee=localStorage.getItem("wf_utm_source")||void 0,N=localStorage.getItem("wf_utm_medium")||void 0,cr=localStorage.getItem("wf_utm_campaign")||void 0,Ps={access_token:g,first_name:I,last_name:F,dub_click_id:k||void 0,referral:C||void 0,promo_code:x||void 0,team_invite_code:n||void 0,utm:ee||N||cr?{utm_source:ee,utm_medium:N,utm_campaign:cr}:void 0,first_landing_url:Ts()};localStorage.setItem("email",E),A&&localStorage.setItem("user_id",A);let lr=localStorage.getItem("signin_provider");lr&&localStorage.setItem("last_authed_provider",lr),A&&fr(A,{email:E,firstName:I,lastName:F});let ur=!1;try{if(!localStorage.getItem("conversion_sent")||t||n){let q=await P.signupUser(Ps);x&&(It(x),ur=!0),t&&(Yi(q),console.log("OAuth signup response:",q),console.log("Showing referral UI"))}}catch(q){console.error("Non-fatal: /signup API failed, user remains authenticated:",q),window.posthog?.startSessionRecording?.(),T("signup_sync_error",{error_message:q instanceof Error?q.message:String(q),email:E,user_id:A,signin_provider:localStorage.getItem("signin_provider")||"unknown",is_oauth_callback:d})}if(localStorage.getItem("conversion_sent")||((async()=>{let q=te=>new Promise(Pe=>{if(typeof window.gtag!="function"){Pe(void 0);return}let Os=setTimeout(()=>Pe(void 0),1e3);window.gtag("get","G-2JTM45W1TF",te,Cs=>{clearTimeout(Os),Pe(Cs)})}),[M,st]=await Promise.all([q("client_id"),q("session_id")]);fetch("https://api.wisprflow.ai/api/v1/tracking/events",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event_name:"app_download",event_id:crypto.randomUUID(),wispr_user_id:A||void 0,email:E||void 0,fbp:_._fbp||void 0,fbc:_._fbc||void 0,gclid:xs(_),ga_client_id:M,ga_session_id:st})}).catch(()=>{})})().catch(()=>{}),await Gi(h,k,C,E)),ur||await P.applyPromoCodeFromCookie(g,x),w.textContent=`Hi ${I}!`,y.style.display="flex",r&&g){if(!["FLOW_PRO_MONTHLY","FLOW_PRO_YEARLY"].includes(r)){window.location.href=t?`/downloads?referral=${t}`:"/downloads";return}document.body.innerHTML='<div style="display: flex; padding-left: 20px; padding-right: 20px; text-align: center; justify-content: center; align-items: center; height: 100vh;"><h3>Checking your subscription...</h3></div>',document.body.style.visibility="visible";try{let M=await P.getSubscriptionStatus(g);if(M.status===401){console.log("Subscription API failed: Token expired"),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"subscription_check_401",plan:r,referral:t,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),await ar(r,t,c);return}if(M.ok){let st=await M.json();if(st.is_subscribed){let te=window.location.pathname;window.history.pushState({},"",te),document.body.innerHTML=`
1
+ "use strict";(()=>{var Is=Object.create;var it=Object.defineProperty;var js=Object.getOwnPropertyDescriptor;var $s=Object.getOwnPropertyNames;var Ls=Object.getPrototypeOf,Us=Object.prototype.hasOwnProperty;var Ds=(s,e)=>()=>(s&&(e=s(s=0)),e);var W=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ns=(s,e)=>{for(var t in e)it(s,t,{get:e[t],enumerable:!0})},dr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $s(e))!Us.call(s,i)&&i!==t&&it(s,i,{get:()=>e[i],enumerable:!(r=js(e,i))||r.enumerable});return s};var hr=(s,e,t)=>(t=s!=null?Is(Ls(s)):{},dr(e||!s||!s.__esModule?it(t,"default",{value:s,enumerable:!0}):t,s)),qs=s=>dr(it({},"__esModule",{value:!0}),s);var se={};Ns(se,{Headers:()=>$t,Request:()=>Ks,Response:()=>Vs,default:()=>jt,fetch:()=>Gs});var zs,_e,Gs,jt,$t,Ks,Vs,Y=Ds(()=>{"use strict";zs=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")},_e=zs(),Gs=_e.fetch,jt=_e.fetch.bind(_e),$t=_e.Headers,Ks=_e.Request,Vs=_e.Response});var Sr=W(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});var Lt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ut.default=Lt});var Nt=W($e=>{"use strict";var Er=$e&&$e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($e,"__esModule",{value:!0});var Xs=Er((Y(),qs(se))),Qs=Er(Sr()),Dt=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=Xs.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let u=null,l=null,d=null,h=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=k:l=JSON.parse(k))}let y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");y&&_&&_.length>1&&(d=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,d=null,h=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{u=JSON.parse(y),Array.isArray(u)&&n.status===404&&(l=[],u=null,h=200,f="OK")}catch{n.status===404&&y===""?(h=204,f="No Content"):u={message:y}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,h=200,f="OK"),u&&this.shouldThrowOnError)throw new Qs.default(u)}return{error:u,data:l,count:d,status:h,statusText:f}});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)}};$e.default=Dt});var Mt=W(Le=>{"use strict";var Zs=Le&&Le.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Le,"__esModule",{value:!0});var ei=Zs(Nt()),qt=class extends ei.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Le.default=qt});var ut=W(Ue=>{"use strict";var ti=Ue&&Ue.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ue,"__esModule",{value:!0});var ri=ti(Mt()),Ft=class extends ri.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};Ue.default=Ft});var Ht=W(Ne=>{"use strict";var si=Ne&&Ne.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ne,"__esModule",{value:!0});var De=si(ut()),Wt=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new De.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new De.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new De.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new De.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new De.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ne.default=Wt});var Tr=W(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.version=void 0;dt.version="0.0.0-automated"});var xr=W(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.DEFAULT_HEADERS=void 0;var ii=Tr();ht.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ii.version}`}});var Rr=W(qe=>{"use strict";var Ar=qe&&qe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(qe,"__esModule",{value:!0});var ni=Ar(Ht()),oi=Ar(ut()),ai=xr(),Bt=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ai.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ni.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([l,d])=>d!==void 0).map(([l,d])=>[l,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([l,d])=>{a.searchParams.append(l,d)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new oi.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};qe.default=Bt});var $r=W(R=>{"use strict";var Me=R&&R.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(R,"__esModule",{value:!0});R.PostgrestBuilder=R.PostgrestTransformBuilder=R.PostgrestFilterBuilder=R.PostgrestQueryBuilder=R.PostgrestClient=void 0;var Pr=Me(Rr());R.PostgrestClient=Pr.default;var Or=Me(Ht());R.PostgrestQueryBuilder=Or.default;var Cr=Me(ut());R.PostgrestFilterBuilder=Cr.default;var Ir=Me(Mt());R.PostgrestTransformBuilder=Ir.default;var jr=Me(Nt());R.PostgrestBuilder=jr.default;R.default={PostgrestClient:Pr.default,PostgrestQueryBuilder:Or.default,PostgrestFilterBuilder:Cr.default,PostgrestTransformBuilder:Ir.default,PostgrestBuilder:jr.default}});var Hr=W((Jn,Wr)=>{"use strict";Wr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Oe=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var T=(s,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:s,retry_attempt:10-t}),window.posthog.capture(s,e)):t>0&&setTimeout(()=>T(s,e,t-1),200)},fr=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var pr=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,b="https://api.wisprflow.ai",re=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},ge=s=>s.trim().toLowerCase(),gr=(s,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof s.code=="string"?s.code:s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:typeof s.detail=="string"&&t.has(s.detail)?s.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},Ce=(s,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[s]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Ms=(s,e,t)=>[s.message,s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"?s.detail.message:null,typeof s.detail=="string"?s.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??Ce(e,t),me=(s,e)=>{let t=gr(s,e);return new re(e,t,Ms(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},Fs=(s,e)=>{let t=gr(s,e);return new re(e,t,Ce(t,e))},nt="promo_code",Ws=4e3,Hs=new Set([200,400,403,404,409,422]),mr=s=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},_r=s=>{if(!s)return"";try{return decodeURIComponent(s).trim()}catch{return""}},Ct=()=>{let s=Oe()[nt];if(s===void 0)return"";let e=_r(s);return e||mr(nt),e},It=s=>{_r(Oe()[nt])===s&&mr(nt)},Bs=s=>s instanceof DOMException&&(s.name==="TimeoutError"||s.name==="AbortError"),Js=(s,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:e===422?"validation_error":"unknown",Ot=class{static async signupUser(e){try{let t=`${b}/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(`${b}/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(`${b}/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(`${b}/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(`${b}/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=ge(e),r=await fetch(`${b}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw me(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${b}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:ge(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw me(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${b}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${b}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${b}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new re(422,"invalid_code",Ce("invalid_code",422));let t=await fetch(`${b}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok){let i=Fs(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new re(t.status,"verification_failed",Ce("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new re(t.status,"authentication_failed",Ce("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${b}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:ge(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw me(r,t.status);return r}static async applyPromoCodeFromCookie(e,t=Ct()){if(t)try{let r=await fetch(`${b}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(Ws)}),{status:i}=r;if(!Hs.has(i)){T("promo_cookie_apply",{outcome:"deferred",status:i});return}if(It(t),r.ok){T("promo_cookie_apply",{outcome:"attached",status:i});return}let n=await r.json().catch(()=>({}));T("promo_cookie_apply",{outcome:"rejected",status:i,reason:Js(n,i)})}catch(r){console.error("Promo cookie apply deferred:",r),T("promo_cookie_apply",Bs(r)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${b}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${b}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,r){let i=`${b}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`&currency=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${b}/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(`${b}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${b}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${b}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,r){let i=new FormData;return i.append("screenshot",e),await fetch(`${b}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function wr(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}var P=Ot;var yr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var vr=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var br=()=>{let{access_token:s,refresh_token:e}=vr(),t=s,r=e;if(!t||!r){let i=yr();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var kr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Y(),se)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var Ie=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},ot=class extends Ie{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},at=class extends Ie{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ct=class extends Ie{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},lt;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(lt||(lt={}));var Ys=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},je=class{constructor(e,{headers:t={},customFetch:r,region:i=lt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=kr(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return Ys(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(w=>{throw new ot(w)}),d=l.headers.get("x-relay-error");if(d&&d==="true")throw new at(l);if(!l.ok)throw new ct(l);let h=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return h==="application/json"?f=yield l.json():h==="application/octet-stream"?f=yield l.blob():h==="text/event-stream"?f=l:h==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var Lr=hr($r(),1),{PostgrestClient:Ur,PostgrestQueryBuilder:xn,PostgrestFilterBuilder:An,PostgrestTransformBuilder:Rn,PostgrestBuilder:Pn}=Lr.default;var Dr="2.10.2";var Nr={"X-Client-Info":`realtime-js/${Dr}`},qr="1.0.0",pt=1e4,Mr=1e3,ie;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(ie||(ie={}));var O;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(O||(O={}));var j;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(j||(j={}));var ft;(function(s){s.websocket="websocket"})(ft||(ft={}));var X;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(X||(X={}));var Fe=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let c=r.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var ne=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 v;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(v||(v={}));var zt=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=ci(o,s,e,i),n),{})},ci=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?Fr(n,o):Jt(o)},Fr=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return hi(e,t)}switch(s){case v.bool:return li(e);case v.float4:case v.float8:case v.int2:case v.int4:case v.int8:case v.numeric:case v.oid:return ui(e);case v.json:case v.jsonb:return di(e);case v.timestamp:return fi(e);case v.abstime:case v.date:case v.daterange:case v.int4range:case v.int8range:case v.money:case v.reltime:case v.text:case v.time:case v.timestamptz:case v.timetz:case v.tsrange:case v.tstzrange:return Jt(e);default:return Jt(e)}},Jt=s=>s,li=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},ui=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},di=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},hi=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Fr(e,a))}return s},fi=s=>typeof s=="string"?s.replace(" ","T"):s,gt=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var oe=class{constructor(e,t,r={},i=pt){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Gt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Gt||(Gt={}));var we=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=s.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let d=n[u];if(d){let h=l.map(_=>_.presence_ref),f=d.map(_=>_.presence_ref),w=l.filter(_=>f.indexOf(_.presence_ref)<0),y=d.filter(_=>h.indexOf(_.presence_ref)<0);w.length>0&&(a[u]=w),y.length>0&&(c[u]=y)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let d=e[a].map(f=>f.presence_ref),h=l.filter(f=>d.indexOf(f.presence_ref)<0);e[a].unshift(...h)}r(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(d=>d.presence_ref);u=u.filter(d=>l.indexOf(d.presence_ref)<0),e[a]=u,i(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Kt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Kt||(Kt={}));var Vt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(Vt||(Vt={}));var Yt;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Yt||(Yt={}));var ye=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=O.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 oe(this,j.join,this.params,this.timeout),this.rejoinTimer=new ne(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=O.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=O.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=O.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=O.errored,this.rejoinTimer.scheduleTimeout())}),this._on(j.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new we(this),this.broadcastEndpointURL=gt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let h=this.bindings.postgres_changes,f=(d=h?.length)!==null&&d!==void 0?d:0,w=[];for(let y=0;y<f;y++){let _=h[y],{filter:{event:k,schema:C,table:x,filter:$}}=_,L=l&&l[y];if(L&&L.event===k&&L.schema===C&&L.table===x&&L.filter===$)w.push(Object.assign(Object.assign({},_),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=w,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=O.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(j.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new oe(this,j.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new oe(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:u,join:l}=j;if(r&&[a,c,u,l].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,t,r);if(t&&!h)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(f=>{var w,y,_;return((w=f.filter)===null||w===void 0?void 0:w.event)==="*"||((_=(y=f.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(h,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var w,y,_,k,C,x;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let $=f.id,L=(w=f.filter)===null||w===void 0?void 0:w.event;return $&&((y=t.ids)===null||y===void 0?void 0:y.includes($))&&(L==="*"||L?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{let $=(C=(k=f?.filter)===null||k===void 0?void 0:k.event)===null||C===void 0?void 0:C.toLocaleLowerCase();return $==="*"||$===((x=t?.event)===null||x===void 0?void 0:x.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof h=="object"&&"ids"in h){let w=h.data,{schema:y,table:_,commit_timestamp:k,type:C,errors:x}=w;h=Object.assign(Object.assign({},{schema:y,table:_,commit_timestamp:k,eventType:C,new:{},old:{},errors:x}),this._getPayloadRecords(w))}f.callback(h,r)})}_isClosed(){return this.state===O.closed}_isJoined(){return this.state===O.joined}_isJoining(){return this.state===O.joining}_isLeaving(){return this.state===O.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(j.close,{},e)}_onError(e){this._on(j.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=O.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=zt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=zt(e.columns,e.old_record)),t}};var gi=()=>{},mi=typeof WebSocket<"u",ve=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Nr,this.params={},this.timeout=pt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=gi,this.conn=null,this.sendBuffer=[],this.serializer=new Fe,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(Y(),se)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${ft.websocket}`,this.httpEndpoint=gt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ne(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(mi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Xt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>hr(Hr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case ie.connecting:return X.Connecting;case ie.open:return X.Open;case ie.closing:return X.Closing;default:return X.Closed}}isConnected(){return this.connectionState()===X.Open}channel(e,t={config:{}}){let r=new ye(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(j.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:qr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(j.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Mr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Xt=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ie.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var be=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function S(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var mt=class extends be{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},We=class extends be{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var _i=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},_t=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Y(),se)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Br=()=>_i(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(Y(),se))).Response:Response});var ke=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Qt=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),wi=(s,e)=>ke(void 0,void 0,void 0,function*(){let t=yield Br();s instanceof t?s.json().then(r=>{e(new mt(Qt(r),s.status||500))}).catch(r=>{e(new We(Qt(r),r))}):e(new We(Qt(s),s))}),yi=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function wt(s,e,t,r,i,n){return ke(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,yi(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>wi(c,a))})})}function He(s,e,t,r){return ke(this,void 0,void 0,function*(){return wt(s,"GET",e,t,r)})}function H(s,e,t,r,i){return ke(this,void 0,void 0,function*(){return wt(s,"POST",e,r,i,t)})}function Jr(s,e,t,r,i){return ke(this,void 0,void 0,function*(){return wt(s,"PUT",e,r,i,t)})}function yt(s,e,t,r,i){return ke(this,void 0,void 0,function*(){return wt(s,"DELETE",e,r,i,t)})}var U=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},vi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},zr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Be=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=_t(i)}uploadOrUpdate(e,t,r,i){return U(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},zr),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield l.json();return l.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(S(n))return{data:null,error:n};throw n}})}upload(e,t,r){return U(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return U(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,u=Object.assign({upsert:zr.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),h=yield d.json();return d.ok?{data:{path:n,fullPath:h.Key},error:null}:{data:null,error:h}}catch(c){if(S(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return U(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield H(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new be("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}})}update(e,t,r){return U(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return U(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}copy(e,t,r){return U(this,void 0,void 0,function*(){try{return{data:{path:(yield H(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return U(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield H(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return U(this,void 0,void 0,function*(){try{let i=yield H(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(S(i))return{data:null,error:i};throw i}})}download(e,t){return U(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 He(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(S(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${u}`)}}}remove(e){return U(this,void 0,void 0,function*(){try{return{data:yield yt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}list(e,t,r){return U(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},vi),t),{prefix:e||""});return{data:yield H(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(S(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 Gr="2.6.0";var Kr={"X-Client-Info":`storage-js/${Gr}`};var Se=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Je=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Kr),t),this.fetch=_t(r)}listBuckets(){return Se(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(S(e))return{data:null,error:e};throw e}})}getBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Se(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Se(this,void 0,void 0,function*(){try{return{data:yield Jr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield yt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}})}};var ze=class extends Je{constructor(e,t={},r){super(e,t,r)}from(e){return new Be(this.url,this.headers,e,this.fetch)}};var Vr="2.44.4";var Ge="";typeof Deno<"u"?Ge="deno":typeof document<"u"?Ge="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ge="react-native":Ge="node";var bi={"X-Client-Info":`supabase-js-${Ge}/${Vr}`},Yr={headers:bi},Xr={schema:"public"},Qr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Zr={};Y();var ki=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Si=s=>{let e;return s?e=s:typeof fetch>"u"?e=jt:e=fetch,(...t)=>e(...t)},Ei=()=>typeof Headers>"u"?$t:Headers,es=(s,e,t)=>{let r=Si(t),i=Ei();return(n,o)=>ki(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",s),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:u}))})};function ts(s){return s.replace(/\/$/,"")}function rs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var vt="2.64.4";var ss="http://localhost:9999",is="supabase.auth.token";var ns={"X-Client-Info":`gotrue-js/${vt}`},Zt=10;var Ke="X-Supabase-Api-Version",er={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function os(s){return Math.round(Date.now()/1e3)+s}function as(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var D=()=>typeof document<"u",ae={tested:!1,writable:!1},Q=()=>{if(!D())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ae.tested)return ae.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),ae.tested=!0,ae.writable=!0}catch{ae.tested=!0,ae.writable=!1}return ae.writable};function bt(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var kt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Y(),se)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},cs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",tr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ye=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},St=async(s,e)=>{await s.removeItem(e)};function Ti(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,u,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),u=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Ve=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Ve.promiseConstructor=Promise;function rr(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Ti(r))}async function ls(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function us(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function xi(s){return("0"+s.toString(16)).substr(-2)}function Ai(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,xi).join("")}async function Ri(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Pi(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Oi(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;let t=await Ri(s);return Pi(t)}async function ce(s,e,t=!1){let r=Ai(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await tr(s,`${e}-code-verifier`,i);let n=await Oi(r);return[n,r===n?"plain":"s256"]}var Ci=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ds(s){let e=s.headers.get(Ke);if(!e||!e.match(Ci))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Xe=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function p(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var Et=class extends Xe{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function hs(s){return p(s)&&s.name==="AuthApiError"}var Ee=class extends Xe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},G=class extends Xe{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},B=class extends G{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Te=class extends G{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},le=class extends G{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ue=class extends G{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}}},Qe=class extends G{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}}},xe=class extends G{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Tt(s){return p(s)&&s.name==="AuthRetryableFetchError"}var Ze=class extends G{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Ii=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},de=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ji=[502,503,504];async function fs(s){var e;if(!cs(s))throw new xe(de(s),0);if(ji.includes(s.status))throw new xe(de(s),s.status);let t;try{t=await s.json()}catch(n){throw new Ee(de(n),n)}let r,i=ds(s);if(i&&i.getTime()>=er["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Ze(de(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new Ze(de(t),s.status,t.weak_password.reasons);throw new Et(de(t),s.status||500,r)}var $i=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function m(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Ke]||(n[Ke]=er["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Li(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Li(s,e,t,r,i,n){let o=$i(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new xe(de(c),0)}if(a.ok||await fs(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await fs(c)}}function K(s){var e;let t=null;Ui(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=os(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function sr(s){let e=K(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function J(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function ps(s){return{data:s,error:null}}function gs(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Ii(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function ms(s){return s}function Ui(s){return s.access_token&&s.refresh_token&&s.expires_in}var Di=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},he=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=kt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(p(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:J})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Di(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:gs,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:J})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:ms});if(l.error)throw l.error;let d=await l.json(),h=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(w=>{let y=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(w.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(p(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:J})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:J})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:J})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var _s={getItem:s=>Q()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{Q()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{Q()&&globalThis.localStorage.removeItem(s)}};function ir(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function ws(){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 fe={debug:!!(globalThis&&Q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},et=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},xt=class extends et{};async function nr(s,e,t){fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),fe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new xt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(fe.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()}})}ws();var Ni={url:ss,storageKey:is,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ns,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},tt=30*1e3,ys=3;async function vs(s,e,t){return await t()}var pe=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&D()&&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({},Ni),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 he({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=kt(i.fetch),this.lock=i.lock||vs,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:D()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=nr:this.lock=vs,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:Q()?this.storage=_s:(this.memoryStorage={},this.storage=ir(this.memoryStorage)):(this.memoryStorage={},this.storage=ir(this.memoryStorage)),D()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${vt}) ${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=D()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return p(e)?{error:e}:{error:new Ee("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:K}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:l,password:d,options:h}=e,f=null,w=null;this.flowType==="pkce"&&([f,w]=await ce(this.storage,this.storageKey)),n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h?.emailRedirectTo,body:{email:l,password:d,data:(t=h?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:f,code_challenge_method:w},xform:K})}else if("phone"in e){let{phone:l,password:d,options:h}=e;n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:d,data:(r=h?.data)!==null&&r!==void 0?r:{},channel:(i=h?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:K})}else throw new le("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(p(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 m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:sr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:sr})}else throw new le("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Te}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ye(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:K});return await St(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 Te}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:K}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Te}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await ce(this.storage,this.storageKey));let{error:d}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:l}}throw new le("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:K});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await ce(this.storage,this.storageKey)),await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:ps})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new B;let{error:i}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await m(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await m(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new le("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ye(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,u,l)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:J}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new B}:await m(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:J})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new B;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await ce(this.storage,this.storageKey));let{data:u,error:l}=await m(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:J});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return rr(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 B;let t=Date.now()/1e3,r=t,i=!0,n=null,o=rr(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new B;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(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!D())throw new ue("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ue("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Qe("Not a valid PKCE flow url.");let t=bt(window.location.href);if(e){if(!t.code)throw new Qe("No code detected.");let{data:C,error:x}=await this._exchangeCodeForSession(t.code);if(x)throw x;let $=new URL(window.location.href);return $.searchParams.delete("code"),window.history.replaceState(window.history.state,"",$.toString()),{data:{session:C.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ue(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:u}=t;if(!n||!a||!o||!u)throw new ue("No session defined in URL");let l=Math.round(Date.now()/1e3),d=parseInt(a),h=l+d;c&&(h=parseInt(c));let f=h-l;f*1e3<=tt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${d}s`);let w=h-d;l-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,h,l):l-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",w,h,l);let{data:y,error:_}=await this._getUser(n);if(_)throw _;let k={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:h,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=bt(window.location.href);return!!(D()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=bt(window.location.href),t=await Ye(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(hs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await St(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=as(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await ce(this.storage,this.storageKey,!0));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,c,u,l;let{data:d,error:h}=n;if(h)throw h;let f=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 m(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return D()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(p(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await us(async i=>(i>0&&await ls(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:K})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Tt(n)&&Date.now()+o-r<tt})}catch(r){if(this._debug(t,"error",r),p(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),D()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ye(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Zt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Zt}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Tt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new B;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Ve;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new B;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),p(n)){let o={session:null,error:n};return Tt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await tr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await St(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&D()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),tt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/tt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${tt}ms, refresh threshold is ${ys} ticks`),i<=ys&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof et)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await ce(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await m(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};pe.nextInstanceID=0;var qi=pe,or=qi;var At=class extends or{constructor(e){super(e)}};var Mi=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},rt=class{constructor(e,t,r){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=ts(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:Xr,realtime:Zr,auth:Object.assign(Object.assign({},Qr),{storageKey:c}),global:Yr},l=rs(r??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=es(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Ur(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new je(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ze(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Mi(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},c,u){var l;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new At({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new ve(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var bs=(s,e,t)=>new rt(s,e,t);var V={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Fi=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Rt=s=>{let[e,t]=s.split(".");return!e||!t?null:Fi(t)},ks=s=>{let e=Rt(s);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Wi="https://api.workos.com",Hi=60,Ae=(s,e)=>typeof s[e]=="string"?s[e]:void 0,Ss=(s,e,t)=>{let r=Rt(s);if(!r)return null;let i=Ae(r,"urn:wispr:user_external_id")??Ae(r,"sub"),n=t?.email??Ae(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,c={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},Bi=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Wi,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:s,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},Es=async(s,e)=>{let t=Rt(s);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=Ae(t,"client_id");if(i-r<Hi&&n){let c=await Bi(e,n,Ae(t,"iss"),Ae(t,"org_id")),u=Ss(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=r)throw new Error("WorkOS session expired");let a=Ss(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Pt=class{constructor(){this.sessionData=null;this.supabase=bs(V.supaBaseUrl,V.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||V.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||V.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||V.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{if(ks(t)==="workos"){this.sessionData=await Es(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||V.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=o?.deviceCode,c=a&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?a:void 0,u=await P.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,device_code:c,redirect_url:i||V.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),u}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await P.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(pr(n))return{kind:"otp",challenge:n};if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0,provider:n.provider||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await P.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||V.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 Ji="wf_first_landing_url";var Ts=()=>{try{return localStorage.getItem(Ji)||void 0}catch{return}};function xs(s){try{let e=s._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let r=t.split(".");if(r.length>=3){let i=r.slice(2).join(".");if(i)return i}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}function zi(){try{let s=document.createElement("canvas"),e=s.getContext("webgl")||s.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info");if(!t)return"mac_unknown";let r=e.getParameter(t.UNMASKED_RENDERER_WEBGL);console.log(`WebGL Renderer: ${r}`);let i=String(r||"").toLowerCase();return i.includes("apple gpu")?"mac_unknown":i.includes("apple")?"mac_m1":i.includes("intel")||i.includes("amd")||i.includes("nvidia")?"mac_intel":"mac_unknown"}}catch{}return"mac_unknown"}var As=async()=>{if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return"iOS";try{let s=await navigator.userAgentData.getHighEntropyValues(["architecture","platform"]);if(s.platform==="Chrome OS")return"ChromeOS";if(s.platform==="macOS")return s.architecture&&s.architecture.includes("arm")?"mac_m1":s.architecture&&s.architecture.includes("x86")?"mac_intel":"mac_unknown";if(s.platform==="Windows"){if(s.architecture&&s.architecture.includes("x86"))return"Windows";if(s.architecture&&s.architecture.includes("arm"))return"win_unknown";if(!s.architecture){let{userAgent:e}=navigator;return/ARM64/i.test(e)?"win_unknown":/(Win64;\s*x64|WOW64)/i.test(e)?"Windows":"win_unknown"}return"win_unknown"}return s.platform}catch{let{userAgent:s}=navigator;return s.includes("CrOS")?"ChromeOS":s.includes("Macintosh")?zi():s.includes("Windows")?/ARM64/i.test(s)?"win_unknown":"Windows":s.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(s)?"iOS":/Android/.test(s)?"Android":"Unknown"}};var Re=!1;window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=sessionStorage.getItem("referral_status");s&&console.log("raw email signup:",JSON.parse(s));let e=new URLSearchParams(window.location.search),t=e.get("referral"),r=e.get("plan"),i=e.get("stripe_checkout_success"),n=e.get("team_invite_code");console.log("Referral queryparam:",t),console.log("Plan queryparam:",r);let o=!1,a=setTimeout(()=>{o||(document.body.style.visibility="visible")},4e3),c=new Pt,{accessToken:u,refreshToken:l}=br(),d=window.location.hash.includes("access_token="),h;try{h=await As()}catch(g){console.error("Platform detection failed:",g),h="Unknown"}let f=localStorage.getItem("email");if((t||r)&&f&&(!u||!l)){window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"early_exit_email_no_tokens",plan:r,referral:t,stored_email:f,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),timestamp:Date.now()})),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),window.location.href=`/get-started${window.location.search}`;return}if(i==="true"){let g=await P.getSubscriptionStatus(u);if(g.ok&&(await g.json()).is_subscribed){document.querySelectorAll("[payment-success]").forEach(A=>{A.style.display="block"});let I=document.querySelector("[default-h1]");I&&(I.textContent="Congrats, Flow Pro user, your download has started!");let F=localStorage.getItem("email");F&&document.querySelectorAll("[email-address]").forEach(A=>{A.textContent=F}),T("stripe_checkout_success",{email:F,device_type:h,source:"downloads_page",plan:localStorage.getItem("checkout_plan")}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"stripe_checkout_success",device_type:h,source:"downloads_page",plan:localStorage.getItem("checkout_plan"),user_external_id:localStorage.getItem("wispr_visitor_id")||void 0})}localStorage.removeItem("checkout_plan")}else localStorage.removeItem("checkout_plan");let w=document.querySelector("#hello-text"),y=document.querySelector("#logout-button");y.style.display="none";let _=Oe(),{dub_id:k,referral:C}=_,x=Ct();if(u&&l)try{c.setCookies(u,l),await c.checkAndSetSession(),c.sessionData&&c.setCookies(c.sessionData.access_token,c.sessionData.refresh_token);let g=c.sessionData?.access_token??u,E=c.sessionData?.user.email,z=c.sessionData?.user.user_metadata.full_name||" ",[I,F]=wr(z),A=c.sessionData?.user.id,ee=localStorage.getItem("wf_utm_source")||void 0,N=localStorage.getItem("wf_utm_medium")||void 0,cr=localStorage.getItem("wf_utm_campaign")||void 0,Ps={access_token:g,first_name:I,last_name:F,dub_click_id:k||void 0,referral:C||void 0,promo_code:x||void 0,team_invite_code:n||void 0,utm:ee||N||cr?{utm_source:ee,utm_medium:N,utm_campaign:cr}:void 0,first_landing_url:Ts()};localStorage.setItem("email",E),A&&localStorage.setItem("user_id",A);let lr=localStorage.getItem("signin_provider");lr&&localStorage.setItem("last_authed_provider",lr),A&&fr(A,{email:E,firstName:I,lastName:F});let ur=!1;try{if(!localStorage.getItem("conversion_sent")||t||n){let q=await P.signupUser(Ps);x&&(It(x),ur=!0),t&&(Yi(q),console.log("OAuth signup response:",q),console.log("Showing referral UI"))}}catch(q){console.error("Non-fatal: /signup API failed, user remains authenticated:",q),window.posthog?.startSessionRecording?.(),T("signup_sync_error",{error_message:q instanceof Error?q.message:String(q),email:E,user_id:A,signin_provider:localStorage.getItem("signin_provider")||"unknown",is_oauth_callback:d})}if(localStorage.getItem("conversion_sent")||((async()=>{let q=te=>new Promise(Pe=>{if(typeof window.gtag!="function"){Pe(void 0);return}let Os=setTimeout(()=>Pe(void 0),1e3);window.gtag("get","G-2JTM45W1TF",te,Cs=>{clearTimeout(Os),Pe(Cs)})}),[M,st]=await Promise.all([q("client_id"),q("session_id")]);fetch("https://api.wisprflow.ai/api/v1/tracking/events",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event_name:"app_download",event_id:crypto.randomUUID(),wispr_user_id:A||void 0,email:E||void 0,fbp:_._fbp||void 0,fbc:_._fbc||void 0,gclid:xs(_),ga_client_id:M,ga_session_id:st})}).catch(()=>{})})().catch(()=>{}),await Gi(h,k,C,E)),ur||await P.applyPromoCodeFromCookie(g,x),w.textContent=`Hi ${I}!`,y.style.display="flex",r&&g){if(!["FLOW_PRO_MONTHLY","FLOW_PRO_YEARLY"].includes(r)){window.location.href=t?`/downloads?referral=${t}`:"/downloads";return}document.body.innerHTML='<div style="display: flex; padding-left: 20px; padding-right: 20px; text-align: center; justify-content: center; align-items: center; height: 100vh;"><h3>Checking your subscription...</h3></div>',document.body.style.visibility="visible";try{let M=await P.getSubscriptionStatus(g);if(M.status===401){console.log("Subscription API failed: Token expired"),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"subscription_check_401",plan:r,referral:t,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),await ar(r,t,c);return}if(M.ok){let st=await M.json();if(st.is_subscribed){let te=window.location.pathname;window.history.pushState({},"",te),document.body.innerHTML=`
2
2
  <div style="display: flex; padding-left: 20px; padding-right: 20px; text-align: center; flex-direction: column; justify-content: center; align-items: center; height: 100vh;">
3
3
  <h3>\u2705 You already have an active subscription!</h3>
4
4
  <div class="spacer-medium"></div>
5
5
  <p class="text-size-medium">Redirecting you to downloads page in <span id="countdown">3</span> seconds...</p>
6
6
  </div>
7
- `;let Pe=t?`/downloads?referral=${t}`:"/downloads";Vi(3,Pe)}else{let te=r;st.is_student===!0&&(r.endsWith("MONTHLY")?te="FLOW_STUDENT_MONTHLY":r.endsWith("YEARLY")&&(te="FLOW_STUDENT_YEARLY")),await Ki(te,g,t)}}else{console.log("Subscription API failed: Non-200 status"),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"subscription_check_non200",status_code:M.status,plan:r,referral:t,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),await ar(r,t,c);return}}catch(M){console.error("Status check error:",M),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"subscription_check_error",error_message:M instanceof Error?M.message:String(M),plan:r,referral:t,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),await ar(r,t,c);return}return}clearTimeout(a),document.body.style.visibility="visible",r||Rs(h)}catch(g){o=!0,clearTimeout(a),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"session_error_redirect",error_message:g instanceof Error?g.message:String(g),plan:r,referral:t,is_oauth_callback:d,had_tokens:!!(u&&l),user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),c.setCookie("access_token","",-1),c.setCookie("refresh_token","",-1),window.location.href="/get-started",console.error("Error during session setup:",g)}else localStorage.getItem("email")?(w.textContent=`Hi ${localStorage.getItem("email")}!`,y.style.display="flex",clearTimeout(a),document.body.style.visibility="visible",r||Rs(h)):(o=!0,clearTimeout(a),window.location.href="/get-started");document.querySelectorAll("[active-download]").forEach(function(g){if(!h.startsWith("mac")&&g.getAttribute("active-download")?.startsWith("mac")){g.onclick=E=>{if(E.preventDefault(),!localStorage.getItem("email"))return o=!0,clearTimeout(a),window.location.href="/get-started",!1;T("app_waitlist",{device_type:g.getAttribute("active-download")}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:g.getAttribute("active-download"),user_external_id:localStorage.getItem("wispr_visitor_id")||void 0});let z={email:localStorage.getItem("email"),device_type:g.getAttribute("active-download")||"unknown"};return P.addToWaitlist(z),g.innerText="We emailed you the download link!",!1};return}g.onclick=()=>{let E=crypto.randomUUID();return T("app_download",{device_type:h,download_type:g.getAttribute("active-download"),auto_download:Re,source:"downloads-page",email:localStorage.getItem("email")||"not-found",user_id:localStorage.getItem("user_id")||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",event_id:E,device_type:h,download_type:g.getAttribute("active-download"),auto_download:Re,source:"downloads-page",user_email:localStorage.getItem("email")||void 0,user_external_id:localStorage.getItem("user_id")||void 0}),!0}}),document.querySelectorAll("[download-link]").forEach(function(g){g.onclick=()=>{let E=crypto.randomUUID();return T("app_download",{device_type:h,source:"downloads-page-fallback",email:localStorage.getItem("email")||"not-found",user_id:localStorage.getItem("user_id")||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",event_id:E,device_type:h,download_type:h,auto_download:!1,source:"downloads-page-fallback",user_email:localStorage.getItem("email")||void 0,user_external_id:localStorage.getItem("user_id")||void 0}),!0}}),document.querySelectorAll("[waitlist]").forEach(function(g){g.onclick=E=>{if(E.preventDefault(),!localStorage.getItem("email"))return o=!0,clearTimeout(a),window.location.href="/get-started",!1;T("app_waitlist",{device_type:g.getAttribute("waitlist")}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:g.getAttribute("waitlist"),user_external_id:localStorage.getItem("wispr_visitor_id")||void 0});let z={email:localStorage.getItem("email"),device_type:g.getAttribute("waitlist")||"unknown"};return P.addToWaitlist(z),g.innerText="You're on the waitlist!",!1}});let Z=document.querySelector("[download-email-form]");Z&&(Z.removeAttribute("action"),Z.addEventListener("submit",async g=>{g.preventDefault(),g.stopPropagation();let E=Z.querySelector("[email-input]"),z=Z.querySelector("[platform-name]"),I=Z.querySelector('input[type="submit"]');if(!E||!z||!I){console.error("Form fields not found");return}let F=E.value.trim(),A=z.value.trim();if(!F||!A){console.error("Email or platform is empty");return}I.value="Please wait...",I.classList.add("pointer-events-none");try{let ee=await P.sendDownloadLink(A,F);if(ee.ok){console.log("Email sent successfully");let N=document.querySelector("[success-div]");N&&(N.style.display="block"),Z.style.display="none",I.classList.remove("pointer-events-none"),T("download_link_email_success",{platform_requested:A,email:F,source:"downloads_page_form",device_type:h}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"download_link_email_success",platform_requested:A,source:"downloads_page_form",device_type:h,user_external_id:localStorage.getItem("wispr_visitor_id")||void 0})}else{console.error("API error:",ee.status);let N=document.querySelector("[error-div]");N&&(N.style.display="block"),I.classList.remove("pointer-events-none")}}catch(ee){console.error("Network error:",ee);let N=document.querySelector("[error-div]");N&&(N.style.display="block"),I.classList.remove("pointer-events-none")}})),y.addEventListener("click",async()=>{try{await c.signOut(),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=!0,clearTimeout(a),window.location.href="/get-started"}catch(g){console.error("Error during sign-out:",g)}})});async function ar(s,e,t){console.log("Handling token expiration - logging out user");try{await t.signOut(),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status");let r="/get-started",i=new URLSearchParams,o=new URLSearchParams(window.location.search).get("utm_source");e&&i.append("referral",e),s&&i.append("plan",s),o&&i.append("utm_source",o),i.toString()&&(r+=`?${i.toString()}`),console.log("Redirecting to:",r),window.location.href=r}catch(r){console.error("Error during token expiration handling:",r),window.location.href="/get-started"}}async function Gi(s,e,t,r){localStorage.getItem("conversion_sent")||(T("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:s,dub_id:e,referral:t,email:r,user_id:localStorage.getItem("user_id")||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown",user_email:r,user_external_id:localStorage.getItem("wispr_visitor_id")||void 0}),localStorage.setItem("conversion_sent","true"))}async function Ki(s,e,t){if(s&&e)try{let r;try{let a=await P.getPricingByIp();console.log("country & currency ->",a.location?.country_code,a.currency);let c=a.location?.country_code;r=a.currency,console.log(`\u2705 Localized pricing: ${c||"unknown"} \u2192 ${r.toUpperCase()}`)}catch(a){console.error("\u274C Pricing API failed, falling back to USD:",a)}let i=await P.createCheckoutSession(s,e,r);console.log("Checkout details:",i);let{url:n}=i,o=t?`/downloads?referral=${t}`:"/downloads";window.history.pushState({},"",o),localStorage.setItem("checkout_plan",s),T("stripe_checkout_redirect",{plan:s,email:localStorage.getItem("email"),device_type:window.userPlatform,source:"downloads_page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"stripe_checkout_redirect",plan:s,device_type:window.userPlatform,source:"downloads_page",user_external_id:localStorage.getItem("wispr_visitor_id")||void 0}),window.open(n,"_blank"),document.body.innerHTML=`<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh;"><h3>Redirecting to checkout...</h3><div class="spacer-medium"></div><p class="text-size-medium">If you were not redirected automatically, <a href=${n} target="_blank">click here.</a></p></div>`}catch(r){console.error("Checkout error:",r)}}function Vi(s,e){let t=s,r=setInterval(()=>{t--;let i=document.getElementById("countdown");i&&(i.textContent=t.toString()),t<=0&&(clearInterval(r),window.location.href=e)},1e3)}function Yi(s){if(s.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"});return}s.referral_status&&(s.referral_status.referral_code_valid?s.referral_status.was_previously_referred===!0?document.querySelectorAll("[already-referred-div]").forEach(t=>{t.style.display="block"}):s.referral_status.user_exists===!0?document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}):document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Invalid referral code."?document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Cannot refer yourself."&&document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}))}function Rs(s){let e=s==="mac_m1"||s==="mac_intel",t=s==="Windows"||s==="win_unknown",r=s==="iOS";if(e){document.querySelectorAll("[mac]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[header-content]").forEach(a=>{a.style.display="block"});let o=document.querySelector(`[active-download="${s}"]`);o&&o.href&&document.querySelectorAll("[download-link]").forEach(c=>{c.href=o.href}),setTimeout(()=>{let a=document.querySelector(`[active-download="${s}"]`);a&&(window.location.href=a.href,a.onclick&&(Re=!0,a.onclick.call(a,new MouseEvent("click")),Re=!1))},500)}else if(t){document.querySelectorAll("[windows]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[header-content]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[windows-card]").forEach(c=>{c.style.display="none"});let a=document.querySelector('[active-download="windows"]');a&&a.href&&document.querySelectorAll("[download-link]").forEach(u=>{u.href=a.href}),setTimeout(()=>{let c=document.querySelector('[active-download="windows"]');c&&(window.location.href=c.href,c.onclick&&(Re=!0,c.onclick.call(c,new MouseEvent("click")),Re=!1))},500)}else if(r){document.querySelectorAll("[header-content]").forEach(l=>{l.style.display="block"});let n=document.querySelector("[default-h1]");n&&(n.textContent="Download Flow for iOS");let o=document.querySelector("[default-para]");o&&(o.textContent="Download the iOS app and use voice dictation anywhere\u2014texts, emails, DMs, and more."),document.querySelectorAll("[ios-download]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(l=>{l.style.display="none"}),document.querySelectorAll("[fallback-download]").forEach(l=>{l.style.display="none"})}else s==="mac_unknown"?document.querySelectorAll("[mac-unknown]").forEach(n=>{n.style.display="block"}):s==="Unknown"?(document.querySelectorAll("[all-download-cards]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(a=>{a.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(a=>{a.style.display="none"})):(document.querySelectorAll("[not-available]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[all-download-cards]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(c=>{c.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(c=>{c.style.display="none"}))}})();
7
+ `;let Pe=t?`/downloads?referral=${t}`:"/downloads";Vi(3,Pe)}else{let te=r;st.is_student===!0&&(r.endsWith("MONTHLY")?te="FLOW_STUDENT_MONTHLY":r.endsWith("YEARLY")&&(te="FLOW_STUDENT_YEARLY")),await Ki(te,g,t)}}else{console.log("Subscription API failed: Non-200 status"),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"subscription_check_non200",status_code:M.status,plan:r,referral:t,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),await ar(r,t,c);return}}catch(M){console.error("Status check error:",M),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"subscription_check_error",error_message:M instanceof Error?M.message:String(M),plan:r,referral:t,is_oauth_callback:d,user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),await ar(r,t,c);return}return}clearTimeout(a),document.body.style.visibility="visible",r||Rs(h)}catch(g){o=!0,clearTimeout(a),window.posthog?.startSessionRecording?.(),localStorage.setItem("checkout_debug",JSON.stringify({event_type:"session_error_redirect",error_message:g instanceof Error?g.message:String(g),plan:r,referral:t,is_oauth_callback:d,had_tokens:!!(u&&l),user_id:localStorage.getItem("user_id"),email:localStorage.getItem("email"),timestamp:Date.now()})),c.setCookie("access_token","",-1),c.setCookie("refresh_token","",-1),window.location.href=`/get-started${window.location.search}`,console.error("Error during session setup:",g)}else localStorage.getItem("email")?(w.textContent=`Hi ${localStorage.getItem("email")}!`,y.style.display="flex",clearTimeout(a),document.body.style.visibility="visible",r||Rs(h)):(o=!0,clearTimeout(a),window.location.href=`/get-started${window.location.search}`);document.querySelectorAll("[active-download]").forEach(function(g){if(!h.startsWith("mac")&&g.getAttribute("active-download")?.startsWith("mac")){g.onclick=E=>{if(E.preventDefault(),!localStorage.getItem("email"))return o=!0,clearTimeout(a),window.location.href=`/get-started${window.location.search}`,!1;T("app_waitlist",{device_type:g.getAttribute("active-download")}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:g.getAttribute("active-download"),user_external_id:localStorage.getItem("wispr_visitor_id")||void 0});let z={email:localStorage.getItem("email"),device_type:g.getAttribute("active-download")||"unknown"};return P.addToWaitlist(z),g.innerText="We emailed you the download link!",!1};return}g.onclick=()=>{let E=crypto.randomUUID();return T("app_download",{device_type:h,download_type:g.getAttribute("active-download"),auto_download:Re,source:"downloads-page",email:localStorage.getItem("email")||"not-found",user_id:localStorage.getItem("user_id")||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",event_id:E,device_type:h,download_type:g.getAttribute("active-download"),auto_download:Re,source:"downloads-page",user_email:localStorage.getItem("email")||void 0,user_external_id:localStorage.getItem("user_id")||void 0}),!0}}),document.querySelectorAll("[download-link]").forEach(function(g){g.onclick=()=>{let E=crypto.randomUUID();return T("app_download",{device_type:h,source:"downloads-page-fallback",email:localStorage.getItem("email")||"not-found",user_id:localStorage.getItem("user_id")||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",event_id:E,device_type:h,download_type:h,auto_download:!1,source:"downloads-page-fallback",user_email:localStorage.getItem("email")||void 0,user_external_id:localStorage.getItem("user_id")||void 0}),!0}}),document.querySelectorAll("[waitlist]").forEach(function(g){g.onclick=E=>{if(E.preventDefault(),!localStorage.getItem("email"))return o=!0,clearTimeout(a),window.location.href=`/get-started${window.location.search}`,!1;T("app_waitlist",{device_type:g.getAttribute("waitlist")}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:g.getAttribute("waitlist"),user_external_id:localStorage.getItem("wispr_visitor_id")||void 0});let z={email:localStorage.getItem("email"),device_type:g.getAttribute("waitlist")||"unknown"};return P.addToWaitlist(z),g.innerText="You're on the waitlist!",!1}});let Z=document.querySelector("[download-email-form]");Z&&(Z.removeAttribute("action"),Z.addEventListener("submit",async g=>{g.preventDefault(),g.stopPropagation();let E=Z.querySelector("[email-input]"),z=Z.querySelector("[platform-name]"),I=Z.querySelector('input[type="submit"]');if(!E||!z||!I){console.error("Form fields not found");return}let F=E.value.trim(),A=z.value.trim();if(!F||!A){console.error("Email or platform is empty");return}I.value="Please wait...",I.classList.add("pointer-events-none");try{let ee=await P.sendDownloadLink(A,F);if(ee.ok){console.log("Email sent successfully");let N=document.querySelector("[success-div]");N&&(N.style.display="block"),Z.style.display="none",I.classList.remove("pointer-events-none"),T("download_link_email_success",{platform_requested:A,email:F,source:"downloads_page_form",device_type:h}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"download_link_email_success",platform_requested:A,source:"downloads_page_form",device_type:h,user_external_id:localStorage.getItem("wispr_visitor_id")||void 0})}else{console.error("API error:",ee.status);let N=document.querySelector("[error-div]");N&&(N.style.display="block"),I.classList.remove("pointer-events-none")}}catch(ee){console.error("Network error:",ee);let N=document.querySelector("[error-div]");N&&(N.style.display="block"),I.classList.remove("pointer-events-none")}})),y.addEventListener("click",async()=>{try{await c.signOut(),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=!0,clearTimeout(a),window.location.href="/get-started"}catch(g){console.error("Error during sign-out:",g)}})});async function ar(s,e,t){console.log("Handling token expiration - logging out user");try{await t.signOut(),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status");let r="/get-started",i=new URLSearchParams(window.location.search);e&&i.set("referral",e),s&&i.set("plan",s),i.toString()&&(r+=`?${i.toString()}`),console.log("Redirecting to:",r),window.location.href=r}catch(r){console.error("Error during token expiration handling:",r),window.location.href=`/get-started${window.location.search}`}}async function Gi(s,e,t,r){localStorage.getItem("conversion_sent")||(T("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:s,dub_id:e,referral:t,email:r,user_id:localStorage.getItem("user_id")||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown",user_email:r,user_external_id:localStorage.getItem("wispr_visitor_id")||void 0}),localStorage.setItem("conversion_sent","true"))}async function Ki(s,e,t){if(s&&e)try{let r;try{let a=await P.getPricingByIp();console.log("country & currency ->",a.location?.country_code,a.currency);let c=a.location?.country_code;r=a.currency,console.log(`\u2705 Localized pricing: ${c||"unknown"} \u2192 ${r.toUpperCase()}`)}catch(a){console.error("\u274C Pricing API failed, falling back to USD:",a)}let i=await P.createCheckoutSession(s,e,r);console.log("Checkout details:",i);let{url:n}=i,o=t?`/downloads?referral=${t}`:"/downloads";window.history.pushState({},"",o),localStorage.setItem("checkout_plan",s),T("stripe_checkout_redirect",{plan:s,email:localStorage.getItem("email"),device_type:window.userPlatform,source:"downloads_page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"stripe_checkout_redirect",plan:s,device_type:window.userPlatform,source:"downloads_page",user_external_id:localStorage.getItem("wispr_visitor_id")||void 0}),window.open(n,"_blank"),document.body.innerHTML=`<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh;"><h3>Redirecting to checkout...</h3><div class="spacer-medium"></div><p class="text-size-medium">If you were not redirected automatically, <a href=${n} target="_blank">click here.</a></p></div>`}catch(r){console.error("Checkout error:",r)}}function Vi(s,e){let t=s,r=setInterval(()=>{t--;let i=document.getElementById("countdown");i&&(i.textContent=t.toString()),t<=0&&(clearInterval(r),window.location.href=e)},1e3)}function Yi(s){if(s.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"});return}s.referral_status&&(s.referral_status.referral_code_valid?s.referral_status.was_previously_referred===!0?document.querySelectorAll("[already-referred-div]").forEach(t=>{t.style.display="block"}):s.referral_status.user_exists===!0?document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}):document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Invalid referral code."?document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Cannot refer yourself."&&document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}))}function Rs(s){let e=s==="mac_m1"||s==="mac_intel",t=s==="Windows"||s==="win_unknown",r=s==="iOS";if(e){document.querySelectorAll("[mac]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[header-content]").forEach(a=>{a.style.display="block"});let o=document.querySelector(`[active-download="${s}"]`);o&&o.href&&document.querySelectorAll("[download-link]").forEach(c=>{c.href=o.href}),setTimeout(()=>{let a=document.querySelector(`[active-download="${s}"]`);a&&(window.location.href=a.href,a.onclick&&(Re=!0,a.onclick.call(a,new MouseEvent("click")),Re=!1))},500)}else if(t){document.querySelectorAll("[windows]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[header-content]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[windows-card]").forEach(c=>{c.style.display="none"});let a=document.querySelector('[active-download="windows"]');a&&a.href&&document.querySelectorAll("[download-link]").forEach(u=>{u.href=a.href}),setTimeout(()=>{let c=document.querySelector('[active-download="windows"]');c&&(window.location.href=c.href,c.onclick&&(Re=!0,c.onclick.call(c,new MouseEvent("click")),Re=!1))},500)}else if(r||s==="Android"){let i=r?"iOS":"Android";document.querySelectorAll("[header-content]").forEach(d=>{d.style.display="block"});let o=document.querySelector("[default-h1]");o&&(o.textContent=`Download Flow for ${i}`);let a=document.querySelector("[default-para]");a&&(a.textContent=`Download the ${i} app and use voice dictation anywhere\u2014texts, emails, DMs, and more.`),document.querySelectorAll("[ios-download]").forEach(d=>{d.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(d=>{d.style.display="none"}),document.querySelectorAll("[fallback-download]").forEach(d=>{d.style.display="none"})}else s==="mac_unknown"?document.querySelectorAll("[mac-unknown]").forEach(n=>{n.style.display="block"}):s==="Unknown"?(document.querySelectorAll("[all-download-cards]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(a=>{a.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(a=>{a.style.display="none"})):(document.querySelectorAll("[not-available]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[all-download-cards]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(c=>{c.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(c=>{c.style.display="none"}))}})();