@tanay-wispr/webflow-package 6.8.14 → 6.8.16
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/global.js +2 -2
- package/dist/login.js +1 -1
- package/dist/signup.js +1 -1
- package/package.json +1 -1
package/dist/login.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var gn=Object.create;var Pt=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var _n=Object.getOwnPropertyNames;var yn=Object.getPrototypeOf,wn=Object.prototype.hasOwnProperty;var vn=(r,e)=>()=>(r&&(e=r(r=0)),e);var ee=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),bn=(r,e)=>{for(var t in e)Pt(r,t,{get:e[t],enumerable:!0})},Fs=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _n(e))!wn.call(r,n)&&n!==t&&Pt(r,n,{get:()=>e[n],enumerable:!(s=mn(e,n))||s.enumerable});return r};var Hs=(r,e,t)=>(t=r!=null?gn(yn(r)):{},Fs(e||!r||!r.__esModule?Pt(t,"default",{value:r,enumerable:!0}):t,r)),kn=r=>Fs(Pt({},"__esModule",{value:!0}),r);var ye={};bn(ye,{Headers:()=>ls,Request:()=>Ln,Response:()=>jn,default:()=>cs,fetch:()=>In});var On,Ue,In,cs,ls,Ln,jn,he=vn(()=>{"use strict";On=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")},Ue=On(),In=Ue.fetch,cs=Ue.fetch.bind(Ue),ls=Ue.Headers,Ln=Ue.Request,jn=Ue.Response});var Ks=ee(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var us=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ds.default=us});var fs=ee(st=>{"use strict";var Ys=st&&st.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(st,"__esModule",{value:!0});var Un=Ys((he(),kn(ye))),Dn=Ys(Ks()),hs=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=Un.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var o,a,c;let l=null,u=null,d=null,f=i.status,g=i.statusText;if(i.ok){if(this.method!=="HEAD"){let O=await i.text();O===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=O:u=JSON.parse(O))}let k=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),S=(a=i.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");k&&S&&S.length>1&&(d=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(l={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,d=null,f=406,g="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{let k=await i.text();try{l=JSON.parse(k),Array.isArray(l)&&i.status===404&&(u=[],l=null,f=200,g="OK")}catch{i.status===404&&k===""?(f=204,g="No Content"):l={message:k}}if(l&&this.isMaybeSingle&&(!((c=l?.details)===null||c===void 0)&&c.includes("0 rows"))&&(l=null,f=200,g="OK"),l&&this.shouldThrowOnError)throw new Dn.default(l)}return{error:l,data:u,count:d,status:f,statusText:g}});return this.shouldThrowOnError||(n=n.catch(i=>{var o,a,c;return{error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:`${(a=i?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=i?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}};st.default=hs});var gs=ee(rt=>{"use strict";var Mn=rt&&rt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rt,"__esModule",{value:!0});var Nn=Mn(fs()),ps=class extends Nn.default{select(e){let t=!1,s=(e??"*").split("").map(n=>/\s/.test(n)&&!t?"":(n==='"'&&(t=!t),n)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:n,referencedTable:i=n}={}){let o=i?`${i}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:n=s}={}){let i=typeof n>"u"?"offset":`${n}.offset`,o=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:n=!1,wal:i=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${l}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};rt.default=ps});var Dt=ee(nt=>{"use strict";var qn=nt&&nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(nt,"__esModule",{value:!0});var Fn=qn(gs()),ms=class extends Fn.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(n=>typeof n=="string"&&new RegExp("[,()]").test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${i}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let n=s?`${s}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};nt.default=ms});var ys=ee(ot=>{"use strict";var Hn=ot&&ot.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ot,"__esModule",{value:!0});var it=Hn(Dt()),_s=class{constructor(e,{headers:t={},schema:s,fetch:n}){this.url=e,this.headers=t,this.schema=s,this.fetch=n}select(e,{head:t=!1,count:s}={}){let n=t?"HEAD":"GET",i=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new it.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let n="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),s||i.push("missing=default"),this.headers.Prefer=i.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 it.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:n,defaultToNull:i=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),n&&a.push(`count=${n}`),i||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",l.join(","))}}return new it.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",n=[];return this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),this.headers.Prefer=n.join(","),new it.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new it.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ot.default=_s});var Xs=ee(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.version=void 0;Mt.version="0.0.0-automated"});var Qs=ee(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.DEFAULT_HEADERS=void 0;var Wn=Xs();Nt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Wn.version}`}});var er=ee(at=>{"use strict";var Zs=at&&at.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(at,"__esModule",{value:!0});var Bn=Zs(ys()),zn=Zs(Dt()),Gn=Qs(),ws=class r{constructor(e,{headers:t={},schema:s,fetch:n}={}){this.url=e,this.headers=Object.assign(Object.assign({},Gn.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=n}from(e){let t=new URL(`${this.url}/${e}`);return new Bn.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:n=!1,count:i}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||n?(o=s?"HEAD":"GET",Object.entries(t).filter(([u,d])=>d!==void 0).map(([u,d])=>[u,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([u,d])=>{a.searchParams.append(u,d)})):(o="POST",c=t);let l=Object.assign({},this.headers);return i&&(l.Prefer=`count=${i}`),new zn.default({method:o,url:a,headers:l,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};at.default=ws});var or=ee(q=>{"use strict";var ct=q&&q.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(q,"__esModule",{value:!0});q.PostgrestBuilder=q.PostgrestTransformBuilder=q.PostgrestFilterBuilder=q.PostgrestQueryBuilder=q.PostgrestClient=void 0;var tr=ct(er());q.PostgrestClient=tr.default;var sr=ct(ys());q.PostgrestQueryBuilder=sr.default;var rr=ct(Dt());q.PostgrestFilterBuilder=rr.default;var nr=ct(gs());q.PostgrestTransformBuilder=nr.default;var ir=ct(fs());q.PostgrestBuilder=ir.default;q.default={PostgrestClient:tr.default,PostgrestQueryBuilder:sr.default,PostgrestFilterBuilder:rr.default,PostgrestTransformBuilder:nr.default,PostgrestBuilder:ir.default}});var gr=ee((jo,pr)=>{"use strict";pr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Qe=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var x=(r,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:r,retry_attempt:10-t}),window.posthog.capture(r,e)):t>0&&setTimeout(()=>x(r,e,t-1),200)};var It=r=>r.verification_method==="email_otp"&&typeof r.pending_authentication_token=="string"&&r.pending_authentication_token.length>0,j="https://api.wisprflow.ai",Q=class extends Error{constructor(t,s,n,i=null){super(n);this.status=t;this.code=s;this.passwordRejectionMessage=i;this.name="AriaAuthError"}},F=r=>r.trim().toLowerCase(),Ws=(r,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof r.code=="string"?r.code:r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:typeof r.detail=="string"&&t.has(r.detail)?r.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},Ze=(r,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[r]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Sn=(r,e,t)=>[r.message,r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"?r.detail.message:null,typeof r.detail=="string"?r.detail:null].find(i=>typeof i=="string"&&i.length>0&&i!==e)??Ze(e,t),$e=(r,e)=>{let t=Ws(r,e);return new Q(e,t,Sn(r,t,e),e===400&&typeof r.detail=="string"&&r.detail.length>0?r.detail:null)},En=(r,e)=>{let t=Ws(r,e);return new Q(e,t,Ze(t,e))},Ot="promo_code",Tn=4e3,Cn=new Set([200,400,403,404,409,422]),Bs=r=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${r}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},zs=r=>{if(!r)return"";try{return decodeURIComponent(r).trim()}catch{return""}},An=()=>{let r=Qe()[Ot];if(r===void 0)return"";let e=zs(r);return e||Bs(Ot),e},xn=r=>{zs(Qe()[Ot])===r&&Bs(Ot)},Rn=r=>r instanceof DOMException&&(r.name==="TimeoutError"||r.name==="AbortError"),Pn=(r,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:e===422?"validation_error":"unknown",as=class{static async signupUser(e){try{let t=`${j}/signup`,n=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),i=n&&n.trim().split("=")[1];(i==="3mo"||i==="2mo")&&(t+=`?trial_promo=${i}`);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(`${j}/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(`${j}/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(`${j}/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(`${j}/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=F(e),s=await fetch(`${j}/user_status?email=${encodeURIComponent(t)}`),n=await s.json().catch(()=>({}));if(!s.ok)throw $e(n,s.status);return n}static async requestPasswordReset(e,t){let s=await fetch(`${j}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:F(e),captcha_token:t})});if(!s.ok){let n=await s.json().catch(()=>({}));throw $e(n,s.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${j}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async signInWithCaptcha(e){let t=await fetch(`${j}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${j}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new Q(422,"invalid_code",Ze("invalid_code",422));let t=await fetch(`${j}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok){let n=En(s,t.status);throw n.code==="rate_limited"||n.code==="provider_unavailable"||n.code==="validation_error"?n:new Q(t.status,"verification_failed",Ze("verification_failed",t.status))}if(s.provider!=="workos"||!s.access_token||!s.refresh_token||!s.user_id||!s.email)throw new Q(t.status,"authentication_failed",Ze("authentication_failed",t.status));return s}static async signInWithEmail(e){let t=await fetch(`${j}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async applyPromoCodeFromCookie(e,t=An()){if(t)try{let s=await fetch(`${j}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(Tn)}),{status:n}=s;if(!Cn.has(n)){x("promo_cookie_apply",{outcome:"deferred",status:n});return}if(xn(t),s.ok){x("promo_cookie_apply",{outcome:"attached",status:n});return}let i=await s.json().catch(()=>({}));x("promo_cookie_apply",{outcome:"rejected",status:n,reason:Pn(i,n)})}catch(s){console.error("Promo cookie apply deferred:",s),x("promo_cookie_apply",Rn(s)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${j}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${j}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s,n){let i=new URLSearchParams({plan:e,custom_redirect:"true"});s&&i.set("currency",s),n?.trim()&&i.set("promo_code",n.trim());let o=`${j}/api/v1/payment/create-checkout-session?${i}`,a=await fetch(o,{method:"POST",headers:{accept:"application/json",Authorization:t}});if(!a.ok&&a.status!==303)throw new Error(`Checkout request failed (${a.status})`);let c=await a.json();if(!c||typeof c.url!="string"||!c.url)throw new Error("Checkout response is missing a URL");return c}static async sendDownloadLink(e,t){return await fetch(`${j}/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(`${j}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${j}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${j}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let n=new FormData;return n.append("screenshot",e),await fetch(`${j}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:n,signal:s})}};function Gs(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function Js(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var N=as;var Vs=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(he(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var et=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Lt=class extends et{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},jt=class extends et{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},$t=class extends et{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ut;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(Ut||(Ut={}));var $n=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},tt=class{constructor(e,{headers:t={},customFetch:s,region:n=Ut.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=Vs(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return $n(this,void 0,void 0,function*(){try{let{headers:n,method:i,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let l;o&&(n&&!Object.prototype.hasOwnProperty.call(n,"Content-Type")||!n)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",l=o):typeof o=="string"?(a["Content-Type"]="text/plain",l=o):typeof FormData<"u"&&o instanceof FormData?l=o:(a["Content-Type"]="application/json",l=JSON.stringify(o)));let u=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),n),body:l}).catch(v=>{throw new Lt(v)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new jt(u);if(!u.ok)throw new $t(u);let f=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield u.json():f==="application/octet-stream"?g=yield u.blob():f==="text/event-stream"?g=u:f==="multipart/form-data"?g=yield u.formData():g=yield u.text(),{data:g,error:null}}catch(n){return{data:null,error:n}}})}};var ar=Hs(or(),1),{PostgrestClient:cr,PostgrestQueryBuilder:go,PostgrestFilterBuilder:mo,PostgrestTransformBuilder:_o,PostgrestBuilder:yo}=ar.default;var lr="2.10.2";var ur={"X-Client-Info":`realtime-js/${lr}`},dr="1.0.0",Ft=1e4,hr=1e3,we;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(we||(we={}));var H;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(H||(H={}));var z;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(z||(z={}));var qt;(function(r){r.websocket="websocket"})(qt||(qt={}));var fe;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(fe||(fe={}));var lt=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let n=t.getUint8(1),i=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+n));o=o+n;let c=s.decode(e.slice(o,o+i));o=o+i;let l=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:l}}};var ve=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var I;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(I||(I={}));var bs=(r,e,t={})=>{var s;let n=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((i,o)=>(i[o]=Jn(o,r,e,n),i),{})},Jn=(r,e,t,s)=>{let n=e.find(a=>a.name===r),i=n?.type,o=t[r];return i&&!s.includes(i)?fr(i,o):vs(o)},fr=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Xn(e,t)}switch(r){case I.bool:return Vn(e);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return Kn(e);case I.json:case I.jsonb:return Yn(e);case I.timestamp:return Qn(e);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:return vs(e);default:return vs(e)}},vs=r=>r,Vn=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Kn=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Yn=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Xn=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let i,o=r.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>fr(e,a))}return r},Qn=r=>typeof r=="string"?r.replace(" ","T"):r,Ht=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var be=class{constructor(e,t,s={},n=Ft){this.channel=e,this.event=t,this.payload=s,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var ks;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(ks||(ks={}));var De=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,n,i,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=r.syncDiff(this.state,n,i,o),a())}),this.onJoin((n,i,o)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:o})}),this.onLeave((n,i,o)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,n){let i=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(i,(l,u)=>{o[l]||(c[l]=u)}),this.map(o,(l,u)=>{let d=i[l];if(d){let f=u.map(S=>S.presence_ref),g=d.map(S=>S.presence_ref),v=u.filter(S=>g.indexOf(S.presence_ref)<0),k=d.filter(S=>f.indexOf(S.presence_ref)<0);v.length>0&&(a[l]=v),k.length>0&&(c[l]=k)}else a[l]=u}),this.syncDiff(i,{joins:a,leaves:c},s,n)}static syncDiff(e,t,s,n){let{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(i,(a,c)=>{var l;let u=(l=e[a])!==null&&l!==void 0?l:[];if(e[a]=this.cloneDeep(c),u.length>0){let d=e[a].map(g=>g.presence_ref),f=u.filter(g=>d.indexOf(g.presence_ref)<0);e[a].unshift(...f)}s(a,u,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.map(d=>d.presence_ref);l=l.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=l,n(a,l,c),l.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let n=e[s];return"metas"in n?t[s]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[s]=n,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 Ss;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(Ss||(Ss={}));var Es;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(Es||(Es={}));var Ts;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Ts||(Ts={}));var Me=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=H.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 be(this,z.join,this.params,this.timeout),this.rejoinTimer=new ve(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=H.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=H.closed,this.socket._remove(this)}),this._onError(n=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,n),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this._on(z.reply,{},(n,i)=>{this._trigger(this._replyEventName(i),n)}),this.presence=new De(this),this.broadcastEndpointURL=Ht(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,n;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:i,presence:o,private:a}}=this.params;this._onError(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("CLOSED"));let c={},l={broadcast:i,presence:o,postgres_changes:(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(u=>u.filter))!==null&&n!==void 0?n:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:u})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,g=(d=f?.length)!==null&&d!==void 0?d:0,v=[];for(let k=0;k<g;k++){let S=f[k],{filter:{event:O,schema:h,table:m,filter:R}}=S,L=u&&u[k];if(L&&L.event===O&&L.schema===h&&L.table===m&&L.filter===R)v.push(Object.assign(Object.assign({},S),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,n;if(!this._canPush()&&e.type==="broadcast"){let{event:i,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:i,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=c.body)===null||n===void 0?void 0:n.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,c;let l=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=H.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(z.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let n=new be(this,z.leave,{},e);n.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new be(this,e,t,s);return this._canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var n,i;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:l,join:u}=z;if(s&&[a,c,l,u].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,t,s);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(g=>{var v,k,S;return((v=g.filter)===null||v===void 0?void 0:v.event)==="*"||((S=(k=g.filter)===null||k===void 0?void 0:k.event)===null||S===void 0?void 0:S.toLocaleLowerCase())===o}).map(g=>g.callback(f,s)):(i=this.bindings[o])===null||i===void 0||i.filter(g=>{var v,k,S,O,h,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){let R=g.id,L=(v=g.filter)===null||v===void 0?void 0:v.event;return R&&((k=t.ids)===null||k===void 0?void 0:k.includes(R))&&(L==="*"||L?.toLocaleLowerCase()===((S=t.data)===null||S===void 0?void 0:S.type.toLocaleLowerCase()))}else{let R=(h=(O=g?.filter)===null||O===void 0?void 0:O.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return R==="*"||R===((m=t?.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof f=="object"&&"ids"in f){let v=f.data,{schema:k,table:S,commit_timestamp:O,type:h,errors:m}=v;f=Object.assign(Object.assign({},{schema:k,table:S,commit_timestamp:O,eventType:h,new:{},old:{},errors:m}),this._getPayloadRecords(v))}g.callback(f,s)})}_isClosed(){return this.state===H.closed}_isJoined(){return this.state===H.joined}_isJoining(){return this.state===H.joining}_isLeaving(){return this.state===H.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let n=e.toLocaleLowerCase(),i={type:n,filter:t,callback:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&r.isEqual(n.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(z.close,{},e)}_onError(e){this._on(z.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=H.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=bs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=bs(e.columns,e.old_record)),t}};var ei=()=>{},ti=typeof WebSocket<"u",Ne=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ur,this.params={},this.timeout=Ft,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=ei,this.conn=null,this.sendBuffer=[],this.serializer=new lt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(he(),ye)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${qt.websocket}`,this.httpEndpoint=Ht(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 n=(s=t?.params)===null||s===void 0?void 0:s.apikey;n&&(this.accessToken=n,this.apiKey=n),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t?.encode?t.encode:(i,o)=>o(JSON.stringify(i)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ve(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(ti){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Cs(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Hs(gr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case we.connecting:return fe.Connecting;case we.open:return fe.Open;case we.closing:return fe.Closing;default:return fe.Closed}}isConnected(){return this.connectionState()===fe.Open}channel(e,t={config:{}}){let s=new Me(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:n,ref:i}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${i})`,n),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(z.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:dr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:n,payload:i,ref:o}=t;(o&&o===this.pendingHeartbeatRef||n===i?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${s} ${n} ${o&&"("+o+")"||""}`,i),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(n,i,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(z.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return`${e}${s}${n}`}_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(hr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Cs=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=we.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var qe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function U(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Wt=class extends qe{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ut=class extends qe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var si=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Bt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(he(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},mr=()=>si(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(he(),ye))).Response:Response});var Fe=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},As=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),ri=(r,e)=>Fe(void 0,void 0,void 0,function*(){let t=yield mr();r instanceof t?r.json().then(s=>{e(new Wt(As(s),r.status||500))}).catch(s=>{e(new ut(As(s),s))}):e(new ut(As(r),r))}),ni=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};function zt(r,e,t,s,n,i){return Fe(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,ni(e,s,n,i)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>ri(c,a))})})}function dt(r,e,t,s){return Fe(this,void 0,void 0,function*(){return zt(r,"GET",e,t,s)})}function te(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return zt(r,"POST",e,s,n,t)})}function _r(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return zt(r,"PUT",e,s,n,t)})}function Gt(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return zt(r,"DELETE",e,s,n,t)})}var G=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ii={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ht=class{constructor(e,t={},s,n){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Bt(n)}uploadOrUpdate(e,t,s,n){return G(this,void 0,void 0,function*(){try{let i,o=Object.assign(Object.assign({},yr),n),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.append("cacheControl",o.cacheControl)):(i=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:i,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(i){if(U(i))return{data:null,error:i};throw i}})}upload(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,n){return G(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,l=Object.assign({upsert:yr.upsert},n),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",l.cacheControl)):(c=s,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:u}),f=yield d.json();return d.ok?{data:{path:i,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(U(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return G(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=Object.assign({},this.headers);t?.upsert&&(n["x-upsert"]="true");let i=yield te(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new qe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}update(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}copy(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:{path:(yield te(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}createSignedUrl(e,t,s){return G(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),i=yield te(this.fetch,`${this.url}/object/sign/${n}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}createSignedUrls(e,t,s){return G(this,void 0,void 0,function*(){try{let n=yield te(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:n.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}download(e,t){return G(this,void 0,void 0,function*(){let n=typeof t?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(t?.transform||{}),o=i?`?${i}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield dt(this.fetch,`${this.url}/${n}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(U(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),n=[],i=t?.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&n.push(i);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&n.push(c);let l=n.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${l}`)}}}remove(e){return G(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}list(e,t,s){return G(this,void 0,void 0,function*(){try{let n=Object.assign(Object.assign(Object.assign({},ii),t),{prefix:e||""});return{data:yield te(this.fetch,`${this.url}/object/list/${this.bucketId}`,n,{headers:this.headers},s),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}_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 wr="2.6.0";var vr={"X-Client-Info":`storage-js/${wr}`};var He=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ft=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},vr),t),this.fetch=Bt(s)}listBuckets(){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}})}getBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return He(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return He(this,void 0,void 0,function*(){try{return{data:yield _r(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}emptyBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}};var pt=class extends ft{constructor(e,t={},s){super(e,t,s)}from(e){return new ht(this.url,this.headers,e,this.fetch)}};var br="2.44.4";var gt="";typeof Deno<"u"?gt="deno":typeof document<"u"?gt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?gt="react-native":gt="node";var oi={"X-Client-Info":`supabase-js-${gt}/${br}`},kr={headers:oi},Sr={schema:"public"},Er={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Tr={};he();var ai=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ci=r=>{let e;return r?e=r:typeof fetch>"u"?e=cs:e=fetch,(...t)=>e(...t)},li=()=>typeof Headers>"u"?ls:Headers,Cr=(r,e,t)=>{let s=ci(t),n=li();return(i,o)=>ai(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,l=new n(o?.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),s(i,Object.assign(Object.assign({},o),{headers:l}))})};function Ar(r){return r.replace(/\/$/,"")}function xr(r,e){let{db:t,auth:s,realtime:n,global:i}=r,{db:o,auth:a,realtime:c,global:l}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),n),global:Object.assign(Object.assign({},l),i)}}var Jt="2.64.4";var Rr="http://localhost:9999",Pr="supabase.auth.token";var Or={"X-Client-Info":`gotrue-js/${Jt}`},xs=10;var mt="X-Supabase-Api-Version",Rs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ir(r){return Math.round(Date.now()/1e3)+r}function Lr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var J=()=>typeof document<"u",ke={tested:!1,writable:!1},pe=()=>{if(!J())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ke.tested)return ke.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),ke.tested=!0,ke.writable=!0}catch{ke.tested=!0,ke.writable=!1}return ke.writable};function Vt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return t.searchParams.forEach((s,n)=>{e[n]=s}),e}var Kt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(he(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},jr=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Ps=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},yt=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Yt=async(r,e)=>{await r.removeItem(e)};function ui(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,n,i,o,a,c,l,u=0;for(r=r.replace("-","+").replace("_","/");u<r.length;)o=e.indexOf(r.charAt(u++)),a=e.indexOf(r.charAt(u++)),c=e.indexOf(r.charAt(u++)),l=e.indexOf(r.charAt(u++)),s=o<<2|a>>4,n=(a&15)<<4|c>>2,i=(c&3)<<6|l,t=t+String.fromCharCode(s),c!=64&&n!=0&&(t=t+String.fromCharCode(n)),l!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}var _t=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};_t.promiseConstructor=Promise;function Os(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(ui(s))}async function $r(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Ur(r,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await r(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function di(r){return("0"+r.toString(16)).substr(-2)}function hi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,n="";for(let i=0;i<56;i++)n+=t.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,di).join("")}async function fi(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}function pi(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function gi(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await fi(r);return pi(t)}async function Se(r,e,t=!1){let s=hi(),n=s;t&&(n+="/PASSWORD_RECOVERY"),await Ps(r,`${e}-code-verifier`,n);let i=await gi(s);return[i,s===i?"plain":"s256"]}var mi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Dr(r){let e=r.headers.get(mt);if(!e||!e.match(mi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var wt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function E(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Xt=class extends wt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Mr(r){return E(r)&&r.name==="AuthApiError"}var We=class extends wt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ce=class extends wt{constructor(e,t,s,n){super(e,s,n),this.name=t,this.status=s}},se=class extends ce{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Be=class extends ce{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ee=class extends ce{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Te=class extends ce{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},vt=class extends ce{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},ze=class extends ce{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Qt(r){return E(r)&&r.name==="AuthRetryableFetchError"}var bt=class extends ce{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var _i=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t},Ce=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),yi=[502,503,504];async function Nr(r){var e;if(!jr(r))throw new ze(Ce(r),0);if(yi.includes(r.status))throw new ze(Ce(r),r.status);let t;try{t=await r.json()}catch(i){throw new We(Ce(i),i)}let s,n=Dr(r);if(n&&n.getTime()>=Rs["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new bt(Ce(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new bt(Ce(t),r.status,t.weak_password.reasons);throw new Xt(Ce(t),r.status||500,s)}var wi=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};async function T(r,e,t,s){var n;let i=Object.assign({},s?.headers);i[mt]||(i[mt]=Rs["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let o=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await vi(r,e,t+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function vi(r,e,t,s,n,i){let o=wi(e,s,n,i),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new ze(Ce(c),0)}if(a.ok||await Nr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await Nr(c)}}function le(r){var e;let t=null;bi(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Ir(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Is(r){let e=le(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function re(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function qr(r){return{data:r,error:null}}function Fr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i}=r,o=_i(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Hr(r){return r}function bi(r){return r.access_token&&r.refresh_token&&r.expires_in}var ki=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t},Ae=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Kt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await T(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(E(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await T(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:re})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=ki(e,["options"]),n=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Fr,redirectTo:t?.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await T(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:re})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,n,i,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await T(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Hr});if(u.error)throw u.error;let d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return g.length>0&&(g.forEach(v=>{let k=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(v.split(";")[1].split("=")[1]);l[`${S}Page`]=k}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(E(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:re})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await T(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:re})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await T(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:re})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await T(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:t,error:s}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await T(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}};var Wr={getItem:r=>pe()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{pe()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{pe()&&globalThis.localStorage.removeItem(r)}};function Ls(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Br(){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 xe={debug:!!(globalThis&&pe()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},kt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Zt=class extends kt{};async function js(r,e,t){xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),xe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,n.name);try{return await t()}finally{xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,n.name)}}else{if(e===0)throw xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Zt(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(xe.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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()}})}Br();var Si={url:Rr,storageKey:Pr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Or,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},St=30*1e3,zr=3;async function Gr(r,e,t){return await t()}var Re=class r{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&J()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let n=Object.assign(Object.assign({},Si),e);if(this.logDebugMessages=!!n.debug,typeof n.debug=="function"&&(this.logger=n.debug),this.persistSession=n.persistSession,this.storageKey=n.storageKey,this.autoRefreshToken=n.autoRefreshToken,this.admin=new Ae({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=Kt(n.fetch),this.lock=n.lock||Gr,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,n.lock?this.lock=n.lock:J()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=js:this.lock=Gr,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?n.storage?this.storage=n.storage:pe()?this.storage=Wr:(this.memoryStorage={},this.storage=Ls(this.memoryStorage)):(this.memoryStorage={},this.storage=Ls(this.memoryStorage)),J()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Jt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=J()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:n,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",n,"redirect type",i),await this._saveSession(n),setTimeout(async()=>{i==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return E(e)?{error:e}:{error:new We("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,n;try{let i=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:le}),{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,s,n;try{let i;if("email"in e){let{email:u,password:d,options:f}=e,g=null,v=null;this.flowType==="pkce"&&([g,v]=await Se(this.storage,this.storageKey)),i=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:g,code_challenge_method:v},xform:le})}else if("phone"in e){let{phone:u,password:d,options:f}=e;i=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:le})}else throw new Ee("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Is})}else if("phone"in e){let{phone:i,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Is})}else throw new Ee("You must provide either an email or phone number and a password");let{data:s,error:n}=t;return n?{data:{user:null,session:null},error:n}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Be}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await yt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(t??"").split("/"),{data:i,error:o}=await T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:le});return await Yt(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Be}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:n,access_token:i,nonce:o}=e,a=await T(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:le}),{data:c,error:l}=a;return l?{data:{user:null,session:null},error:l}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Be}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:l})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,n,i,o;try{if("email"in e){let{email:a,options:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await Se(this.storage,this.storageKey));let{error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=c?.data)!==null&&n!==void 0?n:{},create_user:(i=c?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:l?.message_id},error:u}}throw new Ee("You must provide either an email or phone number.")}catch(a){if(E(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let n,i;"options"in e&&(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:le});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithSSO(e){var t,s,n;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await Se(this.storage,this.storageKey)),await T(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:qr})}catch(i){if(E(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new se;let{error:n}=await T(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:n}})}catch(e){if(E(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:n,options:i}=e,{error:o}=await T(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:n,options:i}=e,{data:o,error:a}=await T(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Ee("You must provide either an email or phone number and a type")}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await yt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,l,u)=>(!o&&l==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,l,u))})}return{data:{session:e},error:null}}let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:n},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:re}):await this._useSession(async t=>{var s,n,i;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new se}:await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:re})})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new se;let o=n.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Se(this.storage,this.storageKey));let{data:l,error:u}=await T(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:re});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Os(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 se;let t=Date.now()/1e3,s=t,n=!0,i=null,o=Os(e.access_token);if(o.exp&&(s=o.exp,n=s<=t),n){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};i=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(E(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new se;let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:n?{data:{user:n.user,session:n},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!J())throw new Te("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Te("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new vt("Not a valid PKCE flow url.");let t=Vt(window.location.href);if(e){if(!t.code)throw new vt("No code detected.");let{data:h,error:m}=await this._exchangeCodeForSession(t.code);if(m)throw m;let R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Te(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:a,expires_at:c,token_type:l}=t;if(!i||!a||!o||!l)throw new Te("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;c&&(f=parseInt(c));let g=f-u;g*1e3<=St&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${d}s`);let v=f-d;u-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,u):u-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",v,f,u);let{data:k,error:S}=await this._getUser(i);if(S)throw S;let O={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:d,expires_at:f,refresh_token:o,token_type:l,user:k.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:O,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Vt(window.location.href);return!!(J()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Vt(window.location.href),t=await yt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:n,error:i}=t;if(i)return{error:i};let o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Mr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Lr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,n;try{let{data:{session:i},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Se(this.storage,this.storageKey,!0));try{return await T(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(E(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:n}=await this._useSession(async i=>{var o,a,c,l,u;let{data:d,error:f}=i;if(f)throw f;let g=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",g,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return J()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(E(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,n;let{data:i,error:o}=t;if(o)throw o;return await T(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Ur(async n=>(n>0&&await $r(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:le})),(n,i)=>{let o=200*Math.pow(2,n);return i&&Qt(i)&&Date.now()+o-s<St})}catch(s){if(this._debug(t,"error",s),E(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),J()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await yt(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let n=Math.round(Date.now()/1e3),i=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<n+xs;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${xs}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Qt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new se;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new _t;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new se;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let a={session:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(n,"error",i),E(i)){let o={session:null,error:i};return Qt(i)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,s=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ps(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Yt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&J()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),St);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/St);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${St}ms, refresh threshold is ${zr} ticks`),n<=zr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof kt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!J()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let n=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,o]=await Se(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s?.queryParams){let i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;return i?{data:null,error:i}:await T(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,n;let{data:i,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await T(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((n=a?.totp)===null||n===void 0)&&n.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;if(i)return{data:null,error:i};let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;return i?{data:null,error:i}:await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],n=s.filter(i=>i.factor_type==="totp"&&i.status==="verified");return{data:{all:s,totp:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:n},error:i}=e;if(i)return{data:null,error:i};if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(n.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=n.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let u=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}};Re.nextInstanceID=0;var Ei=Re,$s=Ei;var es=class extends $s{constructor(e){super(e)}};var Ti=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Et=class{constructor(e,t,s){var n,i,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=Ar(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,l={db:Sr,realtime:Tr,auth:Object.assign(Object.assign({},Er),{storageKey:c}),global:kr},u=xr(s??{},l);this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=Cr(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},u.realtime)),this.rest=new cr(`${a}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new tt(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new pt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Ti(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:n,storageKey:i,flowType:o,debug:a},c,l){var u;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new es({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:n,flowType:o,debug:a,fetch:l,hasCustomAuthorizationHeader:(u="Authorization"in this.headers)!==null&&u!==void 0?u:!1})}_initRealtimeClient(e){return new Ne(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Jr=(r,e,t)=>new Et(r,e,t);var ue={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Ci=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},ts=r=>{let[e,t]=r.split(".");return!e||!t?null:Ci(t)},Ge=r=>{let e=ts(r);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Ai="https://api.workos.com",xi=60,Je=(r,e)=>typeof r[e]=="string"?r[e]:void 0,Vr=(r,e,t)=>{let s=ts(r);if(!s)return null;let n=Je(s,"urn:wispr:user_external_id")??Je(s,"sub"),i=t?.email??Je(s,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof s.exp=="number"?s.exp:void 0,c={id:n??"",aud:"authenticated",email:i,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},Ri=async(r,e,t,s)=>{let n=t?.startsWith("https://")?t.replace(/\/$/,""):Ai,i=await fetch(`${n}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:r,organization_id:s})});if(!i.ok){let o=await i.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${i.status}`)}return await i.json()},Kr=async(r,e)=>{let t=ts(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),n=typeof t.exp=="number"?t.exp:0,i=Je(t,"client_id");if(n-s<xi&&i){let c=await Ri(e,i,Je(t,"iss"),Je(t,"org_id")),l=Vr(c.access_token,c.refresh_token,c.user);if(!l)throw new Error("WorkOS refresh returned an invalid access token");return l}if(n<=s)throw new Error("WorkOS session expired");let a=Vr(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Ve=class{constructor(){this.sessionData=null;this.supabase=Jr(ue.supaBaseUrl,ue.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ue.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||ue.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||ue.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:n}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(n)throw n;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let n=new Date;n.setTime(n.getTime()+s*24*60*60*1e3);let i=`expires=${n.toUTCString()}`;document.cookie=`${e}=${t};${i};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{if(Ge(t)==="workos"){this.sessionData=await Kr(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(n){throw n}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,n]=t.split("=");return e[s]=n,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ue.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,n,i,o){try{if(!i)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,l=await N.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:i,device_code:c,redirect_url:n||ue.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),l}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,s,n){try{if(!s)throw new Error("Please complete the verification");let i=await N.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:n?.provision??!1,workos_capable:n?.workosCapable||void 0});if(It(i))return{kind:"otp",challenge:i};if(!i.access_token||!i.refresh_token)throw new Error(i.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:i.access_token,refreshToken:i.refresh_token,fullName:[i.first_name,i.last_name].filter(Boolean).join(" ")||void 0,provider:i.provider||void 0}}catch(i){throw console.error("Error signing in with password:",i),i}}async resendVerificationEmail(e,t,s,n){try{if(!s)throw new Error("Please complete the verification");let i=await N.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||ue.redirectUri,workos_capable:n?.workosCapable||void 0});return console.log("Verification request completed"),i}catch(i){throw console.error("Error resending verification email:",i),i}}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 ss=null,Yr=(r,e)=>{if(!(r instanceof Error)||r.name!=="AriaAuthError")return e;let t={verification_failed:"Incorrect or expired code. Try again.",invalid_code:"Enter the six-digit code.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again."},{code:s}=r;return s&&t[s]||e},rs=()=>{ss!==null&&(window.clearInterval(ss),ss=null)};function Pe(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),rs()}function Xr(r){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),s=document.querySelector("[otp-email]"),n=document.querySelector("[otp-verify]"),i=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),c=document.querySelector("[otp-resend-countdown]"),l=document.querySelector("[otp-resend-seconds]"),u=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),i&&(i.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),n&&(n.textContent="Verify",n.style.pointerEvents="",n.removeAttribute("aria-disabled")),rs(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let d=h=>{i&&(i.style.display="block"),o&&(o.textContent=h)},f=()=>{i&&(i.style.display="none")},g=!1,v=!1,k=h=>{n&&(n.style.pointerEvents=h?"none":"",h?n.setAttribute("aria-disabled","true"):n.removeAttribute("aria-disabled"),n instanceof HTMLButtonElement&&(n.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},S=async()=>{if(g)return;let h=t.map(m=>m.value).join("");if(h.length!==6){d("Please enter all 6 digits.");return}g=!0,k(!0),t.forEach(m=>m.setAttribute("disabled","true")),f();try{await r.onVerify(h),f(),n&&(n.textContent="Verified \u2705")}catch(m){g=!1,k(!1),t.forEach(R=>{R.value="",R.removeAttribute("disabled")}),d(Yr(m,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,m)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&m<t.length-1&&t[m+1].focus(),f()},h.onkeydown=R=>{R.key==="Backspace"&&!h.value&&m>0?t[m-1].focus():R.key==="Enter"&&(R.preventDefault(),S())},h.onpaste=R=>{R.preventDefault();let L=(R.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);L.split("").forEach((W,Z)=>{t[Z]&&(t[Z].value=W)});let ie=Math.min(L.length,t.length-1);t[ie]?.focus(),f()}}),n&&(n.onclick=h=>{h.preventDefault(),S()});let O=()=>{let h=30;a&&(a.style.display="none"),c&&(c.style.display="block"),l&&(l.textContent=String(h)),rs(),ss=window.setInterval(()=>{h-=1,l&&(l.textContent=String(h)),h<=0&&(rs(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(v||a.style.display==="none")){v=!0,t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),t[0]?.focus(),f(),O();try{await r.onResend?.()}catch(m){d(Yr(m,"We couldn't send a new code. Please try again when the timer ends."))}finally{v=!1}}}),u&&(u.onclick=h=>{h.preventDefault(),Pe(),r.onReset?.()})}var Oe=()=>window.hcaptcha,ns=async()=>{let r=Oe();if(!r)throw new Error("Verification system not loaded");let e=await r.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Tt=(r,e)=>r instanceof Error?r.message:e,Qr=(r,e)=>r instanceof Q?r.code==="sso_required"?(e.showSso(),!0):r.code==="scim_managed_domain"?(e.showScim(),!0):(r.code==="sign_in_to_continue"&&e.showLogin(),e.showError(r.message),!0):!1,Zr=r=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(s){e={pendingAuthenticationToken:s.pendingAuthenticationToken,email:F(s.email)},r.beforeShow(),Xr({email:e.email,onVerify:async n=>{if(!e)throw Pe(),r.onMissingChallenge(),new Error("Missing OTP challenge");let i=await N.verifyEmailOtp({code:n,pending_authentication_token:e.pendingAuthenticationToken});t(),await r.onAuthenticated(i)},onResend:async()=>{if(!e)throw Pe(),r.onMissingChallenge(),new Error("Missing OTP challenge");let n=await ns();try{await r.client.resendVerificationEmail(e.email,r.redirectUrl,n,{workosCapable:r.isWorkosCapable(e.email)})}finally{Oe()?.reset()}},onReset:()=>{t(),r.onReset()}})}}};var ne=null;function Us(r,e=30,t){ne&&(clearInterval(ne),ne=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,ne=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",ne&&(clearInterval(ne),ne=null),t&&t())},1e3)}function en(){ne&&(clearInterval(ne),ne=null)}var tn=/^[\p{L}\p{M}\s\-'.]+$/u;function Pi(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":tn.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Ds(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":tn.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function sn(r,e,t){let s="full-name-match-error",n=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let l=document.getElementById(s);l||(l=document.createElement("div"),l.id=s,l.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",l)),l.textContent=c},i=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=Pi(e.value,r.value);c?n(c):i()},a=()=>{let c=Ds(e.value,r.value);c?n(c):i()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var rn="password-rejection-error",nn=r=>r instanceof Q?r.passwordRejectionMessage:null,Ct=r=>{r.classList.remove("error"),document.getElementById(rn)?.remove()},Ms=(r,e)=>{if(Ct(r),e.length===0)return;r.classList.add("error");let t=document.createElement("div");t.id=rn,t.style.fontSize="0.875rem",t.textContent=e,r.insertAdjacentElement("afterend",t)};var Oi="wisprjam.com",Ii="wispr.ai",Li="wispr_workos_capable",ji=r=>r.trim().toLowerCase().split("@")[1]??"",an=r=>{let e=ji(r);return e===Oi||e===Ii},on=()=>{try{return window.sessionStorage.getItem(Li)==="true"}catch{return!1}};function cn(r,e){let t=new Ve,s="email_input",n=null,i=()=>{n?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),l=document.querySelector("#full-name"),u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),g=document.querySelector("[email-element]"),v=document.querySelector("[different-provider]"),k=document.querySelector("[different-provider-name]"),S=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),R=document.querySelector("[verification-email]"),L=document.querySelector("[email-signup-retry]"),ie=document.querySelector("[email-signup-reset]"),W=document.querySelector("[scim-div]"),Z=document.querySelector("[scim-reset]"),D=document.querySelector("[forgot-password]"),ge=document.querySelector("[forgot-password-success]"),de=document.querySelector("[forgot-password-email]"),B=document.querySelector("[unverified-email]"),At=document.querySelector("[unverified-email-address]"),V=document.querySelector("[resend-verification-email]"),M=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(u&&u.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(_){console.error("Error during Google sign-in:",_)}}),d&&d.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(_){console.error("Error during Apple sign-in:",_)}}),f&&f.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(_){console.error("Error during Microsoft sign-in:",_)}}));let K=()=>{i(),v&&(v.style.display="none"),O&&(O.style.display="none"),h&&(h.style.display="none"),B&&(B.style.display="none"),W&&(W.style.display="none"),D&&(D.style.display="none"),ge&&(ge.style.display="none"),Pe();let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="block"),g&&(g.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),c&&(c.value="",c.style.display="none",c.removeAttribute("required"),Ct(c)),l&&(l.value="",l.style.display="none",l.removeAttribute("required"));let b=document.querySelector("[captcha-embed]"),C=document.querySelector("#h-captcha-container");b&&(b.style.display="none"),C&&(C.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",a&&a.focus()},oe=()=>{g&&(g.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="none",l.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),D&&(D.style.display="block",D.onclick=async()=>{let C=a?.value||"",p=D.textContent||"";try{let{hcaptcha:y}=window;if(!y)throw new Error("Verification system not loaded. Please refresh the page.");D.style.pointerEvents="none",D.textContent="Sending...";let{response:w}=await y.execute({async:!0});if(!w)throw new Error("Verification cancelled");await N.requestPasswordReset(C,w),y.reset(),g&&(g.style.display="none"),D&&(D.style.display="none"),ge&&(ge.style.display="block"),de&&(de.textContent=C)}catch(y){console.error("Error sending password reset email:",y),D.textContent=p,D.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",m&&(m.textContent=y instanceof Error?y.message:"Failed to send reset email"))}}),s="login"},Ke=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="block",l.setAttribute("required","true"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),s="signup"},me=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),W&&(W.style.display="block"),Z&&(Z.onclick=()=>{W&&(W.style.display="none"),_&&(_.style.display="block"),K()})},Ie=_=>{i();let b=Js(_);g&&(g.style.display="none"),v&&(v.style.display="block"),k&&(k.textContent=b),S&&(S.onclick=()=>{v&&(v.style.display="none"),K()}),s="oauth_user"},Ye=async(_,b)=>{let C=await N.signInWithEmail({email:_,password:b,mcp_login_state:e?.mcpLoginState??void 0,workos_capable:on()});if(!C.redirect_url)throw new Error(C.error||"Unable to continue connector login. Please try again.");x("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=C.redirect_url};n=Zr({client:t,redirectUrl:r,isWorkosCapable:()=>!0,beforeShow:()=>{g&&(g.style.display="none"),B&&(B.style.display="none")},onAuthenticated:async _=>{if(i(),t.setCookies(_.access_token,_.refresh_token),localStorage.setItem("email",_.email),localStorage.setItem("user_id",_.user_id),localStorage.setItem("signin_provider","email"),e?.mcpLoginState){try{await Ye(_.email,c.value)}catch(C){Pe(),oe(),X(C)||(h&&(h.style.display="block"),m&&(m.textContent="Unable to continue connector login. Please sign in again."))}return}let b=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,b):window.location.href=r},onMissingChallenge:oe,onReset:K});let ae=_=>{g&&(g.style.display="none"),B&&(B.style.display="block"),At&&(At.textContent=_),V&&(V.onclick=async()=>{let b=V.textContent||"";try{let C=await ns();await t.resendVerificationEmail(_,r,C),V.textContent="Verification email resent! \u2705",V.style.textDecoration="none"}catch(C){V.textContent=b,h&&(h.style.display="block"),m&&(m.textContent=Tt(C,"Unable to resend verification."))}finally{Oe()?.reset()}}),M&&(M.onclick=()=>{B&&(B.style.display="none"),K()}),s="unverified_email"},X=_=>Qr(_,{showSso:()=>Ie("workos"),showScim:me,showLogin:oe,showError:b=>{h&&(h.style.display="block"),m&&(m.textContent=b)}}),Xe=async(_,b)=>{let C=b.value;b.classList.add("loading"),b.value="";try{let p=await N.checkUserStatus(_);b.classList.remove("loading"),b.value=C,!p.exists&&p.scim_managed?me():p.enforce_sso?Ie("workos"):p.exists&&p.provider&&p.provider!=="email"&&p.provider!=="workos"?Ie(p.provider):p.exists&&p.provider==="workos"?oe():p.exists&&p.provider==="email"&&!p.verified?ae(_):p.exists&&p.provider==="email"?oe():Ke()}catch(p){console.error("Error checking user status:",p),b.classList.remove("loading"),b.value=C,X(p)||Ke()}},Le=async(_,b,C,p)=>{if(!b||b.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let y=window.hcaptcha?.getResponse()||"";if(!y){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}C.classList.add("loading"),C.value="";try{if(e?.mcpLoginState){await Ye(_,b);return}let w=on(),A=await t.signInWithPassword(_,b,y,{workosCapable:w,provision:!1});if(A.kind==="otp"){if(!w)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let P={pendingAuthenticationToken:A.challenge.pending_authentication_token,email:F(A.challenge.email||_)};Oe()?.reset(),C.classList.remove("loading"),C.value=p,n?.show(P);return}t.setCookies(A.accessToken,A.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(A.accessToken,A.refreshToken,A.fullName):window.location.href=r}catch(w){window.hcaptcha&&window.hcaptcha.reset(),C.classList.remove("loading"),C.value=p,!X(w)&&h&&(h.style.display="block",m&&(m.textContent=Tt(w,"Unable to sign in. Please try again.")))}},os=async(_,b,C,p,y)=>{if(!b||b.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(b.trim().toLowerCase()===_.trim().toLowerCase()){Ms(c,"Password can't be the same as your email address.");return}if(!C||C.trim().length<2){h&&(h.style.display="block",m&&(m.textContent="Please enter your full name"));return}let w=Ds(C,b);if(w){h&&(h.style.display="block",m&&(m.textContent=w));return}let A=window.hcaptcha?.getResponse()||"";if(!A){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}p.classList.add("loading"),p.value="";try{let P=await t.signUpWithPassword(_,b,C,r,A,{workosCapable:!0,deviceCode:e?.deviceCode});if(window.hcaptcha&&window.hcaptcha.reset(),p.classList.remove("loading"),p.value=y,g&&(g.style.display="none"),h&&(h.style.display="none"),It(P)){let $={pendingAuthenticationToken:P.pending_authentication_token,email:F(P.email||_)};n?.show($);return}O&&(O.style.display="block"),R&&(R.textContent=_),L&&(Us(L,30),L.onclick=async()=>{if(L.style.pointerEvents!=="none")try{let $=await ns();await t.resendVerificationEmail(_,r,$,{workosCapable:!0}),Us(L,30)}catch($){h&&(h.style.display="block"),m&&(m.textContent=Tt($,"Unable to resend verification. Please try again."))}finally{Oe()?.reset()}}),ie&&(ie.onclick=()=>{O&&(O.style.display="none"),en(),K()})}catch(P){p.classList.remove("loading"),p.value=y,Oe()?.reset();let $=nn(P);$&&c?Ms(c,$):!X(P)&&h&&(h.style.display="block",m&&(m.textContent=Tt(P,"Unable to create the account. Please try again.")))}};return o&&c&&l&&(sn(c,l,o.querySelector('[type="submit"]')),c.addEventListener("input",()=>Ct(c))),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let b=F(a?.value||"");a&&(a.value=b);let C=c?.value||"",p=l?.value||"";if(!b||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b)){h&&(h.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),m&&(m.textContent=""),c&&Ct(c);let w=o.querySelector('[type="submit"]'),A=w?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await Xe(b,w):s==="login"?await Le(b,C,w,A):s==="signup"&&await os(b,C,p,w,A)}catch(P){console.error("Auth flow error:",P),w&&(w.classList.remove("loading"),w.value=A),h&&(h.style.display="block")}}),{reset:K}}var $i="wf_first_landing_url";var ln=()=>{try{return localStorage.getItem($i)||void 0}catch{return}};var Ui=/google ads|google adservices|adwords/i,Di=/marketing|advertising/i,dn="JQ2XQxIk",Mi="linkedin insight tag",Ni="ko1w5PpFl",qi="facebook pixel",Fi="BkeKqEjuoZQ",Hi="microsoft advertising",Wi=r=>{let e=r.filter(s=>Ui.test(s.name??""));if(e.length>0)return e.every(s=>s.decision===!0)?{ad_user_data:!0,ad_personalization:!0}:e.every(s=>s.decision===!1)?{ad_user_data:!1,ad_personalization:!1}:void 0;let t=r.filter(s=>Di.test(s.category??""));if(t.length!==0){if(t.some(s=>s.decision===!0))return{ad_user_data:!0,ad_personalization:!0};if(t.every(s=>s.decision===!1))return{ad_user_data:!1,ad_personalization:!1}}},un=r=>{let e=Wi(r),t=r.filter(d=>d.id===dn),s=t.length?t:r.filter(d=>typeof d.name=="string"&&d.name.trim().toLowerCase()===Mi),n=s.length===1?s[0].linkedinConsent:void 0,i=r.filter(d=>d.id===Ni),o=i.length?i:r.filter(d=>typeof d.name=="string"&&d.name.trim().toLowerCase()===qi),a=o.length===1?o[0].metaConsent:void 0,c=r.filter(d=>d.id===Fi),l=c.length?c:r.filter(d=>typeof d.name=="string"&&d.name.trim().toLowerCase()===Hi),u=l.length===1?l[0].microsoftConsent:void 0;if(!(!e&&n===void 0&&a===void 0&&u===void 0))return{...e,...n===void 0?{}:{linkedin_ads_consent:n.given,linkedin_ads_consent_type:n.type},...a===void 0?{}:{meta_ads_consent:a.given,meta_ads_consent_type:a.type},...u===void 0?{}:{microsoft_ads_consent:u.given,microsoft_ads_consent_type:u.type}}},is=(r,e)=>{if(typeof r=="boolean")return{given:r,...e==="EXPLICIT"||e==="IMPLICIT"?{type:e}:{}}},Ns=r=>{if(typeof r?.status!="boolean")return;let e={given:r.status},{history:t}=r;if(!Array.isArray(t)||!t.length||t.some(o=>!Number.isFinite(o?.timestamp)))return e;let s=Math.max(...t.map(o=>o.timestamp)),n=t.filter(o=>o.timestamp===s),i=is(r.status,n[0].type);return i?.type&&n.every(o=>o.type===i.type&&o.status===i.given)?i:e},Bi=async()=>{try{let{__ucCmp:r,UC_UI:e}=window;if(r?.getConsentDetails){let t=await r.getConsentDetails();return un(Object.entries(t?.services??{}).map(([s,n])=>({id:s,name:n?.name,category:n?.category,linkedinConsent:is(n?.consent?.given,n?.consent?.type),metaConsent:is(n?.consent?.given,n?.consent?.type),microsoftConsent:is(n?.consent?.given,n?.consent?.type),decision:n?.consent?.type==="EXPLICIT"&&typeof n.consent.given=="boolean"?n.consent.given:void 0})))}if(e?.getServicesBaseInfo)return un((e.getServicesBaseInfo()??[]).map(t=>{let s=Ns(t.consent),n=Ns(t.consent),i=Ns(t.consent);return{id:t?.id,name:t?.name,category:t?.categorySlug,linkedinConsent:s,metaConsent:n,microsoftConsent:i,decision:t?.id===dn?s?.type==="EXPLICIT"?s.given:void 0:t?.consent?.history?.some(o=>o?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0}}))}catch{}},hn=()=>{let r=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([Bi(),r])};function fn(r){try{let e=r._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let s=t.split(".");if(s.length>=3){let n=s.slice(2).join(".");if(n)return n}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var qs="https://api.wisprflow.ai",pn="https://wisprflow.ai/login",zi="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new Ve,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),s=document.querySelector("[error-div]"),n=document.querySelector("[error-message-api]"),i=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),l=c?.value??"",u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),g=document.querySelector("#sso-login"),v=document.querySelector("[sso-login-div]"),k=document.querySelector("#sso-email"),S=document.querySelector("#sso-signup-form"),O=document.querySelector('[sso-login="go-back"]'),h=document.querySelector(".gs-hero_form-block"),m=localStorage.getItem("last_authed_provider");m&&{google:u,apple:d,microsoft:f,sso:g,email:document.querySelector("#email-input")}[m]?.classList.add("last-used");let R=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},L=()=>{let y=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";x("desktop_login_auto_launch",{deep_link:y}),window.location.href=y},ie=()=>{let p=localStorage.getItem("signin_provider");p&&localStorage.setItem("last_authed_provider",p),e&&(e.style.display="none"),t&&(t.style.display="block"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",L()},W=p=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),n&&(n.textContent=p),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},Z=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},D=null,ge=document.querySelector("[retry-button]");ge&&ge.addEventListener("click",()=>de());let de=()=>{e&&(e.style.display="none"),s&&(s.style.display="none"),a&&(a.style.display="none"),i&&(i.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=l),D&&D()},B=async(p,y)=>{try{let[w,A]=Gs(y||" "),P=N.signupUser({access_token:p,first_name:w,last_name:A}),$=new Promise((je,_e)=>setTimeout(()=>_e(new Error("signup timeout")),4e3));await Promise.race([P,$])}catch(w){x("signup_sync_error",{error_message:w instanceof Error?w.message:String(w)})}},At=()=>{let p=sessionStorage.getItem("wispr_fbclid");return p?`fb.1.${Date.now()}.${p}`:null},V=async(p,y)=>{let w=sessionStorage.getItem("wispr_device_code");if(!w)throw new Error("Device code not found. Please restart authentication from desktop app.");let A=Qe(),P=await hn(),$=localStorage.getItem("wf_utm_source")||void 0,je=localStorage.getItem("wf_utm_medium")||void 0,_e=localStorage.getItem("wf_utm_campaign")||void 0,xt=await fetch(`${qs}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${p}`},body:JSON.stringify({device_code:w,access_token:p,refresh_token:y,fbp:A._fbp||void 0,fbc:A._fbc||At()||void 0,gclid:fn(A),utm:$||je||_e?{utm_source:$,utm_medium:je,utm_campaign:_e}:void 0,first_landing_url:ln(),ad_user_data:P?.ad_user_data,ad_personalization:P?.ad_personalization,linkedin_ads_consent:P?.linkedin_ads_consent,linkedin_ads_consent_type:P?.linkedin_ads_consent_type,meta_ads_consent:P?.meta_ads_consent,meta_ads_consent_type:P?.meta_ads_consent_type,microsoft_ads_consent:P?.microsoft_ads_consent,microsoft_ads_consent_type:P?.microsoft_ads_consent_type})});if(!xt.ok){let Rt=await xt.json().catch(()=>({}));throw xt.status===403&&Rt?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(Rt?.detail?.message||Rt.message||`Server error: ${xt.status}`)}console.log("Device authentication complete"),sessionStorage.removeItem("wispr_device_code"),Ge(p)==="workos"&&r.setCookie("refresh_token",y,30/86400)},M=new URLSearchParams(window.location.search),K=M.get("device_code"),oe=M.get("error"),Ke=M.get("workos_capable");Ke==="true"?sessionStorage.setItem("wispr_workos_capable","true"):Ke==="false"&&sessionStorage.removeItem("wispr_workos_capable");let me=sessionStorage.getItem("wispr_workos_capable")==="true",Ie=M.get("auto_signin")==="true",Ye=new URLSearchParams(window.location.hash.slice(1)),Y=M.get("access_token")||Ye.get("access_token"),ae=M.get("refresh_token")||Ye.get("refresh_token"),X=M.get("mcp_login_state");if(!K&&!Y&&!ae&&!X&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),x("desktop_login_no_device_code"),window.location.href="/get-started";return}if(x("desktop_login_page_view",{auto_signin:Ie,workos_capable:me}),K){sessionStorage.setItem("wispr_device_code",K);let p=M.get("fbclid");p&&sessionStorage.setItem("wispr_fbclid",p);let y=M.get("skip_default_trial"),w=M.get("grant_weekly_bonus");y&&sessionStorage.setItem("wispr_skip_default_trial",y),w&&sessionStorage.setItem("wispr_grant_weekly_bonus",w)}(K||Y||ae||oe)&&window.history.replaceState({},"","/login");let Xe="wispr_workos_second_hop_attempted";if(Y&&ae){console.log("OAuth callback detected - handling tokens");let p=Ge(Y);if(x("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:p}),R(),p==="workos"){sessionStorage.removeItem(Xe);try{r.setCookies(Y,ae);let y=M.get("email");y&&localStorage.setItem("email",y);let w=M.get("user_id");w&&localStorage.setItem("user_id",w),await B(Y,M.get("name")??void 0),await N.applyPromoCodeFromCookie(Y),await V(Y,ae),x("desktop_login_complete_success",{method:"oauth",provider:"workos"}),ie()}catch(y){if(y instanceof Error&&y.message==="enterprise_ip_not_allowed"){x("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),Z();return}let w=y instanceof Error?y.message:"Failed to complete authentication. Please try again.";x("desktop_login_complete_error",{method:"oauth",provider:"workos",error:w}),console.error("Error completing WorkOS device authentication:",y),W(w)}return}try{let y=Y,w=ae;try{r.setCookies(Y,ae),await r.checkAndSetSession(),r.sessionData&&(y=r.sessionData.access_token,w=r.sessionData.refresh_token,r.setCookies(y,w),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}let A=r.sessionData?.user.email;if(me&&A&&an(A)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(Xe)){sessionStorage.setItem(Xe,"true"),x("desktop_login_workos_second_hop",{email_domain:A.split("@")[1]??"unknown"}),window.location.href=`${qs}/authkit/google/sign_in?source=${pn}`;return}await B(y,r.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(y),await V(y,w),x("desktop_login_complete_success",{method:"oauth"}),ie()}catch(y){if(y instanceof Error&&y.message==="enterprise_ip_not_allowed"){x("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),Z();return}let w=y instanceof Error?y.message:"Failed to complete authentication. Please try again.";x("desktop_login_complete_error",{method:"oauth",error:w}),console.error("Error completing device authentication:",y),W(w)}return}if(Ie){console.log("Auto-signin enabled - checking existing session"),R();try{if(await r.checkAndSetSession(),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token),r.sessionData?.access_token&&r.sessionData?.refresh_token){console.log("Existing session found - auto-completing authentication"),await B(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(r.sessionData.access_token),await V(r.sessionData.access_token,r.sessionData.refresh_token),x("desktop_login_auto_signin_success",{token_provider:Ge(r.sessionData.access_token)}),ie();return}console.log("No existing session - showing login form"),x("desktop_login_auto_signin_no_session"),de()}catch(p){if(console.error("Auto-signin error:",p),p instanceof Error&&p.message==="enterprise_ip_not_allowed"){x("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),Z();return}let y=p instanceof Error?p.message:"Auto-signin failed. Please try logging in manually.";x("desktop_login_auto_signin_error",{error:y}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),de()}}else X?(x("desktop_login_mcp_entry"),de()):(x("desktop_login_manual_signout"),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status"),de());let Le=(p,y)=>{console.log(`Redirecting to ${p} OAuth`);let w=window.posthog?.getFeatureFlag?.(zi)===!0,A=me&&w;x("desktop_login_oauth_click",{provider:A?"workos":p,idp:p,mcp:!!X,workos_capable:me,workos_enabled_webflow:w}),localStorage.setItem("signin_provider",p);let P=A?`authkit/${p}/sign_in`:`${p}/sign_in`,$=`${qs}/${P}?source=${pn}`;y&&($+=`&email=${encodeURIComponent(y)}`);let je=sessionStorage.getItem("wispr_skip_default_trial"),_e=sessionStorage.getItem("wispr_grant_weekly_bonus");je&&($+=`&skip_default_trial=${encodeURIComponent(je)}`),_e&&($+=`&grant_weekly_bonus=${encodeURIComponent(_e)}`),X&&($+=`&mcp_login_state=${encodeURIComponent(X)}`),window.location.href=$};u&&u.addEventListener("click",()=>{Le("google")}),d&&d.addEventListener("click",()=>{Le("apple")}),f&&f.addEventListener("click",()=>{Le("microsoft")}),g&&(g.style.display="flex",g.addEventListener("click",p=>{p.preventDefault(),v&&(v.style.display="block"),h&&(h.style.display="none"),k?.focus()})),O&&O.addEventListener("click",()=>{v&&(v.style.display="none"),h&&(h.style.display="block"),k&&(k.value="",k.blur())}),S&&S.addEventListener("submit",p=>{p.preventDefault(),p.stopPropagation();let y=F(k?.value||"");y&&Le("sso",y)});let os=async(p,y,w)=>{try{await B(p,w),await N.applyPromoCodeFromCookie(p),await V(p,y)}catch(A){if(A instanceof Error&&A.message==="enterprise_ip_not_allowed"){x("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),Z();return}let P=A instanceof Error?A.message:"Failed to complete authentication. Please try again.";x("desktop_login_complete_error",{method:"email",error:P}),W(P);return}x("desktop_login_complete_success",{method:"email"}),ie()},_=sessionStorage.getItem("wispr_device_code"),b=_?`${window.location.origin}/login?device_code=${_}`:`${window.location.origin}/login`,{reset:C}=cn(b,{onLoginSuccess:os,deviceCode:_??void 0,mcpLoginState:X,skipOAuthButtons:!0});D=C,oe==="account_unsupported"&&(x("desktop_login_oauth_error",{error:oe}),W("This account is not supported. Try signing in with another account.")),console.log("Desktop login page initialized")});})();
|
|
1
|
+
"use strict";(()=>{var wn=Object.create;var It=Object.defineProperty;var vn=Object.getOwnPropertyDescriptor;var bn=Object.getOwnPropertyNames;var kn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var En=(r,e)=>()=>(r&&(e=r(r=0)),e);var ee=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Tn=(r,e)=>{for(var t in e)It(r,t,{get:e[t],enumerable:!0})},Hs=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of bn(e))!Sn.call(r,n)&&n!==t&&It(r,n,{get:()=>e[n],enumerable:!(s=vn(e,n))||s.enumerable});return r};var Ws=(r,e,t)=>(t=r!=null?wn(kn(r)):{},Hs(e||!r||!r.__esModule?It(t,"default",{value:r,enumerable:!0}):t,r)),Cn=r=>Hs(It({},"__esModule",{value:!0}),r);var ye={};Tn(ye,{Headers:()=>us,Request:()=>Dn,Response:()=>Mn,default:()=>ls,fetch:()=>Un});var $n,Ue,Un,ls,us,Dn,Mn,he=En(()=>{"use strict";$n=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")},Ue=$n(),Un=Ue.fetch,ls=Ue.fetch.bind(Ue),us=Ue.Headers,Dn=Ue.Request,Mn=Ue.Response});var Ys=ee(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var ds=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};hs.default=ds});var ps=ee(rt=>{"use strict";var Xs=rt&&rt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rt,"__esModule",{value:!0});var qn=Xs((he(),Cn(ye))),Fn=Xs(Ys()),fs=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=qn.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var o,a,c;let l=null,u=null,d=null,f=i.status,p=i.statusText;if(i.ok){if(this.method!=="HEAD"){let w=await i.text();w===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=w:u=JSON.parse(w))}let E=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),S=(a=i.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");E&&S&&S.length>1&&(d=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(l={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,d=null,f=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{let E=await i.text();try{l=JSON.parse(E),Array.isArray(l)&&i.status===404&&(u=[],l=null,f=200,p="OK")}catch{i.status===404&&E===""?(f=204,p="No Content"):l={message:E}}if(l&&this.isMaybeSingle&&(!((c=l?.details)===null||c===void 0)&&c.includes("0 rows"))&&(l=null,f=200,p="OK"),l&&this.shouldThrowOnError)throw new Fn.default(l)}return{error:l,data:u,count:d,status:f,statusText:p}});return this.shouldThrowOnError||(n=n.catch(i=>{var o,a,c;return{error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:`${(a=i?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=i?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}};rt.default=fs});var ms=ee(nt=>{"use strict";var Hn=nt&&nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(nt,"__esModule",{value:!0});var Wn=Hn(ps()),gs=class extends Wn.default{select(e){let t=!1,s=(e??"*").split("").map(n=>/\s/.test(n)&&!t?"":(n==='"'&&(t=!t),n)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:n,referencedTable:i=n}={}){let o=i?`${i}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:n=s}={}){let i=typeof n>"u"?"offset":`${n}.offset`,o=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:n=!1,wal:i=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${l}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};nt.default=gs});var Nt=ee(it=>{"use strict";var Bn=it&&it.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(it,"__esModule",{value:!0});var zn=Bn(ms()),_s=class extends zn.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(n=>typeof n=="string"&&new RegExp("[,()]").test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${i}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let n=s?`${s}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};it.default=_s});var ws=ee(at=>{"use strict";var Gn=at&&at.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(at,"__esModule",{value:!0});var ot=Gn(Nt()),ys=class{constructor(e,{headers:t={},schema:s,fetch:n}){this.url=e,this.headers=t,this.schema=s,this.fetch=n}select(e,{head:t=!1,count:s}={}){let n=t?"HEAD":"GET",i=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new ot.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let n="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),s||i.push("missing=default"),this.headers.Prefer=i.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 ot.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:n,defaultToNull:i=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),n&&a.push(`count=${n}`),i||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",l.join(","))}}return new ot.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",n=[];return this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),this.headers.Prefer=n.join(","),new ot.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new ot.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};at.default=ys});var Qs=ee(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.version=void 0;qt.version="0.0.0-automated"});var Zs=ee(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.DEFAULT_HEADERS=void 0;var Jn=Qs();Ft.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Jn.version}`}});var tr=ee(ct=>{"use strict";var er=ct&&ct.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ct,"__esModule",{value:!0});var Vn=er(ws()),Kn=er(Nt()),Yn=Zs(),vs=class r{constructor(e,{headers:t={},schema:s,fetch:n}={}){this.url=e,this.headers=Object.assign(Object.assign({},Yn.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=n}from(e){let t=new URL(`${this.url}/${e}`);return new Vn.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:n=!1,count:i}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||n?(o=s?"HEAD":"GET",Object.entries(t).filter(([u,d])=>d!==void 0).map(([u,d])=>[u,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([u,d])=>{a.searchParams.append(u,d)})):(o="POST",c=t);let l=Object.assign({},this.headers);return i&&(l.Prefer=`count=${i}`),new Kn.default({method:o,url:a,headers:l,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ct.default=vs});var ar=ee(q=>{"use strict";var lt=q&&q.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(q,"__esModule",{value:!0});q.PostgrestBuilder=q.PostgrestTransformBuilder=q.PostgrestFilterBuilder=q.PostgrestQueryBuilder=q.PostgrestClient=void 0;var sr=lt(tr());q.PostgrestClient=sr.default;var rr=lt(ws());q.PostgrestQueryBuilder=rr.default;var nr=lt(Nt());q.PostgrestFilterBuilder=nr.default;var ir=lt(ms());q.PostgrestTransformBuilder=ir.default;var or=lt(ps());q.PostgrestBuilder=or.default;q.default={PostgrestClient:sr.default,PostgrestQueryBuilder:rr.default,PostgrestFilterBuilder:nr.default,PostgrestTransformBuilder:ir.default,PostgrestBuilder:or.default}});var mr=ee((Wo,gr)=>{"use strict";gr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Ze=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var R=(r,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:r,retry_attempt:10-t}),window.posthog.capture(r,e)):t>0&&setTimeout(()=>R(r,e,t-1),200)};var jt=r=>r.verification_method==="email_otp"&&typeof r.pending_authentication_token=="string"&&r.pending_authentication_token.length>0,j="https://api.wisprflow.ai",Q=class extends Error{constructor(t,s,n,i=null){super(n);this.status=t;this.code=s;this.passwordRejectionMessage=i;this.name="AriaAuthError"}},F=r=>r.trim().toLowerCase(),Bs=(r,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof r.code=="string"?r.code:r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:typeof r.detail=="string"&&t.has(r.detail)?r.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},et=(r,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[r]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),An=(r,e,t)=>[r.message,r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"?r.detail.message:null,typeof r.detail=="string"?r.detail:null].find(i=>typeof i=="string"&&i.length>0&&i!==e)??et(e,t),$e=(r,e)=>{let t=Bs(r,e);return new Q(e,t,An(r,t,e),e===400&&typeof r.detail=="string"&&r.detail.length>0?r.detail:null)},xn=(r,e)=>{let t=Bs(r,e);return new Q(e,t,et(t,e))},Lt="promo_code",Rn=4e3,Pn=new Set([200,400,403,404,409,422]),zs=r=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${r}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},Gs=r=>{if(!r)return"";try{return decodeURIComponent(r).trim()}catch{return""}},On=()=>{let r=Ze()[Lt];if(r===void 0)return"";let e=Gs(r);return e||zs(Lt),e},In=r=>{Gs(Ze()[Lt])===r&&zs(Lt)},Ln=r=>r instanceof DOMException&&(r.name==="TimeoutError"||r.name==="AbortError"),jn=(r,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:e===422?"validation_error":"unknown",cs=class{static async signupUser(e){try{let t=`${j}/signup`,n=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),i=n&&n.trim().split("=")[1];(i==="3mo"||i==="2mo")&&(t+=`?trial_promo=${i}`);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(`${j}/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(`${j}/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(`${j}/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(`${j}/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=F(e),s=await fetch(`${j}/user_status?email=${encodeURIComponent(t)}`),n=await s.json().catch(()=>({}));if(!s.ok)throw $e(n,s.status);return n}static async requestPasswordReset(e,t){let s=await fetch(`${j}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:F(e),captcha_token:t})});if(!s.ok){let n=await s.json().catch(()=>({}));throw $e(n,s.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${j}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async signInWithCaptcha(e){let t=await fetch(`${j}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${j}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new Q(422,"invalid_code",et("invalid_code",422));let t=await fetch(`${j}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok){let n=xn(s,t.status);throw n.code==="rate_limited"||n.code==="provider_unavailable"||n.code==="validation_error"?n:new Q(t.status,"verification_failed",et("verification_failed",t.status))}if(s.provider!=="workos"||!s.access_token||!s.refresh_token||!s.user_id||!s.email)throw new Q(t.status,"authentication_failed",et("authentication_failed",t.status));return s}static async signInWithEmail(e){let t=await fetch(`${j}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async applyPromoCodeFromCookie(e,t=On()){if(t)try{let s=await fetch(`${j}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(Rn)}),{status:n}=s;if(!Pn.has(n)){R("promo_cookie_apply",{outcome:"deferred",status:n});return}if(In(t),s.ok){R("promo_cookie_apply",{outcome:"attached",status:n});return}let i=await s.json().catch(()=>({}));R("promo_cookie_apply",{outcome:"rejected",status:n,reason:jn(i,n)})}catch(s){console.error("Promo cookie apply deferred:",s),R("promo_cookie_apply",Ln(s)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${j}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${j}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s,n){let i=new URLSearchParams({plan:e,custom_redirect:"true"});s&&i.set("currency",s),n?.trim()&&i.set("promo_code",n.trim());let o=`${j}/api/v1/payment/create-checkout-session?${i}`,a=await fetch(o,{method:"POST",headers:{accept:"application/json",Authorization:t}});if(!a.ok&&a.status!==303)throw new Error(`Checkout request failed (${a.status})`);let c=await a.json();if(!c||typeof c.url!="string"||!c.url)throw new Error("Checkout response is missing a URL");return c}static async sendDownloadLink(e,t){return await fetch(`${j}/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(`${j}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${j}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${j}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let n=new FormData;return n.append("screenshot",e),await fetch(`${j}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:n,signal:s})}};function Js(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function Vs(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var N=cs;var Ks=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(he(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var tt=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},$t=class extends tt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Ut=class extends tt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Dt=class extends tt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Mt;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(Mt||(Mt={}));var Nn=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},st=class{constructor(e,{headers:t={},customFetch:s,region:n=Mt.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=Ks(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Nn(this,void 0,void 0,function*(){try{let{headers:n,method:i,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let l;o&&(n&&!Object.prototype.hasOwnProperty.call(n,"Content-Type")||!n)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",l=o):typeof o=="string"?(a["Content-Type"]="text/plain",l=o):typeof FormData<"u"&&o instanceof FormData?l=o:(a["Content-Type"]="application/json",l=JSON.stringify(o)));let u=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),n),body:l}).catch(v=>{throw new $t(v)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new Ut(u);if(!u.ok)throw new Dt(u);let f=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield u.json():f==="application/octet-stream"?p=yield u.blob():f==="text/event-stream"?p=u:f==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(n){return{data:null,error:n}}})}};var cr=Ws(ar(),1),{PostgrestClient:lr,PostgrestQueryBuilder:Eo,PostgrestFilterBuilder:To,PostgrestTransformBuilder:Co,PostgrestBuilder:Ao}=cr.default;var ur="2.10.2";var dr={"X-Client-Info":`realtime-js/${ur}`},hr="1.0.0",Wt=1e4,fr=1e3,we;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(we||(we={}));var H;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(H||(H={}));var z;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(z||(z={}));var Ht;(function(r){r.websocket="websocket"})(Ht||(Ht={}));var fe;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(fe||(fe={}));var ut=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let n=t.getUint8(1),i=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+n));o=o+n;let c=s.decode(e.slice(o,o+i));o=o+i;let l=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:l}}};var ve=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var I;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(I||(I={}));var ks=(r,e,t={})=>{var s;let n=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((i,o)=>(i[o]=Xn(o,r,e,n),i),{})},Xn=(r,e,t,s)=>{let n=e.find(a=>a.name===r),i=n?.type,o=t[r];return i&&!s.includes(i)?pr(i,o):bs(o)},pr=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return ti(e,t)}switch(r){case I.bool:return Qn(e);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return Zn(e);case I.json:case I.jsonb:return ei(e);case I.timestamp:return si(e);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:return bs(e);default:return bs(e)}},bs=r=>r,Qn=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Zn=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},ei=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},ti=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let i,o=r.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>pr(e,a))}return r},si=r=>typeof r=="string"?r.replace(" ","T"):r,Bt=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var be=class{constructor(e,t,s={},n=Wt){this.channel=e,this.event=t,this.payload=s,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Ss;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(Ss||(Ss={}));var De=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,n,i,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=r.syncDiff(this.state,n,i,o),a())}),this.onJoin((n,i,o)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:o})}),this.onLeave((n,i,o)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,n){let i=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(i,(l,u)=>{o[l]||(c[l]=u)}),this.map(o,(l,u)=>{let d=i[l];if(d){let f=u.map(S=>S.presence_ref),p=d.map(S=>S.presence_ref),v=u.filter(S=>p.indexOf(S.presence_ref)<0),E=d.filter(S=>f.indexOf(S.presence_ref)<0);v.length>0&&(a[l]=v),E.length>0&&(c[l]=E)}else a[l]=u}),this.syncDiff(i,{joins:a,leaves:c},s,n)}static syncDiff(e,t,s,n){let{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(i,(a,c)=>{var l;let u=(l=e[a])!==null&&l!==void 0?l:[];if(e[a]=this.cloneDeep(c),u.length>0){let d=e[a].map(p=>p.presence_ref),f=u.filter(p=>d.indexOf(p.presence_ref)<0);e[a].unshift(...f)}s(a,u,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.map(d=>d.presence_ref);l=l.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=l,n(a,l,c),l.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let n=e[s];return"metas"in n?t[s]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[s]=n,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 Es;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(Es||(Es={}));var Ts;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(Ts||(Ts={}));var Cs;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Cs||(Cs={}));var Me=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=H.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 be(this,z.join,this.params,this.timeout),this.rejoinTimer=new ve(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=H.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=H.closed,this.socket._remove(this)}),this._onError(n=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,n),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this._on(z.reply,{},(n,i)=>{this._trigger(this._replyEventName(i),n)}),this.presence=new De(this),this.broadcastEndpointURL=Bt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,n;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:i,presence:o,private:a}}=this.params;this._onError(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("CLOSED"));let c={},l={broadcast:i,presence:o,postgres_changes:(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(u=>u.filter))!==null&&n!==void 0?n:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:u})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,p=(d=f?.length)!==null&&d!==void 0?d:0,v=[];for(let E=0;E<p;E++){let S=f[E],{filter:{event:w,schema:h,table:m,filter:O}}=S,L=u&&u[E];if(L&&L.event===w&&L.schema===h&&L.table===m&&L.filter===O)v.push(Object.assign(Object.assign({},S),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,n;if(!this._canPush()&&e.type==="broadcast"){let{event:i,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:i,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=c.body)===null||n===void 0?void 0:n.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,c;let l=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=H.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(z.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let n=new be(this,z.leave,{},e);n.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new be(this,e,t,s);return this._canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var n,i;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:l,join:u}=z;if(s&&[a,c,l,u].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,t,s);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(p=>{var v,E,S;return((v=p.filter)===null||v===void 0?void 0:v.event)==="*"||((S=(E=p.filter)===null||E===void 0?void 0:E.event)===null||S===void 0?void 0:S.toLocaleLowerCase())===o}).map(p=>p.callback(f,s)):(i=this.bindings[o])===null||i===void 0||i.filter(p=>{var v,E,S,w,h,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let O=p.id,L=(v=p.filter)===null||v===void 0?void 0:v.event;return O&&((E=t.ids)===null||E===void 0?void 0:E.includes(O))&&(L==="*"||L?.toLocaleLowerCase()===((S=t.data)===null||S===void 0?void 0:S.type.toLocaleLowerCase()))}else{let O=(h=(w=p?.filter)===null||w===void 0?void 0:w.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return O==="*"||O===((m=t?.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){let v=f.data,{schema:E,table:S,commit_timestamp:w,type:h,errors:m}=v;f=Object.assign(Object.assign({},{schema:E,table:S,commit_timestamp:w,eventType:h,new:{},old:{},errors:m}),this._getPayloadRecords(v))}p.callback(f,s)})}_isClosed(){return this.state===H.closed}_isJoined(){return this.state===H.joined}_isJoining(){return this.state===H.joining}_isLeaving(){return this.state===H.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let n=e.toLocaleLowerCase(),i={type:n,filter:t,callback:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&r.isEqual(n.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(z.close,{},e)}_onError(e){this._on(z.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=H.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ks(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ks(e.columns,e.old_record)),t}};var ni=()=>{},ii=typeof WebSocket<"u",Ne=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=dr,this.params={},this.timeout=Wt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=ni,this.conn=null,this.sendBuffer=[],this.serializer=new ut,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(he(),ye)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Ht.websocket}`,this.httpEndpoint=Bt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let n=(s=t?.params)===null||s===void 0?void 0:s.apikey;n&&(this.accessToken=n,this.apiKey=n),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t?.encode?t.encode:(i,o)=>o(JSON.stringify(i)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ve(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(ii){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new As(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ws(mr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case we.connecting:return fe.Connecting;case we.open:return fe.Open;case we.closing:return fe.Closing;default:return fe.Closed}}isConnected(){return this.connectionState()===fe.Open}channel(e,t={config:{}}){let s=new Me(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:n,ref:i}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${i})`,n),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(z.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:hr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:n,payload:i,ref:o}=t;(o&&o===this.pendingHeartbeatRef||n===i?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${s} ${n} ${o&&"("+o+")"||""}`,i),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(n,i,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(z.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return`${e}${s}${n}`}_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(fr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},As=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=we.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var qe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function U(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var zt=class extends qe{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},dt=class extends qe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var oi=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Gt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(he(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},_r=()=>oi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(he(),ye))).Response:Response});var Fe=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},xs=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),ai=(r,e)=>Fe(void 0,void 0,void 0,function*(){let t=yield _r();r instanceof t?r.json().then(s=>{e(new zt(xs(s),r.status||500))}).catch(s=>{e(new dt(xs(s),s))}):e(new dt(xs(r),r))}),ci=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};function Jt(r,e,t,s,n,i){return Fe(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,ci(e,s,n,i)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>ai(c,a))})})}function ht(r,e,t,s){return Fe(this,void 0,void 0,function*(){return Jt(r,"GET",e,t,s)})}function te(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return Jt(r,"POST",e,s,n,t)})}function yr(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return Jt(r,"PUT",e,s,n,t)})}function Vt(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return Jt(r,"DELETE",e,s,n,t)})}var G=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},li={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},wr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ft=class{constructor(e,t={},s,n){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Gt(n)}uploadOrUpdate(e,t,s,n){return G(this,void 0,void 0,function*(){try{let i,o=Object.assign(Object.assign({},wr),n),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.append("cacheControl",o.cacheControl)):(i=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:i,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(i){if(U(i))return{data:null,error:i};throw i}})}upload(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,n){return G(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,l=Object.assign({upsert:wr.upsert},n),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",l.cacheControl)):(c=s,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:u}),f=yield d.json();return d.ok?{data:{path:i,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(U(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return G(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=Object.assign({},this.headers);t?.upsert&&(n["x-upsert"]="true");let i=yield te(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new qe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}update(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}copy(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:{path:(yield te(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}createSignedUrl(e,t,s){return G(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),i=yield te(this.fetch,`${this.url}/object/sign/${n}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}createSignedUrls(e,t,s){return G(this,void 0,void 0,function*(){try{let n=yield te(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:n.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}download(e,t){return G(this,void 0,void 0,function*(){let n=typeof t?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(t?.transform||{}),o=i?`?${i}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield ht(this.fetch,`${this.url}/${n}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(U(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),n=[],i=t?.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&n.push(i);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&n.push(c);let l=n.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${l}`)}}}remove(e){return G(this,void 0,void 0,function*(){try{return{data:yield Vt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}list(e,t,s){return G(this,void 0,void 0,function*(){try{let n=Object.assign(Object.assign(Object.assign({},li),t),{prefix:e||""});return{data:yield te(this.fetch,`${this.url}/object/list/${this.bucketId}`,n,{headers:this.headers},s),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}_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 vr="2.6.0";var br={"X-Client-Info":`storage-js/${vr}`};var He=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},pt=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},br),t),this.fetch=Gt(s)}listBuckets(){return He(this,void 0,void 0,function*(){try{return{data:yield ht(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}})}getBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield ht(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return He(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return He(this,void 0,void 0,function*(){try{return{data:yield yr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}emptyBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield te(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield Vt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}};var gt=class extends pt{constructor(e,t={},s){super(e,t,s)}from(e){return new ft(this.url,this.headers,e,this.fetch)}};var kr="2.44.4";var mt="";typeof Deno<"u"?mt="deno":typeof document<"u"?mt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?mt="react-native":mt="node";var ui={"X-Client-Info":`supabase-js-${mt}/${kr}`},Sr={headers:ui},Er={schema:"public"},Tr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Cr={};he();var di=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},hi=r=>{let e;return r?e=r:typeof fetch>"u"?e=ls:e=fetch,(...t)=>e(...t)},fi=()=>typeof Headers>"u"?us:Headers,Ar=(r,e,t)=>{let s=hi(t),n=fi();return(i,o)=>di(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,l=new n(o?.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),s(i,Object.assign(Object.assign({},o),{headers:l}))})};function xr(r){return r.replace(/\/$/,"")}function Rr(r,e){let{db:t,auth:s,realtime:n,global:i}=r,{db:o,auth:a,realtime:c,global:l}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),n),global:Object.assign(Object.assign({},l),i)}}var Kt="2.64.4";var Pr="http://localhost:9999",Or="supabase.auth.token";var Ir={"X-Client-Info":`gotrue-js/${Kt}`},Rs=10;var _t="X-Supabase-Api-Version",Ps={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Lr(r){return Math.round(Date.now()/1e3)+r}function jr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var J=()=>typeof document<"u",ke={tested:!1,writable:!1},pe=()=>{if(!J())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ke.tested)return ke.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),ke.tested=!0,ke.writable=!0}catch{ke.tested=!0,ke.writable=!1}return ke.writable};function Yt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return t.searchParams.forEach((s,n)=>{e[n]=s}),e}var Xt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(he(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},$r=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Os=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},wt=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Qt=async(r,e)=>{await r.removeItem(e)};function pi(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,n,i,o,a,c,l,u=0;for(r=r.replace("-","+").replace("_","/");u<r.length;)o=e.indexOf(r.charAt(u++)),a=e.indexOf(r.charAt(u++)),c=e.indexOf(r.charAt(u++)),l=e.indexOf(r.charAt(u++)),s=o<<2|a>>4,n=(a&15)<<4|c>>2,i=(c&3)<<6|l,t=t+String.fromCharCode(s),c!=64&&n!=0&&(t=t+String.fromCharCode(n)),l!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}var yt=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};yt.promiseConstructor=Promise;function Is(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(pi(s))}async function Ur(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Dr(r,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await r(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function gi(r){return("0"+r.toString(16)).substr(-2)}function mi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,n="";for(let i=0;i<56;i++)n+=t.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,gi).join("")}async function _i(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}function yi(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function wi(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await _i(r);return yi(t)}async function Se(r,e,t=!1){let s=mi(),n=s;t&&(n+="/PASSWORD_RECOVERY"),await Os(r,`${e}-code-verifier`,n);let i=await wi(s);return[i,s===i?"plain":"s256"]}var vi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Mr(r){let e=r.headers.get(_t);if(!e||!e.match(vi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var vt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function T(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Zt=class extends vt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Nr(r){return T(r)&&r.name==="AuthApiError"}var We=class extends vt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ce=class extends vt{constructor(e,t,s,n){super(e,s,n),this.name=t,this.status=s}},se=class extends ce{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Be=class extends ce{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ee=class extends ce{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Te=class extends ce{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},bt=class extends ce{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},ze=class extends ce{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function es(r){return T(r)&&r.name==="AuthRetryableFetchError"}var kt=class extends ce{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var bi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t},Ce=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),ki=[502,503,504];async function qr(r){var e;if(!$r(r))throw new ze(Ce(r),0);if(ki.includes(r.status))throw new ze(Ce(r),r.status);let t;try{t=await r.json()}catch(i){throw new We(Ce(i),i)}let s,n=Mr(r);if(n&&n.getTime()>=Ps["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new kt(Ce(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new kt(Ce(t),r.status,t.weak_password.reasons);throw new Zt(Ce(t),r.status||500,s)}var Si=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};async function C(r,e,t,s){var n;let i=Object.assign({},s?.headers);i[_t]||(i[_t]=Ps["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let o=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Ei(r,e,t+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Ei(r,e,t,s,n,i){let o=Si(e,s,n,i),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new ze(Ce(c),0)}if(a.ok||await qr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await qr(c)}}function le(r){var e;let t=null;Ti(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Lr(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Ls(r){let e=le(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function re(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Fr(r){return{data:r,error:null}}function Hr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i}=r,o=bi(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Wr(r){return r}function Ti(r){return r.access_token&&r.refresh_token&&r.expires_in}var Ci=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t},Ae=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Xt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await C(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(T(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await C(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:re})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Ci(e,["options"]),n=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await C(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Hr,redirectTo:t?.redirectTo})}catch(t){if(T(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await C(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:re})}catch(t){if(T(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,n,i,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await C(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Wr});if(u.error)throw u.error;let d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(v=>{let E=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(v.split(";")[1].split("=")[1]);l[`${S}Page`]=E}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(T(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){try{return await C(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:re})}catch(t){if(T(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await C(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:re})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await C(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:re})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await C(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:t,error:s}}catch(t){if(T(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await C(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(T(t))return{data:null,error:t};throw t}}};var Br={getItem:r=>pe()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{pe()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{pe()&&globalThis.localStorage.removeItem(r)}};function js(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function zr(){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 xe={debug:!!(globalThis&&pe()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},St=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ts=class extends St{};async function $s(r,e,t){xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),xe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,n.name);try{return await t()}finally{xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,n.name)}}else{if(e===0)throw xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new ts(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(xe.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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()}})}zr();var Ai={url:Pr,storageKey:Or,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ir,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Et=30*1e3,Gr=3;async function Jr(r,e,t){return await t()}var Re=class r{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&J()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let n=Object.assign(Object.assign({},Ai),e);if(this.logDebugMessages=!!n.debug,typeof n.debug=="function"&&(this.logger=n.debug),this.persistSession=n.persistSession,this.storageKey=n.storageKey,this.autoRefreshToken=n.autoRefreshToken,this.admin=new Ae({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=Xt(n.fetch),this.lock=n.lock||Jr,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,n.lock?this.lock=n.lock:J()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=$s:this.lock=Jr,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?n.storage?this.storage=n.storage:pe()?this.storage=Br:(this.memoryStorage={},this.storage=js(this.memoryStorage)):(this.memoryStorage={},this.storage=js(this.memoryStorage)),J()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Kt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=J()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:n,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",n,"redirect type",i),await this._saveSession(n),setTimeout(async()=>{i==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return T(e)?{error:e}:{error:new We("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,n;try{let i=await C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:le}),{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(T(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,s,n;try{let i;if("email"in e){let{email:u,password:d,options:f}=e,p=null,v=null;this.flowType==="pkce"&&([p,v]=await Se(this.storage,this.storageKey)),i=await C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:v},xform:le})}else if("phone"in e){let{phone:u,password:d,options:f}=e;i=await C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:le})}else throw new Ee("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(T(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:a}=e;t=await C(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ls})}else if("phone"in e){let{phone:i,password:o,options:a}=e;t=await C(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ls})}else throw new Ee("You must provide either an email or phone number and a password");let{data:s,error:n}=t;return n?{data:{user:null,session:null},error:n}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Be}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(t){if(T(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await wt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(t??"").split("/"),{data:i,error:o}=await C(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:le});return await Qt(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Be}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:n,access_token:i,nonce:o}=e,a=await C(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:le}),{data:c,error:l}=a;return l?{data:{user:null,session:null},error:l}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Be}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:l})}catch(t){if(T(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,n,i,o;try{if("email"in e){let{email:a,options:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await Se(this.storage,this.storageKey));let{error:d}=await C(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await C(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=c?.data)!==null&&n!==void 0?n:{},create_user:(i=c?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:l?.message_id},error:u}}throw new Ee("You must provide either an email or phone number.")}catch(a){if(T(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let n,i;"options"in e&&(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await C(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:le});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(n){if(T(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithSSO(e){var t,s,n;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await Se(this.storage,this.storageKey)),await C(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:Fr})}catch(i){if(T(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new se;let{error:n}=await C(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:n}})}catch(e){if(T(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:n,options:i}=e,{error:o}=await C(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:n,options:i}=e,{data:o,error:a}=await C(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Ee("You must provide either an email or phone number and a type")}catch(t){if(T(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await wt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,l,u)=>(!o&&l==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,l,u))})}return{data:{session:e},error:null}}let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:n},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 C(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:re}):await this._useSession(async t=>{var s,n,i;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new se}:await C(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:re})})}catch(t){if(T(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new se;let o=n.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Se(this.storage,this.storageKey));let{data:l,error:u}=await C(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:re});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Is(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 se;let t=Date.now()/1e3,s=t,n=!0,i=null,o=Is(e.access_token);if(o.exp&&(s=o.exp,n=s<=t),n){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};i=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(T(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new se;let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:n?{data:{user:n.user,session:n},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(T(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!J())throw new Te("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Te("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new bt("Not a valid PKCE flow url.");let t=Yt(window.location.href);if(e){if(!t.code)throw new bt("No code detected.");let{data:h,error:m}=await this._exchangeCodeForSession(t.code);if(m)throw m;let O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Te(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:a,expires_at:c,token_type:l}=t;if(!i||!a||!o||!l)throw new Te("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;c&&(f=parseInt(c));let p=f-u;p*1e3<=Et&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);let v=f-d;u-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,u):u-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",v,f,u);let{data:E,error:S}=await this._getUser(i);if(S)throw S;let w={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:d,expires_at:f,refresh_token:o,token_type:l,user:E.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:w,redirectType:t.type},error:null}}catch(t){if(T(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Yt(window.location.href);return!!(J()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Yt(window.location.href),t=await wt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:n,error:i}=t;if(i)return{error:i};let o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Nr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Qt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=jr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,n;try{let{data:{session:i},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Se(this.storage,this.storageKey,!0));try{return await C(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(T(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(T(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:n}=await this._useSession(async i=>{var o,a,c,l,u;let{data:d,error:f}=i;if(f)throw f;let p=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 C(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return J()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(T(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,n;let{data:i,error:o}=t;if(o)throw o;return await C(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(T(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Dr(async n=>(n>0&&await Ur(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await C(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:le})),(n,i)=>{let o=200*Math.pow(2,n);return i&&es(i)&&Date.now()+o-s<Et})}catch(s){if(this._debug(t,"error",s),T(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),J()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await wt(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let n=Math.round(Date.now()/1e3),i=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<n+Rs;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${Rs}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),es(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new se;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new yt;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new se;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let a={session:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(n,"error",i),T(i)){let o={session:null,error:i};return es(i)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,s=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Os(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Qt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&J()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Et);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/Et);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Et}ms, refresh threshold is ${Gr} ticks`),n<=Gr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof St)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!J()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let n=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,o]=await Se(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s?.queryParams){let i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;return i?{data:null,error:i}:await C(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(T(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,n;let{data:i,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await C(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((n=a?.totp)===null||n===void 0)&&n.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(T(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;if(i)return{data:null,error:i};let{data:o,error:a}=await C(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(T(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;return i?{data:null,error:i}:await C(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(T(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],n=s.filter(i=>i.factor_type==="totp"&&i.status==="verified");return{data:{all:s,totp:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:n},error:i}=e;if(i)return{data:null,error:i};if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(n.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=n.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let u=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}};Re.nextInstanceID=0;var xi=Re,Us=xi;var ss=class extends Us{constructor(e){super(e)}};var Ri=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Tt=class{constructor(e,t,s){var n,i,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=xr(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,l={db:Er,realtime:Cr,auth:Object.assign(Object.assign({},Tr),{storageKey:c}),global:Sr},u=Rr(s??{},l);this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=Ar(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},u.realtime)),this.rest=new lr(`${a}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new st(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new gt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Ri(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:n,storageKey:i,flowType:o,debug:a},c,l){var u;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ss({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:n,flowType:o,debug:a,fetch:l,hasCustomAuthorizationHeader:(u="Authorization"in this.headers)!==null&&u!==void 0?u:!1})}_initRealtimeClient(e){return new Ne(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Vr=(r,e,t)=>new Tt(r,e,t);var ue={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Pi=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},rs=r=>{let[e,t]=r.split(".");return!e||!t?null:Pi(t)},Ge=r=>{let e=rs(r);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Oi="https://api.workos.com",Ii=60,Je=(r,e)=>typeof r[e]=="string"?r[e]:void 0,Kr=(r,e,t)=>{let s=rs(r);if(!s)return null;let n=Je(s,"urn:wispr:user_external_id")??Je(s,"sub"),i=t?.email??Je(s,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof s.exp=="number"?s.exp:void 0,c={id:n??"",aud:"authenticated",email:i,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},Li=async(r,e,t,s)=>{let n=t?.startsWith("https://")?t.replace(/\/$/,""):Oi,i=await fetch(`${n}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:r,organization_id:s})});if(!i.ok){let o=await i.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${i.status}`)}return await i.json()},Yr=async(r,e)=>{let t=rs(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),n=typeof t.exp=="number"?t.exp:0,i=Je(t,"client_id");if(n-s<Ii&&i){let c=await Li(e,i,Je(t,"iss"),Je(t,"org_id")),l=Kr(c.access_token,c.refresh_token,c.user);if(!l)throw new Error("WorkOS refresh returned an invalid access token");return l}if(n<=s)throw new Error("WorkOS session expired");let a=Kr(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Ve=class{constructor(){this.sessionData=null;this.supabase=Vr(ue.supaBaseUrl,ue.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ue.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||ue.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||ue.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:n}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(n)throw n;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let n=new Date;n.setTime(n.getTime()+s*24*60*60*1e3);let i=`expires=${n.toUTCString()}`;document.cookie=`${e}=${t};${i};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{if(Ge(t)==="workos"){this.sessionData=await Yr(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(n){throw n}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,n]=t.split("=");return e[s]=n,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ue.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,n,i,o){try{if(!i)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,l=await N.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:i,device_code:c,redirect_url:n||ue.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),l}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,s,n){try{if(!s)throw new Error("Please complete the verification");let i=await N.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:n?.provision??!1,workos_capable:n?.workosCapable||void 0});if(jt(i))return{kind:"otp",challenge:i};if(!i.access_token||!i.refresh_token)throw new Error(i.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:i.access_token,refreshToken:i.refresh_token,fullName:[i.first_name,i.last_name].filter(Boolean).join(" ")||void 0,provider:i.provider||void 0}}catch(i){throw console.error("Error signing in with password:",i),i}}async resendVerificationEmail(e,t,s,n){try{if(!s)throw new Error("Please complete the verification");let i=await N.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||ue.redirectUri,workos_capable:n?.workosCapable||void 0});return console.log("Verification request completed"),i}catch(i){throw console.error("Error resending verification email:",i),i}}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 ns=null,Xr=(r,e)=>{if(!(r instanceof Error)||r.name!=="AriaAuthError")return e;let t={verification_failed:"Incorrect or expired code. Try again.",invalid_code:"Enter the six-digit code.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again."},{code:s}=r;return s&&t[s]||e},is=()=>{ns!==null&&(window.clearInterval(ns),ns=null)};function Pe(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),is()}function Qr(r){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),s=document.querySelector("[otp-email]"),n=document.querySelector("[otp-verify]"),i=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),c=document.querySelector("[otp-resend-countdown]"),l=document.querySelector("[otp-resend-seconds]"),u=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),i&&(i.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),n&&(n.textContent="Verify",n.style.pointerEvents="",n.removeAttribute("aria-disabled")),is(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let d=h=>{i&&(i.style.display="block"),o&&(o.textContent=h)},f=()=>{i&&(i.style.display="none")},p=!1,v=!1,E=h=>{n&&(n.style.pointerEvents=h?"none":"",h?n.setAttribute("aria-disabled","true"):n.removeAttribute("aria-disabled"),n instanceof HTMLButtonElement&&(n.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},S=async()=>{if(p)return;let h=t.map(m=>m.value).join("");if(h.length!==6){d("Please enter all 6 digits.");return}p=!0,E(!0),t.forEach(m=>m.setAttribute("disabled","true")),f();try{await r.onVerify(h),f(),n&&(n.textContent="Verified \u2705")}catch(m){p=!1,E(!1),t.forEach(O=>{O.value="",O.removeAttribute("disabled")}),d(Xr(m,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,m)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&m<t.length-1&&t[m+1].focus(),f()},h.onkeydown=O=>{O.key==="Backspace"&&!h.value&&m>0?t[m-1].focus():O.key==="Enter"&&(O.preventDefault(),S())},h.onpaste=O=>{O.preventDefault();let L=(O.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);L.split("").forEach((W,Z)=>{t[Z]&&(t[Z].value=W)});let ie=Math.min(L.length,t.length-1);t[ie]?.focus(),f()}}),n&&(n.onclick=h=>{h.preventDefault(),S()});let w=()=>{let h=30;a&&(a.style.display="none"),c&&(c.style.display="block"),l&&(l.textContent=String(h)),is(),ns=window.setInterval(()=>{h-=1,l&&(l.textContent=String(h)),h<=0&&(is(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(v||a.style.display==="none")){v=!0,t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),t[0]?.focus(),f(),w();try{await r.onResend?.()}catch(m){d(Xr(m,"We couldn't send a new code. Please try again when the timer ends."))}finally{v=!1}}}),u&&(u.onclick=h=>{h.preventDefault(),Pe(),r.onReset?.()})}var Oe=()=>window.hcaptcha,os=async()=>{let r=Oe();if(!r)throw new Error("Verification system not loaded");let e=await r.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Ct=(r,e)=>r instanceof Error?r.message:e,Zr=(r,e)=>r instanceof Q?r.code==="sso_required"?(e.showSso(),!0):r.code==="scim_managed_domain"?(e.showScim(),!0):(r.code==="sign_in_to_continue"&&e.showLogin(),e.showError(r.message),!0):!1,en=r=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(s){e={pendingAuthenticationToken:s.pendingAuthenticationToken,email:F(s.email)},r.beforeShow(),Qr({email:e.email,onVerify:async n=>{if(!e)throw Pe(),r.onMissingChallenge(),new Error("Missing OTP challenge");let i=await N.verifyEmailOtp({code:n,pending_authentication_token:e.pendingAuthenticationToken});t(),await r.onAuthenticated(i)},onResend:async()=>{if(!e)throw Pe(),r.onMissingChallenge(),new Error("Missing OTP challenge");let n=await os();try{await r.client.resendVerificationEmail(e.email,r.redirectUrl,n,{workosCapable:r.isWorkosCapable(e.email)})}finally{Oe()?.reset()}},onReset:()=>{t(),r.onReset()}})}}};var ne=null;function Ds(r,e=30,t){ne&&(clearInterval(ne),ne=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,ne=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",ne&&(clearInterval(ne),ne=null),t&&t())},1e3)}function tn(){ne&&(clearInterval(ne),ne=null)}var sn=/^[\p{L}\p{M}\s\-'.]+$/u;function ji(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":sn.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Ms(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":sn.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function rn(r,e,t){let s="full-name-match-error",n=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let l=document.getElementById(s);l||(l=document.createElement("div"),l.id=s,l.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",l)),l.textContent=c},i=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=ji(e.value,r.value);c?n(c):i()},a=()=>{let c=Ms(e.value,r.value);c?n(c):i()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var nn="password-rejection-error",on=r=>r instanceof Q?r.passwordRejectionMessage:null,At=r=>{r.classList.remove("error"),document.getElementById(nn)?.remove()},Ns=(r,e)=>{if(At(r),e.length===0)return;r.classList.add("error");let t=document.createElement("div");t.id=nn,t.style.fontSize="0.875rem",t.textContent=e,r.insertAdjacentElement("afterend",t)};var $i="wisprjam.com",Ui="wispr.ai",Di="wispr_workos_capable",Mi=r=>r.trim().toLowerCase().split("@")[1]??"",cn=r=>{let e=Mi(r);return e===$i||e===Ui},an=()=>{try{return window.sessionStorage.getItem(Di)==="true"}catch{return!1}};function ln(r,e){let t=new Ve,s="email_input",n=null,i=()=>{n?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),l=document.querySelector("#full-name"),u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),p=document.querySelector("[email-element]"),v=document.querySelector("[different-provider]"),E=document.querySelector("[different-provider-name]"),S=document.querySelector("[different-provider-reset]"),w=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),O=document.querySelector("[verification-email]"),L=document.querySelector("[email-signup-retry]"),ie=document.querySelector("[email-signup-reset]"),W=document.querySelector("[scim-div]"),Z=document.querySelector("[scim-reset]"),D=document.querySelector("[forgot-password]"),ge=document.querySelector("[forgot-password-success]"),de=document.querySelector("[forgot-password-email]"),B=document.querySelector("[unverified-email]"),Rt=document.querySelector("[unverified-email-address]"),V=document.querySelector("[resend-verification-email]"),M=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(u&&u.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(_){console.error("Error during Google sign-in:",_)}}),d&&d.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(_){console.error("Error during Apple sign-in:",_)}}),f&&f.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(_){console.error("Error during Microsoft sign-in:",_)}}));let K=()=>{i(),v&&(v.style.display="none"),w&&(w.style.display="none"),h&&(h.style.display="none"),B&&(B.style.display="none"),W&&(W.style.display="none"),D&&(D.style.display="none"),ge&&(ge.style.display="none"),Pe();let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="block"),p&&(p.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),c&&(c.value="",c.style.display="none",c.removeAttribute("required"),At(c)),l&&(l.value="",l.style.display="none",l.removeAttribute("required"));let k=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");k&&(k.style.display="none"),A&&(A.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",a&&a.focus()},oe=()=>{p&&(p.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="none",l.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),k&&(k.style.display="block"),D&&(D.style.display="block",D.onclick=async()=>{let A=a?.value||"",g=D.textContent||"";try{let{hcaptcha:y}=window;if(!y)throw new Error("Verification system not loaded. Please refresh the page.");D.style.pointerEvents="none",D.textContent="Sending...";let{response:b}=await y.execute({async:!0});if(!b)throw new Error("Verification cancelled");await N.requestPasswordReset(A,b),y.reset(),p&&(p.style.display="none"),D&&(D.style.display="none"),ge&&(ge.style.display="block"),de&&(de.textContent=A)}catch(y){console.error("Error sending password reset email:",y),D.textContent=g,D.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",m&&(m.textContent=y instanceof Error?y.message:"Failed to send reset email"))}}),s="login"},Ye=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="block",l.setAttribute("required","true"));let _=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),k&&(k.style.display="block"),s="signup"},me=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),W&&(W.style.display="block"),Z&&(Z.onclick=()=>{W&&(W.style.display="none"),_&&(_.style.display="block"),K()})},Ie=_=>{i();let k=Vs(_);p&&(p.style.display="none"),v&&(v.style.display="block"),E&&(E.textContent=k),S&&(S.onclick=()=>{v&&(v.style.display="none"),K()}),s="oauth_user"},Xe=async(_,k)=>{let A=await N.signInWithEmail({email:_,password:k,mcp_login_state:e?.mcpLoginState??void 0,workos_capable:an()});if(!A.redirect_url)throw new Error(A.error||"Unable to continue connector login. Please try again.");R("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=A.redirect_url};n=en({client:t,redirectUrl:r,isWorkosCapable:()=>!0,beforeShow:()=>{p&&(p.style.display="none"),B&&(B.style.display="none")},onAuthenticated:async _=>{if(i(),t.setCookies(_.access_token,_.refresh_token),localStorage.setItem("email",_.email),localStorage.setItem("user_id",_.user_id),localStorage.setItem("signin_provider","email"),e?.mcpLoginState){try{await Xe(_.email,c.value)}catch(A){Pe(),oe(),X(A)||(h&&(h.style.display="block"),m&&(m.textContent="Unable to continue connector login. Please sign in again."))}return}let k=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,k):window.location.href=r},onMissingChallenge:oe,onReset:K});let ae=_=>{p&&(p.style.display="none"),B&&(B.style.display="block"),Rt&&(Rt.textContent=_),V&&(V.onclick=async()=>{let k=V.textContent||"";try{let A=await os();await t.resendVerificationEmail(_,r,A),V.textContent="Verification email resent! \u2705",V.style.textDecoration="none"}catch(A){V.textContent=k,h&&(h.style.display="block"),m&&(m.textContent=Ct(A,"Unable to resend verification."))}finally{Oe()?.reset()}}),M&&(M.onclick=()=>{B&&(B.style.display="none"),K()}),s="unverified_email"},X=_=>Zr(_,{showSso:()=>Ie("workos"),showScim:me,showLogin:oe,showError:k=>{h&&(h.style.display="block"),m&&(m.textContent=k)}}),Qe=async(_,k)=>{let A=k.value;k.classList.add("loading"),k.value="";try{let g=await N.checkUserStatus(_);k.classList.remove("loading"),k.value=A,!g.exists&&g.scim_managed?me():g.enforce_sso?Ie("workos"):g.exists&&g.provider&&g.provider!=="email"&&g.provider!=="workos"?Ie(g.provider):g.exists&&g.provider==="workos"?oe():g.exists&&g.provider==="email"&&!g.verified?ae(_):g.exists&&g.provider==="email"?oe():Ye()}catch(g){console.error("Error checking user status:",g),k.classList.remove("loading"),k.value=A,X(g)||Ye()}},Le=async(_,k,A,g)=>{if(!k||k.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let y=window.hcaptcha?.getResponse()||"";if(!y){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){await Xe(_,k);return}let b=an(),x=await t.signInWithPassword(_,k,y,{workosCapable:b,provision:!1});if(x.kind==="otp"){if(!b)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let P={pendingAuthenticationToken:x.challenge.pending_authentication_token,email:F(x.challenge.email||_)};Oe()?.reset(),A.classList.remove("loading"),A.value=g,n?.show(P);return}t.setCookies(x.accessToken,x.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(x.accessToken,x.refreshToken,x.fullName):window.location.href=r}catch(b){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=g,!X(b)&&h&&(h.style.display="block",m&&(m.textContent=Ct(b,"Unable to sign in. Please try again.")))}},as=async(_,k,A,g,y)=>{if(!k||k.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(k.trim().toLowerCase()===_.trim().toLowerCase()){Ns(c,"Password can't be the same as your email address.");return}if(!A||A.trim().length<2){h&&(h.style.display="block",m&&(m.textContent="Please enter your full name"));return}let b=Ms(A,k);if(b){h&&(h.style.display="block",m&&(m.textContent=b));return}let x=window.hcaptcha?.getResponse()||"";if(!x){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}g.classList.add("loading"),g.value="";try{let P=await t.signUpWithPassword(_,k,A,r,x,{workosCapable:!0,deviceCode:e?.deviceCode});if(window.hcaptcha&&window.hcaptcha.reset(),g.classList.remove("loading"),g.value=y,p&&(p.style.display="none"),h&&(h.style.display="none"),jt(P)){let $={pendingAuthenticationToken:P.pending_authentication_token,email:F(P.email||_)};n?.show($);return}w&&(w.style.display="block"),O&&(O.textContent=_),L&&(Ds(L,30),L.onclick=async()=>{if(L.style.pointerEvents!=="none")try{let $=await os();await t.resendVerificationEmail(_,r,$,{workosCapable:!0}),Ds(L,30)}catch($){h&&(h.style.display="block"),m&&(m.textContent=Ct($,"Unable to resend verification. Please try again."))}finally{Oe()?.reset()}}),ie&&(ie.onclick=()=>{w&&(w.style.display="none"),tn(),K()})}catch(P){g.classList.remove("loading"),g.value=y,Oe()?.reset();let $=on(P);$&&c?Ns(c,$):!X(P)&&h&&(h.style.display="block",m&&(m.textContent=Ct(P,"Unable to create the account. Please try again.")))}};return o&&c&&l&&(rn(c,l,o.querySelector('[type="submit"]')),c.addEventListener("input",()=>At(c))),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let k=F(a?.value||"");a&&(a.value=k);let A=c?.value||"",g=l?.value||"";if(!k||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){h&&(h.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),m&&(m.textContent=""),c&&At(c);let b=o.querySelector('[type="submit"]'),x=b?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await Qe(k,b):s==="login"?await Le(k,A,b,x):s==="signup"&&await as(k,A,g,b,x)}catch(P){console.error("Auth flow error:",P),b&&(b.classList.remove("loading"),b.value=x),h&&(h.style.display="block")}}),{reset:K}}var Ni="wf_first_landing_url";var un=()=>{try{return localStorage.getItem(Ni)||void 0}catch{return}};var qi=/google ads|google adservices|adwords/i,Fi=/marketing|advertising/i,hn="JQ2XQxIk",Hi="linkedin insight tag",Wi="ko1w5PpFl",Bi="facebook pixel",zi="BkeKqEjuoZQ",Gi="microsoft advertising",Ji="6-qobRfu",Vi="tiktok advertising",Ki="lIWYtXOZYJmqeh",Yi="tiktok advanced matching",Xi=r=>{let e=r.filter(s=>qi.test(s.name??""));if(e.length>0)return e.every(s=>s.decision===!0)?{ad_user_data:!0,ad_personalization:!0}:e.every(s=>s.decision===!1)?{ad_user_data:!1,ad_personalization:!1}:void 0;let t=r.filter(s=>Fi.test(s.category??""));if(t.length!==0){if(t.some(s=>s.decision===!0))return{ad_user_data:!0,ad_personalization:!0};if(t.every(s=>s.decision===!1))return{ad_user_data:!1,ad_personalization:!1}}},dn=r=>{let e=Xi(r),t=r.filter(w=>w.id===hn),s=t.length?t:r.filter(w=>typeof w.name=="string"&&w.name.trim().toLowerCase()===Hi),n=s.length===1?s[0].linkedinConsent:void 0,i=r.filter(w=>w.id===Wi),o=i.length?i:r.filter(w=>typeof w.name=="string"&&w.name.trim().toLowerCase()===Bi),a=o.length===1?o[0].metaConsent:void 0,c=r.filter(w=>w.id===zi),l=c.length?c:r.filter(w=>typeof w.name=="string"&&w.name.trim().toLowerCase()===Gi),u=l.length===1?l[0].microsoftConsent:void 0,d=r.filter(w=>w.id===Ji),f=d.length?d:r.filter(w=>typeof w.name=="string"&&w.name.trim().toLowerCase()===Vi),p=f.length===1?f[0].tiktokConsent:void 0,v=r.filter(w=>w.id===Ki),E=v.length?v:r.filter(w=>typeof w.name=="string"&&w.name.trim().toLowerCase()===Yi),S=E.length===1?E[0].tiktokAdvancedMatchingConsent:void 0;if(!(!e&&n===void 0&&a===void 0&&u===void 0&&p===void 0&&S===void 0))return{...e,...n===void 0?{}:{linkedin_ads_consent:n.given,linkedin_ads_consent_type:n.type},...a===void 0?{}:{meta_ads_consent:a.given,meta_ads_consent_type:a.type},...u===void 0?{}:{microsoft_ads_consent:u.given,microsoft_ads_consent_type:u.type},...p===void 0?{}:{tiktok_ads_consent:p.given,tiktok_ads_consent_type:p.type},...S===void 0?{}:{tiktok_advanced_matching_consent:S.given,tiktok_advanced_matching_consent_type:S.type}}},Ke=(r,e)=>{if(typeof r=="boolean")return{given:r,...e==="EXPLICIT"||e==="IMPLICIT"?{type:e}:{}}},xt=r=>{if(typeof r?.status!="boolean")return;let e={given:r.status},{history:t}=r;if(!Array.isArray(t)||!t.length||t.some(o=>!Number.isFinite(o?.timestamp)))return e;let s=Math.max(...t.map(o=>o.timestamp)),n=t.filter(o=>o.timestamp===s),i=Ke(r.status,n[0].type);return i?.type&&n.every(o=>o.type===i.type&&o.status===i.given)?i:e},Qi=async()=>{try{let{__ucCmp:r,UC_UI:e}=window;if(r?.getConsentDetails){let t=await r.getConsentDetails();return dn(Object.entries(t?.services??{}).map(([s,n])=>({id:s,name:n?.name,category:n?.category,linkedinConsent:Ke(n?.consent?.given,n?.consent?.type),metaConsent:Ke(n?.consent?.given,n?.consent?.type),microsoftConsent:Ke(n?.consent?.given,n?.consent?.type),tiktokConsent:Ke(n?.consent?.given,n?.consent?.type),tiktokAdvancedMatchingConsent:Ke(n?.consent?.given,n?.consent?.type),decision:n?.consent?.type==="EXPLICIT"&&typeof n.consent.given=="boolean"?n.consent.given:void 0})))}if(e?.getServicesBaseInfo)return dn((e.getServicesBaseInfo()??[]).map(t=>{let s=xt(t.consent),n=xt(t.consent),i=xt(t.consent),o=xt(t.consent),a=xt(t.consent);return{id:t?.id,name:t?.name,category:t?.categorySlug,linkedinConsent:s,metaConsent:n,microsoftConsent:i,tiktokConsent:o,tiktokAdvancedMatchingConsent:a,decision:t?.id===hn?s?.type==="EXPLICIT"?s.given:void 0:t?.consent?.history?.some(c=>c?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0}}))}catch{}},fn=()=>{let r=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([Qi(),r])};function pn(r){try{let e=r._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let s=t.split(".");if(s.length>=3){let n=s.slice(2).join(".");if(n)return n}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var Zi="wf_ttclid",qs=r=>r?.trim()||void 0;var gn=()=>{try{return qs(localStorage.getItem(Zi))}catch{return}},mn=r=>{let e=qs(r._ttp);if(e)try{return qs(decodeURIComponent(e))}catch{return e}};var Fs="https://api.wisprflow.ai",_n="https://wisprflow.ai/login",eo="workos_enabled_webflow";async function yn(){let r=new Ve,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),s=document.querySelector("[error-div]"),n=document.querySelector("[error-message-api]"),i=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),l=c?.value??"",u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),p=document.querySelector("#sso-login"),v=document.querySelector("[sso-login-div]"),E=document.querySelector("#sso-email"),S=document.querySelector("#sso-signup-form"),w=document.querySelector('[sso-login="go-back"]'),h=document.querySelector(".gs-hero_form-block"),m=localStorage.getItem("last_authed_provider");m&&{google:u,apple:d,microsoft:f,sso:p,email:document.querySelector("#email-input")}[m]?.classList.add("last-used");let O=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},L=()=>{let y=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";R("desktop_login_auto_launch",{deep_link:y}),window.location.href=y},ie=()=>{let g=localStorage.getItem("signin_provider");g&&localStorage.setItem("last_authed_provider",g),e&&(e.style.display="none"),t&&(t.style.display="block"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",L()},W=g=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),n&&(n.textContent=g),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},Z=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},D=null,ge=document.querySelector("[retry-button]");ge&&ge.addEventListener("click",()=>de());let de=()=>{e&&(e.style.display="none"),s&&(s.style.display="none"),a&&(a.style.display="none"),i&&(i.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=l),D&&D()},B=async(g,y)=>{try{let[b,x]=Js(y||" "),P=N.signupUser({access_token:g,first_name:b,last_name:x}),$=new Promise((je,_e)=>setTimeout(()=>_e(new Error("signup timeout")),4e3));await Promise.race([P,$])}catch(b){R("signup_sync_error",{error_message:b instanceof Error?b.message:String(b)})}},Rt=()=>{let g=sessionStorage.getItem("wispr_fbclid");return g?`fb.1.${Date.now()}.${g}`:null},V=async(g,y)=>{let b=sessionStorage.getItem("wispr_device_code");if(!b)throw new Error("Device code not found. Please restart authentication from desktop app.");let x=Ze(),P=await fn(),$=localStorage.getItem("wf_utm_source")||void 0,je=localStorage.getItem("wf_utm_medium")||void 0,_e=localStorage.getItem("wf_utm_campaign")||void 0,Pt=await fetch(`${Fs}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${g}`},body:JSON.stringify({device_code:b,access_token:g,refresh_token:y,fbp:x._fbp||void 0,fbc:x._fbc||Rt()||void 0,gclid:pn(x),ttclid:gn(),ttp:mn(x),utm:$||je||_e?{utm_source:$,utm_medium:je,utm_campaign:_e}:void 0,first_landing_url:un(),ad_user_data:P?.ad_user_data,ad_personalization:P?.ad_personalization,linkedin_ads_consent:P?.linkedin_ads_consent,linkedin_ads_consent_type:P?.linkedin_ads_consent_type,meta_ads_consent:P?.meta_ads_consent,meta_ads_consent_type:P?.meta_ads_consent_type,microsoft_ads_consent:P?.microsoft_ads_consent,microsoft_ads_consent_type:P?.microsoft_ads_consent_type,tiktok_ads_consent:P?.tiktok_ads_consent,tiktok_ads_consent_type:P?.tiktok_ads_consent_type,tiktok_advanced_matching_consent:P?.tiktok_advanced_matching_consent,tiktok_advanced_matching_consent_type:P?.tiktok_advanced_matching_consent_type})});if(!Pt.ok){let Ot=await Pt.json().catch(()=>({}));throw Pt.status===403&&Ot?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(Ot?.detail?.message||Ot.message||`Server error: ${Pt.status}`)}console.log("Device authentication complete"),sessionStorage.removeItem("wispr_device_code"),Ge(g)==="workos"&&r.setCookie("refresh_token",y,30/86400)},M=new URLSearchParams(window.location.search),K=M.get("device_code"),oe=M.get("error"),Ye=M.get("workos_capable");Ye==="true"?sessionStorage.setItem("wispr_workos_capable","true"):Ye==="false"&&sessionStorage.removeItem("wispr_workos_capable");let me=sessionStorage.getItem("wispr_workos_capable")==="true",Ie=M.get("auto_signin")==="true",Xe=new URLSearchParams(window.location.hash.slice(1)),Y=M.get("access_token")||Xe.get("access_token"),ae=M.get("refresh_token")||Xe.get("refresh_token"),X=M.get("mcp_login_state");if(!K&&!Y&&!ae&&!X&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),R("desktop_login_no_device_code"),window.location.href="/get-started";return}if(R("desktop_login_page_view",{auto_signin:Ie,workos_capable:me}),K){sessionStorage.setItem("wispr_device_code",K);let g=M.get("fbclid");g&&sessionStorage.setItem("wispr_fbclid",g);let y=M.get("skip_default_trial"),b=M.get("grant_weekly_bonus");y&&sessionStorage.setItem("wispr_skip_default_trial",y),b&&sessionStorage.setItem("wispr_grant_weekly_bonus",b)}(K||Y||ae||oe)&&window.history.replaceState({},"","/login");let Qe="wispr_workos_second_hop_attempted";if(Y&&ae){console.log("OAuth callback detected - handling tokens");let g=Ge(Y);if(R("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:g}),O(),g==="workos"){sessionStorage.removeItem(Qe);try{r.setCookies(Y,ae);let y=M.get("email");y&&localStorage.setItem("email",y);let b=M.get("user_id");b&&localStorage.setItem("user_id",b),await B(Y,M.get("name")??void 0),await N.applyPromoCodeFromCookie(Y),await V(Y,ae),R("desktop_login_complete_success",{method:"oauth",provider:"workos"}),ie()}catch(y){if(y instanceof Error&&y.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),Z();return}let b=y instanceof Error?y.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"oauth",provider:"workos",error:b}),console.error("Error completing WorkOS device authentication:",y),W(b)}return}try{let y=Y,b=ae;try{r.setCookies(Y,ae),await r.checkAndSetSession(),r.sessionData&&(y=r.sessionData.access_token,b=r.sessionData.refresh_token,r.setCookies(y,b),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}let x=r.sessionData?.user.email;if(me&&x&&cn(x)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(Qe)){sessionStorage.setItem(Qe,"true"),R("desktop_login_workos_second_hop",{email_domain:x.split("@")[1]??"unknown"}),window.location.href=`${Fs}/authkit/google/sign_in?source=${_n}`;return}await B(y,r.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(y),await V(y,b),R("desktop_login_complete_success",{method:"oauth"}),ie()}catch(y){if(y instanceof Error&&y.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),Z();return}let b=y instanceof Error?y.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"oauth",error:b}),console.error("Error completing device authentication:",y),W(b)}return}if(Ie){console.log("Auto-signin enabled - checking existing session"),O();try{if(await r.checkAndSetSession(),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token),r.sessionData?.access_token&&r.sessionData?.refresh_token){console.log("Existing session found - auto-completing authentication"),await B(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(r.sessionData.access_token),await V(r.sessionData.access_token,r.sessionData.refresh_token),R("desktop_login_auto_signin_success",{token_provider:Ge(r.sessionData.access_token)}),ie();return}console.log("No existing session - showing login form"),R("desktop_login_auto_signin_no_session"),de()}catch(g){if(console.error("Auto-signin error:",g),g instanceof Error&&g.message==="enterprise_ip_not_allowed"){R("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),Z();return}let y=g instanceof Error?g.message:"Auto-signin failed. Please try logging in manually.";R("desktop_login_auto_signin_error",{error:y}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),de()}}else X?(R("desktop_login_mcp_entry"),de()):(R("desktop_login_manual_signout"),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status"),de());let Le=(g,y)=>{console.log(`Redirecting to ${g} OAuth`);let b=window.posthog?.getFeatureFlag?.(eo)===!0,x=me&&b;R("desktop_login_oauth_click",{provider:x?"workos":g,idp:g,mcp:!!X,workos_capable:me,workos_enabled_webflow:b}),localStorage.setItem("signin_provider",g);let P=x?`authkit/${g}/sign_in`:`${g}/sign_in`,$=`${Fs}/${P}?source=${_n}`;y&&($+=`&email=${encodeURIComponent(y)}`);let je=sessionStorage.getItem("wispr_skip_default_trial"),_e=sessionStorage.getItem("wispr_grant_weekly_bonus");je&&($+=`&skip_default_trial=${encodeURIComponent(je)}`),_e&&($+=`&grant_weekly_bonus=${encodeURIComponent(_e)}`),X&&($+=`&mcp_login_state=${encodeURIComponent(X)}`),window.location.href=$};u&&u.addEventListener("click",()=>{Le("google")}),d&&d.addEventListener("click",()=>{Le("apple")}),f&&f.addEventListener("click",()=>{Le("microsoft")}),p&&(p.style.display="flex",p.addEventListener("click",g=>{g.preventDefault(),v&&(v.style.display="block"),h&&(h.style.display="none"),E?.focus()})),w&&w.addEventListener("click",()=>{v&&(v.style.display="none"),h&&(h.style.display="block"),E&&(E.value="",E.blur())}),S&&S.addEventListener("submit",g=>{g.preventDefault(),g.stopPropagation();let y=F(E?.value||"");y&&Le("sso",y)});let as=async(g,y,b)=>{try{await B(g,b),await N.applyPromoCodeFromCookie(g),await V(g,y)}catch(x){if(x instanceof Error&&x.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),Z();return}let P=x instanceof Error?x.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"email",error:P}),W(P);return}R("desktop_login_complete_success",{method:"email"}),ie()},_=sessionStorage.getItem("wispr_device_code"),k=_?`${window.location.origin}/login?device_code=${_}`:`${window.location.origin}/login`,{reset:A}=ln(k,{onLoginSuccess:as,deviceCode:_??void 0,mcpLoginState:X,skipOAuthButtons:!0});D=A,oe==="account_unsupported"&&(R("desktop_login_oauth_error",{error:oe}),W("This account is not supported. Try signing in with another account.")),console.log("Desktop login page initialized")}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>void yn(),{once:!0}):yn();})();
|