@tanay-wispr/webflow-package 6.5.18 → 6.6.0
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/downloads.js +1 -1
- package/dist/global.js +2 -2
- package/dist/login.js +1 -1
- package/dist/pricing.js +1 -1
- package/dist/signup.js +1 -1
- package/package.json +1 -1
package/dist/androidWaitlist.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var pi=Object.create;var Lt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var wi=(i,e)=>()=>(i&&(e=i(i=0)),e);var Q=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),vi=(i,e)=>{for(var t in e)Lt(i,t,{get:e[t],enumerable:!0})},Hs=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gi(e))!yi.call(i,r)&&r!==t&&Lt(i,r,{get:()=>e[r],enumerable:!(s=mi(e,r))||s.enumerable});return i};var Vs=(i,e,t)=>(t=i!=null?pi(_i(i)):{},Hs(e||!i||!i.__esModule?Lt(t,"default",{value:i,enumerable:!0}):t,i)),bi=i=>Hs(Lt({},"__esModule",{value:!0}),i);var ye={};vi(ye,{Headers:()=>os,Request:()=>Ei,Response:()=>Ti,default:()=>ns,fetch:()=>Si});var ki,Ie,Si,ns,os,Ei,Ti,de=wi(()=>{"use strict";ki=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")},Ie=ki(),Si=Ie.fetch,ns=Ie.fetch.bind(Ie),os=Ie.Headers,Ei=Ie.Request,Ti=Ie.Response});var Ys=Q(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var as=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ls.default=as});var ds=Q(Xe=>{"use strict";var Xs=Xe&&Xe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Xe,"__esModule",{value:!0});var Ai=Xs((de(),bi(ye))),Li=Xs(Ys()),cs=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=Ai.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,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let d=null,c=null,u=null,f=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=k:c=JSON.parse(k))}let w=(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("/");w&&p&&p.length>1&&(u=parseInt(p[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(d={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,u=null,f=406,m="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{let w=await n.text();try{d=JSON.parse(w),Array.isArray(d)&&n.status===404&&(c=[],d=null,f=200,m="OK")}catch{n.status===404&&w===""?(f=204,m="No Content"):d={message:w}}if(d&&this.isMaybeSingle&&(!((l=d?.details)===null||l===void 0)&&l.includes("0 rows"))&&(d=null,f=200,m="OK"),d&&this.shouldThrowOnError)throw new Li.default(d)}return{error:d,data:c,count:u,status:f,statusText:m}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,l;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:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}};Xe.default=cs});var hs=Q(Qe=>{"use strict";var Ri=Qe&&Qe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Qe,"__esModule",{value:!0});var Pi=Ri(ds()),us=class extends Pi.default{select(e){let t=!1,s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).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:r,referencedTable:n=r}={}){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 r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.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:r=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),d=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${d}"; options=${l};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Qe.default=us});var It=Q(Ze=>{"use strict";var Ci=Ze&&Ze.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ze,"__esModule",{value:!0});var Oi=Ci(hs()),fs=class extends Oi.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(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).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:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="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 r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};Ze.default=fs});var ms=Q(tt=>{"use strict";var Ii=tt&&tt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(tt,"__esModule",{value:!0});var et=Ii(It()),ps=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new et.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r="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,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new et.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,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),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((d,c)=>d.concat(Object.keys(c)),[]);if(l.length>0){let d=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",d.join(","))}}return new et.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new et.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new et.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};tt.default=ps});var Qs=Q(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.version=void 0;jt.version="0.0.0-automated"});var Zs=Q($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.DEFAULT_HEADERS=void 0;var ji=Qs();$t.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ji.version}`}});var tr=Q(st=>{"use strict";var er=st&&st.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(st,"__esModule",{value:!0});var $i=er(ms()),Ui=er(It()),Mi=Zs(),gs=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Mi.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new $i.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([c,u])=>u!==void 0).map(([c,u])=>[c,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([c,u])=>{a.searchParams.append(c,u)})):(o="POST",l=t);let d=Object.assign({},this.headers);return n&&(d.Prefer=`count=${n}`),new Ui.default({method:o,url:a,headers:d,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};st.default=gs});var ar=Q(N=>{"use strict";var rt=N&&N.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(N,"__esModule",{value:!0});N.PostgrestBuilder=N.PostgrestTransformBuilder=N.PostgrestFilterBuilder=N.PostgrestQueryBuilder=N.PostgrestClient=void 0;var sr=rt(tr());N.PostgrestClient=sr.default;var rr=rt(ms());N.PostgrestQueryBuilder=rr.default;var ir=rt(It());N.PostgrestFilterBuilder=ir.default;var nr=rt(hs());N.PostgrestTransformBuilder=nr.default;var or=rt(ds());N.PostgrestBuilder=or.default;N.default={PostgrestClient:sr.default,PostgrestQueryBuilder:rr.default,PostgrestFilterBuilder:ir.default,PostgrestTransformBuilder:nr.default,PostgrestBuilder:or.default}});var gr=Q((lo,mr)=>{"use strict";mr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var D="https://api.wisprflow.ai",is=class{static async signupUser(e){try{let t=`${D}/signup`,r=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=r&&r.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(`${D}/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(`${D}/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(`${D}/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(`${D}/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(`${D}/user_status?email=${encodeURIComponent(e)}`)).json()}static async getSubscriptionStatus(e){return await fetch(`${D}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${D}/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 r=`${D}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`¤cy=${s}`),await(await fetch(r,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${D}/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(`${D}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${D}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${D}/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 r=new FormData;return r.append("screenshot",e),await fetch(`${D}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:r,signal:s})}};function Bs(i){let[e,...t]=i.split(" "),s=t.join(" ");return[e,s]}function Ws(i){return i==="azure"?"Microsoft":i==="workos"?"SSO":i.charAt(0).toUpperCase()+i.slice(1)}var B=is;var Gs=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var zs=()=>{let i=window.location.hash.substring(1),e=new URLSearchParams(i);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var Js=()=>{let{access_token:i,refresh_token:e}=zs(),t=i,s=e;if(!t||!s){let r=Gs();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var Ks=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(de(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Ke=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Rt=class extends Ke{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Pt=class extends Ke{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ct=class extends Ke{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ot;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(Ot||(Ot={}));var xi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Ye=class{constructor(e,{headers:t={},customFetch:s,region:r=Ot.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Ks(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return xi(this,void 0,void 0,function*(){try{let{headers:r,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let d;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",d=o):typeof o=="string"?(a["Content-Type"]="text/plain",d=o):typeof FormData<"u"&&o instanceof FormData?d=o:(a["Content-Type"]="application/json",d=JSON.stringify(o)));let c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:d}).catch(_=>{throw new Rt(_)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new Pt(c);if(!c.ok)throw new Ct(c);let f=((s=c.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),m;return f==="application/json"?m=yield c.json():f==="application/octet-stream"?m=yield c.blob():f==="text/event-stream"?m=c:f==="multipart/form-data"?m=yield c.formData():m=yield c.text(),{data:m,error:null}}catch(r){return{data:null,error:r}}})}};var lr=Vs(ar(),1),{PostgrestClient:cr,PostgrestQueryBuilder:Vn,PostgrestFilterBuilder:Bn,PostgrestTransformBuilder:Wn,PostgrestBuilder:Gn}=lr.default;var dr="2.10.2";var ur={"X-Client-Info":`realtime-js/${dr}`},hr="1.0.0",Mt=1e4,fr=1e3,we;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(we||(we={}));var F;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(F||(F={}));var W;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(W||(W={}));var Ut;(function(i){i.websocket="websocket"})(Ut||(Ut={}));var ue;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(ue||(ue={}));var it=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+r));o=o+r;let l=s.decode(e.slice(o,o+n));o=o+n;let d=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:d}}};var ve=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var A;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(A||(A={}));var ys=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ni(o,i,e,r),n),{})},Ni=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?pr(n,o):_s(o)},pr=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return Hi(e,t)}switch(i){case A.bool:return qi(e);case A.float4:case A.float8:case A.int2:case A.int4:case A.int8:case A.numeric:case A.oid:return Di(e);case A.json:case A.jsonb:return Fi(e);case A.timestamp:return Vi(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 _s(e);default:return _s(e)}},_s=i=>i,qi=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Di=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Fi=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Hi=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>pr(e,a))}return i},Vi=i=>typeof i=="string"?i.replace(" ","T"):i,Nt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var be=class{constructor(e,t,s={},r=Mt){this.channel=e,this.event=t,this.payload=s,this.timeout=r,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 ws;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(ws||(ws={}));var je=class i{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,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,r,n,o),this.pendingDiffs.forEach(l=>{this.state=i.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=i.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(d,c)=>{o[d]||(l[d]=c)}),this.map(o,(d,c)=>{let u=n[d];if(u){let f=c.map(p=>p.presence_ref),m=u.map(p=>p.presence_ref),_=c.filter(p=>m.indexOf(p.presence_ref)<0),w=u.filter(p=>f.indexOf(p.presence_ref)<0);_.length>0&&(a[d]=_),w.length>0&&(l[d]=w)}else a[d]=c}),this.syncDiff(n,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,l)=>{var d;let c=(d=e[a])!==null&&d!==void 0?d:[];if(e[a]=this.cloneDeep(l),c.length>0){let u=e[a].map(m=>m.presence_ref),f=c.filter(m=>u.indexOf(m.presence_ref)<0);e[a].unshift(...f)}s(a,c,l)}),this.map(o,(a,l)=>{let d=e[a];if(!d)return;let c=l.map(u=>u.presence_ref);d=d.filter(u=>c.indexOf(u.presence_ref)<0),e[a]=d,r(a,d,l),d.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 r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,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 vs;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(vs||(vs={}));var bs;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(bs||(bs={}));var ks;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(ks||(ks={}));var $e=class i{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 be(this,W.join,this.params,this.timeout),this.rejoinTimer=new ve(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=F.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.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(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this._on(W.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new je(this),this.broadcastEndpointURL=Nt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,r;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(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},d={broadcast:n,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(c=>c.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:d},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:c})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),c===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,m=(u=f?.length)!==null&&u!==void 0?u:0,_=[];for(let w=0;w<m;w++){let p=f[w],{filter:{event:k,schema:U,table:P,filter:C}}=p,L=c&&c[w];if(L&&L.event===k&&L.schema===U&&L.table===P&&L.filter===C)_.push(Object.assign(Object.assign({},p),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).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,r;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 l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=l.body)===null||r===void 0?void 0:r.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let d=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),d.receive("ok",()=>n("ok")),d.receive("error",()=>n("error")),d.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=F.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(W.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new be(this,W.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.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 r=new be(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:d,join:c}=W;if(s&&[a,l,d,c].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)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(m=>{var _,w,p;return((_=m.filter)===null||_===void 0?void 0:_.event)==="*"||((p=(w=m.filter)===null||w===void 0?void 0:w.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(m=>m.callback(f,s)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var _,w,p,k,U,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let C=m.id,L=(_=m.filter)===null||_===void 0?void 0:_.event;return C&&((w=t.ids)===null||w===void 0?void 0:w.includes(C))&&(L==="*"||L?.toLocaleLowerCase()===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{let C=(U=(k=m?.filter)===null||k===void 0?void 0:k.event)===null||U===void 0?void 0:U.toLocaleLowerCase();return C==="*"||C===((P=t?.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof f=="object"&&"ids"in f){let _=f.data,{schema:w,table:p,commit_timestamp:k,type:U,errors:P}=_;f=Object.assign(Object.assign({},{schema:w,table:p,commit_timestamp:k,eventType:U,new:{},old:{},errors:P}),this._getPayloadRecords(_))}m.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 r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&i.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(W.close,{},e)}_onError(e){this._on(W.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=F.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ys(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ys(e.columns,e.old_record)),t}};var Wi=()=>{},Gi=typeof WebSocket<"u",Ue=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ur,this.params={},this.timeout=Mt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Wi,this.conn=null,this.sendBuffer=[],this.serializer=new it,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(de(),ye)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Ut.websocket}`,this.httpEndpoint=Nt(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 r=(s=t?.params)===null||s===void 0?void 0:s.apikey;r&&(this.accessToken=r,this.apiKey=r),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 ve(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Gi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Ss(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Vs(gr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case we.connecting:return ue.Connecting;case we.open:return ue.Open;case we.closing:return ue.Closing;default:return ue.Closed}}isConnected(){return this.connectionState()===ue.Open}channel(e,t={config:{}}){let s=new $e(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(W.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:hr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||r===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(W.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(fr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Ss=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=we.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var Me=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function $(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var qt=class extends Me{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},nt=class extends Me{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var zi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Dt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(de(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},_r=()=>zi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(de(),ye))).Response:Response});var Ne=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Es=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Ji=(i,e)=>Ne(void 0,void 0,void 0,function*(){let t=yield _r();i instanceof t?i.json().then(s=>{e(new qt(Es(s),i.status||500))}).catch(s=>{e(new nt(Es(s),s))}):e(new nt(Es(i),i))}),Ki=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};function Ft(i,e,t,s,r,n){return Ne(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Ki(e,s,r,n)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Ji(l,a))})})}function ot(i,e,t,s){return Ne(this,void 0,void 0,function*(){return Ft(i,"GET",e,t,s)})}function Z(i,e,t,s,r){return Ne(this,void 0,void 0,function*(){return Ft(i,"POST",e,s,r,t)})}function yr(i,e,t,s,r){return Ne(this,void 0,void 0,function*(){return Ft(i,"PUT",e,s,r,t)})}function Ht(i,e,t,s,r){return Ne(this,void 0,void 0,function*(){return Ft(i,"DELETE",e,s,r,t)})}var G=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Yi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},wr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},at=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Dt(r)}uploadOrUpdate(e,t,s,r){return G(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},wr),r),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 l=this._removeEmptyFolders(t),d=this._getFinalPath(l),c=yield this.fetch(`${this.url}/object/${d}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield c.json();return c.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if($(n))return{data:null,error:n};throw n}})}upload(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return G(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l,d=Object.assign({upsert:wr.upsert},r),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",d.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",d.cacheControl)):(l=s,c["cache-control"]=`max-age=${d.cacheControl}`,c["content-type"]=d.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),f=yield u.json();return u.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(l){if($(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return G(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");let n=yield Z(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Me("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 G(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}copy(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:{path:(yield Z(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return G(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield Z(this.fetch,`${this.url}/object/sign/${r}`,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(r){if($(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return G(this,void 0,void 0,function*(){try{let r=yield Z(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}download(e,t){return G(this,void 0,void 0,function*(){let r=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield ot(this.fetch,`${this.url}/${r}/${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),r=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&r.push(l);let d=r.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${d}`)}}}remove(e){return G(this,void 0,void 0,function*(){try{return{data:yield Ht(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 G(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},Yi),t),{prefix:e||""});return{data:yield Z(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var vr="2.6.0";var br={"X-Client-Info":`storage-js/${vr}`};var qe=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},lt=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},br),t),this.fetch=Dt(s)}listBuckets(){return qe(this,void 0,void 0,function*(){try{return{data:yield ot(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if($(e))return{data:null,error:e};throw e}})}getBucket(e){return qe(this,void 0,void 0,function*(){try{return{data:yield ot(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return qe(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if($(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return qe(this,void 0,void 0,function*(){try{return{data:yield yr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if($(s))return{data:null,error:s};throw s}})}emptyBucket(e){return qe(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}deleteBucket(e){return qe(this,void 0,void 0,function*(){try{return{data:yield Ht(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}};var ct=class extends lt{constructor(e,t={},s){super(e,t,s)}from(e){return new at(this.url,this.headers,e,this.fetch)}};var kr="2.44.4";var dt="";typeof Deno<"u"?dt="deno":typeof document<"u"?dt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?dt="react-native":dt="node";var Xi={"X-Client-Info":`supabase-js-${dt}/${kr}`},Sr={headers:Xi},Er={schema:"public"},Tr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},xr={};de();var Qi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Zi=i=>{let e;return i?e=i:typeof fetch>"u"?e=ns:e=fetch,(...t)=>e(...t)},en=()=>typeof Headers>"u"?os:Headers,Ar=(i,e,t)=>{let s=Zi(t),r=en();return(n,o)=>Qi(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:i,d=new r(o?.headers);return d.has("apikey")||d.set("apikey",i),d.has("Authorization")||d.set("Authorization",`Bearer ${l}`),s(n,Object.assign(Object.assign({},o),{headers:d}))})};function Lr(i){return i.replace(/\/$/,"")}function Rr(i,e){let{db:t,auth:s,realtime:r,global:n}=i,{db:o,auth:a,realtime:l,global:d}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},l),r),global:Object.assign(Object.assign({},d),n)}}var Vt="2.64.4";var Pr="http://localhost:9999",Cr="supabase.auth.token";var Or={"X-Client-Info":`gotrue-js/${Vt}`},Ts=10;var ut="X-Supabase-Api-Version",xs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ir(i){return Math.round(Date.now()/1e3)+i}function jr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}var z=()=>typeof document<"u",ke={tested:!1,writable:!1},he=()=>{if(!z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ke.tested)return ke.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),ke.tested=!0,ke.writable=!0}catch{ke.tested=!0,ke.writable=!1}return ke.writable};function Bt(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}var Wt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(de(),ye)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},$r=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",As=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},ft=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Gt=async(i,e)=>{await i.removeItem(e)};function tn(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,r,n,o,a,l,d,c=0;for(i=i.replace("-","+").replace("_","/");c<i.length;)o=e.indexOf(i.charAt(c++)),a=e.indexOf(i.charAt(c++)),l=e.indexOf(i.charAt(c++)),d=e.indexOf(i.charAt(c++)),s=o<<2|a>>4,r=(a&15)<<4|l>>2,n=(l&3)<<6|d,t=t+String.fromCharCode(s),l!=64&&r!=0&&(t=t+String.fromCharCode(r)),d!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var ht=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ht.promiseConstructor=Promise;function Ls(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.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(tn(s))}async function Ur(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Mr(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function sn(i){return("0"+i.toString(16)).substr(-2)}function rn(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,sn).join("")}async function nn(i){let t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}function on(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function an(i){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."),i;let t=await nn(i);return on(t)}async function Se(i,e,t=!1){let s=rn(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await As(i,`${e}-code-verifier`,r);let n=await an(s);return[n,s===n?"plain":"s256"]}var ln=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Nr(i){let e=i.headers.get(ut);if(!e||!e.match(ln))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var pt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function b(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var zt=class extends pt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function qr(i){return b(i)&&i.name==="AuthApiError"}var De=class extends pt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},oe=class extends pt{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},ee=class extends oe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Fe=class extends oe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ee=class extends oe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Te=class extends oe{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}}},mt=class extends oe{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}}},He=class extends oe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Jt(i){return b(i)&&i.name==="AuthRetryableFetchError"}var gt=class extends oe{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var cn=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},xe=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),dn=[502,503,504];async function Dr(i){var e;if(!$r(i))throw new He(xe(i),0);if(dn.includes(i.status))throw new He(xe(i),i.status);let t;try{t=await i.json()}catch(n){throw new De(xe(n),n)}let s,r=Nr(i);if(r&&r.getTime()>=xs["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 gt(xe(t),i.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 gt(xe(t),i.status,t.weak_password.reasons);throw new zt(xe(t),i.status||500,s)}var un=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function E(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[ut]||(n[ut]=xs["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await hn(i,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function hn(i,e,t,s,r,n){let o=un(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new He(xe(l),0)}if(a.ok||await Dr(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await Dr(l)}}function ae(i){var e;let t=null;fn(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Ir(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function Rs(i){let e=ae(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function te(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function Fr(i){return{data:i,error:null}}function Hr(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=cn(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Vr(i){return i}function fn(i){return i.access_token&&i.refresh_token&&i.expires_in}var pn=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},Ae=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Wt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:te})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=pn(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:Hr,redirectTo:t?.redirectTo})}catch(t){if(b(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:te})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,l;try{let d={nextPage:null,lastPage:0,total:0},c=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:Vr});if(c.error)throw c.error;let u=await c.json(),f=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(_=>{let w=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(_.split(";")[1].split("=")[1]);d[`${p}Page`]=w}),d.total=parseInt(f)),{data:Object.assign(Object.assign({},u),d),error:null}}catch(d){if(b(d))return{data:{users:[]},error:d};throw d}}async getUserById(e){try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:te})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:te})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:te})}catch(s){if(b(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},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 E(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:i=>he()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{he()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{he()&&globalThis.localStorage.removeItem(i)}};function Ps(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function Wr(){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 Le={debug:!!(globalThis&&he()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},_t=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Kt=class extends _t{};async function Cs(i,e,t){Le.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Le.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){Le.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{Le.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw Le.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new Kt(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(Le.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()}})}Wr();var mn={url:Pr,storageKey:Cr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Or,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},yt=30*1e3,Gr=3;async function zr(i,e,t){return await t()}var Re=class i{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=i.nextInstanceID,i.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 r=Object.assign(Object.assign({},mn),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new Ae({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=Wt(r.fetch),this.lock=r.lock||zr,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:z()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Cs:this.lock=zr,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?r.storage?this.storage=r.storage:he()?this.storage=Br:(this.memoryStorage={},this.storage=Ps(this.memoryStorage)):(this.memoryStorage={},this.storage=Ps(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} (${Vt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=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:r,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",n),await this._saveSession(r),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return b(e)?{error:e}:{error:new De("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:ae}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(n){if(b(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){let{email:c,password:u,options:f}=e,m=null,_=null;this.flowType==="pkce"&&([m,_]=await Se(this.storage,this.storageKey)),n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:u,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:_},xform:ae})}else if("phone"in e){let{phone:c,password:u,options:f}=e;n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(r=f?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ae})}else throw new Ee("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 l=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:d,session:l},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 E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Rs})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Rs})}else throw new Ee("You must provide either an email or phone number and a password");let{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Fe}:(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:r})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,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:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await ft(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ae});return await Gt(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 Fe}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ae}),{data:l,error:d}=a;return d?{data:{user:null,session:null},error:d}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Fe}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:d})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){let{email:a,options:l}=e,d=null,c=null;this.flowType==="pkce"&&([d,c]=await Se(this.storage,this.storageKey));let{error:u}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:d,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:d,error:c}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:d?.message_id},error:c}}throw new Ee("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 r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:ae});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,d=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(r){if(b(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Se(this.storage,this.storageKey)),await E(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.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:Fr})}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 ee;let{error:r}=await E(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}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:r,options:n}=e,{error:o}=await E(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,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:r,options:n}=e,{data:o,error:a}=await E(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Ee("You must provide either an email or phone number and a type")}catch(t){if(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(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}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 r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await ft(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,d,c)=>(!o&&d==="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(l,d,c))})}return{data:{session:e},error:null}}let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:te}):await this._useSession(async t=>{var s,r,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ee}:await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:te})})}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:r,error:n}=s;if(n)throw n;if(!r.session)throw new ee;let o=r.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Se(this.storage,this.storageKey));let{data:d,error:c}=await E(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:te});if(c)throw c;return o.user=d.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 Ls(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ee;let t=Date.now()/1e3,s=t,r=!0,n=null,o=Ls(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;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 ee;let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},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 Te("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Te("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new mt("Not a valid PKCE flow url.");let t=Bt(window.location.href);if(e){if(!t.code)throw new mt("No code detected.");let{data:U,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:U.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Te(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:d}=t;if(!n||!a||!o||!d)throw new Te("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),f=c+u;l&&(f=parseInt(l));let m=f-c;m*1e3<=yt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${u}s`);let _=f-u;c-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,f,c):c-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,f,c);let{data:w,error:p}=await this._getUser(n);if(p)throw p;let k={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:u,expires_at:f,refresh_token:o,token_type:d,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:t.type},error:null}}catch(t){if(b(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Bt(window.location.href);return!!(z()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Bt(window.location.href),t=await ft(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{error:n};let o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(qr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Gt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=jr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;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((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await Se(this.storage,this.storageKey,!0));try{return await E(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,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:r}=await this._useSession(async n=>{var o,a,l,d,c;let{data:u,error:f}=n;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await E(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(d=u.session)===null||d===void 0?void 0:d.access_token)!==null&&c!==void 0?c:void 0})});if(r)throw r;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,r;let{data:n,error:o}=t;if(o)throw o;return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r: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 r=>(r>0&&await Ur(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ae})),(r,n)=>{let o=200*Math.pow(2,r);return n&&Jt(n)&&Date.now()+o-s<yt})}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 ft(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let r=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<r+Ts;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Ts}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 ee;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new ht;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new ee;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"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(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"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(l){n.push(l)}});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(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await As(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Gt(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(),yt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let r=Math.floor((s.expires_at*1e3-e)/yt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${yt}ms, refresh threshold is ${Gr} ticks`),r<=Gr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof _t)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 r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await Se(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.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,r;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await E(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return l?{data:null,error:l}:(!((r=a?.totp)===null||r===void 0)&&r.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:r,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.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:r,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=r?.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||[],r=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(r.access_token),a=null;o.aal&&(a=o.aal);let l=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};Re.nextInstanceID=0;var gn=Re,Os=gn;var Yt=class extends Os{constructor(e){super(e)}};var _n=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},wt=class{constructor(e,t,s){var r,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=Lr(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,d={db:Er,realtime:xr,auth:Object.assign(Object.assign({},Tr),{storageKey:l}),global:Sr},c=Rr(s??{},d);this.storageKey=(r=c.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Ar(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new cr(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Ye(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ct(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 _n(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:r,storageKey:n,flowType:o,debug:a},l,d){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Yt({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,debug:a,fetch:d,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new Ue(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Jr=(i,e,t)=>new wt(i,e,t);var le={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Ve=class{constructor(){this.sessionData=null;this.supabase=Jr(le.supaBaseUrl,le.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||le.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||le.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||le.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:r}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(r)throw r;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 r=new Date;r.setTime(r.getTime()+s*24*60*60*1e3);let n=`expires=${r.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{await this.setSession(t,s)}catch(r){throw r}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,r]=t.split("=");return e[s]=r,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||le.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,r,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:r||le.redirectUri,data:{full_name:s},captchaToken:n}});if(o)throw o;console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s){try{let{data:r,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:s}});if(n)throw n;if(!r.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:r.session.access_token,refreshToken:r.session.refresh_token,fullName:r.session.user.user_metadata?.full_name||void 0}}catch(r){throw console.error("Error signing in with password:",r),r}}async resendVerificationEmail(e,t,s){try{let{error:r}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||le.redirectUri,captchaToken:s}});if(r)throw r;console.log("Verification email resent to:",e)}catch(r){throw console.error("Error resending verification email:",r),r}}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 se=null;function Is(i,e=30,t){se&&(clearInterval(se),se=null);let s=e;i.style.pointerEvents="none",i.textContent=`Resend (${s}s)`,se=setInterval(()=>{s=s-1,i.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(i.style.pointerEvents="auto",se&&(clearInterval(se),se=null),t&&t())},1e3)}function Kr(){se&&(clearInterval(se),se=null)}function Yr(i,e){let t=new Ve,s="email_input",r=document.querySelector("#email-form"),n=document.querySelector("#email-input"),o=document.querySelector("#password-input"),a=document.querySelector("#full-name"),l=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),c=document.querySelector("#microsoft-login"),u=document.querySelector("[email-element]"),f=document.querySelector("[different-provider]"),m=document.querySelector("[different-provider-name]"),_=document.querySelector("[different-provider-reset]"),w=document.querySelector("[email-signup-success]"),p=document.querySelector("[email-signup-error]"),k=document.querySelector("[error-message]"),U=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),C=document.querySelector("[email-signup-reset]"),L=document.querySelector("[scim-div]"),fe=document.querySelector("[scim-reset]"),J=document.querySelector("[unverified-email]"),pe=document.querySelector("[unverified-email-address]"),K=document.querySelector("[resend-verification-email]"),Be=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(i)}catch(v){console.error("Error during Google sign-in:",v)}}),d&&d.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(i)}catch(v){console.error("Error during Apple sign-in:",v)}}),c&&c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(i)}catch(v){console.error("Error during Microsoft sign-in:",v)}}));let me=()=>{f&&(f.style.display="none"),w&&(w.style.display="none"),p&&(p.style.display="none"),J&&(J.style.display="none"),L&&(L.style.display="none");let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="block"),u&&(u.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 S=document.querySelector("[captcha-embed]"),x=document.querySelector("#h-captcha-container");S&&(S.style.display="none"),x&&(x.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",n&&n.focus()},vt=()=>{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]"),S=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),S&&(S.style.display="block"),s="login"},We=()=>{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]"),S=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),S&&(S.style.display="block"),s="signup"},bt=()=>{let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="none"),L&&(L.style.display="block"),fe&&(fe.onclick=()=>{L&&(L.style.display="none"),v&&(v.style.display="block"),me()})},ge=v=>{let S=Ws(v);u&&(u.style.display="none"),f&&(f.style.display="block"),m&&(m.textContent=S),_&&(_.onclick=()=>{f&&(f.style.display="none"),me()}),s="oauth_user"},_e=v=>{u&&(u.style.display="none"),J&&(J.style.display="block"),pe&&(pe.textContent=v),K&&(K.onclick=async()=>{let S=K.textContent||"";try{let x=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(v,i,x),K.textContent="Verification email resent! \u2705",K.style.textDecoration="none"}catch(x){console.error("Error resending verification email:",x),K.textContent=S}}),Be&&(Be.onclick=()=>{J&&(J.style.display="none"),me()}),s="unverified_email"},kt=async(v,S)=>{let x=S.value;S.classList.add("loading"),S.value="";try{let T=await B.checkUserStatus(v);S.classList.remove("loading"),S.value=x,!T.exists&&T.scim_managed?bt():T.enforce_sso?ge("workos"):T.exists&&T.provider&&T.provider!=="email"?ge(T.provider):T.exists&&T.provider==="email"&&!T.verified?_e(v):T.exists&&T.provider==="email"?vt():We()}catch(T){console.error("Error checking user status:",T),S.classList.remove("loading"),S.value=x,We()}},St=async(v,S,x,T)=>{if(!S||S.length<8){p&&(p.style.display="block",k&&(k.textContent="Password must be at least 8 characters"));return}let Y=window.hcaptcha?.getResponse()||"";if(!Y){p&&(p.style.display="block",k&&(k.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{let{accessToken:O,refreshToken:I,fullName:re}=await t.signInWithPassword(v,S,Y);t.setCookies(O,I),localStorage.setItem("email",v),e?.onLoginSuccess?await e.onLoginSuccess(O,I,re):window.location.href=i}catch(O){if(console.error("Login error:",O),window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=T,p&&(p.style.display="block",k)){let I=O instanceof Error?O.message:"Invalid login credentials";k.textContent=I}}},Et=async(v,S,x,T,Y)=>{if(!S||S.length<8){p&&(p.style.display="block",k&&(k.textContent="Password must be at least 8 characters"));return}if(!x||x.trim().length<2){p&&(p.style.display="block",k&&(k.textContent="Please enter your full name"));return}let O=window.hcaptcha?.getResponse()||"";if(!O){p&&(p.style.display="block",k&&(k.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{await t.signUpWithPassword(v,S,x,i,O),window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=Y,u&&(u.style.display="none"),p&&(p.style.display="none"),w&&(w.style.display="block"),U&&(U.textContent=v),P&&(Is(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let I=window.hcaptcha?.getResponse()||"";await t.signUpWithPassword(v,S,x,i,I),window.hcaptcha&&window.hcaptcha.reset(),Is(P,30)}catch(I){console.error("Error resending verification email:",I)}}),C&&(C.onclick=()=>{w&&(w.style.display="none"),Kr(),me()})}catch(I){if(console.error("Signup error:",I),T.classList.remove("loading"),T.value=Y,p&&(p.style.display="block",k)){let re=I instanceof Error?I.message:"Signup failed";k.textContent=re}}};r&&r.addEventListener("submit",async v=>{v.stopPropagation(),v.preventDefault();let S=n?.value||"",x=o?.value||"",T=a?.value||"";if(!S||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S)){p&&(p.style.display="block",k&&(k.textContent="Please enter a valid email address"));return}p&&(p.style.display="none"),k&&(k.textContent="");let O=r.querySelector('[type="submit"]'),I=O?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await kt(S,O):s==="login"?await St(S,x,O,I):s==="signup"&&await Et(S,x,T,O,I)}catch(re){console.error("Auth flow error:",re),O&&(O.classList.remove("loading"),O.value=I),p&&(p.style.display="block")}})}var Xt=function(){return Xt=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++)for(var r in e=arguments[t])Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r]);return i},Xt.apply(this,arguments)},Xr=function(){function i(e,t,s){var r=this;this.endVal=t,this.options=s,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){r.startTime||(r.startTime=n);var o=n-r.startTime;r.remaining=r.duration-o,r.useEasing?r.countDown?r.frameVal=r.startVal-r.easingFn(o,0,r.startVal-r.endVal,r.duration):r.frameVal=r.easingFn(o,r.startVal,r.endVal-r.startVal,r.duration):r.frameVal=r.startVal+(r.endVal-r.startVal)*(o/r.duration);var a=r.countDown?r.frameVal<r.endVal:r.frameVal>r.endVal;r.frameVal=a?r.endVal:r.frameVal,r.frameVal=Number(r.frameVal.toFixed(r.options.decimalPlaces)),r.printValue(r.frameVal),o<r.duration?r.rAF=requestAnimationFrame(r.count):r.finalEndVal!==null?r.update(r.finalEndVal):r.options.onCompleteCallback&&r.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,d,c=n<0?"-":"";o=Math.abs(n).toFixed(r.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?r.options.decimal+u[1]:"",r.options.useGrouping){d="";for(var f=3,m=0,_=0,w=a.length;_<w;++_)r.options.useIndianSeparators&&_===4&&(f=2,m=1),_!==0&&m%f==0&&(d=r.options.separator+d),m++,d=a[w-_-1]+d;a=d}return r.options.numerals&&r.options.numerals.length&&(a=a.replace(/[0-9]/g,function(p){return r.options.numerals[+p]}),l=l.replace(/[0-9]/g,function(p){return r.options.numerals[+p]})),c+r.options.prefix+a+l+r.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=Xt(Xt({},this.defaults),s),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return r.handleScroll(r)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,s=e.el.getBoundingClientRect(),r=s.top+window.pageYOffset,n=s.top+s.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||r>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var s=this.countDown?1:-1;this.endVal=e+s*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var s=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,s):this.el.tagName==="INPUT"?this.el.value=s:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=s:this.el.innerHTML=s}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,' ])/g,"\\$1")},s=t(this.options.separator),r=t(this.options.decimal),n=e.replace(new RegExp(s,"g"),"").replace(new RegExp(r,"g"),".");return parseFloat(n)},i}();var Qr=!1;function Zr(){if(Qr)return;Qr=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(s=>{if(s.isIntersecting){let r=s.target;e.unobserve(r);let n=r.dataset.countDirection||"up",o=parseFloat(r.dataset.countOffset||"10")/100,a=parseFloat(r.dataset.countDuration||"2"),l=5,d=r.dataset.countTarget||r.textContent?.trim()||"0",c=parseFloat(d.replace(/,/g,""));if(isNaN(c))return;let u=c*o,f=Math.max(u,l),m=n==="down"?c+f:Math.max(0,c-f);new Xr(r,c,{startVal:Math.round(m),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var ei=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var R=(i,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:i,retry_attempt:10-t}),window.posthog.capture(i,e)):t>0&&setTimeout(()=>R(i,e,t-1),200)},ti=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};async function yn(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new Ve,{accessToken:t,refreshToken:s}=Js(),r=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),d=document.querySelector("[error-div]"),c=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),f=document.querySelector("[spots]"),m=document.querySelectorAll("[referral-code]"),_=document.querySelector("[referral-count]"),w=document.querySelector("[desktop-bonus-remaining]"),p=document.querySelector("[desktop-bonus-complete]"),k=document.querySelector("[climbed-dropped]"),U=document.querySelector("[keep-moving]"),P=document.querySelector("[rank-arrow-wrap]"),C=document.querySelector("[cohort-text]"),L=document.querySelector("[top-100]"),fe=document.querySelector("[top-1000]"),J=document.querySelector("[top-100k]"),pe=document.querySelector("[sms-bonus-remaining]"),K=document.querySelector("[sms-bonus-complete]"),Be=document.querySelector("[total-boost]"),me=document.querySelector("[social-media-details]"),vt=document.querySelector("[sms-popup-button]"),We=document.querySelector("[app-download]"),bt=document.querySelector("[file-upload]"),ge=document.querySelector("[file-input]"),_e=document.querySelector("[file-validation-error]"),kt=document.querySelector("[file-upload-loading]"),St=document.querySelector("[cancel-upload-button]"),Et=document.querySelector("[file-upload-verified]"),v=document.querySelector("[boost-earned]"),S=document.querySelector("[boost-earned-location]"),x=document.querySelector("[woohoo-button]"),T=document.querySelector("[file-upload-failed]"),Y=document.querySelector("[upload-failed-text]"),O=document.querySelector("[close-button]"),I=document.querySelector("[share-on-x]"),re=document.querySelector("[share-on-linkedin]"),Qt=document.querySelector("[share-on-whatsapp]"),Zt=document.querySelector("[share-on-slack]"),es=document.querySelector("[share-on-discord]"),js=document.querySelector("[social-media-bonus-remaining]"),$s=document.querySelector("[social-media-bonus-complete]"),Us=document.querySelector("[share-on-other-channel]");me&&me.addEventListener("click",()=>{R("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),vt&&vt.addEventListener("click",()=>{R("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),We&&We.addEventListener("click",()=>{window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_app_download",source:"android-waitlist-page"}),R("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let Ms=async()=>{clearTimeout(i),document.body.style.visibility="visible",o.forEach(xt=>{xt.style.display="none"}),n&&(n.style.display="block");let Pe=window.__abVariantPromise?await window.__abVariantPromise:"control",Ce=document.querySelector("[auth-hero-default]"),H=document.querySelector("[auth-hero-v1]"),X=document.querySelector("[auth-hero-v2]");Ce&&(Ce.style.display="none"),H&&(H.style.display="none"),X&&(X.style.display="none"),Pe==="dictation-broken"&&H?H.style.display="block":Pe==="smartest"&&X?X.style.display="block":Ce&&(Ce.style.display="block"),n&&(n.style.display="none"),r&&(r.style.display="block");let Tt=document.querySelector("[reusable-section-wrap]");Tt&&r&&r.appendChild(Tt);let Ge=document.querySelector(".wl_cohort-spot-wrap");Ge&&(Ge.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),R("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),Yr(`${window.location.origin}/android-waitlist`)};if(!t||!s){await Ms();return}try{e.setCookies(t,s);let Pe=e.checkAndSetSession(),Ce=new Promise((h,y)=>setTimeout(()=>y(new Error("Session timeout")),3e3));await Promise.race([Pe,Ce]),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(i),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(h=>{h.style.display="flex",h.dataset.bound||(h.dataset.bound="true",h.addEventListener("click",async y=>{y.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let H=e.sessionData?.access_token,X=e.sessionData?.user.email,Tt=e.sessionData?.user.user_metadata.full_name||" ",[Ge,xt]=Bs(Tt),ze=e.sessionData?.user.id;localStorage.setItem("email",X),ze&&localStorage.setItem("user_id",ze),ze&&ti(ze,{email:X,firstName:Ge,lastName:xt});let si=ei(),{dub_id:ts,referral:ss,promo_code:Ns}=si,ri=!!localStorage.getItem("conversion_sent"),Oe=!localStorage.getItem("android_waitlist_joined"),j={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},ii={access_token:H,first_name:Ge,last_name:xt,dub_click_id:ts||void 0,referral:ss||void 0,promo_code:Ns||void 0};try{await B.signupUser(ii),j.signup.success=!0}catch(h){j.signup.success=!1,j.signup.error=h instanceof Error?h.message:"Unknown error"}try{let h=await B.ensureReferralCode(H);if(j.referral.success=h.ok,!h.ok){let y=await h.json().catch(()=>({}));j.referral.error=y.detail||y.message||`Status ${h.status}`}}catch(h){j.referral.success=!1,j.referral.error=h instanceof Error?h.message:"Network error"}ri||(R("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:ts||void 0,referral:ss||void 0,email:X,user_id:ze||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"));let ni={email:X,device_type:"android"},qs=!1;try{await B.addToWaitlist(ni),j.waitlist.success=!0,qs=!0}catch(h){j.waitlist.success=!1,j.waitlist.error=h instanceof Error?h.message:"Unknown error"}Oe&&qs&&(localStorage.setItem("android_waitlist_joined","true"),R("app_waitlist",{device_type:"android",source:"android-waitlist-page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:"android",source:"android-waitlist-page"}));let V=await B.getAndroidWaitlistStats(H);if(V.status===404&&!Oe){R("android_waitlist_recovery_attempted",{reason:"localStorage flag set but 404 from stats API"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_attempted",reason:"localStorage flag set but 404 from stats API"}),localStorage.removeItem("android_waitlist_joined");try{let h={email:X,device_type:"android"};await B.addToWaitlist(h),localStorage.setItem("android_waitlist_joined","true"),V=await B.getAndroidWaitlistStats(H),V.ok&&(R("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(h){console.error("Recovery addToWaitlist failed:",h)}}let oi=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if(j.stats.success=V.ok,V.status===401||V.status===429||!V.ok){let h="";try{let y=await V.json();h=JSON.stringify(y),j.stats.error=y.detail||y.message||h,c&&(c.textContent=`Status: ${V.status} | ${h}`)}catch{h="Could not parse response",j.stats.error=h,c&&(c.textContent=`Status: ${V.status} | ${h}`)}R("android_waitlist_api_error",{status:V.status,error:h,signup_success:j.signup.success,signup_error:j.signup.error,referral_success:j.referral.success,referral_error:j.referral.error,waitlist_success:j.waitlist.success,waitlist_error:j.waitlist.error,stats_error:j.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:V.status,error:h}),a&&(a.style.display="none"),d&&(d.style.display="block");return}let M=await V.json();if(Oe){let h=await yn(X);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:M.current_rank,user_email_hash:h})}let Ds=localStorage.getItem("android_waitlist_last_rank");if(Ds&&!Oe){let h=parseInt(Ds,10);M.current_rank<h&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:M.current_rank,positions_gained:h-M.current_rank,referral_count:M.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",M.current_rank.toString());let rs=h=>{let y=h.current_rank;if(u){let g=y.toLocaleString("en-US");u.textContent=g,u instanceof HTMLElement&&(u.dataset.countTarget=g)}if(h.starting_rank!==null){let g=h.starting_rank-y;f&&(f.textContent=Math.abs(g).toLocaleString()),g<0?(k&&(k.textContent="fell"),U&&(U.style.display="none"),P&&P.classList.add("invert")):(k&&(k.textContent="climbed"),U&&(U.style.display="inline-block"),P&&P.classList.remove("invert"))}if(L&&L.classList.remove("active"),fe&&fe.classList.remove("active"),J&&J.classList.remove("active"),y<=100?L&&L.classList.add("active"):y<=1e3?fe&&fe.classList.add("active"):y<=1e5&&J&&J.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(g=>{g.style.display="none"}),y<=100){let g=document.querySelector('[cohort-wins="top-100"]');g&&(g.style.display="block")}else if(y<=1e3){let g=document.querySelector('[cohort-wins="top-1000"]');g&&(g.style.display="block")}else if(y<=1e5){let g=document.querySelector('[cohort-wins="top-100k"]');g&&(g.style.display="block")}if(C)if(y<=100)C.innerHTML="You're in the <strong>top 100!</strong>";else if(y<=1e3){let g=y-100;C.innerHTML=`<strong>Only ${g.toLocaleString()} spots</strong> to top 100`}else if(y<=1e5){let g=y-1e3;C.innerHTML=`<strong>Only ${g.toLocaleString()} spots</strong> to top 1,000`}else{let g=y-1e5;C.innerHTML=`<strong>Only ${g.toLocaleString()} spots</strong> to top 100,000`}m.forEach(g=>{g.textContent=h.referral_code}),_&&(_.textContent=h.referrals_count.toString()),h.desktop_dictation_bonus_earned?(w&&(w.style.display="none"),p&&(p.style.display="block")):(w&&(w.style.display="block"),p&&(p.style.display="none")),h.phone_number_bonus_earned?(pe&&(pe.style.display="none"),K&&(K.style.display="block")):(pe&&(pe.style.display="block"),K&&(K.style.display="none")),h.verified_share_twitter&&I&&I.classList.add("verified"),h.verified_share_linkedin&&re&&re.classList.add("verified"),h.verified_share_whatsapp&&Qt&&Qt.classList.add("verified"),h.verified_share_slack&&Zt&&Zt.classList.add("verified"),h.verified_share_discord&&es&&es.classList.add("verified");let q=h.verified_share_twitter&&h.verified_share_linkedin&&h.verified_share_whatsapp&&h.verified_share_slack&&h.verified_share_discord;if(q&&(js&&(js.style.display="none"),$s&&($s.style.display="block")),Be){let g=[h.phone_number_bonus_earned,h.desktop_dictation_bonus_earned,q].filter(Boolean).length;Be.textContent=`${g} of 3`}};rs(M);let Fs=h=>h<=100?"top-100":h<=1e3?"top-1000":h<=1e5?"top-100k":"below-100k";R("android_waitlist_page_view",{rank:M.current_rank,total_boost:M.total_boost,referrals_count:M.referrals_count,cohort:Fs(M.current_rank),is_first_visit:Oe}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:M.current_rank,total_boost:M.total_boost,referrals_count:M.referrals_count,cohort:Fs(M.current_rank),is_first_visit:Oe});let ai=`https://wisprflow.ai/waitlist?${M.referral_code}`;document.querySelectorAll("[share]").forEach(h=>{let y=h.getAttribute("share");if(!y)return;let g=document.querySelector(`[share-content="${y}"]`)?.textContent||"";h.addEventListener("click",async()=>{switch(R("android_waitlist_share_clicked",{platform:y}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:y}),y){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(g)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(g),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(ai)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(g)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(g),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(g),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async h=>{let y=h,{phoneNumber:q}=y.detail;try{let g=await B.submitPhoneNumber(q,H),ie=await g.json();if(!g.ok||!ie.success){let At=ie.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:At}})),R("android_waitlist_sms_error",{error:At}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:At});return}window.dispatchEvent(new CustomEvent("sms:success"));let ne=await B.getAndroidWaitlistStats(H);ne.ok&&rs(await ne.json()),R("android_waitlist_sms_submitted",{boost_earned:ie.boost_earned,new_rank:ie.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:ie.boost_earned,new_rank:ie.current_rank})}catch(g){console.error("SMS submission error:",g),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}})),R("android_waitlist_sms_error",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:"network_error"})}});let ce=h=>{bt&&(bt.style.display=h==="idle"?"block":"none"),kt&&(kt.style.display=h==="loading"?"block":"none"),Et&&(Et.style.display=h==="verified"?"block":"none"),T&&(T.style.display=h==="failed"?"block":"none"),_e&&(_e.style.display="none")},li=h=>{let q=["image/png","image/jpeg","image/jpg"];return h.size>20971520?"File too large. Maximum size is 20MB.":q.includes(h.type)?null:"Please upload a PNG or JPEG image."},ci={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},di=h=>ci[h]||"Social Media",ui={social_share_x:I,social_share_linkedin:re,social_share_whatsapp:Qt,social_share_slack:Zt,social_share_discord:es},hi=h=>{let y=ui[h];y&&y.classList.add("verified")},fi=h=>({file_too_large:"File exceeds 20MB limit. (file_too_large)",invalid_file_type:"Please upload a PNG or JPEG. (invalid_file_type)","User not on Android waitlist":"Please join the waitlist first. (User not on Android waitlist)",all_platforms_already_claimed:"You've claimed all social share bonuses! (all_platforms_already_claimed)",x_already_claimed:"You've already received the X bonus. (x_already_claimed)",linkedin_already_claimed:"You've already received the LinkedIn bonus. (linkedin_already_claimed)",whatsapp_already_claimed:"You've already received the WhatsApp bonus. (whatsapp_already_claimed)",slack_already_claimed:"You've already received the Slack bonus. (slack_already_claimed)",discord_already_claimed:"You've already received the Discord bonus. (discord_already_claimed)",not_posted:"This looks like a draft, not a published post. (not_posted)",no_wispr_mention:"Post must mention Wispr Flow or wisprflow.ai. (no_wispr_mention)",invalid:"We couldn't verify this screenshot. Try a clearer image. (invalid)","An error occurred":"Something went wrong. Please try again. (An error occurred)"})[h??""]??`Verification failed. (${h})`,Je=null;ge&&ge.addEventListener("change",async()=>{let h=ge.files?.[0];if(!h)return;ge.value="";let y=li(h);if(y){_e&&(_e.textContent=y,_e.style.display="block"),R("android_waitlist_social_validation_error",{error:y}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:y});return}R("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),ce("loading"),Je=new AbortController;try{let q=await B.submitSocialShare(h,H,Je.signal),g=await q.json();if(!q.ok||!g.success){ce("failed"),Y&&(Y.textContent=fi(g.error)),R("android_waitlist_social_upload_failed",{error:g.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:g.error});return}ce("verified"),v&&(v.textContent=g.boost_earned.toLocaleString()),S&&(S.textContent=di(g.action)),hi(g.action);let ie=await B.getAndroidWaitlistStats(H);if(ie.ok){let ne=await ie.json();rs(ne),ne.verified_share_twitter&&ne.verified_share_linkedin&&ne.verified_share_whatsapp&&ne.verified_share_slack&&ne.verified_share_discord&&(x&&(x.style.display="none"),Us&&(Us.style.display="none"),R("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}R("android_waitlist_social_share_verified",{platform:g.action,boost_earned:g.boost_earned,new_rank:g.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:g.action,boost_earned:g.boost_earned,new_rank:g.current_rank})}catch(q){if(q instanceof Error&&q.name==="AbortError"){ce("idle");return}console.error("Social share upload error:",q),ce("failed"),Y&&(Y.textContent="Network error. Please try again."),R("android_waitlist_social_upload_failed",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:"network_error"})}finally{Je=null}}),St&&St.addEventListener("click",()=>{Je&&Je.abort(),ce("idle"),R("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),x&&x.addEventListener("click",()=>{ce("idle")}),O&&O.addEventListener("click",()=>{ce("idle")}),oi(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Zr()}catch(Pe){console.error("Error on android-waitlist page:",Pe),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await Ms()}});})();
|
|
1
|
+
"use strict";(()=>{var pi=Object.create;var Ct=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var wi=(i,e)=>()=>(i&&(e=i(i=0)),e);var X=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),vi=(i,e)=>{for(var t in e)Ct(i,t,{get:e[t],enumerable:!0})},Hs=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gi(e))!yi.call(i,r)&&r!==t&&Ct(i,r,{get:()=>e[r],enumerable:!(s=mi(e,r))||s.enumerable});return i};var Vs=(i,e,t)=>(t=i!=null?pi(_i(i)):{},Hs(e||!i||!i.__esModule?Ct(t,"default",{value:i,enumerable:!0}):t,i)),bi=i=>Hs(Ct({},"__esModule",{value:!0}),i);var we={};vi(we,{Headers:()=>os,Request:()=>Ei,Response:()=>Ti,default:()=>ns,fetch:()=>Si});var ki,Ue,Si,ns,os,Ei,Ti,fe=wi(()=>{"use strict";ki=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},Ue=ki(),Si=Ue.fetch,ns=Ue.fetch.bind(Ue),os=Ue.Headers,Ei=Ue.Request,Ti=Ue.Response});var Ys=X(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var as=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ls.default=as});var ds=X(tt=>{"use strict";var Xs=tt&&tt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(tt,"__esModule",{value:!0});var Ai=Xs((fe(),bi(we))),Li=Xs(Ys()),cs=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=Ai.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,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let d=null,c=null,u=null,f=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let v=await n.text();v===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=v:c=JSON.parse(v))}let w=(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("/");w&&p&&p.length>1&&(u=parseInt(p[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(d={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,u=null,f=406,m="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{let w=await n.text();try{d=JSON.parse(w),Array.isArray(d)&&n.status===404&&(c=[],d=null,f=200,m="OK")}catch{n.status===404&&w===""?(f=204,m="No Content"):d={message:w}}if(d&&this.isMaybeSingle&&(!((l=d?.details)===null||l===void 0)&&l.includes("0 rows"))&&(d=null,f=200,m="OK"),d&&this.shouldThrowOnError)throw new Li.default(d)}return{error:d,data:c,count:u,status:f,statusText:m}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,l;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:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}};tt.default=cs});var hs=X(st=>{"use strict";var Pi=st&&st.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(st,"__esModule",{value:!0});var Ri=Pi(ds()),us=class extends Ri.default{select(e){let t=!1,s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).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:r,referencedTable:n=r}={}){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 r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.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:r=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),d=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${d}"; options=${l};`,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}};st.default=us});var Ut=X(rt=>{"use strict";var Ci=rt&&rt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(rt,"__esModule",{value:!0});var Oi=Ci(hs()),fs=class extends Oi.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(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).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:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="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 r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};rt.default=fs});var ms=X(nt=>{"use strict";var Ii=nt&&nt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(nt,"__esModule",{value:!0});var it=Ii(Ut()),ps=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=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 it.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r="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,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new it.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,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),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((d,c)=>d.concat(Object.keys(c)),[]);if(l.length>0){let d=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",d.join(","))}}return new it.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new it.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new it.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};nt.default=ps});var Qs=X(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.version=void 0;Mt.version="0.0.0-automated"});var Zs=X(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.DEFAULT_HEADERS=void 0;var ji=Qs();Nt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ji.version}`}});var tr=X(ot=>{"use strict";var er=ot&&ot.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ot,"__esModule",{value:!0});var $i=er(ms()),Ui=er(Ut()),Mi=Zs(),gs=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Mi.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new $i.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([c,u])=>u!==void 0).map(([c,u])=>[c,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([c,u])=>{a.searchParams.append(c,u)})):(o="POST",l=t);let d=Object.assign({},this.headers);return n&&(d.Prefer=`count=${n}`),new Ui.default({method:o,url:a,headers:d,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};ot.default=gs});var ar=X(F=>{"use strict";var at=F&&F.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(F,"__esModule",{value:!0});F.PostgrestBuilder=F.PostgrestTransformBuilder=F.PostgrestFilterBuilder=F.PostgrestQueryBuilder=F.PostgrestClient=void 0;var sr=at(tr());F.PostgrestClient=sr.default;var rr=at(ms());F.PostgrestQueryBuilder=rr.default;var ir=at(Ut());F.PostgrestFilterBuilder=ir.default;var nr=at(hs());F.PostgrestTransformBuilder=nr.default;var or=at(ds());F.PostgrestBuilder=or.default;F.default={PostgrestClient:sr.default,PostgrestQueryBuilder:rr.default,PostgrestFilterBuilder:ir.default,PostgrestTransformBuilder:nr.default,PostgrestBuilder:or.default}});var gr=X((lo,mr)=>{"use strict";mr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var D="https://api.wisprflow.ai",is=class{static async signupUser(e){try{let t=`${D}/signup`,r=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=r&&r.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(`${D}/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(`${D}/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(`${D}/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(`${D}/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(`${D}/user_status?email=${encodeURIComponent(e)}`)).json()}static async requestPasswordReset(e,t){let s=await fetch(`${D}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,captcha_token:t})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new Error(r.message||`Request failed with status ${s.status}`)}}static async getSubscriptionStatus(e){return await fetch(`${D}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${D}/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 r=`${D}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`¤cy=${s}`),await(await fetch(r,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${D}/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(`${D}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${D}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${D}/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 r=new FormData;return r.append("screenshot",e),await fetch(`${D}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:r,signal:s})}};function Bs(i){let[e,...t]=i.split(" "),s=t.join(" ");return[e,s]}function Ws(i){return i==="azure"?"Microsoft":i==="workos"?"SSO":i.charAt(0).toUpperCase()+i.slice(1)}var V=is;var Gs=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var zs=()=>{let i=window.location.hash.substring(1),e=new URLSearchParams(i);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var Js=()=>{let{access_token:i,refresh_token:e}=zs(),t=i,s=e;if(!t||!s){let r=Gs();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var Ks=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Ze=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Ot=class extends Ze{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},It=class extends Ze{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},jt=class extends Ze{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},$t;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})($t||($t={}));var xi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},et=class{constructor(e,{headers:t={},customFetch:s,region:r=$t.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Ks(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return xi(this,void 0,void 0,function*(){try{let{headers:r,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let d;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",d=o):typeof o=="string"?(a["Content-Type"]="text/plain",d=o):typeof FormData<"u"&&o instanceof FormData?d=o:(a["Content-Type"]="application/json",d=JSON.stringify(o)));let c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:d}).catch(_=>{throw new Ot(_)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new It(c);if(!c.ok)throw new jt(c);let f=((s=c.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),m;return f==="application/json"?m=yield c.json():f==="application/octet-stream"?m=yield c.blob():f==="text/event-stream"?m=c:f==="multipart/form-data"?m=yield c.formData():m=yield c.text(),{data:m,error:null}}catch(r){return{data:null,error:r}}})}};var lr=Vs(ar(),1),{PostgrestClient:cr,PostgrestQueryBuilder:Vn,PostgrestFilterBuilder:Bn,PostgrestTransformBuilder:Wn,PostgrestBuilder:Gn}=lr.default;var dr="2.10.2";var ur={"X-Client-Info":`realtime-js/${dr}`},hr="1.0.0",Dt=1e4,fr=1e3,ve;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(ve||(ve={}));var B;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(B||(B={}));var z;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(z||(z={}));var qt;(function(i){i.websocket="websocket"})(qt||(qt={}));var pe;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(pe||(pe={}));var lt=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+r));o=o+r;let l=s.decode(e.slice(o,o+n));o=o+n;let d=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:d}}};var be=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(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(A||(A={}));var ys=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ni(o,i,e,r),n),{})},Ni=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?pr(n,o):_s(o)},pr=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return Hi(e,t)}switch(i){case A.bool:return qi(e);case A.float4:case A.float8:case A.int2:case A.int4:case A.int8:case A.numeric:case A.oid:return Di(e);case A.json:case A.jsonb:return Fi(e);case A.timestamp:return Vi(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 _s(e);default:return _s(e)}},_s=i=>i,qi=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Di=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Fi=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Hi=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>pr(e,a))}return i},Vi=i=>typeof i=="string"?i.replace(" ","T"):i,Ft=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ke=class{constructor(e,t,s={},r=Dt){this.channel=e,this.event=t,this.payload=s,this.timeout=r,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 ws;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(ws||(ws={}));var Me=class i{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,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,r,n,o),this.pendingDiffs.forEach(l=>{this.state=i.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=i.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(d,c)=>{o[d]||(l[d]=c)}),this.map(o,(d,c)=>{let u=n[d];if(u){let f=c.map(p=>p.presence_ref),m=u.map(p=>p.presence_ref),_=c.filter(p=>m.indexOf(p.presence_ref)<0),w=u.filter(p=>f.indexOf(p.presence_ref)<0);_.length>0&&(a[d]=_),w.length>0&&(l[d]=w)}else a[d]=c}),this.syncDiff(n,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,l)=>{var d;let c=(d=e[a])!==null&&d!==void 0?d:[];if(e[a]=this.cloneDeep(l),c.length>0){let u=e[a].map(m=>m.presence_ref),f=c.filter(m=>u.indexOf(m.presence_ref)<0);e[a].unshift(...f)}s(a,c,l)}),this.map(o,(a,l)=>{let d=e[a];if(!d)return;let c=l.map(u=>u.presence_ref);d=d.filter(u=>c.indexOf(u.presence_ref)<0),e[a]=d,r(a,d,l),d.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 r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,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 vs;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(vs||(vs={}));var bs;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(bs||(bs={}));var ks;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(ks||(ks={}));var Ne=class i{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=B.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 ke(this,z.join,this.params,this.timeout),this.rejoinTimer=new be(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=B.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=B.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=B.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=B.errored,this.rejoinTimer.scheduleTimeout())}),this._on(z.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new Me(this),this.broadcastEndpointURL=Ft(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,r;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(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},d={broadcast:n,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(c=>c.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:d},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:c})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),c===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,m=(u=f?.length)!==null&&u!==void 0?u:0,_=[];for(let w=0;w<m;w++){let p=f[w],{filter:{event:v,schema:M,table:C,filter:O}}=p,P=c&&c[w];if(P&&P.event===v&&P.schema===M&&P.table===C&&P.filter===O)_.push(Object.assign(Object.assign({},p),{id:P.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).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,r;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 l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=l.body)===null||r===void 0?void 0:r.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let d=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),d.receive("ok",()=>n("ok")),d.receive("error",()=>n("error")),d.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=B.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(z.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new ke(this,z.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.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 r=new ke(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:d,join:c}=z;if(s&&[a,l,d,c].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)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(m=>{var _,w,p;return((_=m.filter)===null||_===void 0?void 0:_.event)==="*"||((p=(w=m.filter)===null||w===void 0?void 0:w.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(m=>m.callback(f,s)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var _,w,p,v,M,C;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let O=m.id,P=(_=m.filter)===null||_===void 0?void 0:_.event;return O&&((w=t.ids)===null||w===void 0?void 0:w.includes(O))&&(P==="*"||P?.toLocaleLowerCase()===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{let O=(M=(v=m?.filter)===null||v===void 0?void 0:v.event)===null||M===void 0?void 0:M.toLocaleLowerCase();return O==="*"||O===((C=t?.event)===null||C===void 0?void 0:C.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof f=="object"&&"ids"in f){let _=f.data,{schema:w,table:p,commit_timestamp:v,type:M,errors:C}=_;f=Object.assign(Object.assign({},{schema:w,table:p,commit_timestamp:v,eventType:M,new:{},old:{},errors:C}),this._getPayloadRecords(_))}m.callback(f,s)})}_isClosed(){return this.state===B.closed}_isJoined(){return this.state===B.joined}_isJoining(){return this.state===B.joining}_isLeaving(){return this.state===B.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&i.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(z.close,{},e)}_onError(e){this._on(z.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=B.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ys(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ys(e.columns,e.old_record)),t}};var Wi=()=>{},Gi=typeof WebSocket<"u",qe=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ur,this.params={},this.timeout=Dt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Wi,this.conn=null,this.sendBuffer=[],this.serializer=new lt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(fe(),we)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${qt.websocket}`,this.httpEndpoint=Ft(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 r=(s=t?.params)===null||s===void 0?void 0:s.apikey;r&&(this.accessToken=r,this.apiKey=r),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 be(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 Ss(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Vs(gr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case ve.connecting:return pe.Connecting;case ve.open:return pe.Open;case ve.closing:return pe.Closing;default:return pe.Closed}}isConnected(){return this.connectionState()===pe.Open}channel(e,t={config:{}}){let s=new Ne(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(z.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:hr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||r===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,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(z.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(fr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Ss=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ve.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var De=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function U(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var Ht=class extends De{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ct=class extends De{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var zi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Vt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},_r=()=>zi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(fe(),we))).Response:Response});var Fe=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Es=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Ji=(i,e)=>Fe(void 0,void 0,void 0,function*(){let t=yield _r();i instanceof t?i.json().then(s=>{e(new Ht(Es(s),i.status||500))}).catch(s=>{e(new ct(Es(s),s))}):e(new ct(Es(i),i))}),Ki=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};function Bt(i,e,t,s,r,n){return Fe(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Ki(e,s,r,n)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Ji(l,a))})})}function dt(i,e,t,s){return Fe(this,void 0,void 0,function*(){return Bt(i,"GET",e,t,s)})}function Q(i,e,t,s,r){return Fe(this,void 0,void 0,function*(){return Bt(i,"POST",e,s,r,t)})}function yr(i,e,t,s,r){return Fe(this,void 0,void 0,function*(){return Bt(i,"PUT",e,s,r,t)})}function Wt(i,e,t,s,r){return Fe(this,void 0,void 0,function*(){return Bt(i,"DELETE",e,s,r,t)})}var J=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Yi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},wr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ut=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Vt(r)}uploadOrUpdate(e,t,s,r){return J(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},wr),r),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 l=this._removeEmptyFolders(t),d=this._getFinalPath(l),c=yield this.fetch(`${this.url}/object/${d}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield c.json();return c.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(U(n))return{data:null,error:n};throw n}})}upload(e,t,s){return J(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return J(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 l,d=Object.assign({upsert:wr.upsert},r),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",d.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",d.cacheControl)):(l=s,c["cache-control"]=`max-age=${d.cacheControl}`,c["content-type"]=d.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),f=yield u.json();return u.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(l){if(U(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return J(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");let n=yield Q(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new De("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}update(e,t,s){return J(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return J(this,void 0,void 0,function*(){try{return{data:yield Q(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(U(r))return{data:null,error:r};throw r}})}copy(e,t,s){return J(this,void 0,void 0,function*(){try{return{data:{path:(yield Q(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(U(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return J(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield Q(this.fetch,`${this.url}/object/sign/${r}`,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(r){if(U(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return J(this,void 0,void 0,function*(){try{let r=yield Q(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if(U(r))return{data:null,error:r};throw r}})}download(e,t){return J(this,void 0,void 0,function*(){let r=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 dt(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(U(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),r=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&r.push(l);let d=r.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${d}`)}}}remove(e){return J(this,void 0,void 0,function*(){try{return{data:yield Wt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}list(e,t,s){return J(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},Yi),t),{prefix:e||""});return{data:yield Q(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(U(r))return{data:null,error:r};throw r}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var vr="2.6.0";var br={"X-Client-Info":`storage-js/${vr}`};var He=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},ht=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},br),t),this.fetch=Vt(s)}listBuckets(){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}})}getBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return He(this,void 0,void 0,function*(){try{return{data:yield Q(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return He(this,void 0,void 0,function*(){try{return{data:yield yr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}emptyBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield Q(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield Wt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}};var ft=class extends ht{constructor(e,t={},s){super(e,t,s)}from(e){return new ut(this.url,this.headers,e,this.fetch)}};var kr="2.44.4";var pt="";typeof Deno<"u"?pt="deno":typeof document<"u"?pt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?pt="react-native":pt="node";var Xi={"X-Client-Info":`supabase-js-${pt}/${kr}`},Sr={headers:Xi},Er={schema:"public"},Tr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},xr={};fe();var Qi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},Zi=i=>{let e;return i?e=i:typeof fetch>"u"?e=ns:e=fetch,(...t)=>e(...t)},en=()=>typeof Headers>"u"?os:Headers,Ar=(i,e,t)=>{let s=Zi(t),r=en();return(n,o)=>Qi(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:i,d=new r(o?.headers);return d.has("apikey")||d.set("apikey",i),d.has("Authorization")||d.set("Authorization",`Bearer ${l}`),s(n,Object.assign(Object.assign({},o),{headers:d}))})};function Lr(i){return i.replace(/\/$/,"")}function Pr(i,e){let{db:t,auth:s,realtime:r,global:n}=i,{db:o,auth:a,realtime:l,global:d}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},l),r),global:Object.assign(Object.assign({},d),n)}}var Gt="2.64.4";var Rr="http://localhost:9999",Cr="supabase.auth.token";var Or={"X-Client-Info":`gotrue-js/${Gt}`},Ts=10;var mt="X-Supabase-Api-Version",xs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ir(i){return Math.round(Date.now()/1e3)+i}function jr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}var K=()=>typeof document<"u",Se={tested:!1,writable:!1},me=()=>{if(!K())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Se.tested)return Se.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),Se.tested=!0,Se.writable=!0}catch{Se.tested=!0,Se.writable=!1}return Se.writable};function zt(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}var Jt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},$r=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",As=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},_t=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Kt=async(i,e)=>{await i.removeItem(e)};function tn(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,r,n,o,a,l,d,c=0;for(i=i.replace("-","+").replace("_","/");c<i.length;)o=e.indexOf(i.charAt(c++)),a=e.indexOf(i.charAt(c++)),l=e.indexOf(i.charAt(c++)),d=e.indexOf(i.charAt(c++)),s=o<<2|a>>4,r=(a&15)<<4|l>>2,n=(l&3)<<6|d,t=t+String.fromCharCode(s),l!=64&&r!=0&&(t=t+String.fromCharCode(r)),d!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var gt=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};gt.promiseConstructor=Promise;function Ls(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.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(tn(s))}async function Ur(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Mr(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function sn(i){return("0"+i.toString(16)).substr(-2)}function rn(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,sn).join("")}async function nn(i){let t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}function on(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function an(i){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."),i;let t=await nn(i);return on(t)}async function Ee(i,e,t=!1){let s=rn(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await As(i,`${e}-code-verifier`,r);let n=await an(s);return[n,s===n?"plain":"s256"]}var ln=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Nr(i){let e=i.headers.get(mt);if(!e||!e.match(ln))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var yt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function S(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var Yt=class extends yt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function qr(i){return S(i)&&i.name==="AuthApiError"}var Ve=class extends yt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},le=class extends yt{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},Z=class extends le{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Be=class extends le{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Te=class extends le{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},xe=class extends le{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}}},wt=class extends le{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}}},We=class extends le{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Xt(i){return S(i)&&i.name==="AuthRetryableFetchError"}var vt=class extends le{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var cn=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},Ae=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),dn=[502,503,504];async function Dr(i){var e;if(!$r(i))throw new We(Ae(i),0);if(dn.includes(i.status))throw new We(Ae(i),i.status);let t;try{t=await i.json()}catch(n){throw new Ve(Ae(n),n)}let s,r=Nr(i);if(r&&r.getTime()>=xs["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 vt(Ae(t),i.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 vt(Ae(t),i.status,t.weak_password.reasons);throw new Yt(Ae(t),i.status||500,s)}var un=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function E(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[mt]||(n[mt]=xs["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await hn(i,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function hn(i,e,t,s,r,n){let o=un(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new We(Ae(l),0)}if(a.ok||await Dr(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await Dr(l)}}function ce(i){var e;let t=null;fn(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Ir(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function Ps(i){let e=ce(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function ee(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function Fr(i){return{data:i,error:null}}function Hr(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=cn(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Vr(i){return i}function fn(i){return i.access_token&&i.refresh_token&&i.expires_in}var pn=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},Le=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Jt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(S(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ee})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=pn(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:Hr,redirectTo:t?.redirectTo})}catch(t){if(S(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ee})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,l;try{let d={nextPage:null,lastPage:0,total:0},c=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:Vr});if(c.error)throw c.error;let u=await c.json(),f=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(_=>{let w=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(_.split(";")[1].split("=")[1]);d[`${p}Page`]=w}),d.total=parseInt(f)),{data:Object.assign(Object.assign({},u),d),error:null}}catch(d){if(S(d))return{data:{users:[]},error:d};throw d}}async getUserById(e){try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ee})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ee})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ee})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(S(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}}};var Br={getItem:i=>me()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{me()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{me()&&globalThis.localStorage.removeItem(i)}};function Rs(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function Wr(){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 Pe={debug:!!(globalThis&&me()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},bt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Qt=class extends bt{};async function Cs(i,e,t){Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new Qt(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(Pe.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()}})}Wr();var mn={url:Rr,storageKey:Cr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Or,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},kt=30*1e3,Gr=3;async function zr(i,e,t){return await t()}var Re=class i{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=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&K()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let r=Object.assign(Object.assign({},mn),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new Le({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=Jt(r.fetch),this.lock=r.lock||zr,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:K()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Cs:this.lock=zr,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?r.storage?this.storage=r.storage:me()?this.storage=Br:(this.memoryStorage={},this.storage=Rs(this.memoryStorage)):(this.memoryStorage={},this.storage=Rs(this.memoryStorage)),K()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Gt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=K()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:r,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",n),await this._saveSession(r),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return S(e)?{error:e}:{error:new Ve("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:ce}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(n){if(S(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){let{email:c,password:u,options:f}=e,m=null,_=null;this.flowType==="pkce"&&([m,_]=await Ee(this.storage,this.storageKey)),n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:u,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:_},xform:ce})}else if("phone"in e){let{phone:c,password:u,options:f}=e;n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(r=f?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ce})}else throw new Te("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 l=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(n){if(S(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ps})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ps})}else throw new Te("You must provide either an email or phone number and a password");let{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Be}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,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:(r=e.options)===null||r===void 0?void 0:r.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 _t(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ce});return await Kt(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 Be}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ce}),{data:l,error:d}=a;return d?{data:{user:null,session:null},error:d}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Be}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:d})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){let{email:a,options:l}=e,d=null,c=null;this.flowType==="pkce"&&([d,c]=await Ee(this.storage,this.storageKey));let{error:u}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:d,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:d,error:c}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:d?.message_id},error:c}}throw new Te("You must provide either an email or phone number.")}catch(a){if(S(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:ce});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,d=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:d,session:l},error:null}}catch(r){if(S(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Ee(this.storage,this.storageKey)),await E(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.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:Fr})}catch(n){if(S(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new Z;let{error:r}=await E(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(S(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:r,options:n}=e,{error:o}=await E(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,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:r,options:n}=e,{data:o,error:a}=await E(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Te("You must provide either an email or phone number and a type")}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}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 r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.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 _t(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:(l,d,c)=>(!o&&d==="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(l,d,c))})}return{data:{session:e},error:null}}let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ee}):await this._useSession(async t=>{var s,r,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Z}:await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:ee})})}catch(t){if(S(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new Z;let o=r.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Ee(this.storage,this.storageKey));let{data:d,error:c}=await E(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:ee});if(c)throw c;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Ls(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Z;let t=Date.now()/1e3,s=t,r=!0,n=null,o=Ls(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(S(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new Z;let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(S(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!K())throw new xe("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new xe("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new wt("Not a valid PKCE flow url.");let t=zt(window.location.href);if(e){if(!t.code)throw new wt("No code detected.");let{data:M,error:C}=await this._exchangeCodeForSession(t.code);if(C)throw C;let O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:M.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new xe(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:r,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:d}=t;if(!n||!a||!o||!d)throw new xe("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),f=c+u;l&&(f=parseInt(l));let m=f-c;m*1e3<=kt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${u}s`);let _=f-u;c-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,f,c):c-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,f,c);let{data:w,error:p}=await this._getUser(n);if(p)throw p;let v={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:u,expires_at:f,refresh_token:o,token_type:d,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:v,redirectType:t.type},error:null}}catch(t){if(S(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=zt(window.location.href);return!!(K()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=zt(window.location.href),t=await _t(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:r,error:n}=t;if(n)return{error:n};let o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(qr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Kt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=jr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;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((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await Ee(this.storage,this.storageKey,!0));try{return await E(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(S(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(S(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:r}=await this._useSession(async n=>{var o,a,l,d,c;let{data:u,error:f}=n;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await E(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(d=u.session)===null||d===void 0?void 0:d.access_token)!==null&&c!==void 0?c:void 0})});if(r)throw r;return K()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(S(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)throw o;return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Mr(async r=>(r>0&&await Ur(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ce})),(r,n)=>{let o=200*Math.pow(2,r);return n&&Xt(n)&&Date.now()+o-s<kt})}catch(s){if(this._debug(t,"error",s),S(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),K()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await _t(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 r=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<r+Ts;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Ts}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Xt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new Z;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new gt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new Z;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"error",n),S(n)){let o={session:null,error:n};return Xt(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(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"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(l){n.push(l)}});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(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await As(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Kt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&K()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),kt);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 r=Math.floor((s.expires_at*1e3-e)/kt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${kt}ms, refresh threshold is ${Gr} ticks`),r<=Gr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof bt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!K()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await Ee(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await E(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return l?{data:null,error:l}:(!((r=a?.totp)===null||r===void 0)&&r.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(S(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(S(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(S(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],r=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(r.access_token),a=null;o.aal&&(a=o.aal);let l=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};Re.nextInstanceID=0;var gn=Re,Os=gn;var Zt=class extends Os{constructor(e){super(e)}};var _n=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{d(s.next(c))}catch(u){o(u)}}function l(c){try{d(s.throw(c))}catch(u){o(u)}}function d(c){c.done?n(c.value):r(c.value).then(a,l)}d((s=s.apply(i,e||[])).next())})},St=class{constructor(e,t,s){var r,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=Lr(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,d={db:Er,realtime:xr,auth:Object.assign(Object.assign({},Tr),{storageKey:l}),global:Sr},c=Pr(s??{},d);this.storageKey=(r=c.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Ar(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new cr(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new et(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ft(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 _n(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:r,storageKey:n,flowType:o,debug:a},l,d){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Zt({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,debug:a,fetch:d,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new qe(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Jr=(i,e,t)=>new St(i,e,t);var de={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Ge=class{constructor(){this.sessionData=null;this.supabase=Jr(de.supaBaseUrl,de.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||de.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||de.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||de.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:r}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(r)throw r;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 r=new Date;r.setTime(r.getTime()+s*24*60*60*1e3);let n=`expires=${r.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{await this.setSession(t,s)}catch(r){throw r}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,r]=t.split("=");return e[s]=r,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||de.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,r,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:r||de.redirectUri,data:{full_name:s},captchaToken:n}});if(o)throw o;console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s){try{let{data:r,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:s}});if(n)throw n;if(!r.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:r.session.access_token,refreshToken:r.session.refresh_token,fullName:r.session.user.user_metadata?.full_name||void 0}}catch(r){throw console.error("Error signing in with password:",r),r}}async resendVerificationEmail(e,t,s){try{let{error:r}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||de.redirectUri,captchaToken:s}});if(r)throw r;console.log("Verification email resent to:",e)}catch(r){throw console.error("Error resending verification email:",r),r}}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 te=null;function Is(i,e=30,t){te&&(clearInterval(te),te=null);let s=e;i.style.pointerEvents="none",i.textContent=`Resend (${s}s)`,te=setInterval(()=>{s=s-1,i.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(i.style.pointerEvents="auto",te&&(clearInterval(te),te=null),t&&t())},1e3)}function Kr(){te&&(clearInterval(te),te=null)}function Yr(i,e){let t=new Ge,s="email_input",r=document.querySelector("#email-form"),n=document.querySelector("#email-input"),o=document.querySelector("#password-input"),a=document.querySelector("#full-name"),l=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),c=document.querySelector("#microsoft-login"),u=document.querySelector("[email-element]"),f=document.querySelector("[different-provider]"),m=document.querySelector("[different-provider-name]"),_=document.querySelector("[different-provider-reset]"),w=document.querySelector("[email-signup-success]"),p=document.querySelector("[email-signup-error]"),v=document.querySelector("[error-message]"),M=document.querySelector("[verification-email]"),C=document.querySelector("[email-signup-retry]"),O=document.querySelector("[email-signup-reset]"),P=document.querySelector("[scim-div]"),ge=document.querySelector("[scim-reset]"),N=document.querySelector("[forgot-password]"),se=document.querySelector("[forgot-password-success]"),_e=document.querySelector("[forgot-password-email]"),re=document.querySelector("[unverified-email]"),ze=document.querySelector("[unverified-email-address]"),ie=document.querySelector("[resend-verification-email]"),Je=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(i)}catch(b){console.error("Error during Google sign-in:",b)}}),d&&d.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(i)}catch(b){console.error("Error during Apple sign-in:",b)}}),c&&c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(i)}catch(b){console.error("Error during Microsoft sign-in:",b)}}));let ye=()=>{f&&(f.style.display="none"),w&&(w.style.display="none"),p&&(p.style.display="none"),re&&(re.style.display="none"),P&&(P.style.display="none"),N&&(N.style.display="none"),se&&(se.style.display="none");let b=document.querySelector(".gs-hero_form-block");b&&(b.style.display="block"),u&&(u.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 k=document.querySelector("[captcha-embed]"),x=document.querySelector("#h-captcha-container");k&&(k.style.display="none"),x&&(x.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",n&&n.focus()},Ce=()=>{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 b=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");b&&(b.style.display="block"),k&&(k.style.display="block"),N&&(N.style.display="block",N.onclick=async()=>{let x=n?.value||"",T=N.textContent||"";try{let{hcaptcha:$}=window;if(!$)throw new Error("Verification system not loaded. Please refresh the page.");N.style.pointerEvents="none",N.textContent="Sending...";let{response:L}=await $.execute({async:!0});if(!L)throw new Error("Verification cancelled");await V.requestPasswordReset(x,L),$.reset(),u&&(u.style.display="none"),N&&(N.style.display="none"),se&&(se.style.display="block"),_e&&(_e.textContent=x)}catch($){console.error("Error sending password reset email:",$),N.textContent=T,N.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),p&&(p.style.display="block",v&&(v.textContent=$ instanceof Error?$.message:"Failed to send reset email"))}}),s="login"},ue=()=>{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 b=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");b&&(b.style.display="block"),k&&(k.style.display="block"),s="signup"},Et=()=>{let b=document.querySelector(".gs-hero_form-block");b&&(b.style.display="none"),P&&(P.style.display="block"),ge&&(ge.onclick=()=>{P&&(P.style.display="none"),b&&(b.style.display="block"),ye()})},Ke=b=>{let k=Ws(b);u&&(u.style.display="none"),f&&(f.style.display="block"),m&&(m.textContent=k),_&&(_.onclick=()=>{f&&(f.style.display="none"),ye()}),s="oauth_user"},Tt=b=>{u&&(u.style.display="none"),re&&(re.style.display="block"),ze&&(ze.textContent=b),ie&&(ie.onclick=async()=>{let k=ie.textContent||"";try{let x=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(b,i,x),ie.textContent="Verification email resent! \u2705",ie.style.textDecoration="none"}catch(x){console.error("Error resending verification email:",x),ie.textContent=k}}),Je&&(Je.onclick=()=>{re&&(re.style.display="none"),ye()}),s="unverified_email"},xt=async(b,k)=>{let x=k.value;k.classList.add("loading"),k.value="";try{let T=await V.checkUserStatus(b);k.classList.remove("loading"),k.value=x,!T.exists&&T.scim_managed?Et():T.enforce_sso?Ke("workos"):T.exists&&T.provider&&T.provider!=="email"?Ke(T.provider):T.exists&&T.provider==="email"&&!T.verified?Tt(b):T.exists&&T.provider==="email"?Ce():ue()}catch(T){console.error("Error checking user status:",T),k.classList.remove("loading"),k.value=x,ue()}},At=async(b,k,x,T)=>{if(!k||k.length<8){p&&(p.style.display="block",v&&(v.textContent="Password must be at least 8 characters"));return}let $=window.hcaptcha?.getResponse()||"";if(!$){p&&(p.style.display="block",v&&(v.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{let{accessToken:L,refreshToken:I,fullName:ne}=await t.signInWithPassword(b,k,$);t.setCookies(L,I),localStorage.setItem("email",b),e?.onLoginSuccess?await e.onLoginSuccess(L,I,ne):window.location.href=i}catch(L){if(console.error("Login error:",L),window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=T,p&&(p.style.display="block",v)){let I=L instanceof Error?L.message:"Invalid login credentials";v.textContent=I}}},Oe=async(b,k,x,T,$)=>{if(!k||k.length<8){p&&(p.style.display="block",v&&(v.textContent="Password must be at least 8 characters"));return}if(!x||x.trim().length<2){p&&(p.style.display="block",v&&(v.textContent="Please enter your full name"));return}let L=window.hcaptcha?.getResponse()||"";if(!L){p&&(p.style.display="block",v&&(v.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{await t.signUpWithPassword(b,k,x,i,L),window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=$,u&&(u.style.display="none"),p&&(p.style.display="none"),w&&(w.style.display="block"),M&&(M.textContent=b),C&&(Is(C,30),C.onclick=async()=>{if(C.style.pointerEvents!=="none")try{let I=window.hcaptcha?.getResponse()||"";await t.signUpWithPassword(b,k,x,i,I),window.hcaptcha&&window.hcaptcha.reset(),Is(C,30)}catch(I){console.error("Error resending verification email:",I)}}),O&&(O.onclick=()=>{w&&(w.style.display="none"),Kr(),ye()})}catch(I){if(console.error("Signup error:",I),T.classList.remove("loading"),T.value=$,p&&(p.style.display="block",v)){let ne=I instanceof Error?I.message:"Signup failed";v.textContent=ne}}};r&&r.addEventListener("submit",async b=>{b.stopPropagation(),b.preventDefault();let k=n?.value||"",x=o?.value||"",T=a?.value||"";if(!k||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){p&&(p.style.display="block",v&&(v.textContent="Please enter a valid email address"));return}p&&(p.style.display="none"),v&&(v.textContent="");let L=r.querySelector('[type="submit"]'),I=L?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await xt(k,L):s==="login"?await At(k,x,L,I):s==="signup"&&await Oe(k,x,T,L,I)}catch(ne){console.error("Auth flow error:",ne),L&&(L.classList.remove("loading"),L.value=I),p&&(p.style.display="block")}})}var es=function(){return es=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++)for(var r in e=arguments[t])Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r]);return i},es.apply(this,arguments)},Xr=function(){function i(e,t,s){var r=this;this.endVal=t,this.options=s,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){r.startTime||(r.startTime=n);var o=n-r.startTime;r.remaining=r.duration-o,r.useEasing?r.countDown?r.frameVal=r.startVal-r.easingFn(o,0,r.startVal-r.endVal,r.duration):r.frameVal=r.easingFn(o,r.startVal,r.endVal-r.startVal,r.duration):r.frameVal=r.startVal+(r.endVal-r.startVal)*(o/r.duration);var a=r.countDown?r.frameVal<r.endVal:r.frameVal>r.endVal;r.frameVal=a?r.endVal:r.frameVal,r.frameVal=Number(r.frameVal.toFixed(r.options.decimalPlaces)),r.printValue(r.frameVal),o<r.duration?r.rAF=requestAnimationFrame(r.count):r.finalEndVal!==null?r.update(r.finalEndVal):r.options.onCompleteCallback&&r.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,d,c=n<0?"-":"";o=Math.abs(n).toFixed(r.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?r.options.decimal+u[1]:"",r.options.useGrouping){d="";for(var f=3,m=0,_=0,w=a.length;_<w;++_)r.options.useIndianSeparators&&_===4&&(f=2,m=1),_!==0&&m%f==0&&(d=r.options.separator+d),m++,d=a[w-_-1]+d;a=d}return r.options.numerals&&r.options.numerals.length&&(a=a.replace(/[0-9]/g,function(p){return r.options.numerals[+p]}),l=l.replace(/[0-9]/g,function(p){return r.options.numerals[+p]})),c+r.options.prefix+a+l+r.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=es(es({},this.defaults),s),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return r.handleScroll(r)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,s=e.el.getBoundingClientRect(),r=s.top+window.pageYOffset,n=s.top+s.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||r>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var s=this.countDown?1:-1;this.endVal=e+s*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var s=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,s):this.el.tagName==="INPUT"?this.el.value=s:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=s:this.el.innerHTML=s}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,' ])/g,"\\$1")},s=t(this.options.separator),r=t(this.options.decimal),n=e.replace(new RegExp(s,"g"),"").replace(new RegExp(r,"g"),".");return parseFloat(n)},i}();var Qr=!1;function Zr(){if(Qr)return;Qr=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(s=>{if(s.isIntersecting){let r=s.target;e.unobserve(r);let n=r.dataset.countDirection||"up",o=parseFloat(r.dataset.countOffset||"10")/100,a=parseFloat(r.dataset.countDuration||"2"),l=5,d=r.dataset.countTarget||r.textContent?.trim()||"0",c=parseFloat(d.replace(/,/g,""));if(isNaN(c))return;let u=c*o,f=Math.max(u,l),m=n==="down"?c+f:Math.max(0,c-f);new Xr(r,c,{startVal:Math.round(m),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var ei=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var R=(i,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:i,retry_attempt:10-t}),window.posthog.capture(i,e)):t>0&&setTimeout(()=>R(i,e,t-1),200)},ti=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};async function yn(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new Ge,{accessToken:t,refreshToken:s}=Js(),r=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),d=document.querySelector("[error-div]"),c=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),f=document.querySelector("[spots]"),m=document.querySelectorAll("[referral-code]"),_=document.querySelector("[referral-count]"),w=document.querySelector("[desktop-bonus-remaining]"),p=document.querySelector("[desktop-bonus-complete]"),v=document.querySelector("[climbed-dropped]"),M=document.querySelector("[keep-moving]"),C=document.querySelector("[rank-arrow-wrap]"),O=document.querySelector("[cohort-text]"),P=document.querySelector("[top-100]"),ge=document.querySelector("[top-1000]"),N=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),_e=document.querySelector("[sms-bonus-complete]"),re=document.querySelector("[total-boost]"),ze=document.querySelector("[social-media-details]"),ie=document.querySelector("[sms-popup-button]"),Je=document.querySelector("[app-download]"),ye=document.querySelector("[file-upload]"),Ce=document.querySelector("[file-input]"),ue=document.querySelector("[file-validation-error]"),Et=document.querySelector("[file-upload-loading]"),Ke=document.querySelector("[cancel-upload-button]"),Tt=document.querySelector("[file-upload-verified]"),xt=document.querySelector("[boost-earned]"),At=document.querySelector("[boost-earned-location]"),Oe=document.querySelector("[woohoo-button]"),b=document.querySelector("[file-upload-failed]"),k=document.querySelector("[upload-failed-text]"),x=document.querySelector("[close-button]"),T=document.querySelector("[share-on-x]"),$=document.querySelector("[share-on-linkedin]"),L=document.querySelector("[share-on-whatsapp]"),I=document.querySelector("[share-on-slack]"),ne=document.querySelector("[share-on-discord]"),js=document.querySelector("[social-media-bonus-remaining]"),$s=document.querySelector("[social-media-bonus-complete]"),Us=document.querySelector("[share-on-other-channel]");ze&&ze.addEventListener("click",()=>{R("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),ie&&ie.addEventListener("click",()=>{R("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),Je&&Je.addEventListener("click",()=>{window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_app_download",source:"android-waitlist-page"}),R("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let Ms=async()=>{clearTimeout(i),document.body.style.visibility="visible",o.forEach(Pt=>{Pt.style.display="none"}),n&&(n.style.display="block");let Ie=window.__abVariantPromise?await window.__abVariantPromise:"control",je=document.querySelector("[auth-hero-default]"),W=document.querySelector("[auth-hero-v1]"),Y=document.querySelector("[auth-hero-v2]");je&&(je.style.display="none"),W&&(W.style.display="none"),Y&&(Y.style.display="none"),Ie==="dictation-broken"&&W?W.style.display="block":Ie==="smartest"&&Y?Y.style.display="block":je&&(je.style.display="block"),n&&(n.style.display="none"),r&&(r.style.display="block");let Lt=document.querySelector("[reusable-section-wrap]");Lt&&r&&r.appendChild(Lt);let Ye=document.querySelector(".wl_cohort-spot-wrap");Ye&&(Ye.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),R("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),Yr(`${window.location.origin}/android-waitlist`)};if(!t||!s){await Ms();return}try{e.setCookies(t,s);let Ie=e.checkAndSetSession(),je=new Promise((h,y)=>setTimeout(()=>y(new Error("Session timeout")),3e3));await Promise.race([Ie,je]),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(i),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(h=>{h.style.display="flex",h.dataset.bound||(h.dataset.bound="true",h.addEventListener("click",async y=>{y.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let W=e.sessionData?.access_token,Y=e.sessionData?.user.email,Lt=e.sessionData?.user.user_metadata.full_name||" ",[Ye,Pt]=Bs(Lt),Xe=e.sessionData?.user.id;localStorage.setItem("email",Y),Xe&&localStorage.setItem("user_id",Xe),Xe&&ti(Xe,{email:Y,firstName:Ye,lastName:Pt});let si=ei(),{dub_id:ts,referral:ss,promo_code:Ns}=si,ri=!!localStorage.getItem("conversion_sent"),$e=!localStorage.getItem("android_waitlist_joined"),j={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},ii={access_token:W,first_name:Ye,last_name:Pt,dub_click_id:ts||void 0,referral:ss||void 0,promo_code:Ns||void 0};try{await V.signupUser(ii),j.signup.success=!0}catch(h){j.signup.success=!1,j.signup.error=h instanceof Error?h.message:"Unknown error"}try{let h=await V.ensureReferralCode(W);if(j.referral.success=h.ok,!h.ok){let y=await h.json().catch(()=>({}));j.referral.error=y.detail||y.message||`Status ${h.status}`}}catch(h){j.referral.success=!1,j.referral.error=h instanceof Error?h.message:"Network error"}ri||(R("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:ts||void 0,referral:ss||void 0,email:Y,user_id:Xe||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"));let ni={email:Y,device_type:"android"},qs=!1;try{await V.addToWaitlist(ni),j.waitlist.success=!0,qs=!0}catch(h){j.waitlist.success=!1,j.waitlist.error=h instanceof Error?h.message:"Unknown error"}$e&&qs&&(localStorage.setItem("android_waitlist_joined","true"),R("app_waitlist",{device_type:"android",source:"android-waitlist-page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:"android",source:"android-waitlist-page"}));let G=await V.getAndroidWaitlistStats(W);if(G.status===404&&!$e){R("android_waitlist_recovery_attempted",{reason:"localStorage flag set but 404 from stats API"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_attempted",reason:"localStorage flag set but 404 from stats API"}),localStorage.removeItem("android_waitlist_joined");try{let h={email:Y,device_type:"android"};await V.addToWaitlist(h),localStorage.setItem("android_waitlist_joined","true"),G=await V.getAndroidWaitlistStats(W),G.ok&&(R("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(h){console.error("Recovery addToWaitlist failed:",h)}}let oi=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if(j.stats.success=G.ok,G.status===401||G.status===429||!G.ok){let h="";try{let y=await G.json();h=JSON.stringify(y),j.stats.error=y.detail||y.message||h,c&&(c.textContent=`Status: ${G.status} | ${h}`)}catch{h="Could not parse response",j.stats.error=h,c&&(c.textContent=`Status: ${G.status} | ${h}`)}R("android_waitlist_api_error",{status:G.status,error:h,signup_success:j.signup.success,signup_error:j.signup.error,referral_success:j.referral.success,referral_error:j.referral.error,waitlist_success:j.waitlist.success,waitlist_error:j.waitlist.error,stats_error:j.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:G.status,error:h}),a&&(a.style.display="none"),d&&(d.style.display="block");return}let q=await G.json();if($e){let h=await yn(Y);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:q.current_rank,user_email_hash:h})}let Ds=localStorage.getItem("android_waitlist_last_rank");if(Ds&&!$e){let h=parseInt(Ds,10);q.current_rank<h&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:q.current_rank,positions_gained:h-q.current_rank,referral_count:q.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",q.current_rank.toString());let rs=h=>{let y=h.current_rank;if(u){let g=y.toLocaleString("en-US");u.textContent=g,u instanceof HTMLElement&&(u.dataset.countTarget=g)}if(h.starting_rank!==null){let g=h.starting_rank-y;f&&(f.textContent=Math.abs(g).toLocaleString()),g<0?(v&&(v.textContent="fell"),M&&(M.style.display="none"),C&&C.classList.add("invert")):(v&&(v.textContent="climbed"),M&&(M.style.display="inline-block"),C&&C.classList.remove("invert"))}if(P&&P.classList.remove("active"),ge&&ge.classList.remove("active"),N&&N.classList.remove("active"),y<=100?P&&P.classList.add("active"):y<=1e3?ge&&ge.classList.add("active"):y<=1e5&&N&&N.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(g=>{g.style.display="none"}),y<=100){let g=document.querySelector('[cohort-wins="top-100"]');g&&(g.style.display="block")}else if(y<=1e3){let g=document.querySelector('[cohort-wins="top-1000"]');g&&(g.style.display="block")}else if(y<=1e5){let g=document.querySelector('[cohort-wins="top-100k"]');g&&(g.style.display="block")}if(O)if(y<=100)O.innerHTML="You're in the <strong>top 100!</strong>";else if(y<=1e3){let g=y-100;O.innerHTML=`<strong>Only ${g.toLocaleString()} spots</strong> to top 100`}else if(y<=1e5){let g=y-1e3;O.innerHTML=`<strong>Only ${g.toLocaleString()} spots</strong> to top 1,000`}else{let g=y-1e5;O.innerHTML=`<strong>Only ${g.toLocaleString()} spots</strong> to top 100,000`}m.forEach(g=>{g.textContent=h.referral_code}),_&&(_.textContent=h.referrals_count.toString()),h.desktop_dictation_bonus_earned?(w&&(w.style.display="none"),p&&(p.style.display="block")):(w&&(w.style.display="block"),p&&(p.style.display="none")),h.phone_number_bonus_earned?(se&&(se.style.display="none"),_e&&(_e.style.display="block")):(se&&(se.style.display="block"),_e&&(_e.style.display="none")),h.verified_share_twitter&&T&&T.classList.add("verified"),h.verified_share_linkedin&&$&&$.classList.add("verified"),h.verified_share_whatsapp&&L&&L.classList.add("verified"),h.verified_share_slack&&I&&I.classList.add("verified"),h.verified_share_discord&&ne&&ne.classList.add("verified");let H=h.verified_share_twitter&&h.verified_share_linkedin&&h.verified_share_whatsapp&&h.verified_share_slack&&h.verified_share_discord;if(H&&(js&&(js.style.display="none"),$s&&($s.style.display="block")),re){let g=[h.phone_number_bonus_earned,h.desktop_dictation_bonus_earned,H].filter(Boolean).length;re.textContent=`${g} of 3`}};rs(q);let Fs=h=>h<=100?"top-100":h<=1e3?"top-1000":h<=1e5?"top-100k":"below-100k";R("android_waitlist_page_view",{rank:q.current_rank,total_boost:q.total_boost,referrals_count:q.referrals_count,cohort:Fs(q.current_rank),is_first_visit:$e}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:q.current_rank,total_boost:q.total_boost,referrals_count:q.referrals_count,cohort:Fs(q.current_rank),is_first_visit:$e});let ai=`https://wisprflow.ai/waitlist?${q.referral_code}`;document.querySelectorAll("[share]").forEach(h=>{let y=h.getAttribute("share");if(!y)return;let g=document.querySelector(`[share-content="${y}"]`)?.textContent||"";h.addEventListener("click",async()=>{switch(R("android_waitlist_share_clicked",{platform:y}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:y}),y){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(g)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(g),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(ai)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(g)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(g),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(g),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async h=>{let y=h,{phoneNumber:H}=y.detail;try{let g=await V.submitPhoneNumber(H,W),oe=await g.json();if(!g.ok||!oe.success){let Rt=oe.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:Rt}})),R("android_waitlist_sms_error",{error:Rt}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:Rt});return}window.dispatchEvent(new CustomEvent("sms:success"));let ae=await V.getAndroidWaitlistStats(W);ae.ok&&rs(await ae.json()),R("android_waitlist_sms_submitted",{boost_earned:oe.boost_earned,new_rank:oe.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:oe.boost_earned,new_rank:oe.current_rank})}catch(g){console.error("SMS submission error:",g),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}})),R("android_waitlist_sms_error",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:"network_error"})}});let he=h=>{ye&&(ye.style.display=h==="idle"?"block":"none"),Et&&(Et.style.display=h==="loading"?"block":"none"),Tt&&(Tt.style.display=h==="verified"?"block":"none"),b&&(b.style.display=h==="failed"?"block":"none"),ue&&(ue.style.display="none")},li=h=>{let H=["image/png","image/jpeg","image/jpg"];return h.size>20971520?"File too large. Maximum size is 20MB.":H.includes(h.type)?null:"Please upload a PNG or JPEG image."},ci={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},di=h=>ci[h]||"Social Media",ui={social_share_x:T,social_share_linkedin:$,social_share_whatsapp:L,social_share_slack:I,social_share_discord:ne},hi=h=>{let y=ui[h];y&&y.classList.add("verified")},fi=h=>({file_too_large:"File exceeds 20MB limit. (file_too_large)",invalid_file_type:"Please upload a PNG or JPEG. (invalid_file_type)","User not on Android waitlist":"Please join the waitlist first. (User not on Android waitlist)",all_platforms_already_claimed:"You've claimed all social share bonuses! (all_platforms_already_claimed)",x_already_claimed:"You've already received the X bonus. (x_already_claimed)",linkedin_already_claimed:"You've already received the LinkedIn bonus. (linkedin_already_claimed)",whatsapp_already_claimed:"You've already received the WhatsApp bonus. (whatsapp_already_claimed)",slack_already_claimed:"You've already received the Slack bonus. (slack_already_claimed)",discord_already_claimed:"You've already received the Discord bonus. (discord_already_claimed)",not_posted:"This looks like a draft, not a published post. (not_posted)",no_wispr_mention:"Post must mention Wispr Flow or wisprflow.ai. (no_wispr_mention)",invalid:"We couldn't verify this screenshot. Try a clearer image. (invalid)","An error occurred":"Something went wrong. Please try again. (An error occurred)"})[h??""]??`Verification failed. (${h})`,Qe=null;Ce&&Ce.addEventListener("change",async()=>{let h=Ce.files?.[0];if(!h)return;Ce.value="";let y=li(h);if(y){ue&&(ue.textContent=y,ue.style.display="block"),R("android_waitlist_social_validation_error",{error:y}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:y});return}R("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),he("loading"),Qe=new AbortController;try{let H=await V.submitSocialShare(h,W,Qe.signal),g=await H.json();if(!H.ok||!g.success){he("failed"),k&&(k.textContent=fi(g.error)),R("android_waitlist_social_upload_failed",{error:g.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:g.error});return}he("verified"),xt&&(xt.textContent=g.boost_earned.toLocaleString()),At&&(At.textContent=di(g.action)),hi(g.action);let oe=await V.getAndroidWaitlistStats(W);if(oe.ok){let ae=await oe.json();rs(ae),ae.verified_share_twitter&&ae.verified_share_linkedin&&ae.verified_share_whatsapp&&ae.verified_share_slack&&ae.verified_share_discord&&(Oe&&(Oe.style.display="none"),Us&&(Us.style.display="none"),R("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}R("android_waitlist_social_share_verified",{platform:g.action,boost_earned:g.boost_earned,new_rank:g.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:g.action,boost_earned:g.boost_earned,new_rank:g.current_rank})}catch(H){if(H instanceof Error&&H.name==="AbortError"){he("idle");return}console.error("Social share upload error:",H),he("failed"),k&&(k.textContent="Network error. Please try again."),R("android_waitlist_social_upload_failed",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:"network_error"})}finally{Qe=null}}),Ke&&Ke.addEventListener("click",()=>{Qe&&Qe.abort(),he("idle"),R("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),Oe&&Oe.addEventListener("click",()=>{he("idle")}),x&&x.addEventListener("click",()=>{he("idle")}),oi(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Zr()}catch(Ie){console.error("Error on android-waitlist page:",Ie),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await Ms()}});})();
|