@tanay-wispr/webflow-package 6.4.5 → 6.4.7

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.
@@ -1 +1 @@
1
- "use strict";(()=>{var xr=Object.create;var ot=Object.defineProperty;var Ar=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var Or=Object.getPrototypeOf,Cr=Object.prototype.hasOwnProperty;var Pr=(i,e)=>()=>(i&&(e=i(i=0)),e);var M=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Lr=(i,e)=>{for(var t in e)ot(i,t,{get:e[t],enumerable:!0})},cs=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Rr(e))!Cr.call(i,r)&&r!==t&&ot(i,r,{get:()=>e[r],enumerable:!(s=Ar(e,r))||s.enumerable});return i};var hs=(i,e,t)=>(t=i!=null?xr(Or(i)):{},cs(e||!i||!i.__esModule?ot(t,"default",{value:i,enumerable:!0}):t,i)),Ir=i=>cs(ot({},"__esModule",{value:!0}),i);var oe={};Lr(oe,{Headers:()=>jt,Request:()=>Ur,Response:()=>Dr,default:()=>It,fetch:()=>$r});var jr,ve,$r,It,jt,Ur,Dr,Z=Pr(()=>{"use strict";jr=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ve=jr(),$r=ve.fetch,It=ve.fetch.bind(ve),jt=ve.Headers,Ur=ve.Request,Dr=ve.Response});var ys=M(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});var $t=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ut.default=$t});var Nt=M(De=>{"use strict";var _s=De&&De.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(De,"__esModule",{value:!0});var Mr=_s((Z(),Ir(oe))),qr=_s(ys()),Dt=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Mr.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let h=null,c=null,u=null,d=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let x=await n.text();x===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=x:c=JSON.parse(x))}let f=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");f&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(h={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,d=406,p="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{let f=await n.text();try{h=JSON.parse(f),Array.isArray(h)&&n.status===404&&(c=[],h=null,d=200,p="OK")}catch{n.status===404&&f===""?(d=204,p="No Content"):h={message:f}}if(h&&this.isMaybeSingle&&(!((l=h?.details)===null||l===void 0)&&l.includes("0 rows"))&&(h=null,d=200,p="OK"),h&&this.shouldThrowOnError)throw new qr.default(h)}return{error:h,data:c,count:u,status:d,statusText:p}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,l;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}};De.default=Dt});var qt=M(Ne=>{"use strict";var Fr=Ne&&Ne.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ne,"__esModule",{value:!0});var Hr=Fr(Nt()),Mt=class extends Hr.default{select(e){let t=!1,s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:n=r}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; 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}};Ne.default=Mt});var ut=M(Me=>{"use strict";var Vr=Me&&Me.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Me,"__esModule",{value:!0});var Br=Vr(qt()),Ft=class extends Br.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};Me.default=Ft});var Vt=M(Fe=>{"use strict";var Gr=Fe&&Fe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Fe,"__esModule",{value:!0});var qe=Gr(ut()),Ht=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new qe.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new qe.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(l.length>0){let h=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",h.join(","))}}return new qe.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new qe.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new qe.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Fe.default=Ht});var ws=M(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.version=void 0;dt.version="0.0.0-automated"});var vs=M(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.DEFAULT_HEADERS=void 0;var zr=ws();ft.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${zr.version}`}});var ks=M(He=>{"use strict";var bs=He&&He.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(He,"__esModule",{value:!0});var Wr=bs(Vt()),Jr=bs(ut()),Kr=vs(),Bt=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Kr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new Wr.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([c,u])=>u!==void 0).map(([c,u])=>[c,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([c,u])=>{a.searchParams.append(c,u)})):(o="POST",l=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new Jr.default({method:o,url:a,headers:h,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};He.default=Bt});var Rs=M(j=>{"use strict";var Ve=j&&j.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(j,"__esModule",{value:!0});j.PostgrestBuilder=j.PostgrestTransformBuilder=j.PostgrestFilterBuilder=j.PostgrestQueryBuilder=j.PostgrestClient=void 0;var Ss=Ve(ks());j.PostgrestClient=Ss.default;var Es=Ve(Vt());j.PostgrestQueryBuilder=Es.default;var Ts=Ve(ut());j.PostgrestFilterBuilder=Ts.default;var xs=Ve(qt());j.PostgrestTransformBuilder=xs.default;var As=Ve(Nt());j.PostgrestBuilder=As.default;j.default={PostgrestClient:Ss.default,PostgrestQueryBuilder:Es.default,PostgrestFilterBuilder:Ts.default,PostgrestTransformBuilder:xs.default,PostgrestBuilder:As.default}});var Ds=M((bn,Us)=>{"use strict";Us.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",Lt=class{static async signupUser(e){try{let t=`${q}/signup`,r=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=r&&r.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${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("https://api.wisprflow.ai/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,s){let r=`${q}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`&currency=${s}`),await(await fetch(r,{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("https://api-east.wisprflow.ai/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}`}})}};function us(i){let[e,...t]=i.split(" "),s=t.join(" ");return[e,s]}function ds(i){return i==="azure"?"Microsoft":i.charAt(0).toUpperCase()+i.slice(1)}var ne=Lt;var fs=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var ps=()=>{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 ms=()=>{let{access_token:i,refresh_token:e}=ps(),t=i,s=e;if(!t||!s){let r=fs();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var gs=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Z(),oe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var $e=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},at=class extends $e{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},lt=class extends $e{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ct=class extends $e{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ht;(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"})(ht||(ht={}));var Nr=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((s=s.apply(i,e||[])).next())})},Ue=class{constructor(e,{headers:t={},customFetch:s,region:r=ht.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=gs(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Nr(this,void 0,void 0,function*(){try{let{headers:r,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let h;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:h}).catch(g=>{throw new at(g)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new lt(c);if(!c.ok)throw new ct(c);let d=((s=c.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return d==="application/json"?p=yield c.json():d==="application/octet-stream"?p=yield c.blob():d==="text/event-stream"?p=c:d==="multipart/form-data"?p=yield c.formData():p=yield c.text(),{data:p,error:null}}catch(r){return{data:null,error:r}}})}};var Os=hs(Rs(),1),{PostgrestClient:Cs,PostgrestQueryBuilder:tn,PostgrestFilterBuilder:sn,PostgrestTransformBuilder:rn,PostgrestBuilder:nn}=Os.default;var Ps="2.10.2";var Ls={"X-Client-Info":`realtime-js/${Ps}`},Is="1.0.0",mt=1e4,js=1e3,ae;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(ae||(ae={}));var $;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})($||($={}));var U;(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"})(U||(U={}));var pt;(function(i){i.websocket="websocket"})(pt||(pt={}));var ee;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(ee||(ee={}));var Be=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+r));o=o+r;let l=s.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:h}}};var le=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 b;(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"})(b||(b={}));var zt=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Yr(o,i,e,r),n),{})},Yr=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?$s(n,o):Gt(o)},$s=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return ei(e,t)}switch(i){case b.bool:return Qr(e);case b.float4:case b.float8:case b.int2:case b.int4:case b.int8:case b.numeric:case b.oid:return Xr(e);case b.json:case b.jsonb:return Zr(e);case b.timestamp:return ti(e);case b.abstime:case b.date:case b.daterange:case b.int4range:case b.int8range:case b.money:case b.reltime:case b.text:case b.time:case b.timestamptz:case b.timetz:case b.tsrange:case b.tstzrange:return Gt(e);default:return Gt(e)}},Gt=i=>i,Qr=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Xr=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Zr=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},ei=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>$s(e,a))}return i},ti=i=>typeof i=="string"?i.replace(" ","T"):i,gt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ce=class{constructor(e,t,s={},r=mt){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Wt;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Wt||(Wt={}));var be=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,r,n,o),this.pendingDiffs.forEach(l=>{this.state=i.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=i.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(h,c)=>{o[h]||(l[h]=c)}),this.map(o,(h,c)=>{let u=n[h];if(u){let d=c.map(m=>m.presence_ref),p=u.map(m=>m.presence_ref),g=c.filter(m=>p.indexOf(m.presence_ref)<0),f=u.filter(m=>d.indexOf(m.presence_ref)<0);g.length>0&&(a[h]=g),f.length>0&&(l[h]=f)}else a[h]=c}),this.syncDiff(n,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,l)=>{var h;let c=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(l),c.length>0){let u=e[a].map(p=>p.presence_ref),d=c.filter(p=>u.indexOf(p.presence_ref)<0);e[a].unshift(...d)}s(a,c,l)}),this.map(o,(a,l)=>{let h=e[a];if(!h)return;let c=l.map(u=>u.presence_ref);h=h.filter(u=>c.indexOf(u.presence_ref)<0),e[a]=h,r(a,h,l),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Jt;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Jt||(Jt={}));var Kt;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Kt||(Kt={}));var Yt;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(Yt||(Yt={}));var ke=class i{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=$.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 ce(this,U.join,this.params,this.timeout),this.rejoinTimer=new le(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=$.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=$.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=$.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=$.errored,this.rejoinTimer.scheduleTimeout())}),this._on(U.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new be(this),this.broadcastEndpointURL=gt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},h={broadcast:n,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(c=>c.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},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 d=this.bindings.postgres_changes,p=(u=d?.length)!==null&&u!==void 0?u:0,g=[];for(let f=0;f<p;f++){let m=d[f],{filter:{event:x,schema:O,table:A,filter:T}}=m,L=c&&c[f];if(L&&L.event===x&&L.schema===O&&L.table===A&&L.filter===T)g.push(Object.assign(Object.assign({},m),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=g,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=l.body)===null||r===void 0?void 0:r.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let h=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"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=$.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(U.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new ce(this,U.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new ce(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:h,join:c}=U;if(s&&[a,l,h,c].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(p=>{var g,f,m;return((g=p.filter)===null||g===void 0?void 0:g.event)==="*"||((m=(f=p.filter)===null||f===void 0?void 0:f.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(p=>p.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var g,f,m,x,O,A;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let T=p.id,L=(g=p.filter)===null||g===void 0?void 0:g.event;return T&&((f=t.ids)===null||f===void 0?void 0:f.includes(T))&&(L==="*"||L?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let T=(O=(x=p?.filter)===null||x===void 0?void 0:x.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return T==="*"||T===((A=t?.event)===null||A===void 0?void 0:A.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof d=="object"&&"ids"in d){let g=d.data,{schema:f,table:m,commit_timestamp:x,type:O,errors:A}=g;d=Object.assign(Object.assign({},{schema:f,table:m,commit_timestamp:x,eventType:O,new:{},old:{},errors:A}),this._getPayloadRecords(g))}p.callback(d,s)})}_isClosed(){return this.state===$.closed}_isJoined(){return this.state===$.joined}_isJoining(){return this.state===$.joining}_isLeaving(){return this.state===$.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&i.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(U.close,{},e)}_onError(e){this._on(U.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=$.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=zt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=zt(e.columns,e.old_record)),t}};var ri=()=>{},ii=typeof WebSocket<"u",Se=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ls,this.params={},this.timeout=mt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=ri,this.conn=null,this.sendBuffer=[],this.serializer=new Be,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(Z(),oe)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${pt.websocket}`,this.httpEndpoint=gt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let r=(s=t?.params)===null||s===void 0?void 0:s.apikey;r&&(this.accessToken=r,this.apiKey=r),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new le(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(ii){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Qt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>hs(Ds())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case ae.connecting:return ee.Connecting;case ae.open:return ee.Open;case ae.closing:return ee.Closing;default:return ee.Closed}}isConnected(){return this.connectionState()===ee.Open}channel(e,t={config:{}}){let s=new ke(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(U.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Is}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||r===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(U.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(js,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Qt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ae.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var Ee=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function P(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var yt=class extends Ee{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Ge=class extends Ee{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var ni=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((s=s.apply(i,e||[])).next())})},_t=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Z(),oe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Ns=()=>ni(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(Z(),oe))).Response:Response});var Te=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((s=s.apply(i,e||[])).next())})},Xt=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),oi=(i,e)=>Te(void 0,void 0,void 0,function*(){let t=yield Ns();i instanceof t?i.json().then(s=>{e(new yt(Xt(s),i.status||500))}).catch(s=>{e(new Ge(Xt(s),s))}):e(new Ge(Xt(i),i))}),ai=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};function wt(i,e,t,s,r,n){return Te(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,ai(e,s,r,n)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>oi(l,a))})})}function ze(i,e,t,s){return Te(this,void 0,void 0,function*(){return wt(i,"GET",e,t,s)})}function F(i,e,t,s,r){return Te(this,void 0,void 0,function*(){return wt(i,"POST",e,s,r,t)})}function Ms(i,e,t,s,r){return Te(this,void 0,void 0,function*(){return wt(i,"PUT",e,s,r,t)})}function vt(i,e,t,s,r){return Te(this,void 0,void 0,function*(){return wt(i,"DELETE",e,s,r,t)})}var D=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((s=s.apply(i,e||[])).next())})},li={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},qs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},We=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=_t(r)}uploadOrUpdate(e,t,s,r){return D(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},qs),r),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),h=this._getFinalPath(l),c=yield this.fetch(`${this.url}/object/${h}`,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(P(n))return{data:null,error:n};throw n}})}upload(e,t,s){return D(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return D(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,h=Object.assign({upsert:qs.upsert},r),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",h.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",h.cacheControl)):(l=s,c["cache-control"]=`max-age=${h.cacheControl}`,c["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(l){if(P(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return D(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");let n=yield F(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ee("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(P(s))return{data:null,error:s};throw s}})}update(e,t,s){return D(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return D(this,void 0,void 0,function*(){try{return{data:yield F(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}copy(e,t,s){return D(this,void 0,void 0,function*(){try{return{data:{path:(yield F(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return D(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield F(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return D(this,void 0,void 0,function*(){try{let r=yield F(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}download(e,t){return D(this,void 0,void 0,function*(){let r=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield ze(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(P(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),r=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&r.push(l);let h=r.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return D(this,void 0,void 0,function*(){try{return{data:yield vt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}list(e,t,s){return D(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},li),t),{prefix:e||""});return{data:yield F(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Fs="2.6.0";var Hs={"X-Client-Info":`storage-js/${Fs}`};var xe=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((s=s.apply(i,e||[])).next())})},Je=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Hs),t),this.fetch=_t(s)}listBuckets(){return xe(this,void 0,void 0,function*(){try{return{data:yield ze(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(P(e))return{data:null,error:e};throw e}})}getBucket(e){return xe(this,void 0,void 0,function*(){try{return{data:yield ze(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return xe(this,void 0,void 0,function*(){try{return{data:yield F(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(P(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return xe(this,void 0,void 0,function*(){try{return{data:yield Ms(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(P(s))return{data:null,error:s};throw s}})}emptyBucket(e){return xe(this,void 0,void 0,function*(){try{return{data:yield F(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}deleteBucket(e){return xe(this,void 0,void 0,function*(){try{return{data:yield vt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}};var Ke=class extends Je{constructor(e,t={},s){super(e,t,s)}from(e){return new We(this.url,this.headers,e,this.fetch)}};var Vs="2.44.4";var Ye="";typeof Deno<"u"?Ye="deno":typeof document<"u"?Ye="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ye="react-native":Ye="node";var ci={"X-Client-Info":`supabase-js-${Ye}/${Vs}`},Bs={headers:ci},Gs={schema:"public"},zs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ws={};Z();var hi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((s=s.apply(i,e||[])).next())})},ui=i=>{let e;return i?e=i:typeof fetch>"u"?e=It:e=fetch,(...t)=>e(...t)},di=()=>typeof Headers>"u"?jt:Headers,Js=(i,e,t)=>{let s=ui(t),r=di();return(n,o)=>hi(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:i,h=new r(o?.headers);return h.has("apikey")||h.set("apikey",i),h.has("Authorization")||h.set("Authorization",`Bearer ${l}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function Ks(i){return i.replace(/\/$/,"")}function Ys(i,e){let{db:t,auth:s,realtime:r,global:n}=i,{db:o,auth:a,realtime:l,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},l),r),global:Object.assign(Object.assign({},h),n)}}var bt="2.64.4";var Qs="http://localhost:9999",Xs="supabase.auth.token";var Zs={"X-Client-Info":`gotrue-js/${bt}`},Zt=10;var Qe="X-Supabase-Api-Version",es={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function er(i){return Math.round(Date.now()/1e3)+i}function tr(){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 N=()=>typeof document<"u",he={tested:!1,writable:!1},te=()=>{if(!N())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(he.tested)return he.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),he.tested=!0,he.writable=!0}catch{he.tested=!0,he.writable=!1}return he.writable};function kt(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}var St=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Z(),oe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},sr=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",ts=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},Ze=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Et=async(i,e)=>{await i.removeItem(e)};function fi(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,r,n,o,a,l,h,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++)),h=e.indexOf(i.charAt(c++)),s=o<<2|a>>4,r=(a&15)<<4|l>>2,n=(l&3)<<6|h,t=t+String.fromCharCode(s),l!=64&&r!=0&&(t=t+String.fromCharCode(r)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Xe=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Xe.promiseConstructor=Promise;function ss(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(fi(s))}async function rr(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function ir(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function pi(i){return("0"+i.toString(16)).substr(-2)}function mi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,pi).join("")}async function gi(i){let t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}function yi(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _i(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 gi(i);return yi(t)}async function ue(i,e,t=!1){let s=mi(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await ts(i,`${e}-code-verifier`,r);let n=await _i(s);return[n,s===n?"plain":"s256"]}var wi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function nr(i){let e=i.headers.get(Qe);if(!e||!e.match(wi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var et=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function y(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var Tt=class extends et{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function or(i){return y(i)&&i.name==="AuthApiError"}var Ae=class extends et{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},J=class extends et{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},H=class extends J{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Re=class extends J{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},de=class extends J{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},fe=class extends J{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}}},tt=class extends J{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}}},Oe=class extends J{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function xt(i){return y(i)&&i.name==="AuthRetryableFetchError"}var st=class extends J{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var vi=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},pe=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),bi=[502,503,504];async function ar(i){var e;if(!sr(i))throw new Oe(pe(i),0);if(bi.includes(i.status))throw new Oe(pe(i),i.status);let t;try{t=await i.json()}catch(n){throw new Ae(pe(n),n)}let s,r=nr(i);if(r&&r.getTime()>=es["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new st(pe(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 st(pe(t),i.status,t.weak_password.reasons);throw new Tt(pe(t),i.status||500,s)}var ki=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function w(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[Qe]||(n[Qe]=es["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Si(i,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Si(i,e,t,s,r,n){let o=ki(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new Oe(pe(l),0)}if(a.ok||await ar(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await ar(l)}}function K(i){var e;let t=null;Ei(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=er(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function rs(i){let e=K(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function V(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function lr(i){return{data:i,error:null}}function cr(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=vi(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function hr(i){return i}function Ei(i){return i.access_token&&i.refresh_token&&i.expires_in}var Ti=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},me=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=St(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await w(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(y(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await w(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:V})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Ti(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await w(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:cr,redirectTo:t?.redirectTo})}catch(t){if(y(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await w(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:V})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,l;try{let h={nextPage:null,lastPage:0,total:0},c=await w(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:hr});if(c.error)throw c.error;let u=await c.json(),d=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(g=>{let f=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(g.split(";")[1].split("=")[1]);h[`${m}Page`]=f}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(y(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await w(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:V})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await w(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:V})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await w(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:V})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await w(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(y(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await w(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}};var ur={getItem:i=>te()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{te()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{te()&&globalThis.localStorage.removeItem(i)}};function is(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function dr(){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 ge={debug:!!(globalThis&&te()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},rt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},At=class extends rt{};async function ns(i,e,t){ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),ge.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new At(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(ge.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()}})}dr();var xi={url:Qs,storageKey:Xs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Zs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},it=30*1e3,fr=3;async function pr(i,e,t){return await t()}var ye=class i{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&N()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let r=Object.assign(Object.assign({},xi),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new me({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=St(r.fetch),this.lock=r.lock||pr,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:N()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=ns:this.lock=pr,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?r.storage?this.storage=r.storage:te()?this.storage=ur:(this.memoryStorage={},this.storage=is(this.memoryStorage)):(this.memoryStorage={},this.storage=is(this.memoryStorage)),N()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${bt}) ${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=N()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:r,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",n),await this._saveSession(r),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return y(e)?{error:e}:{error:new Ae("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:K}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(y(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){let{email:c,password:u,options:d}=e,p=null,g=null;this.flowType==="pkce"&&([p,g]=await ue(this.storage,this.storageKey)),n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:c,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:p,code_challenge_method:g},xform:K})}else if("phone"in e){let{phone:c,password:u,options:d}=e;n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:K})}else throw new de("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,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(y(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 w(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:rs})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await w(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:rs})}else throw new de("You must provide either an email or phone number and a password");let{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Re}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ze(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await w(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:K});return await Et(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 Re}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await w(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:K}),{data:l,error:h}=a;return h?{data:{user:null,session:null},error:h}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Re}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:h})}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){let{email:a,options:l}=e,h=null,c=null;this.flowType==="pkce"&&([h,c]=await ue(this.storage,this.storageKey));let{error:u}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:h,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:h,error:c}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:c}}throw new de("You must provide either an email or phone number.")}catch(a){if(y(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await w(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:K});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,h=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(r){if(y(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await ue(this.storage,this.storageKey)),await w(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:lr})}catch(n){if(y(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new H;let{error:r}=await w(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(y(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:r,options:n}=e,{error:o}=await w(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:r,options:n}=e,{data:o,error:a}=await w(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new de("You must provide either an email or phone number and a type")}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ze(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,h,c)=>(!o&&h==="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,h,c))})}return{data:{session:e},error:null}}let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:V}):await this._useSession(async t=>{var s,r,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new H}:await w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:V})})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new H;let o=r.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await ue(this.storage,this.storageKey));let{data:h,error:c}=await w(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:V});if(c)throw c;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return ss(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 H;let t=Date.now()/1e3,s=t,r=!0,n=null,o=ss(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(y(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new H;let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!N())throw new fe("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new fe("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new tt("Not a valid PKCE flow url.");let t=kt(window.location.href);if(e){if(!t.code)throw new tt("No code detected.");let{data:O,error:A}=await this._exchangeCodeForSession(t.code);if(A)throw A;let T=new URL(window.location.href);return T.searchParams.delete("code"),window.history.replaceState(window.history.state,"",T.toString()),{data:{session:O.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new fe(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:h}=t;if(!n||!a||!o||!h)throw new fe("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),d=c+u;l&&(d=parseInt(l));let p=d-c;p*1e3<=it&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${u}s`);let g=d-u;c-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,c):c-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,d,c);let{data:f,error:m}=await this._getUser(n);if(m)throw m;let x={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:x,redirectType:t.type},error:null}}catch(t){if(y(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=kt(window.location.href);return!!(N()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=kt(window.location.href),t=await Ze(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{error:n};let o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(or(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Et(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=tr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await ue(this.storage,this.storageKey,!0));try{return await w(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(y(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:r}=await this._useSession(async n=>{var o,a,l,h,c;let{data:u,error:d}=n;if(d)throw d;let p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await w(this.fetch,"GET",p,{headers:this.headers,jwt:(c=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&c!==void 0?c:void 0})});if(r)throw r;return N()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(y(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)throw o;return await w(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await ir(async r=>(r>0&&await rr(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await w(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:K})),(r,n)=>{let o=200*Math.pow(2,r);return n&&xt(n)&&Date.now()+o-s<it})}catch(s){if(this._debug(t,"error",s),y(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),N()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await Ze(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let r=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<r+Zt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Zt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),xt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new H;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new Xe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new H;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"error",n),y(n)){let o={session:null,error:n};return xt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await ts(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Et(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&N()&&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(),it);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let r=Math.floor((s.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${it}ms, refresh threshold is ${fr} ticks`),r<=fr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof rt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!N()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await ue(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await w(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await w(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return l?{data:null,error:l}:(!((r=a?.totp)===null||r===void 0)&&r.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(y(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(y(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],r=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(r.access_token),a=null;o.aal&&(a=o.aal);let l=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};ye.nextInstanceID=0;var Ai=ye,os=Ai;var Rt=class extends os{constructor(e){super(e)}};var Ri=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((s=s.apply(i,e||[])).next())})},nt=class{constructor(e,t,s){var r,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=Ks(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`,h={db:Gs,realtime:Ws,auth:Object.assign(Object.assign({},zs),{storageKey:l}),global:Bs},c=Ys(s??{},h);this.storageKey=(r=c.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Js(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new Cs(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Ue(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ke(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Ri(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:n,flowType:o,debug:a},l,h){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Rt({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new Se(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var mr=(i,e,t)=>new nt(i,e,t);var Y={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Ce=class{constructor(){this.sessionData=null;this.supabase=mr(Y.supaBaseUrl,Y.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||Y.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||Y.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||Y.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:r}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(r)throw r;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw this.signOut(),console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let r=new Date;r.setTime(r.getTime()+s*24*60*60*1e3);let n=`expires=${r.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{await this.setSession(t,s)}catch(r){throw r}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,r]=t.split("=");return e[s]=r,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||Y.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,r,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:r||Y.redirectUri,data:{full_name:s},captchaToken:n}});if(o)throw o;console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s){try{let{data:r,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:s}});if(n)throw n;if(!r.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:r.session.access_token,refreshToken:r.session.refresh_token}}catch(r){throw console.error("Error signing in with password:",r),r}}async resendVerificationEmail(e,t){try{let{error:s}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||Y.redirectUri}});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 B=null;function as(i,e=30,t){B&&(clearInterval(B),B=null);let s=e;i.style.pointerEvents="none",i.textContent=`Resend (${s}s)`,B=setInterval(()=>{s=s-1,i.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(i.style.pointerEvents="auto",B&&(clearInterval(B),B=null),t&&t())},1e3)}function gr(){B&&(clearInterval(B),B=null)}function yr(i){let e=new Ce,t="email_input",s=document.querySelector("#email-form"),r=document.querySelector("#email-input"),n=document.querySelector("#password-input"),o=document.querySelector("#full-name"),a=document.querySelector("#google-login"),l=document.querySelector("#apple-login"),h=document.querySelector("#microsoft-login"),c=document.querySelector("[email-element]"),u=document.querySelector("[different-provider]"),d=document.querySelector("[different-provider-name]"),p=document.querySelector("[different-provider-reset]"),g=document.querySelector("[email-signup-success]"),f=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),x=document.querySelector("[verification-email]"),O=document.querySelector("[email-signup-retry]"),A=document.querySelector("[email-signup-reset]"),T=document.querySelector("[unverified-email]"),L=document.querySelector("[unverified-email-address]"),G=document.querySelector("[resend-verification-email]"),se=document.querySelector("[unverified-email-reset]");a&&a.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await e.signInWithGoogle(i)}catch(v){console.error("Error during Google sign-in:",v)}}),l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await e.signInWithApple(i)}catch(v){console.error("Error during Apple sign-in:",v)}}),h&&h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await e.signInWithMicrosoft(i)}catch(v){console.error("Error during Microsoft sign-in:",v)}});let Q=()=>{u&&(u.style.display="none"),g&&(g.style.display="none"),f&&(f.style.display="none"),T&&(T.style.display="none"),c&&(c.style.display="flex"),r&&(r.value="",r.removeAttribute("readonly"),r.classList.remove("disabled")),n&&(n.value="",n.style.display="none",n.removeAttribute("required")),o&&(o.value="",o.style.display="none",o.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),_=document.querySelector("#h-captcha-container");v&&(v.style.display="none"),_&&(_.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),t="email_input",r&&r.focus()},Pe=()=>{r&&(r.setAttribute("readonly","true"),r.classList.add("disabled")),n&&(n.style.display="block",n.setAttribute("required","true"),n.focus()),o&&(o.style.display="none",o.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),_=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),_&&(_.style.display="block"),t="login"},Le=()=>{r&&(r.setAttribute("readonly","true"),r.classList.add("disabled")),n&&(n.style.display="block",n.setAttribute("required","true"),n.focus()),o&&(o.style.display="block",o.setAttribute("required","true"));let v=document.querySelector("[captcha-embed]"),_=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),_&&(_.style.display="block"),t="signup"},X=v=>{let _=ds(v);c&&(c.style.display="none"),u&&(u.style.display="block"),d&&(d.textContent=_),p&&(p.onclick=()=>{u&&(u.style.display="none"),Q()}),t="oauth_user"},_e=v=>{c&&(c.style.display="none"),T&&(T.style.display="block"),L&&(L.textContent=v),G&&(G.onclick=async()=>{let _=G.textContent||"";try{await e.resendVerificationEmail(v,i),G.textContent="Verification email resent! \u2705",G.style.textDecoration="none"}catch(E){console.error("Error resending verification email:",E),G.textContent=_}}),se&&(se.onclick=()=>{T&&(T.style.display="none"),Q()}),t="unverified_email"},Ie=async(v,_)=>{let E=_.value;_.classList.add("loading"),_.value="";try{let S=await ne.checkUserStatus(v);_.classList.remove("loading"),_.value=E,S.exists&&S.provider&&S.provider!=="email"?X(S.provider):S.exists&&S.provider==="email"&&!S.verified?_e(v):S.exists&&S.provider==="email"?Pe():Le()}catch(S){console.error("Error checking user status:",S),_.classList.remove("loading"),_.value=E,Le()}},we=async(v,_,E,S)=>{if(!_||_.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let z=window.hcaptcha?.getResponse()||"";if(!z){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}E.classList.add("loading"),E.value="";try{let{accessToken:R,refreshToken:C}=await e.signInWithPassword(v,_,z);e.setCookies(R,C),localStorage.setItem("email",v),window.location.href=i}catch(R){if(console.error("Login error:",R),window.hcaptcha&&window.hcaptcha.reset(),E.classList.remove("loading"),E.value=S,f&&(f.style.display="block",m)){let C=R instanceof Error?R.message:"Invalid login credentials";m.textContent=C}}},Ct=async(v,_,E,S,z)=>{if(!_||_.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(!E||E.trim().length<2){f&&(f.style.display="block",m&&(m.textContent="Please enter your full name"));return}let R=window.hcaptcha?.getResponse()||"";if(!R){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{await e.signUpWithPassword(v,_,E,i,R),window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=z,c&&(c.style.display="none"),f&&(f.style.display="none"),g&&(g.style.display="block"),x&&(x.textContent=v),O&&(as(O,30),O.onclick=async()=>{if(O.style.pointerEvents!=="none")try{let C=window.hcaptcha?.getResponse()||"";await e.signUpWithPassword(v,_,E,i,C),window.hcaptcha&&window.hcaptcha.reset(),as(O,30)}catch(C){console.error("Error resending verification email:",C)}}),A&&(A.onclick=()=>{g&&(g.style.display="none"),gr(),Q()})}catch(C){if(console.error("Signup error:",C),S.classList.remove("loading"),S.value=z,f&&(f.style.display="block",m)){let re=C instanceof Error?C.message:"Signup failed";m.textContent=re}}};s&&s.addEventListener("submit",async v=>{v.stopPropagation(),v.preventDefault();let _=r?.value||"",E=n?.value||"",S=o?.value||"";if(!_||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(_)){f&&(f.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}f&&(f.style.display="none"),m&&(m.textContent="");let R=s.querySelector('[type="submit"]'),C=R?.value||"";localStorage.setItem("signin_provider","email");try{t==="email_input"?await Ie(_,R):t==="login"?await we(_,E,R,C):t==="signup"&&await Ct(_,E,S,R,C)}catch(re){console.error("Auth flow error:",re),R&&(R.classList.remove("loading"),R.value=C),f&&(f.style.display="block")}})}var Ot=function(){return Ot=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++)for(var r in e=arguments[t])Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r]);return i},Ot.apply(this,arguments)},_r=function(){function i(e,t,s){var r=this;this.endVal=t,this.options=s,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){r.startTime||(r.startTime=n);var o=n-r.startTime;r.remaining=r.duration-o,r.useEasing?r.countDown?r.frameVal=r.startVal-r.easingFn(o,0,r.startVal-r.endVal,r.duration):r.frameVal=r.easingFn(o,r.startVal,r.endVal-r.startVal,r.duration):r.frameVal=r.startVal+(r.endVal-r.startVal)*(o/r.duration);var a=r.countDown?r.frameVal<r.endVal:r.frameVal>r.endVal;r.frameVal=a?r.endVal:r.frameVal,r.frameVal=Number(r.frameVal.toFixed(r.options.decimalPlaces)),r.printValue(r.frameVal),o<r.duration?r.rAF=requestAnimationFrame(r.count):r.finalEndVal!==null?r.update(r.finalEndVal):r.options.onCompleteCallback&&r.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,h,c=n<0?"-":"";o=Math.abs(n).toFixed(r.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?r.options.decimal+u[1]:"",r.options.useGrouping){h="";for(var d=3,p=0,g=0,f=a.length;g<f;++g)r.options.useIndianSeparators&&g===4&&(d=2,p=1),g!==0&&p%d==0&&(h=r.options.separator+h),p++,h=a[f-g-1]+h;a=h}return r.options.numerals&&r.options.numerals.length&&(a=a.replace(/[0-9]/g,function(m){return r.options.numerals[+m]}),l=l.replace(/[0-9]/g,function(m){return r.options.numerals[+m]})),c+r.options.prefix+a+l+r.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=Ot(Ot({},this.defaults),s),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return r.handleScroll(r)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,s=e.el.getBoundingClientRect(),r=s.top+window.pageYOffset,n=s.top+s.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||r>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var s=this.countDown?1:-1;this.endVal=e+s*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var s=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,s):this.el.tagName==="INPUT"?this.el.value=s:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=s:this.el.innerHTML=s}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,'  ])/g,"\\$1")},s=t(this.options.separator),r=t(this.options.decimal),n=e.replace(new RegExp(s,"g"),"").replace(new RegExp(r,"g"),".");return parseFloat(n)},i}();var wr=!1;function vr(){if(wr)return;wr=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(s=>{if(s.isIntersecting){let r=s.target;e.unobserve(r);let n=r.dataset.countDirection||"up",o=parseFloat(r.dataset.countOffset||"10")/100,a=parseFloat(r.dataset.countDuration||"2"),l=r.dataset.countTarget||r.textContent?.trim()||"0",h=parseFloat(l.replace(/,/g,""));if(isNaN(h))return;let c=n==="down"?h*(1+o):h*(1-o);new _r(r,h,{startVal:Math.round(c),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var br=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var kr=(i,e)=>{window.posthog.capture(i,e)},Sr=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};async function Oi(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new Ce,{accessToken:t,refreshToken:s}=ms(),r=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelector("[stats-skeleton]"),a=document.querySelector("[stats-wrap]"),l=document.querySelector("[error-div]"),h=document.querySelector("[error-text]"),c=document.querySelector("[waitlist-rank]"),u=document.querySelector("[spots]"),d=document.querySelectorAll("[referral-code]"),p=document.querySelector("[referral-count]"),g=document.querySelector("[desktop-bonus-remaining]"),f=document.querySelector("[desktop-bonus-complete]"),m=document.querySelector("[climbed-dropped]"),x=document.querySelector("[keep-moving]"),O=document.querySelector("[rank-arrow-wrap]"),A=document.querySelector("[cohort-text]"),T=document.querySelector("[top-100]"),L=document.querySelector("[top-1000]"),G=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),Q=document.querySelector("[sms-bonus-complete]"),Pe=document.querySelector("[social-media]"),Le=document.querySelector("[social-media-details]");if(Le&&Pe&&Le.addEventListener("click",()=>{Pe.style.display="block",Pe.scrollIntoView({behavior:"smooth"})}),localStorage.getItem("sms_submitted")==="true"?(se&&(se.style.display="none"),Q&&(Q.style.display="block")):(se&&(se.style.display="block"),Q&&(Q.style.display="none")),!t||!s){clearTimeout(i),document.body.style.visibility="visible",r&&(r.style.display="block");let X=document.querySelector("[reusable-section-wrap]");X&&r&&r.appendChild(X);let _e=document.querySelector(".wl_cohort-spot-wrap");_e&&(_e.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),yr(`${window.location.origin}/android-waitlist-v2`);return}try{e.setCookies(t,s);let X=e.checkAndSetSession(),_e=new Promise((k,je)=>setTimeout(()=>je(new Error("Session timeout")),3e3));await Promise.race([X,_e]),clearTimeout(i),document.body.style.visibility="visible",n&&(n.style.display="block");let Ie=e.sessionData?.access_token,we=e.sessionData?.user.email,Ct=e.sessionData?.user.user_metadata.full_name||" ",[v,_]=us(Ct),E=e.sessionData?.user.id;localStorage.setItem("email",we),E&&localStorage.setItem("user_id",E),E&&Sr(E,{email:we,firstName:v,lastName:_});let S=br(),{dub_id:z,referral:R,promo_code:C}=S;if(!localStorage.getItem("conversion_sent")){let k={access_token:Ie,first_name:v,last_name:_,dub_click_id:z||void 0,referral:R||void 0,promo_code:C||void 0};await ne.signupUser(k),await ne.ensureReferralCode(Ie),localStorage.setItem("conversion_sent","true")}let re=!localStorage.getItem("android_waitlist_joined");if(re){let k={email:we,device_type:"android"};await ne.addToWaitlist(k),localStorage.setItem("android_waitlist_joined","true"),kr("app_waitlist",{device_type:"android",source:"android-waitlist-page"})}let ie=await ne.getAndroidWaitlistStats(Ie),Er=()=>{o&&(o.style.display="none"),a&&(a.style.display="block")};if(ie.status===401||ie.status===429||!ie.ok){try{let k=await ie.json();h&&(h.textContent=`Status: ${ie.status} | ${JSON.stringify(k)}`)}catch{h&&(h.textContent=`Status: ${ie.status} | Could not parse response`)}o&&(o.style.display="none"),l&&(l.style.display="block");return}let I=await ie.json();if(re){let k=await Oi(we);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:I.current_rank,user_email_hash:k})}let ls=localStorage.getItem("android_waitlist_last_rank");if(ls&&!re){let k=parseInt(ls,10);I.current_rank<k&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:I.current_rank,positions_gained:k-I.current_rank,referral_count:I.referrals_count}))}if(localStorage.setItem("android_waitlist_last_rank",I.current_rank.toString()),c&&(c.textContent=I.current_rank.toLocaleString()),I.starting_rank!==null){let k=I.starting_rank-I.current_rank;u&&(u.textContent=Math.abs(k).toLocaleString()),k<0&&(m&&(m.textContent="fell"),x&&(x.style.display="none"),O&&O.classList.add("invert"))}let W=I.current_rank;if(W<=100?T&&T.classList.add("active"):W<=1e3?L&&L.classList.add("active"):W<=1e5&&G&&G.classList.add("active"),A)if(W<=100)A.innerHTML="You're in the <strong>top 100!</strong>";else if(W<=1e3){let k=W-100;A.innerHTML=`<strong>Only ${k.toLocaleString()} spots</strong> to top 100`}else if(W<=1e5){let k=W-1e3;A.innerHTML=`<strong>Only ${k.toLocaleString()} spots</strong> to top 1,000`}else{let k=W-1e5;A.innerHTML=`<strong>Only ${k.toLocaleString()} spots</strong> to top 100,000`}d.forEach(k=>{k.textContent=I.referral_code}),p&&(p.textContent=I.referrals_count.toString()),I.desktop_dictation_bonus_earned?(g&&(g.style.display="none"),f&&(f.style.display="block")):(g&&(g.style.display="block"),f&&(f.style.display="none"));let Tr=`https://wisprflow.ai/waitlist?${I.referral_code}`;document.querySelectorAll("[share]").forEach(k=>{let je=k.getAttribute("share");if(!je)return;let Pt=document.querySelector(`[share-content="${je}"]`)?.textContent||"";k.addEventListener("click",async()=>{switch(je){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(Pt)}`,"_blank");break;case"linkedin":window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(Tr)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(Pt)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(Pt),window.open("slack://open","_self");break}})}),Er(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),vr()}catch(X){console.error("Error on android-waitlist page:",X),clearTimeout(i),window.location.href="/get-started?redirect=android-waitlist"}});})();
1
+ "use strict";(()=>{var ei=Object.create;var gt=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var si=Object.getOwnPropertyNames;var ri=Object.getPrototypeOf,ii=Object.prototype.hasOwnProperty;var ni=(i,e)=>()=>(i&&(e=i(i=0)),e);var B=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),oi=(i,e)=>{for(var t in e)gt(i,t,{get:e[t],enumerable:!0})},xs=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of si(e))!ii.call(i,r)&&r!==t&&gt(i,r,{get:()=>e[r],enumerable:!(s=ti(e,r))||s.enumerable});return i};var As=(i,e,t)=>(t=i!=null?ei(ri(i)):{},xs(e||!i||!i.__esModule?gt(t,"default",{value:i,enumerable:!0}):t,i)),ai=i=>xs(gt({},"__esModule",{value:!0}),i);var ue={};oi(ue,{Headers:()=>Wt,Request:()=>ui,Response:()=>hi,default:()=>Bt,fetch:()=>ci});var li,xe,ci,Bt,Wt,ui,hi,se=ni(()=>{"use strict";li=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")},xe=li(),ci=xe.fetch,Bt=xe.fetch.bind(xe),Wt=xe.Headers,ui=xe.Request,hi=xe.Response});var js=B(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});var Gt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};zt.default=Gt});var Kt=B(qe=>{"use strict";var $s=qe&&qe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(qe,"__esModule",{value:!0});var fi=$s((se(),ai(ue))),pi=$s(js()),Jt=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=fi.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let u=null,c=null,h=null,d=n.status,p=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 f=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");f&&m&&m.length>1&&(h=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(u={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,h=null,d=406,p="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{let f=await n.text();try{u=JSON.parse(f),Array.isArray(u)&&n.status===404&&(c=[],u=null,d=200,p="OK")}catch{n.status===404&&f===""?(d=204,p="No Content"):u={message:f}}if(u&&this.isMaybeSingle&&(!((l=u?.details)===null||l===void 0)&&l.includes("0 rows"))&&(u=null,d=200,p="OK"),u&&this.shouldThrowOnError)throw new pi.default(u)}return{error:u,data:c,count:h,status:d,statusText:p}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,l;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}};qe.default=Jt});var Xt=B(Fe=>{"use strict";var mi=Fe&&Fe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Fe,"__esModule",{value:!0});var gi=mi(Kt()),Yt=class extends gi.default{select(e){let t=!1,s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:n=r}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; 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}};Fe.default=Yt});var bt=B(He=>{"use strict";var yi=He&&He.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(He,"__esModule",{value:!0});var _i=yi(Xt()),Qt=class extends _i.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};He.default=Qt});var es=B(Be=>{"use strict";var wi=Be&&Be.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Be,"__esModule",{value:!0});var Ve=wi(bt()),Zt=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new Ve.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new Ve.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(l.length>0){let u=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new Ve.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new Ve.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new Ve.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Be.default=Zt});var Us=B(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.version=void 0;kt.version="0.0.0-automated"});var Ns=B(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.DEFAULT_HEADERS=void 0;var vi=Us();St.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${vi.version}`}});var Ms=B(We=>{"use strict";var Ds=We&&We.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(We,"__esModule",{value:!0});var bi=Ds(es()),ki=Ds(bt()),Si=Ns(),ts=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Si.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new bi.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([c,h])=>h!==void 0).map(([c,h])=>[c,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([c,h])=>{a.searchParams.append(c,h)})):(o="POST",l=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new ki.default({method:o,url:a,headers:u,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};We.default=ts});var Ws=B(U=>{"use strict";var Ge=U&&U.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(U,"__esModule",{value:!0});U.PostgrestBuilder=U.PostgrestTransformBuilder=U.PostgrestFilterBuilder=U.PostgrestQueryBuilder=U.PostgrestClient=void 0;var qs=Ge(Ms());U.PostgrestClient=qs.default;var Fs=Ge(es());U.PostgrestQueryBuilder=Fs.default;var Hs=Ge(bt());U.PostgrestFilterBuilder=Hs.default;var Vs=Ge(Xt());U.PostgrestTransformBuilder=Vs.default;var Bs=Ge(Kt());U.PostgrestBuilder=Bs.default;U.default={PostgrestClient:qs.default,PostgrestQueryBuilder:Fs.default,PostgrestFilterBuilder:Hs.default,PostgrestTransformBuilder:Vs.default,PostgrestBuilder:Bs.default}});var er=B((Jn,Zs)=>{"use strict";Zs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var H="https://api.wisprflow.ai",Vt=class{static async signupUser(e){try{let t=`${H}/signup`,r=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=r&&r.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${H}/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(`${H}/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(`${H}/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(`${H}/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(`${H}/user_status?email=${encodeURIComponent(e)}`)).json()}static async getSubscriptionStatus(e){return await fetch(`${H}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${H}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let r=`${H}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`&currency=${s}`),await(await fetch(r,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${H}/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("https://api-east.wisprflow.ai/api/v1/promos/android_waitlist_rank",{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${H}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch("https://api-east.wisprflow.ai/api/v1/promos/android_waitlist/phone_number",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let r=new FormData;return r.append("screenshot",e),await fetch("https://api-east.wisprflow.ai/api/v1/promos/android_waitlist/verify_social_share",{method:"POST",headers:{Authorization:`${t}`},body:r,signal:s})}};function Rs(i){let[e,...t]=i.split(" "),s=t.join(" ");return[e,s]}function Ps(i){return i==="azure"?"Microsoft":i.charAt(0).toUpperCase()+i.slice(1)}var V=Vt;var Cs=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var Os=()=>{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 Ls=()=>{let{access_token:i,refresh_token:e}=Os(),t=i,s=e;if(!t||!s){let r=Cs();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var Is=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(se(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var De=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},yt=class extends De{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},_t=class extends De{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},wt=class extends De{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},vt;(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"})(vt||(vt={}));var di=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(h){o(h)}}function l(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(a,l)}u((s=s.apply(i,e||[])).next())})},Me=class{constructor(e,{headers:t={},customFetch:s,region:r=vt.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Is(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return di(this,void 0,void 0,function*(){try{let{headers:r,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let u;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:u}).catch(g=>{throw new yt(g)}),h=c.headers.get("x-relay-error");if(h&&h==="true")throw new _t(c);if(!c.ok)throw new wt(c);let d=((s=c.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return d==="application/json"?p=yield c.json():d==="application/octet-stream"?p=yield c.blob():d==="text/event-stream"?p=c:d==="multipart/form-data"?p=yield c.formData():p=yield c.text(),{data:p,error:null}}catch(r){return{data:null,error:r}}})}};var Gs=As(Ws(),1),{PostgrestClient:zs,PostgrestQueryBuilder:Pn,PostgrestFilterBuilder:Cn,PostgrestTransformBuilder:On,PostgrestBuilder:Ln}=Gs.default;var Js="2.10.2";var Ks={"X-Client-Info":`realtime-js/${Js}`},Ys="1.0.0",Tt=1e4,Xs=1e3,he;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(he||(he={}));var N;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(N||(N={}));var D;(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"})(D||(D={}));var Et;(function(i){i.websocket="websocket"})(Et||(Et={}));var re;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(re||(re={}));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),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+r));o=o+r;let l=s.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:u}}};var de=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var 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 rs=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ei(o,i,e,r),n),{})},Ei=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?Qs(n,o):ss(o)},Qs=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return Ri(e,t)}switch(i){case E.bool:return Ti(e);case E.float4:case E.float8:case E.int2:case E.int4:case E.int8:case E.numeric:case E.oid:return xi(e);case E.json:case E.jsonb:return Ai(e);case E.timestamp:return Pi(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 ss(e);default:return ss(e)}},ss=i=>i,Ti=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},xi=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Ai=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Ri=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Qs(e,a))}return i},Pi=i=>typeof i=="string"?i.replace(" ","T"):i,xt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var fe=class{constructor(e,t,s={},r=Tt){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var is;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(is||(is={}));var Ae=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,r,n,o),this.pendingDiffs.forEach(l=>{this.state=i.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=i.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(u,c)=>{o[u]||(l[u]=c)}),this.map(o,(u,c)=>{let h=n[u];if(h){let d=c.map(m=>m.presence_ref),p=h.map(m=>m.presence_ref),g=c.filter(m=>p.indexOf(m.presence_ref)<0),f=h.filter(m=>d.indexOf(m.presence_ref)<0);g.length>0&&(a[u]=g),f.length>0&&(l[u]=f)}else a[u]=c}),this.syncDiff(n,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,l)=>{var u;let c=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(l),c.length>0){let h=e[a].map(p=>p.presence_ref),d=c.filter(p=>h.indexOf(p.presence_ref)<0);e[a].unshift(...d)}s(a,c,l)}),this.map(o,(a,l)=>{let u=e[a];if(!u)return;let c=l.map(h=>h.presence_ref);u=u.filter(h=>c.indexOf(h.presence_ref)<0),e[a]=u,r(a,u,l),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var ns;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(ns||(ns={}));var os;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(os||(os={}));var as;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(as||(as={}));var Re=class i{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=N.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new fe(this,D.join,this.params,this.timeout),this.rejoinTimer=new de(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=N.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=N.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this._on(D.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new Ae(this),this.broadcastEndpointURL=xt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},u={broadcast:n,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(c=>c.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:c})=>{var h;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),c===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,p=(h=d?.length)!==null&&h!==void 0?h:0,g=[];for(let f=0;f<p;f++){let m=d[f],{filter:{event:A,schema:R,table:O,filter:x}}=m,L=c&&c[f];if(L&&L.event===A&&L.schema===R&&L.table===O&&L.filter===x)g.push(Object.assign(Object.assign({},m),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=g,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=l.body)===null||r===void 0?void 0:r.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let u=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"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=N.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(D.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new fe(this,D.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new fe(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:u,join:c}=D;if(s&&[a,l,u,c].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(p=>{var g,f,m;return((g=p.filter)===null||g===void 0?void 0:g.event)==="*"||((m=(f=p.filter)===null||f===void 0?void 0:f.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(p=>p.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var g,f,m,A,R,O;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let x=p.id,L=(g=p.filter)===null||g===void 0?void 0:g.event;return x&&((f=t.ids)===null||f===void 0?void 0:f.includes(x))&&(L==="*"||L?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let x=(R=(A=p?.filter)===null||A===void 0?void 0:A.event)===null||R===void 0?void 0:R.toLocaleLowerCase();return x==="*"||x===((O=t?.event)===null||O===void 0?void 0:O.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof d=="object"&&"ids"in d){let g=d.data,{schema:f,table:m,commit_timestamp:A,type:R,errors:O}=g;d=Object.assign(Object.assign({},{schema:f,table:m,commit_timestamp:A,eventType:R,new:{},old:{},errors:O}),this._getPayloadRecords(g))}p.callback(d,s)})}_isClosed(){return this.state===N.closed}_isJoined(){return this.state===N.joined}_isJoining(){return this.state===N.joining}_isLeaving(){return this.state===N.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&i.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(D.close,{},e)}_onError(e){this._on(D.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=N.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=rs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=rs(e.columns,e.old_record)),t}};var Oi=()=>{},Li=typeof WebSocket<"u",Pe=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ks,this.params={},this.timeout=Tt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Oi,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(()=>(se(),ue)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Et.websocket}`,this.httpEndpoint=xt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let r=(s=t?.params)===null||s===void 0?void 0:s.apikey;r&&(this.accessToken=r,this.apiKey=r),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new de(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Li){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new ls(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>As(er())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case he.connecting:return re.Connecting;case he.open:return re.Open;case he.closing:return re.Closing;default:return re.Closed}}isConnected(){return this.connectionState()===re.Open}channel(e,t={config:{}}){let s=new Re(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(D.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Ys}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||r===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(D.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Xs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},ls=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=he.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var Ce=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function j(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var At=class extends Ce{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Je=class extends Ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Ii=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(h){o(h)}}function l(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(a,l)}u((s=s.apply(i,e||[])).next())})},Rt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(se(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},tr=()=>Ii(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(se(),ue))).Response:Response});var Oe=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(h){o(h)}}function l(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(a,l)}u((s=s.apply(i,e||[])).next())})},cs=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),ji=(i,e)=>Oe(void 0,void 0,void 0,function*(){let t=yield tr();i instanceof t?i.json().then(s=>{e(new At(cs(s),i.status||500))}).catch(s=>{e(new Je(cs(s),s))}):e(new Je(cs(i),i))}),$i=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};function Pt(i,e,t,s,r,n){return Oe(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,$i(e,s,r,n)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>ji(l,a))})})}function Ke(i,e,t,s){return Oe(this,void 0,void 0,function*(){return Pt(i,"GET",e,t,s)})}function W(i,e,t,s,r){return Oe(this,void 0,void 0,function*(){return Pt(i,"POST",e,s,r,t)})}function sr(i,e,t,s,r){return Oe(this,void 0,void 0,function*(){return Pt(i,"PUT",e,s,r,t)})}function Ct(i,e,t,s,r){return Oe(this,void 0,void 0,function*(){return Pt(i,"DELETE",e,s,r,t)})}var M=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(h){o(h)}}function l(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(a,l)}u((s=s.apply(i,e||[])).next())})},Ui={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},rr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ye=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Rt(r)}uploadOrUpdate(e,t,s,r){return M(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},rr),r),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),u=this._getFinalPath(l),c=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),h=yield c.json();return c.ok?{data:{path:l,id:h.Id,fullPath:h.Key},error:null}:{data:null,error:h}}catch(n){if(j(n))return{data:null,error:n};throw n}})}upload(e,t,s){return M(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return M(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,u=Object.assign({upsert:rr.upsert},r),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",u.cacheControl)):(l=s,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType);let h=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),d=yield h.json();return h.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(l){if(j(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return M(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");let n=yield W(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ce("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(j(s))return{data:null,error:s};throw s}})}update(e,t,s){return M(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return M(this,void 0,void 0,function*(){try{return{data:yield W(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}copy(e,t,s){return M(this,void 0,void 0,function*(){try{return{data:{path:(yield W(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return M(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield W(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return M(this,void 0,void 0,function*(){try{let r=yield W(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}download(e,t){return M(this,void 0,void 0,function*(){let r=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Ke(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(j(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),r=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&r.push(l);let u=r.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${u}`)}}}remove(e){return M(this,void 0,void 0,function*(){try{return{data:yield Ct(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}list(e,t,s){return M(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},Ui),t),{prefix:e||""});return{data:yield W(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var ir="2.6.0";var nr={"X-Client-Info":`storage-js/${ir}`};var Le=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(h){o(h)}}function l(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(a,l)}u((s=s.apply(i,e||[])).next())})},Xe=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},nr),t),this.fetch=Rt(s)}listBuckets(){return Le(this,void 0,void 0,function*(){try{return{data:yield Ke(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}})}getBucket(e){return Le(this,void 0,void 0,function*(){try{return{data:yield Ke(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Le(this,void 0,void 0,function*(){try{return{data:yield W(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(j(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Le(this,void 0,void 0,function*(){try{return{data:yield sr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(j(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Le(this,void 0,void 0,function*(){try{return{data:yield W(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Le(this,void 0,void 0,function*(){try{return{data:yield Ct(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}};var Qe=class extends Xe{constructor(e,t={},s){super(e,t,s)}from(e){return new Ye(this.url,this.headers,e,this.fetch)}};var or="2.44.4";var Ze="";typeof Deno<"u"?Ze="deno":typeof document<"u"?Ze="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ze="react-native":Ze="node";var Ni={"X-Client-Info":`supabase-js-${Ze}/${or}`},ar={headers:Ni},lr={schema:"public"},cr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ur={};se();var Di=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(h){o(h)}}function l(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(a,l)}u((s=s.apply(i,e||[])).next())})},Mi=i=>{let e;return i?e=i:typeof fetch>"u"?e=Bt:e=fetch,(...t)=>e(...t)},qi=()=>typeof Headers>"u"?Wt:Headers,hr=(i,e,t)=>{let s=Mi(t),r=qi();return(n,o)=>Di(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:i,u=new r(o?.headers);return u.has("apikey")||u.set("apikey",i),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),s(n,Object.assign(Object.assign({},o),{headers:u}))})};function dr(i){return i.replace(/\/$/,"")}function fr(i,e){let{db:t,auth:s,realtime:r,global:n}=i,{db:o,auth:a,realtime:l,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},l),r),global:Object.assign(Object.assign({},u),n)}}var Ot="2.64.4";var pr="http://localhost:9999",mr="supabase.auth.token";var gr={"X-Client-Info":`gotrue-js/${Ot}`},us=10;var et="X-Supabase-Api-Version",hs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function yr(i){return Math.round(Date.now()/1e3)+i}function _r(){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 q=()=>typeof document<"u",pe={tested:!1,writable:!1},ie=()=>{if(!q())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(pe.tested)return pe.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),pe.tested=!0,pe.writable=!0}catch{pe.tested=!0,pe.writable=!1}return pe.writable};function Lt(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}var It=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(se(),ue)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},wr=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",ds=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},st=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},jt=async(i,e)=>{await i.removeItem(e)};function Fi(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,r,n,o,a,l,u,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++)),u=e.indexOf(i.charAt(c++)),s=o<<2|a>>4,r=(a&15)<<4|l>>2,n=(l&3)<<6|u,t=t+String.fromCharCode(s),l!=64&&r!=0&&(t=t+String.fromCharCode(r)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var tt=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};tt.promiseConstructor=Promise;function fs(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(Fi(s))}async function vr(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function br(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function Hi(i){return("0"+i.toString(16)).substr(-2)}function Vi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,Hi).join("")}async function Bi(i){let t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}function Wi(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Gi(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 Bi(i);return Wi(t)}async function me(i,e,t=!1){let s=Vi(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await ds(i,`${e}-code-verifier`,r);let n=await Gi(s);return[n,s===n?"plain":"s256"]}var zi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function kr(i){let e=i.headers.get(et);if(!e||!e.match(zi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var rt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function _(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var $t=class extends rt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Sr(i){return _(i)&&i.name==="AuthApiError"}var Ie=class extends rt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Y=class extends rt{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},G=class extends Y{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},je=class extends Y{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ge=class extends Y{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ye=class extends Y{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}}},it=class extends Y{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}}},$e=class extends Y{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Ut(i){return _(i)&&i.name==="AuthRetryableFetchError"}var nt=class extends Y{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Ji=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},_e=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Ki=[502,503,504];async function Er(i){var e;if(!wr(i))throw new $e(_e(i),0);if(Ki.includes(i.status))throw new $e(_e(i),i.status);let t;try{t=await i.json()}catch(n){throw new Ie(_e(n),n)}let s,r=kr(i);if(r&&r.getTime()>=hs["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new nt(_e(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 nt(_e(t),i.status,t.weak_password.reasons);throw new $t(_e(t),i.status||500,s)}var Yi=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function v(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[et]||(n[et]=hs["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Xi(i,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Xi(i,e,t,s,r,n){let o=Yi(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new $e(_e(l),0)}if(a.ok||await Er(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await Er(l)}}function X(i){var e;let t=null;Qi(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=yr(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function ps(i){let e=X(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function z(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function Tr(i){return{data:i,error:null}}function xr(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=Ji(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Ar(i){return i}function Qi(i){return i.access_token&&i.refresh_token&&i.expires_in}var Zi=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},we=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=It(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await v(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(_(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await v(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:z})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Zi(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await v(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:xr,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await v(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:z})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await v(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:Ar});if(c.error)throw c.error;let h=await c.json(),d=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(g=>{let f=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(g.split(";")[1].split("=")[1]);u[`${m}Page`]=f}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(_(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await v(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:z})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await v(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:z})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await v(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:z})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await v(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await v(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var Rr={getItem:i=>ie()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{ie()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{ie()&&globalThis.localStorage.removeItem(i)}};function ms(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function Pr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var ve={debug:!!(globalThis&&ie()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ot=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Nt=class extends ot{};async function gs(i,e,t){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),ve.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new Nt(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(ve.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Pr();var en={url:pr,storageKey:mr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:gr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},at=30*1e3,Cr=3;async function Or(i,e,t){return await t()}var be=class i{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&q()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let r=Object.assign(Object.assign({},en),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new we({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=It(r.fetch),this.lock=r.lock||Or,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:q()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=gs:this.lock=Or,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?r.storage?this.storage=r.storage:ie()?this.storage=Rr:(this.memoryStorage={},this.storage=ms(this.memoryStorage)):(this.memoryStorage={},this.storage=ms(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Ot}) ${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=q()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:r,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",n),await this._saveSession(r),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return _(e)?{error:e}:{error:new Ie("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:X}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:u,session:l},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){let{email:c,password:h,options:d}=e,p=null,g=null;this.flowType==="pkce"&&([p,g]=await me(this.storage,this.storageKey)),n=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:c,password:h,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:p,code_challenge_method:g},xform:X})}else if("phone"in e){let{phone:c,password:h,options:d}=e;n=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:h,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:X})}else throw new ge("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,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:u,session:l},error:null}}catch(n){if(_(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 v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ps})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ps})}else throw new ge("You must provide either an email or phone number and a password");let{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new je}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await st(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await v(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:X});return await jt(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 je}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:X}),{data:l,error:u}=a;return u?{data:{user:null,session:null},error:u}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new je}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:u})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await me(this.storage,this.storageKey));let{error:h}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:c}}throw new ge("You must provide either an email or phone number.")}catch(a){if(_(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:X});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,u=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:u,session:l},error:null}}catch(r){if(_(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await me(this.storage,this.storageKey)),await v(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Tr})}catch(n){if(_(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new G;let{error:r}=await v(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(_(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:r,options:n}=e,{error:o}=await v(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:r,options:n}=e,{data:o,error:a}=await v(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new ge("You must provide either an email or phone number and a type")}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await st(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,u,c)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,u,c))})}return{data:{session:e},error:null}}let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:z}):await this._useSession(async t=>{var s,r,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new G}:await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:z})})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new G;let o=r.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await me(this.storage,this.storageKey));let{data:u,error:c}=await v(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=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return fs(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 G;let t=Date.now()/1e3,s=t,r=!0,n=null,o=fs(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new G;let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!q())throw new ye("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ye("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new it("Not a valid PKCE flow url.");let t=Lt(window.location.href);if(e){if(!t.code)throw new it("No code detected.");let{data:R,error:O}=await this._exchangeCodeForSession(t.code);if(O)throw O;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 ye(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:u}=t;if(!n||!a||!o||!u)throw new ye("No session defined in URL");let c=Math.round(Date.now()/1e3),h=parseInt(a),d=c+h;l&&(d=parseInt(l));let p=d-c;p*1e3<=at&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);let g=d-h;c-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,c):c-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,d,c);let{data:f,error:m}=await this._getUser(n);if(m)throw m;let A={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:u,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:A,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Lt(window.location.href);return!!(q()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Lt(window.location.href),t=await st(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{error:n};let o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Sr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await jt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=_r(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await me(this.storage,this.storageKey,!0));try{return await v(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:r}=await this._useSession(async n=>{var o,a,l,u,c;let{data:h,error:d}=n;if(d)throw d;let p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await v(this.fetch,"GET",p,{headers:this.headers,jwt:(c=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(r)throw r;return q()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(_(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)throw o;return await v(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await br(async r=>(r>0&&await vr(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await v(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:X})),(r,n)=>{let o=200*Math.pow(2,r);return n&&Ut(n)&&Date.now()+o-s<at})}catch(s){if(this._debug(t,"error",s),_(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),q()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await st(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let r=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<r+us;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${us}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Ut(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new G;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new tt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new G;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"error",n),_(n)){let o={session:null,error:n};return Ut(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await ds(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await jt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&q()&&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(),at);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let r=Math.floor((s.expires_at*1e3-e)/at);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${at}ms, refresh threshold is ${Cr} ticks`),r<=Cr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ot)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await me(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await v(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await v(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return l?{data:null,error:l}:(!((r=a?.totp)===null||r===void 0)&&r.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],r=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(r.access_token),a=null;o.aal&&(a=o.aal);let l=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};be.nextInstanceID=0;var tn=be,ys=tn;var Dt=class extends ys{constructor(e){super(e)}};var sn=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(h){o(h)}}function l(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(a,l)}u((s=s.apply(i,e||[])).next())})},lt=class{constructor(e,t,s){var r,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=dr(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`,u={db:lr,realtime:ur,auth:Object.assign(Object.assign({},cr),{storageKey:l}),global:ar},c=fr(s??{},u);this.storageKey=(r=c.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=hr(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new zs(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Me(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Qe(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return sn(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:n,flowType:o,debug:a},l,u){var c;let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Dt({url:this.authUrl,headers:Object.assign(Object.assign({},h),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new Pe(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Lr=(i,e,t)=>new lt(i,e,t);var Q={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Ue=class{constructor(){this.sessionData=null;this.supabase=Lr(Q.supaBaseUrl,Q.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||Q.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||Q.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||Q.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:r}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(r)throw r;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw this.signOut(),console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let r=new Date;r.setTime(r.getTime()+s*24*60*60*1e3);let n=`expires=${r.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{await this.setSession(t,s)}catch(r){throw r}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,r]=t.split("=");return e[s]=r,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||Q.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,r,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:r||Q.redirectUri,data:{full_name:s},captchaToken:n}});if(o)throw o;console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s){try{let{data:r,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:s}});if(n)throw n;if(!r.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:r.session.access_token,refreshToken:r.session.refresh_token}}catch(r){throw console.error("Error signing in with password:",r),r}}async resendVerificationEmail(e,t){try{let{error:s}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||Q.redirectUri}});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 J=null;function _s(i,e=30,t){J&&(clearInterval(J),J=null);let s=e;i.style.pointerEvents="none",i.textContent=`Resend (${s}s)`,J=setInterval(()=>{s=s-1,i.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(i.style.pointerEvents="auto",J&&(clearInterval(J),J=null),t&&t())},1e3)}function Ir(){J&&(clearInterval(J),J=null)}function jr(i){let e=new Ue,t="email_input",s=document.querySelector("#email-form"),r=document.querySelector("#email-input"),n=document.querySelector("#password-input"),o=document.querySelector("#full-name"),a=document.querySelector("#google-login"),l=document.querySelector("#apple-login"),u=document.querySelector("#microsoft-login"),c=document.querySelector("[email-element]"),h=document.querySelector("[different-provider]"),d=document.querySelector("[different-provider-name]"),p=document.querySelector("[different-provider-reset]"),g=document.querySelector("[email-signup-success]"),f=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),A=document.querySelector("[verification-email]"),R=document.querySelector("[email-signup-retry]"),O=document.querySelector("[email-signup-reset]"),x=document.querySelector("[unverified-email]"),L=document.querySelector("[unverified-email-address]"),F=document.querySelector("[resend-verification-email]"),ne=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)}}),u&&u.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await e.signInWithMicrosoft(i)}catch(b){console.error("Error during Microsoft sign-in:",b)}});let Z=()=>{h&&(h.style.display="none"),g&&(g.style.display="none"),f&&(f.style.display="none"),x&&(x.style.display="none"),c&&(c.style.display="flex"),r&&(r.value="",r.removeAttribute("readonly"),r.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]"),w=document.querySelector("#h-captcha-container");b&&(b.style.display="none"),w&&(w.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),t="email_input",r&&r.focus()},ct=()=>{r&&(r.setAttribute("readonly","true"),r.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]"),w=document.querySelector("#h-captcha-container");b&&(b.style.display="block"),w&&(w.style.display="block"),t="login"},ke=()=>{r&&(r.setAttribute("readonly","true"),r.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]"),w=document.querySelector("#h-captcha-container");b&&(b.style.display="block"),w&&(w.style.display="block"),t="signup"},ut=b=>{let w=Ps(b);c&&(c.style.display="none"),h&&(h.style.display="block"),d&&(d.textContent=w),p&&(p.onclick=()=>{h&&(h.style.display="none"),Z()}),t="oauth_user"},ht=b=>{c&&(c.style.display="none"),x&&(x.style.display="block"),L&&(L.textContent=b),F&&(F.onclick=async()=>{let w=F.textContent||"";try{await e.resendVerificationEmail(b,i),F.textContent="Verification email resent! \u2705",F.style.textDecoration="none"}catch(P){console.error("Error resending verification email:",P),F.textContent=w}}),ne&&(ne.onclick=()=>{x&&(x.style.display="none"),Z()}),t="unverified_email"},Se=async(b,w)=>{let P=w.value;w.classList.add("loading"),w.value="";try{let T=await V.checkUserStatus(b);w.classList.remove("loading"),w.value=P,T.exists&&T.provider&&T.provider!=="email"?ut(T.provider):T.exists&&T.provider==="email"&&!T.verified?ht(b):T.exists&&T.provider==="email"?ct():ke()}catch(T){console.error("Error checking user status:",T),w.classList.remove("loading"),w.value=P,ke()}},oe=async(b,w,P,T)=>{if(!w||w.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let K=window.hcaptcha?.getResponse()||"";if(!K){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}P.classList.add("loading"),P.value="";try{let{accessToken:I,refreshToken:C}=await e.signInWithPassword(b,w,K);e.setCookies(I,C),localStorage.setItem("email",b),window.location.href=i}catch(I){if(console.error("Login error:",I),window.hcaptcha&&window.hcaptcha.reset(),P.classList.remove("loading"),P.value=T,f&&(f.style.display="block",m)){let C=I instanceof Error?I.message:"Invalid login credentials";m.textContent=C}}},dt=async(b,w,P,T,K)=>{if(!w||w.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(!P||P.trim().length<2){f&&(f.style.display="block",m&&(m.textContent="Please enter your full name"));return}let I=window.hcaptcha?.getResponse()||"";if(!I){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{await e.signUpWithPassword(b,w,P,i,I),window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=K,c&&(c.style.display="none"),f&&(f.style.display="none"),g&&(g.style.display="block"),A&&(A.textContent=b),R&&(_s(R,30),R.onclick=async()=>{if(R.style.pointerEvents!=="none")try{let C=window.hcaptcha?.getResponse()||"";await e.signUpWithPassword(b,w,P,i,C),window.hcaptcha&&window.hcaptcha.reset(),_s(R,30)}catch(C){console.error("Error resending verification email:",C)}}),O&&(O.onclick=()=>{g&&(g.style.display="none"),Ir(),Z()})}catch(C){if(console.error("Signup error:",C),T.classList.remove("loading"),T.value=K,f&&(f.style.display="block",m)){let Ee=C instanceof Error?C.message:"Signup failed";m.textContent=Ee}}};s&&s.addEventListener("submit",async b=>{b.stopPropagation(),b.preventDefault();let w=r?.value||"",P=n?.value||"",T=o?.value||"";if(!w||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w)){f&&(f.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}f&&(f.style.display="none"),m&&(m.textContent="");let I=s.querySelector('[type="submit"]'),C=I?.value||"";localStorage.setItem("signin_provider","email");try{t==="email_input"?await Se(w,I):t==="login"?await oe(w,P,I,C):t==="signup"&&await dt(w,P,T,I,C)}catch(Ee){console.error("Auth flow error:",Ee),I&&(I.classList.remove("loading"),I.value=C),f&&(f.style.display="block")}})}var Mt=function(){return Mt=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++)for(var r in e=arguments[t])Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r]);return i},Mt.apply(this,arguments)},$r=function(){function i(e,t,s){var r=this;this.endVal=t,this.options=s,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){r.startTime||(r.startTime=n);var o=n-r.startTime;r.remaining=r.duration-o,r.useEasing?r.countDown?r.frameVal=r.startVal-r.easingFn(o,0,r.startVal-r.endVal,r.duration):r.frameVal=r.easingFn(o,r.startVal,r.endVal-r.startVal,r.duration):r.frameVal=r.startVal+(r.endVal-r.startVal)*(o/r.duration);var a=r.countDown?r.frameVal<r.endVal:r.frameVal>r.endVal;r.frameVal=a?r.endVal:r.frameVal,r.frameVal=Number(r.frameVal.toFixed(r.options.decimalPlaces)),r.printValue(r.frameVal),o<r.duration?r.rAF=requestAnimationFrame(r.count):r.finalEndVal!==null?r.update(r.finalEndVal):r.options.onCompleteCallback&&r.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,u,c=n<0?"-":"";o=Math.abs(n).toFixed(r.options.decimalPlaces);var h=(o+="").split(".");if(a=h[0],l=h.length>1?r.options.decimal+h[1]:"",r.options.useGrouping){u="";for(var d=3,p=0,g=0,f=a.length;g<f;++g)r.options.useIndianSeparators&&g===4&&(d=2,p=1),g!==0&&p%d==0&&(u=r.options.separator+u),p++,u=a[f-g-1]+u;a=u}return r.options.numerals&&r.options.numerals.length&&(a=a.replace(/[0-9]/g,function(m){return r.options.numerals[+m]}),l=l.replace(/[0-9]/g,function(m){return r.options.numerals[+m]})),c+r.options.prefix+a+l+r.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=Mt(Mt({},this.defaults),s),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return r.handleScroll(r)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,s=e.el.getBoundingClientRect(),r=s.top+window.pageYOffset,n=s.top+s.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||r>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var s=this.countDown?1:-1;this.endVal=e+s*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var s=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,s):this.el.tagName==="INPUT"?this.el.value=s:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=s:this.el.innerHTML=s}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,'  ])/g,"\\$1")},s=t(this.options.separator),r=t(this.options.decimal),n=e.replace(new RegExp(s,"g"),"").replace(new RegExp(r,"g"),".");return parseFloat(n)},i}();var Ur=!1;function Nr(){if(Ur)return;Ur=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(s=>{if(s.isIntersecting){let r=s.target;e.unobserve(r);let n=r.dataset.countDirection||"up",o=parseFloat(r.dataset.countOffset||"10")/100,a=parseFloat(r.dataset.countDuration||"2"),l=5,u=r.dataset.countTarget||r.textContent?.trim()||"0",c=parseFloat(u.replace(/,/g,""));if(isNaN(c))return;let h=c*o,d=Math.max(h,l),p=n==="down"?c+d:Math.max(0,c-d);new $r(r,c,{startVal:Math.round(p),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var Dr=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var qt=(i,e)=>{window.posthog.capture(i,e)},Mr=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};async function rn(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new Ue,{accessToken:t,refreshToken:s}=Ls(),r=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelector("[stats-skeleton]"),a=document.querySelector("[stats-wrap]"),l=document.querySelector("[error-div]"),u=document.querySelector("[error-text]"),c=document.querySelector("[waitlist-rank]"),h=document.querySelector("[spots]"),d=document.querySelectorAll("[referral-code]"),p=document.querySelector("[referral-count]"),g=document.querySelector("[desktop-bonus-remaining]"),f=document.querySelector("[desktop-bonus-complete]"),m=document.querySelector("[climbed-dropped]"),A=document.querySelector("[keep-moving]"),R=document.querySelector("[rank-arrow-wrap]"),O=document.querySelector("[cohort-text]"),x=document.querySelector("[top-100]"),L=document.querySelector("[top-1000]"),F=document.querySelector("[top-100k]"),ne=document.querySelector("[sms-bonus-remaining]"),Z=document.querySelector("[sms-bonus-complete]"),ct=document.querySelector("[total-boost]"),ke=document.querySelector("[social-media]"),ut=document.querySelector("[social-media-details]"),ht=document.querySelector("[file-upload]"),Se=document.querySelector("[file-input]"),oe=document.querySelector("[file-validation-error]"),dt=document.querySelector("[file-upload-loading]"),b=document.querySelector("[cancel-upload-button]"),w=document.querySelector("[file-upload-verified]"),P=document.querySelector("[boost-earned]"),T=document.querySelector("[boost-earned-location]"),K=document.querySelector("[woohoo-button]"),I=document.querySelector("[file-upload-failed]"),C=document.querySelector("[upload-failed-text]"),Ee=document.querySelector("[close-button]"),qr=document.querySelector("[share-on-x]"),Fr=document.querySelector("[share-on-linkedin]"),Hr=document.querySelector("[share-on-whatsapp]"),Vr=document.querySelector("[share-on-slack]");if(ut&&ke&&ut.addEventListener("click",()=>{ke.style.display="block",ke.scrollIntoView({behavior:"smooth"})}),!t||!s){clearTimeout(i),document.body.style.visibility="visible",r&&(r.style.display="block");let Te=document.querySelector("[reusable-section-wrap]");Te&&r&&r.appendChild(Te);let ft=document.querySelector(".wl_cohort-spot-wrap");ft&&(ft.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),jr(`${window.location.origin}/android-waitlist-v2`);return}try{e.setCookies(t,s);let Te=e.checkAndSetSession(),ft=new Promise((y,k)=>setTimeout(()=>k(new Error("Session timeout")),3e3));await Promise.race([Te,ft]),clearTimeout(i),document.body.style.visibility="visible",n&&(n.style.display="block");let ae=e.sessionData?.access_token,pt=e.sessionData?.user.email,Br=e.sessionData?.user.user_metadata.full_name||" ",[ws,vs]=Rs(Br),mt=e.sessionData?.user.id;localStorage.setItem("email",pt),mt&&localStorage.setItem("user_id",mt),mt&&Mr(mt,{email:pt,firstName:ws,lastName:vs});let Wr=Dr(),{dub_id:bs,referral:ks,promo_code:Ss}=Wr;if(!localStorage.getItem("conversion_sent")){let y={access_token:ae,first_name:ws,last_name:vs,dub_click_id:bs||void 0,referral:ks||void 0,promo_code:Ss||void 0};await V.signupUser(y),await V.ensureReferralCode(ae),localStorage.setItem("conversion_sent","true")}let Ft=!localStorage.getItem("android_waitlist_joined");if(Ft){let y={email:pt,device_type:"android"};await V.addToWaitlist(y),localStorage.setItem("android_waitlist_joined","true"),qt("app_waitlist",{device_type:"android",source:"android-waitlist-page"})}let le=await V.getAndroidWaitlistStats(ae),Gr=()=>{o&&(o.style.display="none"),a&&(a.style.display="block")};if(le.status===401||le.status===429||!le.ok){try{let y=await le.json();u&&(u.textContent=`Status: ${le.status} | ${JSON.stringify(y)}`)}catch{u&&(u.textContent=`Status: ${le.status} | Could not parse response`)}o&&(o.style.display="none"),l&&(l.style.display="block");return}let ee=await le.json();if(Ft){let y=await rn(pt);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:ee.current_rank,user_email_hash:y})}let Es=localStorage.getItem("android_waitlist_last_rank");if(Es&&!Ft){let y=parseInt(Es,10);ee.current_rank<y&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:ee.current_rank,positions_gained:y-ee.current_rank,referral_count:ee.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",ee.current_rank.toString());let Ht=y=>{let k=y.current_rank;if(c){let S=k.toLocaleString();c.textContent=S,c instanceof HTMLElement&&(c.dataset.countTarget=S)}if(y.starting_rank!==null){let S=y.starting_rank-k;h&&(h.textContent=Math.abs(S).toLocaleString()),S<0?(m&&(m.textContent="fell"),A&&(A.style.display="none"),R&&R.classList.add("invert")):(m&&(m.textContent="climbed"),A&&(A.style.display="inline-block"),R&&R.classList.remove("invert"))}if(x&&x.classList.remove("active"),L&&L.classList.remove("active"),F&&F.classList.remove("active"),k<=100?x&&x.classList.add("active"):k<=1e3?L&&L.classList.add("active"):k<=1e5&&F&&F.classList.add("active"),O)if(k<=100)O.innerHTML="You're in the <strong>top 100!</strong>";else if(k<=1e3){let S=k-100;O.innerHTML=`<strong>Only ${S.toLocaleString()} spots</strong> to top 100`}else if(k<=1e5){let S=k-1e3;O.innerHTML=`<strong>Only ${S.toLocaleString()} spots</strong> to top 1,000`}else{let S=k-1e5;O.innerHTML=`<strong>Only ${S.toLocaleString()} spots</strong> to top 100,000`}if(d.forEach(S=>{S.textContent=y.referral_code}),p&&(p.textContent=y.referrals_count.toString()),y.desktop_dictation_bonus_earned?(g&&(g.style.display="none"),f&&(f.style.display="block")):(g&&(g.style.display="block"),f&&(f.style.display="none")),y.phone_number_bonus_earned?(ne&&(ne.style.display="none"),Z&&(Z.style.display="block")):(ne&&(ne.style.display="block"),Z&&(Z.style.display="none")),ct){let S=[y.phone_number_bonus_earned,y.desktop_dictation_bonus_earned].filter(Boolean).length;ct.textContent=`${S} of 3`}};Ht(ee);let zr=`https://wisprflow.ai/waitlist?${ee.referral_code}`;document.querySelectorAll("[share]").forEach(y=>{let k=y.getAttribute("share");if(!k)return;let $=document.querySelector(`[share-content="${k}"]`)?.textContent||"";y.addEventListener("click",async()=>{switch(k){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent($)}`,"_blank");break;case"linkedin":window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(zr)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent($)}`,"_blank");break;case"slack":await navigator.clipboard.writeText($),window.open("slack://open","_self");break}})}),window.addEventListener("sms:submit",async y=>{let k=y,{phoneNumber:S}=k.detail;try{let $=await V.submitPhoneNumber(S,ae),ce=await $.json();if(!$.ok||!ce.success){window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:ce.error||"Something went wrong"}}));return}window.dispatchEvent(new CustomEvent("sms:success"));let Ts=await V.getAndroidWaitlistStats(ae);Ts.ok&&Ht(await Ts.json()),qt("android_waitlist_sms_submitted",{boost_earned:ce.boost_earned,new_rank:ce.current_rank})}catch($){console.error("SMS submission error:",$),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}}))}});let te=y=>{ht&&(ht.style.display=y==="idle"?"block":"none"),dt&&(dt.style.display=y==="loading"?"block":"none"),w&&(w.style.display=y==="verified"?"block":"none"),I&&(I.style.display=y==="failed"?"block":"none"),oe&&(oe.style.display="none")},Jr=y=>{let S=["image/png","image/jpeg","image/jpg"];return y.size>20971520?"File too large. Maximum size is 20MB.":S.includes(y.type)?null:"Please upload a PNG or JPEG image."},Kr={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack"},Yr=y=>Kr[y]||"Social Media",Xr={social_share_x:qr,social_share_linkedin:Fr,social_share_whatsapp:Hr,social_share_slack:Vr},Qr=y=>{let k=Xr[y];k&&k.classList.add("verified")},Zr=y=>({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)",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)"})[y??""]??`Verification failed. (${y})`,Ne=null;Se&&Se.addEventListener("change",async()=>{let y=Se.files?.[0];if(!y)return;Se.value="";let k=Jr(y);if(k){oe&&(oe.textContent=k,oe.style.display="block");return}te("loading"),Ne=new AbortController;try{let S=await V.submitSocialShare(y,ae,Ne.signal),$=await S.json();if(!S.ok||!$.success){te("failed"),C&&(C.textContent=Zr($.error));return}te("verified"),P&&(P.textContent=$.boost_earned.toLocaleString()),T&&(T.textContent=Yr($.action)),Qr($.action);let ce=await V.getAndroidWaitlistStats(ae);ce.ok&&Ht(await ce.json()),qt("android_waitlist_social_share_verified",{platform:$.action,boost_earned:$.boost_earned,new_rank:$.current_rank})}catch(S){if(S instanceof Error&&S.name==="AbortError"){te("idle");return}console.error("Social share upload error:",S),te("failed"),C&&(C.textContent="Network error. Please try again.")}finally{Ne=null}}),b&&b.addEventListener("click",()=>{Ne&&Ne.abort(),te("idle")}),K&&K.addEventListener("click",()=>{te("idle")}),Ee&&Ee.addEventListener("click",()=>{te("idle")}),Gr(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Nr()}catch(Te){console.error("Error on android-waitlist page:",Te),clearTimeout(i),window.location.href="/get-started?redirect=android-waitlist"}});})();