1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Vision-B5IUoty2.js","assets/rolldown-runtime-CXHxssQy.js","assets/react-vendor-DfDPcXOr.js","assets/Programs-Dms8A0ks.js","assets/Team-DnAUWzvN.js","assets/createLucideIcon-BbJQayZI.js","assets/SectionLabel-mrfLdp1S.js","assets/dist-8pIHLCaF.js","assets/Contact-v8ZtinJf.js","assets/Imprint-Ch7iluOv.js","assets/Privacy-Bv347CSE.js","assets/Aidd-B0p-Pcat.js","assets/News-C_xdbrw3.js","assets/news-C-zHgtKz.js","assets/NewsPost-xICcv9id.js","assets/lib-DqGF6vpl.js","assets/Login-DJtBXvGu.js","assets/NewsList-D5gkas9U.js","assets/newsAdmin-DfoojRWL.js","assets/NewsForm-BhRe4pwl.js"])))=>i.map(i=>d[i]); 2import{r as Cs}from"./rolldown-runtime-CXHxssQy.js";import{i as Os,n as Ps,t as js}from"./react-vendor-DfDPcXOr.js";import{a as Is,i as Ns,n as Er,r as $s,t as Ls}from"./ogl-vendor-1-2c9wHm.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();var f=Cs(Os(),1),Ds=Ps(),Us="modulepreload",Bs=function(t){return"/"+t},kr={},W=function(e,r,n){let s=Promise.resolve();if(r&&r.length>0){let c=function(u){return Promise.all(u.map(p=>Promise.resolve(p).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))},h=function(u){return import.meta.resolve?import.meta.resolve(u):new URL(u,import.meta.url).href};const a=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");s=c(r.map(u=>{if(u=Bs(u,n),u=h(u),u in kr)return;kr[u]=!0;const p=u.endsWith(".css");for(let y=a.length-1;y>=0;y--){const v=a[y];if(v.href===u&&(!p||v.rel==="stylesheet"))return}const d=document.createElement("link");if(d.rel=p?"stylesheet":Us,p||(d.as="script"),d.crossOrigin="",d.href=u,l&&d.setAttribute("nonce",l),document.head.appendChild(d),p)return new Promise((y,v)=>{d.addEventListener("load",y),d.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return s.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return e().catch(i)})},dr=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,Sn=/^[\\/]{2}/;function Ms(t,e){return e+t.replace(/\\/g,"/")}var Sr="popstate";function Rr(t){return typeof t=="object"&&t!=null&&"pathname"in t&&"search"in t&&"hash"in t&&"state"in t&&"key"in t}function Fs(t={}){function e(n,s){let i=s.state?.masked,{pathname:a,search:o,hash:l}=i||n.location;return Yt("",{pathname:a,search:o,hash:l},s.state&&s.state.usr||null,s.state&&s.state.key||"default",i?{pathname:n.location.pathname,search:n.location.search,hash:n.location.hash}:void 0)}function r(n,s){return typeof s=="string"?s:Fe(s)}return qs(e,r,null,t)}function O(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function H(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function Hs(){return Math.random().toString(36).substring(2,10)}function xr(t,e){return{usr:t.state,key:t.key,idx:e,masked:t.mask?{pathname:t.pathname,search:t.search,hash:t.hash}:void 0}}function Yt(t,e,r=null,n,s){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof e=="string"?je(e):e,state:r,key:e&&e.key||n||Hs(),mask:s}}function Fe({pathname:t="/",search:e="",hash:r=""}){return e&&e!=="?"&&(t+=e.charAt(0)==="?"?e:"?"+e),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function je(t){let e={};if(t){let r=t.indexOf("#");r>=0&&(e.hash=t.substring(r),t=t.substring(0,r));let n=t.indexOf("?");n>=0&&(e.search=t.substring(n),t=t.substring(0,n)),t&&(e.pathname=t)}return e}function qs(t,e,r,n={}){let{window:s=document.defaultView,v5Compat:i=!1}=n,a=s.history,o="POP",l=null,c=h();c==null&&(c=0,a.replaceState({...a.state,idx:c},""));function h(){return(a.state||{idx:null}).idx}function u(){o="POP";let m=h(),_=m==null?null:m-c;c=m,l&&l({action:o,location:v.location,delta:_})}function p(m,_){o="PUSH";let b=Rr(m)?m:Yt(v.location,m,_);r&&r(b,m),c=h()+1;let w=xr(b,c),T=v.createHref(b.mask||b);try{a.pushState(w,"",T)}
2catch(x){if(x instanceof DOMException&&x.name==="DataCloneError")throw x;s.location.assign(T)}i&&l&&l({action:o,location:v.location,delta:1})}function d(m,_){o="REPLACE";let b=Rr(m)?m:Yt(v.location,m,_);r&&r(b,m),c=h();let w=xr(b,c),T=v.createHref(b.mask||b);a.replaceState(w,"",T),i&&l&&l({action:o,location:v.location,delta:0})}function y(m){return Ws(s,m)}let v={get action(){return o},get location(){return t(s,a)},listen(m){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(Sr,u),l=m,()=>{s.removeEventListener(Sr,u),l=null}},createHref(m){return e(s,m)},createURL:y,encodeLocation(m){let _=y(m);return{pathname:_.pathname,search:_.search,hash:_.hash}},push:p,replace:d,go(m){return a.go(m)}};return v}function Ws(t,e,r=!1){let n="http://localhost";t&&(n=t.location.origin!=="null"?t.location.origin:t.location.href),O(n,"No window.location.(origin|href) available to create URL");let s=typeof e=="string"?e:Fe(e);return s=s.replace(/ $/,"%20"),!r&&Sn.test(s)&&(s=n+s),new URL(s,n)}var zs;zs=new WeakMap;function Rn(t,e,r="/"){return xn(t,e,r,!1)}function xn(t,e,r,n,s){let i=te((typeof e=="string"?je(e):e).pathname||"/",r);if(i==null)return null;let a=s??Ks(t),o=null,l=si(i);for(let c=0;o==null&&c<a.length;++c)o=ni(a[c],l,n);return o}function Vs(t,e){let{route:r,pathname:n,params:s}=t;return{id:r.id,pathname:n,params:s,data:e[r.id],loaderData:e[r.id],handle:r.handle}}function Ks(t){let e=Tn(t);return Js(e),e}function Tn(t,e=[],r=[],n="",s=!1){let i=(a,o,l=s,c)=>{let h={relativePath:c===void 0?a.path||"":c,caseSensitive:a.caseSensitive===!0,childrenIndex:o,route:a};if(h.relativePath.startsWith("/")){if(!h.relativePath.startsWith(n)&&l)return;O(h.relativePath.startsWith(n),`Absolute route path "${h.relativePath}" nested under path "${n}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),h.relativePath=h.relativePath.slice(n.length)}let u=Q([n,h.relativePath]),p=r.concat(h);a.children&&a.children.length>0&&(O(a.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${u}".`),Tn(a.children,e,p,u,l)),!(a.path==null&&!a.index)&&e.push({path:u,score:ti(u,a.index),routesMeta:p.map((d,y)=>{let[v,m]=On(d.relativePath,d.caseSensitive,y===p.length-1);return{...d,matcher:v,compiledParams:m}})})};return t.forEach((a,o)=>{if(a.path===""||!a.path?.includes("?"))i(a,o);else for(let l of An(a.path))i(a,o,!0,l)}),e}function An(t){let e=t.split("/");if(e.length===0)return[];let[r,...n]=e,s=r.endsWith("?"),i=r.replace(/\?$/,"");if(n.length===0)return s?[i,""]:[i];let a=An(n.join("/")),o=[];return o.push(...a.map(l=>l===""?i:[i,l].join("/"))),s&&o.push(...a),o.map(l=>t.startsWith("/")&&l===""?"/":l)}function Js(t){t.sort((e,r)=>e.score!==r.score?r.score-e.score:ri(e.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}var Gs=/^:[\w-]+$/,Ys=3,Xs=2,Qs=1,Zs=10,ei=-2,Tr=t=>t==="*";function ti(t,e){let r=t.split("/"),n=r.length;return r.some(Tr)&&(n+=ei),e&&(n+=Xs),r.filter(s=>!Tr(s)).reduce((s,i)=>s+(Gs.test(i)?Ys:i===""?Qs:Zs),n)}function ri(t,e){return t.length===e.length&&t.slice(0,-1).every((r,n)=>r===e[n])?t[t.length-1]-e[e.length-1]:0}function ni(t,e,r=!1){let{routesMeta:n}=t,s={},i="/",a=[];for(let o=0;o<n.length;++o){let l=n[o],c=o===n.length-1,h=i==="/"?e:e.slice(i.length)||"/",u={path:l.relativePath,caseSensitive:l.caseSensitive,end:c},p=l.matcher&&l.compiledParams?Cn(u,h,l.matcher,l.compiledParams):bt(u,h),d=l.route;if(!p&&c&&r&&!n[n.length-1].route.index&&(p=bt({path:l.relativePath,caseSensitive:l.caseSensitive,end:!1},h)),!p)return null;
2Object.assign(s,p.params),a.push({params:s,pathname:Q([i,p.pathname]),pathnameBase:oi(Q([i,p.pathnameBase])),route:d}),p.pathnameBase!=="/"&&(i=Q([i,p.pathnameBase]))}return a}function bt(t,e){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[r,n]=On(t.path,t.caseSensitive,t.end);return Cn(t,e,r,n)}function Cn(t,e,r,n){let s=e.match(r);if(!s)return null;let i=s[0],a=i.replace(/(.)\/+$/,"$1"),o=s.slice(1);return{params:n.reduce((l,{paramName:c,isOptional:h},u)=>{if(c==="*"){let d=o[u]||"";a=i.slice(0,i.length-d.length).replace(/(.)\/+$/,"$1")}const p=o[u];return h&&!p?l[c]=void 0:l[c]=(p||"").replace(/%2F/g,"/"),l},{}),pathname:i,pathnameBase:a,pattern:t}}function On(t,e=!1,r=!0){H(t==="*"||!t.endsWith("*")||t.endsWith("/*"),`Route path "${t}" will be treated as if it were "${t.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${t.replace(/\*$/,"/*")}".`);let n=[],s="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,a,o,l,c)=>{if(n.push({paramName:a,isOptional:o!=null}),o){let h=c.charAt(l+i.length);return h&&h!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(n.push({paramName:"*"}),s+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?s+="\\/*$":t!==""&&t!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),n]}function si(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return H(!1,`The URL path "${t}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).`),t}}function te(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let r=e.endsWith("/")?e.length-1:e.length,n=t.charAt(r);return n&&n!=="/"?null:t.slice(r)||"/"}function ii(t,e="/"){let{pathname:r,search:n="",hash:s=""}=typeof t=="string"?je(t):t,i;return r?(r=Pn(r),r.startsWith("/")?i=Ar(r.substring(1),"/"):i=Ar(r,e)):i=e,{pathname:i,search:li(n),hash:ci(s)}}function Ar(t,e){let r=_t(e).split("/");return t.split("/").forEach(n=>{n===".."?r.length>1&&r.pop():n!=="."&&r.push(n)}),r.length>1?r.join("/"):"/"}function Bt(t,e,r,n){return`Cannot include a '${t}' character in a manually specified \`to.${e}\` field [${JSON.stringify(n)}]. Please separate it out to the \`to.${r}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function ai(t){return t.filter((e,r)=>r===0||e.route.path&&e.route.path.length>0)}function fr(t){let e=ai(t);return e.map((r,n)=>n===e.length-1?r.pathname:r.pathnameBase)}function Pt(t,e,r,n=!1){let s;typeof t=="string"?s=je(t):(s={...t},O(!s.pathname||!s.pathname.includes("?"),Bt("?","pathname","search",s)),O(!s.pathname||!s.pathname.includes("#"),Bt("#","pathname","hash",s)),O(!s.search||!s.search.includes("#"),Bt("#","search","hash",s)));let i=t===""||s.pathname==="",a=i?"/":s.pathname,o;if(a==null)o=r;else{let u=e.length-1;if(!n&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),u-=1;s.pathname=p.join("/")}o=u>=0?e[u]:"/"}let l=ii(s,o),c=a&&a!=="/"&&a.endsWith("/"),h=(i||a===".")&&r.endsWith("/");return!l.pathname.endsWith("/")&&(c||h)&&(l.pathname+="/"),l}var Pn=t=>t.replace(/[\\/]{2,}/g,"/"),Q=t=>Pn(t.join("/")),_t=t=>t.replace(/\/+$/,""),oi=t=>_t(t).replace(/^\/*/,"/"),li=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,ci=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t,ui=class{constructor(t,e,r,n=!1){this.status=t,this.statusText=e||"",this.internal=n,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}};function jn(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}function hi(t){return Q(t.map(e=>e.route.path).filter(Boolean))||"/"}var In=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Nn(t,e){let r=t;if(typeof r!="string"||!dr.test(r))return{absoluteURL:void 0,isExternal:!1,to:r};let n=r,s=!1;if(In)try{let i=new URL(window.location.href),a=Sn.test(r)?new URL(Ms(r,i.protocol)):new URL(r),o=te(a.pathname,e);a.origin===i.origin&&o!=null?r=o+a.search+a.hash:s=!0}catch{H(!1,`<Link to="${r}">
2 contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:n,isExternal:s,to:r}}var Ru=Object.getOwnPropertyNames(Object.prototype).sort().join("\0"),$n=["POST","PUT","PATCH","DELETE"],xu=new Set($n),di=["GET",...$n],Tu=new Set(di),fi,pi,mi,gi;fi=new WeakMap;pi=new WeakMap;mi=new WeakMap;gi=new WeakMap;var vi=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function yi(t){try{return vi.includes(new URL(t).protocol)}catch{return!1}}var Ie=f.createContext(null);Ie.displayName="DataRouter";var Ye=f.createContext(null);Ye.displayName="DataRouterState";var Ln=f.createContext(!1);function Dn(){return f.useContext(Ln)}var Un=f.createContext({isTransitioning:!1});Un.displayName="ViewTransition";var wi=f.createContext(new Map);wi.displayName="Fetchers";var Xt=f.createContext(null);Xt.displayName="Await";var B=f.createContext(null);B.displayName="Navigation";var Xe=f.createContext(null);Xe.displayName="Location";var K=f.createContext({outlet:null,matches:[],isDataRoute:!1});K.displayName="Route";var pr=f.createContext(null);pr.displayName="RouteError";var Bn="REACT_ROUTER_ERROR",bi="REDIRECT",_i="ROUTE_ERROR_RESPONSE";function Ei(t){if(t.startsWith(`${Bn}:${bi}:{`))try{let e=JSON.parse(t.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function ki(t){if(t.startsWith(`${Bn}:${_i}:{`))try{let e=JSON.parse(t.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new ui(e.status,e.statusText,e.data)}catch{}}function Si(t,{relative:e}={}){O(Ne(),"useHref() may be used only in the context of a <Router> component.");let{basename:r,navigator:n}=f.useContext(B),{hash:s,pathname:i,search:a}=Qe(t,{relative:e}),o=i;return r!=="/"&&(o=i==="/"?r:Q([r,i])),n.createHref({pathname:o,search:a,hash:s})}function Ne(){return f.useContext(Xe)!=null}function U(){return O(Ne(),"useLocation() may be used only in the context of a <Router> component."),f.useContext(Xe).location}var Mn="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function Fn(t){f.useContext(B).static||f.useLayoutEffect(t)}function mr(){let{isDataRoute:t}=f.useContext(K);return t?Bi():Ri()}function Ri(){O(Ne(),"useNavigate() may be used only in the context of a <Router> component.");let t=f.useContext(Ie),{basename:e,navigator:r}=f.useContext(B),{matches:n}=f.useContext(K),{pathname:s}=U(),i=JSON.stringify(fr(n)),a=f.useRef(!1);return Fn(()=>{a.current=!0}),f.useCallback((o,l={})=>{if(H(a.current,Mn),!a.current)return;if(typeof o=="number"){r.go(o);return}let c=Pt(o,JSON.parse(i),s,l.relative==="path");t==null&&e!=="/"&&(c.pathname=c.pathname==="/"?e:Q([e,c.pathname])),(l.replace?r.replace:r.push)(c,l.state,l)},[e,r,i,s,t])}var xi=f.createContext(null);function Ti(t){let e=f.useContext(K).outlet;return f.useMemo(()=>e&&f.createElement(xi.Provider,{value:t},e),[e,t])}function Au(){let{matches:t}=f.useContext(K);return t[t.length-1]?.params??{}}function Qe(t,{relative:e}={}){let{matches:r}=f.useContext(K),{pathname:n}=U(),s=JSON.stringify(fr(r));return f.useMemo(()=>Pt(t,JSON.parse(s),n,e==="path"),[t,s,n,e])}function Ai(t,e){return Hn(t,e)}function Hn(t,e,r){O(Ne(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:n}=f.useContext(B),{matches:s}=f.useContext(K),i=s[s.length-1],a=i?i.params:{},o=i?i.pathname:"/",l=i?i.pathnameBase:"/",c=i&&i.route;{let m=c&&c.path||"";zn(o,!c||m.endsWith("*")||m.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${o}" (under <Route path="${m}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. 3 4Please change the parent <Route path="${m}"> to <Route path="${m==="/"?"*":`${m}/*`}">.`)}let h=U(),u;if(e){let m=typeof e=="string"?je(e):e;O(l==="/"||m.pathname?.startsWith(l),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${l}" but pathname "${m.pathname}" was given in the \`location\` prop.`),u=m}else u=h;let p=u.pathname||"/",d=p;if(l!=="/"){let m=l.replace(/^\//,"").split("/");d="/"+p.replace(/^\//,"").split("/").slice(m.length).join("/")}let y=r&&r.state.matches.length?r.state.matches.map(m=>Object.assign(m,{route:r.manifest[m.route.id]||m.route})):Rn(t,{pathname:d});H(c||y!=null,`No routes matched location "${u.pathname}${u.search}${u.hash}" `),H(y==null||y[y.length-1].route.element!==void 0||y[y.length-1].route.Component!==void 0||y[y.length-1].route.lazy!==void 0,`Matched leaf route at location "${u.pathname}${u.search}${u.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let v=Ii(y&&y.map(m=>Object.assign({},m,{params:Object.assign({},a,m.params),pathname:Q([l,n.encodeLocation?n.encodeLocation(m.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:m.pathname]),pathnameBase:m.pathnameBase==="/"?l:Q([l,n.encodeLocation?n.encodeLocation(m.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:m.pathnameBase])})),s,r);return e&&v?f.createElement(Xe.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...u},navigationType:"POP"}},v):v}function Ci(){let t=Ui(),e=jn(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,n="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:n},i={padding:"2px 4px",backgroundColor:n},a=null;return console.error("Error handled by React Router default ErrorBoundary:",t),a=f.createElement(f.Fragment,null,f.createElement("p",null,"ð¿ Hey developer ð"),f.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",f.createElement("code",{style:i},"ErrorBoundary")," or"," ",f.createElement("code",{style:i},"errorElement")," prop on your route.")),f.createElement(f.Fragment,null,f.createElement("h2",null,"Unexpected Application
4Error!"),f.createElement("h3",{style:{fontStyle:"italic"}},e),r?f.createElement("pre",{style:s},r):null,a)}var Oi=f.createElement(Ci,null),qn=class extends f.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,e){return e.location!==t.location||e.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:e.error,location:e.location,revalidation:t.revalidation||e.revalidation}}componentDidCatch(t,e){this.props.onError?this.props.onError(t,e):console.error("React Router caught the following error during render",t)}render(){let t=this.state.error;if(this.context&&typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){const r=ki(t.digest);r&&(t=r)}let e=t!==void 0?f.createElement(K.Provider,{value:this.props.routeContext},f.createElement(pr.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?f.createElement(Pi,{error:t},e):e}};qn.contextType=Ln;var Mt=new WeakMap;function Pi({children:t,error:e}){let{basename:r}=f.useContext(B);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let n=Ei(e.digest);if(n){let s=Mt.get(e);if(s)throw s;let i=Nn(n.location,r),a=i.absoluteURL||i.to;if(yi(a))throw new Error("Invalid redirect location");if(In&&!Mt.get(e))if(i.isExternal||n.reloadDocument)window.location.href=a;else{const o=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:n.replace}));throw Mt.set(e,o),o}return f.createElement("meta",{httpEquiv:"refresh",content:`0;url=${a}`})}}return t}function ji({routeContext:t,match:e,children:r}){let n=f.useContext(Ie);return n&&n.static&&n.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(n.staticContext._deepestRenderedBoundaryId=e.route.id),f.createElement(K.Provider,{value:t},r)}function Ii(t,e=[],r){let n=r?.state;if(t==null){if(!n)return null;if(n.errors)t=n.matches;else if(e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let s=t,i=n?.errors;if(i!=null){let h=s.findIndex(u=>u.route.id&&i?.[u.route.id]!==void 0);O(h>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(i).join(",")}`),s=s.slice(0,Math.min(s.length,h+1))}let a=!1,o=-1;if(r&&n){a=n.renderFallback;for(let h=0;h<s.length;h++){let u=s[h];if((u.route.HydrateFallback||u.route.hydrateFallbackElement)&&(o=h),u.route.id){let{loaderData:p,errors:d}=n,y=u.route.loader&&!p.hasOwnProperty(u.route.id)&&(!d||d[u.route.id]===void 0);if(u.route.lazy||y){r.isStatic&&(a=!0),o>=0?s=s.slice(0,o+1):s=[s[0]];break}}}}let l=r?.onError,c=n&&l?(h,u)=>{l(h,{location:n.location,params:n.matches?.[0]?.params??{},pattern:hi(n.matches),errorInfo:u})}:void 0;return s.reduceRight((h,u,p)=>{let d,y=!1,v=null,m=null;n&&(d=i&&u.route.id?i[u.route.id]:void 0,v=u.route.errorElement||Oi,a&&(o<0&&p===0?(zn("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),y=!0,m=null):o===p&&(y=!0,m=u.route.hydrateFallbackElement||null)));let _=e.concat(s.slice(0,p+1)),b=()=>{let w;return d?w=v:y?w=m:u.route.Component?w=f.createElement(u.route.Component,null):u.route.element?w=u.route.element:w=h,f.createElement(ji,{match:u,routeContext:{outlet:h,matches:_,isDataRoute:n!=null},children:w})};return n&&(u.route.ErrorBoundary||u.route.errorElement||p===0)?f.createElement(qn,{location:n.location,revalidation:n.revalidation,component:v,error:d,children:b(),routeContext:{outlet:null,matches:_,isDataRoute:!0},onError:c}):b()},null)}function gr(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Ni(t){let e=f.useContext(Ie);return O(e,gr(t)),e}function vr(t){let e=f.useContext(Ye);return O(e,gr(t)),e}function $i(t){let e=f.useContext(K);return O(e,gr(t)),e}function yr(t){let e=$i(t),r=e.matches[e.matches.length-1];return O(r.route.id,`${t} can only be used on routes that contain a unique "id"`),r.route.id}function Li(){return yr("useRouteId")}function Di(){let t=vr("useNavigation");return f.useMemo(()=>{let{matches:e,historyAction:r,...n}=t.navigation;return n},[t.navigation])}function Wn(){let{matches:t,loaderData:e}=vr("useMatches");return f.useMemo(()=>t.map(r=>Vs(r,e)),[t,e])}function Ui(){let t=f.useContext(pr),e=vr("useRouteError"),r=yr("useRouteError");return t!==void 0?t:e.errors?.[r]}function Bi(){let{router:t}=Ni("useNavigate"),e=yr("useNavigate"),r=f.useRef(!1);return Fn(()=>{r.current=!0}),f.useCallback(async(n,s={})=>{H(r.current,Mn),r.current&&(typeof n=="number"?await t.navigate(n):await t.navigate(n,{fromRouteId:e,...s}))},[t,e])}var Cr={};function zn(t,e,r){!e&&!Cr[t]&&(Cr[t]=!0,H(!1,r))}var Or={};function Mi(t,e){!t&&!Or[e]&&(Or[e]=!0,console.warn(e))}var Cu=f.memo(Fi);function Fi({routes:t,manifest:e,future:r,state:n,isStatic:s,onError:i}){return Hn(t,void 0,{manifest:e,state:n,isStatic:s,onError:i,future:r})}function ft({to:t,replace:e,state:r,relative:n}){O(Ne(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=f.useContext(B);H(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:i}=f.useContext(K),{pathname:a}=U(),o=mr(),l=Pt(t,fr(i),a,n==="path"),c=JSON.stringify(l);return f.useEffect(()=>{o(JSON.parse(c),{replace:e,state:r,relative:n})},[o,c,n,e,r]),null}function Hi(t){return Ti(t.context)}function I(t){O(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function Vn({basename:t="/",children:e=null,location:r,navigationType:n="POP",navigator:s,static:i=!1,useTransitions:a}){O(!Ne(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let o=t.replace(/^\/*/,"/"),l=f.useMemo(()=>({basename:o,navigator:s,static:i,useTransitions:a,future:{}}),[o,s,i,a]);typeof r=="string"&&(r=je(r));let{pathname:c="/",search:h="",hash:u="",state:p=null,key:d="default",mask:y}=r,v=f.useMemo(()=>{let m=te(c,o);return m==null?null:{location:{pathname:m,search:h,hash:u,state:p,key:d,mask:y},navigationType:n}},[o,c,h,u,p,d,n,y]);
4return H(v!=null,`<Router basename="${o}"> is not able to match the URL "${c}${h}${u}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:f.createElement(B.Provider,{value:l},f.createElement(Xe.Provider,{children:e,value:v}))}function qi({children:t,location:e}){return Ai(Qt(t),e)}var Ou=class extends f.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,e){this.props.onError?this.props.onError(t,e):console.error("<Await> caught the following error during render",t,e)}render(){let{children:t,errorElement:e,resolve:r}=this.props,n=null,s=0;if(!(r instanceof Promise))s=1,n=Promise.resolve(),Object.defineProperty(n,"_tracked",{get:()=>!0}),Object.defineProperty(n,"_data",{get:()=>r});else if(this.state.error){s=2;let i=this.state.error;n=Promise.reject().catch(()=>{}),Object.defineProperty(n,"_tracked",{get:()=>!0}),Object.defineProperty(n,"_error",{get:()=>i})}else r._tracked?(n=r,s="_error"in n?2:"_data"in n?1:0):(s=0,Object.defineProperty(r,"_tracked",{get:()=>!0}),n=r.then(i=>Object.defineProperty(r,"_data",{get:()=>i}),i=>{this.props.onError?.(i),Object.defineProperty(r,"_error",{get:()=>i})}));if(s===2&&!e)throw n._error;if(s===2)return f.createElement(Xt.Provider,{value:n,children:e});if(s===1)return f.createElement(Xt.Provider,{value:n,children:t});throw n}};function Qt(t,e=[]){let r=[];return f.Children.forEach(t,(n,s)=>{if(!f.isValidElement(n))return;let i=[...e,s];if(n.type===f.Fragment){r.push.apply(r,Qt(n.props.children,i));return}O(n.type===I,`[${typeof n.type=="string"?n.type:n.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),O(!n.props.index||!n.props.children,"An index route cannot have child routes.");let a={id:n.props.id||i.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,middleware:n.props.middleware,loader:n.props.loader,action:n.props.action,hydrateFallbackElement:n.props.hydrateFallbackElement,HydrateFallback:n.props.HydrateFallback,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.hasErrorBoundary===!0||n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(a.children=Qt(n.props.children,i)),r.push(a)}),r}var pt="get",mt="application/x-www-form-urlencoded";function jt(t){return typeof HTMLElement<"u"&&t instanceof HTMLElement}function Wi(t){return jt(t)&&t.tagName.toLowerCase()==="button"}function zi(t){return jt(t)&&t.tagName.toLowerCase()==="form"}function Vi(t){return jt(t)&&t.tagName.toLowerCase()==="input"}function Ki(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function Ji(t,e){return t.button===0&&(!e||e==="_self")&&!Ki(t)}function Zt(t=""){return new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,r)=>{let n=t[r];return e.concat(Array.isArray(n)?n.map(s=>[r,s]):[[r,n]])},[]))}function Gi(t,e){let r=Zt(t);return e&&e.forEach((n,s)=>{r.has(s)||e.getAll(s).forEach(i=>{r.append(s,i)})}),r}var rt=null;function Yi(){if(rt===null)try{new FormData(document.createElement("form"),0),rt=!1}catch{rt=!0}return rt}var Xi=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Ft(t){return t!=null&&!Xi.has(t)?(H(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${mt}"`),null):t}function Qi(t,e){let r,n,s,i,a;if(zi(t)){let o=t.getAttribute("action");n=o?te(o,e):null,r=t.getAttribute("method")||pt,s=Ft(t.getAttribute("enctype"))||mt,i=new FormData(t)}else if(Wi(t)||Vi(t)&&(t.type==="submit"||t.type==="image")){let o=t.form;if(o==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let l=t.getAttribute("formaction")||o.getAttribute("action");if(n=l?te(l,e):null,r=t.getAttribute("formmethod")||o.getAttribute("method")||pt,s=Ft(t.getAttribute("formenctype"))||Ft(o.getAttribute("enctype"))||mt,i=new FormData(o,t),!Yi()){let{name:c,type:h,value:u}=t;if(h==="image"){let p=c?`${c}.`:"";i.append(`${p}x`,"0"),i.append(`${p}y`,"0")}else c&&i.append(c,u)}}else{if(jt(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');
4r=pt,n=null,s=mt,a=t}return i&&s==="text/plain"&&(a=i,i=void 0),{action:n,method:r.toLowerCase(),encType:s,formData:i,body:a}}var Pu=Object.getOwnPropertyNames(Object.prototype).sort().join("\0"),Zi={"&":"\\u0026",">":"\\u003e","<":"\\u003c","\u2028":"\\u2028","\u2029":"\\u2029"},ea=/[&><\u2028\u2029]/g;function Pr(t){return t.replace(ea,e=>Zi[e])}function It(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function Kn(t,e,r,n){let s=typeof t=="string"?new URL(t,typeof window>"u"?"server://singlefetch/":window.location.origin):t;return r?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${n}`:s.pathname=`${s.pathname}.${n}`:s.pathname==="/"?s.pathname=`_root.${n}`:e&&te(s.pathname,e)==="/"?s.pathname=`${_t(e)}/_root.${n}`:s.pathname=`${_t(s.pathname)}.${n}`,s}async function ta(t,e){if(t.id in e)return e[t.id];try{let r=await W(()=>import(t.module),[]);return e[t.id]=r,r}catch(r){return console.error(`Error loading route module \`${t.module}\`, reloading page...`),console.error(r),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function ra(t){return t!=null&&typeof t.page=="string"}function na(t){return t==null?!1:t.href==null?t.rel==="preload"&&typeof t.imageSrcSet=="string"&&typeof t.imageSizes=="string":typeof t.rel=="string"&&typeof t.href=="string"}async function sa(t,e,r){return oa((await Promise.all(t.map(async n=>{let s=e.routes[n.route.id];if(s){let i=await ta(s,r);return i.links?i.links():[]}return[]}))).flat(1).filter(na).filter(n=>n.rel==="stylesheet"||n.rel==="preload").map(n=>n.rel==="stylesheet"?{...n,rel:"prefetch",as:"style"}:{...n,rel:"prefetch"}))}function jr(t,e,r,n,s,i){let a=(l,c)=>r[c]?l.route.id!==r[c].route.id:!0,o=(l,c)=>r[c].pathname!==l.pathname||r[c].route.path?.endsWith("*")&&r[c].params["*"]!==l.params["*"];return i==="assets"?e.filter((l,c)=>a(l,c)||o(l,c)):i==="data"?e.filter((l,c)=>{let h=n.routes[l.route.id];if(!h||!h.hasLoader)return!1;if(a(l,c)||o(l,c))return!0;if(l.route.shouldRevalidate){let u=l.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:r[0]?.params||{},nextUrl:new URL(t,window.origin),nextParams:l.params,defaultShouldRevalidate:!0});if(typeof u=="boolean")return u}return!0}):[]}function Jn(t,e,{includeHydrateFallback:r}={}){return ia(t.map(n=>{let s=e.routes[n.route.id];if(!s)return[];let i=[s.module];return s.clientActionModule&&(i=i.concat(s.clientActionModule)),s.clientLoaderModule&&(i=i.concat(s.clientLoaderModule)),r&&s.hydrateFallbackModule&&(i=i.concat(s.hydrateFallbackModule)),s.imports&&(i=i.concat(s.imports)),i}).flat(1))}function ia(t){return[...new Set(t)]}function aa(t){let e={},r=Object.keys(t).sort();for(let n of r)e[n]=t[n];return e}function oa(t,e){let r=new Set,n=new Set(e);return t.reduce((s,i)=>{if(e&&!ra(i)&&i.as==="script"&&i.href&&n.has(i.href))return s;let a=JSON.stringify(aa(i));return r.has(a)||(r.add(a),s.push({key:a,link:i})),s},[])}function la(t,e){return t.mode==="lazy"&&e===!0}function ca({sri:t,...e},r){let n=new Set(r.state.matches.map(o=>o.route.id)),s=r.state.location.pathname.split("/").filter(Boolean),i=["/"];for(s.pop();s.length>0;)i.push(`/${s.join("/")}`),s.pop();i.forEach(o=>{let l=xn(r.routes,o,r.basename||"/",!1,r.branches);l&&l.forEach(c=>n.add(c.route.id))});let a=[...n].reduce((o,l)=>Object.assign(o,{[l]:e.routes[l]}),{});return{...e,routes:a,sri:t?!0:void 0}}function Nt(){let t=f.useContext(Ie);return It(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function Gn(){let t=f.useContext(Ye);return It(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var $t=f.createContext(void 0);$t.displayName="FrameworkContext";function ye(){let t=f.useContext($t);return It(t,"You must render this element inside a <HydratedRouter> element"),t}function ua(t,e){let r=f.useContext($t),[n,s]=f.useState(!1),[i,a]=f.useState(!1),{onFocus:o,onBlur:l,onMouseEnter:c,onMouseLeave:h,onTouchStart:u}=e,p=f.useRef(null);f.useEffect(()=>{if(t==="render"&&a(!0),t==="viewport"){let v=_=>{_.forEach(b=>{a(b.isIntersecting)})},m=new IntersectionObserver(v,{threshold:.5});return p.current&&m.observe(p.current),()=>{m.disconnect()}}},[t]),f.useEffect(()=>{if(n){let v=setTimeout(()=>{a(!0)},100);return()=>{clearTimeout(v)}}},[n]);let d=()=>{s(!0)},y=()=>{s(!1),a(!1)};return r?t!=="intent"?[i,p,{}]:[i,p,{onFocus:Le(o,d),onBlur:Le(l,y),onMouseEnter:Le(c,d),onMouseLeave:Le(h,y),onTouchStart:Le(u,d)}]:[!1,p,{}]}function Le(t,e){return r=>{t&&t(r),r.defaultPrevented||e(r)}}function ha(t,e,r){if(r&&!Et)return[t[0]];if(e){let n=t.findIndex(s=>e[s.route.id]!==void 0);return t.slice(0,n+1)}return t}function da({page:t,...e}){let r=Dn(),{nonce:n}=ye(),{router:s}=Nt(),i=f.useMemo(()=>Rn(s.routes,t,s.basename),[s.routes,t,s.basename]);return i?(e.nonce==null&&n&&(e={...e,nonce:n}),r?f.createElement(pa,{page:t,matches:i,...e}):f.createElement(ma,{page:t,matches:i,...e})):null}function fa(t){let{manifest:e,routeModules:r}=ye(),[n,s]=f.useState([]);return f.useEffect(()=>{let i=!1;return sa(t,e,r).then(a=>{i||s(a)}),()=>{i=!0}},[t,e,r]),n}function pa({page:t,matches:e,...r}){let n=U(),{future:s}=ye(),{basename:i}=Nt(),a=f.useMemo(()=>
4{if(t===n.pathname+n.search+n.hash)return[];let o=Kn(t,i,s.v8_trailingSlashAwareDataRequests,"rsc"),l=!1,c=[];for(let h of e)typeof h.route.shouldRevalidate=="function"?l=!0:c.push(h.route.id);return l&&c.length>0&&o.searchParams.set("_routes",c.join(",")),[o.pathname+o.search]},[i,s.v8_trailingSlashAwareDataRequests,t,n,e]);return f.createElement(f.Fragment,null,a.map(o=>f.createElement("link",{key:o,rel:"prefetch",as:"fetch",href:o,...r})))}function ma({page:t,matches:e,...r}){let n=U(),{future:s,manifest:i,routeModules:a}=ye(),{basename:o}=Nt(),{loaderData:l,matches:c}=Gn(),h=f.useMemo(()=>jr(t,e,c,i,n,"data"),[t,e,c,i,n]),u=f.useMemo(()=>jr(t,e,c,i,n,"assets"),[t,e,c,i,n]),p=f.useMemo(()=>{if(t===n.pathname+n.search+n.hash)return[];let v=new Set,m=!1;if(e.forEach(b=>{let w=i.routes[b.route.id];!w||!w.hasLoader||(!h.some(T=>T.route.id===b.route.id)&&b.route.id in l&&a[b.route.id]?.shouldRevalidate||w.hasClientLoader?m=!0:v.add(b.route.id))}),v.size===0)return[];let _=Kn(t,o,s.v8_trailingSlashAwareDataRequests,"data");return m&&v.size>0&&_.searchParams.set("_routes",e.filter(b=>v.has(b.route.id)).map(b=>b.route.id).join(",")),[_.pathname+_.search]},[o,s.v8_trailingSlashAwareDataRequests,l,n,i,h,e,t,a]),d=f.useMemo(()=>Jn(u,i),[u,i]),y=fa(u);return f.createElement(f.Fragment,null,p.map(v=>f.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...r})),d.map(v=>f.createElement("link",{key:v,rel:"modulepreload",href:v,...r})),y.map(({key:v,link:m})=>f.createElement("link",{key:v,nonce:r.nonce,...m,crossOrigin:m.crossOrigin??r.crossOrigin})))}var Et=!1;function ga(){Et=!0}function va(t){let{manifest:e,serverHandoffString:r,isSpaMode:n,renderMeta:s,routeDiscovery:i,ssr:a,nonce:o}=ye(),{router:l,static:c,staticContext:h}=Nt(),{matches:u}=Gn(),p=Dn(),d=la(i,a);t.nonce==null&&o&&(t={...t,nonce:o}),s&&(s.didRenderScripts=!0);let y=ha(u,null,n);f.useEffect(()=>{ga()},[]);let v=f.useMemo(()=>{if(p)return null;let b=h?`window.__reactRouterContext = ${r};window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());`:" ",w=c?`${e.hmr?.runtime?`import ${JSON.stringify(e.hmr.runtime)};`:""}${d?"":`import ${JSON.stringify(e.url)}`}; 5${y.map((T,x)=>{let S=`route${x}`,A=e.routes[T.route.id];It(A,`Route ${T.route.id} not found in manifest`);let{clientActionModule:z,clientLoaderModule:N,clientMiddlewareModule:we,hydrateFallbackModule:et,module:tt}=A,be=[...z?[{module:z,varName:`${S}_clientAction`}]:[],...N?[{module:N,varName:`${S}_clientLoader`}]:[],...we?[{module:we,varName:`${S}_clientMiddleware`}]:[],...et?[{module:et,varName:`${S}_HydrateFallback`}]:[],{module:tt,varName:`${S}_main`}];return be.length===1?`import * as ${S} from ${JSON.stringify(tt)};`:[be.map(de=>`import * as ${de.varName} from "${de.module}";`).join(` 6`),`const ${S} = {${be.map(de=>`...${de.varName}`).join(",")}};`].join(` 7`)}).join(` 8`)} 9 ${d?`window.__reactRouterManifest = ${JSON.stringify(ca(e,l),null,2)};`:""} 10 window.__reactRouterRouteModules = {${y.map((T,x)=>`${JSON.stringify(T.route.id)}:route${x}`).join(",")}}; 11 12import(${JSON.stringify(e.entry.module)});`:" ";return f.createElement(f.Fragment,null,f.createElement("script",{...t,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:b},type:void 0}),f.createElement("script",{...t,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:w},type:"module",async:!0}))},[]),m=Et||p?[]:[...new Set(e.entry.imports.concat(Jn(y,e,{includeHydrateFallback:!0})))],_=typeof e.sri=="object"?e.sri:{};return Mi(!p,"The <Scripts /> element is a no-op when using RSC and can be safely removed."),Et||p?null:f.createElement(f.Fragment,null,typeof e.sri=="object"?f.createElement("script",{...t,"rr-importmap":"",type:"importmap",suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:JSON.stringify({integrity:_})}}):null,d?null:f.createElement("link",{rel:"modulepreload",href:e.url,crossOrigin:t.crossOrigin,integrity:_[e.url],nonce:t.nonce,suppressHydrationWarning:!0}),f.createElement("link",{rel:"modulepreload",href:e.entry.module,crossOrigin:t.crossOrigin,integrity:_[e.entry.module],nonce:t.nonce,suppressHydrationWarning:!0}),m.map(b=>f.createElement("link",{key:b,rel:"modulepreload",href:b,crossOrigin:t.crossOrigin,integrity:_[b],nonce:t.nonce,suppressHydrationWarning:!0})),v)}function ya(...t){return e=>{t.forEach(r=>
12{typeof r=="function"?r(e):r!=null&&(r.current=e)})}}var ju=class extends f.Component{constructor(t){super(t),this.state={error:t.error||null,location:t.location}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,e){return e.location!==t.location?{error:t.error||null,location:t.location}:{error:t.error||e.error,location:e.location}}render(){return this.state.error?f.createElement(wa,{error:this.state.error,isOutsideRemixApp:!0}):this.props.children}};function wa({error:t,isOutsideRemixApp:e}){let{nonce:r}=ye();console.error(t);let n=f.createElement("script",{nonce:r,dangerouslySetInnerHTML:{__html:` 13 console.log( 14 "ð¿ Hey developer ð. You can provide a way better UX than this when your app throws errors. Check out https://reactrouter.com/how-to/error-boundary for more information." 15 ); 16 `}});if(jn(t))return f.createElement(Ir,{title:"Unhandled Thrown Response!"},f.createElement("h1",{style:{fontSize:"24px"}},t.status," ",t.statusText),n);let s;if(t instanceof Error)s=t;else{let i=t==null?"Unknown Error":typeof t=="object"&&"toString"in t?t.toString():JSON.stringify(t);s=new Error(i)}return f.createElement(Ir,{title:"Application Error!",isOutsideRemixApp:e},f.createElement("h1",{style:{fontSize:"24px"}},"Application Error"),f.createElement("pre",{style:{padding:"2rem",background:"hsla(10, 50%, 50%, 0.1)",color:"red",overflow:"auto"}},s.stack),n)}function Ir({title:t,renderScripts:e,isOutsideRemixApp:r,children:n}){let{routeModules:s}=ye();return s.root?.Layout&&!r?n:f.createElement("html",{lang:"en"},f.createElement("head",null,f.createElement("meta",{charSet:"utf-8"}),f.createElement("meta",{name:"viewport",content:"width=device-width,initial-scale=1,viewport-fit=cover"}),f.createElement("title",null,t)),f.createElement("body",null,f.createElement("main",{style:{fontFamily:"system-ui, sans-serif",padding:"2rem"}},n,e?f.createElement(va,null):null)))}var ba=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{ba&&(window.__reactRouterVersion="7.18.2")}catch{}function _a({basename:t,children:e,useTransitions:r,window:n}){let s=f.useRef();s.current==null&&(s.current=Fs({window:n,v5Compat:!0}));let i=s.current,[a,o]=f.useState({action:i.action,location:i.location}),l=f.useCallback(c=>{r===!1?o(c):f.startTransition(()=>o(c))},[r]);return f.useLayoutEffect(()=>i.listen(l),[i,l]),f.createElement(Vn,{basename:t,children:e,location:a.location,navigationType:a.action,navigator:i,useTransitions:r})}function Ea({basename:t,children:e,history:r,useTransitions:n}){let[s,i]=f.useState({action:r.action,location:r.location}),a=f.useCallback(o=>{n===!1?i(o):f.startTransition(()=>i(o))},[n]);return f.useLayoutEffect(()=>r.listen(a),[r,a]),f.createElement(Vn,{basename:t,children:e,location:s.location,navigationType:s.action,navigator:r,useTransitions:n})}Ea.displayName="unstable_HistoryRouter";var Yn=f.forwardRef(function({onClick:e,discover:r="render",prefetch:n="none",relative:s,reloadDocument:i,replace:a,mask:o,state:l,target:c,to:h,preventScrollReset:u,viewTransition:p,defaultShouldRevalidate:d,...y},v){let{basename:m,navigator:_,useTransitions:b}=f.useContext(B),w=typeof h=="string"&&dr.test(h),T=Nn(h,m);h=T.to;let x=Si(h,{relative:s}),S=U(),A=null;if(o){let oe=Pt(o,[],S.mask?S.mask.pathname:"/",!0);m!=="/"&&(oe.pathname=oe.pathname==="/"?m:Q([m,oe.pathname])),A=_.createHref(oe)}let[z,N,we]=ua(n,y),et=Ta(h,{replace:a,mask:o,state:l,target:c,preventScrollReset:u,relative:s,viewTransition:p,defaultShouldRevalidate:d,useTransitions:b});function tt(oe){e&&e(oe),oe.defaultPrevented||et(oe)}let be=!(T.isExternal||i),de=f.createElement("a",{...y,...we,href:(be?A:void 0)||T.absoluteURL||x,onClick:be?tt:e,ref:ya(v,N),target:c,"data-discover":!w&&r==="render"?"true":void 0});return z&&!w?f.createElement(f.Fragment,null,de,f.createElement(da,{page:x})):de});Yn.displayName="Link";var ka=f.forwardRef(function({"aria-current":e="page",caseSensitive:r=!1,className:n="",end:s=!1,style:i,to:a,viewTransition:o,children:l,...c},h){let u=Qe(a,{relative:c.relative}),p=U(),d=f.useContext(Ye),{navigator:y,basename:v}=f.useContext(B),m=d!=null&&Na(u)&&o===!0,_=y.encodeLocation?y.encodeLocation(u).pathname:u.pathname,b=p.pathname,w=d&&d.navigation&&d.navigation.location?d.navigation.location.pathname:null;r||(b=b.toLowerCase(),w=w?w.toLowerCase():null,_=_.toLowerCase()),w&&v&&(w=te(w,v)||w);const T=_!=="/"&&_.endsWith("/")?_.length-1:_.length;let x=b===_||!s&&b.startsWith(_)&&b.charAt(T)==="/",S=w!=null&&(w===_||!s&&w.startsWith(_)&&w.charAt(_.length)==="/"),A={isActive:x,isPending:S,isTransitioning:m},z=x?e:void 0,N;typeof n=="function"?N=n(A):N=[n,x?"active":null,S?"pending":null,m?"transitioning":null].filter(
16Boolean).join(" ");let we=typeof i=="function"?i(A):i;return f.createElement(Yn,{...c,"aria-current":z,className:N,ref:h,style:we,to:a,viewTransition:o},typeof l=="function"?l(A):l)});ka.displayName="NavLink";var Sa=f.forwardRef(({discover:t="render",fetcherKey:e,navigate:r,reloadDocument:n,replace:s,state:i,method:a=pt,action:o,onSubmit:l,relative:c,preventScrollReset:h,viewTransition:u,defaultShouldRevalidate:p,...d},y)=>{let{useTransitions:v}=f.useContext(B),m=Oa(),_=Pa(o,{relative:c}),b=a.toLowerCase()==="get"?"get":"post",w=typeof o=="string"&&dr.test(o),T=x=>{if(l&&l(x),x.defaultPrevented)return;x.preventDefault();let S=x.nativeEvent.submitter,A=S?.getAttribute("formmethod")||a,z=()=>m(S||x.currentTarget,{fetcherKey:e,method:A,navigate:r,replace:s,state:i,relative:c,preventScrollReset:h,viewTransition:u,defaultShouldRevalidate:p});v&&r!==!1?f.startTransition(()=>z()):z()};return f.createElement("form",{ref:y,method:b,action:_,onSubmit:n?l:T,...d,"data-discover":!w&&t==="render"?"true":void 0})});Sa.displayName="Form";function Ra({getKey:t,storageKey:e,...r}){let n=f.useContext($t),{basename:s}=f.useContext(B),i=U(),a=Wn();ja({getKey:t,storageKey:e});let o=f.useMemo(()=>{if(!n||!t)return null;let c=tr(i,a,s,t);return c!==i.key?c:null},[]);if(!n||n.isSpaMode)return null;let l=((c,h)=>{if(!window.history.state||!window.history.state.key){let u=Math.random().toString(32).slice(2);window.history.replaceState({key:u},"")}try{let u=JSON.parse(sessionStorage.getItem(c)||"{}")[h||window.history.state.key];typeof u=="number"&&window.scrollTo(0,u)}catch(u){console.error(u),sessionStorage.removeItem(c)}}).toString();return r.nonce==null&&n?.nonce&&(r.nonce=n.nonce),f.createElement("script",{...r,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`(${l})(${Pr(JSON.stringify(e||er))}, ${Pr(JSON.stringify(o))})`}})}Ra.displayName="ScrollRestoration";function Xn(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function wr(t){let e=f.useContext(Ie);return O(e,Xn(t)),e}function xa(t){let e=f.useContext(Ye);return O(e,Xn(t)),e}function Ta(t,{target:e,replace:r,mask:n,state:s,preventScrollReset:i,relative:a,viewTransition:o,defaultShouldRevalidate:l,useTransitions:c}={}){let h=mr(),u=U(),p=Qe(t,{relative:a});return f.useCallback(d=>{if(Ji(d,e)){d.preventDefault();let y=r!==void 0?r:Fe(u)===Fe(p),v=()=>h(t,{replace:y,mask:n,state:s,preventScrollReset:i,relative:a,viewTransition:o,defaultShouldRevalidate:l});c?f.startTransition(()=>v()):v()}},[u,h,p,r,n,s,e,t,i,a,o,l,c])}function Iu(t){H(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let e=f.useRef(Zt(t)),r=f.useRef(!1),n=U(),s=f.useMemo(()=>Gi(n.search,r.current?null:e.current),[n.search]),i=mr();return[s,f.useCallback((a,o)=>{const l=Zt(typeof a=="function"?a(new URLSearchParams(s)):a);r.current=!0,i("?"+l,o)},[i,s])]}var Aa=0,Ca=()=>`__${String(++Aa)}__`;function Oa(){let{router:t}=wr("useSubmit"),{basename:e}=f.useContext(B),r=Li(),n=t.fetch,s=t.navigate;return f.useCallback(async(i,a={})=>{let{action:o,method:l,encType:c,formData:h,body:u}=Qi(i,e);if(a.navigate===!1){let p=a.fetcherKey||Ca();await n(p,r,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:h,body:u,formMethod:a.method||l,formEncType:a.encType||c,flushSync:a.flushSync})}else await s(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:h,body:u,formMethod:a.method||l,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:r,flushSync:a.flushSync,viewTransition:a.viewTransition})},[n,s,e,r])}function Pa(t,{relative:e}={}){let{basename:r}=f.useContext(B),n=f.useContext(K);O(n,"useFormAction must be used inside a RouteContext");let[s]=n.matches.slice(-1),i={...Qe(t||".",{relative:e})},a=U();if(t==null){i.search=a.search;let o=new URLSearchParams(i.search),l=o.getAll("index");if(l.some(c=>
16c==="")){o.delete("index"),l.filter(h=>h).forEach(h=>o.append("index",h));let c=o.toString();i.search=c?`?${c}`:""}}return(!t||t===".")&&s.route.index&&(i.search=i.search?i.search.replace(/^\?/,"?index&"):"?index"),r!=="/"&&(i.pathname=i.pathname==="/"?r:Q([r,i.pathname])),Fe(i)}var er="react-router-scroll-positions",nt={};function tr(t,e,r,n){let s=null;return n&&(r!=="/"?s=n({...t,pathname:te(t.pathname,r)||t.pathname},e):s=n(t,e)),s==null&&(s=t.key),s}function ja({getKey:t,storageKey:e}={}){let{router:r}=wr("useScrollRestoration"),{restoreScrollPosition:n,preventScrollReset:s}=xa("useScrollRestoration"),{basename:i}=f.useContext(B),a=U(),o=Wn(),l=Di();f.useEffect(()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"}),[]),Ia(f.useCallback(()=>{if(l.state==="idle"){let c=tr(a,o,i,t);nt[c]=window.scrollY}try{sessionStorage.setItem(e||er,JSON.stringify(nt))}catch(c){H(!1,`Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${c}).`)}window.history.scrollRestoration="auto"},[l.state,t,i,a,o,e])),typeof document<"u"&&(f.useLayoutEffect(()=>{try{let c=sessionStorage.getItem(e||er);c&&(nt=JSON.parse(c))}catch{}},[e]),f.useLayoutEffect(()=>{let c=r?.enableScrollRestoration(nt,()=>window.scrollY,t?(h,u)=>tr(h,u,i,t):void 0);return()=>c&&c()},[r,i,t]),f.useLayoutEffect(()=>{if(n!==!1){if(typeof n=="number"){window.scrollTo(0,n);return}try{if(a.hash){let c=document.getElementById(decodeURIComponent(a.hash.slice(1)));if(c){c.scrollIntoView();return}}}catch{H(!1,`"${a.hash.slice(1)}" is not a decodable element ID. The view will not scroll to it.`)}s!==!0&&window.scrollTo(0,0)}},[a,n,s]))}function Ia(t,e){let{capture:r}=e||{};f.useEffect(()=>{let n=r!=null?{capture:r}:void 0;return window.addEventListener("pagehide",t,n),()=>{window.removeEventListener("pagehide",t,n)}},[t,r])}function Na(t,{relative:e}={}){let r=f.useContext(Un);O(r!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:n}=wr("useViewTransitionState"),s=Qe(t,{relative:e});if(!r.isTransitioning)return!1;let i=te(r.currentLocation.pathname,n)||r.currentLocation.pathname,a=te(r.nextLocation.pathname,n)||r.nextLocation.pathname;return bt(s.pathname,a)!=null||bt(s.pathname,i)!=null}var g=js();function he({href:t,...e}){return(0,g.jsx)("a",{href:t,...e})}var Ht=[{kind:"link",label:"Programs",href:"/programs"},{kind:"link",label:"AIDD Service",href:"/aidd"},{kind:"link",label:"Team",href:"/team"},{kind:"link",label:"News",href:"/news"},{kind:"link",label:"Contact",href:"/contact"}];function $a(){return[{heading:"Science",links:[{label:"Programs",href:"/programs"},{label:"AIDD Service",href:"/aidd"}]},{heading:"Company",links:[{label:"Team",href:"/team"},{label:"News",href:"/news"}]},{heading:"Legal",links:[{label:"Privacy Policy",href:"/privacy"},{label:"Imprint",href:"/imprint"}]}]}var La="px-4 py-3 text-base font-medium text-gray-950 hover:bg-black/5 rounded-lg",Da="px-4 py-3 text-base font-medium text-white hover:bg-white/10 rounded-lg",Ua="pl-8 pr-4 py-2.5 text-base font-medium text-gray-950 hover:bg-black/5 rounded-lg",Ba="pl-8 pr-4 py-2.5 text-base font-medium text-white hover:bg-white/10 rounded-lg",Ma="px-4 py-2 text-base font-medium text-gray-950",Fa="px-4 py-2 text-base font-medium text-white";function Ha({item:t,navLinkClass:e}){switch(t.kind){case"link":return(0,g.jsx)(he,{href:t.href,className:e,children:t.label});case"menu":return(0,g.jsxs)("div",{className:"relative inline-block group",children:[(0,g.jsxs)("button",{type:"button",className:`${e} inline-flex items-center gap-1`,"aria-haspopup":"menu",children:[t.label,(0,g.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"size-4 shrink-0 opacity-60 transition group-hover:rotate-180","aria-hidden":!0,children:(0,g.jsx)("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),(0,g.jsx)("div",{className:"absolute left-0 top-full z-50 pt-2 opacity-0 invisible transition-[opacity,visibility] duration-150 group-hover:opacity-100 group-hover:visible group-focus-within:opacity-100 group-focus-within:visible",role:"menu","aria-label":`${t.label} menu`,children:(0,g.jsx)("div",{className:"min-w-[11rem] overflow-hidden rounded-lg bg-white/70 py-1 shadow-lg ring-1 ring-black/10",children:t.items.map(r=>(0,g.jsx)(he,{href:r.href,role:"menuitem",className:"block px-4 py-2.5 text-base font-medium text-gray-950 hover:bg-black/5",children:r.label},r.href))})})]});default:return t}}function Nr({item:t,navLinkClass:e,mobileMenuLabelClass:r,mobileNestedLinkClass:n}){switch(t.kind){case"link":return(0,g.jsx)(he,{href:t.href,className:e,children:t.label});case"menu":return(0,g.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,g.jsx)("span",{className:r,children:t.label}),t.items.map(s=>(0,g.jsx)(he,{href:s.href,className:n,children:s.label},s.href))]});default:return t}}function qa({homeHref:t,logoSrc:e="/light_transparent_logo.svg",navOnDark:r=!1,showLogo:n=!0,onMobileMenuOpenChange:s}){const[i,a]=(0,f.useState)(!1),o=r?Da:La,l=r?Ba:Ua,c=r?Fa:Ma;return(0,f.useEffect)(()=>{s?.(i)},[i,s]),(0,g.jsxs)("header",{className:"pt-12 sm:pt-16",children:[(0,g.jsxs)("div",{className:`flex items-center ${n?"justify-between":"justify-end lg:justify-center"}`,children:[n?(0,g.jsx)(he,{href:t,"aria-label":"Home",className:"block",children:(0,g.jsx)("img",{src:e,alt:"",className:"h-7 w-auto max-w-[min(100%,228px)] object-contain object-left drop-shadow-[0_1px_2px_rgba(15,23,42,0.07)]"})}):null,(0,g.jsx)("nav",{className:"hidden lg:flex items-center gap-1",children:Ht.map(h=>(0,g.jsx)(Ha,{item:h,navLinkClass:o},h.label))}),(0,g.jsx)("button",{type:"button",className:`flex size-12 items-center justify-center rounded-lg lg:hidden ${r?"text-white hover:bg-white/10":"hover:bg-black/5"}`,onClick:()=>a(!i),"aria-expanded":i,"aria-controls":"aidd-marketing-mobile-nav","aria-label":i?"Close main menu":"Open main menu",children:(0,g.jsxs)("span",{className:"relative block size-6","aria-hidden":!0,
16children:[(0,g.jsx)("span",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,g.jsx)("span",{className:`block h-0.5 w-6 rounded-full bg-current transition-transform duration-300 ease-out motion-reduce:transition-none ${i?"translate-y-0 rotate-45":"-translate-y-[5px] rotate-0"}`})}),(0,g.jsx)("span",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,g.jsx)("span",{className:`block h-0.5 w-6 rounded-full bg-current transition-transform duration-300 ease-out motion-reduce:transition-none ${i?"translate-y-0 -rotate-45":"translate-y-[5px] rotate-0"}`})})]})})]}),(0,g.jsx)("div",{className:`grid overflow-hidden transition-[grid-template-rows] duration-300 ease-in-out motion-reduce:transition-none lg:hidden ${i?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:(0,g.jsx)("div",{className:"min-h-0",inert:i?void 0:!0,children:(0,g.jsx)("div",{className:`mt-4 border-t pb-4 ${r?"border-white/10":"border-black/10"}`,children:(0,g.jsxs)("nav",{id:"aidd-marketing-mobile-nav",className:"mt-4 grid grid-cols-2 gap-x-2 gap-y-1",children:[(0,g.jsx)("div",{className:"flex flex-col gap-1",children:Ht.slice(0,2).map(h=>(0,g.jsx)(Nr,{item:h,navLinkClass:o,mobileMenuLabelClass:c,mobileNestedLinkClass:l},h.label))}),(0,g.jsx)("div",{className:"flex flex-col gap-1",children:Ht.slice(2).map(h=>(0,g.jsx)(Nr,{item:h,navLinkClass:o,mobileMenuLabelClass:c,mobileNestedLinkClass:l},h.label))})]})})})})]})}function Wa({logoHref:t}){const e=$a();return(0,g.jsx)("footer",{className:"bg-gray-950 py-16 px-6 lg:px-8",children:(0,g.jsxs)("div",{className:"mx-auto max-w-2xl lg:max-w-7xl",children:[(0,g.jsxs)("div",{className:"flex flex-col gap-12 lg:flex-row lg:items-start lg:justify-between",children:[(0,g.jsx)("div",{className:"shrink-0",children:(0,g.jsx)(he,{href:t,"aria-label":"Home",className:"block",children:(0,g.jsx)("img",{src:"/dark_transparent_no_spacing.svg",alt:"",className:"h-7 w-auto max-w-[min(100%,228px)] object-contain object-left"})})}),(0,g.jsx)("div",{className:"grid grid-cols-2 gap-8 sm:grid-cols-3",children:e.map(r=>(0,g.jsxs)("div",{children:[(0,g.jsx)("p",{className:"text-sm font-semibold text-white",children:r.heading}),(0,g.jsxs)("ul",{className:"mt-4 space-y-2",children:[r.links.map(n=>(0,g.jsx)("li",{children:(0,g.jsx)(he,{href:n.href,className:"text-sm text-gray-400 hover:text-white transition-colors",children:n.label})},n.label)),r.heading==="Company"&&(0,g.jsx)("li",{children:(0,g.jsx)(he,{href:"/contact",className:"text-sm text-gray-400 hover:text-white transition-colors",children:"Contact"})})]})]},r.heading))})]}),(0,g.jsx)("div",{className:"mt-12 border-t border-white/10 pt-8",children:(0,g.jsxs)("div",{className:"flex items-center justify-between",children:[(0,g.jsxs)("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," Cancentus GmbH. All Rights Reserved"]}),(0,g.jsx)("a",{href:"https://www.linkedin.com/company/cancentus-gmbh/",target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-white transition-colors","aria-label":"Cancentus on LinkedIn",children:(0,g.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:(0,g.jsx)("path",{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"})})})]})})]})})}var za=` 17attribute vec2 position; 18attribute vec2 uv; 19varying vec2 vUv; 20void main() { 21 vUv = uv; 22 gl_Position = vec4(position, 0.0, 1.0); 23} 24`,Va=` 25precision mediump float; 26 27uniform float iTime; 28uniform vec3 iResolution; 29uniform vec3 uColor; 30uniform float uAmplitude; 31uniform float uDistance; 32uniform vec2 uMouse; 33 34#define PI 3.1415926538 35 36const int u_line_count = 20; 37const float u_line_width = 7.0; 38const float u_line_blur = 8.0; 39 40float Perlin2D(vec2 P) { 41 vec2 Pi = floor(P); 42 vec4 Pf_Pfmin1 = P.xyxy - vec4(Pi, Pi + 1.0); 43 vec4 Pt = vec4(Pi.xy, Pi.xy + 1.0); 44 Pt = Pt - floor(Pt * (1.0 / 71.0)) * 71.0; 45 Pt += vec2(26.0, 161.0).xyxy; 46 Pt *= Pt; 47 Pt = Pt.xzxz * Pt.yyww; 48 vec4 hash_x = fract(Pt * (1.0 / 951.135664)); 49 vec4 hash_y = fract(Pt * (1.0 / 642.949883)); 50 vec4 grad_x = hash_x - 0.49999; 51 vec4 grad_y = hash_y - 0.49999; 52 vec4 grad_results = inversesqrt(grad_x * grad_x + grad_y * grad_y) 53 * (grad_x * Pf_Pfmin1.xzxz + grad_y * Pf_Pfmin1.yyww); 54 grad_results *= 1.4142135623730950; 55 vec2 blend = Pf_Pfmin1.xy * Pf_Pfmin1.xy * Pf_Pfmin1.xy 56 * (Pf_Pfmin1.xy * (Pf_Pfmin1.xy * 6.0 - 15.0) + 10.0); 57 vec4 blend2 = vec4(blend, vec2(1.0 - blend)); 58 return dot(grad_results, blend2.zxzx * blend2.wwyy); 59} 60
61float pixel(float count, vec2 resolution) { 62 return (1.0 / max(resolution.x, resolution.y)) * count; 63} 64 65float lineFn(vec2 st, float width, float perc, float offset, vec2 mouse, float time, float amplitude, float distance) { 66 float split_offset = (perc * 0.4); 67 float split_point = 0.1 + split_offset; 68 69 float amplitude_normal = smoothstep(split_point, 0.7, st.x); 70 float amplitude_strength = 0.5; 71 float finalAmplitude = amplitude_normal * amplitude_strength 72 * amplitude * (1.0 + (mouse.y - 0.5) * 0.2); 73 74 float time_scaled = time / 10.0 + (mouse.x - 0.5) * 1.0; 75 float blur = smoothstep(split_point, split_point + 0.05, st.x) * perc; 76 77 float xnoise = mix( 78 Perlin2D(vec2(time_scaled, st.x + perc) * 2.5), 79 Perlin2D(vec2(time_scaled, st.x + time_scaled) * 3.5) / 1.5, 80 st.x * 0.3 81 ); 82 83 float y = 0.5 + (perc - 0.5) * distance + xnoise / 2.0 * finalAmplitude; 84 85 float line_start = smoothstep( 86 y + (width / 2.0) + (u_line_blur * pixel(1.0, iResolution.xy)), 87 y, 88 st.y 89 ); 90 91 float line_end = smoothstep( 92 y, 93 y - (width / 2.0) - (u_line_blur * pixel(1.0, iResolution.xy) * blur), 94 st.y 95 ); 96 97 return clamp( 98 (line_start - line_end) * (1.0 - smoothstep(0.0, 1.0, pow(perc, 0.3))), 99 0.0, 100 1.0 101 ); 102} 103 104void mainImage(out vec4 fragColor, in vec2 fragCoord) { 105 vec2 uv = fragCoord / iResolution.xy; 106 107 float line_strength = 1.0; 108 for (int i = 0; i < u_line_count; i++) { 109 float p = float(i) / float(u_line_count); 110 line_strength *= (1.0 - lineFn( 111 uv, 112 u_line_width * pixel(1.0, iResolution.xy) * (1.0 - p), 113 p, 114 (PI * 1.0) * p, 115 uMouse, 116 iTime, 117 uAmplitude, 118 uDistance 119 )); 120 } 121 122 float colorVal = 1.0 - line_strength; 123 fragColor = vec4(uColor * colorVal, colorVal); 124} 125 126void main() { 127 mainImage(gl_FragColor, gl_FragCoord.xy); 128} 129`,Ka=({color:t=[1,1,1],amplitude:e=1,distance:r=0,enableMouseInteraction:n=!1})=>{const s=(0,f.useRef)(null),i=(0,f.useRef)(void 0),a=(0,f.useRef)(0),o=(0,f.useRef)(!0);return(0,f.useEffect)(()=>{if(!s.current)return;const l=s.current,c=new Ns({alpha:!0}),h=c.gl;h.clearColor(0,0,0,0),h.enable(h.BLEND),h.blendFunc(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA),l.appendChild(h.canvas);const u=new Ls(h),p=new Is(h,{vertex:za,fragment:Va,uniforms:{iTime:{value:0},iResolution:{value:new Er(h.canvas.width,h.canvas.height,h.canvas.width/h.canvas.height)},uColor:{value:new Er(...t)},uAmplitude:{value:e},uDistance:{value:r},uMouse:{value:new Float32Array([.5,.5])}}}),d=new $s(h,{geometry:u,program:p});function y(){const{clientWidth:x,clientHeight:S}=l;c.setSize(x,S),p.uniforms.iResolution.value.r=x,p.uniforms.iResolution.value.g=S,p.uniforms.iResolution.value.b=x/S}window.addEventListener("resize",y),y();const v=[.5,.5];let m=[.5,.5];function _(x){const S=l.getBoundingClientRect();m=[(x.clientX-S.left)/S.width,1-(x.clientY-S.top)/S.height]}function b(){m=[.5,.5]}n&&(l.addEventListener("mousemove",_),l.addEventListener("mouseleave",b));function w(x){if(i.current=requestAnimationFrame(w),!o.current)return;const S=1e3/30,A=x-a.current;A<S||(a.current=x-A%S,n?(v[0]+=.05*(m[0]-v[0]),v[1]+=.05*(m[1]-v[1]),p.uniforms.uMouse.value[0]=v[0],p.uniforms.uMouse.value[1]=v[1]):(p.uniforms.uMouse.value[0]=.5,p.uniforms.uMouse.value[1]=.5),p.uniforms.iTime.value=x*.001,c.render({scene:d}))}function T(){o.current=!document.hidden}return document.addEventListener("visibilitychange",T),i.current=requestAnimationFrame(w),()=>{i.current&&cancelAnimationFrame(i.current),window.removeEventListener("resize",y),document.removeEventListener("visibilitychange",T),n&&(l.removeEventListener("mousemove",_),l.removeEventListener("mouseleave",b)),l.contains(h.canvas)&&l.removeChild(h.canvas),h.getExtension("WEBGL_lose_context")?.loseContext()}},[t,e,r,n]),(0,g.jsx)("div",{ref:s,className:"threads-container"})},Ja=(0,f.memo)(Ka),_e={fontFamily:"Switzer, system-ui, sans-serif"};function Ga(){document.getElementById("vision")?.scrollIntoView({behavior:"smooth"})}function Ya(){const t=(0,f.useMemo)(()=>[.42,.58,.88],[]),[e,r]=(0,f.useState)(!1);return(0,f.useEffect)(()=>{const n=document.createElement("link");return n.rel="stylesheet",n.href="https://api.fontshare.com/v2/css?f[]=switzer@400,500,600,700&display=swap",document.head.appendChild(n),()=>{document.head.removeChild(n)}},[]),(0,g.jsxs)("div",{className:"min-h-screen w-full overflow-x-hidden text-gray-950 antialiased",style:{..._e,background:"white"},children:[(0,g.jsxs)("section",{id:"hero",className:"relative h-screen w-full","aria-label":"Home hero",children:[(0,g.jsx)("div",{className:"pointer-events-none absolute inset-0 z-0",style:{background:"linear-gradient(to bottom, #010208 0%, #0a1733 42%, #122c54 100%)"}}),(0,g.jsx)("div",{className:"absolute inset-0 z-0",children:(0,g.jsx)(Ja,{color:t,amplitude:1,distance:0,enableMouseInteraction:!1})}),(0,g.jsx)("div",{className:"relative z-50 px-6 lg:px-8",children:(0,g.jsx)("div",{className:"mx-auto max-w-2xl lg:max-w-7xl",children:(0,g.jsx)(qa,{homeHref:"/",navOnDark:!0,showLogo:!1,onMobileMenuOpenChange:r})})}),(0,g.jsx)("div",{className:`absolute inset-0 flex flex-col items-center justify-center px-8 z-40 pointer-events-none transition-transform duration-300 ease-in-out motion-reduce:transition-none ${e?"translate-y-40 lg:translate-y-0":"translate-y-0"}`,children:(0,g.jsxs)("div",{className:"pointer-events-auto flex flex-col items-center text-center",children:[(0,g.jsx)("img",{src:"/logo_transparent_dark.svg",alt:"Cancentus Logo",className:"h-10 object-contain drop-shadow-[0_1px_3px_rgba(0,0,0,0.25)]"}),(0,g.jsx)("p",{className:"mt-6 text-lg sm:text-2xl font-semibold text-white drop-shadow-sm",style:_e,children:"Developing Novel Cancer Therapies"})]})}),(0,g.jsx)("div",{className:`absolute bottom-8 left-0 right-0 z-40 flex flex-col items-center gap-1 transition-opacity duration-300 ease-in-out motion-reduce:transition-none ${e?"opacity-0 lg:opacity-100 pointer-events-none lg:pointer-events-auto":"opacity-100"}`,children:(0,g.jsxs)("a",{href:"#vision",onClick:n=>{n.preventDefault(),Ga()},className:"group flex flex-col items-center gap-2 text-white/90 hover:text-white transition-colors",children:[(0,g.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:"size-6 motion-safe:animate-bounce","aria-hidden":!0,
129children:(0,g.jsx)("path",{d:"M19 9l-7 7-7-7"})}),(0,g.jsx)("span",{className:"text-sm font-semibold tracking-wide",children:"Our Vision"}),(0,g.jsx)("span",{className:"sr-only",children:"Scroll to Our Vision"})]})})]}),(0,g.jsx)("section",{id:"vision",className:"w-full overflow-x-hidden py-32 px-6 lg:px-8",style:{background:"linear-gradient(to bottom, white 50%, #f3f4f6 100%)"},children:(0,g.jsxs)("div",{className:"mx-auto max-w-3xl",children:[(0,g.jsx)("p",{className:"font-mono text-xs/5 font-semibold tracking-widest text-gray-500 uppercase",children:"Company"}),(0,g.jsx)("h1",{className:"mt-2 max-w-3xl text-4xl font-medium tracking-tight text-pretty text-gray-950 sm:text-6xl",style:_e,children:"Our Vision"}),(0,g.jsxs)("div",{className:"mt-10 sm:mt-16 max-w-3xl space-y-12",children:[(0,g.jsxs)("p",{className:"text-base sm:text-lg text-pretty text-gray-600 leading-relaxed",children:["At ",(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"Cancentus"}),", we recognize that the primary obstacle to effective cancer therapy is toxicity to normal tissues. Our mission centers on optimizing the"," ",(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"therapeutic index"}),", the critical balance between treatment efficacy and patient safety."]}),(0,g.jsxs)("div",{className:"space-y-4",children:[(0,g.jsx)("h2",{className:"text-2xl/8 font-medium tracking-tight text-gray-950 sm:text-3xl",style:_e,children:"The Principle of Selectivity"}),(0,g.jsxs)("p",{className:"text-sm/6 sm:text-base/7 text-gray-600",children:["We believe that successful cancer therapeutics must be built on a foundation of"," ",(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"highly selective targets"}),"."]}),(0,g.jsxs)("ul",{className:"mt-4 max-w-[600px] space-y-2.5 text-sm/6 text-gray-600 list-disc pl-5 marker:text-gray-400",children:[(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"Selective Inhibition:"})," ","We target pathways whose inhibition triggers irreversible cancer cell death while sparing healthy cells."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"Tolerability:"})," ","This selectivity is essential for developing treatments that patients can tolerate."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"Clinical Confidence:"})," ","We provide the precision required so that physicians can confidently prescribe our therapies."]})]})]}),(0,g.jsxs)("div",{className:"space-y-4",children:[(0,g.jsx)("h2",{className:"text-2xl/8 font-medium tracking-tight text-gray-950 sm:text-3xl",style:_e,children:"Our Strategy: Exploiting DNA Replication Stress"}),(0,g.jsxs)("p",{className:"text-sm/6 sm:text-base/7 text-gray-600",children:["Central to our scientific strategy is the exploitation of"," ",(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"oncogene-induced DNA replication stress"}),", a fundamental vulnerability in cancer cells that provides a powerful handle for selective therapeutic intervention."]}),(0,g.jsxs)("ul",{className:"mt-4 max-w-[600px] space-y-2.5 text-sm/6 text-gray-600 list-disc pl-5 marker:text-gray-400",children:[(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"The Biological Distinction:"})," ","Cancer cells, driven by aberrant oncogene activation, experience heightened replication stress that distinguishes them from normal cells."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"Selective Elimination:"})," ","By targeting the pathways that cancer cells depend upon to manage this stress, we can develop therapies that selectively eliminate malignant cells while preserving normal tissue function."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"A Paradigm Shift:"})," ","This approach moves beyond traditional cytotoxic approaches toward precision therapeutics that exploit the inherent weaknesses created by oncogenic transformation."]})]})]}),(0,g.jsxs)("div",{className:"space-y-4",children:[(0,g.jsx)("h2",{className:"text-2xl/8 font-medium tracking-tight text-gray-950 sm:text-3xl",style:_e,children:"Our Philosophy: Purposeful Innovation"}),(0,g.jsxs)("p",{className:"text-sm/6 sm:text-base/7 text-gray-600",children:["Our approach focuses on"," ",(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"novel targets and methodologies"})," ",'rather than pursuing "me-too" programs that simply replicate existing therapies.']}),(0,g.jsxs)("ul",{className:"mt-4 max-w-[600px] space-y-2.5 text-sm/6 text-gray-600 list-disc pl-5 marker:text-gray-400",children:[(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"Embracing Necessary Complexity:"})," ","We accept the complexity required to develop truly effective treatments, whether that involves advanced delivery mechanisms or combination strategies."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("strong",{className:"font-medium text-gray-950",children:"Integrated design:"})," ","We are equally committed to avoiding hurdles that could hinder development or clinical implementation. This philosophy guides every decision we make, from target selection to clinical trial design."]})]})]})]})]})}),(0,g.jsx)(Wa,{logoHref:"/"})]})}var Xa=Symbol.for("@supabase/supabase-js.traceContextExtractor");function Qa(){return globalThis[Xa]}var $r=function(){return $r=Object.assign||function(e){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},$r.apply(this,arguments)};function Lt(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function Za(t,e,r,n){function s(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(h){try{c(n.next(h))}catch(u){a(u)}}function l(h){try{c(n.throw(h))}catch(u){a(u)}}function c(h){h.done?i(h.value):s(h.value).then(o,l)}c((n=n.apply(t,e||[])).next())})}function Nu(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,i;n<s;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}var eo=t=>t?(...e)=>t(...e):(...e)=>
129fetch(...e),br=class extends Error{constructor(t,e="FunctionsError",r){super(t),this.name=e,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}},to=class extends br{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}},Lr=class extends br{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}},Dr=class extends br{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}},rr;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(rr||(rr={}));var ro=class{constructor(t,{headers:e={},customFetch:r,region:n=rr.Any}={}){this.url=t,this.headers=e,this.region=n,this.fetch=eo(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return Za(this,arguments,void 0,function*(e,r={}){var n,s;let i,a,o;try{const{headers:l,method:c,body:h,signal:u,timeout:p}=r;let d={},{region:y}=r;y||(y=this.region);const v=new URL(`${this.url}/${e}`);y&&y!=="any"&&(d["x-region"]=y,v.searchParams.set("forceFunctionRegion",y));let m;const _=!!l&&Object.keys(l).some(A=>A.toLowerCase()==="content-type");h&&!_?typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",m=h):typeof h=="string"?(d["Content-Type"]="text/plain",m=h):typeof FormData<"u"&&h instanceof FormData?m=h:(d["Content-Type"]="application/json",m=JSON.stringify(h)):h&&typeof h!="string"&&!(typeof Blob<"u"&&h instanceof Blob)&&!(h instanceof ArrayBuffer)&&!(typeof FormData<"u"&&h instanceof FormData)?m=JSON.stringify(h):m=h;let b=u;p&&(a=new AbortController,i=setTimeout(()=>a.abort(),p),u?(b=a.signal,o=()=>a.abort(),u.addEventListener("abort",o)):b=a.signal);const w=yield this.fetch(v.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),l),body:m,signal:b}).catch(A=>{throw new to(A)}),T=w.headers.get("x-relay-error");if(T&&T==="true")throw new Lr(w);if(!w.ok)throw new Dr(w);let x=((n=w.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim().toLowerCase(),S;return x==="application/json"?S=yield w.json():x==="application/octet-stream"||x==="application/pdf"?S=yield w.blob():x==="text/event-stream"?S=w:x==="multipart/form-data"?S=yield w.formData():S=yield w.text(),{data:S,error:null,response:w}}catch(l){return{data:null,error:l,response:l instanceof Dr||l instanceof Lr?l.context:void 0}}finally{i&&clearTimeout(i),o&&((s=r.signal)===null||s===void 0||s.removeEventListener("abort",o))}})}},Qn=3,Ur=t=>Math.min(1e3*2**t,3e4),no=[520,503],Zn=["GET","HEAD","OPTIONS"],qt=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
129de=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function He(t){"@babel/helpers - typeof";return He=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},He(t)}function so(t,e){if(He(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(He(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function io(t){var e=so(t,"string");return He(e)=="symbol"?e:e+""}function ao(t,e,r){return(e=io(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Br(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function Ae(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Br(Object(r),!0).forEach(function(n){ao(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Br(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Mr(t,e){return new Promise(r=>{if(e?.aborted){r();return}const n=setTimeout(()=>{e?.removeEventListener("abort",s),r()},t);function s(){clearTimeout(n),r()}e?.addEventListener("abort",s)})}function oo(t,e,r,n){return!(!n||r>=Qn||!Zn.includes(t)||!no.includes(e))}var lo=class{constructor(t){var e,r,n,s,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,this.retryEnabled=(i=t.retry)!==null&&i!==void 0?i:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const a=this.headers.get("Accept");a==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!a||a==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const n=this.fetch;let i=(async()=>{let a=0;for(;;){const c={};r.headers.forEach((u,p)=>{c[p]=u}),a>0&&(c["X-Retry-Count"]=String(a));let h;try{h=await n(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(u,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal})}catch(u){if(u?.name==="AbortError"||u?.code==="ABORT_ERR"||!Zn.includes(r.method))throw u;if(r.retryEnabled&&a<Qn){const p=Ur(a);a++,await Mr(p,r.signal);continue}throw u}if(oo(r.method,h.status,a,r.retryEnabled)){var o,l;const u=(o=(l=h.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&o!==void 0?o:null,p=u!==null?Math.max(0,parseInt(u,10)||0)*1e3:Ur(a);await h.text(),a++,await Mr(p,r.signal);continue}return await r.processResponse(h)}})();return this.shouldThrowOnError||(i=i.catch(a=>{var o;let l="",c="",h="";const u=a?.cause;if(u){var p,d,y,v;const b=(p=u?.message)!==null&&p!==void 0?p:"",w=(d=u?.code)!==null&&d!==void 0?d:"";l=`${(y=a?.name)!==null&&y!==void 0?y:"FetchError"}: ${a?.message}`,l+=` 130 131Caused by: ${(v=u?.name)!==null&&v!==void 0?v:"Error"}: ${b}`,w&&(l+=` (${w})`),u?.stack&&(l+=` 132${u.stack}`)}else{var m;l=(m=a?.stack)!==null&&m!==void 0?m:""}const _=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",_>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${_} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(u?.name==="HeadersOverflowError"||u?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",_>this.urlLengthLimit&&(c+=`. Your request URL is ${_} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(o=a?.n
132ame)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:l,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}async processResponse(t){var e=this;let r=null,n=null,s=null,i=t.status,a=t.statusText;if(t.ok){var o,l;if(e.method!=="HEAD"){var c;const d=await t.text();if(d!=="")if(e.headers.get("Accept")==="text/csv")n=d;else if(e.headers.get("Accept")&&(!((c=e.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text")))n=d;else try{n=JSON.parse(d)}catch{if(r={message:d},n=null,e.shouldThrowOnError)throw new qt({message:d,details:"",hint:"",code:""})}}const u=(o=e.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),p=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");if(u&&p&&p.length>1&&(s=parseInt(p[1])),e.isMaybeSingle&&Array.isArray(n))if(n.length>1){if(r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,s=null,i=406,a="Not Acceptable",e.shouldThrowOnError){var h;throw new qt(Ae(Ae({},r),{},{hint:(h=r.hint)!==null&&h!==void 0?h:""}))}}else n.length===1?n=n[0]:n=null}else{const u=await t.text();try{r=JSON.parse(u),Array.isArray(r)&&t.status===404&&(n=[],r=null,i=200,a="OK")}catch{t.status===404&&u===""?(i=204,a="No Content"):r={message:u}}if(r&&e.shouldThrowOnError)throw new qt(r)}return{success:r===null,error:r,data:n,count:s,status:i,statusText:a}}returns(){return this}overrideTypes(){return this}},co=class extends lo{throwOnError(){return super.throwOnError()}select(t){let e=!1;const r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){const i=s?`${s}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){const s=typeof n>"u"?"offset":`${n}.offset`,i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Fr=new RegExp("[,()]"),xe=class extends co{throwOnError(){return super.throwOnError()}eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Fr.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Fr.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let s="";n==="plain"?s="pl":n==="phrase"?s="ph":n==="websearch"&&(s="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>
132r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},uo=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:s=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=s,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:n}=e??{},s=r?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),n&&l.append("Prefer",`count=${n}`),new xe({method:s,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;const s="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(o.length>0){const l=[...new Set(o)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","))}}return new xe({method:s,url:i,headers:a,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;const a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),s||l.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((h,u)=>h.concat(Object.keys(u)),[]);if(c.length>0){const h=[...new Set(c)].map(u=>`"${u}"`);o.searchParams.set("columns",h.join(","))}}return new xe({method:a,url:o,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const n="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new xe({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new xe({method:r,url:n,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},ho=class es{constructor(e,{headers:r={},schema:n,fetch:s,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=a;const l=s??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,h)=>{const u=new AbortController,p=setTimeout(()=>u.abort(),i),d=h?.signal;if(d){if(d.aborted)return clearTimeout(p),l(c,h);const y=()=>{clearTimeout(p),u.abort()};return d.addEventListener("abort",y,{once:!0}),l(c,Ae(Ae({},h),{},{signal:u.signal})).finally(()=>{clearTimeout(p),d.removeEventListener("abort",y)})}return l(c,Ae(Ae({},h),{},{signal:u.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new uo(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new es(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:n=!1,get:s=!1,count:i}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let c;const h=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(h)),u=n&&Object.values(r).some(h);u?(o="POST",c=r):n||s?(o=n?"HEAD":"GET",Object.entries(r).filter(([d,y])=>y!==void 0).map(([d,y])=>[d,Array.isArray(y)?`{${y.join(",")}}`:`${y}
132`]).forEach(([d,y])=>{l.searchParams.append(d,y)})):(o="POST",c=r);const p=new Headers(this.headers);return u?p.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&p.set("Prefer",`count=${i}`),new xe({method:o,url:l,headers:p,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},fo=class{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const e=globalThis;if(typeof globalThis<"u"&&typeof e.WebSocket<"u")return{type:"native",wsConstructor:e.WebSocket};const r=typeof global<"u"?global:void 0;if(r&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};if(typeof globalThis<"u"&&typeof e.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&e.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const n=globalThis.process;if(n){const s=n.versions;if(s&&s.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const t=this.detectEnvironment();if(t.wsConstructor)return t.wsConstructor;let e=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(e+=` 133 134Suggested solution: ${t.workaround}`),new Error(e)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}},po="2.112.4",mo=`realtime-js/${po}`,go="1.0.0",ts="2.0.0",vo=ts,yo=1e4,ce={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},rs={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},nr={connecting:"connecting",open:"open",closing:"closing",closed:"closed"},wo=class{constructor(t){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=t??[]}encode(t,e){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return e(this._binaryEncodeUserBroadcastPush(t));let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(t){var e;return this._isArrayBuffer((e=t.payload)===null||e===void 0?void 0:e.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var e,r;const n=(r=(e=t.payload)===null||e===void 0?void 0:e.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(t){var e,r;const n=(r=(e=t.payload)===null||e===void 0?void 0:e.payload)!==null&&r!==void 0?r:{},s=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,s)}_encodeUserBroadcastPush(t,e,r){var n,s;const i=new TextEncoder,a=i.encode(t.topic),o=i.encode((n=t.ref)!==null&&n!==void 0?n:""),l=i.encode((s=t.join_ref)!==null&&s!==void 0?s:""),c=i.encode(t.payload.event),h=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},u=i.encode(Object.keys(h).length===0?"":JSON.stringify(h));if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`metadata length ${u.length} exceeds maximum of 255`);const p=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+o.length+a.length+c.length+u.length,d=new ArrayBuffer(this.HEADER_LENGTH+p),y=new DataView(d),v=new Uint8Array(d);let m=0;y.setUint8(m++,this.KINDS.userBroadcastPush),y.setUint8(m++,l.length),y.setUint8(m++,o.length),y.setUint8(m++,a.length),y.setUint8(m++,c.length),y.setUint8(m++,u.length),y.setUint8(m++,e),v.set(l,m),m+=l.length,v.set(o,m),m+=o.length,v.set(a,m),m+=a.length,v.set(c,m),m+=c.length,v.set(u,m),m+=u.length;var _=new Uint8Array(d.byteLength+r.byteLength);return _.set(new Uint8Array(d),0),_.set(new Uint8Array(r),d.byteLength),_.buffer}decode(t,e){if(this._isArrayBuffer(t))return e(this._binaryDecode(t));if(typeof t=="string"){const[r,n,s,i,a]=JSON.parse(t);return e({join_ref:r,ref:n,topic:s,event:i,payload:a})}return e({})}
134_binaryDecode(t){const e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(t,e,n)}_decodeUserBroadcast(t,e,r){const n=e.getUint8(1),s=e.getUint8(2),i=e.getUint8(3),a=e.getUint8(4);let o=this.HEADER_LENGTH+4;const l=r.decode(t.slice(o,o+n));o=o+n;const c=r.decode(t.slice(o,o+s));o=o+s;const h=r.decode(t.slice(o,o+i));o=o+i;const u=t.slice(o,t.byteLength),p=a===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,d={type:this.BROADCAST_EVENT,event:c,payload:p};return i>0&&(d.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:d}}_isArrayBuffer(t){var e;return t instanceof ArrayBuffer||((e=t?.constructor)===null||e===void 0?void 0:e.name)==="ArrayBuffer"}_pick(t,e){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([r])=>e.includes(r)))}},C;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(C||(C={}));var Hr=(t,e,r={})=>{var n;const s=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((i,a)=>(i[a]=bo(a,t,e,s),i),{}):{}},bo=(t,e,r,n)=>{const s=e.find(o=>o.name===t),i=s?.type,a=r[t];return i&&!n.includes(i)?ns(i,a):sr(a)},ns=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return So(e,r)}switch(t){case C.bool:return _o(e);case C.float4:case C.float8:case C.int2:case C.int4:case C.int8:case C.numeric:case C.oid:return Eo(e);case C.json:case C.jsonb:return ko(e);case C.timestamp:return Ro(e);case C.abstime:case C.date:case C.daterange:case C.int4range:case C.int8range:case C.money:case C.reltime:case C.text:case C.time:case C.timestamptz:case C.timetz:case C.tsrange:case C.tstzrange:return sr(e);default:return sr(e)}},sr=t=>t,_o=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Eo=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},ko=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},So=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s;const i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>ns(e,a))}return t},Ro=t=>typeof t=="string"?t.replace(" ","T"):t,ss=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href},Ce=t=>typeof t=="function"?t:function(){return t},xo=typeof self<"u"?self:null,Te=typeof window<"u"?window:null,Z=xo||Te||globalThis,To="2.0.0",Ao=1e4,Co=1e3,Oo=100,ee={connecting:0,open:1,closing:2,closed:3},M={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},se={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},ir={longpoll:"longpoll",websocket:"websocket"},Po={complete:4},ar="base64url.bearer.phx.",st=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),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()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}
vendor: 7,012 bytes, line 134
134matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},is=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}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))}},jo=class{constructor(t,e,r){this.state=M.closed,this.topic=t,this.params=Ce(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new st(this,se.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new is(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=M.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",n=>{this.state=M.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=M.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=M.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new st(this,se.leave,Ce({}),this.timeout).send(),this.state=M.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(se.reply,(n,s)=>{this.trigger(this.replyEventName(s),n)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=M.closed,this.bindings=[]}onClose(t){this.on(se.close,t)}onError(t){return this.on(se.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new st(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=M.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(se.close,"leave")},r=new st(this,se.leave,Ce({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,n){return this.topic!==t?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=M.joining,this.joinPush.resend(t))}trigger(t,e,r,n){let s=this.onMessage(t,e,r,n);if(e&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,r));for(let a=0;a<i.length;a++)i[a].callback(s,r,n||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===M.closed}isErrored(){return this.state===M.errored}isJoined(){return this.state===M.joined}isJoining(){return this.state===M.joining}isLeaving(){return this.state===M.leaving}},kt=class{static request(t,e,r,n,s,i,a){if(Z.XDomainRequest){let o=new Z.XDomainRequest;return this.xdomainRequest(o,t,e,n,s,i,a)}else if(Z.XMLHttpRequest){let o=new Z.XMLHttpRequest;return this.xhrRequest(o,t,e,r,n,s,i,a)}else{if(Z.fetch&&Z.AbortController)return this.fetchRequest(t,e,r,n,s,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,s,i,a){let o={method:t,headers:r,body:n},l=null;return s&&(l=new AbortController,setTimeout(()=>l.abort(),s),o.signal=l.signal),Z.fetch(e,o).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>a&&a(c)).catch(c=>{c.name==="AbortError"&&i?i():a&&a(null)}),l}static xdomainRequest(t,e,r,n,s,i,a){return t.timeout=s,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,s,i,a,o){t.open(e,r,!0),t.timeout=i;for(let[l,c]of Object.entries(n))t.setRequestHeader(l,c);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{t.readyState===Po.complete&&o&&o(this.parseJSON(t.responseText))},a&&(t.ontimeout=a),t.send(s),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=e?`${e}[${n}]`:n,i=t[n];typeof i=="object"?r.push(this.serialize(i,s)):r.push(encodeURIComponent(s)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){return Object.keys(e).length===0?t:`${t}${t.match(/\?/)?"&":"?"}${this.serialize(e)}`}},Io=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let s=0;s<n;s++)e+=String.fromCharCode(r[s]);return btoa(e)},Ee=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(ar)&&(this.authToken=atob(e[1].slice(ar.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){}
vendor: 9,246 bytes, lines 134-135
134,this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=ee.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+ir.websocket),"$1/"+ir.longpoll)}endpointURL(){return kt.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=ee.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===ee.open||this.readyState===ee.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:s}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=n}else r=0;switch(r){case 200:s.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=ee.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Io(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t,e=0){this.awaitingBatchAck=!0;const r=e+Oo,n=t.slice(e,r);this.ajax("POST",{"Content-Type":"application/x-ndjson"},n.join(` 135`),()=>this.onerror("timeout"),s=>{!s||s.status!==200?(this.awaitingBatchAck=!1,this.onerror(s&&s.status),this.closeAndRetry(1011,"internal server error",!1)):r<t.length?this.batchSend(t,r):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(t,e,r){for(let s of this.reqs)s.abort();this.readyState=ee.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(t,e,r,n,s){let i,a=()=>{this.reqs.delete(i),n()};i=kt.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&s(o)}),this.reqs.add(i)}},No=class Ue{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,s=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Ue.syncState(this.state,s,i,a),this.pendingDiffs.forEach(l=>{this.state=Ue.syncDiff(this.state,l,i,a)}),this.pendingDiffs=[],o()}),this.channel.on(n.diff,s=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=Ue.syncDiff(this.state,s,i,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Ue.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,s){let i=this.toNullProtoObj(this.clone(e));r=this.toNullProtoObj(r);let a=Object.create(null),o=Object.create(null);return this.map(i,(l,c)=>{r[l]||(o[l]=c)}),this.map(r,(l,c)=>{let h=i[l];if(h){let u=c.metas.map(v=>v.phx_ref),p=h.metas.map(v=>v.phx_ref),d=c.metas.filter(v=>p.indexOf(v.phx_ref)<0),y=h.metas.filter(v=>u.indexOf(v.phx_ref)<0);d.length>0&&(a[l]=c,a[l].metas=d),y.length>0&&(o[l]=this.clone(h),o[l].metas=y)}else a[l]=c}),this.syncDiff(i,{joins:a,leaves:o},n,s)}static syncDiff(e,r,n,s){e=this.toNullProtoObj(e);let{joins:i,leaves:a}=this.clone(r);return n||(n=function(){}),s||(s=function(){}),this.map(i,(o,l)=>{let c=e[o];if(e[o]=this.clone(l),c){let h=e[o].metas.map(p=>p.phx_ref),u=c.metas.filter(p=>h.indexOf(p.phx_ref)<0);e[o].metas.unshift(...u)}n(o,c,l)}),this.map(a,(o,l)=>{let c=e[o];if(!c)return;let h=l.metas.map(u=>u.phx_ref);c.metas=c.metas.filter(u=>h.indexOf(u.phx_ref)<0),s(o,c,l),c.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(n,s){return s}),this.map(e,(n,s)=>r(n,s))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let r=Object.create(null);return Object.getOwnPropertyNames(e).forEach(n=>{r[n]=e[n]}),r}static clone(e){return JSON.parse(JSON.stringify(e))}},it={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,s,i,a]=JSON.parse(t);return e({join_ref:r,ref:n,topic:s,event:i,payload:a})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:s,payload:i}=t,a=new TextEncoder,o=a.encode(e),l=a.encode(r),c=a.encode(s),h=a.encode(n);this.assertFieldSize(o.byteLength,"join_ref"),this.assertFieldSize(l.byteLength,"ref"),this.assertFieldSize(c.byteLength,"topic"),this.assertFieldSize(h.byteLength,"event");let u=this.META_LENGTH+o.byteLength+l.byteLength+c.byteLength+h.byteLength,p=new ArrayBuffer(this.HEADER_LENGTH+u),d=new Uint8Array(p),y=new DataView(p),v=0;y.setUint8(v++,this.KINDS.push),y.setUint8(v++,o.byteLength),y.setUint8(v++,l.byteLength),y.setUint8(v++,c.byteLength),y.setUint8(v++,h.byteLength),d.set(o,v),v+=o.byteLength,d.set(l,v),v+=l.byteLength,d.set(c,v),v+=c.byteLength,d.set(h,v),v+=h.byteLength;var m=new Uint8Array(p.byteLength+i.byteLength);return m.set(d,0),m.set(new Uint8Array(i),p.byteLength),m.buffer},assertFieldSize(t,e){if(t>255)throw new Error(`unable to convert ${e} to binary: must be less than or equal to 255 bytes, but is ${t} bytes`)},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),s=e.getUint8(2),i=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+n));a=a+n;let l=r.decode(t.slice(a,a+s));a=a+s;let c=r.decode(t.slice(a,a+i));return a=a+i,{join_ref:o,ref:null,topic:l,event:c,payload:t.slice(a,t.byteLength)}},decodeReply(t,e,r){let n=e.getUint8(1),s=e.getUint8(2),i=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(o,o+n));o=o+n;let c=r.decode(t.slice(o,o+s));o=o+s;let h=r.decode(t.slice(o,o+i));o=o+i;let u=r.decode(t.slice(o,o+a));o=o+a;let p={status:u,response:t.slice(o,t.byteLength)};return{join_ref:l,ref:c,topic:h,event:se.reply,payload:p}},decodeBroadcast(t,e,r){let n=e.getUint8(1),s=e.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(t.slice(i,i+n));i=i+n;let o=r.decode(t.slice(i,i+s));return i=i+s,{join_ref:null,ref:null,topic:a,event:o,payload:t.slice(i,t.byteLength)}}},$o=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Ao,this.transport=e.transport||Z.WebSocket||Ee,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=Z&&Z.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=it.encode.bind(it),this.defaultDecoder=it.decode.bind(it),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Ee?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;Te&&Te.addEventListener&&(Te.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Te.addEventListener("pageshow",s=>{n===this.connectClock&&(n=null,this.connect())}),Te.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,i,a)=>{console.log(`${s}: ${i}`,a)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Ce(e.params||{}),this.endPoint=`${t}/${ir.websocket}`,this.vsn=e.vsn||To,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new is(()=>
135{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken&&Ce(e.authToken)}getLongPollTransport(){return Ee}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=kt.appendParams(kt.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Ce(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ee?this.connectWithF
vendor: 4,355 bytes, line 135
135allback(Ee,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(s=>{s.ref===e&&(this.off([n]),t(Date.now()-r))});return!0}transportName(t){return t===Ee?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${ar}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,n=!0,s,i,a=this.transportName(t),o=l=>{this.log("transport",`falling back to ${a}...`,l),this.off([s,i]),n=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),i=this.onError(l=>{this.log("transport","error",l),n&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!n){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Co,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===ee.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}
vendor: 4,203 bytes, line 135
135triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(se.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case ee.connecting:return"connecting";case ee.open:return"open";case ee.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new jo(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:s,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${s})`,n)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:s,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(s.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${s.status||""} ${r} ${n} ${i&&"("+i+")"||""}`.trim(),s);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(r,n,s,a)&&l.trigger(n,s,i,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e)}catch(s){this.log("error",`error in ${t} callback`,s)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}},Lo=class gt{constructor(e,r){const n=Uo(r);this.presence=new No(e.getChannel(),n),this.presence.onJoin((s,i,a)=>{const o=gt.onJoinPayload(s,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((s,i,a)=>{const o=gt.onLeavePayload(s,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return gt.transformState(this.presence.state)}static transformState(e){return e=Do(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{const s=e[n];return r[n]=vt(s),r},{})}static onJoinPayload(e,r,n){return{event:"join",key:e,currentPresences:qr(r),newPresences:vt(n)}}static onLeavePayload(e,r,n){return{event:"leave",key:e,currentPresences:qr(r),leftPresences:vt(n)}}};function vt(t){return t.metas.map(e=>{const r=Object.getOwnPropertyDescriptors(e),n=Object.defineProperties({},r);return n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n})}function Do(t){return JSON.parse(JSON.stringify(t))}function Uo(t){return t?.events&&{events:t.events}}function qr(t){return t?.metas?vt(t):[]}var Wr;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Wr||(Wr={}));var Bo=class{get state(){return this.presenceAdapter.state}constructor(t,e){this.channel=t,this.presenceAdapter=new Lo(this.channel.channelAdapter,e)}};function Mo(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;
135if(typeof e.code=="number"){const r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}var Fo=class{constructor(t,e,r){const n=Ho(r);this.channel=t.getSocket().channel(e,n),this.socket=t}get state(){return this.channel.state}set state(t){this.channel.state=t}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(t,e){return this.channel.on(t,e)}off(t,e){this.channel.off(t,e)}subscribe(t){return this.channel.join(t)}unsubscribe(t){return this.channel.leave(t)}teardown(){this.channel.teardown()}onClose(t){this.channel.onClose(t)}onError(t){return this.channel.onError(t)}push(t,e,r){let n;try{n=this.channel.push(t,e,r)}catch{throw new Error(`tried to push '${t}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){const s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(t){const e=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},e),t)}canPush(){return this.socket.isConnected()&&this.state===ce.joined}isJoined(){return this.state===ce.joined}isJoining(){return this.state===ce.joining}isClosed(){return this.state===ce.closed}isLeaving(){return this.state===ce.leaving}updateFilterBindings(t){this.channel.filterBindings=t}updatePayloadTransform(t){this.channel.onMessage=t}getChannel(){return this.channel}};function Ho(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var qo=/[,()"\\]/,Wo=t=>qo.test(t)||t!==t.trim(),zo=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,zr=t=>{const e=t===null?"null":String(t);return Wo(e)?zo(e):e},Vo=t=>t===null?"null":String(t),Ko=(t,e)=>{if(t==="in"){const r=Array.isArray(e)?e:[e];if(r.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(r)).map(n=>zr(n)).join(",")})`}return t==="is"?`is.${Vo(e)}`:`${t}.${zr(e)}`},Jo=class{constructor(){this.filters=[]}add(t,e,r,n=!1){const s=n?"not.":"";return this.filters.push(`${t}=${s}${Ko(e,r)}`),this}eq(t,e){return this.add(t,"eq",e)}neq(t,e){return this.add(t,"neq",e)}gt(t,e){return this.add(t,"gt",e)}gte(t,e){return this.add(t,"gte",e)}lt(t,e){return this.add(t,"lt",e)}lte(t,e){return this.add(t,"lte",e)}in(t,e){return this.add(t,"in",e)}like(t,e){return this.add(t,"like",e)}ilike(t,e){return this.add(t,"ilike",e)}match(t,e){return this.add(t,"match",e)}imatch(t,e){return this.add(t,"imatch",e)}is(t,e){return this.add(t,"is",e)}isDistinct(t,e){return this.add(t,"isdistinct",e)}not(t,e,r){return this.add(t,e,r,!0)}build(){return this.filters.join(",")}toString(){return this.build()}},Vr;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Vr||(Vr={}));var me;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(me||(me={}));var ie;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(ie||(ie={}));var Go=class le{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},n){var s,i;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Fo(this.socket.socketAdapter,e,this.params),this.presence=new Bo(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=ss(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:l}}=this.params,c=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(d=>d.filter))!==null&&s!==void 0?s:[],h=!!this.bindings[me.PRESENCE]&&this.bindings[me.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,u={},p={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:h}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(d=>{e?.(ie.CHANNEL_ERROR,Mo(d))}),this._onClose(()=>e?.(ie.CLOSED)),this.updateJoinPayload(Object.assign({config:p},u)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:d})=>{if(this.socket._isManualToken()||this.socket.setAuth(),d===void 0){e?.(ie.SUBSCRIBED);return}this._updatePostgresBindings(d,e)}).receive("error",d=>{this.state=ce.errored;const y=Object.values(d).join(", ")||"error";e?.(ie.CHANNEL_ERROR,new Error(y,{cause:d}))}).receive("timeout",()=>{e?.(ie.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var n;const s=this.bindings.postgres_changes,i=(n=s?.length)!==null&&n!==void 0?n:0,a=[];for(let o=0;o<i;o++){const l=s[o],{filter:{event:c,schema:h,table:u,filter:p}}=l,d=e&&e[o];if(d&&d.event===c&&le.isFilterValueEqual(d.schema,h)&&le.isFilterValueEqual(d.table,u)&&le.isFilterValueEqual(d.filter,p))a.push(Object.assign(Object.assign({},l),{id:d.id}));else{this.unsubscribe(),this.state=ce.errored,r?.(ie.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=ce.errored&&r&&r(ie.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){const s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===me.PRESENCE||e===me.POSTGRES_CHANGES;if(s&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,n)}async httpSend(e,r,n={}){var s;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i=r instanceof ArrayBuffer||ArrayBuffer.isView(r),a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o=new URL(this.broadcastEndpointURL);o.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&o.searchParams.set("private","true");const l={method:"POST",headers:a,body:i?r:JSON.stringify(r)},c=await this._fetchWithTimeout(o.toString(),l,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(c.status===202)return{success:!0};if(c.status===404)return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realt
135ime-js/migrations/httpsend-server-version.md"));let h=c.statusText;try{const u=await c.json();h=u.error||u.message||h}catch{}return Promise.reject(new Error(h))}async send(e,r={}){var n,s;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){const i="Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.";this.socket.hasLogger()?this.socket.log("channel",i):console.warn(i);const{event:a,payload:o}=e,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const h=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=h.body)===null||s===void 0?void 0:s.cancel()),h.ok?"ok":"error"}catch(h){return h instanceof Error&&h.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,l;const c=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,n){const s=new AbortController,i=setTimeout(()=>s.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:s.signal}));return clearTimeout(i),a}_on(e,r,n){var s;const i=e.toLocaleLowerCase(),a=r?.filter;if((a instanceof Jo||typeof a=="object"&&a!==null&&typeof a.build=="function")&&(r=Object.assign(Object.assign({},r),{filter:a.build()})),i===me.POSTGRES_CHANGES&&!((s=this.bindings[i])===null||s===void 0)&&s.find(c=>le.isSamePostgresFilter(c.filter,r)))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,r),this;const o=this.channelAdapter.on(e,n),l={type:i,filter:r,callback:n,ref:o};return this.bindings[i]?this.bindings[i].push(l):this.bindings[i]=[l],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var s,i,a,o,l,c,h;const u=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(u,n))return!1;const p=(s=this.bindings[u])===null||s===void 0?void 0:s.find(d=>d.ref===e.ref);if(!p)return!0;if(["broadcast","presence","postgres_changes"].includes(u))if("id"in p){const d=p.id,y=(i=p.filter)===null||i===void 0?void 0:i.event;return d&&((a=r.ids)===null||a===void 0?void 0:a.includes(d))&&(y==="*"||y?.toLocaleLowerCase()===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const d=(c=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return d==="*"||d===((h=r?.event)===null||h===void 0?void 0:h.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===u})}_notThisChannelEvent(e,r){const{close:n,error:s,leave:i,join:a}=rs;return r&&[n,s,i,a].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){const s=r.data,{schema:i,table:a,commit_timestamp:o,type:l,errors:c}=s;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(s))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const n of e.bindings[r])this._on(n.type,n.filter,n.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}static isSamePostgresFilter(e,r){var n,s,i,a;const o=(s=(n=e?.select)===null||n===void 0?void 0:n.join())!==null&&s!==void 0?s:void 0,l=(a=(i=r?.select)===null||i===void 0?void 0:i.join())!==null&&a!==void 0?a:void 0;return e?.event===r?.event&&le.isFilterValueEqual(e?.schema,r?.schema)&&le.
135isFilterValueEqual(e?.table,r?.table)&&le.isFilterValueEqual(e?.filter,r?.filter)&&o===l}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Hr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Hr(e.columns,e.old_record)),r}},Yo=class{constructor(t,e){this.socket=new $o(t,e)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(t){this.socket.heartbeatCallback=t}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(t,e,r,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{t(),s("ok")},e,r)})}push(t){this.socket.push(t)}log(t,e,r){this.socket.log(t,e,r)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(t){this.socket.onOpen(t)}onClose(t){this.socket.onClose(t)}onError(t){this.socket.onError(t)}onMessage(t){this.socket.onMessage(t)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==nr.connecting}isDisconnecting(){return this.socket.connectionState()==nr.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}},Kr={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Xo=[1e3,2e3,5e3,1e4],Qo=1e4;function Zo(){const t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function el(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return Zo()}var tl=` 136 addEventListener("message", (e) => { 137 if (e.data.event === "start") { 138 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 139 } 140 });`,rl=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(t,e){var r;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new wo,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((r=e?.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=e.params.apikey;const n=this._initializeOptions(e);this.socketAdapter=new Yo(t,n),this.httpEndpoint=ss(t),this.fetch=this._resolveFetch(e?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){const e=t.message;throw new Error(`WebSocket not available: ${e}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(t,e){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},t,e)}getChannels(){return this.channels}async removeChannel(t){const e=await t.unsubscribe();return e==="ok"&&t.teardown(),e}async removeAllChannels(){const t=this.channels.map(async r=>{const n=await r.unsubscribe();return r.teardown(),n}),e=await Promise.all(t);return await this.disconnect(),e}log(t,e,r){this.socketAdapter.log(t,e,r)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||nr.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(t,e={config:{}}){const r=`realtime:${t}`,n=this.getChannels().find(s=>s.topic===r);if(n)return n;{const s=new Go(`realtime:${t}`,e,this);return this._cancelPendingDisconnect(),this.channels.push(s),s}}push(t){this.socketAdapter.push(t)}async setAuth(t=null){const e=++this._authGeneration,r=this._performAuth(t,e);e===this._authGeneration&&(this._authPromise=r);try{await r}finally{this._authPromise===r&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(t){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(t)}_makeRef(){return this.socketAdapter.makeRef()}_remove(t){this.channels=this.channels.filter(e=>e.topic!==t.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}
140this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(t,e){let r,n=!1;if(t)r=t,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),r=this.accessTokenValue}else r=this.accessTokenValue;e===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:n&&(this._manuallySetToken=!0),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(s=>{const i={access_token:r,version:mo};s.updateJoinPayload(i),s.joinedOnce&&s.channelAdapter.isJoined()&&s.channelAdapter.push(rs.access_token,{access_token:r})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(e=>{this.log("error",`Error setting auth in ${t}`,e)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(t=>{this.log("error","error waiting for auth on connect",t)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(t=>{t.ref&&t.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(t){return(e,r)=>{e!=="disconnected"&&(e=="sent"&&this._setAuthSafely(),t&&t(e,r))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{e.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(t){let e;if(t)e=t;else{const r=new Blob([tl],{type:"application/javascript"});e=URL.createObjectURL(r)}return e}_initializeOptions(t){var e,r,n,s,i,a,o,l,c,h,u,p;this.worker=(e=t?.worker)!==null&&e!==void 0?e:!1,this.accessToken=(r=t?.accessToken)!==null&&r!==void 0?r:null;const d={};d.timeout=(n=t?.timeout)!==null&&n!==void 0?n:yo,d.heartbeatIntervalMs=(s=t?.heartbeatIntervalMs)!==null&&s!==void 0?s:Kr.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(i=t?.disconnectOnEmptyChannelsAfterMs)!==null&&i!==void 0?i:2*((a=t?.heartbeatIntervalMs)!==null&&a!==void 0?a:Kr.HEARTBEAT_INTERVAL),d.transport=(o=t?.transport)!==null&&o!==void 0?o:fo.getWebSocketConstructor(),d.params=t?.params,d.logger=t?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(t?.heartbeatCallback),d.sessionStorage=(l=t?.sessionStorage)!==null&&l!==void 0?l:el(),d.reconnectAfterMs=(c=t?.reconnectAfterMs)!==null&&c!==void 0?c:(_=>Xo[_-1]||Qo);let y,v;const m=(h=t?.vsn)!==null&&h!==void 0?h:vo;switch(m){case go:y=(_,b)=>b(JSON.stringify(_)),v=(_,b)=>b(JSON.parse(_));break;case ts:y=this.serializer.encode.bind(this.serializer),v=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=m,d.encode=(u=t?.encode)!==null&&u!==void 0?u:y,d.decode=(p=t?.decode)!==null&&p!==void 0?p:v,d.beforeReconnect=this._reconnectAuth.bind(this),(t?.logLevel||t?.log_level)&&(this.logLevel=t.logLevel||t.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}
140,qe=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function nl(t,e,r){const n=new URL(e,t);if(r)for(const[s,i]of Object.entries(r))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function sl(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function il(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:a}){const o=nl(t.baseUrl,n,s),l=await sl(t.auth),c=await e(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):void 0}),h=await c.text(),u=(c.headers.get("content-type")||"").includes("application/json"),p=u&&h?JSON.parse(h):h;if(!c.ok){const d=u?p:void 0,y=d?.error;throw new qe(y?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:y?.type,icebergCode:y?.code,details:d})}return{status:c.status,headers:c.headers,data:p}}}}function at(t){return t.join("�")}var al=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:at(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${at(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${at(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${at(t.namespace)}`}),!0}catch(e){if(e instanceof qe&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof qe&&r.status===409)return;throw r}}};function ke(t){return t.join("�")}var ol=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ke(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ke(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ke(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ke(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ke(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ke(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof qe&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof qe&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},ll=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=il({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new al(this.client,e),this.tableOps=new ol(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}
140async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function We(t){"@babel/helpers - typeof";return We=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},We(t)}function cl(t,e){if(We(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(We(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ul(t){var e=cl(t,"string");return We(e)=="symbol"?e:e+""}function hl(t,e,r){return(e=ul(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Jr(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function R(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Jr(Object(r),!0).forEach(function(n){hl(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Jr(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Dt=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function Ut(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var or=class extends Dt{constructor(t,e,r,n="storage",s){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r,this.co
140de=s}toJSON(){return R(R({},super.toJSON()),{},{code:this.code})}},as=class extends Dt{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function St(t,e,r){const n=R({},t),s=e.toLowerCase();for(const i of Object.keys(n))i.toLowerCase()===s&&delete n[i];return n[s]=r,n}function dl(t){const e={};for(const[r,n]of Object.entries(t))e[r.toLowerCase()]=n;return e}var fl=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),pl=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},lr=t=>{if(Array.isArray(t))return t.map(r=>lr(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,n])=>{const s=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=lr(n)}),e},ml=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),os=t=>t.split("/").map(encodeURIComponent).join("/"),Gr=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},gl=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){const s=t;let i=parseInt(String(s.status),10);Number.isFinite(i)||(i=500),s.json().then(a=>{const o=a?.statusCode||a?.code||i+"";e(new or(Gr(a),i,o,n,a?.code))}).catch(()=>{const a=i+"";e(new or(s.statusText||`HTTP ${i} error`,i,a,n))})}else e(new as(Gr(t),t,n))},vl=(t,e,r,n)=>{const s={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!n)return R(R({},s),r);if(pl(n)){var i;const a=e?.headers||{};let o;for(const[l,c]of Object.entries(a))l.toLowerCase()==="content-type"&&(o=c);s.headers=St(a,"Content-Type",(i=o)!==null&&i!==void 0?i:"application/json"),s.body=JSON.stringify(n)}else s.body=n;return e?.duplex&&(s.duplex=e.duplex),R(R({},s),r)};async function De(t,e,r,n,s,i,a){return new Promise((o,l)=>{t(r,vl(e,n,s,i)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(a==="vectors"){const h=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!h||!h.includes("application/json"))return{}}return c.json()}).then(c=>o(c)).catch(c=>gl(c,l,n,a))})}function ls(t="storage"){return{get:async(e,r,n,s)=>De(e,"GET",r,n,s,void 0,t),post:async(e,r,n,s,i)=>De(e,"POST",r,s,i,n,t),put:async(e,r,n,s,i)=>De(e,"PUT",r,s,i,n,t),head:async(e,r,n,s)=>De(e,"HEAD",r,R(R({},n),{},{noResolveJson:!0}),s,void 0,t),remove:async(e,r,n,s,i)=>De(e,"DELETE",r,s,i,n,t)}}var{get:ze,post:Y,put:cr,head:yl,remove:Ve}=ls("storage"),q=ls("vectors"),$e=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=dl(e),this.fetch=fl(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=St(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Ut(r))return{data:null,error:r};throw r}}},cs;cs=Symbol.toStringTag;var wl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[cs]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ut(e))return{data:null,error:e};throw e}}},us;us=Symbol.toStringTag;var bl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[us]="BlobDownloadBuilder",this.promise=null}asStream(){return new wl(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ut(e))return{data:null,error:e};throw e}}},Wt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Yr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},_l=class extends $e{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var s=this;return s.handleOperation(async()=>{let i;const a=R(R({},Yr),n);let o=R(R({},s.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;if(typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),n?.headers)for(const[p,d]of Object.entries(n.headers))o=St(o,p,d);const c=s._removeEmptyFolders(e),h=s._getFinalPath(c),u=await(t=="PUT"?cr:Y)(s.fetch,`${s.url}/object/${h}`,i,R({headers:o},a?.duplex?{duplex:a.duplex}:{}));return{path:c,id:u.Id,fullPath:u.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}
140async uploadToSignedUrl(t,e,r,n){var s=this;const i=s._removeEmptyFolders(t),a=s._getFinalPath(i),o=new URL(s.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),s.handleOperation(async()=>{let l;const c=R(R({},Yr),n);let h=R(R({},s.headers),{"x-upsert":String(c.upsert)});const u=c.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),u&&l.append("metadata",s.encodeMetadata(u)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",c.cacheControl),u&&!l.has("metadata")&&l.append("metadata",s.encodeMetadata(u))):(l=r,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType,u&&(h["x-metadata"]=s.toBase64(s.encodeMetadata(u))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!c.duplex&&(c.duplex="half")),n?.headers)for(const[p,d]of Object.entries(n.headers))h=St(h,p,d);return{path:i,fullPath:(await cr(s.fetch,o.toString(),l,R({headers:h},c?.duplex?{duplex:c.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t);const s=R({},r.headers);e?.upsert&&(s["x-upsert"]="true");const i=await Y(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new Dt("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await Y(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await Y(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(t);const i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await Y(n.fetch,`${n.url}/object/sign/${s}`,R({expiresIn:e},i?{transform:r.transform}:{}),{headers:n.headers});const o=new URLSearchParams;r?.download&&o.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&o.set("cacheNonce",String(r.cacheNonce));const l=o.toString();return{signedUrl:encodeURI(`${n.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{const s=await Y(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));const a=i.toString();return s.map(o=>R(R({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${a?`&${a}`:""}`):null}))})}download(t,e,r){const n=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",s=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce));const i=s.toString(),a=this._getFinalPath(t),o=()=>ze(this.fetch,`${this.url}/${n}/${a}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new bl(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>lr(await ze(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await yl(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(Ut(s)){var n;const i=s instanceof or?s.status:s instanceof as?(n=s.originalError)===null||n===void 0?void 0:n.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:s}}throw s}}getPublicUrl(t,e){const r=this._getFinalPath(t),n=new URLSearchParams;e?.download&&n.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));const s=n.toString(),i=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(s?`?${s}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Ve(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async purgeCache(t,e,r){var n=this;return n.handleOperation(async()=>{const s=os(n._getFinalPath(t)),i=new URLSearchParams;e?.transformations&&i.set("transformations","true");const a=i.toString();return await Ve(n.fetch,`${n.url}/cdn/${s}${a?`?${a}`:""}`,{},{headers:n.headers},r)})}async list(t,e,r){var n=this;return n.handleOperation(async()=>{const s=e?.sortBy?R(R({},Wt.sortBy),e.sortBy):Wt.sortBy,i=R(R(R({},Wt),e),{},{sortBy:s,prefix:t||""});return await Y(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const n=R({},t);return await Y(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("qual
140ity",e.quality.toString()),t}},Ze={"X-Client-Info":"storage-js/2.112.4"},El=class extends $e{constructor(t,e={},r,n){const s=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));const i=s.href.replace(/\/$/,""),a=R(R({},Ze),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await ze(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ze(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Y(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await cr(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Y(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ve(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}async purgeBucketCache(t,e,r){var n=this;return n.handleOperation(async()=>{const s=new URLSearchParams;e?.transformations&&s.set("transformations","true");const i=s.toString();return await Ve(n.fetch,`${n.url}/cdn/${os(t)}${i?`?${i}`:""}`,{},{headers:n.headers},r)})}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},kl=class extends $e{constructor(t,e={},r){const n=t.replace(/\/$/,""),s=R(R({},Ze),e);super(n,s,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Y(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);const n=r.toString(),s=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await ze(e.fetch,s,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ve(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!ml(t))throw new Dt("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new ll({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(s,i){const a=s[i];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(s,o),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},Sl=class extends $e{constructor(t,e={},r){const n=t.replace(/\/$/,""),s=R(R({},Ze),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await q.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await q.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Rl=class extends $e{constructor(t,e={},r){const n=t.replace(/\/$/,""),s=R(R({},Ze),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");
140if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},xl=class extends $e{constructor(t,e={},r){const n=t.replace(/\/$/,""),s=R(R({},Ze),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await q.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Tl=class extends xl{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Al(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Al=class extends Sl{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Cl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Cl=class extends Rl{constructor(t,e,r,n,s){super(t,e,s),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Ol=class extends El{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new _l(this.url,this.headers,t,this.fetch)}get vectors(){return new Tl(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new kl(this.url+"/iceberg",this.headers,this.fetch)}},hs="2.112.4",ge=3e4;var zt=3*ge,Pl=2*ge,jl="http://localhost:9999",Il="supabase.auth.token",Nl={"X-Client-Info":`gotrue-js/${hs}`},ds="X-Supabase-Api-Version",fs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},$l=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Be="sb_flow_id";var Ke=class extends Error{constructor(t,e,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=e,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function E(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Ll=class extends Ke{constructor(t,e,r){super(t,e,r),this.name="AuthApiError",this.status=e,this.co
140de=r}};function Xr(t){return E(t)&&t.name==="AuthApiError"}var X=class extends Ke{constructor(t,e){super(t),this.name="AuthUnknownError",this.originalError=e}},re=class extends Ke{constructor(t,e,r,n){super(t,r,n),this.name=e,this.status=r}},$=class extends re{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function ot(t){return E(t)&&t.name==="AuthSessionMissingError"}var Se=class extends re{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},lt=class extends re{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}},ct=class extends re{constructor(t,e=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=e}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function Dl(t){return E(t)&&t.name==="AuthImplicitGrantRedirectError"}var Qr=class extends re{constructor(t,e=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=e}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Ul=class extends re{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}},yt=class extends re{constructor(t,e){super(t,"AuthRetryableFetchError",e,void 0)}};function ut(t){return E(t)&&t.name==="AuthRetryableFetchError"}var Zr=class extends re{constructor(t="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(t,"AuthRefreshDiscardedError",409,void 0)}};function Bl(t){return E(t)&&t.name==="AuthRefreshDiscardedError"}var en=class extends re{constructor(t,e,r){super(t,"AuthWeakPasswordError",e,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}},Rt=class extends re{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}},xt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tn=` 141\r=`.split(""),Ml=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<tn.length;e+=1)t[tn[e].charCodeAt(0)]=-2;for(let e=0;e<xt.length;e+=1)t[xt[e].charCodeAt(0)]=e;return t})();function rn(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(xt[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(xt[n]),e.queuedBits-=6}}function ps(t,e,r){const n=Ml[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function nn(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=a=>{ql(a,n,r)};for(let a=0;a<t.length;a+=1)ps(t.charCodeAt(a),s,i);return e.join("")}function Fl(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Hl(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){const s=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|s)+65536,r+=1}Fl(n,e)}}function ql(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Oe(t){const e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<t.length;
141s+=1)ps(t.charCodeAt(s),r,n);return new Uint8Array(e)}function Wl(t){const e=[];return Hl(t,r=>e.push(r)),new Uint8Array(e)}function ve(t){const e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};return t.forEach(s=>rn(s,r,n)),rn(null,r,n),e.join("")}function zl(t){return Math.round(Date.now()/1e3)+t}function Vl(){return Symbol("auth-callback")}var L=()=>typeof window<"u"&&typeof document<"u",fe={tested:!1,writable:!1},ms=()=>{if(!L())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(fe.tested)return fe.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),fe.tested=!0,fe.writable=!0}catch{fe.tested=!0,fe.writable=!1}return fe.writable};function sn(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((n,s)=>{e[s]=n}),e}var gs=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Kl=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",ae=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},D=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},F=async(t,e)=>{await t.removeItem(e)},vs=class ys{constructor(){this.promise=new ys.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};vs.promiseConstructor=Promise;function ht(t){const e=t.split(".");if(e.length!==3)throw new Rt("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!$l.test(e[r]))throw new Rt("JWT not in base64url format");return{header:JSON.parse(nn(e[0])),payload:JSON.parse(nn(e[1])),signature:Oe(e[2]),raw:{header:e[0],payload:e[1]}}}async function Jl(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Gl(t,e){return new Promise((r,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{const i=await t(s);if(!e(s,null,i)){r(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function ws(t){return("0"+t.toString(16)).substr(-2)}function Yl(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";let s="";for(let i=0;i<56;i++)s+=r.charAt(Math.floor(Math.random()*66));return s}return crypto.getRandomValues(e),Array.from(e,ws).join("")}async function Xl(t){const e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(r);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function Ql(t){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."),t;const e=await Xl(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Zl=/^[a-zA-Z0-9_-]{8,64}$/;function wt(t){return typeof t=="string"&&Zl.test(t)?t:null}function ec(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,ws).join("")}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}var Pe=(t,e)=>`${t}-flow-${e}-code-verifier`,Je=t=>`${t}-flows-code-verifier`;async function _r(t,e){const r=await D(t,Je(e));return Array.isArray(r)?r.filter(n=>wt(n)!==null):[]}async function tc(t,e,r,n,s){await ae(t,Pe(e,r),n);const i=(await _r(t,e)).filter(a=>a!==r);for(i.push(r);i.length>5;){const a=i.shift();await F(t,Pe(e,a)),s?.(a)}await ae(t,Je(e),i),await ae(t,`${e}-code-verifier`,n)}async function rc(t,e,r){if(r){const s=await D(t,Pe(e,r));return{verifier:typeof s=="string"?s:null,flowId:r}}const n=await D(t,`${e}-code-verifier`);return{verifier:typeof n=="string"?n:null,flowId:null}}async function J(t,e,r){const n=`${e}-code-verifier`;if(!r){await F(t,n);return}const s=Pe(e,r),i=await D(t,s);await F(t,s);const a=await _r(t,e),o=a.filter(l=>l!==r);o.length!==a.length&&(o.length>0?await ae(t,Je(e),o):await F(t,Je(e))),i!=null&&i===await D(t,n)&&await F(t,n)}async function nc(t,e){const r=await _r(t,e);for(const n of r)await F(t,Pe(e,n));await F(t,Je(e)),await F(t,`${e}-code-verifier`)}function sc(t,e){const r=t.indexOf("#");let n=r===-1?t:t.slice(0,r);const s=r===-1?"":t.slice(r),i=n.indexOf("?");if(i!==-1){const o=n.slice(0,i),l=n.slice(i+1).split("&").filter(c=>c!==""&&c!=="sb_flow_id"&&!c.startsWith("sb_flow_id="));n=l.length>0?`${o}?${l.join("&")}`:o}const a=n.includes("?")?"&":"?";return`${n}${a}${Be}=${encodeURIComponent(e)}${s}`}async function ic(t,e,r=!1,n){const s=Yl();let i=s;r&&(i+="/recovery");const a=ec();await tc(t,e,a,i,n);const o=await Ql(s);return[o,s===o?"plain":"s256",a]}var ac=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function oc(t){const e=t.headers.get(ds);if(!e||!e.match(ac))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function lc(t){if(!t)throw new Error("Missing exp claim");if(t<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}function cc(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var uc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ne(t){if(!uc.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function G(t){if(!t.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function Vt(){return new Proxy({},{get:(t,e)=>{if(e==="__isUserNotAvailableProxy")return!0;
141if(typeof e=="symbol"){const r=e.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${e}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,e)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${e}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,e)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${e}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function hc(t,e){return new Proxy(t,{get:(r,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){const i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,s)}return!e.value&&typeof n=="string"&&(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 may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,s)}})}function an(t){return JSON.parse(JSON.stringify(t))}var pe=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},on=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function ln(t){var e;if(!Kl(t))throw new yt(pe(t),0);let r;try{r=await t.json()}catch(i){throw on.includes(t.status)?new yt(t.statusText||`HTTP ${t.status}`,t.status):new X(pe(i),i)}if(on.includes(t.status))throw new yt(pe(r),t.status);let n;const s=oc(t);if(s&&s.getTime()>=fs["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new en(pe(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new $}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new en(pe(r),t.status,r.weak_password.reasons);throw new Ll(pe(r),t.status||500,n)}var dc=(t,e,r,n)=>{const s={method:t,headers:e?.headers||{}};return t==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))};async function k(t,e,r,n){var s;const i=Object.assign({},n?.headers);i["X-Supabase-Api-Version"]||(i[ds]=fs["2024-01-01"].name),n?.jwt&&(i.Authorization=`Bearer ${n.jwt}`);const a=(s=n?.query)!==null&&s!==void 0?s:{};n?.redirectTo&&(a.redirect_to=n.redirectTo);const o=await fc(t,e,r+(Object.keys(a).length?"?"+new URLSearchParams(a).toString():""),{headers:i,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(o):{data:Object.assign({},o),error:null}}async function fc(t,e,r,n,s,i){const a=dc(e,n,s,i);let o;try{o=await t(r,Object.assign({},a))}catch(l){throw new yt(pe(l),0)}if(o.ok||await ln(o),n?.noResolveJson)return o;try{return await o.json()}catch(l){await ln(l)}}function V(t){var e;let r=null;gc(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=zl(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:typeof t?.id=="string"?t:null;return{data:{session:r,user:n},error:null}}function cn(t){const e=V(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function ue(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function pc(t){return{data:t,error:null}}function mc(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i}=t,a=Lt(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i},user:Object.assign({},a)},error:null}}function un(t){return t}function gc(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}var Kt=["global","local","others"],vc=class{constructor({url:t="",headers:e={},fetch:r,experimental:n}){this.url=t,this.headers=e,this.fetch=gs(r),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(t,e=Kt[0]){if(Kt.indexOf(e)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Kt.join(", ")}`);try{return await k(this.fetch,"POST",`${this.url}/logout?scope=${e}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(E(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,e={}){try{return await k(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:e.data},headers:this.headers,redirectTo:e.redirectTo,xform:ue})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:e}=t,r=Lt(t,["options"]),n=Object.assign(Object.assign({},r),e);return"newEmail"in r&&(n.new_email=r?.newEmail,delete n.newEmail),await k(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:mc,redirectTo:e?.redirectTo})}catch(e){if(E(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(t){try{return await k(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:ue})}catch(e){if(E(e))return{data:{user:null},error:e};throw e}}async listUsers(t){var e,r,n,s,i,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await k(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(e=t?.page)===null||e===void 0?void 0:e.toString())!==null&&r!==void 0?r:"",per_page:(s=(n=t?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:un});if(c.error)throw c.error;const h=await c.json(),u=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(o=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&o!==void 0?o:[];return p.length>
1410&&(p.forEach(d=>{const y=parseInt(d.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(d.split(";")[1].split("=")[1]);l[`${v}Page`]=y}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(E(l))return{data:{users:[]},error:l};throw l}}async getUserById(t){ne(t);try{return await k(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:ue})}catch(e){if(E(e))return{data:{user:null},error:e};throw e}}async updateUserById(t,e){ne(t);try{return await k(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:e,headers:this.headers,xform:ue})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,e=!1){ne(t);try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:e},xform:ue})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){ne(t.userId);try{const{data:e,error:r}=await k(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:e,error:r}}catch(e){if(E(e))return{data:null,error:e};throw e}}async _deleteFactor(t){ne(t.userId),ne(t.id);try{return{data:await k(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(e){if(E(e))return{data:null,error:e};throw e}}async _listOAuthClients(t){var e,r,n,s,i,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await k(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(e=t?.page)===null||e===void 0?void 0:e.toString())!==null&&r!==void 0?r:"",per_page:(s=(n=t?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:un});if(c.error)throw c.error;const h=await c.json(),u=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(o=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&o!==void 0?o:[];return p.length>0&&(p.forEach(d=>{const y=parseInt(d.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(d.split(";")[1].split("=")[1]);l[`${v}Page`]=y}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(E(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(t){try{return await k(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(E(e))return{data:null,error:e};throw e}}async _getOAuthClient(t){try{return await k(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(E(e))return{data:null,error:e};throw e}}async _updateOAuthClient(t,e){try{return await k(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(E(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await k(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(E(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(t){try{return await k(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(E(e))return{data:null,error:e};throw e}}async _listCustomProviders(t){try{const e={};return t?.type&&(e.type=t.type),await k(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:e,xform:r=>{var n;return{data:{providers:(n=r?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(e){if(E(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(t){try{return await k(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(E(e))return{data:null,error:e};throw e}}async _getCustomProvider(t){try{return await k(this.fetch,"GET",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(E(e))return{data:null,error:e};throw e}}async _updateCustomProvider(t,e){try{return await k(this.fetch,"PUT",`${this.url}/admin/custom-providers/${t}`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(E(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(t){try{return await k(this.fetch,"DELET
141E",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(E(e))return{data:null,error:e};throw e}}async _adminListPasskeys(t){G(this.experimental),ne(t.userId);try{return await k(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(E(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(t){G(this.experimental),ne(t.userId),ne(t.passkeyId);try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/passkeys/${t.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(E(e))return{data:null,error:e};throw e}}};function hn(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var $u={debug:!!(globalThis&&ms()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},yc=class extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}};function wc(){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)}}function bs(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function bc(t){return parseInt(t,16)}function _c(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function Ec(t){var e;const{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:h,uri:u,version:p}=t;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(` 142`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`);const d=bs(t.address),y=`${h?`${h}://${n}`:n} wants you to sign in with your Ethereum account: 143${d} 144 145${t.statement?`${t.statement} 146`:""}`;let v=`URI: ${u} 147Version: ${p} 148Chain ID: ${r}${a?` 149Nonce: ${a}`:""} 150Issued At: ${i.toISOString()}`;if(s&&(v+=` 151Expiration Time: ${s.toISOString()}`),o&&(v+=` 152Not Before: ${o.toISOString()}`),l&&(v+=` 153Request ID: ${l}`),c){let m=` 154Resources:`;for(const _ of c){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);m+=` 155- ${_}`}v+=m}return`${y} 156${v}`}var j=class extends Error{constructor({message:t,code:e,cause:r,name:n}){var s;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(s=n??(r instanceof Error?r.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=e}toJSON(){return{name:this.name,message:this.message,code:this.code}}},Tt=class extends j{constructor(t,e){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e,message:t}),this.name="WebAuthnUnknownError",this.originalError=e}};function kc({error:t,options:e}){var r,n,s;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new j({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new j({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new j({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new j({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new j({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new j({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new j({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new j({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(_s(a)){if(i.rp.id!==a)return new j({message:`The RP ID "${i.rp.id}
156" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new j({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new j({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new j({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new j({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Sc({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new j({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new j({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(_s(n)){if(r.rpId!==n)return new j({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new j({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new j({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new j({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var Rc=class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}},ur=new Rc;function dn(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:n}=t,s=Lt(t,["challenge","user","excludeCredentials"]),i=Oe(e).buffer,a=Object.assign(Object.assign({},r),{id:Oe(r.id).buffer}),o=Object.assign(Object.assign({},s),{challenge:i,user:a});if(n&&n.length>0){o.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){const c=n[l];o.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:Oe(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return o}function fn(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,n=Lt(t,["challenge","allowCredentials"]),s=Oe(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:Oe(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function pn(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:ve(new Uint8Array(t.response.attestationObject)),clientDataJSON:ve(new
156Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function mn(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,n=t.getClientExtensionResults(),s=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:ve(new Uint8Array(s.authenticatorData)),clientDataJSON:ve(new Uint8Array(s.clientDataJSON)),signature:ve(new Uint8Array(s.signature)),userHandle:s.userHandle?ve(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function _s(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function At(){var t,e;return!!(L()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Es(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Tt("Browser returned unexpected credential type",e)}:{data:null,error:new Tt("Empty credential response",e)}}catch(e){return{data:null,error:kc({error:e,options:t})}}}async function ks(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Tt("Browser returned unexpected credential type",e)}:{data:null,error:new Tt("Empty credential response",e)}}catch(e){return{data:null,error:Sc({error:e,options:t})}}}var xc={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Tc={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ct(...t){const e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),r=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(const s of t)if(s)for(const i in s){const a=s[i];if(a!==void 0)if(Array.isArray(a))n[i]=a;else if(r(a))n[i]=a;else if(e(a)){const o=n[i];e(o)?n[i]=Ct(o,a):n[i]=Ct(a)}else n[i]=a}return n}function Ac(t,e){return Ct(xc,t,e||{})}function Cc(t,e){return Ct(Tc,t,e||{})}var Oc=class{constructor(t){this.client=t,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:e,friendlyName:r,signal:n},s){var i;try{const{data:a,error:o}=await this.client.mfa.challenge({factorId:t,webauthn:e});if(!a)return{data:null,error:o};const l=n??ur.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){const h=r;if(h)c.name=`${c.id}:${h}`;else{const u=(await this.client.getUser()).data.user,p=((i=u?.user_metadata)===null||i===void 0?void 0:i.name)||u?.email||u?.id||"User";c.name=`${c.id}:${p}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{const{data:c,error:h}=await Es({publicKey:Ac(a.webauthn.credential_options.publicKey,s?.create),signal:l});return c?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:c}},error:null}:{data:null,error:h}}case"request":{const c=Cc(a.webauthn.credential_options.publicKey,s?.request),{data:h,error:u}=await ks(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:l}));return h?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:u}}}}catch(a){return E(a)?{data:null,error:a}:{data:null,error:new X("Unexpected error in challenge",a)}}}async _verify({challengeId:t,factorId:e,webauthn:r}){return this.client.mfa.verify({factorId:e,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:e=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!e)return{data:null,error:new Ke("rpId is required for WebAuthn authentication")};try{if(!At())return{data:null,error:new X("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this.challenge({factorId:t,webauthn:{rpId:e,rpOrigins:r},signal:n},{request:s});if(!i)return{data:null,error:a};const{webauthn:o}=i;return this._verify({factorId:t,challengeId:i.challengeId,webauthn:{type:o.type,rpId:e,rpOrigins:r,credential_response:o.credential_response}})}catch(i){return E(i)?{data:null,error:i}:{data:null,error:new X("Unexpected error in authenticate",i)}}}async _register({friendlyName:t,webauthn:{rpId:e=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!e)return{data:null,error:new Ke("rpId is required for WebAuthn registration")};try{if(!At())return{data:null,error:new X("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this._enroll({friendlyName:t});if(!i)return await this.client.mfa.listFactors().then(c=>{var h;
156return(h=c.data)===null||h===void 0?void 0:h.all.find(u=>u.factor_type==="webauthn"&&u.friendly_name===t&&u.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};const{data:o,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:e,rpOrigins:r},signal:n},{create:s});return o?this._verify({factorId:i.id,challengeId:o.challengeId,webauthn:{rpId:e,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:l}}catch(i){return E(i)?{data:null,error:i}:{data:null,error:new X("Unexpected error in register",i)}}}};wc();var Pc={url:jl,storageKey:Il,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Nl,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Re={},gn=!1,Ss=class hr{get jwks(){var e,r;return(r=(e=Re[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Re[this.storageKey]=Object.assign(Object.assign({},Re[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Re[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Re[this.storageKey]=Object.assign(Object.assign({},Re[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},Pc),e);if(this.storageKey=i.storageKey,this.instanceID=(r=hr.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,hr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&L()){const a=`${this._logPrefix()} 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.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(n=i.experimental)!==null&&n!==void 0?n:{},this.admin=new vc({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=gs(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,gn||(gn=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),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),webauthn:new Oc(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:ms()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=hn(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=hn(this.memoryStorage)),L()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),(a.data.event==="TOKEN_REFRESHED"||a.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${hs}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();
156const r=await this.initializePromise,n=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(const s of n)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return r}async _initialize(){var e;try{let r={},n="none";if(L()&&(r=sn(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),L()&&this.detectSessionInUrl&&n!=="none"){const{data:s,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Dl(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:o}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return E(r)?this._returnResult({error:r}):this._returnResult({error:new X("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,s;try{const{data:i,error:a}=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:V});if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});const o=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(i){if(E(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,n,s;let i=null;try{let a;if("email"in e){const{email:u,password:p,options:d}=e;let y=null,v=null;this.flowType==="pkce"&&([y,v,i]=await this._getCodeChallengeAndMethod()),a=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(d?.emailRedirectTo,i),body:{email:u,password:p,data:(r=d?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:y,code_challenge_method:v},xform:V})}else if("phone"in e){const{phone:u,password:p,options:d}=e;a=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:p,data:(n=d?.data)!==null&&n!==void 0?n:{},channel:(s=d?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:V})}else throw new lt("You must provide either an email or phone number and a password");const{data:o,error:l}=a;if(l||!o)return await J(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:l});const c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:h,session:c},error:null})}catch(a){if(await J(this.storage,this.storageKey,i),E(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await k(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:cn})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await k(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:cn})}else throw new lt("You must provide either an email or phone number and a password");const{data:n,error:s}=r;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){const i=new Se;return this._returnResult({data:{user:null,session:null},error:i})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(r){if(E(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,r){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,r)):this._exchangeCodeForSession(e,r)}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,s,i,a,o,l,c,h,u,p;let d,y;if("message"in e)d=e.message,y=e.signature;else{const{chain:v,wallet:m,statement:_,options:b}=e;let w;if(L())if(typeof m=="object")w=m;else{const N=window;if("ethereum"in N&&typeof N.ethereum=="object"&&"request"in N.ethereum&&typeof N.ethereum.request=="function")w=N.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof m!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=m}const T=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),x=await w.request({method:"eth_requestAccounts"}).then(N=>N).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!x||x.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const S=bs(x[0]);let A=(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!A){const N=await w.request({method:"eth_chainId"});
156A=bc(N)}const z={domain:T.host,address:S,statement:_,uri:T.href,version:"1",chainId:A,nonce:(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(a=(i=b?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(h=b?.signInWithEthereum)===null||h===void 0?void 0:h.resources};d=Ec(z),y=await w.request({method:"personal_sign",params:[_c(d),S]})}try{const{data:v,error:m}=await k(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:y},!((u=e.options)===null||u===void 0)&&u.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:V});if(m)throw m;if(!v||!v.session||!v.user){const _=new Se;return this._returnResult({data:{user:null,session:null},error:_})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:m})}catch(v){if(E(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,n,s,i,a,o,l,c,h,u,p,d;let y,v;if("message"in e)y=e.message,v=e.signature;else{const{chain:m,wallet:_,statement:b,options:w}=e;let T;if(L())if(typeof _=="object")T=_;else{const S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))T=S.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof _!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");T=_}const x=new URL((r=w?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in T&&T.signIn){const S=await T.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w?.signInWithSolana),{version:"1",domain:x.host,uri:x.href}),b?{statement:b}:null));let A;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")A=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)A=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in A&&"signature"in A&&(typeof A.signedMessage=="string"||A.signedMessage instanceof Uint8Array)&&A.signature instanceof Uint8Array)y=typeof A.signedMessage=="string"?A.signedMessage:new TextDecoder().decode(A.signedMessage),v=A.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in T)||typeof T.signMessage!="function"||!("publicKey"in T)||typeof T!="object"||!T.publicKey||!("toBase58"in T.publicKey)||typeof T.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${x.host} wants you to sign in with your Solana account:`,T.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${x.href}`,`Issued At: ${(s=(n=w?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=w?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((a=w?.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((o=w?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((l=w?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((c=w?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((u=(h=w?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||u===void 0)&&u.length?["Resources",...w.sign
156InWithSolana.resources.map(A=>`- ${A}`)]:[]].join(` 157`);const S=await T.signMessage(new TextEncoder().encode(y),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=S}}try{const{data:m,error:_}=await k(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:ve(v)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:V});if(_)throw _;if(!m||!m.session||!m.user){const b=new Se;return this._returnResult({data:{user:null,session:null},error:b})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if(E(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e,r){const n=r?.flowId!=null,s=n?wt(r?.flowId):L()?wt(sn(window.location.href)[Be]):null;n&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",r?.flowId);const{verifier:i,flowId:a}=n&&!s?{verifier:null,flowId:null}:await rc(this.storage,this.storageKey,s),[o,l]=(i??"").split("/");try{if(!o&&this.flowType==="pkce")throw new Ul;const{data:c,error:h}=await k(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:V});if(await J(this.storage,this.storageKey,a),h)throw h;if(!c||!c.session||!c.user){const u=new Se;return this._returnResult({data:{user:null,session:null,redirectType:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers(l==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c.session)),this._returnResult({data:Object.assign(Object.assign({},c),{redirectType:l??null}),error:h})}catch(c){if(await J(this.storage,this.storageKey,a),E(c))return this._returnResult({data:{user:null,session:null,redirectType:null},error:c});throw c}}async signInWithIdToken(e){try{const{options:r,provider:n,token:s,access_token:i,nonce:a}=e,{data:o,error:l}=await k(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:V});if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o||!o.session||!o.user){const c=new Se;return this._returnResult({data:{user:null,session:null},error:c})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:l})}catch(r){if(E(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,s,i,a;let o=null;try{if("email"in e){const{email:l,options:c}=e;let h=null,u=null;this.flowType==="pkce"&&([h,u,o]=await this._getCodeChallengeAndMethod());const{error:p}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:u},redirectTo:this._maybeAppendFlowIdToRedirect(c?.emailRedirectTo,o)});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){const{phone:l,options:c}=e,{data:h,error:u}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(s=c?.data)!==null&&s!==void 0?s:{},create_user:(i=c?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(a=c?.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:u})}throw new lt("You must provide either an email or phone number.")}catch(l){if(await J(this.storage,this.storageKey,o),E(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var r,n;try{let s,i;"options"in e&&(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:a,error:o}=await k(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:V});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(E(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var r,n,s,i;let a=null;try{let o=null,l=null;this.flowType==="pkce"&&([o,l,a]=await this._getCodeChallengeAndMethod());const c=await k(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:this._maybeAppendFlowIdToRedirect((r=e.options)===null||r===void 0?void 0:r.redirectTo,a)}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}
157:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:pc});return!((s=c.data)===null||s===void 0)&&s.url&&L()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await J(this.storage,this.storageKey,a),E(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new $;const{error:s}=await k(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(E(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let r=null;try{const n=`${this.url}/resend`;if("email"in e){const{email:s,type:i,options:a}=e;let o=null,l=null;this.flowType==="pkce"&&([o,l,r]=await this._getCodeChallengeAndMethod());const{error:c}=await k(this.fetch,"POST",n,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken},code_challenge:o,code_challenge_method:l},redirectTo:this._maybeAppendFlowIdToRedirect(a?.emailRedirectTo,r)});return c&&await J(this.storage,this.storageKey,r),this._returnResult({data:{user:null,session:null},error:c})}else if("phone"in e){const{phone:s,type:i,options:a}=e,{data:o,error:l}=await k(this.fetch,"POST",n,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:l})}throw new lt("You must provide either an email or phone number and a type")}catch(n){if(await J(this.storage,this.storageKey,r),E(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}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{return await e(await this.__loadSession())}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await D(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()<zt:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const a=await D(this.userStorage,this.storageKey+"-user");a?.user?e.user=a.user:e.user=Vt()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=hc(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);if(i){if(e.expires_at&&e.expires_at*1e3>Date.now()){const a=await D(this.storage,this.storageKey);if(a&&a.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ue}):await this._useSession(async r=>{var n,s,i;const{data:a,error:o}=r;if(o)throw o;return!(!((n=a.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new $}:await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ue})})}catch(r){if(E(r))return ot(r)&&await this._removeSession(),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){let n=null;try{return await this._useSession(async s=>{const{data:i,error:a}=s;
157if(a)throw a;if(!i.session)throw new $;const o=i.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c,n]=await this._getCodeChallengeAndMethod());const{data:h,error:u}=await k(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,n),body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:c}),jwt:o.access_token,xform:ue});if(u)throw u;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await J(this.storage,this.storageKey,n),E(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new $;const r=Date.now()/1e3;let n=r,s=!0,i=null;const{payload:a}=ht(e.access_token);if(a.exp&&(n=a.exp,s=n<=r),s){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(E(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(n=a.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new $;const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(E(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!L())throw new ct("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ct(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new Qr("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ct("Not a valid implicit grant flow url.")}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Qr("No code detected.");const{data:w,error:T}=await this._exchangeCodeForSession(e.code,{flowId:e[Be]});if(T)throw T;const x=new URL(window.location.href);return x.searchParams.delete("code"),x.searchParams.delete(Be),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:w.session,redirectType:(n=w.redirectType)!==null&&n!==void 0?n:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:a,refresh_token:o,expires_in:l,expires_at:c,token_type:h}=e;if(!a||!l||!o||!h)throw new ct("No session defined in URL");const u=Math.round(Date.now()/1e3),p=parseInt(l);let d=u+p;c&&(d=parseInt(c));const y=d-u;y*1e3<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${p}s`);const v=d-p;u-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,d,u):u-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,d,u);const{data:m,error:_}=await this._getUser(a);if(_)throw _;const b={provider_token:s,provider_refresh_token:i,access_token:a,expires_in:p,expires_at:d,refresh_token:o,token_type:h,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(s){if(E(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}
157async _isPKCECallback(e){if(!e.code)return!1;const r=wt(e[Be]);return r&&await D(this.storage,Pe(this.storageKey,r))?!0:!!await D(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;const s=async()=>{await this._removeSession()},{data:i,error:a}=r;if(a&&!ot(a))return this._returnResult({error:a});const o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(Xr(l)&&(l.status===404||l.status===401||l.status===403)||ot(l)))return e!=="others"&&await s(),this._returnResult({error:l})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){const r=Vl(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,s;try{const{data:{session:i},error:a}=r;if(a)throw a;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ot(i)||ut(i)||Xr(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let n=null,s=null,i=null;this.flowType==="pkce"&&([n,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await k(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r.redirectTo,i)})}catch(a){if(await J(this.storage,this.storageKey,i),E(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;let n=null;try{const{data:s,error:i}=await this._useSession(async a=>{var o,l,c,h,u;const{data:p,error:d}=a;if(d)throw d;const{url:y,flowId:v}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return n=v,await k(this.fetch,"GET",y,{headers:this.headers,jwt:(u=(h=p.session)===null||h===void 0?void 0:h.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return L()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:n},error:null})}catch(s){if(E(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:n},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{const{error:s,data:{session:i}}=r;if(s)throw s;const{options:a,provider:o,token:l,access_token:c,nonce:h}=e,{data:u,error:p}=await k(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:o,id_token:l,access_token:c,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:V});return p?this._returnResult({data:{user:null,session:null},error:p}):!u||!u.session||!u.user?this._returnResult({data:{user:null,session:null},error:new Se}):(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:p}))}catch(s){if(await J(this.storage,this.storageKey,null),E(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,s;const{data:i,error:a}=r;if(a)throw a;
157return await k(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r="#_refreshAccessToken()";this._debug(r,"begin");try{const n=Date.now();return await Gl(async s=>(s>0&&await Jl(200*Math.pow(2,s-1)),this._debug(r,"refreshing attempt",s),await k(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(s,i)=>{const a=200*Math.pow(2,s);return i&&ut(i)&&Date.now()+a-n<3e4})}catch(n){if(this._debug(r,"error",n),E(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const{url:n,flowId:s}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),L()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n,flowId:s},error:null}}async _recoverAndRefresh(){var e,r;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const s=await D(this.storage,this.storageKey);if(s&&this.userStorage){let a=await D(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:s.user},await ae(this.userStorage,this.storageKey+"-user",a)),s.user=(e=a?.user)!==null&&e!==void 0?e:Vt()}else if(s&&!s.user&&!s.user){const a=await D(this.storage,this.storageKey+"-user");a&&a?.user?(s.user=a.user,await F(this.storage,this.storageKey+"-user"),await ae(this.storage,this.storageKey,s)):s.user=Vt()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}const i=((r=s.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<zt;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${zt}s`),i){if(this.autoRefreshToken&&s.refresh_token){const{error:a}=await this._callRefreshToken(s.refresh_token);a&&(Bl(a)?this._debug(n,"refresh discarded by commit guard",a):this._debug(n,"refresh failed",a))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(s.access_token);!o&&a?.user?(s.user=a.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(n,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),ut(s)?console.warn(s):console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new $;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;const s="#_callRefreshToken()";this._debug(s,"begin");try{this.refreshingDeferred=new vs,this.refreshingDeferred.promise.then(void 0,()=>{});const i=await D(this.storage,this.storageKey),{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new $;const l=await D(this.storage,this.storageKey);if(i!==null&&(l===null||l.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:l?"replaced":"cleared"});const u={data:null,error:new Zr};return this.refreshingDeferred.resolve(u),u}const c=this._sessionRemovalEpoch;if(await this._saveSession(a.session),this._sessionRemovalEpoch!==c){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, und
157oing write"),await F(this.storage,this.storageKey),this.userStorage&&await F(this.userStorage,this.storageKey+"-user");const u={data:null,error:new Zr};return this.refreshingDeferred.resolve(u),u}await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const h={data:a.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(s,"error",i),E(i)){const a={data:null,error:i};if(!ut(i)){const o=await D(this.storage,this.storageKey);o?.expires_at&&o.expires_at*1e3>Date.now()?this._debug(s,"proactive refresh failed, access token still valid â preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:a,expiresAt:Date.now()+Pl},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,r,n=!0){if(this._pendingInitNotifications!==null&&n){this._pendingInitNotifications.push({event:e,session:r,broadcast:n});return}const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await ae(this.userStorage,this.storageKey+"-user",{user:r.user});const s=Object.assign({},r);delete s.user;const i=an(s);await ae(this.storage,this.storageKey,i)}else{const s=an(r);await ae(this.storage,this.storageKey,s)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await F(this.storage,this.storageKey),await nc(this.storage,this.storageKey),await F(this.storage,this.storageKey+"-user"),this.userStorage&&await F(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&L()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),ge);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((n.expires_at*1e3-e)/ge);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${ge}ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof yc)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const e=Date.now();try{await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((n.expires_at*1e3-e)/ge);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${ge}ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!L()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>
157{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let s=n?.redirectTo,i=null,a=null,o=null;this.flowType==="pkce"&&([i,a,o]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,o));const l=[`provider=${encodeURIComponent(r)}`];if(s&&l.push(`redirect_to=${encodeURIComponent(s)}`),n?.scopes&&l.push(`scopes=${encodeURIComponent(n.scopes)}`),i!=null&&a!=null){const c=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});l.push(c.toString())}if(n?.queryParams){const c=new URLSearchParams(n.queryParams);l.push(c.toString())}return n?.skipBrowserRedirect&&l.push(`skip_http_redirect=${n.skipBrowserRedirect}`),{url:`${e}?${l.join("&")}`,flowId:o}}_maybeAppendFlowIdToRedirect(e,r){return!e||!r||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:sc(e,r)}async _getCodeChallengeAndMethod(e=!1){return ic(this.storage,this.storageKey,e,r=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",r))}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:s,error:i}=r;return i?this._returnResult({data:null,error:i}):await k(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,s;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await k(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l?.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){const r=async()=>{try{return await this._useSession(async n=>{var s;const{data:i,error:a}=n;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?pn(e.webauthn.credential_response):mn(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:c}))})}catch(n){if(E(n))return this._returnResult({data:null,error:n});throw n}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){const r=async()=>{try{return await this._useSession(async n=>{var s;const{data:i,error:a}=n;if(a)return this._returnResult({data:null,error:a});const o=await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:dn(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:fn(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(E(n))return this._returnResult({data:null,error:n});throw n}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};const s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,s,i;if(e)try{const{payload:p}=ht(e);let d=null;p.aal&&(d=p.aal);let y=d;const{data:{user:v},error:m}=await this.getUser(e);if(m)return this._returnResult({data:null,error:m});((n=(r=v?.factors)===null||r===void 0?void 0:r.filter(b=>b.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(y="aal2");const _=p.amr||[];return{data:{currentLevel:d,nextLevel:y,currentAuthenticationMethods:_},error:null}}catch(p){if(E(p))return this._returnResult({data:null,error:p});throw p}const{data:{session:a},error:o}
157=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=ht(a.access_token);let c=null;l.aal&&(c=l.aal);let h=c;((i=(s=a.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");const u=l.amr||[];return{data:{currentLevel:c,nextLevel:h,currentAuthenticationMethods:u},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?await k(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new $})})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new $});const a=await k(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&L()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(n){if(E(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new $});const a=await k(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&L()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(n){if(E(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await k(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new $})})}catch(e){if(E(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?(await k(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new $})})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(o=>o.kid===e);if(n)return n;const s=Date.now();if(n=this.jwks.keys.find(o=>o.kid===e),n&&this.jwks_cached_at+6e5>s)return n;const{data:i,error:a}=await k(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(o=>o.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:p,error:d}
157=await this.getSession();if(d||!p.session)return this._returnResult({data:null,error:d});n=p.session.access_token}const{header:s,payload:i,signature:a,raw:{header:o,payload:l}}=ht(n);if(!r?.allowExpired)try{lc(i.exp)}catch(p){throw new Rt(p instanceof Error?p.message:"JWT validation failed")}const c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){const{error:p}=await this.getUser(n);if(p)throw p;return{data:{claims:i,header:s,signature:a},error:null}}const h=cc(s.alg),u=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,u,a,Wl(`${o}.${l}`)))throw new Rt("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(n){if(E(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,s;G(this.experimental);try{if(!At())return this._returnResult({data:null,error:new X("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!i)return this._returnResult({data:null,error:a});const o=fn(i.options),l=(s=(n=e?.options)===null||n===void 0?void 0:n.signal)!==null&&s!==void 0?s:ur.createNewAbortSignal(),{data:c,error:h}=await ks({publicKey:o,signal:l});if(h||!c)return this._returnResult({data:null,error:h??new X("WebAuthn ceremony failed",null)});const u=mn(c);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:u})}catch(i){if(E(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,n;G(this.experimental);try{if(!At())return this._returnResult({data:null,error:new X("Browser does not support WebAuthn",null)});const{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});const a=dn(s.options),o=(n=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:ur.createNewAbortSignal(),{data:l,error:c}=await Es({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:c??new X("WebAuthn ceremony failed",null)});const h=pn(l);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(E(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){G(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new $});const{data:s,error:i}=await k(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(E(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){G(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new $});const{data:i,error:a}=await k(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;G(this.experimental);try{const{data:n,error:s}=await k(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:n,error:null})}catch(n){if(E(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){G(this.experimental);try{const{data:r,error:n}=await k(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return n?this._returnResult({data:null,error:n}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){G(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new $});const{data:s,error:i}=await k(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:a=>({data:a,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(E(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){G(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new $});const{data:i,error:a}=await k(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){G(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new $});const{error:i}
157=await k(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(E(r))return this._returnResult({data:null,error:r});throw r}}};Ss.nextInstanceID={};var jc=Ss,Ic="2.112.4",Me="",Ot;if(typeof Deno<"u"){var Jt;Me="deno",Ot=(Jt=Deno.version)===null||Jt===void 0?void 0:Jt.deno}else if(typeof document<"u")Me="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")Me="react-native";else{var Gt;Me="node";const t=globalThis.process;Ot=t==null||(Gt=t.version)===null||Gt===void 0?void 0:Gt.replace(/^v/,"")}var Rs=[`runtime=${Me}`];Ot&&Rs.push(`runtime-version=${Ot}`);var Nc={headers:{"X-Client-Info":`supabase-js/${Ic}; ${Rs.join("; ")}`}},$c={schema:"public"},Lc={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Dc={},Uc={enabled:!1,respectSamplingDecision:!0};function Bc(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,n,s,i]=e;if(r.length!==2||n.length!==32||s.length!==16||i.length!==2)return null;const a=/^[0-9a-f]+$/i;return!a.test(r)||!a.test(n)||!a.test(s)||!a.test(i)||n==="00000000000000000000000000000000"||s==="0000000000000000"?null:{version:r,traceId:n,parentId:s,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function Mc(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const n of e)try{if(typeof n=="string"){if(Fc(r.hostname,n))return!0}else if(n instanceof RegExp){if(n.test(r.hostname))return!0}else if(typeof n=="function"&&n(r))return!0}catch{continue}return!1}function Fc(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function Hc(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function Ge(t){"@babel/helpers - typeof";return Ge=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ge(t)}function qc(t,e){if(Ge(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Ge(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Wc(t){var e=qc(t,"string");return Ge(e)=="symbol"?e:e+""}function zc(t,e,r){return(e=Wc(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function vn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function P(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?vn(Object(r),!0).forEach(function(n){zc(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):vn(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Vc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Kc=()=>Headers,xs=t=>t.startsWith("sb_publishable_")||t.startsWith("sb_secret_"),Jc="sb_temp_",yn=new Set,Gc=t=>{var e,r;if(!t.startsWith("sb_")||xs(t)||t.startsWith(Jc))return;const n=(e=(r=t.match(/^sb_[a-zA-Z0-9]+_/))===null||r===void 0?void 0:r[0])!==null&&e!==void 0?e:"unknown";yn.has(n)||(yn.add(n),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))},wn=(t,e,r,n,s,i)=>{const a=Vc(n),o=Kc(),l=s?.enabled===!0,c=s?.respectSamplingDecision!==!1,h=l?Hc(e):null,u=!(i?.omitApiKeyAsBearer&&xs(t));return async(p,d)=>{const y=await r();let v=new o(d?.headers);if(v.has("apikey")||v.set("apikey",t),!v.has("Authorization")){const m=y??(u?t:null);m&&v.set("Authorization",`Bearer ${m}`)}if(h){const m=Yc(p,h,c);m&&(m.traceparent&&!v.has("traceparent")&&v.set("traceparent",m.traceparent),m.tracestate&&!v.has("tracestate")&&v.set("tracestate",m.tracestate),m.baggage&&!v.has("baggage")&&v.set("baggage",m.baggage))}return a(p,P(P({},d),{},{headers:v}))}},bn=!1,_n=!1;function Yc(t,e,r){const n=Qa();if(!n)return bn||(bn=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!Mc(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const s=n();if(!s||!s.traceparent){var i;if(!(s==null||(i=s.carrierKeys)===null||i===void 0)&&i.length&&!_n){_n=!0;const a=s.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it."
157:" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${s.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+a)}return null}if(r){const a=Bc(s.traceparent);if(a&&!a.isSampled)return{traceparent:s.traceparent}}return s}function En(t){return typeof t=="boolean"?{enabled:t}:t}function Xc(t){return t.endsWith("/")?t:t+"/"}function Qc(t,e){var r,n,s,i,a,o;const{db:l,auth:c,realtime:h,global:u}=t,{db:p,auth:d,realtime:y,global:v}=e,m=En(t.tracePropagation),_=En(e.tracePropagation),b={db:P(P({},p),l),auth:P(P({},d),c),realtime:P(P({},y),h),storage:{},global:P(P(P({},v),u),{},{headers:P(P({},(r=v?.headers)!==null&&r!==void 0?r:{}),(n=u?.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(s=(i=m?.enabled)!==null&&i!==void 0?i:_?.enabled)!==null&&s!==void 0?s:!1,respectSamplingDecision:(a=(o=m?.respectSamplingDecision)!==null&&o!==void 0?o:_?.respectSamplingDecision)!==null&&a!==void 0?a:!0},accessToken:async()=>""};return t.accessToken?b.accessToken=t.accessToken:delete b.accessToken,b}function Zc(t){const e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Xc(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var eu=class extends jc{constructor(t){super(t)}},tu=class{constructor(t,e,r){var n,s;this.supabaseUrl=t,this.supabaseKey=e;const i=Zc(t);if(!e)throw new Error("supabaseKey is required.");Gc(e),this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:$c,realtime:Dc,auth:P(P({},Lc),{},{storageKey:a}),global:Nc,tracePropagation:Uc},l=Qc(r??{},o);if(this.settings=l,this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(h,u)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(u)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=wn(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation),this.functionsFetch=wn(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(P({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new ho(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit,retry:l.db.retry}),this.storage=new Ol(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new ro(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:null}async _getAccessToken(){var t=this,e;return(e=await t._getSessionToken())!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:a,lock:o,debug:l,throwOnError:c,experimental:h,lockAcquireTimeout:u,skipAutoInitialize:p},d,y){const v={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new eu({url:this.authUrl.href,headers:P(P({},v),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,flowType:a,lock:o,debug:l,throwOnError:c,experimental:h,fetch:y,lockAcquireTimeout:u,skipAutoInitialize:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new rl(this.realtimeUrl.href,P(P({},t),{},{params:P(P({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN"||t==="INITIAL_SESSION")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},ru=(t,e,r)=>new tu(t,e,r);
157function nu(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}nu()&&console.warn("â ï¸ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");var Ts="https://cjizgjazlbrnbmmpmabn.supabase.co",su="sb_publishable_e_WWC8bjzcLE35xejoCleg_fxbWe5wA",dt=ru(Ts,su,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1,storageKey:"cancentus-admin-auth"}});function Lu(t){if(!t)return null;if(/^https?:\/\//i.test(t))return t;const e=t.replace(/^\/+/,"");return`${Ts}/storage/v1/object/public/blog-media/${e}`}var As=(0,f.createContext)(null);function iu(){const t=(0,f.useContext)(As);if(!t)throw new Error("useAuth must be used within an AuthProvider");return t}function au({children:t}){const[e,r]=(0,f.useState)(null),[n,s]=(0,f.useState)(!0);(0,f.useEffect)(()=>{let l=!1;dt.auth.getSession().then(({data:h})=>{l||(r(h.session),s(!1))});const{data:c}=dt.auth.onAuthStateChange((h,u)=>{r(u),s(!1)});return()=>{l=!0,c.subscription.unsubscribe()}},[]);const i=(0,f.useCallback)(async(l,c)=>{const{error:h}=await dt.auth.signInWithPassword({email:l,password:c});if(h)throw new Error(h.message)},[]),a=(0,f.useCallback)(async()=>{const{error:l}=await dt.auth.signOut();if(l)throw new Error(l.message)},[]),o=(0,f.useMemo)(()=>({session:e,user:e?.user??null,loading:n,signIn:i,signOut:a}),[e,n,i,a]);return(0,g.jsx)(As.Provider,{value:o,children:t})}function ou(){const{session:t,loading:e}=iu(),r=U();return e?(0,g.jsx)("div",{className:"flex min-h-screen w-full items-center justify-center bg-white",children:(0,g.jsx)("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-gray-900","aria-label":"Loading"})}):t?(0,g.jsx)(Hi,{}):(0,g.jsx)(ft,{to:"/admin/login",replace:!0,state:{from:`${r.pathname}${r.search}`}})}var lu=(0,f.lazy)(()=>W(()=>import("./Vision-B5IUoty2.js"),__vite__mapDeps([0,1,2]))),cu=(0,f.lazy)(()=>W(()=>import("./Programs-Dms8A0ks.js"),__vite__mapDeps([3,1,2]))),uu=(0,f.lazy)(()=>W(()=>import("./Team-DnAUWzvN.js"),__vite__mapDeps([4,1,2,5,6,7]))),hu=(0,f.lazy)(()=>W(()=>import("./Contact-v8ZtinJf.js"),__vite__mapDeps([8,1,2,5,6]))),du=(0,f.lazy)(()=>W(()=>import("./Imprint-Ch7iluOv.js"),__vite__mapDeps([9,1,2,6]))),fu=(0,f.lazy)(()=>W(()=>import("./Privacy-Bv347CSE.js"),__vite__mapDeps([10,1,2,6]))),pu=(0,f.lazy)(()=>W(()=>import("./Aidd-B0p-Pcat.js"),__vite__mapDeps([11,1,2]))),mu=(0,f.lazy)(()=>W(()=>import("./News-C_xdbrw3.js"),__vite__mapDeps([12,1,2,13]))),gu=(0,f.lazy)(()=>W(()=>import("./NewsPost-xICcv9id.js"),__vite__mapDeps([14,1,2,13,15]))),vu=(0,f.lazy)(()=>W(()=>import("./Login-DJtBXvGu.js"),__vite__mapDeps([16,1,2]))),yu=(0,f.lazy)(()=>W(()=>import("./NewsList-D5gkas9U.js"),__vite__mapDeps([17,1,2,7,18]))),kn=(0,f.lazy)(()=>W(()=>import("./NewsForm-BhRe4pwl.js"),__vite__mapDeps([19,1,2,15,7,18])));function wu(){const t=U();return(0,f.useEffect)(()=>{requestAnimationFrame(()=>{window.scrollTo({top:0,left:0,behavior:"instant"})});const r=setTimeout(()=>{document.querySelectorAll('img[src^="blob:"]').forEach(n=>{n instanceof HTMLImageElement&&n.src.startsWith("blob:")&&URL.revokeObjectURL(n.src)}),typeof requestIdleCallback<"u"&&requestIdleCallback(()=>{document.querySelectorAll('img[data-cleanup="true"]').forEach(n=>{n instanceof HTMLImageElement&&(n.loading="lazy")})})},100);return()=>clearTimeout(r)},[t.pathname]),null}function bu({children:t}){const e=U();return(0,g.jsx)("div",{children:t},e.pathname)}function _u(){return(0,f.useEffect)(()=>{document.documentElement.classList.add("dark")},[]),(0,g.jsx)(_a,{children:(0,g.jsxs)(au,{children:[(0,g.jsx)(wu,{}),(0,g.jsx)(f.Suspense,{fallback:(0,g.jsx)("div",{className:"min-h-screen w-full flex items-center justify-center bg-white dark:bg-[#0A0E1F]",children:(0,g.jsx)("div",{className:"text-center",children:(0,g.jsx)("div",{className:"inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 dark:border-white"})})}),children:(0,g.jsx)(bu,{children:(0,g.jsxs)(qi,{children:[(0,g.jsx)(I,{path:"/",element:(0,g.jsx)(Ya,{})}),(0,g.jsx)(I,{path:"/vision",element:(0,g.jsx)(lu,{})}),(0,g.jsx)(I,{path:"/programs",element:(0,g.jsx)(cu,{})}),(0,g.jsx)(I,{path:"/therapeutic-areas",element:(0,g.jsx)(ft,{to:"/programs#therapeutic-areas",replace:!0})}),(0,g.jsx)(I,{path:"/team",element:(0,g.jsx)(uu,{})}),(0,g.jsx)(I,{path:"/founders",element:(0,g.jsx)(ft,{to:"/team",replace:!0})}),(0,g.jsx)(I,{path:"/board",element:(0,g.jsx)(ft,{to:"/team",replace:!0})}),(0,g.jsx)(I,{path:"/contact",element:(0,g.jsx)(hu,{})}),(0,g.jsx)(I,{path:"/imprint",element:(0,g.jsx)(du,{})}),(0,g.jsx)(I,{path:"/privacy",element:(0,g.jsx)(fu,{})}),(0,g.jsx)(I,{path:"/aidd",element:(0,g.jsx)(pu,{})}),(0,g.jsx)(I,{path:"/news",element:(0,g.jsx)(mu,{})}),(0,g.jsx)(I,{path:"/news/:slug",element:(0,g.jsx)(gu,{})}),(0,g.jsx)(I,{path:"/admin/login",element:(0,g.jsx)(vu,{})}),(0,g.jsxs)(I,{element:(0,g.jsx)(ou,{}),children:[(0,g.jsx)(I,{path:"/admin/news",element:(0,g.jsx)(yu,{})}),(0,g.jsx)(I,{path:"/admin/news/new",element:(0,g.jsx)(kn,{mode:"create"})}),(0,g.jsx)(I,{path:"/admin/news/:id/edit",element:(0,g.jsx)(kn,{mode:"edit"})})]})]})})})]})})}(0,Ds.createRoot)(document.getElementById("root")).render((0,g.jsx)(f.StrictMode,{children:(0,g.jsx)(_u,{})}));export{Lt as a,qa as c,ft as d,U as f,Iu as h,$r as i,he as l,Au as m,Lu as n,Nu as o,mr as p,dt as r,Wa as s,iu as t,Yn as u};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.