@tanay-wispr/webflow-package 6.6.30 → 6.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/androidWaitlist.js +1 -1
- package/dist/calculator-business.js +1 -1
- package/dist/calculator.js +1 -1
- package/dist/desktopAuth.js +1 -1
- package/dist/login.js +1 -1
- package/dist/pricing.js +1 -1
- package/dist/web-demo/index.js +2 -2
- package/package.json +1 -1
package/dist/login.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var Dr=Object.create;var dt=Object.defineProperty;var Nr=Object.getOwnPropertyDescriptor;var Mr=Object.getOwnPropertyNames;var qr=Object.getPrototypeOf,Fr=Object.prototype.hasOwnProperty;var Hr=(r,e)=>()=>(r&&(e=r(r=0)),e);var K=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Br=(r,e)=>{for(var t in e)dt(r,t,{get:e[t],enumerable:!0})},ks=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mr(e))!Fr.call(r,i)&&i!==t&&dt(r,i,{get:()=>e[i],enumerable:!(s=Nr(e,i))||s.enumerable});return r};var Ss=(r,e,t)=>(t=r!=null?Dr(qr(r)):{},ks(e||!r||!r.__esModule?dt(t,"default",{value:r,enumerable:!0}):t,r)),Wr=r=>ks(dt({},"__esModule",{value:!0}),r);var ue={};Br(ue,{Headers:()=>Ht,Request:()=>Jr,Response:()=>Kr,default:()=>Ft,fetch:()=>Gr});var zr,Se,Gr,Ft,Ht,Jr,Kr,oe=Hr(()=>{"use strict";zr=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")},Se=zr(),Gr=Se.fetch,Ft=Se.fetch.bind(Se),Ht=Se.Headers,Jr=Se.Request,Kr=Se.Response});var As=K(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});var Bt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Wt.default=Bt});var Gt=K(Fe=>{"use strict";var Rs=Fe&&Fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fe,"__esModule",{value:!0});var Yr=Rs((oe(),Wr(ue))),Xr=Rs(As()),zt=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=Yr.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let u=null,l=null,h=null,f=n.status,_=n.statusText;if(n.ok){if(this.method!=="HEAD"){let y=await n.text();y===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=y:l=JSON.parse(y))}let m=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),p=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");m&&p&&p.length>1&&(h=parseInt(p[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,h=null,f=406,_="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let m=await n.text();try{u=JSON.parse(m),Array.isArray(u)&&n.status===404&&(l=[],u=null,f=200,_="OK")}catch{n.status===404&&m===""?(f=204,_="No Content"):u={message:m}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,f=200,_="OK"),u&&this.shouldThrowOnError)throw new Xr.default(u)}return{error:u,data:l,count:h,status:f,statusText:_}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};Fe.default=zt});var Kt=K(He=>{"use strict";var Qr=He&&He.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(He,"__esModule",{value:!0});var Zr=Qr(Gt()),Jt=class extends Zr.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};He.default=Jt});var _t=K(Be=>{"use strict";var ei=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});var ti=ei(Kt()),Vt=class extends ti.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};Be.default=Vt});var Xt=K(ze=>{"use strict";var si=ze&&ze.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ze,"__esModule",{value:!0});var We=si(_t()),Yt=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new We.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new We.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new We.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new We.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 We.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ze.default=Yt});var Ps=K(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.version=void 0;yt.version="0.0.0-automated"});var Os=K(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.DEFAULT_HEADERS=void 0;var ri=Ps();wt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ri.version}`}});var Is=K(Ge=>{"use strict";var Cs=Ge&&Ge.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ge,"__esModule",{value:!0});var ii=Cs(Xt()),ni=Cs(_t()),oi=Os(),Qt=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},oi.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ii.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,h])=>h!==void 0).map(([l,h])=>[l,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([l,h])=>{a.searchParams.append(l,h)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new ni.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Ge.default=Qt});var Ns=K(D=>{"use strict";var Je=D&&D.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(D,"__esModule",{value:!0});D.PostgrestBuilder=D.PostgrestTransformBuilder=D.PostgrestFilterBuilder=D.PostgrestQueryBuilder=D.PostgrestClient=void 0;var Ls=Je(Is());D.PostgrestClient=Ls.default;var js=Je(Xt());D.PostgrestQueryBuilder=js.default;var $s=Je(_t());D.PostgrestFilterBuilder=$s.default;var Us=Je(Kt());D.PostgrestTransformBuilder=Us.default;var Ds=Je(Gt());D.PostgrestBuilder=Ds.default;D.default={PostgrestClient:Ls.default,PostgrestQueryBuilder:js.default,PostgrestFilterBuilder:$s.default,PostgrestTransformBuilder:Us.default,PostgrestBuilder:Ds.default}});var Js=K((Un,Gs)=>{"use strict";Gs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var L="https://api.wisprflow.ai";function Ne(r,e){return typeof r.message=="string"&&r.message||typeof r.error=="string"&&r.error||typeof r.detail=="string"&&r.detail||`Request failed with status ${e}`}var qt=class{static async signupUser(e){try{let t=`${L}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${L}/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(`${L}/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(`${L}/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(`${L}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${L}/user_status?email=${encodeURIComponent(e)}`)).json()}static async requestPasswordReset(e,t){let s=await fetch(`${L}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,captcha_token:t})});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(Ne(i,s.status))}}static async signUpWithCaptcha(e){let t=await fetch(`${L}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(Ne(s,t.status));return s}static async signInWithCaptcha(e){let t=await fetch(`${L}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(Ne(s,t.status));return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${L}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(Ne(s,t.status))}}static async signInWithEmail(e){let t=await fetch(`${L}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(Ne(s,t.status));return s}static async getSubscriptionStatus(e){return await fetch(`${L}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${L}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let i=`${L}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(i+=`¤cy=${s}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${L}/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(`${L}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${L}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${L}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let i=new FormData;return i.append("screenshot",e),await fetch(`${L}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function Es(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function Ts(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var V=qt;var xs=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Me=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},ft=class extends Me{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},pt=class extends Me{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},gt=class extends Me{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 Vr=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},qe=class{constructor(e,{headers:t={},customFetch:s,region:i=mt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=xs(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Vr(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(k=>{throw new ft(k)}),h=l.headers.get("x-relay-error");if(h&&h==="true")throw new pt(l);if(!l.ok)throw new gt(l);let f=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),_;return f==="application/json"?_=yield l.json():f==="application/octet-stream"?_=yield l.blob():f==="text/event-stream"?_=l:f==="multipart/form-data"?_=yield l.formData():_=yield l.text(),{data:_,error:null}}catch(i){return{data:null,error:i}}})}};var Ms=Ss(Ns(),1),{PostgrestClient:qs,PostgrestQueryBuilder:_n,PostgrestFilterBuilder:yn,PostgrestTransformBuilder:wn,PostgrestBuilder:vn}=Ms.default;var Fs="2.10.2";var Hs={"X-Client-Info":`realtime-js/${Fs}`},Bs="1.0.0",bt=1e4,Ws=1e3,he;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(he||(he={}));var F;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(F||(F={}));var B;(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"})(B||(B={}));var vt;(function(r){r.websocket="websocket"})(vt||(vt={}));var ae;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(ae||(ae={}));var Ke=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var de=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 x;(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"})(x||(x={}));var es=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=ai(o,r,e,i),n),{})},ai=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?zs(n,o):Zt(o)},zs=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return hi(e,t)}switch(r){case x.bool:return ci(e);case x.float4:case x.float8:case x.int2:case x.int4:case x.int8:case x.numeric:case x.oid:return li(e);case x.json:case x.jsonb:return ui(e);case x.timestamp:return di(e);case x.abstime:case x.date:case x.daterange:case x.int4range:case x.int8range:case x.money:case x.reltime:case x.text:case x.time:case x.timestamptz:case x.timetz:case x.tsrange:case x.tstzrange:return Zt(e);default:return Zt(e)}},Zt=r=>r,ci=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},li=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},ui=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},hi=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n,o=r.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>zs(e,a))}return r},di=r=>typeof r=="string"?r.replace(" ","T"):r,kt=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var fe=class{constructor(e,t,s={},i=bt){this.channel=e,this.event=t,this.payload=s,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var ts;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(ts||(ts={}));var Ee=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let h=n[u];if(h){let f=l.map(p=>p.presence_ref),_=h.map(p=>p.presence_ref),k=l.filter(p=>_.indexOf(p.presence_ref)<0),m=h.filter(p=>f.indexOf(p.presence_ref)<0);k.length>0&&(a[u]=k),m.length>0&&(c[u]=m)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let h=e[a].map(_=>_.presence_ref),f=l.filter(_=>h.indexOf(_.presence_ref)<0);e[a].unshift(...f)}s(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(h=>h.presence_ref);u=u.filter(h=>l.indexOf(h.presence_ref)<0),e[a]=u,i(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var ss;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(ss||(ss={}));var rs;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(rs||(rs={}));var is;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(is||(is={}));var Te=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=F.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new fe(this,B.join,this.params,this.timeout),this.rejoinTimer=new de(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=F.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=F.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this._on(B.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Ee(this),this.broadcastEndpointURL=kt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var h;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,_=(h=f?.length)!==null&&h!==void 0?h:0,k=[];for(let m=0;m<_;m++){let p=f[m],{filter:{event:y,schema:O,table:P,filter:C}}=p,T=l&&l[m];if(T&&T.event===y&&T.schema===O&&T.table===P&&T.filter===C)k.push(Object.assign(Object.assign({},p),{id:T.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=k,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=F.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(B.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new fe(this,B.leave,{},e);i.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let i=new AbortController,n=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new fe(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:u,join:l}=B;if(s&&[a,c,u,l].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,t,s);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(_=>{var k,m,p;return((k=_.filter)===null||k===void 0?void 0:k.event)==="*"||((p=(m=_.filter)===null||m===void 0?void 0:m.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(_=>_.callback(f,s)):(n=this.bindings[o])===null||n===void 0||n.filter(_=>{var k,m,p,y,O,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in _){let C=_.id,T=(k=_.filter)===null||k===void 0?void 0:k.event;return C&&((m=t.ids)===null||m===void 0?void 0:m.includes(C))&&(T==="*"||T?.toLocaleLowerCase()===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{let C=(O=(y=_?.filter)===null||y===void 0?void 0:y.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return C==="*"||C===((P=t?.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return _.type.toLocaleLowerCase()===o}).map(_=>{if(typeof f=="object"&&"ids"in f){let k=f.data,{schema:m,table:p,commit_timestamp:y,type:O,errors:P}=k;f=Object.assign(Object.assign({},{schema:m,table:p,commit_timestamp:y,eventType:O,new:{},old:{},errors:P}),this._getPayloadRecords(k))}_.callback(f,s)})}_isClosed(){return this.state===F.closed}_isJoined(){return this.state===F.joined}_isJoining(){return this.state===F.joining}_isLeaving(){return this.state===F.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(B.close,{},e)}_onError(e){this._on(B.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=F.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=es(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=es(e.columns,e.old_record)),t}};var pi=()=>{},gi=typeof WebSocket<"u",xe=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Hs,this.params={},this.timeout=bt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=pi,this.conn=null,this.sendBuffer=[],this.serializer=new Ke,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${vt.websocket}`,this.httpEndpoint=kt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(s=t?.params)===null||s===void 0?void 0:s.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new de(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(gi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new ns(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ss(Js())).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 he.connecting:return ae.Connecting;case he.open:return ae.Open;case he.closing:return ae.Closing;default:return ae.Closed}}isConnected(){return this.connectionState()===ae.Open}channel(e,t={config:{}}){let s=new Te(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(B.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:Bs}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(B.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Ws,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},ns=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=he.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var Ae=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function j(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var St=class extends Ae{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Ve=class extends Ae{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var mi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Et=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Ks=()=>mi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(oe(),ue))).Response:Response});var Re=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},os=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),_i=(r,e)=>Re(void 0,void 0,void 0,function*(){let t=yield Ks();r instanceof t?r.json().then(s=>{e(new St(os(s),r.status||500))}).catch(s=>{e(new Ve(os(s),s))}):e(new Ve(os(r),r))}),yi=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};function Tt(r,e,t,s,i,n){return Re(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,yi(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>_i(c,a))})})}function Ye(r,e,t,s){return Re(this,void 0,void 0,function*(){return Tt(r,"GET",e,t,s)})}function Y(r,e,t,s,i){return Re(this,void 0,void 0,function*(){return Tt(r,"POST",e,s,i,t)})}function Vs(r,e,t,s,i){return Re(this,void 0,void 0,function*(){return Tt(r,"PUT",e,s,i,t)})}function xt(r,e,t,s,i){return Re(this,void 0,void 0,function*(){return Tt(r,"DELETE",e,s,i,t)})}var W=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},wi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ys={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Xe=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Et(i)}uploadOrUpdate(e,t,s,i){return W(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Ys),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),h=yield l.json();return l.ok?{data:{path:c,id:h.Id,fullPath:h.Key},error:null}:{data:null,error:h}}catch(n){if(j(n))return{data:null,error:n};throw n}})}upload(e,t,s){return W(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return W(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,u=Object.assign({upsert:Ys.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",u.cacheControl)):(c=s,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let h=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),f=yield h.json();return h.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(j(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return W(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield Y(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ae("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(j(s))return{data:null,error:s};throw s}})}update(e,t,s){return W(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return W(this,void 0,void 0,function*(){try{return{data:yield Y(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}copy(e,t,s){return W(this,void 0,void 0,function*(){try{return{data:{path:(yield Y(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return W(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield Y(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return W(this,void 0,void 0,function*(){try{let i=yield Y(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}download(e,t){return W(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Ye(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(j(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${u}`)}}}remove(e){return W(this,void 0,void 0,function*(){try{return{data:yield xt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}list(e,t,s){return W(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},wi),t),{prefix:e||""});return{data:yield Y(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Xs="2.6.0";var Qs={"X-Client-Info":`storage-js/${Xs}`};var Pe=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Qe=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Qs),t),this.fetch=Et(s)}listBuckets(){return Pe(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}})}getBucket(e){return Pe(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Pe(this,void 0,void 0,function*(){try{return{data:yield Y(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(j(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Pe(this,void 0,void 0,function*(){try{return{data:yield Vs(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(j(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Pe(this,void 0,void 0,function*(){try{return{data:yield Y(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Pe(this,void 0,void 0,function*(){try{return{data:yield xt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}};var Ze=class extends Qe{constructor(e,t={},s){super(e,t,s)}from(e){return new Xe(this.url,this.headers,e,this.fetch)}};var Zs="2.44.4";var et="";typeof Deno<"u"?et="deno":typeof document<"u"?et="web":typeof navigator<"u"&&navigator.product==="ReactNative"?et="react-native":et="node";var vi={"X-Client-Info":`supabase-js-${et}/${Zs}`},er={headers:vi},tr={schema:"public"},sr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},rr={};oe();var bi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},ki=r=>{let e;return r?e=r:typeof fetch>"u"?e=Ft:e=fetch,(...t)=>e(...t)},Si=()=>typeof Headers>"u"?Ht:Headers,ir=(r,e,t)=>{let s=ki(t),i=Si();return(n,o)=>bi(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",r),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:u}))})};function nr(r){return r.replace(/\/$/,"")}function or(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var At="2.64.4";var ar="http://localhost:9999",cr="supabase.auth.token";var lr={"X-Client-Info":`gotrue-js/${At}`},as=10;var tt="X-Supabase-Api-Version",cs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function ur(r){return Math.round(Date.now()/1e3)+r}function hr(){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 z=()=>typeof document<"u",pe={tested:!1,writable:!1},ce=()=>{if(!z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(pe.tested)return pe.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),pe.tested=!0,pe.writable=!0}catch{pe.tested=!0,pe.writable=!1}return pe.writable};function Rt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var Pt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},dr=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",ls=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},rt=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Ot=async(r,e)=>{await r.removeItem(e)};function Ei(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,u,l=0;for(r=r.replace("-","+").replace("_","/");l<r.length;)o=e.indexOf(r.charAt(l++)),a=e.indexOf(r.charAt(l++)),c=e.indexOf(r.charAt(l++)),u=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var st=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};st.promiseConstructor=Promise;function us(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(Ei(s))}async function fr(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function pr(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await r(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Ti(r){return("0"+r.toString(16)).substr(-2)}function xi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,Ti).join("")}async function Ai(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Ri(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Pi(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 Ai(r);return Ri(t)}async function ge(r,e,t=!1){let s=xi(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await ls(r,`${e}-code-verifier`,i);let n=await Pi(s);return[n,s===n?"plain":"s256"]}var Oi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function gr(r){let e=r.headers.get(tt);if(!e||!e.match(Oi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var it=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function b(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Ct=class extends it{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function mr(r){return b(r)&&r.name==="AuthApiError"}var Oe=class extends it{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},se=class extends it{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},X=class extends se{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ce=class extends se{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},me=class extends se{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},_e=class extends se{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}}},nt=class extends se{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}}},Ie=class extends se{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function It(r){return b(r)&&r.name==="AuthRetryableFetchError"}var ot=class extends se{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};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 i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},ye=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Ii=[502,503,504];async function _r(r){var e;if(!dr(r))throw new Ie(ye(r),0);if(Ii.includes(r.status))throw new Ie(ye(r),r.status);let t;try{t=await r.json()}catch(n){throw new Oe(ye(n),n)}let s,i=gr(r);if(i&&i.getTime()>=cs["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 ot(ye(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new ot(ye(t),r.status,t.weak_password.reasons);throw new Ct(ye(t),r.status||500,s)}var Li=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function S(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[tt]||(n[tt]=cs["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await ji(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function ji(r,e,t,s,i,n){let o=Li(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new Ie(ye(c),0)}if(a.ok||await _r(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await _r(c)}}function re(r){var e;let t=null;$i(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=ur(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function hs(r){let e=re(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 Q(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function yr(r){return{data:r,error:null}}function wr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Ci(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function vr(r){return r}function $i(r){return r.access_token&&r.refresh_token&&r.expires_in}var Ui=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},we=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Pt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Q})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Ui(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:wr,redirectTo:t?.redirectTo})}catch(t){if(b(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Q})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:vr});if(l.error)throw l.error;let h=await l.json(),f=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,_=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return _.length>0&&(_.forEach(k=>{let m=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(k.split(";")[1].split("=")[1]);u[`${p}Page`]=m}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(b(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Q})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Q})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Q})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}};var br={getItem:r=>ce()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ce()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ce()&&globalThis.localStorage.removeItem(r)}};function ds(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function kr(){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 ve={debug:!!(globalThis&&ce()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},at=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Lt=class extends at{};async function fs(r,e,t){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),ve.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Lt(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(ve.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}kr();var Di={url:ar,storageKey:cr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:lr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},ct=30*1e3,Sr=3;async function Er(r,e,t){return await t()}var be=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&&z()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},Di),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new we({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Pt(i.fetch),this.lock=i.lock||Er,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:z()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=fs:this.lock=Er,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:ce()?this.storage=br:(this.memoryStorage={},this.storage=ds(this.memoryStorage)):(this.memoryStorage={},this.storage=ds(this.memoryStorage)),z()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${At}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=z()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return b(e)?{error:e}:{error:new Oe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:re}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(b(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:l,password:h,options:f}=e,_=null,k=null;this.flowType==="pkce"&&([_,k]=await ge(this.storage,this.storageKey)),n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:l,password:h,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:_,code_challenge_method:k},xform:re})}else if("phone"in e){let{phone:l,password:h,options:f}=e;n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:h,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(i=f?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:re})}else throw new me("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(b(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:hs})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:hs})}else throw new me("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Ce}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await rt(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:re});return await Ot(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Ce}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:i,access_token:n,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:re}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Ce}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await ge(this.storage,this.storageKey));let{error:h}=await S(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:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:l}}throw new me("You must provide either an email or phone number.")}catch(a){if(b(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:re});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(b(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await ge(this.storage,this.storageKey)),await S(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:yr})}catch(n){if(b(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new X;let{error:i}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(b(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await S(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:i,options:n}=e,{data:o,error:a}=await S(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new me("You must provide either an email or phone number and a type")}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await rt(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,u,l)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Q}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new X}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:Q})})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new X;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await ge(this.storage,this.storageKey));let{data:u,error:l}=await S(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:Q});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return us(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 X;let t=Date.now()/1e3,s=t,i=!0,n=null,o=us(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(b(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 X;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!z())throw new _e("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new _e("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new nt("Not a valid PKCE flow url.");let t=Rt(window.location.href);if(e){if(!t.code)throw new nt("No code detected.");let{data:O,error:P}=await this._exchangeCodeForSession(t.code);if(P)throw P;let C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:O.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new _e(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:u}=t;if(!n||!a||!o||!u)throw new _e("No session defined in URL");let l=Math.round(Date.now()/1e3),h=parseInt(a),f=l+h;c&&(f=parseInt(c));let _=f-l;_*1e3<=ct&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${_}s, should have been closer to ${h}s`);let k=f-h;l-k>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",k,f,l):l-k<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",k,f,l);let{data:m,error:p}=await this._getUser(n);if(p)throw p;let y={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:h,expires_at:f,refresh_token:o,token_type:u,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:t.type},error:null}}catch(t){if(b(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Rt(window.location.href);return!!(z()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Rt(window.location.href),t=await rt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{error:n};let o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(mr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Ot(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=hr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await ge(this.storage,this.storageKey,!0));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(b(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,u,l;let{data:h,error:f}=n;if(f)throw f;let _=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 S(this.fetch,"GET",_,{headers:this.headers,jwt:(l=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return z()&&!(!((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(b(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(b(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 pr(async i=>(i>0&&await fr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:re})),(i,n)=>{let o=200*Math.pow(2,i);return n&&It(n)&&Date.now()+o-s<ct})}catch(s){if(this._debug(t,"error",s),b(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),z()&&!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 rt(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<i+as;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${as}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),It(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 X;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new st;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new X;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),b(n)){let o={session:null,error:n};return It(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await ls(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Ot(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&z()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),ct);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((s.expires_at*1e3-e)/ct);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${ct}ms, refresh threshold is ${Sr} ticks`),i<=Sr&&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 at)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!z()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await ge(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await S(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(b(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(b(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};be.nextInstanceID=0;var Ni=be,ps=Ni;var jt=class extends ps{constructor(e){super(e)}};var Mi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},lt=class{constructor(e,t,s){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=nr(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:tr,realtime:rr,auth:Object.assign(Object.assign({},sr),{storageKey:c}),global:er},l=or(s??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=ir(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new qs(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new qe(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ze(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},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 Mi(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,storageKey:n,flowType:o,debug:a},c,u){var l;let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new jt({url:this.authUrl,headers:Object.assign(Object.assign({},h),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new xe(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 Tr=(r,e,t)=>new lt(r,e,t);var ie={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var qi=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},$t=r=>{let[e,t]=r.split(".");return!e||!t?null:qi(t)},Le=r=>{let e=$t(r);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Fi="https://api.workos.com",Hi=60,je=(r,e)=>typeof r[e]=="string"?r[e]:void 0,xr=(r,e,t)=>{let s=$t(r);if(!s)return null;let i=je(s,"urn:wispr:user_external_id")??je(s,"sub"),n=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:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},Bi=async(r,e,t,s)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Fi,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:r,organization_id:s})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},Ar=async(r,e)=>{let t=$t(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=je(t,"client_id");if(i-s<Hi&&n){let c=await Bi(e,n,je(t,"iss"),je(t,"org_id")),u=xr(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=s)throw new Error("WorkOS session expired");let a=xr(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var $e=class{constructor(){this.sessionData=null;this.supabase=Tr(ie.supaBaseUrl,ie.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ie.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||ie.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||ie.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let i=new Date;i.setTime(i.getTime()+s*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{if(Le(t)==="workos"){this.sessionData=await Ar(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,i]=t.split("=");return e[s]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ie.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,i,n){try{if(!n)throw new Error("Please complete the verification");await V.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:n,redirect_url:i||ie.redirectUri}),console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await V.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:i?.provision??!1,workos_capable:i?.workosCapable});if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in successful for:",e),{accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,s){try{if(!s)throw new Error("Please complete the verification");await V.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||ie.redirectUri}),console.log("Verification email resent to:",e)}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 Z=null;function gs(r,e=30,t){Z&&(clearInterval(Z),Z=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,Z=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",Z&&(clearInterval(Z),Z=null),t&&t())},1e3)}function Rr(){Z&&(clearInterval(Z),Z=null)}var Pr=/^[\p{L}\p{M}\s\-'.]+$/u;function Wi(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Pr.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":Pr.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 Or(r,e,t){let s="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let u=document.getElementById(s);u||(u=document.createElement("div"),u.id=s,u.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",u)),u.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=Wi(e.value,r.value);c?i(c):n()},a=()=>{let c=ms(e.value,r.value);c?i(c):n()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var zi="123456",Ut=null;function _s(){return new URLSearchParams(window.location.search).get("dev-mode")==="true"}var Dt=()=>{Ut!==null&&(window.clearInterval(Ut),Ut=null)};function ys(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),Dt()}function ws(r){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),s=document.querySelector("[otp-email]"),i=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),c=document.querySelector("[otp-resend-countdown]"),u=document.querySelector("[otp-resend-seconds]"),l=document.querySelector("[otp-reset]");t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),n&&(n.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents=""),Dt(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let h=m=>{n&&(n.style.display="block"),o&&(o.textContent=m)},f=()=>{n&&(n.style.display="none")},_=async()=>{let m=t.map(p=>p.value).join("");if(m.length!==6){h("Please enter all 6 digits.");return}m===zi?(f(),i&&(i.textContent="Verified \u2705",i.style.pointerEvents="none"),t.forEach(p=>p.setAttribute("disabled","true")),await r.onVerifySuccess?.()):h("Incorrect or expired code. Try again.")};t.forEach((m,p)=>{m.oninput=()=>{m.value=m.value.replace(/\D/g,"").slice(0,1),m.value&&p<t.length-1&&t[p+1].focus(),f()},m.onkeydown=y=>{y.key==="Backspace"&&!m.value&&p>0?t[p-1].focus():y.key==="Enter"&&(y.preventDefault(),_())},m.onpaste=y=>{y.preventDefault();let O=(y.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((C,T)=>{t[T]&&(t[T].value=C)});let P=Math.min(O.length,t.length-1);t[P]?.focus(),f()}}),i&&(i.onclick=m=>{m.preventDefault(),_()});let k=()=>{let m=60;a&&(a.style.display="none"),c&&(c.style.display="block"),u&&(u.textContent=String(m)),Dt(),Ut=window.setInterval(()=>{m-=1,u&&(u.textContent=String(m)),m<=0&&(Dt(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async m=>{m.preventDefault(),t.forEach(p=>{p.value="",p.removeAttribute("disabled")}),t[0]?.focus(),f(),k(),await r.onResend?.()}),l&&(l.onclick=m=>{m.preventDefault(),ys(),r.onReset?.()})}var A=(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(()=>A(r,e,t-1),200)};var Gi="wisprjam.com",Ji="wispr.ai",Ki=r=>r.trim().toLowerCase().split("@")[1]??"",vs=r=>{let e=Ki(r);return e===Gi||e===Ji};function Cr(r,e){let t=new $e,s="email_input",i=document.querySelector("#email-form"),n=document.querySelector("#email-input"),o=document.querySelector("#password-input"),a=document.querySelector("#full-name"),c=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),h=document.querySelector("[email-element]"),f=document.querySelector("[different-provider]"),_=document.querySelector("[different-provider-name]"),k=document.querySelector("[different-provider-reset]"),m=document.querySelector("[email-signup-success]"),p=document.querySelector("[email-signup-error]"),y=document.querySelector("[error-message]"),O=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),C=document.querySelector("[email-signup-reset]"),T=document.querySelector("[scim-div]"),le=document.querySelector("[scim-reset]"),N=document.querySelector("[forgot-password]"),ee=document.querySelector("[forgot-password-success]"),M=document.querySelector("[forgot-password-email]"),H=document.querySelector("[unverified-email]"),Ue=document.querySelector("[unverified-email-address]"),te=document.querySelector("[resend-verification-email]"),G=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(c&&c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(d){console.error("Error during Google sign-in:",d)}}),u&&u.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(d){console.error("Error during Apple sign-in:",d)}}),l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(d){console.error("Error during Microsoft sign-in:",d)}}));let q=()=>{f&&(f.style.display="none"),m&&(m.style.display="none"),p&&(p.style.display="none"),H&&(H.style.display="none"),T&&(T.style.display="none"),N&&(N.style.display="none"),ee&&(ee.style.display="none"),ys();let d=document.querySelector(".gs-hero_form-block");d&&(d.style.display="block"),h&&(h.style.display="flex"),n&&(n.value="",n.removeAttribute("readonly"),n.classList.remove("disabled")),o&&(o.value="",o.style.display="none",o.removeAttribute("required")),a&&(a.value="",a.style.display="none",a.removeAttribute("required"));let g=document.querySelector("[captcha-embed]"),w=document.querySelector("#h-captcha-container");g&&(g.style.display="none"),w&&(w.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",n&&n.focus()},ne=()=>{n&&(n.setAttribute("readonly","true"),n.classList.add("disabled")),o&&(o.style.display="block",o.setAttribute("required","true"),o.focus()),a&&(a.style.display="none",a.removeAttribute("required"));let d=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");d&&(d.style.display="block"),g&&(g.style.display="block"),N&&(N.style.display="block",N.onclick=async()=>{let w=n?.value||"",E=N.textContent||"";try{let{hcaptcha:I}=window;if(!I)throw new Error("Verification system not loaded. Please refresh the page.");N.style.pointerEvents="none",N.textContent="Sending...";let{response:R}=await I.execute({async:!0});if(!R)throw new Error("Verification cancelled");await V.requestPasswordReset(w,R),I.reset(),h&&(h.style.display="none"),N&&(N.style.display="none"),ee&&(ee.style.display="block"),M&&(M.textContent=w)}catch(I){console.error("Error sending password reset email:",I),N.textContent=E,N.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),p&&(p.style.display="block",y&&(y.textContent=I instanceof Error?I.message:"Failed to send reset email"))}}),s="login"},ke=()=>{n&&(n.setAttribute("readonly","true"),n.classList.add("disabled")),o&&(o.style.display="block",o.setAttribute("required","true"),o.focus()),a&&(a.style.display="block",a.setAttribute("required","true"));let d=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");d&&(d.style.display="block"),g&&(g.style.display="block"),s="signup"},De=()=>{let d=document.querySelector(".gs-hero_form-block");d&&(d.style.display="none"),T&&(T.style.display="block"),le&&(le.onclick=()=>{T&&(T.style.display="none"),d&&(d.style.display="block"),q()})},ut=d=>{let g=Ts(d);h&&(h.style.display="none"),f&&(f.style.display="block"),_&&(_.textContent=g),k&&(k.onclick=()=>{f&&(f.style.display="none"),q()}),s="oauth_user"},ht=d=>{h&&(h.style.display="none"),H&&(H.style.display="block"),Ue&&(Ue.textContent=d),te&&(te.onclick=async()=>{if(_s()){H&&(H.style.display="none"),ws({email:d,onVerifySuccess:()=>{console.log("[dev-mode] OTP verified for",d)},onResend:()=>{console.log("[dev-mode] resend clicked for",d)},onReset:()=>{q()}});return}let g=te.textContent||"";try{let w=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(d,r,w),te.textContent="Verification email resent! \u2705",te.style.textDecoration="none"}catch(w){console.error("Error resending verification email:",w),te.textContent=g}}),G&&(G.onclick=()=>{H&&(H.style.display="none"),q()}),s="unverified_email"},Nt=async(d,g)=>{let w=g.value;g.classList.add("loading"),g.value="";try{let E=await V.checkUserStatus(d);g.classList.remove("loading"),g.value=w,!E.exists&&E.scim_managed?De():E.enforce_sso?ut("workos"):E.exists&&E.provider&&E.provider!=="email"?ut(E.provider):E.exists&&E.provider==="email"&&!E.verified?ht(d):E.exists&&E.provider==="email"?ne():ke()}catch(E){console.error("Error checking user status:",E),g.classList.remove("loading"),g.value=w,ke()}},Mt=async(d,g,w,E)=>{if(!g||g.length<8){p&&(p.style.display="block",y&&(y.textContent="Password must be at least 8 characters"));return}let I=window.hcaptcha?.getResponse()||"";if(!I){p&&(p.style.display="block",y&&(y.textContent="Please complete the verification"));return}w.classList.add("loading"),w.value="";try{if(e?.mcpLoginState){let J=await V.signInWithEmail({email:d,password:g,mcp_login_state:e.mcpLoginState});if(!J.redirect_url)throw new Error(J.error||"Unable to continue connector login. Please try again.");A("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=J.redirect_url;return}let{accessToken:R,refreshToken:U,fullName:$}=await t.signInWithPassword(d,g,I,{workosCapable:vs(d),provision:!1});t.setCookies(R,U),localStorage.setItem("email",d),e?.onLoginSuccess?await e.onLoginSuccess(R,U,$):window.location.href=r}catch(R){if(console.error("Login error:",R),window.hcaptcha&&window.hcaptcha.reset(),w.classList.remove("loading"),w.value=E,p&&(p.style.display="block",y)){let U=R instanceof Error?R.message:"Invalid login credentials";y.textContent=U}}},v=async(d,g,w,E,I)=>{if(!g||g.length<8){p&&(p.style.display="block",y&&(y.textContent="Password must be at least 8 characters"));return}if(!w||w.trim().length<2){p&&(p.style.display="block",y&&(y.textContent="Please enter your full name"));return}let R=ms(w,g);if(R){p&&(p.style.display="block",y&&(y.textContent=R));return}let U=window.hcaptcha?.getResponse()||"";if(!U){p&&(p.style.display="block",y&&(y.textContent="Please complete the verification"));return}E.classList.add("loading"),E.value="";try{if(await t.signUpWithPassword(d,g,w,r,U),window.hcaptcha&&window.hcaptcha.reset(),E.classList.remove("loading"),E.value=I,h&&(h.style.display="none"),p&&(p.style.display="none"),_s()){ws({email:d,onVerifySuccess:()=>{console.log("[dev-mode] OTP verified for signup",d)},onResend:()=>{console.log("[dev-mode] resend clicked for signup",d)},onReset:()=>{q()}});return}m&&(m.style.display="block"),O&&(O.textContent=d),P&&(gs(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let $=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(d,r,$),window.hcaptcha&&window.hcaptcha.reset(),gs(P,30)}catch($){console.error("Error resending verification email:",$)}}),C&&(C.onclick=()=>{m&&(m.style.display="none"),Rr(),q()})}catch($){if(console.error("Signup error:",$),E.classList.remove("loading"),E.value=I,p&&(p.style.display="block",y)){let J=$ instanceof Error?$.message:"Signup failed";y.textContent=J}}};return i&&o&&a&&Or(o,a,i.querySelector('[type="submit"]')),i&&i.addEventListener("submit",async d=>{d.stopPropagation(),d.preventDefault();let g=n?.value||"",w=o?.value||"",E=a?.value||"";if(!g||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g)){p&&(p.style.display="block",y&&(y.textContent="Please enter a valid email address"));return}p&&(p.style.display="none"),y&&(y.textContent="");let R=i.querySelector('[type="submit"]'),U=R?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await Nt(g,R):s==="login"?await Mt(g,w,R,U):s==="signup"&&await v(g,w,E,R,U)}catch($){console.error("Auth flow error:",$),R&&(R.classList.remove("loading"),R.value=U),p&&(p.style.display="block")}}),{reset:q}}var Vi=/google ads|google adservices|adwords/i,Yi=/marketing|advertising/i,Ir=r=>{let e=r.filter(s=>Vi.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=>Yi.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}}},Xi=async()=>{try{let{__ucCmp:r,UC_UI:e}=window;if(r?.getConsentDetails){let t=await r.getConsentDetails();return Ir(Object.values(t?.services??{}).map(s=>({name:s?.name,category:s?.category,decision:s?.consent?.type==="EXPLICIT"&&typeof s.consent.given=="boolean"?s.consent.given:void 0})))}if(e?.getServicesBaseInfo)return Ir((e.getServicesBaseInfo()??[]).map(t=>({name:t?.name,category:t?.categorySlug,decision:t?.consent?.history?.some(s=>s?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0})))}catch{}},Lr=()=>{let r=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([Xi(),r])};function jr(r){try{let e=r._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let s=t.split(".");if(s.length>=3){let i=s.slice(2).join(".");if(i)return i}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var $r=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var bs="https://api.wisprflow.ai",Ur="https://wisprflow.ai";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new $e,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),s=document.querySelector("[error-div]"),i=document.querySelector("[error-message-api]"),n=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),u=c?.value??"",l=document.querySelector("#google-login"),h=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),_=localStorage.getItem("last_authed_provider");_&&{google:l,apple:h,microsoft:f,sso:document.querySelector("#sso-login"),email:document.querySelector("#email-input")}[_]?.classList.add("last-used");let k=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},m=()=>{let d=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";A("desktop_login_auto_launch",{deep_link:d}),window.location.href=d},p=()=>{let v=localStorage.getItem("signin_provider");v&&localStorage.setItem("last_authed_provider",v),e&&(e.style.display="none"),t&&(t.style.display="block"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",m()},y=v=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),i&&(i.textContent=v),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},O=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},P=null,C=document.querySelector("[retry-button]");C&&C.addEventListener("click",()=>T());let T=()=>{e&&(e.style.display="none"),a&&(a.style.display="none"),n&&(n.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=u),P&&P()},le=async(v,d)=>{try{let[g,w]=Es(d||" "),E=V.signupUser({access_token:v,first_name:g,last_name:w}),I=new Promise((R,U)=>setTimeout(()=>U(new Error("signup timeout")),4e3));await Promise.race([E,I])}catch(g){A("signup_sync_error",{error_message:g instanceof Error?g.message:String(g)})}},N=()=>{let v=sessionStorage.getItem("wispr_fbclid");return v?`fb.1.${Date.now()}.${v}`:null},ee=async(v,d)=>{let g=sessionStorage.getItem("wispr_device_code");if(!g)throw new Error("Device code not found. Please restart authentication from desktop app.");let w=$r(),E=await Lr(),I=localStorage.getItem("wf_utm_source")||void 0,R=localStorage.getItem("wf_utm_medium")||void 0,U=localStorage.getItem("wf_utm_campaign")||void 0,$=await fetch(`${bs}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${v}`},body:JSON.stringify({device_code:g,access_token:v,refresh_token:d,fbp:w._fbp||void 0,fbc:w._fbc||N()||void 0,gclid:jr(w),utm:I||R||U?{utm_source:I,utm_medium:R,utm_campaign:U}:void 0,ad_user_data:E?.ad_user_data,ad_personalization:E?.ad_personalization})});if(!$.ok){let J=await $.json().catch(()=>({}));throw $.status===403&&J?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(J?.detail?.message||J.message||`Server error: ${$.status}`)}console.log("Device authentication complete:",await $.json()),sessionStorage.removeItem("wispr_device_code"),Le(v)==="workos"&&r.setCookie("refresh_token",d,30/86400)},M=new URLSearchParams(window.location.search),H=M.get("device_code"),Ue=M.get("auto_signin")==="true",te=new URLSearchParams(window.location.hash.slice(1)),G=M.get("access_token")||te.get("access_token"),q=M.get("refresh_token")||te.get("refresh_token"),ne=M.get("mcp_login_state");if(!H&&!G&&!q&&!ne&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),A("desktop_login_no_device_code"),window.location.href="/get-started";return}if(A("desktop_login_page_view",{auto_signin:Ue}),H){sessionStorage.setItem("wispr_device_code",H),console.log("Device code stored:",H);let v=M.get("fbclid");v&&sessionStorage.setItem("wispr_fbclid",v);let d=M.get("skip_default_trial"),g=M.get("grant_weekly_bonus");d&&sessionStorage.setItem("wispr_skip_default_trial",d),g&&sessionStorage.setItem("wispr_grant_weekly_bonus",g),window.history.replaceState({},"","/login")}let ke="wispr_workos_second_hop_attempted";if(G&&q){console.log("OAuth callback detected - handling tokens");let v=Le(G);if(A("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:v}),k(),v==="workos"){sessionStorage.removeItem(ke);try{r.setCookies(G,q);let d=M.get("email");d&&localStorage.setItem("email",d);let g=M.get("user_id");g&&localStorage.setItem("user_id",g),await le(G,M.get("name")??void 0),await ee(G,q),A("desktop_login_complete_success",{method:"oauth",provider:"workos"}),p()}catch(d){if(d instanceof Error&&d.message==="enterprise_ip_not_allowed"){A("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),O();return}let g=d instanceof Error?d.message:"Failed to complete authentication. Please try again.";A("desktop_login_complete_error",{method:"oauth",provider:"workos",error:g}),console.error("Error completing WorkOS device authentication:",d),y(g)}return}try{let d=G,g=q;try{r.setCookies(G,q),await r.checkAndSetSession(),r.sessionData&&(d=r.sessionData.access_token,g=r.sessionData.refresh_token,r.setCookies(d,g),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}let w=r.sessionData?.user.email;if(w&&vs(w)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(ke)){sessionStorage.setItem(ke,"true"),A("desktop_login_workos_second_hop",{email_domain:w.split("@")[1]??"unknown"}),window.location.href=`${bs}/authkit/google/sign_in?source=${Ur}`;return}await le(d,r.sessionData?.user.user_metadata?.full_name),await ee(d,g),A("desktop_login_complete_success",{method:"oauth"}),p()}catch(d){if(d instanceof Error&&d.message==="enterprise_ip_not_allowed"){A("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),O();return}let g=d instanceof Error?d.message:"Failed to complete authentication. Please try again.";A("desktop_login_complete_error",{method:"oauth",error:g}),console.error("Error completing device authentication:",d),y(g)}return}if(Ue){console.log("Auto-signin enabled - checking existing session"),k();try{let v=r.checkAndSetSession(),d=new Promise((g,w)=>setTimeout(()=>w(new Error("Session timeout")),3e3));if(await Promise.race([v,d]),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 le(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await ee(r.sessionData.access_token,r.sessionData.refresh_token),A("desktop_login_auto_signin_success",{token_provider:Le(r.sessionData.access_token)}),p();return}console.log("No existing session - showing login form"),A("desktop_login_auto_signin_no_session"),T()}catch(v){if(console.error("Auto-signin error:",v),v instanceof Error&&v.message==="enterprise_ip_not_allowed"){A("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),O();return}let d=v instanceof Error?v.message:"Auto-signin failed. Please try logging in manually.";A("desktop_login_auto_signin_error",{error:d}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),T()}}else ne?(A("desktop_login_mcp_entry"),T()):(A("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"),T());let De=v=>{console.log(`Redirecting to ${v} OAuth`),A("desktop_login_oauth_click",{provider:v,mcp:!!ne}),localStorage.setItem("signin_provider",v);let d=`${bs}/${v}/sign_in?source=${Ur}`,g=sessionStorage.getItem("wispr_skip_default_trial"),w=sessionStorage.getItem("wispr_grant_weekly_bonus");g&&(d+=`&skip_default_trial=${encodeURIComponent(g)}`),w&&(d+=`&grant_weekly_bonus=${encodeURIComponent(w)}`),ne&&(d+=`&mcp_login_state=${encodeURIComponent(ne)}`),window.location.href=d};l&&l.addEventListener("click",()=>{De("google")}),h&&h.addEventListener("click",()=>{De("apple")}),f&&f.addEventListener("click",()=>{De("microsoft")});let ut=async(v,d,g)=>{try{await le(v,g),await ee(v,d)}catch(w){if(w instanceof Error&&w.message==="enterprise_ip_not_allowed"){A("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),O();return}let E=w instanceof Error?w.message:"Failed to complete authentication. Please try again.";A("desktop_login_complete_error",{method:"email",error:E}),y(E);return}A("desktop_login_complete_success",{method:"email"}),p()},ht=sessionStorage.getItem("wispr_device_code"),Nt=ht?`${window.location.origin}/login?device_code=${ht}`:`${window.location.origin}/login`,{reset:Mt}=Cr(Nt,{onLoginSuccess:ut,mcpLoginState:ne,skipOAuthButtons:!0});P=Mt,console.log("Desktop login page initialized")});})();
|
|
1
|
+
"use strict";(()=>{var Mr=Object.create;var pt=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Fr=Object.getOwnPropertyNames;var Hr=Object.getPrototypeOf,Br=Object.prototype.hasOwnProperty;var Wr=(r,e)=>()=>(r&&(e=r(r=0)),e);var K=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),zr=(r,e)=>{for(var t in e)pt(r,t,{get:e[t],enumerable:!0})},Es=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fr(e))!Br.call(r,i)&&i!==t&&pt(r,i,{get:()=>e[i],enumerable:!(s=qr(e,i))||s.enumerable});return r};var Ts=(r,e,t)=>(t=r!=null?Mr(Hr(r)):{},Es(e||!r||!r.__esModule?pt(t,"default",{value:r,enumerable:!0}):t,r)),Gr=r=>Es(pt({},"__esModule",{value:!0}),r);var ue={};zr(ue,{Headers:()=>Wt,Request:()=>Vr,Response:()=>Yr,default:()=>Bt,fetch:()=>Kr});var Jr,Se,Kr,Bt,Wt,Vr,Yr,oe=Wr(()=>{"use strict";Jr=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")},Se=Jr(),Kr=Se.fetch,Bt=Se.fetch.bind(Se),Wt=Se.Headers,Vr=Se.Request,Yr=Se.Response});var Ps=K(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});var zt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Gt.default=zt});var Kt=K(Be=>{"use strict";var Os=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});var Qr=Os((oe(),Gr(ue))),Zr=Os(Ps()),Jt=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=Qr.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let u=null,l=null,h=null,d=n.status,y=n.statusText;if(n.ok){if(this.method!=="HEAD"){let w=await n.text();w===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=w:l=JSON.parse(w))}let m=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),f=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");m&&f&&f.length>1&&(h=parseInt(f[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,h=null,d=406,y="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let m=await n.text();try{u=JSON.parse(m),Array.isArray(u)&&n.status===404&&(l=[],u=null,d=200,y="OK")}catch{n.status===404&&m===""?(d=204,y="No Content"):u={message:m}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,d=200,y="OK"),u&&this.shouldThrowOnError)throw new Zr.default(u)}return{error:u,data:l,count:h,status:d,statusText:y}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};Be.default=Jt});var Yt=K(We=>{"use strict";var ei=We&&We.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(We,"__esModule",{value:!0});var ti=ei(Kt()),Vt=class extends ti.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};We.default=Vt});var wt=K(ze=>{"use strict";var si=ze&&ze.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ze,"__esModule",{value:!0});var ri=si(Yt()),Xt=class extends ri.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};ze.default=Xt});var Zt=K(Je=>{"use strict";var ii=Je&&Je.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Je,"__esModule",{value:!0});var Ge=ii(wt()),Qt=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new Ge.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new Ge.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new Ge.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new Ge.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 Ge.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Je.default=Qt});var Cs=K(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.version=void 0;vt.version="0.0.0-automated"});var Is=K(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.DEFAULT_HEADERS=void 0;var ni=Cs();bt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ni.version}`}});var js=K(Ke=>{"use strict";var Ls=Ke&&Ke.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ke,"__esModule",{value:!0});var oi=Ls(Zt()),ai=Ls(wt()),ci=Is(),es=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ci.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new oi.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,h])=>h!==void 0).map(([l,h])=>[l,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([l,h])=>{a.searchParams.append(l,h)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new ai.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Ke.default=es});var qs=K(D=>{"use strict";var Ve=D&&D.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(D,"__esModule",{value:!0});D.PostgrestBuilder=D.PostgrestTransformBuilder=D.PostgrestFilterBuilder=D.PostgrestQueryBuilder=D.PostgrestClient=void 0;var $s=Ve(js());D.PostgrestClient=$s.default;var Us=Ve(Zt());D.PostgrestQueryBuilder=Us.default;var Ds=Ve(wt());D.PostgrestFilterBuilder=Ds.default;var Ns=Ve(Yt());D.PostgrestTransformBuilder=Ns.default;var Ms=Ve(Kt());D.PostgrestBuilder=Ms.default;D.default={PostgrestClient:$s.default,PostgrestQueryBuilder:Us.default,PostgrestFilterBuilder:Ds.default,PostgrestTransformBuilder:Ns.default,PostgrestBuilder:Ms.default}});var Vs=K((Mn,Ks)=>{"use strict";Ks.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var L="https://api.wisprflow.ai";function qe(r,e){return typeof r.message=="string"&&r.message||typeof r.error=="string"&&r.error||typeof r.detail=="string"&&r.detail||`Request failed with status ${e}`}var Ht=class{static async signupUser(e){try{let t=`${L}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${L}/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(`${L}/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(`${L}/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(`${L}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${L}/user_status?email=${encodeURIComponent(e)}`)).json()}static async requestPasswordReset(e,t){let s=await fetch(`${L}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,captcha_token:t})});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(qe(i,s.status))}}static async signUpWithCaptcha(e){let t=await fetch(`${L}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(qe(s,t.status));return s}static async signInWithCaptcha(e){let t=await fetch(`${L}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(qe(s,t.status));return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${L}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(qe(s,t.status))}}static async signInWithEmail(e){let t=await fetch(`${L}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(qe(s,t.status));return s}static async getSubscriptionStatus(e){return await fetch(`${L}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${L}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let i=`${L}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(i+=`¤cy=${s}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${L}/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(`${L}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${L}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${L}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let i=new FormData;return i.append("screenshot",e),await fetch(`${L}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function xs(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function As(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var V=Ht;var Rs=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Fe=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},gt=class extends Fe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},mt=class extends Fe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},_t=class extends Fe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},yt;(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"})(yt||(yt={}));var Xr=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},He=class{constructor(e,{headers:t={},customFetch:s,region:i=yt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Rs(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Xr(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(k=>{throw new gt(k)}),h=l.headers.get("x-relay-error");if(h&&h==="true")throw new mt(l);if(!l.ok)throw new _t(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),y;return d==="application/json"?y=yield l.json():d==="application/octet-stream"?y=yield l.blob():d==="text/event-stream"?y=l:d==="multipart/form-data"?y=yield l.formData():y=yield l.text(),{data:y,error:null}}catch(i){return{data:null,error:i}}})}};var Fs=Ts(qs(),1),{PostgrestClient:Hs,PostgrestQueryBuilder:vn,PostgrestFilterBuilder:bn,PostgrestTransformBuilder:kn,PostgrestBuilder:Sn}=Fs.default;var Bs="2.10.2";var Ws={"X-Client-Info":`realtime-js/${Bs}`},zs="1.0.0",St=1e4,Gs=1e3,he;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(he||(he={}));var M;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(M||(M={}));var F;(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"})(F||(F={}));var kt;(function(r){r.websocket="websocket"})(kt||(kt={}));var ae;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(ae||(ae={}));var Ye=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var de=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var A;(function(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"})(A||(A={}));var ss=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=li(o,r,e,i),n),{})},li=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?Js(n,o):ts(o)},Js=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return fi(e,t)}switch(r){case A.bool:return ui(e);case A.float4:case A.float8:case A.int2:case A.int4:case A.int8:case A.numeric:case A.oid:return hi(e);case A.json:case A.jsonb:return di(e);case A.timestamp:return pi(e);case A.abstime:case A.date:case A.daterange:case A.int4range:case A.int8range:case A.money:case A.reltime:case A.text:case A.time:case A.timestamptz:case A.timetz:case A.tsrange:case A.tstzrange:return ts(e);default:return ts(e)}},ts=r=>r,ui=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},hi=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},di=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},fi=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n,o=r.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Js(e,a))}return r},pi=r=>typeof r=="string"?r.replace(" ","T"):r,Et=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var fe=class{constructor(e,t,s={},i=St){this.channel=e,this.event=t,this.payload=s,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var rs;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(rs||(rs={}));var Ee=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let h=n[u];if(h){let d=l.map(f=>f.presence_ref),y=h.map(f=>f.presence_ref),k=l.filter(f=>y.indexOf(f.presence_ref)<0),m=h.filter(f=>d.indexOf(f.presence_ref)<0);k.length>0&&(a[u]=k),m.length>0&&(c[u]=m)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let h=e[a].map(y=>y.presence_ref),d=l.filter(y=>h.indexOf(y.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(h=>h.presence_ref);u=u.filter(h=>l.indexOf(h.presence_ref)<0),e[a]=u,i(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var is;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(is||(is={}));var ns;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(ns||(ns={}));var os;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(os||(os={}));var Te=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=M.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 fe(this,F.join,this.params,this.timeout),this.rejoinTimer=new de(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=M.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=M.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=M.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=M.errored,this.rejoinTimer.scheduleTimeout())}),this._on(F.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Ee(this),this.broadcastEndpointURL=Et(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var h;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,y=(h=d?.length)!==null&&h!==void 0?h:0,k=[];for(let m=0;m<y;m++){let f=d[m],{filter:{event:w,schema:O,table:P,filter:C}}=f,x=l&&l[m];if(x&&x.event===w&&x.schema===O&&x.table===P&&x.filter===C)k.push(Object.assign(Object.assign({},f),{id:x.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=k,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=M.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(F.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new fe(this,F.leave,{},e);i.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let i=new AbortController,n=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new fe(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:u,join:l}=F;if(s&&[a,c,u,l].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(y=>{var k,m,f;return((k=y.filter)===null||k===void 0?void 0:k.event)==="*"||((f=(m=y.filter)===null||m===void 0?void 0:m.event)===null||f===void 0?void 0:f.toLocaleLowerCase())===o}).map(y=>y.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(y=>{var k,m,f,w,O,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in y){let C=y.id,x=(k=y.filter)===null||k===void 0?void 0:k.event;return C&&((m=t.ids)===null||m===void 0?void 0:m.includes(C))&&(x==="*"||x?.toLocaleLowerCase()===((f=t.data)===null||f===void 0?void 0:f.type.toLocaleLowerCase()))}else{let C=(O=(w=y?.filter)===null||w===void 0?void 0:w.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return C==="*"||C===((P=t?.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return y.type.toLocaleLowerCase()===o}).map(y=>{if(typeof d=="object"&&"ids"in d){let k=d.data,{schema:m,table:f,commit_timestamp:w,type:O,errors:P}=k;d=Object.assign(Object.assign({},{schema:m,table:f,commit_timestamp:w,eventType:O,new:{},old:{},errors:P}),this._getPayloadRecords(k))}y.callback(d,s)})}_isClosed(){return this.state===M.closed}_isJoined(){return this.state===M.joined}_isJoining(){return this.state===M.joining}_isLeaving(){return this.state===M.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(F.close,{},e)}_onError(e){this._on(F.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=M.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ss(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ss(e.columns,e.old_record)),t}};var mi=()=>{},_i=typeof WebSocket<"u",xe=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ws,this.params={},this.timeout=St,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=mi,this.conn=null,this.sendBuffer=[],this.serializer=new Ye,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${kt.websocket}`,this.httpEndpoint=Et(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(s=t?.params)===null||s===void 0?void 0:s.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new de(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(_i){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new as(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ts(Vs())).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 he.connecting:return ae.Connecting;case he.open:return ae.Open;case he.closing:return ae.Closing;default:return ae.Closed}}isConnected(){return this.connectionState()===ae.Open}channel(e,t={config:{}}){let s=new Te(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(F.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:zs}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(F.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Gs,"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=he.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var Ae=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function $(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Tt=class extends Ae{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Xe=class extends Ae{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var yi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},xt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Ys=()=>yi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(oe(),ue))).Response:Response});var Re=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},cs=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),wi=(r,e)=>Re(void 0,void 0,void 0,function*(){let t=yield Ys();r instanceof t?r.json().then(s=>{e(new Tt(cs(s),r.status||500))}).catch(s=>{e(new Xe(cs(s),s))}):e(new Xe(cs(r),r))}),vi=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};function At(r,e,t,s,i,n){return Re(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,vi(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>wi(c,a))})})}function Qe(r,e,t,s){return Re(this,void 0,void 0,function*(){return At(r,"GET",e,t,s)})}function Y(r,e,t,s,i){return Re(this,void 0,void 0,function*(){return At(r,"POST",e,s,i,t)})}function Xs(r,e,t,s,i){return Re(this,void 0,void 0,function*(){return At(r,"PUT",e,s,i,t)})}function Rt(r,e,t,s,i){return Re(this,void 0,void 0,function*(){return At(r,"DELETE",e,s,i,t)})}var H=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},bi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Qs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ze=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=xt(i)}uploadOrUpdate(e,t,s,i){return H(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Qs),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),h=yield l.json();return l.ok?{data:{path:c,id:h.Id,fullPath:h.Key},error:null}:{data:null,error:h}}catch(n){if($(n))return{data:null,error:n};throw n}})}upload(e,t,s){return H(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return H(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,u=Object.assign({upsert:Qs.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",u.cacheControl)):(c=s,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let h=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield h.json();return h.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if($(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return H(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield Y(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ae("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if($(s))return{data:null,error:s};throw s}})}update(e,t,s){return H(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return H(this,void 0,void 0,function*(){try{return{data:yield Y(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if($(i))return{data:null,error:i};throw i}})}copy(e,t,s){return H(this,void 0,void 0,function*(){try{return{data:{path:(yield Y(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if($(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return H(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield Y(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if($(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return H(this,void 0,void 0,function*(){try{let i=yield Y(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if($(i))return{data:null,error:i};throw i}})}download(e,t){return H(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Qe(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if($(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${u}`)}}}remove(e){return H(this,void 0,void 0,function*(){try{return{data:yield Rt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}list(e,t,s){return H(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},bi),t),{prefix:e||""});return{data:yield Y(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if($(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Zs="2.6.0";var er={"X-Client-Info":`storage-js/${Zs}`};var Pe=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},et=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},er),t),this.fetch=xt(s)}listBuckets(){return Pe(this,void 0,void 0,function*(){try{return{data:yield Qe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if($(e))return{data:null,error:e};throw e}})}getBucket(e){return Pe(this,void 0,void 0,function*(){try{return{data:yield Qe(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Pe(this,void 0,void 0,function*(){try{return{data:yield Y(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($(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Pe(this,void 0,void 0,function*(){try{return{data:yield Xs(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($(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Pe(this,void 0,void 0,function*(){try{return{data:yield Y(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Pe(this,void 0,void 0,function*(){try{return{data:yield Rt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}};var tt=class extends et{constructor(e,t={},s){super(e,t,s)}from(e){return new Ze(this.url,this.headers,e,this.fetch)}};var tr="2.44.4";var st="";typeof Deno<"u"?st="deno":typeof document<"u"?st="web":typeof navigator<"u"&&navigator.product==="ReactNative"?st="react-native":st="node";var ki={"X-Client-Info":`supabase-js-${st}/${tr}`},sr={headers:ki},rr={schema:"public"},ir={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},nr={};oe();var Si=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Ei=r=>{let e;return r?e=r:typeof fetch>"u"?e=Bt:e=fetch,(...t)=>e(...t)},Ti=()=>typeof Headers>"u"?Wt:Headers,or=(r,e,t)=>{let s=Ei(t),i=Ti();return(n,o)=>Si(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",r),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:u}))})};function ar(r){return r.replace(/\/$/,"")}function cr(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var Pt="2.64.4";var lr="http://localhost:9999",ur="supabase.auth.token";var hr={"X-Client-Info":`gotrue-js/${Pt}`},ls=10;var rt="X-Supabase-Api-Version",us={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function dr(r){return Math.round(Date.now()/1e3)+r}function fr(){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 B=()=>typeof document<"u",pe={tested:!1,writable:!1},ce=()=>{if(!B())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(pe.tested)return pe.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),pe.tested=!0,pe.writable=!0}catch{pe.tested=!0,pe.writable=!1}return pe.writable};function Ot(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var Ct=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(oe(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},pr=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",hs=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},nt=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},It=async(r,e)=>{await r.removeItem(e)};function xi(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,u,l=0;for(r=r.replace("-","+").replace("_","/");l<r.length;)o=e.indexOf(r.charAt(l++)),a=e.indexOf(r.charAt(l++)),c=e.indexOf(r.charAt(l++)),u=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var it=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};it.promiseConstructor=Promise;function ds(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(xi(s))}async function gr(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function mr(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await r(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Ai(r){return("0"+r.toString(16)).substr(-2)}function Ri(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,Ai).join("")}async function Pi(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Oi(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ci(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 Pi(r);return Oi(t)}async function ge(r,e,t=!1){let s=Ri(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await hs(r,`${e}-code-verifier`,i);let n=await Ci(s);return[n,s===n?"plain":"s256"]}var Ii=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function _r(r){let e=r.headers.get(rt);if(!e||!e.match(Ii))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ot=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function b(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Lt=class extends ot{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function yr(r){return b(r)&&r.name==="AuthApiError"}var Oe=class extends ot{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},se=class extends ot{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},X=class extends se{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ce=class extends se{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},me=class extends se{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},_e=class extends se{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}}},at=class extends se{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}}},Ie=class extends se{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function jt(r){return b(r)&&r.name==="AuthRetryableFetchError"}var ct=class extends se{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Li=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},ye=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),ji=[502,503,504];async function wr(r){var e;if(!pr(r))throw new Ie(ye(r),0);if(ji.includes(r.status))throw new Ie(ye(r),r.status);let t;try{t=await r.json()}catch(n){throw new Oe(ye(n),n)}let s,i=_r(r);if(i&&i.getTime()>=us["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 ct(ye(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new ct(ye(t),r.status,t.weak_password.reasons);throw new Lt(ye(t),r.status||500,s)}var $i=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function S(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[rt]||(n[rt]=us["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Ui(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Ui(r,e,t,s,i,n){let o=$i(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new Ie(ye(c),0)}if(a.ok||await wr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await wr(c)}}function re(r){var e;let t=null;Di(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=dr(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function fs(r){let e=re(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 Q(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function vr(r){return{data:r,error:null}}function br(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Li(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function kr(r){return r}function Di(r){return r.access_token&&r.refresh_token&&r.expires_in}var Ni=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},we=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Ct(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Q})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Ni(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:br,redirectTo:t?.redirectTo})}catch(t){if(b(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Q})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:kr});if(l.error)throw l.error;let h=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,y=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return y.length>0&&(y.forEach(k=>{let m=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),f=JSON.parse(k.split(";")[1].split("=")[1]);u[`${f}Page`]=m}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(b(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Q})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Q})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Q})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}};var Sr={getItem:r=>ce()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ce()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ce()&&globalThis.localStorage.removeItem(r)}};function ps(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Er(){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 ve={debug:!!(globalThis&&ce()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},lt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},$t=class extends lt{};async function gs(r,e,t){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),ve.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new $t(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(ve.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Er();var Mi={url:lr,storageKey:ur,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:hr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},ut=30*1e3,Tr=3;async function xr(r,e,t){return await t()}var be=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&&B()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},Mi),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new we({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Ct(i.fetch),this.lock=i.lock||xr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:B()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=gs:this.lock=xr,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:ce()?this.storage=Sr:(this.memoryStorage={},this.storage=ps(this.memoryStorage)):(this.memoryStorage={},this.storage=ps(this.memoryStorage)),B()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Pt}) ${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=B()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return b(e)?{error:e}:{error:new Oe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:re}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(b(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:l,password:h,options:d}=e,y=null,k=null;this.flowType==="pkce"&&([y,k]=await ge(this.storage,this.storageKey)),n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:h,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:y,code_challenge_method:k},xform:re})}else if("phone"in e){let{phone:l,password:h,options:d}=e;n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:h,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:re})}else throw new me("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(b(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:fs})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:fs})}else throw new me("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Ce}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await nt(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:re});return await It(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Ce}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:i,access_token:n,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:re}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Ce}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await ge(this.storage,this.storageKey));let{error:h}=await S(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:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:l}}throw new me("You must provide either an email or phone number.")}catch(a){if(b(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:re});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(b(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await ge(this.storage,this.storageKey)),await S(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:vr})}catch(n){if(b(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new X;let{error:i}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(b(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await S(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:i,options:n}=e,{data:o,error:a}=await S(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new me("You must provide either an email or phone number and a type")}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await nt(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,u,l)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Q}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new X}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:Q})})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new X;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await ge(this.storage,this.storageKey));let{data:u,error:l}=await S(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:Q});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return ds(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 X;let t=Date.now()/1e3,s=t,i=!0,n=null,o=ds(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(b(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 X;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!B())throw new _e("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new _e("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new at("Not a valid PKCE flow url.");let t=Ot(window.location.href);if(e){if(!t.code)throw new at("No code detected.");let{data:O,error:P}=await this._exchangeCodeForSession(t.code);if(P)throw P;let C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:O.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new _e(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:u}=t;if(!n||!a||!o||!u)throw new _e("No session defined in URL");let l=Math.round(Date.now()/1e3),h=parseInt(a),d=l+h;c&&(d=parseInt(c));let y=d-l;y*1e3<=ut&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${h}s`);let k=d-h;l-k>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",k,d,l):l-k<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",k,d,l);let{data:m,error:f}=await this._getUser(n);if(f)throw f;let w={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:u,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:w,redirectType:t.type},error:null}}catch(t){if(b(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Ot(window.location.href);return!!(B()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Ot(window.location.href),t=await nt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{error:n};let o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(yr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await It(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=fr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await ge(this.storage,this.storageKey,!0));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(b(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,u,l;let{data:h,error:d}=n;if(d)throw d;let y=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 S(this.fetch,"GET",y,{headers:this.headers,jwt:(l=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return B()&&!(!((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(b(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(b(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 mr(async i=>(i>0&&await gr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:re})),(i,n)=>{let o=200*Math.pow(2,i);return n&&jt(n)&&Date.now()+o-s<ut})}catch(s){if(this._debug(t,"error",s),b(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),B()&&!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 nt(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<i+ls;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${ls}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),jt(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 X;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new it;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new X;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),b(n)){let o={session:null,error:n};return jt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await hs(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await It(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&B()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),ut);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((s.expires_at*1e3-e)/ut);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${ut}ms, refresh threshold is ${Tr} ticks`),i<=Tr&&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 lt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!B()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await ge(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await S(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(b(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(b(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};be.nextInstanceID=0;var qi=be,ms=qi;var Ut=class extends ms{constructor(e){super(e)}};var Fi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},ht=class{constructor(e,t,s){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=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`,u={db:rr,realtime:nr,auth:Object.assign(Object.assign({},ir),{storageKey:c}),global:sr},l=cr(s??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=or(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Hs(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new He(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new tt(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 Fi(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,storageKey:n,flowType:o,debug:a},c,u){var l;let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ut({url:this.authUrl,headers:Object.assign(Object.assign({},h),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new xe(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 Ar=(r,e,t)=>new ht(r,e,t);var ie={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Hi=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Dt=r=>{let[e,t]=r.split(".");return!e||!t?null:Hi(t)},Le=r=>{let e=Dt(r);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Bi="https://api.workos.com",Wi=60,je=(r,e)=>typeof r[e]=="string"?r[e]:void 0,Rr=(r,e,t)=>{let s=Dt(r);if(!s)return null;let i=je(s,"urn:wispr:user_external_id")??je(s,"sub"),n=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:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},zi=async(r,e,t,s)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Bi,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:r,organization_id:s})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},Pr=async(r,e)=>{let t=Dt(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=je(t,"client_id");if(i-s<Wi&&n){let c=await zi(e,n,je(t,"iss"),je(t,"org_id")),u=Rr(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=s)throw new Error("WorkOS session expired");let a=Rr(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var $e=class{constructor(){this.sessionData=null;this.supabase=Ar(ie.supaBaseUrl,ie.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ie.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||ie.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||ie.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let i=new Date;i.setTime(i.getTime()+s*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{if(Le(t)==="workos"){this.sessionData=await Pr(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,i]=t.split("=");return e[s]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ie.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,i,n){try{if(!n)throw new Error("Please complete the verification");await V.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:n,redirect_url:i||ie.redirectUri}),console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await V.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:i?.provision??!1,workos_capable:i?.workosCapable});if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in successful for:",e),{accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,s){try{if(!s)throw new Error("Please complete the verification");await V.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||ie.redirectUri}),console.log("Verification email resent to:",e)}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 Z=null;function _s(r,e=30,t){Z&&(clearInterval(Z),Z=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,Z=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",Z&&(clearInterval(Z),Z=null),t&&t())},1e3)}function Or(){Z&&(clearInterval(Z),Z=null)}var Cr=/^[\p{L}\p{M}\s\-'.]+$/u;function Gi(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Cr.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 ys(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Cr.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 Ir(r,e,t){let s="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let u=document.getElementById(s);u||(u=document.createElement("div"),u.id=s,u.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",u)),u.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=Gi(e.value,r.value);c?i(c):n()},a=()=>{let c=ys(e.value,r.value);c?i(c):n()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var Ji="123456",Nt=null;function ws(){return new URLSearchParams(window.location.search).get("dev-mode")==="true"}var Mt=()=>{Nt!==null&&(window.clearInterval(Nt),Nt=null)};function vs(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),Mt()}function bs(r){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),s=document.querySelector("[otp-email]"),i=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),c=document.querySelector("[otp-resend-countdown]"),u=document.querySelector("[otp-resend-seconds]"),l=document.querySelector("[otp-reset]");t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),n&&(n.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents=""),Mt(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let h=m=>{n&&(n.style.display="block"),o&&(o.textContent=m)},d=()=>{n&&(n.style.display="none")},y=async()=>{let m=t.map(f=>f.value).join("");if(m.length!==6){h("Please enter all 6 digits.");return}m===Ji?(d(),i&&(i.textContent="Verified \u2705",i.style.pointerEvents="none"),t.forEach(f=>f.setAttribute("disabled","true")),await r.onVerifySuccess?.()):h("Incorrect or expired code. Try again.")};t.forEach((m,f)=>{m.oninput=()=>{m.value=m.value.replace(/\D/g,"").slice(0,1),m.value&&f<t.length-1&&t[f+1].focus(),d()},m.onkeydown=w=>{w.key==="Backspace"&&!m.value&&f>0?t[f-1].focus():w.key==="Enter"&&(w.preventDefault(),y())},m.onpaste=w=>{w.preventDefault();let O=(w.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((C,x)=>{t[x]&&(t[x].value=C)});let P=Math.min(O.length,t.length-1);t[P]?.focus(),d()}}),i&&(i.onclick=m=>{m.preventDefault(),y()});let k=()=>{let m=60;a&&(a.style.display="none"),c&&(c.style.display="block"),u&&(u.textContent=String(m)),Mt(),Nt=window.setInterval(()=>{m-=1,u&&(u.textContent=String(m)),m<=0&&(Mt(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async m=>{m.preventDefault(),t.forEach(f=>{f.value="",f.removeAttribute("disabled")}),t[0]?.focus(),d(),k(),await r.onResend?.()}),l&&(l.onclick=m=>{m.preventDefault(),vs(),r.onReset?.()})}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 Ki="wisprjam.com",Vi="wispr.ai",Yi=r=>r.trim().toLowerCase().split("@")[1]??"",ks=r=>{let e=Yi(r);return e===Ki||e===Vi};function Lr(r,e){let t=new $e,s="email_input",i=document.querySelector("#email-form"),n=document.querySelector("#email-input"),o=document.querySelector("#password-input"),a=document.querySelector("#full-name"),c=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),h=document.querySelector("[email-element]"),d=document.querySelector("[different-provider]"),y=document.querySelector("[different-provider-name]"),k=document.querySelector("[different-provider-reset]"),m=document.querySelector("[email-signup-success]"),f=document.querySelector("[email-signup-error]"),w=document.querySelector("[error-message]"),O=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),C=document.querySelector("[email-signup-reset]"),x=document.querySelector("[scim-div]"),le=document.querySelector("[scim-reset]"),N=document.querySelector("[forgot-password]"),ee=document.querySelector("[forgot-password-success]"),U=document.querySelector("[forgot-password-email]"),q=document.querySelector("[unverified-email]"),Ue=document.querySelector("[unverified-email-address]"),W=document.querySelector("[resend-verification-email]"),De=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(c&&c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(v){console.error("Error during Google sign-in:",v)}}),u&&u.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(v){console.error("Error during Apple sign-in:",v)}}),l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(v){console.error("Error during Microsoft sign-in:",v)}}));let z=()=>{d&&(d.style.display="none"),m&&(m.style.display="none"),f&&(f.style.display="none"),q&&(q.style.display="none"),x&&(x.style.display="none"),N&&(N.style.display="none"),ee&&(ee.style.display="none"),vs();let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="block"),h&&(h.style.display="flex"),n&&(n.value="",n.removeAttribute("readonly"),n.classList.remove("disabled")),o&&(o.value="",o.style.display="none",o.removeAttribute("required")),a&&(a.value="",a.style.display="none",a.removeAttribute("required"));let p=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");p&&(p.style.display="none"),g&&(g.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",n&&n.focus()},G=()=>{n&&(n.setAttribute("readonly","true"),n.classList.add("disabled")),o&&(o.style.display="block",o.setAttribute("required","true"),o.focus()),a&&(a.style.display="none",a.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),p=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),p&&(p.style.display="block"),N&&(N.style.display="block",N.onclick=async()=>{let g=n?.value||"",_=N.textContent||"";try{let{hcaptcha:E}=window;if(!E)throw new Error("Verification system not loaded. Please refresh the page.");N.style.pointerEvents="none",N.textContent="Sending...";let{response:T}=await E.execute({async:!0});if(!T)throw new Error("Verification cancelled");await V.requestPasswordReset(g,T),E.reset(),h&&(h.style.display="none"),N&&(N.style.display="none"),ee&&(ee.style.display="block"),U&&(U.textContent=g)}catch(E){console.error("Error sending password reset email:",E),N.textContent=_,N.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),f&&(f.style.display="block",w&&(w.textContent=E instanceof Error?E.message:"Failed to send reset email"))}}),s="login"},te=()=>{n&&(n.setAttribute("readonly","true"),n.classList.add("disabled")),o&&(o.style.display="block",o.setAttribute("required","true"),o.focus()),a&&(a.style.display="block",a.setAttribute("required","true"));let v=document.querySelector("[captcha-embed]"),p=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),p&&(p.style.display="block"),s="signup"},ne=()=>{let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="none"),x&&(x.style.display="block"),le&&(le.onclick=()=>{x&&(x.style.display="none"),v&&(v.style.display="block"),z()})},ke=v=>{let p=As(v);h&&(h.style.display="none"),d&&(d.style.display="block"),y&&(y.textContent=p),k&&(k.onclick=()=>{d&&(d.style.display="none"),z()}),s="oauth_user"},Ne=v=>{h&&(h.style.display="none"),q&&(q.style.display="block"),Ue&&(Ue.textContent=v),W&&(W.onclick=async()=>{if(ws()){q&&(q.style.display="none"),bs({email:v,onVerifySuccess:()=>{console.log("[dev-mode] OTP verified for",v)},onResend:()=>{console.log("[dev-mode] resend clicked for",v)},onReset:()=>{z()}});return}let p=W.textContent||"";try{let g=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(v,r,g),W.textContent="Verification email resent! \u2705",W.style.textDecoration="none"}catch(g){console.error("Error resending verification email:",g),W.textContent=p}}),De&&(De.onclick=()=>{q&&(q.style.display="none"),z()}),s="unverified_email"},qt=async(v,p)=>{let g=p.value;p.classList.add("loading"),p.value="";try{let _=await V.checkUserStatus(v);p.classList.remove("loading"),p.value=g,!_.exists&&_.scim_managed?ne():_.enforce_sso?ke("workos"):_.exists&&_.provider&&_.provider!=="email"?ke(_.provider):_.exists&&_.provider==="email"&&!_.verified?Ne(v):_.exists&&_.provider==="email"?G():te()}catch(_){console.error("Error checking user status:",_),p.classList.remove("loading"),p.value=g,te()}},dt=async(v,p,g,_)=>{if(!p||p.length<8){f&&(f.style.display="block",w&&(w.textContent="Password must be at least 8 characters"));return}let E=window.hcaptcha?.getResponse()||"";if(!E){f&&(f.style.display="block",w&&(w.textContent="Please complete the verification"));return}g.classList.add("loading"),g.value="";try{if(e?.mcpLoginState){let J=await V.signInWithEmail({email:v,password:p,mcp_login_state:e.mcpLoginState});if(!J.redirect_url)throw new Error(J.error||"Unable to continue connector login. Please try again.");R("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=J.redirect_url;return}let{accessToken:T,refreshToken:I,fullName:j}=await t.signInWithPassword(v,p,E,{workosCapable:ks(v),provision:!1});t.setCookies(T,I),localStorage.setItem("email",v),e?.onLoginSuccess?await e.onLoginSuccess(T,I,j):window.location.href=r}catch(T){if(console.error("Login error:",T),window.hcaptcha&&window.hcaptcha.reset(),g.classList.remove("loading"),g.value=_,f&&(f.style.display="block",w)){let I=T instanceof Error?T.message:"Invalid login credentials";w.textContent=I}}},Ft=async(v,p,g,_,E)=>{if(!p||p.length<8){f&&(f.style.display="block",w&&(w.textContent="Password must be at least 8 characters"));return}if(!g||g.trim().length<2){f&&(f.style.display="block",w&&(w.textContent="Please enter your full name"));return}let T=ys(g,p);if(T){f&&(f.style.display="block",w&&(w.textContent=T));return}let I=window.hcaptcha?.getResponse()||"";if(!I){f&&(f.style.display="block",w&&(w.textContent="Please complete the verification"));return}_.classList.add("loading"),_.value="";try{if(await t.signUpWithPassword(v,p,g,r,I),window.hcaptcha&&window.hcaptcha.reset(),_.classList.remove("loading"),_.value=E,h&&(h.style.display="none"),f&&(f.style.display="none"),ws()){bs({email:v,onVerifySuccess:()=>{console.log("[dev-mode] OTP verified for signup",v)},onResend:()=>{console.log("[dev-mode] resend clicked for signup",v)},onReset:()=>{z()}});return}m&&(m.style.display="block"),O&&(O.textContent=v),P&&(_s(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let j=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(v,r,j),window.hcaptcha&&window.hcaptcha.reset(),_s(P,30)}catch(j){console.error("Error resending verification email:",j)}}),C&&(C.onclick=()=>{m&&(m.style.display="none"),Or(),z()})}catch(j){if(console.error("Signup error:",j),_.classList.remove("loading"),_.value=E,f&&(f.style.display="block",w)){let J=j instanceof Error?j.message:"Signup failed";w.textContent=J}}};return i&&o&&a&&Ir(o,a,i.querySelector('[type="submit"]')),i&&i.addEventListener("submit",async v=>{v.stopPropagation(),v.preventDefault();let p=n?.value||"",g=o?.value||"",_=a?.value||"";if(!p||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){f&&(f.style.display="block",w&&(w.textContent="Please enter a valid email address"));return}f&&(f.style.display="none"),w&&(w.textContent="");let T=i.querySelector('[type="submit"]'),I=T?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await qt(p,T):s==="login"?await dt(p,g,T,I):s==="signup"&&await Ft(p,g,_,T,I)}catch(j){console.error("Auth flow error:",j),T&&(T.classList.remove("loading"),T.value=I),f&&(f.style.display="block")}}),{reset:z}}var Xi=/google ads|google adservices|adwords/i,Qi=/marketing|advertising/i,jr=r=>{let e=r.filter(s=>Xi.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=>Qi.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}}},Zi=async()=>{try{let{__ucCmp:r,UC_UI:e}=window;if(r?.getConsentDetails){let t=await r.getConsentDetails();return jr(Object.values(t?.services??{}).map(s=>({name:s?.name,category:s?.category,decision:s?.consent?.type==="EXPLICIT"&&typeof s.consent.given=="boolean"?s.consent.given:void 0})))}if(e?.getServicesBaseInfo)return jr((e.getServicesBaseInfo()??[]).map(t=>({name:t?.name,category:t?.categorySlug,decision:t?.consent?.history?.some(s=>s?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0})))}catch{}},$r=()=>{let r=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([Zi(),r])};function Ur(r){try{let e=r._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let s=t.split(".");if(s.length>=3){let i=s.slice(2).join(".");if(i)return i}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var Dr=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Ss="https://api.wisprflow.ai",Nr="https://wisprflow.ai",en="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new $e,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),s=document.querySelector("[error-div]"),i=document.querySelector("[error-message-api]"),n=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),u=c?.value??"",l=document.querySelector("#google-login"),h=document.querySelector("#apple-login"),d=document.querySelector("#microsoft-login"),y=localStorage.getItem("last_authed_provider");y&&{google:l,apple:h,microsoft:d,sso:document.querySelector("#sso-login"),email:document.querySelector("#email-input")}[y]?.classList.add("last-used");let k=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},m=()=>{let g=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";R("desktop_login_auto_launch",{deep_link:g}),window.location.href=g},f=()=>{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"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",m()},w=p=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),i&&(i.textContent=p),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},O=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},P=null,C=document.querySelector("[retry-button]");C&&C.addEventListener("click",()=>x());let x=()=>{e&&(e.style.display="none"),a&&(a.style.display="none"),n&&(n.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=u),P&&P()},le=async(p,g)=>{try{let[_,E]=xs(g||" "),T=V.signupUser({access_token:p,first_name:_,last_name:E}),I=new Promise((j,J)=>setTimeout(()=>J(new Error("signup timeout")),4e3));await Promise.race([T,I])}catch(_){R("signup_sync_error",{error_message:_ instanceof Error?_.message:String(_)})}},N=()=>{let p=sessionStorage.getItem("wispr_fbclid");return p?`fb.1.${Date.now()}.${p}`:null},ee=async(p,g)=>{let _=sessionStorage.getItem("wispr_device_code");if(!_)throw new Error("Device code not found. Please restart authentication from desktop app.");let E=Dr(),T=await $r(),I=localStorage.getItem("wf_utm_source")||void 0,j=localStorage.getItem("wf_utm_medium")||void 0,J=localStorage.getItem("wf_utm_campaign")||void 0,Me=await fetch(`${Ss}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${p}`},body:JSON.stringify({device_code:_,access_token:p,refresh_token:g,fbp:E._fbp||void 0,fbc:E._fbc||N()||void 0,gclid:Ur(E),utm:I||j||J?{utm_source:I,utm_medium:j,utm_campaign:J}:void 0,ad_user_data:T?.ad_user_data,ad_personalization:T?.ad_personalization})});if(!Me.ok){let ft=await Me.json().catch(()=>({}));throw Me.status===403&&ft?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(ft?.detail?.message||ft.message||`Server error: ${Me.status}`)}console.log("Device authentication complete:",await Me.json()),sessionStorage.removeItem("wispr_device_code"),Le(p)==="workos"&&r.setCookie("refresh_token",g,30/86400)},U=new URLSearchParams(window.location.search),q=U.get("device_code"),Ue=U.get("workos_capable");Ue==="true"?sessionStorage.setItem("wispr_workos_capable","true"):Ue==="false"&&sessionStorage.removeItem("wispr_workos_capable");let W=sessionStorage.getItem("wispr_workos_capable")==="true",De=U.get("auto_signin")==="true",z=new URLSearchParams(window.location.hash.slice(1)),G=U.get("access_token")||z.get("access_token"),te=U.get("refresh_token")||z.get("refresh_token"),ne=U.get("mcp_login_state");if(!q&&!G&&!te&&!ne&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),R("desktop_login_no_device_code"),window.location.href="/get-started";return}if(R("desktop_login_page_view",{auto_signin:De,workos_capable:W}),q){sessionStorage.setItem("wispr_device_code",q),console.log("Device code stored:",q);let p=U.get("fbclid");p&&sessionStorage.setItem("wispr_fbclid",p);let g=U.get("skip_default_trial"),_=U.get("grant_weekly_bonus");g&&sessionStorage.setItem("wispr_skip_default_trial",g),_&&sessionStorage.setItem("wispr_grant_weekly_bonus",_),window.history.replaceState({},"","/login")}let ke="wispr_workos_second_hop_attempted";if(G&&te){console.log("OAuth callback detected - handling tokens");let p=Le(G);if(R("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:p}),k(),p==="workos"){sessionStorage.removeItem(ke);try{r.setCookies(G,te);let g=U.get("email");g&&localStorage.setItem("email",g);let _=U.get("user_id");_&&localStorage.setItem("user_id",_),await le(G,U.get("name")??void 0),await ee(G,te),R("desktop_login_complete_success",{method:"oauth",provider:"workos"}),f()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),O();return}let _=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"oauth",provider:"workos",error:_}),console.error("Error completing WorkOS device authentication:",g),w(_)}return}try{let g=G,_=te;try{r.setCookies(G,te),await r.checkAndSetSession(),r.sessionData&&(g=r.sessionData.access_token,_=r.sessionData.refresh_token,r.setCookies(g,_),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}let E=r.sessionData?.user.email;if(E&&ks(E)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(ke)){sessionStorage.setItem(ke,"true"),R("desktop_login_workos_second_hop",{email_domain:E.split("@")[1]??"unknown"}),window.location.href=`${Ss}/authkit/google/sign_in?source=${Nr}`;return}await le(g,r.sessionData?.user.user_metadata?.full_name),await ee(g,_),R("desktop_login_complete_success",{method:"oauth"}),f()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),O();return}let _=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"oauth",error:_}),console.error("Error completing device authentication:",g),w(_)}return}if(De){console.log("Auto-signin enabled - checking existing session"),k();try{let p=r.checkAndSetSession(),g=new Promise((_,E)=>setTimeout(()=>E(new Error("Session timeout")),3e3));if(await Promise.race([p,g]),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 le(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await ee(r.sessionData.access_token,r.sessionData.refresh_token),R("desktop_login_auto_signin_success",{token_provider:Le(r.sessionData.access_token)}),f();return}console.log("No existing session - showing login form"),R("desktop_login_auto_signin_no_session"),x()}catch(p){if(console.error("Auto-signin error:",p),p instanceof Error&&p.message==="enterprise_ip_not_allowed"){R("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),O();return}let g=p instanceof Error?p.message:"Auto-signin failed. Please try logging in manually.";R("desktop_login_auto_signin_error",{error:g}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),x()}}else ne?(R("desktop_login_mcp_entry"),x()):(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"),x());let Ne=p=>{console.log(`Redirecting to ${p} OAuth`);let g=window.posthog?.getFeatureFlag?.(en)===!0,_=p==="google"&&W&&g;R("desktop_login_oauth_click",{provider:_?"workos":p,idp:p,mcp:!!ne,workos_capable:W,workos_enabled_webflow:g}),localStorage.setItem("signin_provider",p);let E=_?"authkit/google/sign_in":`${p}/sign_in`,T=`${Ss}/${E}?source=${Nr}`,I=sessionStorage.getItem("wispr_skip_default_trial"),j=sessionStorage.getItem("wispr_grant_weekly_bonus");I&&(T+=`&skip_default_trial=${encodeURIComponent(I)}`),j&&(T+=`&grant_weekly_bonus=${encodeURIComponent(j)}`),ne&&(T+=`&mcp_login_state=${encodeURIComponent(ne)}`),window.location.href=T};l&&l.addEventListener("click",()=>{Ne("google")}),h&&h.addEventListener("click",()=>{Ne("apple")}),d&&d.addEventListener("click",()=>{Ne("microsoft")});let qt=async(p,g,_)=>{try{await le(p,_),await ee(p,g)}catch(E){if(E instanceof Error&&E.message==="enterprise_ip_not_allowed"){R("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),O();return}let T=E instanceof Error?E.message:"Failed to complete authentication. Please try again.";R("desktop_login_complete_error",{method:"email",error:T}),w(T);return}R("desktop_login_complete_success",{method:"email"}),f()},dt=sessionStorage.getItem("wispr_device_code"),Ft=dt?`${window.location.origin}/login?device_code=${dt}`:`${window.location.origin}/login`,{reset:v}=Lr(Ft,{onLoginSuccess:qt,mcpLoginState:ne,skipOAuthButtons:!0});P=v,console.log("Desktop login page initialized")});})();
|