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