@tanay-wispr/webflow-package 5.1.0 → 5.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/downloads.js CHANGED
@@ -4,4 +4,4 @@
4
4
  <div class="spacer-medium"></div>
5
5
  <p class="text-size-medium">Redirecting you to downloads page in <span id="countdown">3</span> seconds...</p>
6
6
  </div>
7
- `;let ns=t?`/downloads?referral=${t}`:"/downloads";fi(3,ns)}else{let ve=r;wt.is_student===!0&&(r.endsWith("MONTHLY")?ve="FLOW_STUDENT_MONTHLY":r.endsWith("YEARLY")&&(ve="FLOW_STUDENT_YEARLY")),await di(ve,l,t)}}else{console.log("Subscription API failed: Non-200 status"),await Vt(r,t,a);return}}catch(z){console.error("Status check error:",z),await Vt(r,t,a);return}return}clearTimeout(o),document.body.style.visibility="visible",r||is(c)}catch(w){n=!0,clearTimeout(o),window.location.href="/get-started",console.error("Error during session setup:",w)}else localStorage.getItem("email")?(d.textContent=`Hi ${localStorage.getItem("email")}!`,f.style.display="flex",clearTimeout(o),document.body.style.visibility="visible",r||is(c)):(n=!0,clearTimeout(o),window.location.href="/get-started");document.querySelectorAll("[active-download]").forEach(function(w){if(!c.startsWith("mac")&&w.getAttribute("active-download")?.startsWith("mac")){w.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;W("app_waitlist",{device_type:w.getAttribute("active-download")});let I={email:localStorage.getItem("email"),device_type:w.getAttribute("active-download")||"unknown"};return Ve.addToWaitlist(I),w.innerText="We emailed you the download link!",!1};return}w.onclick=()=>(W("app_download",{device_type:c,download_type:w.getAttribute("active-download"),auto_download:ye,source:"downloads-page",email:localStorage.getItem("email")||"not-found"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",device_type:c,download_type:w.getAttribute("active-download"),auto_download:ye,source:"downloads-page"}),!0)}),document.querySelectorAll("[download-link]").forEach(function(w){w.onclick=()=>(W("app_download",{device_type:c,source:"downloads-page-fallback",email:localStorage.getItem("email")||"not-found"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",device_type:c,download_type:c,auto_download:!1,source:"downloads-page-fallback"}),!0)}),document.querySelectorAll("[waitlist]").forEach(function(w){w.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;W("app_waitlist",{device_type:w.getAttribute("waitlist")});let I={email:localStorage.getItem("email"),device_type:w.getAttribute("waitlist")||"unknown"};return Ve.addToWaitlist(I),w.innerText="You're on the waitlist!",!1}});let b=document.querySelector("[download-email-form]");b&&(b.removeAttribute("action"),b.addEventListener("submit",async w=>{w.preventDefault(),w.stopPropagation();let M=b.querySelector("[email-input]"),I=b.querySelector("[platform-name]"),C=b.querySelector('input[type="submit"]');if(!M||!I||!C){console.error("Form fields not found");return}let L=M.value.trim(),F=I.value.trim();if(!L||!F){console.error("Email or platform is empty");return}C.value="Please wait...",C.classList.add("pointer-events-none");try{let we=await fetch("https://api.wisprflow.ai/api/v1/referral/download-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:F,recipient_email:L})});if(we.ok){console.log("Email sent successfully");let $=document.querySelector("[success-div]");$&&($.style.display="block"),b.style.display="none",C.classList.remove("pointer-events-none"),W("download_link_email_success",{platform_requested:F,email:L,source:"downloads_page_form",device_type:c})}else{console.error("API error:",we.status);let $=document.querySelector("[error-div]");$&&($.style.display="block"),C.classList.remove("pointer-events-none")}}catch(we){console.error("Network error:",we);let $=document.querySelector("[error-div]");$&&($.style.display="block"),C.classList.remove("pointer-events-none")}})),f.addEventListener("click",async()=>{try{await a.signOut(),localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),n=!0,clearTimeout(o),window.location.href="/get-started"}catch(w){console.error("Error during sign-out:",w)}})});async function Vt(s,e,t){console.log("Handling token expiration - logging out user");try{await t.signOut(),localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status");let r="/get-started",i=new URLSearchParams;e&&i.append("referral",e),s&&i.append("plan",s),i.toString()&&(r+=`?${i.toString()}`),console.log("Redirecting to:",r),window.location.href=r}catch(r){console.error("Error during token expiration handling:",r),window.location.href="/get-started"}}async function ui(){try{let e=await(await fetch("https://api.ipinfo.io/lite/me?token=37dcb37ab0fb46")).json();return console.log("Country code:",e.country_code),e.country_code||null}catch(s){return console.error("\u274C Geolocation API call failed->",s),null}}async function hi(s,e,t,r){localStorage.getItem("conversion_sent")||(W("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:s,dub_id:e,referral:t,email:r}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"))}async function di(s,e,t){if(s&&e)try{let r=await ui(),i=`https://api.wisprflow.ai/api/v1/payment/create-checkout-session?plan=${s}&custom_redirect=true`;r==="GB"&&(i+="&currency=gbp",console.log("\u{1F1EC}\u{1F1E7} UK user detected"));let o=await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:e}})).json();console.log("Checkout details:",o);let{url:a}=o,l=t?`/downloads?referral=${t}`:"/downloads";window.history.pushState({},"",l),localStorage.setItem("checkout_plan",s),W("stripe_checkout_redirect",{plan:s,email:localStorage.getItem("email"),device_type:window.userPlatform,source:"downloads_page"}),window.open(a,"_blank"),document.body.innerHTML=`<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh;"><h3>Redirecting to checkout...</h3><div class="spacer-medium"></div><p class="text-size-medium">If you were not redirected automatically, <a href=${a} target="_blank">click here.</a></p></div>`}catch(r){console.error("Checkout error:",r)}}function fi(s,e){let t=s,r=setInterval(()=>{t--;let i=document.getElementById("countdown");i&&(i.textContent=t.toString()),t<=0&&(clearInterval(r),window.location.href=e)},1e3)}function pi(s){if(s.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"});return}s.referral_status&&(s.referral_status.referral_code_valid?s.referral_status.was_previously_referred===!0?document.querySelectorAll("[already-referred-div]").forEach(t=>{t.style.display="block"}):s.referral_status.user_exists===!0?document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}):document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Invalid referral code."?document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Cannot refer yourself."&&document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}))}function is(s){let e=s==="mac_m1"||s==="mac_intel",t=s==="Windows",r=s==="iOS";if(e){document.querySelectorAll("[mac]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[header-content]").forEach(a=>{a.style.display="block"});let o=document.querySelector(`[active-download="${s}"]`);o&&o.href&&document.querySelectorAll("[download-link]").forEach(l=>{l.href=o.href}),setTimeout(()=>{let a=document.querySelector(`[active-download="${s}"]`);a&&(window.location.href=a.href,a.onclick&&(ye=!0,a.onclick.call(a,new MouseEvent("click")),ye=!1))},500)}else if(t){document.querySelectorAll("[windows]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[header-content]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[windows-card]").forEach(l=>{l.style.display="none"});let a=document.querySelector('[active-download="windows"]');a&&a.href&&document.querySelectorAll("[download-link]").forEach(u=>{u.href=a.href}),setTimeout(()=>{let l=document.querySelector('[active-download="windows"]');l&&(window.location.href=l.href,l.onclick&&(ye=!0,l.onclick.call(l,new MouseEvent("click")),ye=!1))},500)}else if(r){document.querySelectorAll("[header-content]").forEach(c=>{c.style.display="block"});let n=document.querySelector("[default-h1]");n&&(n.textContent="Download Flow for iOS");let o=document.querySelector("[default-para]");o&&(o.textContent="Download the iOS app and use voice dictation anywhere\u2014texts, emails, DMs, and more."),document.querySelectorAll("[ios-download]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(c=>{c.style.display="none"}),document.querySelectorAll("[fallback-download]").forEach(c=>{c.style.display="none"})}else s==="mac_unknown"?document.querySelectorAll("[mac-unknown]").forEach(n=>{n.style.display="block"}):s==="win_unknown"||s==="Unknown"?(document.querySelectorAll("[all-download-cards]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(a=>{a.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(a=>{a.style.display="none"}),s==="win_unknown"&&document.querySelectorAll("[win-unknown]").forEach(l=>{l.style.display="block"})):(document.querySelectorAll("[not-available]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[all-download-cards]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(l=>{l.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(l=>{l.style.display="none"}))}})();
7
+ `;let ns=t?`/downloads?referral=${t}`:"/downloads";fi(3,ns)}else{let ve=r;wt.is_student===!0&&(r.endsWith("MONTHLY")?ve="FLOW_STUDENT_MONTHLY":r.endsWith("YEARLY")&&(ve="FLOW_STUDENT_YEARLY")),await di(ve,l,t)}}else{console.log("Subscription API failed: Non-200 status"),await Vt(r,t,a);return}}catch(z){console.error("Status check error:",z),await Vt(r,t,a);return}return}clearTimeout(o),document.body.style.visibility="visible",r||is(c)}catch(w){n=!0,clearTimeout(o),window.location.href="/get-started",console.error("Error during session setup:",w)}else localStorage.getItem("email")?(d.textContent=`Hi ${localStorage.getItem("email")}!`,f.style.display="flex",clearTimeout(o),document.body.style.visibility="visible",r||is(c)):(n=!0,clearTimeout(o),window.location.href="/get-started");document.querySelectorAll("[active-download]").forEach(function(w){if(!c.startsWith("mac")&&w.getAttribute("active-download")?.startsWith("mac")){w.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;W("app_waitlist",{device_type:w.getAttribute("active-download")});let I={email:localStorage.getItem("email"),device_type:w.getAttribute("active-download")||"unknown"};return Ve.addToWaitlist(I),w.innerText="We emailed you the download link!",!1};return}w.onclick=()=>(W("app_download",{device_type:c,download_type:w.getAttribute("active-download"),auto_download:ye,source:"downloads-page",email:localStorage.getItem("email")||"not-found"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",device_type:c,download_type:w.getAttribute("active-download"),auto_download:ye,source:"downloads-page"}),!0)}),document.querySelectorAll("[download-link]").forEach(function(w){w.onclick=()=>(W("app_download",{device_type:c,source:"downloads-page-fallback",email:localStorage.getItem("email")||"not-found"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_download",device_type:c,download_type:c,auto_download:!1,source:"downloads-page-fallback"}),!0)}),document.querySelectorAll("[waitlist]").forEach(function(w){w.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;W("app_waitlist",{device_type:w.getAttribute("waitlist")});let I={email:localStorage.getItem("email"),device_type:w.getAttribute("waitlist")||"unknown"};return Ve.addToWaitlist(I),w.innerText="You're on the waitlist!",!1}});let b=document.querySelector("[download-email-form]");b&&(b.removeAttribute("action"),b.addEventListener("submit",async w=>{w.preventDefault(),w.stopPropagation();let M=b.querySelector("[email-input]"),I=b.querySelector("[platform-name]"),C=b.querySelector('input[type="submit"]');if(!M||!I||!C){console.error("Form fields not found");return}let L=M.value.trim(),F=I.value.trim();if(!L||!F){console.error("Email or platform is empty");return}C.value="Please wait...",C.classList.add("pointer-events-none");try{let we=await fetch("https://api.wisprflow.ai/api/v1/referral/download-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:F,recipient_email:L})});if(we.ok){console.log("Email sent successfully");let $=document.querySelector("[success-div]");$&&($.style.display="block"),b.style.display="none",C.classList.remove("pointer-events-none"),W("download_link_email_success",{platform_requested:F,email:L,source:"downloads_page_form",device_type:c})}else{console.error("API error:",we.status);let $=document.querySelector("[error-div]");$&&($.style.display="block"),C.classList.remove("pointer-events-none")}}catch(we){console.error("Network error:",we);let $=document.querySelector("[error-div]");$&&($.style.display="block"),C.classList.remove("pointer-events-none")}})),f.addEventListener("click",async()=>{try{await a.signOut(),localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),n=!0,clearTimeout(o),window.location.href="/get-started"}catch(w){console.error("Error during sign-out:",w)}})});async function Vt(s,e,t){console.log("Handling token expiration - logging out user");try{await t.signOut(),localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status");let r="/get-started",i=new URLSearchParams,o=new URLSearchParams(window.location.search).get("utm_source");e&&i.append("referral",e),s&&i.append("plan",s),o&&i.append("utm_source",o),i.toString()&&(r+=`?${i.toString()}`),console.log("Redirecting to:",r),window.location.href=r}catch(r){console.error("Error during token expiration handling:",r),window.location.href="/get-started"}}async function ui(){try{let e=await(await fetch("https://api.ipinfo.io/lite/me?token=37dcb37ab0fb46")).json();return console.log("Country code:",e.country_code),e.country_code||null}catch(s){return console.error("\u274C Geolocation API call failed->",s),null}}async function hi(s,e,t,r){localStorage.getItem("conversion_sent")||(W("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:s,dub_id:e,referral:t,email:r}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"))}async function di(s,e,t){if(s&&e)try{let r=await ui(),i=`https://api.wisprflow.ai/api/v1/payment/create-checkout-session?plan=${s}&custom_redirect=true`;r==="GB"&&(i+="&currency=gbp",console.log("\u{1F1EC}\u{1F1E7} UK user detected"));let o=await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:e}})).json();console.log("Checkout details:",o);let{url:a}=o,l=t?`/downloads?referral=${t}`:"/downloads";window.history.pushState({},"",l),localStorage.setItem("checkout_plan",s),W("stripe_checkout_redirect",{plan:s,email:localStorage.getItem("email"),device_type:window.userPlatform,source:"downloads_page"}),window.open(a,"_blank"),document.body.innerHTML=`<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh;"><h3>Redirecting to checkout...</h3><div class="spacer-medium"></div><p class="text-size-medium">If you were not redirected automatically, <a href=${a} target="_blank">click here.</a></p></div>`}catch(r){console.error("Checkout error:",r)}}function fi(s,e){let t=s,r=setInterval(()=>{t--;let i=document.getElementById("countdown");i&&(i.textContent=t.toString()),t<=0&&(clearInterval(r),window.location.href=e)},1e3)}function pi(s){if(s.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"});return}s.referral_status&&(s.referral_status.referral_code_valid?s.referral_status.was_previously_referred===!0?document.querySelectorAll("[already-referred-div]").forEach(t=>{t.style.display="block"}):s.referral_status.user_exists===!0?document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}):document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Invalid referral code."?document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Cannot refer yourself."&&document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}))}function is(s){let e=s==="mac_m1"||s==="mac_intel",t=s==="Windows",r=s==="iOS";if(e){document.querySelectorAll("[mac]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[header-content]").forEach(a=>{a.style.display="block"});let o=document.querySelector(`[active-download="${s}"]`);o&&o.href&&document.querySelectorAll("[download-link]").forEach(l=>{l.href=o.href}),setTimeout(()=>{let a=document.querySelector(`[active-download="${s}"]`);a&&(window.location.href=a.href,a.onclick&&(ye=!0,a.onclick.call(a,new MouseEvent("click")),ye=!1))},500)}else if(t){document.querySelectorAll("[windows]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[header-content]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[windows-card]").forEach(l=>{l.style.display="none"});let a=document.querySelector('[active-download="windows"]');a&&a.href&&document.querySelectorAll("[download-link]").forEach(u=>{u.href=a.href}),setTimeout(()=>{let l=document.querySelector('[active-download="windows"]');l&&(window.location.href=l.href,l.onclick&&(ye=!0,l.onclick.call(l,new MouseEvent("click")),ye=!1))},500)}else if(r){document.querySelectorAll("[header-content]").forEach(c=>{c.style.display="block"});let n=document.querySelector("[default-h1]");n&&(n.textContent="Download Flow for iOS");let o=document.querySelector("[default-para]");o&&(o.textContent="Download the iOS app and use voice dictation anywhere\u2014texts, emails, DMs, and more."),document.querySelectorAll("[ios-download]").forEach(c=>{c.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(c=>{c.style.display="none"}),document.querySelectorAll("[fallback-download]").forEach(c=>{c.style.display="none"})}else s==="mac_unknown"?document.querySelectorAll("[mac-unknown]").forEach(n=>{n.style.display="block"}):s==="win_unknown"||s==="Unknown"?(document.querySelectorAll("[all-download-cards]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(a=>{a.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(a=>{a.style.display="none"}),s==="win_unknown"&&document.querySelectorAll("[win-unknown]").forEach(l=>{l.style.display="block"})):(document.querySelectorAll("[not-available]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[all-download-cards]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(l=>{l.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(l=>{l.style.display="none"}))}})();
@@ -1 +1 @@
1
- "use strict";(()=>{if(window.location.pathname.startsWith("/r/")){let o=document.querySelector(".utility-page_component"),t=window.location.pathname.split("/r/")[1];if(o){o.innerHTML="";let e=document.createElement("h2");e.className="h2-small line-height-large text-color-purple";let a=document.createElement("span");a.className="text-color-linear",a.textContent="Adding a referral for ";let n=document.createElement("span");n.className="loading-dots",e.appendChild(a),e.appendChild(document.createTextNode(t)),e.appendChild(n),o.appendChild(e)}if(t&&t!==""){let e=new URL("/get-started",window.location.origin);e.searchParams.set("referral",t),new URLSearchParams(window.location.search).forEach((n,r)=>{e.searchParams.set(r,n)}),window.location.href=e.toString()}}})();
1
+ "use strict";(()=>{if(window.location.pathname.startsWith("/r/")){let r=document.querySelector(".utility-page_component"),a=window.location.pathname.split("/r/")[1];if(r){r.innerHTML="";let e=document.createElement("h2");e.className="h2-small line-height-large text-color-purple";let t=document.createElement("span");t.className="text-color-linear",t.textContent="Adding a referral for ";let n=document.createElement("span");n.className="loading-dots",e.appendChild(t),e.appendChild(document.createTextNode(a)),e.appendChild(n),r.appendChild(e)}if(a&&a!==""){let e=new URL("/get-started",window.location.origin);e.searchParams.set("referral",a),e.searchParams.set("utm_source","referral"),new URLSearchParams(window.location.search).forEach((n,o)=>{e.searchParams.set(o,n)}),window.location.href=e.toString()}}})();
package/dist/signup.js CHANGED
@@ -1 +1 @@
1
- "use strict";(()=>{var Kr=Object.create;var De=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,Yr=Object.prototype.hasOwnProperty;var Zr=(s,e)=>()=>(s&&(e=s(s=0)),e);var C=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),es=(s,e)=>{for(var t in e)De(s,t,{get:e[t],enumerable:!0})},Ft=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Qr(e))!Yr.call(s,i)&&i!==t&&De(s,i,{get:()=>e[i],enumerable:!(r=Vr(e,i))||r.enumerable});return s};var Mt=(s,e,t)=>(t=s!=null?Kr(Xr(s)):{},Ft(e||!s||!s.__esModule?De(t,"default",{value:s,enumerable:!0}):t,s)),ts=s=>Ft(De({},"__esModule",{value:!0}),s);var B={};es(B,{Headers:()=>ht,Request:()=>is,Response:()=>ns,default:()=>lt,fetch:()=>ss});var rs,te,ss,lt,ht,is,ns,N=Zr(()=>{"use strict";rs=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")},te=rs(),ss=te.fetch,lt=te.fetch.bind(te),ht=te.Headers,is=te.Request,ns=te.Response});var Wt=C(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});var ut=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};dt.default=ut});var pt=C(fe=>{"use strict";var zt=fe&&fe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(fe,"__esModule",{value:!0});var as=zt((N(),ts(B))),cs=zt(Wt()),ft=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=as.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=k:l=JSON.parse(k))}let y=(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("/");y&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{h=JSON.parse(y),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&y===""?(d=204,f="No Content"):h={message:y}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new cs.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};fe.default=ft});var mt=C(pe=>{"use strict";var ls=pe&&pe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pe,"__esModule",{value:!0});var hs=ls(pt()),gt=class extends hs.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"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=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};pe.default=gt});var He=C(ge=>{"use strict";var us=ge&&ge.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ge,"__esModule",{value:!0});var ds=us(mt()),_t=class extends ds.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};ge.default=_t});var vt=C(_e=>{"use strict";var fs=_e&&_e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_e,"__esModule",{value:!0});var me=fs(He()),yt=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new me.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new me.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new me.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new me.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new me.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};_e.default=yt});var Kt=C(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.version=void 0;Je.version="0.0.0-automated"});var Vt=C(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.DEFAULT_HEADERS=void 0;var ps=Kt();Ge.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ps.version}`}});var Xt=C(ye=>{"use strict";var Qt=ye&&ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ye,"__esModule",{value:!0});var gs=Qt(vt()),ms=Qt(He()),_s=Vt(),wt=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},_s.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new gs.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new ms.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ye.default=wt});var sr=C(E=>{"use strict";var ve=E&&E.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(E,"__esModule",{value:!0});E.PostgrestBuilder=E.PostgrestTransformBuilder=E.PostgrestFilterBuilder=E.PostgrestQueryBuilder=E.PostgrestClient=void 0;var Yt=ve(Xt());E.PostgrestClient=Yt.default;var Zt=ve(vt());E.PostgrestQueryBuilder=Zt.default;var er=ve(He());E.PostgrestFilterBuilder=er.default;var tr=ve(mt());E.PostgrestTransformBuilder=tr.default;var rr=ve(pt());E.PostgrestBuilder=rr.default;E.default={PostgrestClient:Yt.default,PostgrestQueryBuilder:Zt.default,PostgrestFilterBuilder:er.default,PostgrestTransformBuilder:tr.default,PostgrestBuilder:rr.default}});var dr=C((Mi,ur)=>{"use strict";ur.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Ne="https://api.wisprflow.ai",ct=class{static async signupUser(e){try{let t=`${Ne}/signup`,i=document.cookie.split(";").find(o=>o.trim().startsWith("trial_promo="));i&&i.trim().split("=")[1]==="3mo"&&(t+="?trial_promo=3mo");let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Signup failed with status ${n.status}`);return console.log("User signed up successfully"),await n.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${Ne}/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(`${Ne}/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(`${Ne}/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}}};var qt=ct;var Bt=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Ht=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var Jt=()=>{let{access_token:s,refresh_token:e}=Ht(),t=s,r=e;if(!t||!r){let i=Bt();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var Gt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(N(),B)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ue=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Fe=class extends ue{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Me=class extends ue{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},qe=class extends ue{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Be;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Be||(Be={}));var os=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},de=class{constructor(e,{headers:t={},customFetch:r,region:i=Be.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Gt(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return os(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",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 l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(_=>{throw new Fe(_)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new Me(l);if(!l.ok)throw new qe(l);let d=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var ir=Mt(sr(),1),{PostgrestClient:nr,PostgrestQueryBuilder:bi,PostgrestFilterBuilder:ki,PostgrestTransformBuilder:Si,PostgrestBuilder:Ei}=ir.default;var or="2.10.2";var ar={"X-Client-Info":`realtime-js/${or}`},cr="1.0.0",ze=1e4,lr=1e3,H;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(H||(H={}));var x;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(x||(x={}));var T;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(T||(T={}));var We;(function(s){s.websocket="websocket"})(We||(We={}));var F;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(F||(F={}));var we=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let c=r.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var J=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 v;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(v||(v={}));var kt=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=ys(o,s,e,i),n),{})},ys=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?hr(n,o):bt(o)},hr=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return ks(e,t)}switch(s){case v.bool:return vs(e);case v.float4:case v.float8:case v.int2:case v.int4:case v.int8:case v.numeric:case v.oid:return ws(e);case v.json:case v.jsonb:return bs(e);case v.timestamp:return Ss(e);case v.abstime:case v.date:case v.daterange:case v.int4range:case v.int8range:case v.money:case v.reltime:case v.text:case v.time:case v.timestamptz:case v.timetz:case v.tsrange:case v.tstzrange:return bt(e);default:return bt(e)}},bt=s=>s,vs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},ws=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},bs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},ks=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>hr(e,a))}return s},Ss=s=>typeof s=="string"?s.replace(" ","T"):s,Ke=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var G=class{constructor(e,t,r={},i=ze){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var St;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(St||(St={}));var re=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=s.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(m=>m.presence_ref),f=u.map(m=>m.presence_ref),_=l.filter(m=>f.indexOf(m.presence_ref)<0),y=u.filter(m=>d.indexOf(m.presence_ref)<0);_.length>0&&(a[h]=_),y.length>0&&(c[h]=y)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}r(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Et;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Et||(Et={}));var xt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(xt||(xt={}));var Tt;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Tt||(Tt={}));var se=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=x.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 G(this,T.join,this.params,this.timeout),this.rejoinTimer=new J(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=x.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=x.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this._on(T.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new re(this),this.broadcastEndpointURL=Ke(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let y=0;y<f;y++){let m=d[y],{filter:{event:k,schema:A,table:j,filter:w}}=m,S=l&&l[y];if(S&&S.event===k&&S.schema===A&&S.table===j&&S.filter===w)_.push(Object.assign(Object.assign({},m),{id:S.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),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=x.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(T.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new G(this,T.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new G(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=T;if(r&&[a,c,h,l].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(f=>{var _,y,m;return((_=f.filter)===null||_===void 0?void 0:_.event)==="*"||((m=(y=f.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var _,y,m,k,A,j;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let w=f.id,S=(_=f.filter)===null||_===void 0?void 0:_.event;return w&&((y=t.ids)===null||y===void 0?void 0:y.includes(w))&&(S==="*"||S?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let w=(A=(k=f?.filter)===null||k===void 0?void 0:k.event)===null||A===void 0?void 0:A.toLocaleLowerCase();return w==="*"||w===((j=t?.event)===null||j===void 0?void 0:j.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:y,table:m,commit_timestamp:k,type:A,errors:j}=_;d=Object.assign(Object.assign({},{schema:y,table:m,commit_timestamp:k,eventType:A,new:{},old:{},errors:j}),this._getPayloadRecords(_))}f.callback(d,r)})}_isClosed(){return this.state===x.closed}_isJoined(){return this.state===x.joined}_isJoining(){return this.state===x.joining}_isLeaving(){return this.state===x.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(T.close,{},e)}_onError(e){this._on(T.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=x.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=kt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=kt(e.columns,e.old_record)),t}};var xs=()=>{},Ts=typeof WebSocket<"u",ie=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ar,this.params={},this.timeout=ze,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=xs,this.conn=null,this.sendBuffer=[],this.serializer=new we,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(N(),B)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${We.websocket}`,this.httpEndpoint=Ke(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new J(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(Ts){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new At(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Mt(dr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case H.connecting:return F.Connecting;case H.open:return F.Open;case H.closing:return F.Closing;default:return F.Closed}}isConnected(){return this.connectionState()===F.Open}channel(e,t={config:{}}){let r=new se(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(T.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:cr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(T.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(lr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},At=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=H.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var ne=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function b(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Ve=class extends ne{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},be=class extends ne{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var As=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Qe=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(N(),B)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},fr=()=>As(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(N(),B))).Response:Response});var oe=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Ot=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Os=(s,e)=>oe(void 0,void 0,void 0,function*(){let t=yield fr();s instanceof t?s.json().then(r=>{e(new Ve(Ot(r),s.status||500))}).catch(r=>{e(new be(Ot(r),r))}):e(new be(Ot(s),s))}),Ps=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function Xe(s,e,t,r,i,n){return oe(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,Ps(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Os(c,a))})})}function ke(s,e,t,r){return oe(this,void 0,void 0,function*(){return Xe(s,"GET",e,t,r)})}function $(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Xe(s,"POST",e,r,i,t)})}function pr(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Xe(s,"PUT",e,r,i,t)})}function Ye(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Xe(s,"DELETE",e,r,i,t)})}var P=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Rs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},gr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Se=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Qe(i)}uploadOrUpdate(e,t,r,i){return P(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},gr),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(b(n))return{data:null,error:n};throw n}})}upload(e,t,r){return P(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return P(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:gr.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",h.cacheControl)):(c=r,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(b(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return P(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield $(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ne("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}update(e,t,r){return P(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return P(this,void 0,void 0,function*(){try{return{data:yield $(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}copy(e,t,r){return P(this,void 0,void 0,function*(){try{return{data:{path:(yield $(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return P(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield $(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return P(this,void 0,void 0,function*(){try{let i=yield $(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}download(e,t){return P(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield ke(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(b(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return P(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}list(e,t,r){return P(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Rs),t),{prefix:e||""});return{data:yield $(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var mr="2.6.0";var _r={"X-Client-Info":`storage-js/${mr}`};var ae=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Ee=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},_r),t),this.fetch=Qe(r)}listBuckets(){return ae(this,void 0,void 0,function*(){try{return{data:yield ke(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(b(e))return{data:null,error:e};throw e}})}getBucket(e){return ae(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(b(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ae(this,void 0,void 0,function*(){try{return{data:yield $(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return ae(this,void 0,void 0,function*(){try{return{data:yield pr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}emptyBucket(e){return ae(this,void 0,void 0,function*(){try{return{data:yield $(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ae(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}};var xe=class extends Ee{constructor(e,t={},r){super(e,t,r)}from(e){return new Se(this.url,this.headers,e,this.fetch)}};var yr="2.44.4";var Te="";typeof Deno<"u"?Te="deno":typeof document<"u"?Te="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Te="react-native":Te="node";var js={"X-Client-Info":`supabase-js-${Te}/${yr}`},vr={headers:js},wr={schema:"public"},br={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},kr={};N();var Cs=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},$s=s=>{let e;return s?e=s:typeof fetch>"u"?e=lt:e=fetch,(...t)=>e(...t)},Is=()=>typeof Headers>"u"?ht:Headers,Sr=(s,e,t)=>{let r=$s(t),i=Is();return(n,o)=>Cs(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",s),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};function Er(s){return s.replace(/\/$/,"")}function xr(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}var Ze="2.64.4";var Tr="http://localhost:9999",Ar="supabase.auth.token";var Or={"X-Client-Info":`gotrue-js/${Ze}`},Pt=10;var Ae="X-Supabase-Api-Version",Rt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Pr(s){return Math.round(Date.now()/1e3)+s}function Rr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var R=()=>typeof document<"u",W={tested:!1,writable:!1},M=()=>{if(!R())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(W.tested)return W.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),W.tested=!0,W.writable=!0}catch{W.tested=!0,W.writable=!1}return W.writable};function et(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var tt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(N(),B)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},jr=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",jt=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Pe=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},rt=async(s,e)=>{await s.removeItem(e)};function Ls(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,h,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),h=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Oe=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Oe.promiseConstructor=Promise;function Ct(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Ls(r))}async function Cr(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function $r(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Us(s){return("0"+s.toString(16)).substr(-2)}function Ds(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Us).join("")}async function Ns(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Fs(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ms(s){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."),s;let t=await Ns(s);return Fs(t)}async function z(s,e,t=!1){let r=Ds(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await jt(s,`${e}-code-verifier`,i);let n=await Ms(r);return[n,r===n?"plain":"s256"]}var qs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ir(s){let e=s.headers.get(Ae);if(!e||!e.match(qs))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Re=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function p(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var st=class extends Re{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Lr(s){return p(s)&&s.name==="AuthApiError"}var ce=class extends Re{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},U=class extends Re{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},I=class extends U{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},le=class extends U{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},K=class extends U{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},V=class extends U{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}}},je=class extends U{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},he=class extends U{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function it(s){return p(s)&&s.name==="AuthRetryableFetchError"}var Ce=class extends U{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Bs=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Q=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Hs=[502,503,504];async function Ur(s){var e;if(!jr(s))throw new he(Q(s),0);if(Hs.includes(s.status))throw new he(Q(s),s.status);let t;try{t=await s.json()}catch(n){throw new ce(Q(n),n)}let r,i=Ir(s);if(i&&i.getTime()>=Rt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Ce(Q(t),s.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 Ce(Q(t),s.status,t.weak_password.reasons);throw new st(Q(t),s.status||500,r)}var Js=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function g(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Ae]||(n[Ae]=Rt["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Gs(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Gs(s,e,t,r,i,n){let o=Js(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new he(Q(c),0)}if(a.ok||await Ur(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await Ur(c)}}function D(s){var e;let t=null;Ws(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Pr(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function $t(s){let e=D(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function L(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Dr(s){return{data:s,error:null}}function Nr(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Bs(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Fr(s){return s}function Ws(s){return s.access_token&&s.refresh_token&&s.expires_in}var zs=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},X=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=tt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(p(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:L})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=zs(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Nr,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:L})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Fr});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(_=>{let y=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(_.split(";")[1].split("=")[1]);h[`${m}Page`]=y}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:L})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:L})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:L})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var Mr={getItem:s=>M()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{M()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{M()&&globalThis.localStorage.removeItem(s)}};function It(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function qr(){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 Y={debug:!!(globalThis&&M()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},$e=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},nt=class extends $e{};async function Lt(s,e,t){Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Y.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new nt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Y.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()}})}qr();var Ks={url:Tr,storageKey:Ar,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Or,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ie=30*1e3,Br=3;async function Hr(s,e,t){return await t()}var Z=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&R()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},Ks),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new X({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=tt(i.fetch),this.lock=i.lock||Hr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:R()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Lt:this.lock=Hr,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:M()?this.storage=Mr:(this.memoryStorage={},this.storage=It(this.memoryStorage)):(this.memoryStorage={},this.storage=It(this.memoryStorage)),R()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Ze}) ${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=R()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return p(e)?{error:e}:{error:new ce("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:D}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,_=null;this.flowType==="pkce"&&([f,_]=await z(this.storage,this.storageKey)),n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:_},xform:D})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:D})}else throw new K("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(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 g(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:$t})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await g(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:$t})}else throw new K("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new le}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Pe(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:D});return await rt(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 le}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:D}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new le}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await z(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new K("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:D});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await z(this.storage,this.storageKey)),await g(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Dr})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new I;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await g(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await g(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new K("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Pe(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!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(c,h,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:L}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new I}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:L})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new I;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await z(this.storage,this.storageKey));let{data:h,error:l}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:L});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return Ct(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 I;let t=Date.now()/1e3,r=t,i=!0,n=null,o=Ct(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new I;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!R())throw new V("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new V("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new je("Not a valid PKCE flow url.");let t=et(window.location.href);if(e){if(!t.code)throw new je("No code detected.");let{data:A,error:j}=await this._exchangeCodeForSession(t.code);if(j)throw j;let w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:A.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new V(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new V("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=Ie&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let _=d-u;l-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,l):l-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,l);let{data:y,error:m}=await this._getUser(n);if(m)throw m;let k={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=et(window.location.href);return!!(R()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=et(window.location.href),t=await Pe(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Lr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await rt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Rr(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await z(this.storage,this.storageKey,!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await g(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return R()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(p(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await $r(async i=>(i>0&&await Cr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:D})),(i,n)=>{let o=200*Math.pow(2,i);return n&&it(n)&&Date.now()+o-r<Ie})}catch(r){if(this._debug(t,"error",r),p(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),R()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Pe(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Pt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Pt}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),it(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new I;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Oe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new I;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),p(n)){let o={session:null,error:n};return it(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await jt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await rt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&R()&&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(),Ie);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/Ie);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ie}ms, refresh threshold is ${Br} ticks`),i<=Br&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof $e)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!R()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await z(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await g(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};Z.nextInstanceID=0;var Vs=Z,Ut=Vs;var ot=class extends Ut{constructor(e){super(e)}};var Qs=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Le=class{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=Er(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:wr,realtime:kr,auth:Object.assign(Object.assign({},br),{storageKey:c}),global:vr},l=xr(r??{},h);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Sr(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new nr(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new de(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new xe(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Qs(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ot({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new ie(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Jr=(s,e,t)=>new Le(s,e,t);var ee={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var at=class{constructor(){this.sessionData=null;this.supabase=Jr(ee.supaBaseUrl,ee.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ee.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||ee.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||ee.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw this.signOut(),console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e){try{let{error:t}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:ee.redirectUri}});if(t)throw t}catch(t){throw console.error("Error sending magic link:",t),t}}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}};function Xs(){try{let s=document.createElement("canvas"),e=s.getContext("webgl")||s.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info");if(!t)return"mac_unknown";let r=e.getParameter(t.UNMASKED_RENDERER_WEBGL);console.log(`WebGL Renderer: ${r}`);let i=String(r||"").toLowerCase();return i.includes("apple gpu")?"mac_unknown":i.includes("apple")?"mac_m1":i.includes("intel")||i.includes("amd")||i.includes("nvidia")?"mac_intel":"mac_unknown"}}catch{}return"mac_unknown"}var Gr=async()=>{if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return"iOS";try{let s=await navigator.userAgentData.getHighEntropyValues(["architecture","platform"]);if(s.platform==="macOS")return s.architecture&&s.architecture.includes("arm")?"mac_m1":s.architecture&&s.architecture.includes("x86")?"mac_intel":"mac_unknown";if(s.platform==="Windows"){if(s.architecture&&s.architecture.includes("x86"))return"Windows";if(s.architecture&&s.architecture.includes("arm"))return"win_unknown";if(!s.architecture){let{userAgent:e}=navigator;return/ARM64/i.test(e)?"win_unknown":/(Win64;\s*x64|WOW64)/i.test(e)?"Windows":"win_unknown"}return"win_unknown"}return s.platform}catch{let{userAgent:s}=navigator;return s.includes("Macintosh")?Xs():s.includes("Windows")?/ARM64/i.test(s)?"win_unknown":"Windows":s.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(s)?"iOS":/Android/.test(s)?"Android":"Unknown"}};var Wr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var zr=(s,e)=>{window.posthog.capture(s,e)};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=!1,e=setTimeout(()=>{s||(document.body.style.visibility="visible")},4e3),t=new at,{accessToken:r,refreshToken:i}=Jt(),n=await Gr(),o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#google-login"),h=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),u=Wr(),{dub_id:d,referral:f,promo_code:_}=u,y=localStorage.getItem("email"),m=new URLSearchParams(window.location.search),k=m.get("referral"),A=m.get("plan"),j=m.get("code"),w=`${window.location.origin}/downloads`,S=new URLSearchParams;if(k&&S.append("referral",k),A&&S.append("plan",A),S.toString()&&(w+=`?${S.toString()}`),r&&i)try{t.setCookies(r,i);let O=t.checkAndSetSession(),q=new Promise((Nt,Ue)=>setTimeout(()=>Ue(new Error("Session timeout")),3e3));await Promise.race([O,q]);let Dt=t.sessionData?.user.email;localStorage.setItem("email",Dt),s=!0,clearTimeout(e),window.location.href=w}catch(O){console.error("Error during session setup:",O),document.body.style.visibility="visible"}else y?(s=!0,clearTimeout(e),window.location.href=w):document.body.style.visibility="visible";c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(w)}catch(O){console.error("Error during sign-in:",O)}}),h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(w)}catch(O){console.error("Error during sign-in:",O)}}),l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(w)}catch(O){console.error("Error during sign-in:",O)}}),o.addEventListener("submit",async O=>{O.stopPropagation(),O.preventDefault();let q=a.value;if(!q||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q)){console.error("Email invalid");return}let Nt={email:q,first_name:"",last_name:"",dub_click_id:d||void 0,referral:f||void 0,promo_code:_||void 0};zr("email_submission_success",{signin_provider:"email",device_type:n,dub_id:d,referral:f,email:q}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:"email"}),localStorage.setItem("email",q),localStorage.setItem("conversion_sent","true");let Ue=await qt.addRawUserEmail(Nt);Ue&&sessionStorage.setItem("referral_status",JSON.stringify(Ue)),s=!0,clearTimeout(e),window.location.href=w})});})();
1
+ "use strict";(()=>{var Vr=Object.create;var Ne=Object.defineProperty;var Qr=Object.getOwnPropertyDescriptor;var Xr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Zr=Object.prototype.hasOwnProperty;var es=(s,e)=>()=>(s&&(e=s(s=0)),e);var C=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),ts=(s,e)=>{for(var t in e)Ne(s,t,{get:e[t],enumerable:!0})},Mt=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xr(e))!Zr.call(s,i)&&i!==t&&Ne(s,i,{get:()=>e[i],enumerable:!(r=Qr(e,i))||r.enumerable});return s};var qt=(s,e,t)=>(t=s!=null?Vr(Yr(s)):{},Mt(e||!s||!s.__esModule?Ne(t,"default",{value:s,enumerable:!0}):t,s)),rs=s=>Mt(Ne({},"__esModule",{value:!0}),s);var B={};ts(B,{Headers:()=>ut,Request:()=>ns,Response:()=>os,default:()=>ht,fetch:()=>is});var ss,te,is,ht,ut,ns,os,N=es(()=>{"use strict";ss=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")},te=ss(),is=te.fetch,ht=te.fetch.bind(te),ut=te.Headers,ns=te.Request,os=te.Response});var zt=C(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});var dt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ft.default=dt});var gt=C(pe=>{"use strict";var Kt=pe&&pe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pe,"__esModule",{value:!0});var cs=Kt((N(),rs(B))),ls=Kt(zt()),pt=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=cs.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=k:l=JSON.parse(k))}let y=(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("/");y&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{h=JSON.parse(y),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&y===""?(d=204,f="No Content"):h={message:y}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new ls.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};pe.default=pt});var _t=C(ge=>{"use strict";var hs=ge&&ge.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ge,"__esModule",{value:!0});var us=hs(gt()),mt=class extends us.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"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=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};ge.default=mt});var Je=C(me=>{"use strict";var ds=me&&me.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(me,"__esModule",{value:!0});var fs=ds(_t()),yt=class extends fs.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};me.default=yt});var wt=C(ye=>{"use strict";var ps=ye&&ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ye,"__esModule",{value:!0});var _e=ps(Je()),vt=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new _e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new _e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new _e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new _e.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new _e.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ye.default=vt});var Vt=C(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.version=void 0;Ge.version="0.0.0-automated"});var Qt=C(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.DEFAULT_HEADERS=void 0;var gs=Vt();We.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${gs.version}`}});var Yt=C(ve=>{"use strict";var Xt=ve&&ve.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ve,"__esModule",{value:!0});var ms=Xt(wt()),_s=Xt(Je()),ys=Qt(),bt=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ys.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ms.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new _s.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ve.default=bt});var ir=C(S=>{"use strict";var we=S&&S.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(S,"__esModule",{value:!0});S.PostgrestBuilder=S.PostgrestTransformBuilder=S.PostgrestFilterBuilder=S.PostgrestQueryBuilder=S.PostgrestClient=void 0;var Zt=we(Yt());S.PostgrestClient=Zt.default;var er=we(wt());S.PostgrestQueryBuilder=er.default;var tr=we(Je());S.PostgrestFilterBuilder=tr.default;var rr=we(_t());S.PostgrestTransformBuilder=rr.default;var sr=we(gt());S.PostgrestBuilder=sr.default;S.default={PostgrestClient:Zt.default,PostgrestQueryBuilder:er.default,PostgrestFilterBuilder:tr.default,PostgrestTransformBuilder:rr.default,PostgrestBuilder:sr.default}});var fr=C((qi,dr)=>{"use strict";dr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Fe="https://api.wisprflow.ai",lt=class{static async signupUser(e){try{let t=`${Fe}/signup`,i=document.cookie.split(";").find(o=>o.trim().startsWith("trial_promo="));i&&i.trim().split("=")[1]==="3mo"&&(t+="?trial_promo=3mo");let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Signup failed with status ${n.status}`);return console.log("User signed up successfully"),await n.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${Fe}/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(`${Fe}/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(`${Fe}/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}}};var Bt=lt;var Ht=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Jt=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var Gt=()=>{let{access_token:s,refresh_token:e}=Jt(),t=s,r=e;if(!t||!r){let i=Ht();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var Wt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(N(),B)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var de=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Me=class extends de{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},qe=class extends de{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Be=class extends de{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},He;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(He||(He={}));var as=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},fe=class{constructor(e,{headers:t={},customFetch:r,region:i=He.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Wt(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return as(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",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 l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(_=>{throw new Me(_)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new qe(l);if(!l.ok)throw new Be(l);let d=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var nr=qt(ir(),1),{PostgrestClient:or,PostgrestQueryBuilder:ki,PostgrestFilterBuilder:Si,PostgrestTransformBuilder:Ei,PostgrestBuilder:xi}=nr.default;var ar="2.10.2";var cr={"X-Client-Info":`realtime-js/${ar}`},lr="1.0.0",Ke=1e4,hr=1e3,H;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(H||(H={}));var E;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(E||(E={}));var T;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(T||(T={}));var ze;(function(s){s.websocket="websocket"})(ze||(ze={}));var F;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(F||(F={}));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),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let c=r.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var J=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 v;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(v||(v={}));var St=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=vs(o,s,e,i),n),{})},vs=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?ur(n,o):kt(o)},ur=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return Ss(e,t)}switch(s){case v.bool:return ws(e);case v.float4:case v.float8:case v.int2:case v.int4:case v.int8:case v.numeric:case v.oid:return bs(e);case v.json:case v.jsonb:return ks(e);case v.timestamp:return Es(e);case v.abstime:case v.date:case v.daterange:case v.int4range:case v.int8range:case v.money:case v.reltime:case v.text:case v.time:case v.timestamptz:case v.timetz:case v.tsrange:case v.tstzrange:return kt(e);default:return kt(e)}},kt=s=>s,ws=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},bs=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},ks=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Ss=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>ur(e,a))}return s},Es=s=>typeof s=="string"?s.replace(" ","T"):s,Ve=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var G=class{constructor(e,t,r={},i=Ke){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Et;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Et||(Et={}));var re=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=s.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(m=>m.presence_ref),f=u.map(m=>m.presence_ref),_=l.filter(m=>f.indexOf(m.presence_ref)<0),y=u.filter(m=>d.indexOf(m.presence_ref)<0);_.length>0&&(a[h]=_),y.length>0&&(c[h]=y)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}r(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var xt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(xt||(xt={}));var Tt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(Tt||(Tt={}));var At;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(At||(At={}));var se=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=E.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 G(this,T.join,this.params,this.timeout),this.rejoinTimer=new J(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=E.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=E.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=E.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=E.errored,this.rejoinTimer.scheduleTimeout())}),this._on(T.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new re(this),this.broadcastEndpointURL=Ve(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let y=0;y<f;y++){let m=d[y],{filter:{event:k,schema:A,table:x,filter:O}}=m,w=l&&l[y];if(w&&w.event===k&&w.schema===A&&w.table===x&&w.filter===O)_.push(Object.assign(Object.assign({},m),{id:w.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),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=E.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(T.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new G(this,T.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new G(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=T;if(r&&[a,c,h,l].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(f=>{var _,y,m;return((_=f.filter)===null||_===void 0?void 0:_.event)==="*"||((m=(y=f.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var _,y,m,k,A,x;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let O=f.id,w=(_=f.filter)===null||_===void 0?void 0:_.event;return O&&((y=t.ids)===null||y===void 0?void 0:y.includes(O))&&(w==="*"||w?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let O=(A=(k=f?.filter)===null||k===void 0?void 0:k.event)===null||A===void 0?void 0:A.toLocaleLowerCase();return O==="*"||O===((x=t?.event)===null||x===void 0?void 0:x.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:y,table:m,commit_timestamp:k,type:A,errors:x}=_;d=Object.assign(Object.assign({},{schema:y,table:m,commit_timestamp:k,eventType:A,new:{},old:{},errors:x}),this._getPayloadRecords(_))}f.callback(d,r)})}_isClosed(){return this.state===E.closed}_isJoined(){return this.state===E.joined}_isJoining(){return this.state===E.joining}_isLeaving(){return this.state===E.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(T.close,{},e)}_onError(e){this._on(T.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=E.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=St(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=St(e.columns,e.old_record)),t}};var Ts=()=>{},As=typeof WebSocket<"u",ie=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=cr,this.params={},this.timeout=Ke,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Ts,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(()=>(N(),B)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${ze.websocket}`,this.httpEndpoint=Ve(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new J(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(As){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Ot(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>qt(fr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case H.connecting:return F.Connecting;case H.open:return F.Open;case H.closing:return F.Closing;default:return F.Closed}}isConnected(){return this.connectionState()===F.Open}channel(e,t={config:{}}){let r=new se(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(T.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:lr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(T.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(hr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Ot=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=H.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var ne=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function b(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Qe=class extends ne{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ke=class extends ne{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Os=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Xe=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(N(),B)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},pr=()=>Os(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(N(),B))).Response:Response});var oe=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Pt=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Ps=(s,e)=>oe(void 0,void 0,void 0,function*(){let t=yield pr();s instanceof t?s.json().then(r=>{e(new Qe(Pt(r),s.status||500))}).catch(r=>{e(new ke(Pt(r),r))}):e(new ke(Pt(s),s))}),Rs=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function Ye(s,e,t,r,i,n){return oe(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,Rs(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Ps(c,a))})})}function Se(s,e,t,r){return oe(this,void 0,void 0,function*(){return Ye(s,"GET",e,t,r)})}function $(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Ye(s,"POST",e,r,i,t)})}function gr(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Ye(s,"PUT",e,r,i,t)})}function Ze(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Ye(s,"DELETE",e,r,i,t)})}var R=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},js={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},mr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ee=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Xe(i)}uploadOrUpdate(e,t,r,i){return R(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},mr),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(b(n))return{data:null,error:n};throw n}})}upload(e,t,r){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return R(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:mr.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",h.cacheControl)):(c=r,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(b(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return R(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield $(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ne("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}update(e,t,r){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return R(this,void 0,void 0,function*(){try{return{data:yield $(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}copy(e,t,r){return R(this,void 0,void 0,function*(){try{return{data:{path:(yield $(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return R(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield $(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return R(this,void 0,void 0,function*(){try{let i=yield $(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}download(e,t){return R(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Se(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(b(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return R(this,void 0,void 0,function*(){try{return{data:yield Ze(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}list(e,t,r){return R(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},js),t),{prefix:e||""});return{data:yield $(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var _r="2.6.0";var yr={"X-Client-Info":`storage-js/${_r}`};var ae=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},xe=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},yr),t),this.fetch=Xe(r)}listBuckets(){return ae(this,void 0,void 0,function*(){try{return{data:yield Se(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(b(e))return{data:null,error:e};throw e}})}getBucket(e){return ae(this,void 0,void 0,function*(){try{return{data:yield Se(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ae(this,void 0,void 0,function*(){try{return{data:yield $(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return ae(this,void 0,void 0,function*(){try{return{data:yield gr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}emptyBucket(e){return ae(this,void 0,void 0,function*(){try{return{data:yield $(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ae(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(b(t))return{data:null,error:t};throw t}})}};var Te=class extends xe{constructor(e,t={},r){super(e,t,r)}from(e){return new Ee(this.url,this.headers,e,this.fetch)}};var vr="2.44.4";var Ae="";typeof Deno<"u"?Ae="deno":typeof document<"u"?Ae="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ae="react-native":Ae="node";var Cs={"X-Client-Info":`supabase-js-${Ae}/${vr}`},wr={headers:Cs},br={schema:"public"},kr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Sr={};N();var $s=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Is=s=>{let e;return s?e=s:typeof fetch>"u"?e=ht:e=fetch,(...t)=>e(...t)},Ls=()=>typeof Headers>"u"?ut:Headers,Er=(s,e,t)=>{let r=Is(t),i=Ls();return(n,o)=>$s(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",s),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};function xr(s){return s.replace(/\/$/,"")}function Tr(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}var et="2.64.4";var Ar="http://localhost:9999",Or="supabase.auth.token";var Pr={"X-Client-Info":`gotrue-js/${et}`},Rt=10;var Oe="X-Supabase-Api-Version",jt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Rr(s){return Math.round(Date.now()/1e3)+s}function jr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var j=()=>typeof document<"u",W={tested:!1,writable:!1},M=()=>{if(!j())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(W.tested)return W.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),W.tested=!0,W.writable=!0}catch{W.tested=!0,W.writable=!1}return W.writable};function tt(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var rt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(N(),B)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Cr=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Ct=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Re=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},st=async(s,e)=>{await s.removeItem(e)};function Us(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,h,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),h=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Pe=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Pe.promiseConstructor=Promise;function $t(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Us(r))}async function $r(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Ir(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Ds(s){return("0"+s.toString(16)).substr(-2)}function Ns(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Ds).join("")}async function Fs(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Ms(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qs(s){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."),s;let t=await Fs(s);return Ms(t)}async function z(s,e,t=!1){let r=Ns(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Ct(s,`${e}-code-verifier`,i);let n=await qs(r);return[n,r===n?"plain":"s256"]}var Bs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Lr(s){let e=s.headers.get(Oe);if(!e||!e.match(Bs))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var je=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function p(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var it=class extends je{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Ur(s){return p(s)&&s.name==="AuthApiError"}var ce=class extends je{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},U=class extends je{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},I=class extends U{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},le=class extends U{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},K=class extends U{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},V=class extends U{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}}},Ce=class extends U{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},he=class extends U{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function nt(s){return p(s)&&s.name==="AuthRetryableFetchError"}var $e=class extends U{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Hs=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Q=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Js=[502,503,504];async function Dr(s){var e;if(!Cr(s))throw new he(Q(s),0);if(Js.includes(s.status))throw new he(Q(s),s.status);let t;try{t=await s.json()}catch(n){throw new ce(Q(n),n)}let r,i=Lr(s);if(i&&i.getTime()>=jt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new $e(Q(t),s.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 $e(Q(t),s.status,t.weak_password.reasons);throw new it(Q(t),s.status||500,r)}var Gs=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function g(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Oe]||(n[Oe]=jt["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Ws(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Ws(s,e,t,r,i,n){let o=Gs(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new he(Q(c),0)}if(a.ok||await Dr(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await Dr(c)}}function D(s){var e;let t=null;zs(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Rr(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function It(s){let e=D(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function L(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Nr(s){return{data:s,error:null}}function Fr(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Hs(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Mr(s){return s}function zs(s){return s.access_token&&s.refresh_token&&s.expires_in}var Ks=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},X=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=rt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(p(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:L})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Ks(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Fr,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:L})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Mr});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(_=>{let y=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(_.split(";")[1].split("=")[1]);h[`${m}Page`]=y}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:L})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:L})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:L})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var qr={getItem:s=>M()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{M()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{M()&&globalThis.localStorage.removeItem(s)}};function Lt(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function Br(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var Y={debug:!!(globalThis&&M()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ie=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ot=class extends Ie{};async function Ut(s,e,t){Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Y.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw Y.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ot(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Y.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()}})}Br();var Vs={url:Ar,storageKey:Or,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Le=30*1e3,Hr=3;async function Jr(s,e,t){return await t()}var Z=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&j()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},Vs),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new X({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=rt(i.fetch),this.lock=i.lock||Jr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:j()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Ut:this.lock=Jr,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:M()?this.storage=qr:(this.memoryStorage={},this.storage=Lt(this.memoryStorage)):(this.memoryStorage={},this.storage=Lt(this.memoryStorage)),j()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${et}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=j()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return p(e)?{error:e}:{error:new ce("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:D}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,_=null;this.flowType==="pkce"&&([f,_]=await z(this.storage,this.storageKey)),n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:_},xform:D})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:D})}else throw new K("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(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 g(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:It})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await g(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:It})}else throw new K("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new le}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Re(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:D});return await st(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 le}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:D}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new le}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await z(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new K("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:D});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await z(this.storage,this.storageKey)),await g(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Nr})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new I;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await g(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await g(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new K("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Re(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!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(c,h,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:L}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new I}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:L})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new I;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await z(this.storage,this.storageKey));let{data:h,error:l}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:L});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return $t(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 I;let t=Date.now()/1e3,r=t,i=!0,n=null,o=$t(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new I;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!j())throw new V("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new V("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ce("Not a valid PKCE flow url.");let t=tt(window.location.href);if(e){if(!t.code)throw new Ce("No code detected.");let{data:A,error:x}=await this._exchangeCodeForSession(t.code);if(x)throw x;let O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:A.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new V(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new V("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=Le&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let _=d-u;l-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,l):l-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,l);let{data:y,error:m}=await this._getUser(n);if(m)throw m;let k={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=tt(window.location.href);return!!(j()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=tt(window.location.href),t=await Re(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Ur(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await st(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=jr(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await z(this.storage,this.storageKey,!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await g(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return j()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(p(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Ir(async i=>(i>0&&await $r(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:D})),(i,n)=>{let o=200*Math.pow(2,i);return n&&nt(n)&&Date.now()+o-r<Le})}catch(r){if(this._debug(t,"error",r),p(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),j()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Re(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Rt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Rt}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),nt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new I;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Pe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new I;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),p(n)){let o={session:null,error:n};return nt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ct(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await st(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&j()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Le);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/Le);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Le}ms, refresh threshold is ${Hr} ticks`),i<=Hr&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ie)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!j()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await z(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await g(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};Z.nextInstanceID=0;var Qs=Z,Dt=Qs;var at=class extends Dt{constructor(e){super(e)}};var Xs=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Ue=class{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=xr(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:br,realtime:Sr,auth:Object.assign(Object.assign({},kr),{storageKey:c}),global:wr},l=Tr(r??{},h);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Er(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new or(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new fe(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Te(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Xs(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new at({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new ie(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Gr=(s,e,t)=>new Ue(s,e,t);var ee={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var ct=class{constructor(){this.sessionData=null;this.supabase=Gr(ee.supaBaseUrl,ee.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ee.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||ee.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||ee.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw this.signOut(),console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e){try{let{error:t}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:ee.redirectUri}});if(t)throw t}catch(t){throw console.error("Error sending magic link:",t),t}}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}};function Ys(){try{let s=document.createElement("canvas"),e=s.getContext("webgl")||s.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info");if(!t)return"mac_unknown";let r=e.getParameter(t.UNMASKED_RENDERER_WEBGL);console.log(`WebGL Renderer: ${r}`);let i=String(r||"").toLowerCase();return i.includes("apple gpu")?"mac_unknown":i.includes("apple")?"mac_m1":i.includes("intel")||i.includes("amd")||i.includes("nvidia")?"mac_intel":"mac_unknown"}}catch{}return"mac_unknown"}var Wr=async()=>{if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return"iOS";try{let s=await navigator.userAgentData.getHighEntropyValues(["architecture","platform"]);if(s.platform==="macOS")return s.architecture&&s.architecture.includes("arm")?"mac_m1":s.architecture&&s.architecture.includes("x86")?"mac_intel":"mac_unknown";if(s.platform==="Windows"){if(s.architecture&&s.architecture.includes("x86"))return"Windows";if(s.architecture&&s.architecture.includes("arm"))return"win_unknown";if(!s.architecture){let{userAgent:e}=navigator;return/ARM64/i.test(e)?"win_unknown":/(Win64;\s*x64|WOW64)/i.test(e)?"Windows":"win_unknown"}return"win_unknown"}return s.platform}catch{let{userAgent:s}=navigator;return s.includes("Macintosh")?Ys():s.includes("Windows")?/ARM64/i.test(s)?"win_unknown":"Windows":s.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(s)?"iOS":/Android/.test(s)?"Android":"Unknown"}};var zr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Kr=(s,e)=>{window.posthog.capture(s,e)};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=!1,e=setTimeout(()=>{s||(document.body.style.visibility="visible")},4e3),t=new ct,{accessToken:r,refreshToken:i}=Gt(),n=await Wr(),o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#google-login"),h=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),u=zr(),{dub_id:d,referral:f,promo_code:_}=u,y=localStorage.getItem("email"),m=new URLSearchParams(window.location.search),k=m.get("referral"),A=m.get("plan"),x=m.get("utm_source"),O=m.get("code"),w=`${window.location.origin}/downloads`,ue=new URLSearchParams;if(k&&ue.append("referral",k),A&&ue.append("plan",A),x&&ue.append("utm_source",x),ue.toString()&&(w+=`?${ue.toString()}`),r&&i)try{t.setCookies(r,i);let P=t.checkAndSetSession(),q=new Promise((Ft,De)=>setTimeout(()=>De(new Error("Session timeout")),3e3));await Promise.race([P,q]);let Nt=t.sessionData?.user.email;localStorage.setItem("email",Nt),s=!0,clearTimeout(e),window.location.href=w}catch(P){console.error("Error during session setup:",P),document.body.style.visibility="visible"}else y?(s=!0,clearTimeout(e),window.location.href=w):document.body.style.visibility="visible";c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(w)}catch(P){console.error("Error during sign-in:",P)}}),h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(w)}catch(P){console.error("Error during sign-in:",P)}}),l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(w)}catch(P){console.error("Error during sign-in:",P)}}),o.addEventListener("submit",async P=>{P.stopPropagation(),P.preventDefault();let q=a.value;if(!q||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q)){console.error("Email invalid");return}let Ft={email:q,first_name:"",last_name:"",dub_click_id:d||void 0,referral:f||void 0,promo_code:_||void 0};Kr("email_submission_success",{signin_provider:"email",device_type:n,dub_id:d,referral:f,email:q}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:"email"}),localStorage.setItem("email",q),localStorage.setItem("conversion_sent","true");let De=await Bt.addRawUserEmail(Ft);De&&sessionStorage.setItem("referral_status",JSON.stringify(De)),s=!0,clearTimeout(e),window.location.href=w})});})();
@@ -1,13 +1,13 @@
1
- "use strict";(()=>{async function he(){let C=()=>document.querySelector('.w--tab-active [demo-element="input"]'),n=C(),p=document.querySelector('[demo-element="gradient"]'),b=()=>document.querySelector(".wd_pill-wrap"),x=()=>document.querySelector(".wd_pill"),v=()=>x()?.querySelector(".wd_pill-lottie-wrap"),ee=document.querySelectorAll('[demo-element="start-recording"]'),te=document.querySelectorAll('[demo-element="stop-recording"]'),le=new Audio("https://dl.dropbox.com/scl/fi/zv8278qh9ovwq0r89rch1/dictation-start.wav?rlkey=pk241hf4c8qv7780qsq2m4cgv&st=wgpy7vop&dl=0"),ge=new Audio("https://dl.dropbox.com/scl/fi/4mkbgr7om46imcp0l86yd/dictation-stop.wav?rlkey=4t5uwvg9kufphlu58natjn43t&st=9or4oqr0&dl=0");function we(e){let r=document.getSelection();return r.rangeCount>0&&e.contains(r.focusNode)?r.getRangeAt(0):null}function be(e,r,s){s.deleteContents();let t=document.createElement("div");t.innerHTML=r;let o=document.createDocumentFragment();for(;t.firstChild;)o.appendChild(t.firstChild);s.insertNode(o),s.collapse(!1);let u=document.getSelection();u.removeAllRanges(),u.addRange(s)}function $(e){e.dataset.isPlaceholder==="true"?(e.classList.remove("cursor-after"),e.classList.add("cursor-before"),e.style.color="#1a1a1a80"):(e.classList.remove("cursor-before"),e.classList.add("cursor-after"),e.style.color="#1a1a1a")}let J=()=>{ee.forEach(e=>{e&&(e.style.display="flex")}),document.querySelectorAll('[demo-element="start-recording-text"]').forEach(e=>{e&&(e.style.display="block")})},G=()=>{ee.forEach(e=>{e&&(e.style.display="none")}),document.querySelectorAll('[demo-element="start-recording-text"]').forEach(e=>{e&&(e.style.display="none")})},ve=()=>{te.forEach(e=>{e&&(e.style.display="flex")}),document.querySelectorAll('[demo-element="stop-recording-text"]').forEach(e=>{e&&(e.style.display="block")})},j=()=>{te.forEach(e=>{e&&(e.style.display="none")}),document.querySelectorAll('[demo-element="stop-recording-text"]').forEach(e=>{e&&(e.style.display="none")})},z=window.matchMedia("(min-width: 992px)").matches,y=null,d=null,ce=[],_=!1,W=!1,K=!0,V=!0,l=null,I=null,Y=null,Z=null,a=null,B=null,S=null,P=0,k=[],oe=1024,Q=16e3,R=[],F=!1,M=null,re=!1,L=null,T=!1;navigator.mediaDevices.getUserMedia({audio:!0}).then(e=>{y=e,e.getAudioTracks().forEach(r=>r.enabled=!1),V=!1}).catch(e=>{console.error("Initial microphone permission denied:",e),V=!1,alert("Please enable microphone access in your browser settings to continue."),G()}),p&&(p.style.opacity="0",p.style.transition="opacity 0.3s ease"),j(),navigator.userAgent.toLowerCase().includes("firefox")&&(document.querySelectorAll("[wd-para-div]").forEach(e=>{e.style.display="none"}),document.querySelectorAll("[wd-start-stop-button-div]").forEach(e=>{e.style.display="block"})),z&&n&&n.focus({preventScroll:!0}),document.querySelectorAll('[demo-element="input"]').forEach((e,r)=>{e.classList.add("cursor-before"),e.dataset.isFirstRecording="true",e.dataset.placeholderText=e.textContent.trim(),e.dataset.placeholderHtml=e.innerHTML,e.dataset.isPlaceholder="true",e.addEventListener("beforeinput",()=>{e.dataset.isPlaceholder==="true"&&(e.innerHTML=""),e.dataset.isPlaceholder="false",$(e)}),e.addEventListener("input",()=>{if(e.textContent.trim()===""){e.innerHTML=e.dataset.placeholderHtml,e.dataset.isPlaceholder="true";let s=document.createRange();s.setStart(e,0),s.collapse(!0);let t=window.getSelection();t.removeAllRanges(),t.addRange(s)}$(e)}),e.addEventListener("focus",()=>{}),e.addEventListener("blur",()=>{e.textContent.trim()===""&&(e.innerHTML=e.dataset.placeholderHtml,e.dataset.isPlaceholder="true",e.dataset.isFirstRecording="true",$(e))}),e.addEventListener("mousedown",s=>{if(e.dataset.isPlaceholder==="true"){s.preventDefault();let t=document.createRange();t.setStart(e,0),t.collapse(!0);let o=window.getSelection();o.removeAllRanges(),o.addRange(t)}}),e.addEventListener("keydown",s=>{if(e.dataset.isPlaceholder==="true"&&["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(s.key)){s.preventDefault();let t=document.createRange();t.setStart(e,0),t.collapse(!0);let o=window.getSelection();o.removeAllRanges(),o.addRange(t)}})});let se=new MutationObserver(()=>{de()});se.observe(n,{childList:!0,subtree:!0,characterData:!0}),ue().catch(e=>{console.error("Initial token generation failed:",e)});let ne,Se=e=>new Promise((r,s)=>{let t=new FileReader;t.onloadend=()=>{typeof t.result=="string"?r(t.result.split(",")[1]):s(new Error("Failed to convert blob to base64"))},t.onerror=s,t.readAsDataURL(e)}),ke=async()=>{let r=k.length*1*2+44,s=new ArrayBuffer(r),t=new DataView(s),o=0,u=(f,g,h)=>{for(let m=0;m<h.length;m++)f.setUint8(g+m,h.charCodeAt(m))};u(t,0,"RIFF"),o+=4,t.setUint32(o,36+k.length*1*2,!0),o+=4,u(t,o,"WAVE"),o+=4,u(t,o,"fmt "),o+=4,t.setUint32(o,16,!0),o+=4,t.setUint16(o,1,!0),o+=2,t.setUint16(o,1,!0),o+=2,t.setUint32(o,Q,!0),o+=4,t.setUint32(o,Q*1*2,!0),o+=4,t.setUint16(o,1*2,!0),o+=2,t.setUint16(o,16,!0),o+=2,u(t,o,"data"),o+=4,t.setUint32(o,k.length*1*2,!0),o+=4;for(let f=0;f<k.length;f++)t.setInt16(o,k[f],!0),o+=2;return new Blob([t],{type:"audio/wav"})};function Le(){if(!F||R.length===0)return;console.log(`Flushing ${R.length} buffered audio chunks...`),R.forEach(r=>{try{a&&a.readyState===WebSocket.OPEN&&a.send(JSON.stringify(r))}catch(s){console.error(`Error sending buffered chunk ${r.position}:`,s)}});let e=M?Date.now()-M:0;console.log(`Buffer flushed! Buffering lasted ${e}ms`),R=[],F=!1,M=null}let de=()=>{n&&(n.scrollHeight>n.clientHeight?n.style.overflowY="auto":n.style.overflowY="visible")};async function ue(){try{let e=await fetch("https://api.wisprflow.ai/api/v1/dash/webflow_demo/generate_token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"webflow_demo"})});if(!e.ok)throw new Error(`Token generation failed with status: ${e.status}`);let r=await e.json();return localStorage.setItem("accessToken",r.access_token),localStorage.setItem("tokenExpiration",(Date.now()+r.expires_in*1e3).toString()),r.access_token}catch(e){if(console.error("Token generation failed:",e),n||(n=C()),!n)return;throw document.querySelectorAll('[demo-element="input"]').forEach(r=>{r.innerHTML='Our servers are busy processing requests right now. <a href="/get-started" class="text-color-primary text-weight-medium">Try our desktop app instead.</a>',r.removeAttribute("contenteditable")}),n.classList.remove("cursor-before","cursor-after"),G(),K=!1,e}}async function fe(){let e=localStorage.getItem("tokenExpiration");return!e||Date.now()>=parseInt(e)?await ue():localStorage.getItem("accessToken")}async function Te(){a&&a.readyState===WebSocket.CLOSED&&(a=null),a&&(a.readyState===WebSocket.OPEN||a.readyState===WebSocket.CONNECTING)&&(a.onclose=null,a.close(),a=null);let e=await fe(),r=`wss://api.wisprflow.ai/api/v1/dash/client_ws?client_key=Bearer ${e}`;console.log("Connecting to WebSocket"),a=new WebSocket(r),a.onopen=()=>{let t=new URLSearchParams(window.location.search).get("type")==="email"?"email":"other";a.send(JSON.stringify({type:"auth",access_token:`Bearer ${e}`,context:{app:{type:t}}}))},a.onmessage=s=>{try{let t=JSON.parse(s.data);if(t.status==="error"||t.status==="auth_error"){console.error("WebSocket error:",t),N();return}if(t.status==="text"&&t.final){if(re=!0,L&&(clearTimeout(L),L=null),t.body&&t.body.text===null)console.log("Empty recording detected, skipping text display");else{let o="No speech detected.";t.body&&t.body.text?o=t.body.text:t.body.status==="formatted"?o=t.body.llm_text:t.body.status==="raw_transcript"&&(o=t.body.asr_text),me(o+"\xA0")}J(),j(),v()?.classList.remove("show"),b()?.style.setProperty("opacity","0")}}catch(t){console.error("WebSocket message parsing error:",t),N()}},a.onclose=s=>{console.log("WebSocket closed:",s.code,s.reason),a=null,T=!1},a.onerror=s=>{console.error("WebSocket error:",s)}}async function Ae(){if(a&&a.readyState===WebSocket.CONNECTING){console.log("\u23F3 WebSocket already connecting, skipping duplicate call");return}try{T=!1,await Te();let e=0,r=50;for(;(!a||a.readyState!==WebSocket.OPEN)&&e<r;)await new Promise(s=>setTimeout(s,100)),e++;a&&a.readyState===WebSocket.OPEN?(T=!0,console.log("\u2705 WebSocket marked as ready for streaming")):(console.log("WebSocket connection failed, will use fallback"),T=!1)}catch(e){console.error("WebSocket background connection failed:",e),T=!1}}function N(){L&&(clearTimeout(L),L=null),Ee()}async function Ee(){try{console.log("Using Fetch API fallback with collected samples");let e=await ke(),r=await Se(e),s=await fe(),t=await fetch("https://api.wisprflow.ai/api/v1/dash/client_api",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({audio:r,properties:{language:""}})});if(!t.ok)throw new Error("Fallback server error");let o=await t.json();if(o.text===null){console.log("Empty fallback recording detected, skipping text display"),v()?.classList.remove("show"),b()?.style.setProperty("opacity","0"),J(),j();return}me(o.text+"\xA0"),v()?.classList.remove("show"),b()?.style.setProperty("opacity","0"),J(),j()}catch(e){if(console.error("Fallback also failed:",e),n||(n=C()),!n)return;document.querySelectorAll('[demo-element="input"]').forEach(r=>{r.innerHTML='Our servers are busy processing requests right now. <a href="/get-started" class="text-color-primary text-weight-medium">Try our desktop app instead.</a>',r.removeAttribute("contenteditable")}),n.classList.remove("cursor-before","cursor-after"),G(),K=!1,x()?.classList.remove("is-speaking"),v()?.classList.remove("show"),b()?.style.setProperty("opacity","0")}}async function Ce(){try{return y&&y.getAudioTracks().length>0?y.getAudioTracks().forEach(e=>e.enabled=!0):y=await navigator.mediaDevices.getUserMedia({audio:!0}),d=new MediaRecorder(y),d.ondataavailable=e=>{ce.push(e.data)},d.onstop=async()=>{y.getTracks().forEach(e=>{e.enabled=!1}),d=null},!0}catch(e){return console.error("Microphone access error:",e),(e.name==="NotAllowedError"||e.name==="PermissionDeniedError")&&alert("Please enable microphone access in your browser settings to continue."),!1}}function me(e,r=!1){if(e=e.replace(/\n/g,"<br>"),e=e.replace(/<br>(?=\s*<\/?(?:ul|ol|li))|(?<=<\/?(?:ul|ol|li)>\s*)<br>/gi,""),!n)return;n.dataset.isPlaceholder==="true"&&(n.innerHTML=""),n.dataset.isPlaceholder="false",n.classList.remove("no-cursor");let s=we(n);if(s?be(n,e,s):n.textContent.trim()===""?n.innerHTML=e:n.innerHTML+=e,de(),n.dataset.previousText=n.textContent,n.dataset.isFirstRecording==="true"&&(n.classList.remove("cursor-before"),n.classList.add("cursor-after"),n.dataset.isFirstRecording="false"),typeof posthog<"u"){let o=document.querySelector(".w-tab-link.w--current"),u=o?o.textContent.trim().toLowerCase().replace(/\s+/g,"_"):"Unknown";posthog.capture("demo_transcription_completed",{transcribed_text:e,tab_name:u})}document.querySelectorAll(".wd-tab-content-bottom").forEach(o=>{o.style.display="flex"}),$(n),J()}async function pe(e=!1){if(n||(n=C()),!n)return;document.querySelectorAll(".wd-tab-link").forEach(o=>{o.classList.contains("w--current")||o.classList.add("pointer-events-none")}),R=[],F=!1,M=null,P=0,Ae();let s=n.innerHTML||"";s&&!s.includes("Flow is listening")&&!s.includes("Converting...")&&!s.includes("Error")&&(n.dataset.previousText=s);let t=n.dataset.isFirstRecording==="true";n.classList.add("no-cursor");try{le.currentTime=0,le.play()}catch(o){console.error("Error playing start dictation sound:",o)}if(!d&&!await Ce()){n.dataset.previousText?n.innerHTML=n.dataset.previousText:n.innerHTML="",n.classList.remove("no-cursor");return}if(d.state==="inactive"){ce=[],d.start(),_=!0,k=[],P=0,l||(l=new AudioContext),B=l.createMediaStreamSource(y),S=l.createScriptProcessor(oe,1,1),S.onaudioprocess=async f=>{let g=f.inputBuffer.getChannelData(0),h=Math.ceil(oe*Q/l.sampleRate),m=new OfflineAudioContext(1,h,Q),q=l.createBuffer(1,g.length,l.sampleRate);q.copyToChannel(g,0);let D=m.createBufferSource();D.buffer=q,D.connect(m.destination),D.start();let c=(await m.startRendering()).getChannelData(0),E=new Int16Array(c.length),O=0;for(let i=0;i<c.length;i++){let ie=Math.max(-1,Math.min(1,c[i]));E[i]=ie<0?ie*32768:ie*32767,k.push(E[i]),O+=c[i]*c[i]}let H=Math.sqrt(O/c.length),X=new Uint8Array(E.buffer),w="";for(let i=0;i<X.length;i++)w+=String.fromCharCode(X[i]);let Re=btoa(w);try{let i={type:"append",position:P,final:!1,audio_packets:{packets:[Re],volumes:[H],packet_duration:oe/l.sampleRate,audio_encoding:"wav",byte_encoding:"base64"}};T&&a&&a.readyState===WebSocket.OPEN?(F&&Le(),a.send(JSON.stringify(i))):(R.push(i),F=!0,M||(M=Date.now()),P===0&&console.log("WebSocket not ready yet, buffering audio chunks")),P++}catch(i){console.error("Error processing audio chunk:",i)}},B.connect(S),S.connect(l.destination),p&&(p.style.opacity="1"),b()?.style.setProperty("opacity","1"),x()?.classList.remove("is-speaking"),v()?.classList.remove("show");let o=document.querySelector(".wave-svg");o&&(o.style.opacity="1"),ne=p.animate([{transform:"scale(1)"},{transform:"scale(1.3)"},{transform:"scale(1)"}],{duration:1500,iterations:1/0}),G(),ve(),I=l.createAnalyser(),l.createMediaStreamSource(y).connect(I),I.fftSize=32,Y=new Uint8Array(I.frequencyBinCount),Z=setInterval(()=>{I.getByteFrequencyData(Y);let f=Y.reduce((A,c)=>A+c,0)/Y.length,g=8,h=0;f>g&&(h=Math.pow((f-g)/(255-g),1.5));let m=1+h*2,q=x();q&&(h>.06?q.classList.add("is-speaking"):q.classList.remove("is-speaking")),p.animate([{transform:`scale(${m})`}],{duration:300,fill:"forwards"});let D=document.querySelector(".wave-path");if(D){let A=40+h*300,c=Date.now()/1e3,E=w=>A*.3*Math.sin(w/1440*Math.PI*2+c*.8),O=w=>A*.2*Math.sin(w/720*Math.PI*2+c*1.2),H=w=>A*.1*Math.sin(w/360*Math.PI*2+c*1.8),X=`
1
+ "use strict";(()=>{async function ge(){let h=()=>document.querySelector('.w--tab-active [demo-element="input"]'),n=h(),p=document.querySelector('[demo-element="gradient"]'),v=()=>document.querySelector(".wd_pill-wrap"),x=()=>document.querySelector(".wd_pill"),S=()=>x()?.querySelector(".wd_pill-lottie-wrap"),ee=document.querySelectorAll('[demo-element="start-recording"]'),te=document.querySelectorAll('[demo-element="stop-recording"]'),le=new Audio("https://dl.dropbox.com/scl/fi/zv8278qh9ovwq0r89rch1/dictation-start.wav?rlkey=pk241hf4c8qv7780qsq2m4cgv&st=wgpy7vop&dl=0"),he=new Audio("https://dl.dropbox.com/scl/fi/4mkbgr7om46imcp0l86yd/dictation-stop.wav?rlkey=4t5uwvg9kufphlu58natjn43t&st=9or4oqr0&dl=0");function we(e){let r=document.getSelection();return r.rangeCount>0&&e.contains(r.focusNode)?r.getRangeAt(0):null}function be(e,r,s){s.deleteContents();let t=document.createElement("div");t.innerHTML=r;let o=document.createDocumentFragment();for(;t.firstChild;)o.appendChild(t.firstChild);s.insertNode(o),s.collapse(!1);let u=document.getSelection();u.removeAllRanges(),u.addRange(s)}function $(e){e.dataset.isPlaceholder==="true"?(e.classList.remove("cursor-after"),e.classList.add("cursor-before"),e.style.color="#1a1a1a80"):(e.classList.remove("cursor-before"),e.classList.add("cursor-after"),e.style.color="#1a1a1a")}let J=()=>{ee.forEach(e=>{e&&(e.style.display="flex")}),document.querySelectorAll('[demo-element="start-recording-text"]').forEach(e=>{e&&(e.style.display="block")})},G=()=>{ee.forEach(e=>{e&&(e.style.display="none")}),document.querySelectorAll('[demo-element="start-recording-text"]').forEach(e=>{e&&(e.style.display="none")})},ve=()=>{te.forEach(e=>{e&&(e.style.display="flex")}),document.querySelectorAll('[demo-element="stop-recording-text"]').forEach(e=>{e&&(e.style.display="block")})},j=()=>{te.forEach(e=>{e&&(e.style.display="none")}),document.querySelectorAll('[demo-element="stop-recording-text"]').forEach(e=>{e&&(e.style.display="none")})},z=window.matchMedia("(min-width: 992px)").matches,y=null,d=null,ce=[],_=!1,W=!1,K=!0,V=!0,l=null,I=null,Y=null,Z=null,a=null,B=null,k=null,P=0,L=[],oe=1024,Q=16e3,R=[],F=!1,M=null,re=!1,T=null,E=!1;navigator.mediaDevices.getUserMedia({audio:!0}).then(e=>{y=e,e.getAudioTracks().forEach(r=>r.enabled=!1),V=!1}).catch(e=>{console.error("Initial microphone permission denied:",e),V=!1,alert("Please enable microphone access in your browser settings to continue."),G()}),p&&(p.style.opacity="0",p.style.transition="opacity 0.3s ease"),j(),navigator.userAgent.toLowerCase().includes("firefox")&&(document.querySelectorAll("[wd-para-div]").forEach(e=>{e.style.display="none"}),document.querySelectorAll("[wd-start-stop-button-div]").forEach(e=>{e.style.display="block"})),z&&n&&n.focus({preventScroll:!0}),document.querySelectorAll('[demo-element="input"]').forEach((e,r)=>{e.classList.add("cursor-before"),e.dataset.isFirstRecording="true",e.dataset.placeholderText=e.textContent.trim(),e.dataset.placeholderHtml=e.innerHTML,e.dataset.isPlaceholder="true",e.addEventListener("beforeinput",()=>{e.dataset.isPlaceholder==="true"&&(e.innerHTML=""),e.dataset.isPlaceholder="false",$(e)}),e.addEventListener("input",()=>{if(e.textContent.trim()===""){e.innerHTML=e.dataset.placeholderHtml,e.dataset.isPlaceholder="true";let s=document.createRange();s.setStart(e,0),s.collapse(!0);let t=window.getSelection();t.removeAllRanges(),t.addRange(s)}$(e)}),e.addEventListener("focus",()=>{}),e.addEventListener("blur",()=>{e.textContent.trim()===""&&(e.innerHTML=e.dataset.placeholderHtml,e.dataset.isPlaceholder="true",e.dataset.isFirstRecording="true",$(e))}),e.addEventListener("mousedown",s=>{if(e.dataset.isPlaceholder==="true"){s.preventDefault();let t=document.createRange();t.setStart(e,0),t.collapse(!0);let o=window.getSelection();o.removeAllRanges(),o.addRange(t)}}),e.addEventListener("keydown",s=>{if(e.dataset.isPlaceholder==="true"&&["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(s.key)){s.preventDefault();let t=document.createRange();t.setStart(e,0),t.collapse(!0);let o=window.getSelection();o.removeAllRanges(),o.addRange(t)}})});let se=new MutationObserver(()=>{de()});se.observe(n,{childList:!0,subtree:!0,characterData:!0}),ue().catch(e=>{console.error("Initial token generation failed:",e)});let ne,Se=e=>new Promise((r,s)=>{let t=new FileReader;t.onloadend=()=>{typeof t.result=="string"?r(t.result.split(",")[1]):s(new Error("Failed to convert blob to base64"))},t.onerror=s,t.readAsDataURL(e)}),ke=async()=>{let r=L.length*1*2+44,s=new ArrayBuffer(r),t=new DataView(s),o=0,u=(f,w,g)=>{for(let m=0;m<g.length;m++)f.setUint8(w+m,g.charCodeAt(m))};u(t,0,"RIFF"),o+=4,t.setUint32(o,36+L.length*1*2,!0),o+=4,u(t,o,"WAVE"),o+=4,u(t,o,"fmt "),o+=4,t.setUint32(o,16,!0),o+=4,t.setUint16(o,1,!0),o+=2,t.setUint16(o,1,!0),o+=2,t.setUint32(o,Q,!0),o+=4,t.setUint32(o,Q*1*2,!0),o+=4,t.setUint16(o,1*2,!0),o+=2,t.setUint16(o,16,!0),o+=2,u(t,o,"data"),o+=4,t.setUint32(o,L.length*1*2,!0),o+=4;for(let f=0;f<L.length;f++)t.setInt16(o,L[f],!0),o+=2;return new Blob([t],{type:"audio/wav"})};function Le(){if(!F||R.length===0)return;console.log(`Flushing ${R.length} buffered audio chunks...`),R.forEach(r=>{try{a&&a.readyState===WebSocket.OPEN&&a.send(JSON.stringify(r))}catch(s){console.error(`Error sending buffered chunk ${r.position}:`,s)}});let e=M?Date.now()-M:0;console.log(`Buffer flushed! Buffering lasted ${e}ms`),R=[],F=!1,M=null}let de=()=>{n&&(n.scrollHeight>n.clientHeight?n.style.overflowY="auto":n.style.overflowY="visible")};async function ue(){try{let e=await fetch("https://api.wisprflow.ai/api/v1/dash/webflow_demo/generate_token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"webflow_demo"})});if(!e.ok)throw new Error(`Token generation failed with status: ${e.status}`);let r=await e.json();return localStorage.setItem("accessToken",r.access_token),localStorage.setItem("tokenExpiration",(Date.now()+r.expires_in*1e3).toString()),r.access_token}catch(e){if(console.error("Token generation failed:",e),n||(n=h()),!n)return;throw document.querySelectorAll('[demo-element="input"]').forEach(r=>{r.innerHTML='Our servers are busy processing requests right now. <a href="/get-started" class="text-color-primary text-weight-medium">Try our desktop app instead.</a>',r.removeAttribute("contenteditable")}),n.classList.remove("cursor-before","cursor-after"),G(),K=!1,e}}async function fe(){let e=localStorage.getItem("tokenExpiration");return!e||Date.now()>=parseInt(e)?await ue():localStorage.getItem("accessToken")}async function Te(){a&&a.readyState===WebSocket.CLOSED&&(a=null),a&&(a.readyState===WebSocket.OPEN||a.readyState===WebSocket.CONNECTING)&&(a.onclose=null,a.close(),a=null);let e=await fe(),r=`wss://api.wisprflow.ai/api/v1/dash/client_ws?client_key=Bearer ${e}`;console.log("Connecting to WebSocket"),a=new WebSocket(r),a.onopen=()=>{let t=new URLSearchParams(window.location.search).get("type")==="email"?"email":"other";a.send(JSON.stringify({type:"auth",access_token:`Bearer ${e}`,context:{app:{type:t}}}))},a.onmessage=s=>{try{let t=JSON.parse(s.data);if(t.status==="error"||t.status==="auth_error"){console.error("WebSocket error:",t),N();return}if(t.status==="text"&&t.final){if(re=!0,T&&(clearTimeout(T),T=null),t.body&&t.body.text===null)console.log("Empty recording detected, skipping text display");else{let o="No speech detected.";t.body&&t.body.text?o=t.body.text:t.body.status==="formatted"?o=t.body.llm_text:t.body.status==="raw_transcript"&&(o=t.body.asr_text),me(o+"\xA0")}J(),j(),S()?.classList.remove("show"),v()?.style.setProperty("opacity","0")}}catch(t){console.error("WebSocket message parsing error:",t),N()}},a.onclose=s=>{console.log("WebSocket closed:",s.code,s.reason),a=null,E=!1},a.onerror=s=>{console.error("WebSocket error:",s)}}async function Ee(){if(a&&a.readyState===WebSocket.CONNECTING){console.log("\u23F3 WebSocket already connecting, skipping duplicate call");return}try{E=!1,await Te();let e=0,r=50;for(;(!a||a.readyState!==WebSocket.OPEN)&&e<r;)await new Promise(s=>setTimeout(s,100)),e++;a&&a.readyState===WebSocket.OPEN?(E=!0,console.log("\u2705 WebSocket marked as ready for streaming")):(console.log("WebSocket connection failed, will use fallback"),E=!1)}catch(e){console.error("WebSocket background connection failed:",e),E=!1}}function N(){T&&(clearTimeout(T),T=null),Ae()}async function Ae(){try{console.log("Using Fetch API fallback with collected samples");let e=await ke(),r=await Se(e),s=await fe(),t=await fetch("https://api.wisprflow.ai/api/v1/dash/client_api",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({audio:r,properties:{language:""}})});if(!t.ok)throw new Error("Fallback server error");let o=await t.json();if(o.text===null){console.log("Empty fallback recording detected, skipping text display"),S()?.classList.remove("show"),v()?.style.setProperty("opacity","0"),J(),j();return}me(o.text+"\xA0"),S()?.classList.remove("show"),v()?.style.setProperty("opacity","0"),J(),j()}catch(e){if(console.error("Fallback also failed:",e),n||(n=h()),!n)return;document.querySelectorAll('[demo-element="input"]').forEach(r=>{r.innerHTML='Our servers are busy processing requests right now. <a href="/get-started" class="text-color-primary text-weight-medium">Try our desktop app instead.</a>',r.removeAttribute("contenteditable")}),n.classList.remove("cursor-before","cursor-after"),G(),K=!1,x()?.classList.remove("is-speaking"),S()?.classList.remove("show"),v()?.style.setProperty("opacity","0")}}async function Ce(){try{return y&&y.getAudioTracks().length>0?y.getAudioTracks().forEach(e=>e.enabled=!0):y=await navigator.mediaDevices.getUserMedia({audio:!0}),d=new MediaRecorder(y),d.ondataavailable=e=>{ce.push(e.data)},d.onstop=async()=>{y.getTracks().forEach(e=>{e.enabled=!1}),d=null},!0}catch(e){return console.error("Microphone access error:",e),(e.name==="NotAllowedError"||e.name==="PermissionDeniedError")&&alert("Please enable microphone access in your browser settings to continue."),!1}}function me(e,r=!1){if(e=e.replace(/\n/g,"<br>"),e=e.replace(/<br>(?=\s*<\/?(?:ul|ol|li))|(?<=<\/?(?:ul|ol|li)>\s*)<br>/gi,""),!n)return;n.dataset.isPlaceholder==="true"&&(n.innerHTML=""),n.dataset.isPlaceholder="false",n.classList.remove("no-cursor");let s=we(n);if(s?be(n,e,s):n.textContent.trim()===""?n.innerHTML=e:n.innerHTML+=e,de(),n.dataset.previousText=n.textContent,n.dataset.isFirstRecording==="true"&&(n.classList.remove("cursor-before"),n.classList.add("cursor-after"),n.dataset.isFirstRecording="false"),typeof posthog<"u"){let o=document.querySelector(".w-tab-link.w--current"),u=o?o.textContent.trim().toLowerCase().replace(/\s+/g,"_"):"Unknown";posthog.capture("demo_transcription_completed",{transcribed_text:e,tab_name:u})}document.querySelectorAll(".wd-tab-content-bottom").forEach(o=>{o.style.display="flex"}),$(n),J()}async function pe(e=!1){if(n||(n=h()),!n)return;document.querySelectorAll(".wd-tab-link").forEach(o=>{o.classList.contains("w--current")||o.classList.add("pointer-events-none")}),R=[],F=!1,M=null,P=0,Ee();let s=n.innerHTML||"";s&&!s.includes("Flow is listening")&&!s.includes("Converting...")&&!s.includes("Error")&&(n.dataset.previousText=s);let t=n.dataset.isFirstRecording==="true";n.classList.add("no-cursor");try{le.currentTime=0,le.play()}catch(o){console.error("Error playing start dictation sound:",o)}if(!d&&!await Ce()){n.dataset.previousText?n.innerHTML=n.dataset.previousText:n.innerHTML="",n.classList.remove("no-cursor");return}if(d.state==="inactive"){ce=[],d.start(),_=!0,L=[],P=0,l||(l=new AudioContext),B=l.createMediaStreamSource(y),k=l.createScriptProcessor(oe,1,1),k.onaudioprocess=async f=>{let w=f.inputBuffer.getChannelData(0),g=Math.ceil(oe*Q/l.sampleRate),m=new OfflineAudioContext(1,g,Q),q=l.createBuffer(1,w.length,l.sampleRate);q.copyToChannel(w,0);let D=m.createBufferSource();D.buffer=q,D.connect(m.destination),D.start();let c=(await m.startRendering()).getChannelData(0),C=new Int16Array(c.length),O=0;for(let i=0;i<c.length;i++){let ie=Math.max(-1,Math.min(1,c[i]));C[i]=ie<0?ie*32768:ie*32767,L.push(C[i]),O+=c[i]*c[i]}let H=Math.sqrt(O/c.length),X=new Uint8Array(C.buffer),b="";for(let i=0;i<X.length;i++)b+=String.fromCharCode(X[i]);let Re=btoa(b);try{let i={type:"append",position:P,final:!1,audio_packets:{packets:[Re],volumes:[H],packet_duration:oe/l.sampleRate,audio_encoding:"wav",byte_encoding:"base64"}};E&&a&&a.readyState===WebSocket.OPEN?(F&&Le(),a.send(JSON.stringify(i))):(R.push(i),F=!0,M||(M=Date.now()),P===0&&console.log("WebSocket not ready yet, buffering audio chunks")),P++}catch(i){console.error("Error processing audio chunk:",i)}},B.connect(k),k.connect(l.destination),p&&(p.style.opacity="1"),v()?.style.setProperty("opacity","1"),x()?.classList.remove("is-speaking"),S()?.classList.remove("show");let o=document.querySelector(".wave-svg");o&&(o.style.opacity="1"),ne=p.animate([{transform:"scale(1)"},{transform:"scale(1.3)"},{transform:"scale(1)"}],{duration:1500,iterations:1/0}),G(),ve(),I=l.createAnalyser(),l.createMediaStreamSource(y).connect(I),I.fftSize=32,Y=new Uint8Array(I.frequencyBinCount),Z=setInterval(()=>{I.getByteFrequencyData(Y);let f=Y.reduce((A,c)=>A+c,0)/Y.length,w=8,g=0;f>w&&(g=Math.pow((f-w)/(255-w),1.5));let m=1+g*2,q=x();q&&(g>.06?q.classList.add("is-speaking"):q.classList.remove("is-speaking")),p.animate([{transform:`scale(${m})`}],{duration:300,fill:"forwards"});let D=document.querySelector(".wave-path");if(D){let A=40+g*300,c=Date.now()/1e3,C=b=>A*.3*Math.sin(b/1440*Math.PI*2+c*.8),O=b=>A*.2*Math.sin(b/720*Math.PI*2+c*1.2),H=b=>A*.1*Math.sin(b/360*Math.PI*2+c*1.8),X=`
2
2
  M0,160
3
- C120,${100+E(120)}
3
+ C120,${100+C(120)}
4
4
  240,${220+O(240)}
5
5
  480,${160+H(480)}
6
- C720,${100+E(720)}
6
+ C720,${100+C(720)}
7
7
  900,${220+O(900)}
8
8
  1080,${160+H(1080)}
9
- C1260,${100+E(1260)}
9
+ C1260,${100+C(1260)}
10
10
  1440,${220+O(1440)}
11
11
  1440,${160+H(1440)}
12
12
  L1440,320 L0,320 Z
13
- `;D.setAttribute("d",X)}},50)}}async function ae(){try{ge.play()}catch(r){console.error("Error playing stop dictation sound:",r)}if(d&&d.state==="recording"){d.stop(),_=!1,p&&(p.style.opacity="0"),x()?.classList.remove("is-speaking"),b()?.style.setProperty("opacity","1"),v()?.classList.add("show");let r=document.querySelector(".wave-svg");r&&(r.style.opacity="0"),ne&&ne.cancel()}if(Z&&(clearInterval(Z),Z=null),l&&(l.close().catch(console.error),l=null),S&&(S.disconnect(),S=null),B&&(B.disconnect(),B=null),re=!1,T&&a&&a.readyState===WebSocket.OPEN)try{a.send(JSON.stringify({type:"commit",total_packets:P})),L=setTimeout(()=>{re||(console.log("WebSocket timeout, falling back to Fetch"),N())},4e3)}catch(r){console.error("WebSocket commit failed:",r),N()}else console.log("WebSocket not available, using Fetch fallback"),N();document.querySelectorAll(".wd-tab-link").forEach(r=>{r.classList.remove("pointer-events-none")})}let xe=100,U=null;document.addEventListener("keydown",e=>{console.log("Key pressed:",e.key),z&&e.key==="Control"&&!W&&K&&!_&&(e.preventDefault(),W=!0,U=setTimeout(()=>{W&&pe(!0)},xe))}),document.addEventListener("keyup",async e=>{z&&e.key==="Control"&&(W=!1,clearTimeout(U),_&&await ae())}),ee.forEach(e=>{e&&e.addEventListener("click",r=>{r.preventDefault(),!V&&K&&pe()})}),te.forEach(e=>{e&&e.addEventListener("click",async r=>{r.preventDefault(),!V&&await ae()})});async function ye(){W=!1,U&&(clearTimeout(U),U=null),_&&await ae(),x()?.classList.remove("is-speaking"),v()?.classList.remove("show"),b()?.style.setProperty("opacity","0")}function Pe(){let e=document.querySelector(".wd-tab-link.w--current");if(e){let r=new URL(window.location);e.getAttribute("app-type")==="email"?r.searchParams.set("type","email"):r.searchParams.delete("type"),window.history.replaceState({},"",r)}}document.addEventListener("click",e=>{e.target.closest(".wd-tab-link")&&(z&&setTimeout(()=>{let s=C();if(s&&(s.focus(),s.dataset.isPlaceholder==="false")){let t=document.createRange(),o=window.getSelection();t.selectNodeContents(s),t.collapse(!1),o.removeAllRanges(),o.addRange(t)}},250),setTimeout(()=>{let s=C();s&&s!==n&&(n=s,se.disconnect(),se.observe(n,{childList:!0,subtree:!0,characterData:!0}))},320),setTimeout(()=>{Pe()},100))}),window.addEventListener("blur",ye),document.addEventListener("visibilitychange",()=>{document.hidden&&ye()})}document.addEventListener("DOMContentLoaded",async function(){await he(),console.log("Web demo initialized successfully")});})();
13
+ `;D.setAttribute("d",X)}},50)}}async function ae(){try{he.play()}catch(r){console.error("Error playing stop dictation sound:",r)}if(d&&d.state==="recording"){d.stop(),_=!1,p&&(p.style.opacity="0"),x()?.classList.remove("is-speaking"),v()?.style.setProperty("opacity","1"),S()?.classList.add("show");let r=document.querySelector(".wave-svg");r&&(r.style.opacity="0"),ne&&ne.cancel()}if(Z&&(clearInterval(Z),Z=null),l&&(l.close().catch(console.error),l=null),k&&(k.disconnect(),k=null),B&&(B.disconnect(),B=null),re=!1,E&&a&&a.readyState===WebSocket.OPEN)try{a.send(JSON.stringify({type:"commit",total_packets:P})),T=setTimeout(()=>{re||(console.log("WebSocket timeout, falling back to Fetch"),N())},4e3)}catch(r){console.error("WebSocket commit failed:",r),N()}else console.log("WebSocket not available, using Fetch fallback"),N();document.querySelectorAll(".wd-tab-link").forEach(r=>{r.classList.remove("pointer-events-none")})}let xe=100,U=null;document.addEventListener("keydown",e=>{console.log("Key pressed:",e.key),z&&e.key==="Control"&&!W&&K&&!_&&(e.preventDefault(),W=!0,U=setTimeout(()=>{W&&pe(!0)},xe))}),document.addEventListener("keyup",async e=>{z&&e.key==="Control"&&(W=!1,clearTimeout(U),_&&await ae())}),ee.forEach(e=>{e&&e.addEventListener("click",r=>{r.preventDefault(),!V&&K&&pe()})}),te.forEach(e=>{e&&e.addEventListener("click",async r=>{r.preventDefault(),!V&&await ae()})});async function ye(){W=!1,U&&(clearTimeout(U),U=null),_&&await ae(),x()?.classList.remove("is-speaking"),S()?.classList.remove("show"),v()?.style.setProperty("opacity","0")}function Pe(){let e=document.querySelector(".wd-tab-link.w--current");if(e){let r=new URL(window.location);e.getAttribute("app-type")==="email"?r.searchParams.set("type","email"):r.searchParams.delete("type"),window.history.replaceState({},"",r)}}document.addEventListener("click",e=>{e.target.closest(".wd-tab-link")&&(z&&setTimeout(()=>{let s=h();if(s&&(s.focus(),s.dataset.isPlaceholder==="false")){let t=document.createRange(),o=window.getSelection();t.selectNodeContents(s),t.collapse(!1),o.removeAllRanges(),o.addRange(t)}},250),setTimeout(()=>{let s=h();s&&s!==n&&(n=s,se.disconnect(),se.observe(n,{childList:!0,subtree:!0,characterData:!0}))},320),setTimeout(()=>{Pe()},100))}),window.addEventListener("blur",ye),document.addEventListener("visibilitychange",()=>{document.hidden&&ye()})}document.addEventListener("DOMContentLoaded",async function(){await ge(),console.log("Web demo initialized successfully")});window.addEventListener("pageshow",h=>{h.persisted&&(console.log("Page restored from bfcache - reloading..."),location.reload())});})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanay-wispr/webflow-package",
3
- "version": "5.1.0",
3
+ "version": "5.1.2",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },