1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-BHH8rdGj.css"])))=>i.map(i=>d[i]); 2var Ks=Object.defineProperty;var Ws=(t,e,r)=>e in t?Ks(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Ze=(t,e,r)=>Ws(t,typeof e!="symbol"?e+"":e,r);import{R as tr,j as n,r as y,u as re,N as z,a as Js,b as cs,L as gr,c as Hs,d as h,_ as m,e as Xs,B as Ys}from"./vendor-react-BPv6TnFg.js";function pd(){import.meta.url,import("_").catch(()=>1),(async function*(){})().next()}const _r="cm:chunk-reload",Zs=/dynamically imported module|Importing a module script failed|error loading dynamically imported module|Failed to fetch dynamically|MIME type|Unable to preload CSS|ChunkLoadError|Loading (CSS )?chunk \S+ failed|Error loading https?:\/\/\S*\/assets\//i;function Qs(t){if(!t)return!1;const e=t instanceof Error?"".concat(t.name,": ").concat(t.message):String(t);return Zs.test(e)}const wr="c51d5d30e889af2e8656b07b1971c9214e7e03a2",en=600*1e3;let Ut=!1;function ls(){return Ut}function _t(t){var e,r;if(Ut)return!0;if(!Qs(t))return!1;try{const s=sessionStorage.getItem(_r);if(s){let i="",a=0;try{const o=JSON.parse(s);i=(e=o.build)!=null?e:"",a=(r=o.t)!=null?r:0}catch(o){}if(i===wr&&Date.now()-a<en)return!1}sessionStorage.setItem(_r,JSON.stringify({build:wr,t:Date.now()}))}catch(s){return!1}return Ut=!0,window.location.reload(),!0}const vr=()=>new Promise(()=>{});function p(t){return tr.lazy(()=>t().then(e=>!e&&ls()?vr():e).catch(e=>_t(e)?vr():new Promise(r=>setTimeout(r,400)).then(()=>t())))}function rr(t){const e=t.replace(/\/+$/,"")||"/";return e==="/newsletter"||e.startsWith("/sparplan-test")||e.startsWith("/portfolio-schnellcheck")||e==="/junior-depot"||e==="/finanzguide"||e==="/finanzguide/danke"||e==="/methode"||e==="/methode-neu"||e==="/1zu1"||e==="/pricing-neu"||e==="/events-neu"||e==="/finanzguide-neu"||e==="/kauf-abschliessen"||e==="/coaching-neu"||e==="/karten-test"||e==="/retreat-neu"||e==="/check-neu"||e==="/track-record-neu"||e==="/links-neu"||e==="/newsletter-neu"||e==="/about-us-neu"||e==="/partners-neu"||e==="/start"||e==="/start-b"||e==="/erstgespraech"||e==="/gespraech"||e==="/gespraech/gebucht"||e==="/"||e==="/neu"||e==="/pricing"||e==="/events"||e==="/events/success"||e==="/coaching"||e==="/retreat"||e==="/track-record"||e==="/links"||e==="/about-us"||e==="/partners"||e==="/check"||e.startsWith("/mein-portfolio")||e==="/beginner"||e==="/beginner-b"||e==="/beginner-c"||e==="/newsletter-erfolge"||e.startsWith("/beginner-guide")||e.startsWith("/junior-depot-guide")}const br="#FAF8F4",yr="#111111";class xe extends tr.Component{constructor(){super(...arguments);Ze(this,"state",{failed:!1})}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r,s){_t(r)||console.error("AppErrorBoundary:",r,s==null?void 0:s.componentStack)}componentDidUpdate(r){this.state.failed&&!Object.is(r.resetKey,this.props.resetKey)&&this.setState({failed:!1})}render(){if(!this.state.failed)return this.props.children;if(ls())return null;if(this.props.fallback!==void 0)return this.props.fallback;const r=this.props.variant!=="inline";return n.jsx("div",{role:"alert",className:"flex flex-col items-center justify-center px-6 py-16 ".concat(r?"min-h-screen":"min-h-[60vh]"),style:{background:r?br:"transparent"},children:n.jsxs("div",{className:"w-full max-w-md rounded-3xl px-8 py-10 text-center shadow-sm",style:{background:br,color:yr,border:"1px solid rgba(17,17,17,0.08)"},children:[n.jsx("h1",{className:"text-3xl font-semibold leading-tight",style:{fontFamily:"Fraunces, Georgia, serif"},children:"Da ist etwas schiefgelaufen."}),n.jsx("p",{className:"mt-4 text-base leading-relaxed",style:{color:"rgba(17,17,17,0.68)"},children:"Diese Seite konnte nicht geladen werden. Meist liegt es an einer veralteten Version im Browser â ein Neuladen behebt es."}),n.jsxs("div",{className:"mt-8 flex flex-col gap-3 sm:flex-row sm:justify-center",children:[n.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-[#4F46E5] px-6 py-3 font-bold text-white transition-colors hover:bg-[#443CC4] focus:outline-none focus-visible:ring-4 focus-visible:ring-[#4F46E5]/40",children:"Seite neu laden"}),n.jsx("button",{type:"button",onClick:()=>{window.location.href="/"},className:"rounded-full border px-6 py-3 font-semibold transition-colors hover:bg-black/5 focus:outline-none focus-visible:ring-4 focus-visible:ring-[#4F46E5]/40",style:{borderColor:"rgba(17,17,17,0.15)",color:yr},children:"Zur Startseite"})]})]})})}}const Oe=class Oe{constructor(){Ze(this,"preferences",null);Ze(this,"callbacks",[]);this.loadPreferences()}static getInstance(){return Oe.instance||(Oe.instance=new Oe),Oe.instance}loadPreferences(){try{const e=localStorage.getItem("cookie-consent");if(e)return this.preferences=JSON.parse(e),this.preferences}catch(e){console.error("Error loading cookie preferences:",e)}return null}getPreferences(){return this.preferences}hasConsent(){return this.preferences!==null}hasAnalyticsConsent(){var e;return((e=this.preferences)==null?void 0:e.analytics)===!0}hasMarketingConsent(){var e;return((e=this.preferences)==null?void 0:e.marketing)===!0}hasExternalConsent(){var e;return((e=this.preferences)==null?void 0:e.external)===!0}setPreferences(e){this.preferences=e,localStorage.setItem("cookie-consent",JSON.stringify(e)),localStorage.setItem("cookie-consent-date",new Date().toISOString()),this.callbacks.forEach(r=>r(e)),this.handleGoogleAnalytics(e.analytics)}acceptAll(){const e={necessary:!0,analytics:!0,marketing:!0,external:!0};this.setPreferences(e)}rejectAll(){const e={necessary:!0,analytics:!1,marketing:!1,external:!1};this.setPreferences(e)}onPreferencesChange(e){this.callbacks.push(e)}removePreferencesListener(e){this.callbacks=this.callbacks.filter(r=>r!==e)}handleGoogleAnalytics(e){typeof window<"u"&&(e?(window.gtag&&window.gtag("consent","update",{analytics_storage:"granted"}),console.log("Google Analytics enabled")):(window.gtag&&window.gtag("consent","update",{analytics_storage:"denied"}),console.log("Google Analytics disabled")))}resetConsent(){localStorage.removeItem("cookie-consent"),localStorage.removeItem("cookie-consent-date"),this.preferences=null,this.handleGoogleAnalytics(!1)}getConsentDate(){const e=localStorage.getItem("cookie-consent-date");return e?new Date(e):null}isConsentExpired(e=365){const r=this.getConsentDate();return r?(new Date().getTime()-r.getTime())/(1e3*60*60*24)>e:!0}};Ze(Oe,"instance");let Vt=Oe;const me=Vt.getInstance(),tn="rbz2g",rn="tw-rbz2g-rcber",sn="tw-rbz2g-rcbeo";function xr(){if(window.twq)return;const t=window.twq=function(...r){t.exe?t.exe.apply(t,r):t.queue.push(r)};t.version="1.1",t.queue=[];const e=document.createElement("script");e.async=!0,e.src="https://static.ads-twitter.com/uwt.js",document.head.appendChild(e),window.twq("config",tn)}const nn=()=>(y.useEffect(()=>{const t=me.getPreferences();t!=null&&t.marketing&&xr();const e=r=>{r.marketing&&xr()};return me.onPreferencesChange(e),()=>{me.removePreferencesListener(e)}},[]),null);function _d(t){window.twq&&window.twq("event",rn,t?{email_address:t}:{})}function wd(t){window.twq&&window.twq("event",sn,t?{value:t.toFixed(2),currency:"EUR"}:{})}function wt(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(t);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(t,s[i])&&(r[s[i]]=t[s[i]]);return r}function vd(t,e,r,s){var i=arguments.length,a=i<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,r):s,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(t,e,r,s);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,r,a):o(e,r))||a);return i>3&&a&&Object.defineProperty(e,r,a),a}function an(t,e,r,s){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(d){try{u(s.next(d))}catch(_){o(_)}}function l(d){try{u(s.throw(d))}catch(_){o(_)}}function u(d){d.done?a(d.value):i(d.value).then(c,l)}u((s=s.apply(t,e||[])).next())})}const on=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);
2class sr extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}}class cn extends sr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Er extends sr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class kr extends sr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var qt;(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"})(qt||(qt={}));class ln{constructor(e,{headers:r={},customFetch:s,region:i=qt.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=on(s)}setAuth(e){this.headers.Authorization="Bearer ".concat(e)}invoke(e){return an(this,arguments,void 0,function*(r,s={}){var i;let a,o;try{const{headers:c,method:l,body:u,signal:d,timeout:_}=s;let g={},{region:f}=s;f||(f=this.region);const w=new URL("".concat(this.url,"/").concat(r));f&&f!=="any"&&(g["x-region"]=f,w.searchParams.set("forceFunctionRegion",f));let v;u&&(c&&!Object.prototype.hasOwnProperty.call(c,"Content-Type")||!c)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",v=u):typeof u=="string"?(g["Content-Type"]="text/plain",v=u):typeof FormData<"u"&&u instanceof FormData?v=u:(g["Content-Type"]="application/json",v=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?v=JSON.stringify(u):v=u;let b=d;_&&(o=new AbortController,a=setTimeout(()=>o.abort(),_),d?(b=o.signal,d.addEventListener("abort",()=>o.abort())):b=o.signal);const x=yield this.fetch(w.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),c),body:v,signal:b}).catch(q=>{throw new cn(q)}),E=x.headers.get("x-relay-error");if(E&&E==="true")throw new Er(x);if(!x.ok)throw new kr(x);let k=((i=x.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),A;return k==="application/json"?A=yield x.json():k==="application/octet-stream"||k==="application/pdf"?A=yield x.blob():k==="text/event-stream"?A=x:k==="multipart/form-data"?A=yield x.formData():A=yield x.text(),{data:A,error:null,response:x}}catch(c){return{data:null,error:c,response:c instanceof kr||c instanceof Er?c.context:void 0}}finally{a&&clearTimeout(a)}})}}var un=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
2de=t.code}},dn=class{constructor(t){var e,r;this.shouldThrowOnError=!1,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,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;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");const s=this.fetch;let i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let o=null,c=null,l=null,u=a.status,d=a.statusText;if(a.ok){var _,g;if(r.method!=="HEAD"){var f;const x=await a.text();x===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?c=x:c=JSON.parse(x))}const v=(_=r.headers.get("Prefer"))===null||_===void 0?void 0:_.match(/count=(exact|planned|estimated)/),b=(g=a.headers.get("content-range"))===null||g===void 0?void 0:g.split("/");v&&b&&b.length>1&&(l=parseInt(b[1])),r.isMaybeSingle&&r.method==="GET"&&Array.isArray(c)&&(c.length>1?(o={code:"PGRST116",details:"Results contain ".concat(c.length," rows, application/vnd.pgrst.object+json requires 1 row"),hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,l=null,u=406,d="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{var w;const v=await a.text();try{o=JSON.parse(v),Array.isArray(o)&&a.status===404&&(c=[],o=null,u=200,d="OK")}catch(b){a.status===404&&v===""?(u=204,d="No Content"):o={message:v}}if(o&&r.isMaybeSingle&&(!(o==null||(w=o.details)===null||w===void 0)&&w.includes("0 rows"))&&(o=null,u=200,d="OK"),o&&r.shouldThrowOnError)throw new un(o)}return{error:o,data:c,count:l,status:u,statusText:d}});return this.shouldThrowOnError||(i=i.catch(a=>{var o;let c="";const l=a==null?void 0:a.cause;if(l){var u,d,_,g;const w=(u=l==null?void 0:l.message)!==null&&u!==void 0?u:"",v=(d=l==null?void 0:l.code)!==null&&d!==void 0?d:"";c="".concat((_=a==null?void 0:a.name)!==null&&_!==void 0?_:"FetchError",": ").concat(a==null?void 0:a.message),c+="\n\nCaused by: ".concat((g=l==null?void 0:l.name)!==null&&g!==void 0?g:"Error",": ").concat(w),v&&(c+=" (".concat(v,")")),l!=null&&l.stack&&(c+="\n".concat(l.stack))}else{var f;c=(f=a==null?void 0:a.stack)!==null&&f!==void 0?f:""}return{error:{message:"".concat((o=a==null?void 0:a.name)!==null&&o!==void 0?o:"FetchError",": ").concat(a==null?void 0:a.message),details:c,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},hn=class extends dn{select(t){let e=!1;const r=(t!=null?t:"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){const a=i?"".concat(i,".order"):"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,"".concat(o?"".concat(o,","):"").concat(t,".").concat(e?"asc":"desc").concat(r===void 0?"":r?".nullsfirst":".nullslast")),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":"".concat(r,".limit");return this.url.searchParams.set(s,"".concat(t)),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const i=typeof s>"u"?"offset":"".concat(s,".offset"),a=typeof s>"u"?"limit":"".concat(s,".limit");return this.url.searchParams.set(i,"".concat(t)),this.url.searchParams.set(a,"".concat(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.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
2explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:a="text"}={}){var o;const c=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept","application/vnd.pgrst.plan+".concat(a,'; for="').concat(l,'"; options=').concat(c,";")),a==="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=".concat(t)),this}};const jr=new RegExp("[,()]");var Fe=class extends hn{eq(t,e){return this.url.searchParams.append(t,"eq.".concat(e)),this}neq(t,e){return this.url.searchParams.append(t,"neq.".concat(e)),this}gt(t,e){return this.url.searchParams.append(t,"gt.".concat(e)),this}gte(t,e){return this.url.searchParams.append(t,"gte.".concat(e)),this}lt(t,e){return this.url.searchParams.append(t,"lt.".concat(e)),this}lte(t,e){return this.url.searchParams.append(t,"lte.".concat(e)),this}like(t,e){return this.url.searchParams.append(t,"like.".concat(e)),this}likeAllOf(t,e){return this.url.searchParams.append(t,"like(all).{".concat(e.join(","),"}")),this}likeAnyOf(t,e){return this.url.searchParams.append(t,"like(any).{".concat(e.join(","),"}")),this}ilike(t,e){return this.url.searchParams.append(t,"ilike.".concat(e)),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,"ilike(all).{".concat(e.join(","),"}")),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,"ilike(any).{".concat(e.join(","),"}")),this}regexMatch(t,e){return this.url.searchParams.append(t,"match.".concat(e)),this}regexIMatch(t,e){return this.url.searchParams.append(t,"imatch.".concat(e)),this}is(t,e){return this.url.searchParams.append(t,"is.".concat(e)),this}isDistinct(t,e){return this.url.searchParams.append(t,"isdistinct.".concat(e)),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&jr.test(s)?'"'.concat(s,'"'):"".concat(s)).join(",");return this.url.searchParams.append(t,"in.(".concat(r,")")),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&jr.test(s)?'"'.concat(s,'"'):"".concat(s)).join(",");return this.url.searchParams.append(t,"not.in.(".concat(r,")")),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,"cs.".concat(e)):Array.isArray(e)?this.url.searchParams.append(t,"cs.{".concat(e.join(","),"}")):this.url.searchParams.append(t,"cs.".concat(JSON.stringify(e))),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,"cd.".concat(e)):Array.isArray(e)?this.url.searchParams.append(t,"cd.{".concat(e.join(","),"}")):this.url.searchParams.append(t,"cd.".concat(JSON.stringify(e))),this}rangeGt(t,e){return this.url.searchParams.append(t,"sr.".concat(e)),this}rangeGte(t,e){return this.url.searchParams.append(t,"nxl.".concat(e)),this}rangeLt(t,e){return this.url.searchParams.append(t,"sl.".concat(e)),this}rangeLte(t,e){return this.url.searchParams.append(t,"nxr.".concat(e)),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,"adj.".concat(e)),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,"ov.".concat(e)):this.url.searchParams.append(t,"ov.{".concat(e.join(","),"}")),this}textSearch(t,e,{config:r,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");const a=r===void 0?"":"(".concat(r,")");return this.url.searchParams.append(t,"".concat(i,"fts").concat(a,".").concat(e)),this}match(t){return Object.entries(t).forEach(([e,r])=>{this.url.searchParams.append(e,"eq.".concat(r))}),this}not(t,e,r){return this.url.searchParams.append(t,"not.".concat(e,".").concat(r)),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?"".concat(r,".or"):"or";return this.url.searchParams.append(s,"(".concat(t,")")),this}filter(t,e,r){return this.url.searchParams.append(t,"".concat(e,".").concat(r)),this}},fn=class{constructor(t,{headers:e={},schema:r,fetch:s}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s}
2cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e!=null?e:{},i=r?"HEAD":"GET";let a=!1;const o=(t!=null?t:"*").split("").map(u=>/\s/.test(u)&&!a?"":(u==='"'&&(a=!a),u)).join(""),{url:c,headers:l}=this.cloneRequestState();return c.searchParams.set("select",o),s&&l.append("Prefer","count=".concat(s)),new Fe({method:i,url:c,headers:l,schema:this.schema,fetch:this.fetch})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const i="POST",{url:a,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer","count=".concat(e)),r||o.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){const l=[...new Set(c)].map(u=>'"'.concat(u,'"'));a.searchParams.set("columns",l.join(","))}}return new Fe({method:i,url:a,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var a;const o="POST",{url:c,headers:l}=this.cloneRequestState();if(l.append("Prefer","resolution=".concat(r?"ignore":"merge","-duplicates")),e!==void 0&&c.searchParams.set("on_conflict",e),s&&l.append("Prefer","count=".concat(s)),i||l.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,_)=>d.concat(Object.keys(_)),[]);if(u.length>0){const d=[...new Set(u)].map(_=>'"'.concat(_,'"'));c.searchParams.set("columns",d.join(","))}}return new Fe({method:o,url:c,headers:l,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}update(t,{count:e}={}){var r;const s="PATCH",{url:i,headers:a}=this.cloneRequestState();return e&&a.append("Prefer","count=".concat(e)),new Fe({method:s,url:i,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer","count=".concat(t)),new Fe({method:r,url:s,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch})}},mn=class us{constructor(e,{headers:r={},schema:s,fetch:i}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.fetch=i}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new fn(new URL("".concat(this.url,"/").concat(e)),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new us(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:s=!1,get:i=!1,count:a}={}){var o;let c;const l=new URL("".concat(this.url,"/rpc/").concat(e));let u;const d=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(d)),_=s&&Object.values(r).some(d);_?(c="POST",u=r):s||i?(c=s?"HEAD":"GET",Object.entries(r).filter(([f,w])=>w!==void 0).map(([f,w])=>[f,Array.isArray(w)?"{".concat(w.join(","),"}"):"".concat(w)]).forEach(([f,w])=>{l.searchParams.append(f,w)})):(c="POST",u=r);const g=new Headers(this.headers);return _?g.set("Prefer",a?"count=".concat(a,",return=minimal"):"return=minimal"):a&&g.set("Prefer","count=".concat(a)),new Fe({method:c,url:l,headers:g,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}};class pn{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.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"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.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 r=globalThis.process;if(r){const s=r.versions;if(s&&s.node){const i=s.node,a=parseInt(i.replace(/^v/,"").split(".")[0]);return a>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:"Node.js ".concat(a," detected but native WebSocket not found."),workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:"Node.js ".concat(a," detected without native WebSocket support."),workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}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 e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+="\n\nSuggested solution: ".concat(e.workaround)),new Error(r)}static createWebSocket(e,r){const s=this.getWebSocketConstructor();return new s(e,r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch(e){return!1}}}
2const gn="2.90.1",_n="realtime-js/".concat(gn),ds="1.0.0",wn="2.0.0",Ar=ds,Bt=1e4,vn=1e3,bn=100;var Ee;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(Ee||(Ee={}));var H;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(H||(H={}));var fe;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(fe||(fe={}));var Mt;(function(t){t.websocket="websocket"})(Mt||(Mt={}));var Pe;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Pe||(Pe={}));class yn{constructor(e){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=e!=null?e:[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const i=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,s;const i=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,s){var i,a;const o=e.topic,c=(i=e.ref)!==null&&i!==void 0?i:"",l=(a=e.join_ref)!==null&&a!==void 0?a:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},_=Object.keys(d).length===0?"":JSON.stringify(d);if(l.length>255)throw new Error("joinRef length ".concat(l.length," exceeds maximum of 255"));if(c.length>255)throw new Error("ref length ".concat(c.length," exceeds maximum of 255"));if(o.length>255)throw new Error("topic length ".concat(o.length," exceeds maximum of 255"));if(u.length>255)throw new Error("userEvent length ".concat(u.length," exceeds maximum of 255"));if(_.length>255)throw new Error("metadata length ".concat(_.length," exceeds maximum of 255"));const g=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+c.length+o.length+u.length+_.length,f=new ArrayBuffer(this.HEADER_LENGTH+g);let w=new DataView(f),v=0;w.setUint8(v++,this.KINDS.userBroadcastPush),w.setUint8(v++,l.length),w.setUint8(v++,c.length),w.setUint8(v++,o.length),w.setUint8(v++,u.length),w.setUint8(v++,_.length),w.setUint8(v++,r),Array.from(l,x=>w.setUint8(v++,x.charCodeAt(0))),Array.from(c,x=>w.setUint8(v++,x.charCodeAt(0))),Array.from(o,x=>w.setUint8(v++,x.charCodeAt(0))),Array.from(u,x=>w.setUint8(v++,x.charCodeAt(0))),Array.from(_,x=>w.setUint8(v++,x.charCodeAt(0)));var b=new Uint8Array(f.byteLength+s.byteLength);return b.set(new Uint8Array(f),0),b.set(new Uint8Array(s),f.byteLength),b.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[i,a,o,c,l]=s;return r({join_ref:i,ref:a,topic:o,event:c,payload:l})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),i=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,i)}}_decodeUserBroadcast(e,r,s){const i=r.getUint8(1),a=r.getUint8(2),o=r.getUint8(3),c=r.getUint8(4);let l=this.HEADER_LENGTH+4;const u=s.decode(e.slice(l,l+i));l=l+i;const d=s.decode(e.slice(l,l+a));l=l+a;const _=s.decode(e.slice(l,l+o));l=l+o;const g=e.slice(l,e.byteLength),f=c===this.JSON_ENCODING?JSON.parse(s.decode(g)):g,w={type:this.BROADCAST_EVENT,event:d,payload:f};return o>0&&(w.meta=JSON.parse(_)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:w}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0:e.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}class hs{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var V;(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.t
2srange="tsrange",t.tstzrange="tstzrange"})(V||(V={}));const Sr=(t,e,r={})=>{var s;const i=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((a,o)=>(a[o]=xn(o,t,e,i),a),{}):{}},xn=(t,e,r,s)=>{const i=e.find(c=>c.name===t),a=i==null?void 0:i.type,o=r[t];return a&&!s.includes(a)?fs(a,o):Ft(o)},fs=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return An(e,r)}switch(t){case V.bool:return En(e);case V.float4:case V.float8:case V.int2:case V.int4:case V.int8:case V.numeric:case V.oid:return kn(e);case V.json:case V.jsonb:return jn(e);case V.timestamp:return Sn(e);case V.abstime:case V.date:case V.daterange:case V.int4range:case V.int8range:case V.money:case V.reltime:case V.text:case V.time:case V.timestamptz:case V.timetz:case V.tsrange:case V.tstzrange:return Ft(e);default:return Ft(e)}},Ft=t=>t,En=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},kn=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},jn=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return t}return t},An=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let a;const o=t.slice(1,r);try{a=JSON.parse("["+o+"]")}catch(c){a=o?o.split(","):[]}return a.map(c=>fs(e,c))}return t},Sn=t=>typeof t=="string"?t.replace(" ","T"):t,ms=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};class At{constructor(e,r,s={},i=Bt){this.channel=e,this.event=r,this.payload=s,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var s;return this._hasReceived(e)&&r((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Tr;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Tr||(Tr={}));class et{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{const{onJoin:a,onLeave:o,onSync:c}=this.caller;this.joinRef=this.channel._joinRef(),this.state=et.syncState(this.state,i,a,o),this.pendingDiffs.forEach(l=>{this.state=et.syncDiff(this.state,l,a,o)}),this.pendingDiffs=[],c()}),this.channel._on(s.diff,{},i=>{const{onJoin:a,onLeave:o,onSync:c}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=et.syncDiff(this.state,i,a,o),c())}),this.onJoin((i,a,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:a,newPresences:o})}),this.onLeave((i,a,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:a,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,s,i){const a=this.cloneDeep(e),o=this.transformState(r),c={},l={};return this.map(a,(u,d)=>{o[u]||(l[u]=d)}),this.map(o,(u,d)=>{const _=a[u];if(_){const g=d.map(b=>b.presence_ref),f=_.map(b=>b.presence_ref),w=d.filter(b=>f.indexOf(b.presence_ref)<0),v=_.filter(b=>g.indexOf(b.presence_ref)<0);w.length>0&&(c[u]=w),v.length>0&&(l[u]=v)}else c[u]=d}),this.syncDiff(a,{joins:c,leaves:l},s,i)}static syncDiff(e,r,s,i){const{joins:a,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(a,(c,l)=>{var u;
2const d=(u=e[c])!==null&&u!==void 0?u:[];if(e[c]=this.cloneDeep(l),d.length>0){const _=e[c].map(f=>f.presence_ref),g=d.filter(f=>_.indexOf(f.presence_ref)<0);e[c].unshift(...g)}s(c,d,l)}),this.map(o,(c,l)=>{let u=e[c];if(!u)return;const d=l.map(_=>_.presence_ref);u=u.filter(_=>d.indexOf(_.presence_ref)<0),e[c]=u,i(c,u,l),u.length===0&&delete e[c]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const i=e[s];return"metas"in i?r[s]=i.metas.map(a=>(a.presence_ref=a.phx_ref,delete a.phx_ref,delete a.phx_ref_prev,a)):r[s]=i,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Pr;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Pr||(Pr={}));var tt;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(tt||(tt={}));var we;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(we||(we={}));class Ke{constructor(e,r={config:{}},s){var i,a;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.state=H.closed,this.joinedOnce=!1,this.pushBuffer=[],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.timeout=this.socket.timeout,this.joinPush=new At(this,fe.join,this.params,this.timeout),this.rejoinTimer=new hs(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=H.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel","close ".concat(this.topic," ").concat(this._joinRef())),this.state=H.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel","error ".concat(this.topic),o),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel","timeout ".concat(this.topic),this.joinPush.timeout),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel","error ".concat(this.topic),o),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this._on(fe.reply,{},(o,c)=>{this._trigger(this._replyEventName(c),o)}),this.presence=new et(this),this.broadcastEndpointURL=ms(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((a=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||a===void 0)&&a.replay))throw"tried to use replay on public channel '".concat(this.topic,"'. It must be a private channel.")}subscribe(e,r=this.timeout){var s,i,a;if(this.socket.isConnected()||this.socket.connect(),this.state==H.closed){const{config:{broadcast:o,presence:c,private:l}}=this.params,u=(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&i!==void 0?i:[],d=!!this.bindings[tt.PRESENCE]&&this.bindings[tt.PRESENCE].length>0||((a=this.params.config.presence)===null||a===void 0?void 0:a.enabled)===!0,_={},g={broadcast:o,presence:Object.assign(Object.assign({},c),{enabled:d}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(_.access_token=this.socket.accessTokenValue),this._onError(f=>e==null?void 0:e(we.CHANNEL_ERROR,f)),this._onClose(()=>e==null?void 0:e(we.CLOSED)),this.updateJoinPayload(Object.assign({config:g},_)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:f})=>{var w;if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e==null||e(we.SUBSCRIBED);return}else{const v=this.bindings.postgres_changes,b=(w=v==null?void 0:v.length)!==null&&w!==void 0?w:0,x=[];for(let E=0;E<b;E++){const k=v[E],{filter:{event:A,schema:q,table:R,filter:D}}=k,C=f&&f[E];if(C&&C.event===A&&Ke.isFilterValueEqual(C.schema,q)&&Ke.isFilterValueEqual(C.table,R)&&Ke.isFilterValueEqual(C.filter,D))x.push(Object.assign(Object.assign({},k),{id:C.id}));else{this.unsubscribe(),this.state=H.errored,e==null||e(we.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=x,e&&e(we.SUBSCRIBED);return}}).receive("error",f=>{this.state=H.errored,e==null||e(we.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(we.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){return this.state===H.joined&&e===tt.PRESENCE&&(this.socket.log("channel","resubscribe to ".concat(this.topic," due to change in presence callbacks on joined channel")),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,r,s)}async httpSend(e,r,s={}){var i;if(r==null)return Promise.reject("Payload is required for httpSend()");const a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization="Bearer ".concat(this.socket.accessTokenValue));const o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},c=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=s.timeout)!==null&&i!==void 0?i:this.timeout);if(c.status===202)return{success:!0};let l=c.statusText;
2try{const u=await c.json();l=u.error||u.message||l}catch(u){}return Promise.reject(new Error(l))}async send(e,r={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:a,payload:o}=e,c={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(c.Authorization="Bearer ".concat(this.socket.accessTokenValue));const l={method:"POST",headers:c,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=u.body)===null||i===void 0?void 0:i.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var o,c,l;const u=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(c=(o=this.params)===null||o===void 0?void 0:o.config)===null||c===void 0?void 0:c.broadcast)===null||l===void 0)&&l.ack)&&a("ok"),u.receive("ok",()=>a("ok")),u.receive("error",()=>a("error")),u.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=H.leaving;const r=()=>{this.socket.log("channel","leave ".concat(this.topic)),this._trigger(fe.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(i=>{s=new At(this,fe.leave,{},e),s.receive("ok",()=>{r(),i("ok")}).receive("timeout",()=>{r(),i("timed out")}).receive("error",()=>{i("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s==null||s.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=H.closed,this.bindings={}}async _fetchWithTimeout(e,r,s){const i=new AbortController,a=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(a),o}_push(e,r,s=this.timeout){if(!this.joinedOnce)throw"tried to push '".concat(e,"' to '").concat(this.topic,"' before joining. Use channel.subscribe() before pushing events");let i=new At(this,e,r,s);return this._canPush()?i.send():this._addToPushBuffer(i),i}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>bn){const r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel","discarded push due to buffer overflow: ".concat(r.event),r.payload))}}_onMessage(e,r,s){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,s){var i,a;const o=e.toLocaleLowerCase(),{close:c,error:l,leave:u,join:d}=fe;if(s&&[c,l,u,d].indexOf(o)>=0&&s!==this._joinRef())return;let g=this._onMessage(o,r,s);if(r&&!g)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(f=>{var w,v,b;return((w=f.filter)===null||w===void 0?void 0:w.event)==="*"||((b=(v=f.filter)===null||v===void 0?void 0:v.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(f=>f.callback(g,s)):(a=this.bindings[o])===null||a===void 0||a.filter(f=>{var w,v,b,x,E,k,A,q;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){const R=f.id,D=(w=f.filter)===null||w===void 0?void 0:w.event;return R&&((v=r.ids)===null||v===void 0?void 0:v.includes(R))&&(D==="*"||(D==null?void 0:D.toLocaleLowerCase())===((b=r.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))&&(!(!((x=f.filter)===null||x===void 0)&&x.table)||f.filter.table===((E=r.data)===null||E===void 0?void 0:E.table))}else{const R=(A=(k=f==null?void 0:f.filter)===null||k===void 0?void 0:k.event)===null||A===void 0?void 0:A.toLocaleLowerCase();return R==="*"||R===((q=r==null?void 0:r.event)===null||q===void 0?void 0:q.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof g=="object"&&"ids"in g){const w=g.data,{schema:v,table:b,commit_timestamp:x,type:E,errors:k}=w;g=Object.assign(Object.assign({},{schema:v,table:b,commit_timestamp:x,eventType:E,new:{},old:{},errors:k}),this._getPayloadRecords(w))}f.callback(g,s)})}_isClosed(){return this.state===H.closed}_isJoined(){return this.state===H.joined}_isJoining(){return this.state===H.joining}_isLeaving(){return this.state===H.leaving}_replyEventName(e){return"chan_reply_".concat(e)}_on(e,r,s){const i=e.toLocaleLowerCase(),a={type:i,filter:r,callback:s};return this.bindings[i]?this.bindings[i].push(a):this.bindings[i]=[a],this}_off(e,r){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(i=>{var a;return!(((a=i.type)===null||a===void 0?void 0:a.toLocaleLowerCase())===s&&Ke.isEqual(i.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(const s in e)if(e[s]!==r[s])return!1;return!0}static isFilterValueEqual(e,r){const s=e!=null?e:void 0,i=r!=null?r:void 0;return s===i}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(fe.close,{},e)}_onError(e){this._on(fe.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=H.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Sr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Sr(e.columns,e.old_record)),r}}const St=()=>{},lt={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Tn=[1e3,2e3,5e3,1e4],Pn=1e4,Rn='\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });';class On{constructor(e,r){var s;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Bt,this.transport=null,this.heartbeatIntervalMs=lt.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=St,this.ref=0,this.reconnectTimer=null,this.vsn=Ar,this.logger=St,this.conn=null,this.sendBuffer=[],this.serializer
2=new yn,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=i=>i?(...a)=>i(...a):(...a)=>fetch(...a),!(!((s=r==null?void 0:r.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint="".concat(e,"/").concat(Mt.websocket),this.httpEndpoint=ms(e),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=pn.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const r=e.message;throw r.includes("Node.js")?new Error("".concat(r,"\n\n")+'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })'):new Error("WebSocket not available: ".concat(r))}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,r!=null?r:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,s){this.logger(e,r,s)}connectionState(){switch(this.conn&&this.conn.readyState){case Ee.connecting:return Pe.Connecting;case Ee.open:return Pe.Open;case Ee.closing:return Pe.Closing;default:return Pe.Closed}}isConnected(){return this.connectionState()===Pe.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){const s="realtime:".concat(e),i=this.getChannels().find(a=>a.topic===s);if(i)return i;{const a=new Ke("realtime:".concat(e),r,this);return this.channels.push(a),a}}push(e){const{topic:r,event:s,payload:i,ref:a}=e,o=()=>{this.encode(e,c=>{var l;(l=this.conn)===null||l===void 0||l.send(c)})};this.log("push","".concat(r," ").concat(s," (").concat(a,")"),i),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(vn,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.sc
2heduleTimeout()},lt.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));r&&(this.log("transport",'leaving duplicate topic "'.concat(e,'"')),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply"&&r.ref&&r.ref===this.pendingHeartbeatRef){const u=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error",u)}catch(d){this.log("error","error in heartbeat callback",d)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:s,event:i,payload:a,ref:o}=r,c=o?"(".concat(o,")"):"",l=a.status||"";this.log("receive","".concat(l," ").concat(s," ").concat(i," ").concat(c).trim(),a),this.channels.filter(u=>u._isMember(s)).forEach(u=>u._trigger(i,a,o)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===Ee.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===Ee.open||this.conn.readyState===Ee.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport","connected to ".concat(this.endpointURL())),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker","starting worker for from ".concat(this.workerUrl)):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker()},this.workerRef.onmessage=r=>{r.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)}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.sc
2heduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport","".concat(e)),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(fe.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;const s=e.match(/\?/)?"&":"?",i=new URLSearchParams(r);return"".concat(e).concat(s).concat(i)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([Rn],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{const a={access_token:r,version:_n};r&&i.updateJoinPayload(a),i.joinedOnce&&i._isJoined()&&i._push(fe.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error","Error setting auth in ".concat(e),r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(r)}catch(i){this.log("error","error in ".concat(e," callback"),i)}})}catch(s){this.log("error","error triggering ".concat(e," callbacks"),s)}}_setupReconnectionTimer(){this.reconnectTimer=new hs(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},lt.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,s,i,a,o,c,l,u,d,_,g,f;switch(this.transport=(r=e==null?void 0:e.transport)!==null&&r!==void 0?r:null,this.timeout=(s=e==null?void 0:e.timeout)!==null&&s!==void 0?s:Bt,this.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:lt.HEARTBEAT_INTERVAL,this.worker=(a=e==null?void 0:e.worker)!==null&&a!==void 0?a:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(c=e==null?void 0:e.heartbeatCallback)!==null&&c!==void 0?c:St,this.vsn=(l=e==null?void 0:e.vsn)!==null&&l!==void 0?l:Ar,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=e==null?void 0:e.reconnectAfterMs)!==null&&u!==void 0?u:(w=>Tn[w-1]||Pn),this.vsn){case ds:this.encode=(d=e==null?void 0:e.encode)!==null&&d!==void 0?d:((w,v)=>v(JSON.stringify(w))),this.decode=(_=e==null?void 0:e.decode)!==null&&_!==void 0?_:((w,v)=>v(JSON.parse(w)));break;case wn:this.encode=(g=e==null?void 0:e.encode)!==null&&g!==void 0?g:this.serializer.encode.bind(this.serializer),this.decode=(f=e==null?void 0:e.decode)!==null&&f!==void 0?f:this.serializer.decode.bind(this.serializer);break;default:throw new Error("Unsupported serializer version: ".concat(this.vsn))}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}var rt=class extends Error{constructor(t,e){var r;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)&&((r=e.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function In(t,e,r){const s=new URL(e,t);if(r)for(const[i,a]of Object.entries(r))a!==void 0&&s.searchParams.set(i,a);return s.toString()}async function Cn(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:"Bearer ".concat(t.token)}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Dn(t){var r;const e=(r=t.fetchImpl)!=null?r:globalThis.fetch;return{async request({method:s,path:i,query:a,body:o,headers:c}){var w;const l=In(t.baseUrl,i,a),u=await Cn(t.auth),d=await e(l,{method:s,headers:{...o?{"Content-Type":"application/json"}:{},...u,...c},body:o?JSON.stringify(o):void 0}),_=await d.text(),g=(d.headers.get("content-type")||"").includes("application/json"),f=g&&_?JSON.parse(_):_;if(!d.ok){const v=g?f:void 0,b=v==null?void 0:v.error;throw new rt((w=b==null?void 0:b.message)!=null?w:"Request failed with status ".concat(d.status),{status:d.status,icebergType:b==null?void 0:b.type,icebergCode:b==null?void 0:b.code,details:v})}return{status:d.status,headers:d.headers,data:f}}}}function ut(t){return t.join("�")}var Ln=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:ut(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces"),query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces"),body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:"".concat(this.prefix,"/namespaces/").concat(ut(t.namespace))})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(ut(t.namespace))})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:"".concat(this.prefix,"/namespaces/").concat(ut(t.namespace))}),!0}catch(e){if(e instanceof rt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof rt&&r.status===409)return;throw r}}};function Ne(t){return t.join("�")}var Nn=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:"".concat(this.prefix,"/namespaces/").concat(Ne(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:"".concat(this.prefix,"/namespaces/").concat(Ne(t.namespace),"/tables"),body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces/").concat(Ne(t.namespace),"/tables/").concat(t.name),body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){var r;await this.client.request({method:"DELETE",path:"".concat(this.prefix,"/namespaces/").concat(Ne(t.namespace),"/tables/").concat(t.name),query:{purgeRequested:String((r=e==null?void 0:e.purge)!=null?r:!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(Ne(t.namespace),"/tables/").concat(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:"".concat(this.prefix,"/namespaces/").concat(Ne(t.namespace),"/tables/").concat(t.name),headers:e}),!0}catch(r){if(r instanceof rt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof rt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},$n=class{constructor(t){var s;let e="v1";t.catalogName&&(e+="/".concat(t.catalogName));const r=t.baseUrl.endsWith("/")?t.baseUrl:"".concat(t.baseUrl,"/");this.client=Dn({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new Ln(this.client,e),this.tableOps=new Nn(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)}
2async 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)}},vt=class extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}};function F(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Un=class extends vt{constructor(t,e,r){super(t),this.name="StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},zt=class extends vt{constructor(t,e){super(t),this.name="StorageUnknownError",this.originalError=e}};const nr=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Vn=()=>Response,Gt=t=>{if(Array.isArray(t))return t.map(r=>Gt(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const i=r.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[i]=Gt(s)}),e},qn=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)},Bn=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function st(t){"@babel/helpers - typeof";return st=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},st(t)}function Mn(t,e){if(st(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(st(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Fn(t){var e=Mn(t,"string");return st(e)=="symbol"?e:e+""}function zn(t,e,r){return(e=Fn(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Rr(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,s)}return r}function P(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Rr(Object(r),!0).forEach(function(s){zn(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Rr(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const Tt=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},Gn=async(t,e,r)=>{t instanceof await Vn()&&!(r!=null&&r.noResolveJson)?t.json().then(s=>{const i=t.status||500,a=(s==null?void 0:s.statusCode)||i+"";e(new Un(Tt(s),i,a))}).catch(s=>{e(new zt(Tt(s),s))}):e(new zt(Tt(t),t))},Kn=(t,e,r,s)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||!s?i:(qn(s)?(i.headers=P({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(s)):i.body=s,e!=null&&e.duplex&&(i.duplex=e.duplex),P(P({},i),r))};async function ct(t,e,r,s,i,a){return new Promise((o,c)=>{t(r,Kn(e,s,i,a)).then(l=>{if(!l.ok)throw l;return s!=null&&s.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Gn(l,c,s))})}async function nt(t,e,r,s){return ct(t,"GET",e,r,s)}async function he(t,e,r,s,i){return ct(t,"POST",e,s,i,r)}async function Kt(t,e,r,s,i){return ct(t,"PUT",e,s,i,r)}async function Wn(t,e,r,s){return ct(t,"HEAD",e,P(P({},r),{},{noResolveJson:!0}),s)}async function ir(t,e,r,s,i){return ct(t,"DELETE",e,s,i,r)}var Jn=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(F(e))return{data:null,error:e};throw e}}};let ps;ps=Symbol.toStringTag;var Hn=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[ps]="BlobDownloadBuilder",this.promise=null}asStream(){return new Jn(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(F(e))return{data:null,error:e};throw e}}};const Xn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Or={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Yn=class{constructor(t,e={},r,s){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.bucketId=r,this.fetch=nr(s)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(t,e,r,s){var i=this;try{let a;const o=P(P({},Or),s);let c=P(P({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",o.cacheControl),l&&a.append("metadata",i.encodeMetadata(l)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",o.cacheControl),l&&!a.has("metadata")&&a.append("metadata",i.encodeMetadata(l))):(a=r,c["cac
2he-control"]="max-age=".concat(o.cacheControl),c["content-type"]=o.contentType,l&&(c["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&typeof a=="object"&&"pipe"in a&&typeof a.pipe=="function")&&!o.duplex&&(o.duplex="half")),s!=null&&s.headers&&(c=P(P({},c),s.headers));const u=i._removeEmptyFolders(e),d=i._getFinalPath(u),_=await(t=="PUT"?Kt:he)(i.fetch,"".concat(i.url,"/object/").concat(d),a,P({headers:c},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{data:{path:u,id:_.Id,fullPath:_.Key},error:null}}catch(a){if(i.shouldThrowOnError)throw a;if(F(a))return{data:null,error:a};throw a}}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var i=this;const a=i._removeEmptyFolders(t),o=i._getFinalPath(a),c=new URL(i.url+"/object/upload/sign/".concat(o));c.searchParams.set("token",e);try{let l;const u=P({upsert:Or.upsert},s),d=P(P({},i.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,d["cache-control"]="max-age=".concat(u.cacheControl),d["content-type"]=u.contentType),{data:{path:a,fullPath:(await Kt(i.fetch,c.toString(),l,{headers:d})).Key},error:null}}catch(l){if(i.shouldThrowOnError)throw l;if(F(l))return{data:null,error:l};throw l}}async createSignedUploadUrl(t,e){var r=this;try{let s=r._getFinalPath(t);const i=P({},r.headers);e!=null&&e.upsert&&(i["x-upsert"]="true");const a=await he(r.fetch,"".concat(r.url,"/object/upload/sign/").concat(s),{},{headers:i}),o=new URL(r.url+a.url),c=o.searchParams.get("token");if(!c)throw new vt("No token returned by API");return{data:{signedUrl:o.toString(),path:t,token:c},error:null}}catch(s){if(r.shouldThrowOnError)throw s;if(F(s))return{data:null,error:s};throw s}}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;try{return{data:await he(s.fetch,"".concat(s.url,"/object/move"),{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers}),error:null}}catch(i){if(s.shouldThrowOnError)throw i;if(F(i))return{data:null,error:i};throw i}}async copy(t,e,r){var s=this;try{return{data:{path:(await he(s.fetch,"".concat(s.url,"/object/copy"),{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers})).Key},error:null}}catch(i){if(s.shouldThrowOnError)throw i;if(F(i))return{data:null,error:i};throw i}}async createSignedUrl(t,e,r){var s=this;try{let i=s._getFinalPath(t),a=await he(s.fetch,"".concat(s.url,"/object/sign/").concat(i),P({expiresIn:e},r!=null&&r.transform?{transform:r.transform}:{}),{headers:s.headers});const o=r!=null&&r.download?"&download=".concat(r.download===!0?"":r.download):"";return a={signedUrl:encodeURI("".concat(s.url).concat(a.signedURL).concat(o))},{data:a,error:null}}catch(i){if(s.shouldThrowOnError)throw i;if(F(i))return{data:null,error:i};throw i}}async createSignedUrls(t,e,r){var s=this;try{const i=await he(s.fetch,"".concat(s.url,"/object/sign/").concat(s.bucketId),{expiresIn:e,paths:t},{headers:s.headers}),a=r!=null&&r.download?"&download=".concat(r.download===!0?"":r.download):"";return{data:i.map(o=>P(P({},o),{},{signedUrl:o.signedURL?encodeURI("".concat(s.url).concat(o.signedURL).concat(a)):null})),error:null}}catch(i){if(s.shouldThrowOnError)throw i;if(F(i))return{data:null,error:i};throw i}}download(t,e){const r=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),i=s?"?".concat(s):"",a=this._getFinalPath(t),o=()=>nt(this.fetch,"".concat(this.url,"/").concat(r,"/").concat(a).concat(i),{headers:this.headers,noResolveJson:!0});return new Hn(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);try{return{data:Gt(await nt(e.fetch,"".concat(e.url,"/object/info/").concat(r),{headers:e.headers})),error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(F(s))return{data:null,error:s};throw s}}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await Wn(e.fetch,"".concat(e.url,"/object/").concat(r),{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(F(s)&&s instanceof zt){const i=s.originalError;if([400,404].includes(i==null?void 0:i.status))return{data:!1,error:s}}throw s}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=[],i=e!=null&&e.download?"download=".concat(e.download===!0?"":e.download):"";i!==""&&s.push(i);const a=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",o=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});o!==""&&s.push(o);let c=s.join("&");return c!==""&&(c="?".concat(c)),{data:{publicUrl:encodeURI("".concat(this.url,"/").concat(a,"/public/").concat(r).concat(c))}}}async remove(t){var e=this;try{return{data:await ir(e.fetch,"".concat(e.url,"/object/").concat(e.bucketId),{prefixes:t},{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw r}}async list(t,e,r){var s=this;try{const i=P(P(P({},Xn),e),{},{prefix:t||""});return{data:await he(s.fetch,"".concat(s.url,"/object/list/").concat(s.bucketId),i,{headers:s.headers},r),error:null}}catch(i){if(s.shouldThrowOnError)throw i;if(F(i))return{data:null,error:i};throw i}}async listV2(t,e){var r=this;try{const s=P({},t);return{data:await he(r.fetch,"".concat(r.url,"/object/list-v2/").concat(r.bucketId),s,{headers:r.headers},e),error:null}}catch(s){if(r.shouldThrowOnError)throw s;if(F(s))return{data:null,error:s};throw s}}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return"".concat(this.bucketId,"/").concat(t.replace(/^\/+/,""))}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push("width=".concat(t.width)),t.height&&e.push("height=".concat(t.height)),t.resize&&e.push("resize=".concat(t.resize)),t.format&&e.push("format=".concat(t.format)),t.quality&&e.push("quality=".concat(t.quality)),e.join("&")}};const gs="2.90.1",_s={"X-Client-Info":"storage-js/".concat(gs)};var Zn=class{constructor(t,e={},r,s){this.shouldThrowOnError=!1;const i=new URL(t);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),this.url=i.href.replace(/\/$/,""),this.headers=P(P({},_s),e),this.fetch=nr(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(t){var e=this;try{const r=e.listBucketOptionsToQueryString(t);return{data:await nt(e.fetch,"".concat(e.url,"/bucket").concat(r),{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw r}}async getBucket(t){var e=this;try{return{data:await nt(e.fetch,"".concat(e.url,"/bucket/").concat(t),{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw r}}async createBucket(t,e={public:!1}){var r=this;try{return{data:await he(r.fetch,"".concat(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}),error:null}}catch(s){if(r.shouldThrowOnError)throw s;if(F(s))return{data:null,error:s};throw s}}async updateBucket(t,e){var r=this;try{return{data:await Kt(r.fetch,"".concat(r.url,"/bucket/").concat(t),{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}),error:null}}catch(s){if(r.shouldThrowOnError)throw s;if(F(s))return{data:null,error:s};throw s}}async emptyBucket(t){var e=this;try{return{data:await he(e.fetch,"".concat(e.url,"/bucket/").concat(t,"/empty"),{},{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw r}}async deleteBucket(t){var e=this;try{return{data:await ir(e.fetch,"".concat(e.url,"/bucket/").concat(t),{},{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw 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():""}},Qn=class{constructor(t,e={},r){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=P(P({},_s),e),this.fetch=nr(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(t){var e=this;try{return{data:await he(e.fetch,"".concat(e.url,"/bucket"),{name:t},{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw r}}async listBuckets(t){var e=this;
2try{const r=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const s=r.toString(),i=s?"".concat(e.url,"/bucket?").concat(s):"".concat(e.url,"/bucket");return{data:await nt(e.fetch,i,{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw r}}async deleteBucket(t){var e=this;try{return{data:await ir(e.fetch,"".concat(e.url,"/bucket/").concat(t),{},{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(F(r))return{data:null,error:r};throw r}}from(t){var e=this;if(!Bn(t))throw new vt("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 $n({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(i,a){const o=i[a];return typeof o!="function"?o:async(...c)=>{try{return{data:await o.apply(i,c),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}};const ar={"X-Client-Info":"storage-js/".concat(gs),"Content-Type":"application/json"};var ws=class extends Error{constructor(t){super(t),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function ae(t){return typeof t=="object"&&t!==null&&"__isStorageVectorsError"in t}var Pt=class extends ws{constructor(t,e,r){super(t),this.name="StorageVectorsApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ei=class extends ws{constructor(t,e){super(t),this.name="StorageVectorsUnknownError",this.originalError=e}};const or=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),ti=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)},Ir=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),ri=async(t,e,r)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!(r!=null&&r.noResolveJson)){const s=t.status||500,i=t;if(typeof i.json=="function")i.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||s+"";e(new Pt(Ir(a),s,o))}).catch(()=>{const a=s+"";e(new Pt(i.statusText||"HTTP ".concat(s," error"),s,a))});else{const a=s+"";e(new Pt(i.statusText||"HTTP ".concat(s," error"),s,a))}}else e(new ei(Ir(t),t))},si=(t,e,r,s)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return s?(ti(s)?(i.headers=P({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(s)):i.body=s,P(P({},i),r)):i};async function ni(t,e,r,s,i,a){return new Promise((o,c)=>{t(r,si(e,s,i,a)).then(l=>{if(!l.ok)throw l;if(s!=null&&s.noResolveJson)return l;const u=l.headers.get("content-type");return!u||!u.includes("application/json")?{}:l.json()}).then(l=>o(l)).catch(l=>ri(l,c,s))})}async function oe(t,e,r,s,i){return ni(t,"POST",e,s,i,r)}var ii=class{constructor(t,e={},r){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=P(P({},ar),e),this.fetch=or(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(t){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/CreateIndex"),t,{headers:e.headers})||{},error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async getIndex(t,e){var r=this;try{return{data:await oe(r.fetch,"".concat(r.url,"/GetIndex"),{vectorBucketName:t,indexName:e},{headers:r.headers}),error:null}}catch(s){if(r.shouldThrowOnError)throw s;if(ae(s))return{data:null,error:s};throw s}}async listIndexes(t){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/ListIndexes"),t,{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async deleteIndex(t,e){var r=this;try{return{data:await oe(r.fetch,"".concat(r.url,"/DeleteIndex"),{vectorBucketName:t,indexName:e},{headers:r.headers})||{},error:null}}catch(s){if(r.shouldThrowOnError)throw s;if(ae(s))return{data:null,error:s};throw s}}},ai=class{constructor(t,e={},r){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=P(P({},ar),e),this.fetch=or(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(t){var e=this;try{if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await oe(e.fetch,"".concat(e.url,"/PutVectors"),t,{headers:e.headers})||{},error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async getVectors(t){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/GetVectors"),t,{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async listVectors(t){var e=this;try{if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");
2if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error("segmentIndex must be between 0 and ".concat(t.segmentCount-1))}return{data:await oe(e.fetch,"".concat(e.url,"/ListVectors"),t,{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async queryVectors(t){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/QueryVectors"),t,{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async deleteVectors(t){var e=this;try{if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await oe(e.fetch,"".concat(e.url,"/DeleteVectors"),t,{headers:e.headers})||{},error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}},oi=class{constructor(t,e={},r){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=P(P({},ar),e),this.fetch=or(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(t){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/CreateVectorBucket"),{vectorBucketName:t},{headers:e.headers})||{},error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async getBucket(t){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/GetVectorBucket"),{vectorBucketName:t},{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async listBuckets(t={}){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/ListVectorBuckets"),t,{headers:e.headers}),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}async deleteBucket(t){var e=this;try{return{data:await oe(e.fetch,"".concat(e.url,"/DeleteVectorBucket"),{vectorBucketName:t},{headers:e.headers})||{},error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ae(r))return{data:null,error:r};throw r}}},ci=class extends oi{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new li(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)}},li=class extends ii{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,P(P({},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 ui(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},ui=class extends ai{constructor(t,e,r,s,i){super(t,e,i),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},di=class extends Zn{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Yn(this.url,this.headers,t,this.fetch)}get vectors(){return new ci(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Qn(this.url+"/iceberg",this.headers,this.fetch)}};const vs="2.90.1",ze=30*1e3,Wt=3,Rt=Wt*ze,hi="http://localhost:9999",fi="supabase.auth.token",mi={"X-Client-Info":"gotrue-js/".concat(vs)},Jt="X-Supabase-Api-Version",bs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},pi=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,gi=600*1e3;
2class it extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function S(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class _i extends it{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function wi(t){return S(t)&&t.name==="AuthApiError"}class Re extends it{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class ve extends it{constructor(e,r,s,i){super(e,s,i),this.name=r,this.status=s}}class ie extends ve{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function vi(t){return S(t)&&t.name==="AuthSessionMissingError"}class $e extends ve{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class dt extends ve{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ht extends ve{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function bi(t){return S(t)&&t.name==="AuthImplicitGrantRedirectError"}class Cr extends ve{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class yi extends ve{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")}}class Ht extends ve{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Ot(t){return S(t)&&t.name==="AuthRetryableFetchError"}class Dr extends ve{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class Xt extends ve{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Lr=" \n\r=".split(""),xi=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Lr.length;e+=1)t[Lr[e].charCodeAt(0)]=-2;for(let e=0;e<ft.length;e+=1)t[ft[e].charCodeAt(0)]=e;return t})();function Nr(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(ft[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(ft[s]),e.queuedBits-=6}}function ys(t,e,r){const s=xi[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error('Invalid Base64-URL character "'.concat(String.fromCharCode(t),'"'))}}function $r(t){const e=[],r=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=o=>{ji(o,s,r)};for(let o=0;o<t.length;o+=1)ys(t.charCodeAt(o),i,a);return e.join("")}function Ei(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: ".concat(t.toString(16)))}function ki(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const i=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}Ei(s,e)}}function ji(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;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 We(t){const e=[],r={queue:0,queuedBits:0},s=i=>{e.push(i)};for(let i=0;i<t.length;i+=1)ys(t.charCodeAt(i),r,s);return new Uint8Array(e)}function Ai(t){const e=[];return ki(t,r=>e.push(r)),new Uint8Array(e)}function Ie(t){const e=[],r={queue:0,queuedBits:0},s=i=>{e.push(i)};return t.forEach(i=>
2Nr(i,r,s)),Nr(null,r,s),e.join("")}function Si(t){return Math.round(Date.now()/1e3)+t}function Ti(){return Symbol("auth-callback")}const Q=()=>typeof window<"u"&&typeof document<"u",Ae={tested:!1,writable:!1},xs=()=>{if(!Q())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch(e){return!1}if(Ae.tested)return Ae.writable;const t="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Ae.tested=!0,Ae.writable=!0}catch(e){Ae.tested=!0,Ae.writable=!1}return Ae.writable};function Pi(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,a)=>{e[a]=i})}catch(s){}return r.searchParams.forEach((s,i)=>{e[i]=s}),e}const Es=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ri=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Ge=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},Se=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch(s){return r}},Y=async(t,e)=>{await t.removeItem(e)};class bt{constructor(){this.promise=new bt.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}bt.promiseConstructor=Promise;function It(t){const e=t.split(".");if(e.length!==3)throw new Xt("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!pi.test(e[s]))throw new Xt("JWT not in base64url format");return{header:JSON.parse($r(e[0])),payload:JSON.parse($r(e[1])),signature:We(e[2]),raw:{header:e[0],payload:e[1]}}}async function Oi(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Ii(t,e){return new Promise((s,i)=>{(async()=>{for(let a=0;a<1/0;a++)try{const o=await t(a);if(!e(a,null,o)){s(o);return}}catch(o){if(!e(a,o)){i(o);return}}})()})}function Ci(t){return("0"+t.toString(16)).substr(-2)}function Di(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let i="";for(let a=0;a<56;a++)i+=r.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,Ci).join("")}async function Li(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(s);return Array.from(i).map(a=>String.fromCharCode(a)).join("")}async function Ni(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 r=await Li(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ue(t,e,r=!1){const s=Di();let i=s;r&&(i+="/PASSWORD_RECOVERY"),await Ge(t,"".concat(e,"-code-verifier"),i);const a=await Ni(s);return[a,s===a?"plain":"s256"]}const $i=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ui(t){const e=t.headers.get(Jt);if(!e||!e.match($i))return null;try{return new Date("".concat(e,"T00:00:00.0Z"))}catch(r){return null}}function Vi(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function qi(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")}}const Bi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Ve(t){if(!Bi.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ct(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="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 "'.concat(r,'" property of the session object is not supported. Please use getUser() instead.'))},set:(e,r)=>{throw new Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "'.concat(r,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))},deleteProperty:(e,r)=>{throw new Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "'.concat(r,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))}})}function Mi(t,e){return new Proxy(t,{get:(r,s,i)=>{if(s==="__isInsecureUserWarningProxy")return!0;
2if(typeof s=="symbol"){const a=s.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)"||a==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,i)}return!e.value&&typeof s=="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,s,i)}})}function Ur(t){return JSON.parse(JSON.stringify(t))}const Te=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Fi=[502,503,504];async function Vr(t){var e;if(!Ri(t))throw new Ht(Te(t),0);if(Fi.includes(t.status))throw new Ht(Te(t),t.status);let r;try{r=await t.json()}catch(a){throw new Re(Te(a),a)}let s;const i=Ui(t);if(i&&i.getTime()>=bs["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new Dr(Te(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new ie}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((a,o)=>a&&typeof o=="string",!0))throw new Dr(Te(r),t.status,r.weak_password.reasons);throw new _i(Te(r),t.status||500,s)}const zi=(t,e,r,s)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};async function T(t,e,r,s){var i;const a=Object.assign({},s==null?void 0:s.headers);a[Jt]||(a[Jt]=bs["2024-01-01"].name),s!=null&&s.jwt&&(a.Authorization="Bearer ".concat(s.jwt));const o=(i=s==null?void 0:s.query)!==null&&i!==void 0?i:{};s!=null&&s.redirectTo&&(o.redirect_to=s.redirectTo);const c=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Gi(t,e,r+c,{headers:a,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function Gi(t,e,r,s,i,a){const o=zi(e,s,i,a);let c;try{c=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new Ht(Te(l),0)}if(c.ok||await Vr(c),s!=null&&s.noResolveJson)return c;try{return await c.json()}catch(l){await Vr(l)}}function de(t){var e;let r=null;Ji(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Si(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function qr(t){const e=de(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,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function ke(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Ki(t){return{data:t,error:null}}function Wi(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:i,verification_type:a}=t,o=wt(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),c={action_link:e,email_otp:r,hashed_token:s,redirect_to:i,verification_type:a},l=Object.assign({},o);return{data:{properties:c,user:l},error:null}}function Br(t){return t}function Ji(t){return t.access_token&&t.refresh_token&&t.expires_in}const Dt=["global","local","others"];class Hi{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=Es(s),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)}}async signOut(e,r=Dt[0]){if(Dt.indexOf(r)<0)throw new Error("@supabase/auth-js: Parameter scope must be one of ".concat(Dt.join(", ")));try{return await T(this.fetch,"POST","".concat(this.url,"/logout?scope=").concat(r),{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(S(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await T(this.fetch,"POST","".concat(this.url,"/invite"),{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:ke})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=wt(e,["options"]),i=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(i.new_email=s==null?void 0:s.newEmail,delete i.newEmail),await T(this.fetch,"POST","".concat(this.url,"/admin/generate_link"),{body:i,headers:this.headers,xform:Wi,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(S(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await T(this.fetch,"POST","".concat(this.url,"/admin/users"),{body:e,headers:this.headers,xform:ke})}catch(r){if(S(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,i,a,o,c,l;try{const u={nextPage:null,lastPage:0,total:0},d=await T(this.fetch,"GET","".concat(this.url,"/admin/users"),{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(a=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""},xform:Br});if(d.error)throw d.error;const _=await d.json(),g=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(c=d.headers.get("link"))===null||c===void 0?void 0:c.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(w=>{const v=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(w.split(";")[1].split("=")[1]);u["".concat(b,"Page")]=v}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},_),u),error:null}}catch(u){if(S(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Ve(e);try{return await T(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,xform:ke})}catch(r){if(S(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Ve(e);try{return await T(this.fetch,"PUT","".concat(this.url,"/admin/users/").concat(e),{body:r,headers:this.headers,xform:ke})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Ve(e);
2try{return await T(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,body:{should_soft_delete:r},xform:ke})}catch(s){if(S(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Ve(e.userId);try{const{data:r,error:s}=await T(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e.userId,"/factors"),{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:s}}catch(r){if(S(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Ve(e.userId),Ve(e.id);try{return{data:await T(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e.userId,"/factors/").concat(e.id),{headers:this.headers}),error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,i,a,o,c,l;try{const u={nextPage:null,lastPage:0,total:0},d=await T(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients"),{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(a=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""},xform:Br});if(d.error)throw d.error;const _=await d.json(),g=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(c=d.headers.get("link"))===null||c===void 0?void 0:c.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(w=>{const v=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(w.split(";")[1].split("=")[1]);u["".concat(b,"Page")]=v}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},_),u),error:null}}catch(u){if(S(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await T(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients"),{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(S(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await T(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(S(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await T(this.fetch,"PUT","".concat(this.url,"/admin/oauth/clients/").concat(e),{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(S(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await T(this.fetch,"DELETE","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(S(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await T(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients/").concat(e,"/regenerate_secret"),{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(S(r))return{data:null,error:r};throw r}}}function Mr(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const qe={debug:!!(globalThis&&xs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ks extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Xi extends ks{}async function Yi(t,e,r){qe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),qe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){qe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{qe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw qe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Xi('Acquiring an exclusive Navigator LockManager lock "'.concat(t,'" immediately failed'));if(qe.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}function Zi(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(t){typeof self<"u"&&(self.globalThis=self)}}function js(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error('@supabase/auth-js: Address "'.concat(t,'" is invali
2d.'));return t.toLowerCase()}function Qi(t){return parseInt(t,16)}function ea(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function ta(t){var e;const{chainId:r,domain:s,expirationTime:i,issuedAt:a=new Date,nonce:o,notBefore:c,requestId:l,resources:u,scheme:d,uri:_,version:g}=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: '.concat(r));if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error('@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: '.concat(o));if(!_)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error("@supabase/auth-js: Invalid SIWE message field \"version\". Version must be '1'. Provided value: ".concat(g));if(!((e=t.statement)===null||e===void 0)&&e.includes("\n"))throw new Error("@supabase/auth-js: Invalid SIWE message field \"statement\". Statement must not include '\\n'. Provided value: ".concat(t.statement))}const f=js(t.address),w=d?"".concat(d,"://").concat(s):s,v=t.statement?"".concat(t.statement,"\n"):"",b="".concat(w," wants you to sign in with your Ethereum account:\n").concat(f,"\n\n").concat(v);let x="URI: ".concat(_,"\nVersion: ").concat(g,"\nChain ID: ").concat(r).concat(o?"\nNonce: ".concat(o):"","\nIssued At: ").concat(a.toISOString());if(i&&(x+="\nExpiration Time: ".concat(i.toISOString())),c&&(x+="\nNot Before: ".concat(c.toISOString())),l&&(x+="\nRequest ID: ".concat(l)),u){let E="\nResources:";for(const k of u){if(!k||typeof k!="string")throw new Error('@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: '.concat(k));E+="\n- ".concat(k)}x+=E}return"".concat(b,"\n").concat(x)}class J extends Error{constructor({message:e,code:r,cause:s,name:i}){var a;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(a=i!=null?i:s instanceof Error?s.name:void 0)!==null&&a!==void 0?a:"Unknown Error",this.code=r}}class mt extends J{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function ra({error:t,options:e}){var r,s,i;const{publicKey:a}=e;if(!a)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=a.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"&&((s=a.authenticatorSelection)===null||s===void 0?void 0:s.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(((i=a.authenticatorSelection)===null||i===void 0?void 0:i.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 a.pubKeyCredParams.filter(c=>c.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 o=window.location.hostname;
2if(As(o)){if(a.rp.id!==o)return new J({message:'The RP ID "'.concat(a.rp.id,'" is invalid for this domain'),code:"ERROR_INVALID_RP_ID",cause:t})}else return new J({message:"".concat(window.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(a.user.id.byteLength<1||a.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 sa({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 s=window.location.hostname;if(As(s)){if(r.rpId!==s)return new J({message:'The RP ID "'.concat(r.rpId,'" is invalid for this domain'),code:"ERROR_INVALID_RP_ID",cause:t})}else return new J({message:"".concat(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})}class na{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ia=new na;function aa(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:s}=t,i=wt(t,["challenge","user","excludeCredentials"]),a=We(e).buffer,o=Object.assign(Object.assign({},r),{id:We(r.id).buffer}),c=Object.assign(Object.assign({},i),{challenge:a,user:o});if(s&&s.length>0){c.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const u=s[l];c.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:We(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return c}function oa(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,s=wt(t,["challenge","allowCredentials"]),i=We(e).buffer,a=Object.assign(Object.assign({},s),{challenge:i});if(r&&r.length>0){a.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){const c=r[o];a.allowCredentials[o]=Object.assign(Object.assign({},c),{id:We(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function ca(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:Ie(new Uint8Array(t.response.attestationObject)),clientDataJSON:Ie(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function la(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Ie(new Uint8Array(i.authenticatorData)),clientDataJSON:Ie(new Uint8Array(i.clientDataJSON)),signature:Ie(new Uint8Array(i.signature)),userHandle:i.userHandle?Ie(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function As(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Fr(){var t,e;return!!(Q()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function ua(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new mt("Browser returned unexpected credential type",e)}:{data:null,error:new mt("Empty credential response",e)}}catch(e){return{data:null,error:ra({error:e,options:t})}}}async function da(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new mt("Browser returned unexpected credential type",e)}:{data:null,error:new mt("Empty credential response",e)}}catch(e){return{data:null,error:sa({error:e,options:t})}}}const ha={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},fa={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function pt(...t){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),s={};for(const i of t)if(i)for(const a in i){const o=i[a];if(o!==void 0)if(Array.isArray(o))s[a]=o;else if(r(o))s[a]=o;else if(e(o)){const c=s[a];e(c)?s[a]=pt(c,o):s[a]=pt(o)}else s[a]=o}return s}function ma(t,e){return pt(ha,t,e||{})}function pa(t,e){return pt(fa,t,e||{})}class ga{constructor(e){this.client=e,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(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:i},a){try{const{data:o,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:c};const l=i!=null?i:ia.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:u}=o.webauthn.credential_options.publicKey;u.name||(u.name="".concat(u.id,":").concat(s)),u.displayName||(u.displayName=u.name)}
2switch(o.webauthn.type){case"create":{const u=ma(o.webauthn.credential_options.publicKey,a==null?void 0:a.create),{data:d,error:_}=await ua({publicKey:u,signal:l});return d?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:d}},error:null}:{data:null,error:_}}case"request":{const u=pa(o.webauthn.credential_options.publicKey,a==null?void 0:a.request),{data:d,error:_}=await da(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:u,signal:l}));return d?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:d}},error:null}:{data:null,error:_}}}}catch(o){return S(o)?{data:null,error:o}:{data:null,error:new Re("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new it("rpId is required for WebAuthn authentication")};try{if(!Fr())return{data:null,error:new Re("Browser does not support WebAuthn",null)};const{data:o,error:c}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:i},{request:a});if(!o)return{data:null,error:c};const{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(o){return S(o)?{data:null,error:o}:{data:null,error:new Re("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new it("rpId is required for WebAuthn registration")};try{if(!Fr())return{data:null,error:new Re("Browser does not support WebAuthn",null)};const{data:o,error:c}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(d=>{var _;return(_=d.data)===null||_===void 0?void 0:_.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:c};const{data:l,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:i},{create:a});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(o){return S(o)?{data:null,error:o}:{data:null,error:new Re("Unexpected error in register",o)}}}}Zi();const _a={url:hi,storageKey:fi,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:mi,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function zr(t,e,r){return await r()}const Be={};class at{get jwks(){var e,r;return(r=(e=Be[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Be[this.storageKey]=Object.assign(Object.assign({},Be[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Be[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Be[this.storageKey]=Object.assign(Object.assign({},Be[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,i;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const a=Object.assign(Object.assign({},_a),e);if(this.storageKey=a.storageKey,this.instanceID=(r=at.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,at.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.instanceID>0&&Q()){const o="".concat(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(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.admin=new Hi({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=Es(a.fetch),this.lock=a.lock||zr,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&Q()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Yi:this.lock=zr,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 ga(this)}
2,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.persistSession?(a.storage?this.storage=a.storage:xs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Mr(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=Mr(this.memoryStorage)),Q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),await this._notifyAllSubscribers(o.data.event,o.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return"GoTrueClient@"+"".concat(this.storageKey,":").concat(this.instanceID," (").concat(vs,") ").concat(new Date().toISOString())}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(Q()&&(r=Pi(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),Q()&&this.detectSessionInUrl&&s!=="none"){const{data:i,error:a}=await this._getSessionFromURL(r,s);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),bi(a)){const l=(e=a.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:a}}return{error:a}}const{session:o,redirectType:c}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",c),await this._saveSession(o),setTimeout(async()=>{c==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return S(r)?this._returnResult({error:r}):this._returnResult({error:new Re("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,i;try{const a=await T(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{data:(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:de}),{data:o,error:c}=a;if(c||!o)return this._returnResult({data:{user:null,session:null},error:c});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(a){if(S(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var r,s,i;try{let a;if("email"in e){const{email:d,password:_,options:g}=e;let f=null,w=null;this.flowType==="pkce"&&([f,w]=await Ue(this.storage,this.storageKey)),a=await T(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:d,password:_,data:(r=g==null?void 0:g.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:f,code_challenge_method:w},xform:de})}else if("phone"in e){const{phone:d,password:_,options:g}=e;a=await T(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{phone:d,password:_,data:(s=g==null?void 0:g.data)!==null&&s!==void 0?s:{},channel:(i=g==null?void 0:g.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:de})}else throw new dt("You must provide either an email or phone number and a password");const{data:o,error:c}=a;if(c||!o)return await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),this._returnResult({data:{user:null,session:null},error:c});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(a){if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),S(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:a,password:o,options:c}=e;r=await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=password"),{headers:this.headers,body:{email:a,password:o,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:qr})}else if("phone"in e){const{phone:a,password:o,options:c}=e;r=await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=password"),{headers:this.headers,body:{phone:a,password:o,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:qr})}else throw new dt("You must provide either an email or phone number and a password");const{data:s,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!s||!s.session||!s.user){const a=new $e;return this._returnResult({data:{user:null,session:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(r){if(S(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,i,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}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 "'.concat(r,'"'))}}async signInWithEthereum(e){var r,s,i,a,o,c,l,u,d,_,g;let f,w;if("message"in e)f=e.message,w=e.signature;else{const{chain:v,wallet:b,statement:x,options:E}=e;let k;if(Q())if(typeof b=="object")k=b;else{const G=window;if("ethereum"in G&&typeof G.ethereum=="object"&&"request"in G.ethereum&&typeof G.ethereum.request=="function")k=G.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 b!="object"||!(E!=null&&E.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=b}const A=new URL((r=E==null?void 0:E.url)!==null&&r!==void 0?r:window.location.href),q=await k.request({method:"eth_requestAccounts"}).then(G=>G).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!q||q.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const R=js(q[0]);let D=(s=E==null?void 0:E.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!D){const G=await k.request({method:"eth_chainId"});D=Qi(G)}const C={domain:A.host,address:R,statement:x,uri:A.href,version:"1",chainId:D,nonce:(i=E==null?void 0:E.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(a=E==null?void 0:E.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(c=E==null?void 0:E.signInWithEthereum)===null||c===void 0?void 0:c.expirationTime,notBefore:(l=E==null?void 0:E.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=E==null?void 0:E.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=E==null?void 0:E.signInWithEthereum)===null||d===void 0?void 0:d.resources};f=ta(C),w=await k.request({method:"personal_sign",params:[ea(f),R]})}try{const{data:v,error:b}=await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:w},!((_=e.options)===null||_===void 0)&&_.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:de});if(b)throw b;if(!v||!v.session||!v.user){const x=new $e;return this._returnResult({data:{user:null,session:null},error:x})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:b})}catch(v){if(S(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,s,i,a,o,c,l,u,d,_,g,f;let w,v;if("message"in e)w=e.message,v=e.signature;else{const{chain:b,wallet:x,statement:E,options:k}=e;let A;if(Q())if(typeof x=="object")A=x;else{const R=window;if("solana"in R&&typeof R.solana=="object"&&("signIn"in R.solana&&typeof R.solana.signIn=="function"||"signMessage"in R.solana&&typeof R.solana.signMessage=="function"))A=R.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 x!="object"||!(k!=null&&k.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");A=x}const q=new URL((r=k==null?void 0:k.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in A&&A.signIn){const R=await A.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},k==null?void 0:k.signInWithSolana),{version:"1",domain:q.host,uri:q.href}),E?{statement:E}:null));let D;if(Array.isArray(R)&&R[0]&&typeof R[0]=="object")D=R[0];else if(R&&typeof R=="object"&&"signedMessage"in R&&"signature"in R)D=R;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in D&&"signature"in D&&(typeof D.signedMessage=="string"||D.signedMessage instanceof Uint8Array)&&D.signature instanceof Uint8Array)w=typeof D.signedMessage=="string"?D.signedMessage:new TextDecoder().decode(D.signedMessage),v=D.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in A)||typeof A.signMessage!="function"||!("publicKey"in A)||typeof A!="object"||!A.publicKey||!("toBase58"in A.publicKey)||typeof A.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");w=["".concat(q.host," wants you to sign in with your Solana account:"),A.publicKey.toBase58(),...E?["",E,""]:[""],"Version: 1","URI: ".concat(q.href),"Issued At: ".concat((i=(s=k==null?void 0:k.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()),...!((a=k==null?void 0:k.signInWithSolana)===null||a===void 0)&&a.notBefore?["Not Before: ".concat(k.signInWithSolana.notBefore)]:[],...!((o=k==null?void 0:k.signInWithSolana)===null||o===void 0)&&o.expirationTime?["Expiration Time: ".concat(k.signInWithSolana.expirationTime)]:[],...!((c=k==null?void 0:k.signInWithSolana)===null||c===void 0)&&c.chainId?["Chain ID: ".concat(k.signInWithSolana.chainId)]:[],...!((l=k==null?void 0:k.signInWithSolana)===null||l===void 0)&&l.nonce?["Nonce: ".concat(k.signInWithSolana.nonce)]:[],...!((u=k==null?void 0:k.signInWithSolana)===null||u===void 0)&&u.requestId?["Request ID: ".concat(k.signInWithSolana.requestId)]:[],...!((_=(d=k==null?void 0:k.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||_===void 0)&&_.length?["Resources",...k.signInWithSolana.resources.map(D=>"- ".concat(D))]:[]].join("\n");const R=await A.signMessage(new TextEncoder().encode(w),"utf8");if(!R||!(R instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=R}}try{const{data:b,error:x}=await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"solana",message:w,signature:Ie(v)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:de});if(x)throw x;if(!b||!b.session||!b.user){const E=new $e;return this._returnResult({data:{user:null,session:null},error:E})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:x})}catch(b){if(S(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){const r=await Se(this.storage,"".concat(this.storageKey,"-code-verifier")),[s,i]=(r!=null?r:"").split("/");try{if(!s&&this.flowType==="pkce")throw new yi;const{data:a,error:o}=await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=pkce"),{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:de});if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),o)throw o;if(!a||!a.session||!a.user){const c=new $e;return this._returnResult({data:{user:null,session:null,redirectType:null},error:c})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:i!=null?i:null}),error:o})}catch(a){if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),S(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:r,provider:s,token:i,access_token:a,nonce:o}=e,c=await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=id_token"),{headers:this.headers,body:{provider:s,id_token:i,access_token:a,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:de}),{data:l,error:u}=c;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const d=new $e;return this._returnResult({data:{user:null,session:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(S(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,i,a,o;try{if("email"in e){const{email:c,options:l}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Ue(this.storage,this.storageKey));const{error:_}=await T(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{email:c,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:_})}if("phone"in e){const{phone:c,options:l}=e,{data:u,error:d}=await T(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{phone:c,data:(i=l==null?void 0:l.data)!==null&&i!==void 0?i:{},c
2reate_user:(a=l==null?void 0:l.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new dt("You must provide either an email or phone number.")}catch(c){if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),S(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var r,s;try{let i,a;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:c}=await T(this.fetch,"POST","".concat(this.url,"/verify"),{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:de});if(c)throw c;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,u=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(S(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,s,i,a,o;try{let c=null,l=null;this.flowType==="pkce"&&([c,l]=await Ue(this.storage,this.storageKey));const u=await T(this.fetch,"POST","".concat(this.url,"/sso"),{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:c,code_challenge_method:l}),headers:this.headers,xform:Ki});return!((a=u.data)===null||a===void 0)&&a.url&&Q()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(c){if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),S(c))return this._returnResult({data:null,error:c});throw c}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new ie;const{error:i}=await T(this.fetch,"GET","".concat(this.url,"/reauthenticate"),{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(S(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r="".concat(this.url,"/resend");if("email"in e){const{email:s,type:i,options:a}=e,{error:o}=await T(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:s,type:i,options:a}=e,{data:o,error:c}=await T(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:c})}throw new dt("You must provide either an email or phone number and a type")}catch(r){if(S(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch(a){}})()),i}return await this.lock("lock:".concat(this.storageKey),e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch(i){}})()),await s;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Se(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 val
2id"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Rt:!1;if(this._debug("#__loadSession()","session has".concat(s?"":" not"," expired"),"expires_at",e.expires_at),!s){if(this.userStorage){const o=await Se(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ct()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=Mi(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await T(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:e,xform:ke}):await this._useSession(async r=>{var s,i,a;const{data:o,error:c}=r;if(c)throw c;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ie}:await T(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:(a=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:ke})})}catch(r){if(S(r))return vi(r)&&(await this._removeSession(),await Y(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:i,error:a}=s;
2if(a)throw a;if(!i.session)throw new ie;const o=i.session;let c=null,l=null;this.flowType==="pkce"&&e.email!=null&&([c,l]=await Ue(this.storage,this.storageKey));const{data:u,error:d}=await T(this.fetch,"PUT","".concat(this.url,"/user"),{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:l}),jwt:o.access_token,xform:ke});if(d)throw d;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),S(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ie;const r=Date.now()/1e3;let s=r,i=!0,a=null;const{payload:o}=It(e.access_token);if(o.exp&&(s=o.exp,i=s<=r),i){const{data:c,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c)return{data:{user:null,session:null},error:null};a=c}else{const{data:c,error:l}=await this._getUser(e.access_token);if(l)throw l;a={access_token:e.access_token,refresh_token:e.refresh_token,user:c.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(r){if(S(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:o,error:c}=r;if(c)throw c;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new ie;const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(S(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!Q())throw new ht("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ht(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 Cr("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ht("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Cr("No code detected.");const{data:E,error:k}=await this._exchangeCodeForSession(e.code);if(k)throw k;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:E.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:a,refresh_token:o,expires_in:c,expires_at:l,token_type:u}=e;if(!a||!c||!o||!u)throw new ht("No session defined in URL");const d=Math.round(Date.now()/1e3),_=parseInt(c);let g=d+_;l&&(g=parseInt(l));const f=g-d;f*1e3<=ze&&console.warn("@supabase/gotrue-js: Session as retrieved from URL expires in ".concat(f,"s, should have been closer to ").concat(_,"s"));const w=g-_;d-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,g,d):d-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",w,g,d);const{data:v,error:b}=await this._getUser(a);if(b)throw b;const x={provider_token:s,provider_refresh_token:i,access_token:a,expires_in:_,expires_at:g,refresh_token:o,token_type:u,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:x,redirectType:e.type},error:null})}catch(s){if(S(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_description)}async _isPKCECallback(e){const r=await Se(this.storage,"".concat(this.storageKey,"-code-verifier"));return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:i,error:a}=r;if(a)return this._returnResult({error:a});const o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:c}=await this.admin.signOut(o,e);
2if(c&&!(wi(c)&&(c.status===404||c.status===401||c.status===403)))return this._returnResult({error:c})}return e!=="others"&&(await this._removeSession(),await Y(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({error:null})})}onAuthStateChange(e){const r=Ti(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,i;try{const{data:{session:a},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),console.error(a)}})}async resetPasswordForEmail(e,r={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await Ue(this.storage,this.storageKey,!0));try{return await T(this.fetch,"POST","".concat(this.url,"/recover"),{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(a){if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),S(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(S(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;try{const{data:s,error:i}=await this._useSession(async a=>{var o,c,l,u,d;const{data:_,error:g}=a;if(g)throw g;const f=await this._getUrlForProvider("".concat(this.url,"/user/identities/authorize"),e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",f,{headers:this.headers,jwt:(d=(u=_.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(i)throw i;return Q()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(S(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:i,data:{session:a}}=r;if(i)throw i;const{options:o,provider:c,token:l,access_token:u,nonce:d}=e,_=await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=id_token"),{headers:this.headers,jwt:(s=a==null?void 0:a.access_token)!==null&&s!==void 0?s:void 0,body:{provider:c,id_token:l,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:de}),{data:g,error:f}=_;return f?this._returnResult({data:{user:null,session:null},error:f}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new $e}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:f}))}catch(i){if(await Y(this.storage,"".concat(this.storageKey,"-code-verifier")),S(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,i;const{data:a,error:o}=r;if(o)throw o;return await T(this.fetch,"DELETE","".concat(this.url,"/user/identities/").concat(e.identity_id),{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(S(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r="#_refreshAccessToken(".concat(e.substring(0,5),"...)");this._debug(r,"begin");try{const s=Date.now();return await Ii(async i=>(i>0&&await Oi(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await T(this.fetch,"POST","".concat(this.url,"/token?grant_type=refresh_token"),{body:{refresh_token:e},headers:this.headers,xform:de})),(i,a)=>{const o=200*Math.pow(2,i);return a&&Ot(a)&&Date.now()+o-s<ze})}catch(s){if(this._debug(r,"error",s),S(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}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 s=await this._getUrlForProvider("".concat(this.url,"/authorize"),e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),Q()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const i=await Se(this.storage,this.storageKey);if(i&&this.userStorage){let o=await Se(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await Ge(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ct()}else if(i&&!i.user&&!i.user){const o=await Se(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(i.user=o.user,await Y(this.storage,this.storageKey+"-user"),await Ge(this.storage,this.storageKey,i)):i.user=Ct()}
2if(this._debug(s,"session from storage",i),!this._isValidSession(i)){this._debug(s,"session is not valid"),i!==null&&await this._removeSession();return}const a=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Rt;if(this._debug(s,"session has".concat(a?"":" not"," expired with margin of ").concat(Rt,"s")),a){if(this.autoRefreshToken&&i.refresh_token){const{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Ot(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:c}=await this._getUser(i.access_token);!c&&(o!=null&&o.user)?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(s,"error",i),console.error(i);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new ie;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i="#_callRefreshToken(".concat(e.substring(0,5),"...)");this._debug(i,"begin");try{this.refreshingDeferred=new bt;const{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new ie;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const c={data:a.session,error:null};return this.refreshingDeferred.resolve(c),c}catch(a){if(this._debug(i,"error",a),S(a)){const o={data:null,error:a};return Ot(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(a),a}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,s=!0){const i="#_notifyAllSubscribers(".concat(e,")");this._debug(i,"begin",r,"broadcast = ".concat(s));try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const a=[],o=Array.from(this.stateChangeEmitters.values()).map(async c=>{try{await c.callback(e,r)}catch(l){a.push(l)}});if(await Promise.all(o),a.length>0){for(let c=0;c<a.length;c+=1)console.error(a[c]);throw a[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Y(this.storage,"".concat(this.storageKey,"-code-verifier"));const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Ge(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const a=Ur(i);await Ge(this.storage,this.storageKey,a)}else{const i=Ur(r);await Ge(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Y(this.storage,this.storageKey),await Y(this.storage,this.storageKey+"-code-verifier"),await Y(this.storage,this.storageKey+"-user"),this.userStorage&&await Y(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Q()&&(window!=null&&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(),ze);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 _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((s.expires_at*1e3-e)/ze);this._debug("#_autoRefreshTokenTick()","access token expires in ".concat(i," ticks, a tick lasts ").concat(ze,"ms, refresh threshold is ").concat(Wt," ticks")),i<=Wt&&await this._callRefreshToken(s.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.isAcquireTimeout||e instanceof ks)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Q()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r="#_onVisibilityChanged(".concat(e,")");this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(
2await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{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()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const i=["provider=".concat(encodeURIComponent(r))];if(s!=null&&s.redirectTo&&i.push("redirect_to=".concat(encodeURIComponent(s.redirectTo))),s!=null&&s.scopes&&i.push("scopes=".concat(encodeURIComponent(s.scopes))),this.flowType==="pkce"){const[a,o]=await Ue(this.storage,this.storageKey),c=new URLSearchParams({code_challenge:"".concat(encodeURIComponent(a)),code_challenge_method:"".concat(encodeURIComponent(o))});i.push(c.toString())}if(s!=null&&s.queryParams){const a=new URLSearchParams(s.queryParams);i.push(a.toString())}return s!=null&&s.skipBrowserRedirect&&i.push("skip_http_redirect=".concat(s.skipBrowserRedirect)),"".concat(e,"?").concat(i.join("&"))}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:i,error:a}=r;return a?this._returnResult({data:null,error:a}):await T(this.fetch,"DELETE","".concat(this.url,"/factors/").concat(e.factorId),{headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(S(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,i;const{data:a,error:o}=r;if(o)return this._returnResult({data:null,error:o});const c=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:u}=await T(this.fetch,"POST","".concat(this.url,"/factors"),{body:c,headers:this.headers,jwt:(s=a==null?void 0:a.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code="data:image/svg+xml;utf-8,".concat(l.totp.qr_code)),this._returnResult({data:l,error:null}))})}catch(r){if(S(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:i,error:a}=r;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"?ca(e.webauthn.credential_response):la(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:l}=await T(this.fetch,"POST","".concat(this.url,"/factors/").concat(e.factorId,"/verify"),{body:o,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:l}))})}catch(r){if(S(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=await T(this.fetch,"POST","".concat(this.url,"/factors/").concat(e.factorId,"/challenge"),{body:e,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});if(o.error)return o;const{data:c}=o;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:aa(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:oa(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(S(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const i={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])i.all.push(a),a.status==="verified"&&i[a.factor_type].push(a);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(){var e,r;const{data:{session:s},error:i}
2=await this.getSession();if(i)return this._returnResult({data:null,error:i});if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:a}=It(s.access_token);let o=null;a.aal&&(o=a.aal);let c=o;((r=(e=s.user.factors)===null||e===void 0?void 0:e.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");const u=a.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:u},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;return i?this._returnResult({data:null,error:i}):s?await T(this.fetch,"GET","".concat(this.url,"/oauth/authorizations/").concat(e),{headers:this.headers,jwt:s.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new ie})})}catch(r){if(S(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:i},error:a}=s;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new ie});const o=await T(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(e,"/consent"),{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:c=>({data:c,error:null})});return o.data&&o.data.redirect_url&&Q()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(s){if(S(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:i},error:a}=s;
2if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new ie});const o=await T(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(e,"/consent"),{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:c=>({data:c,error:null})});return o.data&&o.data.redirect_url&&Q()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(s){if(S(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await T(this.fetch,"GET","".concat(this.url,"/user/oauth/grants"),{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new ie})})}catch(e){if(S(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;return i?this._returnResult({data:null,error:i}):s?(await T(this.fetch,"DELETE","".concat(this.url,"/user/oauth/grants"),{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new ie})})}catch(r){if(S(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(c=>c.kid===e);if(s)return s;const i=Date.now();if(s=this.jwks.keys.find(c=>c.kid===e),s&&this.jwks_cached_at+gi>i)return s;const{data:a,error:o}=await T(this.fetch,"GET","".concat(this.url,"/.well-known/jwks.json"),{headers:this.headers});if(o)throw o;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=i,s=a.keys.find(c=>c.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:w}
2=await this.getSession();if(w||!f.session)return this._returnResult({data:null,error:w});s=f.session.access_token}const{header:i,payload:a,signature:o,raw:{header:c,payload:l}}=It(s);r!=null&&r.allowExpired||Vi(a.exp);const u=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!u){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:a,header:i,signature:o},error:null}}const d=qi(i.alg),_=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,_,o,Ai("".concat(c,".").concat(l))))throw new Xt("Invalid JWT signature");return{data:{claims:a,header:i,signature:o},error:null}}catch(s){if(S(s))return this._returnResult({data:null,error:s});throw s}}}at.nextInstanceID={};const wa=at,va="2.90.1";let Qe="";typeof Deno<"u"?Qe="deno":typeof document<"u"?Qe="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Qe="react-native":Qe="node";const ba={"X-Client-Info":"supabase-js-".concat(Qe,"/").concat(va)},ya={headers:ba},xa={schema:"public"},Ea={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ka={};function ot(t){"@babel/helpers - typeof";return ot=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},ot(t)}function ja(t,e){if(ot(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ot(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Aa(t){var e=ja(t,"string");return ot(e)=="symbol"?e:e+""}function Sa(t,e,r){return(e=Aa(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Gr(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,s)}return r}function K(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Gr(Object(r),!0).forEach(function(s){Sa(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Gr(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const Ta=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Pa=()=>Headers,Ra=(t,e,r)=>{const s=Ta(r),i=Pa();return async(a,o)=>{var c;const l=(c=await e())!==null&&c!==void 0?c:t;let u=new i(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization","Bearer ".concat(l)),s(a,K(K({},o),{},{headers:u}))}};function Oa(t){return t.endsWith("/")?t:t+"/"}function Ia(t,e){var r,s;const{db:i,auth:a,realtime:o,global:c}=t,{db:l,auth:u,realtime:d,global:_}=e,g={db:K(K({},l),i),auth:K(K({},u),a),realtime:K(K({},d),o),storage:{},global:K(K(K({},_),c),{},{headers:K(K({},(r=_==null?void 0:_.headers)!==null&&r!==void 0?r:{}),(s=c==null?void 0:c.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?g.accessToken=t.accessToken:delete g.accessToken,g}function Ca(t){const e=t==null?void 0: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(Oa(e))}catch(r){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Da=class extends wa{constructor(t){super(t)}},La=class{constructor(t,e,r){var s,i;this.supabaseUrl=t,this.supabaseKey=e;const a=Ca(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o="sb-".concat(a.hostname.split(".")[0],"-auth-token"),c={db:xa,realtime:ka,auth:K(K({},Ea),{},{storageKey:o}),global:ya},l=Ia(r!=null?r:{},c);if(this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(d,_)=>{throw new Error("@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.".concat(String(_)," is not possible"))}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Ra(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(K({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&this.accessToken().then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new mn(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this.storage=new di(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new ln(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}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 _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:a,flowType:o,lock:c,debug:l,throwOnError:u},d,_){const g={Authorization:"Bearer ".concat(this.supabaseKey),apikey:"".concat(this.supabaseKey)};return new Da({url:this.authUrl.href,headers:K(K({},g),d),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:i,flowType:o,lock:c,debug:l,throwOnError:u,fetch:_,hasCu
2stomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new On(this.realtimeUrl.href,K(K({},t),{},{params:K(K({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&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)}};const Na=(t,e,r)=>new La(t,e,r);function $a(){if(typeof window<"u")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)<=18:!1}$a()&&console.warn("â ï¸ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Ua="https://bsmvcmmwkmaqpgrmvjql.supabase.co",Va="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJzbXZjbW13a21hcXBncm12anFsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQ3MTQyMjUsImV4cCI6MjA2MDI5MDIyNX0.KyPuN_OCKx10MjCqve_4cPjzouAzG7ONt4mcPFUU-Ks",N=Na(Ua,Va,{auth:{lock:async(t,e,r)=>await r()}}),Yt="cm_utm_first_touch",Ss="cm_letzter_fb_klick",gt="cm_attribution_first_touch",Zt="cm_visitor_id",Lt="cm_first_touch_reported",Ts=2160*60*60*1e3,Ps=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],Rs=["fbclid","gclid","ttclid","msclkid","twclid"];function Os(){if(typeof window>"u")return{};const t=new URLSearchParams(window.location.search),e={};for(const r of Ps){const s=t.get(r);s&&(e[r]=s)}return e}function qa(){if(typeof window>"u")return{};const t=new URLSearchParams(window.location.search),e={};for(const r of Rs){const s=t.get(r);s&&(e[r]=s)}return e}function Is(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Yt);if(!t)return null;const e=JSON.parse(t);return!e.saved_at||Date.now()-e.saved_at>Ts?(window.localStorage.removeItem(Yt),null):e}catch(t){return null}}function Cs(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(gt);if(!t)return null;const e=JSON.parse(t);return!e.saved_at||Date.now()-e.saved_at>Ts?(window.localStorage.removeItem(gt),null):e}catch(t){return null}}function Ba(){if(typeof window>"u")return;const t=Os(),e=qa(),r=document.referrer||void 0,s=!!(t.utm_source||t.utm_medium||t.utm_campaign),i=!!(e.fbclid||e.gclid||e.ttclid||e.msclkid||e.twclid),a=!!r&&!r.startsWith(window.location.origin);if(Ds(),s&&!Is()){const l={...t,saved_at:Date.now(),landing_page:window.location.pathname};try{window.localStorage.setItem(Yt,JSON.stringify(l))}catch(u){}}const o=Cs();if(o){if(s||i){const c={...o,...t,...e,referrer:a?r:o.referrer,saved_at:o.saved_at};try{window.localStorage.setItem(gt,JSON.stringify(c))}catch(l){}}}else{const c={...t,...e,referrer:a?r:void 0,landing_url:window.location.href,landing_path:window.location.pathname,user_agent:navigator.userAgent,first_seen_at:new Date().toISOString(),saved_at:Date.now()};try{window.localStorage.setItem(gt,JSON.stringify(c))}catch(l){}}try{const c=new URL(window.location.href);let l=!1;for(const u of Ps)c.searchParams.has(u)&&(c.searchParams.delete(u),l=!0);for(const u of Rs)c.searchParams.has(u)&&(c.searchParams.delete(u),l=!0);l&&window.history.replaceState({},"",c.pathname+(c.search||"")+c.hash)}catch(c){}}function Ma(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=e=>Array.from({length:e},()=>Math.floor(Math.random()*16).toString(16)).join("");return"".concat(t(8),"-").concat(t(4),"-4").concat(t(3),"-").concat((Math.random()*4|8).toString(16)).concat(t(3),"-").concat(t(12))}function cr(){if(typeof window>"u")return"";try{const t=window.localStorage.getItem(Zt);if(t)return t;const e=Ma();return window.localStorage.setItem(Zt,e),e}catch(t){return""}}function Fa(t){if(!(typeof window>"u"))try{if(window.localStorage.getItem(Lt))return;const e=lr();if(!e.landing_url)return;const r=cr();if(!r)return;window.localStorage.setItem(Lt,"1"),Promise.resolve(t.functions.invoke("attribution-track",{body:{visitor_id:r,...e}})).catch(()=>{try{window.localStorage.removeItem(Lt)}catch(s){}})}catch(e){}}async function za(t){if(!(typeof window>"u"))try{const e=window.localStorage.getItem(Zt);if(!e)return;await t.rpc("link_visit_to_user",{p_visitor_id:e})}catch(e){}}function Ga(){const t=Os();if(t.utm_source||t.utm_campaign)return t;const e=Is();if(!e)return{};const{saved_at:r,landing_page:s,...i}=e;return i}function lr(){const t=Cs();if(!t)return{};const{saved_at:e,...r}=t;return r}function yt(){try{const t=JSON.parse(window.localStorage.getItem("cookie-consent")||"null");return!!t&&t.marketing===!0}catch(t){return!1}}function Ds(){if(!(typeof window>"u"||!yt()))try{const t=new URLSearchParams(window.location.search).get("fbclid");t&&window.localStorage.setItem(Ss,JSON.stringify({fbclid:t,zeit:Date.now()}))}catch(t){}}function bd(){return yt()}function yd(){try{const t=JSON.parse(window.localStorage.getItem("cookie-consent")||"null");return t?t.marketing===!0?"ja":"nein":"offen"}catch(t){return"offen"}}
2function Ka(){if(yt()){try{const t=JSON.parse(window.localStorage.getItem(Ss)||"null");if(t!=null&&t.fbclid&&(t!=null&&t.zeit))return"fb.1.".concat(t.zeit,".").concat(t.fbclid)}catch(t){}try{const t=lr();if(!t.fbclid)return;const e=t.first_seen_at?new Date(t.first_seen_at).getTime():Date.now();return"fb.1.".concat(e,".").concat(t.fbclid)}catch(t){return}}}function xd(){if(yt())try{const t=document.cookie.match(/(?:^|; )_fbp=([^;]*)/);return t?decodeURIComponent(t[1]):void 0}catch(t){return}}async function Wa(t,e){var i,a,o;const r=Ga();if(!r.utm_source&&!r.utm_campaign&&!r.utm_medium)return;const{data:s}=await t.from("profiles").select("utm_source").eq("id",e).maybeSingle();!s||s.utm_source||await t.from("profiles").update({utm_source:(i=r.utm_source)!=null?i:null,utm_medium:(a=r.utm_medium)!=null?a:null,utm_campaign:(o=r.utm_campaign)!=null?o:null}).eq("id",e)}async function Ja(t,e){var i,a,o,c,l,u,d,_,g,f,w,v,b,x,E;const r=lr();if(!r.landing_url)return;const{data:s}=await t.from("user_attribution").select("user_id").eq("user_id",e).maybeSingle();s||await t.from("user_attribution").insert({user_id:e,utm_source:(i=r.utm_source)!=null?i:null,utm_medium:(a=r.utm_medium)!=null?a:null,utm_campaign:(o=r.utm_campaign)!=null?o:null,utm_term:(c=r.utm_term)!=null?c:null,utm_content:(l=r.utm_content)!=null?l:null,referrer:(u=r.referrer)!=null?u:null,landing_url:(d=r.landing_url)!=null?d:null,landing_path:(_=r.landing_path)!=null?_:null,fbclid:(g=r.fbclid)!=null?g:null,gclid:(f=r.gclid)!=null?f:null,ttclid:(w=r.ttclid)!=null?w:null,msclkid:(v=r.msclkid)!=null?v:null,twclid:(b=r.twclid)!=null?b:null,user_agent:(x=r.user_agent)!=null?x:null,first_seen_at:(E=r.first_seen_at)!=null?E:null})}function Ed(t){if(!t.startsWith("https://buy.stripe.com/"))return t;const e=cr();return!e||!/^[A-Za-z0-9_-]{1,180}$/.test(e)?t:"".concat(t).concat(t.includes("?")?"&":"?","client_reference_id=besucher_").concat(e)}const Ha="1662104488268693",Xa="https://bsmvcmmwkmaqpgrmvjql.supabase.co/functions/v1/meta-capi-send";function Qt(){return window.__cmPageViewId||(window.__cmPageViewId=De()),window.__cmPageViewId}function Kr(){if(window.fbq)return;const t=window,e=document,r=t.fbq=function(...a){r.callMethod?r.callMethod.apply(r,a):r.queue.push(a)};t._fbq||(t._fbq=r),r.push=r,r.loaded=!0,r.version="2.0",r.queue=[];const s=e.createElement("script");s.async=!0,s.src="https://connect.facebook.net/en_US/fbevents.js";const i=e.getElementsByTagName("script")[0];i.parentNode.insertBefore(s,i),window.fbq("init",Ha),window.fbq("track","PageView",{},{eventID:Qt()})}function De(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"".concat(Date.now(),"-").concat(Math.random().toString(36).slice(2))}function Wr(t){const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):void 0}async function Ya(){var t,e;try{const{data:r}=await N.auth.getUser(),s=r==null?void 0:r.user;if(!s)return{};const i=((t=s.user_metadata)==null?void 0:t.full_name)||((e=s.user_metadata)==null?void 0:e.name)||void 0;let a,o;if(i){const c=i.trim().split(/\s+/);a=c[0],o=c.length>1?c.slice(1).join(" "):void 0}return{email:s.email||void 0,external_id:s.id||void 0,first_name:a,last_name:o}}catch(r){return{}}}function Za(){try{const e=new URLSearchParams(window.location.search).get("fbclid");return e?"fb.1.".concat(Date.now(),".").concat(e):void 0}catch(t){return}}function Qa(){try{const t=new URL(window.location.href);return["kauf","session_id"].forEach(e=>t.searchParams.delete(e)),t.toString()}catch(t){return window.location.origin+window.location.pathname}}function Ls(){var t;try{return((t=me.getPreferences())==null?void 0:t.marketing)===!0}catch(e){return!1}}async function Ce(t,e,r,s){if(Ls())try{const a={...await Ya(),...s||{}};await fetch(Xa,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event_name:t,event_id:e,event_source_url:Qa(),action_source:"website",user_data:{email:a.email,external_id:a.external_id,first_name:a.first_name,last_name:a.last_name,fbp:Wr("_fbp"),fbc:Wr("_fbc")||Za()||Ka(),client_user_agent:navigator.userAgent},custom_data:r||{}}),keepalive:!0})}catch(i){console.warn("CAPI send failed",i)}}const eo=()=>(y.useEffect(()=>{!window.__cmPageViewSent&&Ls()&&(Ce("PageView",Qt()),window.__cmPageViewSent=!0);const t=me.getPreferences();t!=null&&t.marketing&&Kr();const e=r=>{r.marketing&&(Kr(),Ds(),window.__cmPageViewSent||(Ce("PageView",Qt()),window.__cmPageViewSent=!0))};return me.onPreferencesChange(e),()=>{me.removePreferencesListener(e)}},[]),null),kd={sparplan:"finanzguide",finanzguide:"finanzguide",rebalancing:"rebalancing",einfuehrung:"einfuehrung",abo:"abo",premium:"premium",buendel_abo_coaching:"buendel_abo_coaching",buendel_abo_guide:"buendel_abo_guide",buendel_abo_seminar:"premium",buendel_guide_seminar:"buendel_guide_seminar",jahrespass:"jahrespass"},to={finanzguide:"Finanzguide",depot_guide:"Depot-Guide",rebalancing:"Rebalancing",einfuehrung:"Einrichtung mit Maurice",abo:"CraderMind Abo",premium:"CraderMind Premium",buendel_abo_coaching:"CraderMind + Maurice",buendel_abo_guide:"CraderMind + Finanzguide",buendel_guide_seminar:"Finanzguide + Seminar",seminar:"Live-Seminar",jahrespass:"Praxis-Lab-Jahrespass",erstgespraech:"1:1 mit Florian"};function xt(t,e,r){const s={};r!==void 0&&(s.value=r,s.currency="EUR");const i=e&&to[e]||t;return i&&(s.content_name=i),e&&(s.content_ids=[e],s.content_type="product"),s}
2function jd(t,e,r){const s=De(),i=xt(t,e,r);window.fbq&&window.fbq("track","ViewContent",i,{eventID:s}),Ce("ViewContent",s,i)}function Ad(t,e){const r=De(),s=t?{content_name:t}:{};window.fbq&&window.fbq("track","Lead",s,{eventID:r}),Ce("Lead",r,s,e?{email:e}:void 0)}function Sd(t,e={},r){const s=De();window.fbq&&window.fbq("trackCustom",t,e,{eventID:s}),Ce(t,s,e,void 0)}function Td(t,e,r,s){const i=De(),a=xt(e,s,t);return window.fbq&&window.fbq("track","InitiateCheckout",a,{eventID:i}),Ce("InitiateCheckout",i,a,r?{email:r}:void 0),i}function Pd(t,e,r,s){const i=r||De(),a=xt(e,s,t);return window.fbq&&window.fbq("track","Purchase",a,{eventID:i}),i}function Rd(t,e,r){const s=De(),i=xt(t,"erstgespraech");return window.fbq&&window.fbq("track","Schedule",i,{eventID:s}),Ce("Schedule",s,i,r?{email:r}:void 0),s}const ro="G-JPDEY5837K",so=t=>{typeof window.gtag<"u"&&window.gtag("config",ro,{page_location:t})},pe=(t,e,r,s)=>{typeof window.gtag<"u"&&window.gtag("event",t,{event_category:e,event_label:r,value:s})},no=(t="email")=>{pe("login","authentication",t)},io=()=>{pe("logout","authentication")},Od=(t,e)=>{pe("purchase","subscription","".concat(t,"_").concat(e))},Id=t=>{pe("like","engagement",t)},Cd=()=>{pe("follow","social","user_interaction")},Dd=()=>{pe("unfollow","social","user_interaction")},Ld=t=>{pe("calculator_use","tools",t)},Nd=()=>{pe("chat_message","community","engagement")},$d=t=>{pe("page_visit","navigation",t)},Ud=(t,e)=>{pe("trading_idea_view","content",e||"unknown",t?1:0)},Vd=(t,e)=>{pe("search","user_behavior",e,t.length)};async function ao(t,e,r){try{await fetch("".concat(t,"/functions/v1/claim-brand"),{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({brand:r})})}catch(s){console.warn("claimBrand failed, account stays unbranded:",s)}}const oo={id:"cradermind",name:"CraderMind",tagline:"Your Edge in Crypto Markets",domain:"cradermind.com",deepLinkScheme:"cradermind://",bundleId:{ios:"com.cradermind.mobile",android:"com.cradermind.app"},colors:{primary:"#C9A96E",primaryLight:"#E6C88A",primaryDark:"#A8864A",secondary:"#E6C88A",bgDeep:"#0A0A0A",bgSurface:"#0A0A0A",bgElevated:"#111111",bgNavbar:"#0A0A0A",success:"#22C55E",error:"#EF4444",neutral1:"#1A1714",neutral2:"#9C9585",neutral3:"#6B6560",accentFrom:"#A8864A",accentTo:"#E6C88A",bronze:"#C9A96E",bronzeLight:"#E6C88A",bronzeDark:"#A8864A",bronzeDarker:"#6B5530",bg:"#0A0A0A",bg2:"#111111",bg3:"#1A1714",bg4:"#2A2520",fg:"#F5F0E8",fgMuted:"#9C9585",fgDim:"#6B6560",line:"#2A2520",lineStrong:"#3D3530",long:"#22C55E",short:"#EF4444",link:"#60a5fa",warn:"#F59E0B",activeTradeAccent:"#C9A96E",activeTradeWarning:"#DC2626",activeTradeGlow:"rgba(220,38,38,0.35)",activeTradeBorder:"#7A1F1F"},logos:{full:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/CRADER_Logo-thumb.webp",icon:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/CraderMind%20(14).png",collapsed:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/CRADER_Logo-thumb.webp",mobileSplash:"./assets/cradermind/logo-no-bg.png"},features:{communityTab:!0,educationSection:!0,strategies:!0,discover:!0,saveALife:!0,partnerPage:!0,events:!0,webinars:!0,getFunded:!0,videoTutorials:!0,textTutorials:!1,affiliate:!0,aiAssistant:!0},subscription:{model:"two_tier"},iap:{proMonthlyProductId:"com.cradermind.app.pro_monthly"},legal:{companyName:"CraderMind",contactEmail:"[email protected]"},analytics:{gaTrackingId:"G-JPDEY5837K"}};function co(){return"cradermind"}function lo(){return oo}const O=lo(),Ns=y.createContext({user:null,isAdmin:!1,isEmailVerified:!1,signIn:async()=>{},signOut:async()=>{},authLoading:!0,hasActivePlan:!1,isFreeUser:!1,isInGracePeriod:!1,gracePeriodDaysLeft:void 0,hasInternalAnalysisAccess:!1,hasStarterGuide:!1,hasJuniorGuide:!1,hasRebalancing:!1,hasStarterRebalancing:!1,hasJuniorRebalancing:!1}),ge=()=>y.useContext(Ns),uo=({children:t})=>{const[e,r]=y.useState(null),[s,i]=y.useState(!1),[a,o]=y.useState(!1),[c,l]=y.useState(!0),[u,d]=y.useState(!1),[_,g]=y.useState(!1),[f,w]=y.useState(!1),[v,b]=y.useState(void 0),[x,E]=y.useState(!1),[k,A]=y.useState(!1),[q,R]=y.useState(!1),[D,C]=y.useState(!1),G=()=>{r(null),i(!1),o(!1),d(!1),g(!1),w(!1),b(void 0),E(!1),A(!1),R(!1),C(!1)},Je=async(L,B)=>
2{if(B){E(!0);return}const{data:W}=await N.from("internal_analysis_access").select("user_id").eq("user_id",L).maybeSingle();E(!!W)},dr=async()=>{try{await N.rpc("guide_kaeufe_zuordnen")}catch(L){}},hr=async(L,B)=>{if(B){A(!0),R(!0),C(!0);return}const[{data:W},{data:M}]=await Promise.all([N.from("guide_purchases").select("guide_type").eq("user_id",L),N.from("rebalancing_subscriptions").select("id").eq("user_id",L).eq("status","active").gt("current_period_end",new Date().toISOString()).limit(1).maybeSingle()]),I=(W!=null?W:[]).map(ue=>ue.guide_type),se=I.includes("finanzguide");A(se||I.includes("starter_depot")),R(se||I.includes("junior_depot")),C(!!M)},fr=["free","none"],Et=(L,B)=>{var _e;const W=L==null?void 0:L.plan,M=(_e=B==null?void 0:B.plan)!=null?_e:fr.includes(W)?W:void 0,I=(B==null?void 0:B.gracePeriodActive)===!0,se=B==null?void 0:B.planExpiresAt,ue=B==null?void 0:B.planRevokedAt;let $=!1,be=!1,ne=!1,je,ce=!1;if(M==="free")be=!0,$=!1,ne=!1;else if(M==="none"&&ue&&I===!1)ce=!0,$=!1,ne=!1;else if(M&&M!=="none")if(I&&se){const Xe=new Date(se),Ye=new Date;if(Xe>Ye){$=!0,ne=!0;const ee=Xe.getTime()-Ye.getTime();je=Math.ceil(ee/(1e3*3600*24))}else $=!1,ne=!1}else $=!0,ne=!1;return{hasActive:$,isFree:be,inGracePeriod:ne,daysLeft:je,forceLogout:ce,plan:M}},mr=y.useRef(!1),pr=async L=>{var M,I;if(mr.current)return;const B=(M=L==null?void 0:L.user_metadata)==null?void 0:M.plan;(I=L==null?void 0:L.app_metadata)!=null&&I.plan||!B||fr.includes(B)||(mr.current=!0,console.log("Plan steht nur in der Anzeige â hole frische Sitzung"),await N.auth.refreshSession())},kt=async L=>{var W,M,I;console.warn("Authentication error:",L),((W=L.message)==null?void 0:W.includes("refresh_token_not_found"))||((M=L.message)==null?void 0:M.includes("Invalid Refresh Token"))||((I=L.message)==null?void 0:I.includes("JWT expired"))||L.code==="invalid_refresh_token"||L.code==="token_not_found"?(console.error("Critical auth error detected, logging out:",L),await He()):console.warn("Non-critical auth error (not logging out):",L.message||L)};y.useEffect(()=>{(async()=>{var M,I,se,ue;try{const{data:{session:$},error:be}=await N.auth.getSession();if(be){await kt(be),l(!1);return}if($!=null&&$.user){const ne=(M=$.user.app_metadata)==null?void 0:M.role,je=$.user.user_metadata||{},ce=Et(je,$.user.app_metadata||{});if(await pr($.user),ce.forceLogout&&ne!=="admin"){console.log("User access was revoked, forcing logout"),await He(),window.location.href="/";return}r({id:$.user.id,email:$.user.email,role:ne,email_confirmed_at:$.user.email_confirmed_at,plan:ce.plan,planCanceledAt:(I=$.user.app_metadata)==null?void 0:I.planCanceledAt,planExpiresAt:(se=$.user.app_metadata)==null?void 0:se.planExpiresAt,gracePeriodActive:(ue=$.user.app_metadata)==null?void 0:ue.gracePeriodActive});const _e=ne==="admin";i(_e),o(!!$.user.email_confirmed_at),d(ce.hasActive),g(ce.isFree),w(ce.inGracePeriod),b(ce.daysLeft),await Je($.user.id,_e),await dr(),await hr($.user.id,_e)}else G();l(!1)}catch($){if(($==null?void 0:$.name)==="AbortError"){console.warn("Auth lock timed out, clearing stale session"),G(),l(!1);return}await kt($),l(!1)}})();const B=setInterval(async()=>{var M;try{const{data:{session:I}}=await N.auth.getSession();if(I!=null&&I.user){const se=(M=I.user.app_metadata)==null?void 0:M.role,ue=I.user.user_metadata||{};Et(ue,I.user.app_metadata||{}).forceLogout&&se!=="admin"&&(console.log("Periodic check: User access was revoked, forcing logout"),clearInterval(B),await He(),window.location.href="/")}}catch(I){console.error("Periodic auth check error:",I)}},432e5),{data:{subscription:W}}=N.auth.onAuthStateChange(async(M,I)=>{var se,ue,$,be,ne,je,ce,_e,Xe,Ye;console.log("Auth state change event:",M,"Has session:",!!I);try{if(I!=null&&I.user){const ee=I.user.user_metadata||{};!ee.brand&&I.access_token&&ao("https://bsmvcmmwkmaqpgrmvjql.supabase.co",I.access_token,co());const te=(se=I.user.app_metadata)==null?void 0:se.role,Le=Et(ee,I.user.app_metadata||{});if(await pr(I.user),Le.forceLogout&&te!=="admin"){console.log("User access was revoked, forcing logout"),await He(),window.location.href="/";return}r({id:I.user.id,email:I.user.email,role:te,email_confirmed_at:I.user.email_confirmed_at,plan:Le.plan,planCanceledAt:(ue=I.user.app_metadata)==null?void 0:ue.planCanceledAt,planExpiresAt:($=I.user.app_metadata)==null?void 0:$.planExpiresAt,gracePeriodActive:(be=I.user.app_metadata)==null?void 0:be.gracePeriodActive});const jt=te==="admin";i(jt),o(!!I.user.email_confirmed_at),d(Le.hasActive),g(Le.isFree),w(Le.inGracePeriod),b(Le.daysLeft),Je(I.user.id,jt),dr().then(()=>hr(I.user.id,jt))}else if(M==="SIGNED_OUT")console.log("User signed out explicitly"),G();else if(M==="TOKEN_REFRESHED"){console.log("Token refreshed but no session - attempting to re
2cover");try{const{data:{session:ee},error:te}=await N.auth.getSession();te?(console.warn("Failed to get session after token refresh:",te),((ne=te.message)!=null&&ne.includes("refresh_token_not_found")||(je=te.message)!=null&&je.includes("Invalid Refresh Token")||(ce=te.message)!=null&&ce.includes("JWT expired"))&&(console.error("Critical token error, clearing auth state"),G())):ee?console.log("Session recovered after refresh"):console.warn("No session available after refresh attempt")}catch(ee){console.error("Error during session recovery:",ee)}}else{console.log("Null session on event:",M,"- attempting to recover");try{const{data:{session:ee},error:te}=await N.auth.getSession();te?(console.warn("Failed to get session:",te),((_e=te.message)!=null&&_e.includes("refresh_token_not_found")||(Xe=te.message)!=null&&Xe.includes("Invalid Refresh Token")||(Ye=te.message)!=null&&Ye.includes("JWT expired"))&&(console.error("Critical auth error, clearing state"),G())):ee?console.log("Session recovered"):console.warn("No session available, but keeping current auth state")}catch(ee){console.error("Error during session recovery:",ee)}}l(!1)}catch(ee){console.error("Error in auth state change handler:",ee),await kt(ee),l(!1)}});return()=>{W.unsubscribe(),clearInterval(B)}},[]);const Gs=async(L,B)=>{try{const{error:W}=await N.auth.signInWithPassword({email:L,password:B});if(W)throw W;no("email")}catch(W){throw console.error("Error signing in:",W),W}},He=async()=>{try{G(),io(),localStorage.removeItem("sb-bsmvcmmwkmaqpgrmvjql-auth-token");const{error:L}=await N.auth.signOut();if(L)throw L}catch(L){throw console.error("Error signing out:",L),G(),localStorage.removeItem("sb-bsmvcmmwkmaqpgrmvjql-auth-token"),L}};return n.jsx(Ns.Provider,{value:{user:e,isAdmin:s,isEmailVerified:a,signIn:Gs,signOut:He,authLoading:c,hasActivePlan:u,isFreeUser:_,isInGracePeriod:f,gracePeriodDaysLeft:v,hasInternalAnalysisAccess:x,hasStarterGuide:k,hasJuniorGuide:q,hasRebalancing:D,hasStarterRebalancing:D&&k,hasJuniorRebalancing:D&&q},children:t})},ho={en:{"nav.memberArea":"Member Area","nav.backToDashboard":"Back to Dashboard","hero.subtitle":"Your Edge in Crypto Markets","hero.description":"Whether you're into spot investing or active leveraged trading â CraderMind gives you live charts, clear entry levels, risk assessments, and real trading ideas.","benefits.title":"What to Expect from CraderMind?","benefits.analysis.title":"Pros plan your trade","benefits.analysis.description":"Fully planned setups every day â with exact entry, stop-loss, and take-profit levels. No interpretation needed, just execution.","benefits.data.title":"The market explains itself","benefits.data.description":"Funding rates, liquidations, and on-chain data in one clean dashboard. Know what institutional players are doing before you enter.","benefits.structure.title":"Your system â already built","benefits.structure.description":"Position calculator, trading journal, and portfolio tracker â everything you need for disciplined, professional trading in one place.","pricing.title":"Choose Your Plan","pricing.subtitle":"Start your journey to smarter trading","pricing.pro.title":"CraderMind Pro","pricing.pro.price":"99â¬","pricing.pro.period":"pro Monat","pricing.pro.tax":"exkl. MwSt.","pricing.pro.description":"CraderMind Pro â All-in-One Access.\n\n\nFull power for traders and investors: spot analysis, leverage trading ideas, smart tools, live charts, news, rebuy calculators, and exclusive access to every feature.","pricing.button":"Subscribe Now","pricing.learnMore":"Learn More","cta.button":"Start Trading Smarter","disclaimer.title":"Disclaimer: No Financial Advice","disclaimer.content1":"The content on this website is provided for informational and educational purposes only and does not constitute financial advice, investment recommendations, or an offer to buy or sell any financial instruments.","disclaimer.content2":"CraderMind provides analyses, strategies, and tools that may assist your own research, but they do not replace professional or individual financial advice.","disclaimer.content3":"Investing in cryptocurrencies involves significant risk and may result in the total loss of capital.","disclaimer.content4":"Always consult a qualified financial advisor before making any investment decisions.","dashboard.title":"Dashboard","dashboard.traderView":"Trader View","dashboard.investorView":"Investor View","dashboard.analysis":"Analysis","dashboard.analysis.description":"Deep dive into market trends and patterns","dashboard.tools":"Tools","dashboard.tools.description":"Trading calculators and utilities","dashboard.education":"Education","dashboard.education.description":"Learn trading strategies and concepts","dashboard.signals":"Signals","dashboard.signals.description":"Real-time trading signals and alerts","dashboard.community":"Community","dashboard.community.description":"Connect with fellow traders","dashboard.news":"News","dashboard.news.description":"Latest market news, updates and economical data","dashboard.trackRecord":"Track Record","dashboard.trackRecord.description":"View historical performance","dashboard.tradingIdeas":"Trading Ideas","dashboard.viewCharts":"View Charts","dashboard.viewAll":"View All","dashboard.searchPlaceholder":"Search by pair, strategy, or analyst...","dashboard.searchPairPlaceholder":"Search by pair...","dashboard.marketNews":"Market News","dashboard.cryptoOverview":"Cryptocurrency Overview","dashboard.highImpact":"High Impact","dashboard.mediumImpact":"Medium Impact","dashboard.readMore":"Read More","news.title":"Market News & Exter
2nal Conditions","news.subtitle":"Stay informed about market-moving events and external conditions that affect cryptocurrency markets.","news.importantNews":"Important News","news.externalConditions":"External Conditions","news.influenceDistribution":"Influence Distribution","news.searchConditions":"Search conditions...","news.allImpacts":"All Impacts","news.highImpact":"High Impact","news.mediumImpact":"Medium Impact","news.lowImpact":"Low Impact","news.noResults":"No conditions found matching your search criteria","news.influenceScore":"Influence Score","dashboard.tabCrypto":"Cryptocurrencies","dashboard.tabCommodities":"Commodities","dashboard.tabStocks":"Stocks","dashboard.marketOverview":"Market Overview","messaging.inbox":"Messages","messaging.typeMessage":"Type a message...","messaging.noConversations":"No conversations yet","messaging.startConversation":"Visit a profile to start a conversation","messaging.you":"You","messaging.send":"Send","messaging.typing":"typing...","messaging.messageUser":"Message","messaging.noMessages":"Say hello!","messaging.online":"Online","messaging.searchPlaceholder":"Search conversations...","messaging.community":"Community","messaging.deleted":"Message deleted","messaging.loadOlder":"Load older messages","messaging.newMessage":"New Message","messaging.noResults":"No users found","team.title":"Team Dashboard","team.overview":"Overview","team.tasks":"Tasks","team.calendar":"Calendar","team.chat":"Team Chat","team.members":"Members","team.kanban.todo":"To-Do","team.kanban.inProgress":"In Progress","team.kanban.done":"Done","team.kanban.addTask":"Add Task","team.task.title":"Title","team.task.description":"Description","team.task.importance":"Importance","team.task.assignee":"Assignee","team.task.dueDate":"Due Date","team.task.comments":"Comments","team.importance.low":"Low","team.importance.medium":"Medium","team.importance.high":"High","team.calendar.addEvent":"Add Event","team.calendar.type.reminder":"Reminder","team.calendar.type.note":"Note","team.calendar.type.holiday":"Holiday","team.calendar.type.meeting":"Meeting","team.calendar.type.deadline":"Deadline","team.chat.typeMessage":"Type a message...","team.members.add":"Add Member","team.accessDenied":"You are not a team member. Contact an administrator for access.","akademie.title":"Akademie","akademie.subtitle":"Learn everything about CraderMind in 14 lessons","akademie.intro":"Step-by-step from setup to mastery â strategies, signals, tools.","akademie.lesson":"Lesson","akademie.lessons":"Lessons","akademie.watch":"Watch","akademie.nowPlaying":"Now playing","akademie.upNext":"Up next","akademie.startCourse":"Start with Lesson 1","akademie.of":"of","akademie.comingSoon":"Coming soon","akademie.loading":"Loading lessonsâ¦","akademie.empty":"No lessons published yet.","akademie.category.get_started":"Get Started","akademie.category.platform":"Platform & Setup","akademie.category.method":"Method","akademie.category.strategies":"Strategies","akademie.category.practical":"Practical Trading"},de:{"nav.memberArea":"Mitgliederbereich","nav.backToDashboard":"Zurück zum Dashboard","hero.subtitle":"Dein Vorsprung im Kryptomarkt","hero.description":"Ob Spot-Investment oder aktives Hebeltrading: CraderMind liefert dir Live-Charts, klare Einstiegslevel, Risikoanalysen und echte Trading-Ideen.","benefits.title":"Was erwartet dich bei CraderMind?","benefits.analysis.title":"Profis planen deinen Trade","benefits.analysis.description":"Täglich vollständig geplante Setups â mit konkretem Entry, Stop-Loss und Take-Profit. Kein Interpretieren, nur Ausführen.","benefits.data.title":"Der Markt erklärt sich selbst","benefits.data.description":"Funding Rates, Liquidierungen und On-Chain-Daten in einem klaren Dashboard. Verstehe was institutionelle Marktteilnehmer tun, bevor du einsteigst.","benefits.structure.title":"Dein System â fertig gebaut","benefits.structure.description":"Positionsrechner, Trading-Journal und Portfolio-Tracker â alles für diszipliniertes, professionelles Trading an einem Ort.","pricing.title":"Wähle deinen Plan","pricing.subtitle":"Starte deine Reise zum intelligenteren Trading","pricing.pro.title":"CraderMind Pro","pricing.pro.price":"99â¬","pricing.pro.period":"pro Monat","pricing.pro.tax":"exkl. MwSt.","pricing.pro.description":"CraderMind Pro â Alles in einem Paket.\n\n\nVolle Power für Trader und Investoren: Spot-Analysen, Hebeltrading-Ideen, smarte Tools, Live-Charts, News, Rebuy-Rechner und exklusiver Zugang zu allen Funktionen.","pricing.button":"Jetzt Abonnieren","pricing.learnMore":"Mehr erfahren","cta.button":"Jetzt Smarter Traden","disclaimer.title":"Hinweis: Keine Finanzberatung","disclaimer.content1":"Die Inhalte auf dieser Website dienen ausschlieÃlich zu Informations- und Bildungszwecken und stellen keine Finanzberatung, Anlageempfehlung oder Aufforderung zum Kauf oder Verkauf von Finanzinstrumenten dar.","disclaimer.content2":"CraderMind bietet Analysen, Strategien und Tools an, die als Unterstützung für eigene Recherchen dienen können â jedoch keine individuelle Beratung ersetzen.","disclaimer.content3":"Investitionen in Kryptowährungen sind mit erheblichen Risiken verbunden und können zu einem Totalverlust führen.","disclaimer.content4":"Bitte wende dich bei finanziellen Entscheidungen stets an eine qualifizierte Finanzberatung.","dashboard.title":"Dashboard","dashboard.traderView":"Trader Ansicht","dashboard.investorView":"Investor Ansicht","dashboard.analysis":"Analyse","dashboard.analysis.description":"Tauche ein in Markttrends und Muster","dashboard.tools":"Tools","dashboard.tools.description":"Trading-Rechner und Hilfsmittel","dashboard.education":"Bildung","dashboard.education.description":"Lerne Trading-Strategien und Konzepte","dashboard.signals":"Signale","dashboard.signals.description":"Echtzeit-Trading-Signale und Alerts","dashboard.community":"Community","dashboard.community.description":"Verbinde dich mit anderen Tradern","dashboard.news":"News","dashboard.news.description":"Aktuelle Marktnachrichten, Updates und externe Bedingungen","dashboard.trackRecord":"Track Record","dashboard.trackRecord.description":"Zeige historische Performance","dashboard.tradingIdeas":"Trading-Ideen","dashboard.viewCharts":"Charts anzeigen","dashboard.viewAll":"Alle anzeigen","dashboard.searchPlaceholder":"Suche nac
2h Pair, Strategie oder Analyst...","dashboard.searchPairPlaceholder":"Suche nach Pair...","dashboard.marketNews":"Marktnachrichten & Externe Bedingungen","dashboard.cryptoOverview":"Kryptowährungen Ãbersicht","dashboard.highImpact":"Hohe Auswirkung","dashboard.mediumImpact":"Mittlere Auswirkung","dashboard.readMore":"Mehr lesen","news.title":"Marktnachrichten & Externe Bedingungen","news.subtitle":"Bleibe informiert über marktbewegende Ereignisse und externe Bedingungen, die die Kryptomärkte beeinflussen.","news.importantNews":"Wichtige Nachrichten","news.externalConditions":"Externe Bedingungen","news.influenceDistribution":"Einflussverteilung","news.searchConditions":"Bedingungen suchen...","news.allImpacts":"Alle Auswirkungen","news.highImpact":"Hohe Auswirkung","news.mediumImpact":"Mittlere Auswirkung","news.lowImpact":"Geringe Auswirkung","news.noResults":"Keine Bedingungen gefunden, die deinen Suchkriterien entsprechen","news.influenceScore":"Einflusswert","dashboard.tabCrypto":"Kryptowährungen","dashboard.tabCommodities":"Rohstoffe","dashboard.tabStocks":"Aktien","dashboard.marketOverview":"Marktübersicht","messaging.inbox":"Nachrichten","messaging.typeMessage":"Nachricht eingeben...","messaging.noConversations":"Noch keine Unterhaltungen","messaging.startConversation":"Besuche ein Profil, um eine Unterhaltung zu starten","messaging.you":"Du","messaging.send":"Senden","messaging.typing":"tippt...","messaging.messageUser":"Nachricht","messaging.noMessages":"Sag Hallo!","messaging.online":"Online","messaging.searchPlaceholder":"Unterhaltungen suchen...","messaging.community":"Community","messaging.deleted":"Nachricht gelöscht","messaging.loadOlder":"Ãltere Nachrichten laden","messaging.newMessage":"Neue Nachricht","messaging.noResults":"Keine Benutzer gefunden","team.title":"Team Dashboard","team.overview":"Ãbersicht","team.tasks":"Aufgaben","team.calendar":"Kalender","team.chat":"Team Chat","team.members":"Mitglieder","team.kanban.todo":"Zu erledigen","team.kanban.inProgress":"In Arbeit","team.kanban.done":"Erledigt","team.kanban.addTask":"Aufgabe hinzufügen","team.task.title":"Titel","team.task.description":"Beschreibung","team.task.importance":"Wichtigkeit","team.task.assignee":"Zugewiesen","team.task.dueDate":"Fälligkeitsdatum","team.task.comments":"Kommentare","team.importance.low":"Niedrig","team.importance.medium":"Mittel","team.importance.high":"Hoch","team.calendar.addEvent":"Termin hinzufügen","team.calendar.type.reminder":"Erinnerung","team.calendar.type.note":"Notiz","team.calendar.type.holiday":"Urlaub","team.calendar.type.meeting":"Meeting","team.calendar.type.deadline":"Deadline","team.chat.typeMessage":"Nachricht eingeben...","team.members.add":"Mitglied hinzufügen","team.accessDenied":"Du bist kein Teammitglied. Kontaktiere einen Administrator für Zugang.","akademie.title":"Akademie","akademie.subtitle":"In 14 Lektionen alles über CraderMind lernen","akademie.intro":"Schritt für Schritt vom Setup zur Meisterschaft â Strategien, Signale, Tools.","akademie.lesson":"Lektion","akademie.lessons":"Lektionen","akademie.watch":"Ansehen","akademie.nowPlaying":"Wird abgespielt","akademie.upNext":"Nächste Lektion","akademie.startCourse":"Mit Lektion 1 starten","akademie.of":"von","akademie.comingSoon":"Bald verfügbar","akademie.loading":"Lektionen werden geladenâ¦","akademie.empty":"Noch keine Lektionen veröffentlicht.","akademie.category.get_started":"Loslegen","akademie.category.platform":"Plattform & Setup","akademie.category.method":"Methode","akademie.category.strategies":"Strategien","akademie.category.practical":"Praktisch traden"}},$s=y.createContext({language:"de",setLanguage:()=>{},t:()=>""}),fo=()=>y.useContext($s),mo=({children:t})=>{const[e,r]=y.useState(()=>localStorage.getItem("language")||"de");y.useEffect(()=>{localStorage.setItem("language",e)},[e]);const s=i=>ho[e][i]||i;return n.jsx($s.Provider,{value:{language:e,setLanguage:r,t:s},children:t})},Us=y.createContext({theme:"dark",toggleTheme:()=>{}}),qd=()=>y.useContext(Us),po=({children:t})=>(y.useEffect(()=>{document.documentElement.classList.remove("light"),document.documentElement.classList.add("dark");try{localStorage.setItem("theme","dark")}catch(e){}},[]),n.jsx(Us.Provider,{value:{theme:"dark",toggleTheme:()=>{}},children:t})),Vs=y.createContext({coins:[],priceMap:new Map,loading:!0,lastUpdate:null,getCoin:()=>{}}),Bd=()=>y.useContext(Vs),go=({children:t})=>{const e=re(),r=rr(e.pathname),[s,i]=y.useState([]),[a,o]=y.useState(new Map),[c,l]=y.useState(!0),[u,d]=y.useState(null),_=y.useRef(!0),g=async()=>{try{const b=window.location.hostname==="localhost"?"https://cradermind.com/.netlify/functions/coins-price-change":"/.netlify/functions/coins-price-change",x=await fetch(b);
2if(!x.ok)return;const E=await x.json();if(!_.current)return;if(E.success&&Array.isArray(E.data)){i(E.data);const k=new Map;E.data.forEach(A=>{A.symbol&&A.current_price&&k.set(A.symbol,A.current_price)}),o(k),d(new Date),l(!1)}}catch(v){}};y.useEffect(()=>{if(_.current=!0,r)return;let v;const b=()=>{const E=window.requestIdleCallback;E?v=E(()=>g(),{timeout:2e3}):v=window.setTimeout(g,200)};document.readyState==="complete"?b():window.addEventListener("load",b,{once:!0});const x=setInterval(g,1e4);return()=>{if(_.current=!1,window.removeEventListener("load",b),v!==void 0){const E=window.cancelIdleCallback;E?E(v):clearTimeout(v)}clearInterval(x)}},[r]);const f=v=>s.find(b=>b.symbol===v),w=y.useMemo(()=>({coins:s,priceMap:a,loading:c,lastUpdate:u,getCoin:f}),[s,a,c,u]);return n.jsx(Vs.Provider,{value:w,children:t})},qs=y.createContext({stocks:[],priceMap:new Map,loading:!0,lastUpdate:null}),Md=()=>y.useContext(qs),_o=({children:t})=>{const e=re(),r=rr(e.pathname),[s,i]=y.useState([]),[a,o]=y.useState(new Map),[c,l]=y.useState(!0),[u,d]=y.useState(null),_=y.useRef(!0),g=async()=>{try{const v=window.location.hostname==="localhost"?"https://cradermind.com/.netlify/functions/stocks-commodities-prices":"/.netlify/functions/stocks-commodities-prices",b=await fetch(v);if(!b.ok)return;const x=await b.json();if(!_.current)return;if(x.data&&Array.isArray(x.data)){const E=x.data;i(E);const k=new Map;E.forEach(A=>{A.symbol&&A.current_price&&k.set(A.symbol,A.current_price)}),o(k),d(new Date),l(!1)}}catch(w){}};y.useEffect(()=>{if(_.current=!0,r)return;let w;const v=()=>{const x=window.requestIdleCallback;x?w=x(()=>g(),{timeout:2e3}):w=window.setTimeout(g,200)};document.readyState==="complete"?v():window.addEventListener("load",v,{once:!0});const b=setInterval(g,3e4);return()=>{if(_.current=!1,window.removeEventListener("load",v),w!==void 0){const x=window.cancelIdleCallback;x?x(w):clearTimeout(w)}clearInterval(b)}},[r]);const f=y.useMemo(()=>({stocks:s,priceMap:a,loading:c,lastUpdate:u}),[s,a,c,u]);return n.jsx(qs.Provider,{value:f,children:t})},Jr="goldCart_lines",Bs=y.createContext(void 0),Fd=()=>{const t=y.useContext(Bs);if(!t)throw new Error("useGoldCart must be used within a GoldCartProvider");return t},wo=({children:t})=>{const[e,r]=y.useState(()=>{try{const f=localStorage.getItem(Jr);return f?JSON.parse(f):[]}catch(f){return[]}});y.useEffect(()=>{try{localStorage.setItem(Jr,JSON.stringify(e))}catch(f){}},[e]);const s=(f,w=1)=>{r(v=>v.find(x=>x.productId===f.productId)?v.map(x=>x.productId===f.productId?{...x,quantity:x.quantity+w}:x):[...v,{...f,quantity:w}])},i=(f,w)=>{if(w<=0){r(v=>v.filter(b=>b.productId!==f));return}r(v=>v.map(b=>b.productId===f?{...b,quantity:w}:b))},a=f=>{r(w=>w.filter(v=>v.productId!==f))},o=()=>r([]),[c,l]=y.useState(!1),u=()=>l(!0),d=()=>l(!1),_=e.reduce((f,w)=>f+w.unitPrice*w.quantity,0),g=e.reduce((f,w)=>f+w.quantity,0);return n.jsx(Bs.Provider,{value:{lines:e,addItem:s,updateQuantity:i,removeItem:a,clearCart:o,subtotal:_,itemCount:g,isDrawerOpen:c,openDrawer:u,closeDrawer:d},children:t})},j=({children:t,requiresAdmin:e=!1,requiresJournalAccess:r=!1,requiresPortfolioAccess:s=!1,requiresInternalAnalysisAccess:i=!1})=>{const{user:a,isAdmin:o,authLoading:c,hasActivePlan:l,isFreeUser:u,hasInternalAnalysisAccess:d}=ge(),_=re(),[g,f]=y.useState(null),[w,v]=y.useState(!1),[b,x]=y.useState(null),[E,k]=y.useState(!1);y.useEffect(()=>{r&&a&&!c&&A()},[r,a,c]),y.useEffect(()=>{s&&a&&!c&&q()},[s,a,c]);const A=async()=>{v(!0);try{f(!!(l||o))}catch(R){console.error("Error checking journal access:",R),f(!1)}finally{v(!1)}},q=async()=>{k(!0);try{if(o){x(!0);return}const{data:R,error:D}=await N.from("portfolio_access").select("*").eq("user_id",a.id).eq("is_active",!0).single();if(D&&D.code!=="PGRST116"){console.error("Error checking portfolio access:",D),x(!1);return}x(!!R)}catch(R){console.error("Error checking portfolio access:",R),x(!1)}finally{k(!1)}};return c||r&&w||s&&E?n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-surface-elevated flex items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-bronze-600 mx-auto mb-4"}),n.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Loading..."})]})}):a?e&&!o?n.jsx(z,{to:"/",replace:!0}
2):!l&&!u&&!o?n.jsx(z,{to:"/payment-required",state:{from:_},replace:!0}):r&&g===!1?n.jsx(z,{to:"/dashboard",replace:!0}):s&&b===!1?n.jsx(z,{to:"/dashboard",replace:!0}):i&&!d?n.jsx(z,{to:"/",replace:!0}):n.jsx(n.Fragment,{children:t}):n.jsx(z,{to:"/payment-required",state:{from:_},replace:!0})};function Hr({children:t}){const{user:e,authLoading:r}=ge(),s=re();if(r)return n.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"#08090e"},children:n.jsx("div",{className:"animate-spin rounded-full h-10 w-10 border-b-2 border-[#C9A84C]"})});if(!e){const i=s.pathname+s.search;return n.jsx(z,{to:"/webinar-zugang?next=".concat(encodeURIComponent(i)),replace:!0})}return n.jsx(n.Fragment,{children:t})}const Ms=y.createContext({xpSummary:null,loading:!0,toasts:[],dismissToast:()=>{},refreshXP:async()=>{}}),vo=()=>y.useContext(Ms),bo={daily_visit:"Daily Visit",post_created:"Post Created",trading_idea_posted:"Trading Idea",comment_written:"Comment",like_given:"Like Given",like_received:"Like Received",follower_gained:"New Follower",follow_given:"Followed User",journal_entry:"Journal Entry",journal_entry_detailed:"Detailed Entry Bonus",chat_message_sent:"Chat Message",profile_picture_added:"Profile Picture",bio_written:"Bio Written",demo_trade_closed:"Demo Trade Closed",achievement_unlocked:"Achievement Bonus"},yo=({children:t})=>{const{user:e}=ge(),[r,s]=y.useState(null),[i,a]=y.useState(!0),[o,c]=y.useState([]),l=y.useRef(!1),u=y.useCallback(f=>{c(w=>w.filter(v=>v.id!==f))},[]),d=y.useCallback((f,w,v,b,x)=>{const E=crypto.randomUUID(),k=(x==null?void 0:x.display_name)||bo[w]||w.replace(/_/g," ");c(A=>[...A.slice(-4),{id:E,xp:f,description:k,levelUp:v,newLevel:b,achievement:x}])},[]),_=y.useCallback(async()=>{if(!e)return;const{data:f,error:w}=await N.rpc("get_xp_summary",{p_user_id:e.id});!w&&f&&s(f),a(!1)},[e]),g=y.useCallback(async()=>{await _()},[_]);return y.useEffect(()=>{e?_():(s(null),a(!1),l.current=!1)},[e,_]),y.useEffect(()=>{if(!e||l.current)return;l.current=!0,(async()=>{const{data:w,error:v}=await N.rpc("process_daily_visit");if(!v&&w){const b=w;if(!b.already_visited&&b.xp_awarded){const x=parseInt(b.xp_awarded,10);x>0&&d(x,"daily_visit",b.level_up==="true")}await _()}})()},[e,d,_]),y.useEffect(()=>{if(!e)return;const f=N.channel("xp-toasts-".concat(e.id)).on("postgres_changes",{event:"INSERT",schema:"public",table:"xp_transactions",filter:"user_id=eq.".concat(e.id)},b=>{const x=b.new;x.activity_type!=="daily_visit"&&x.activity_type!=="achievement_unlocked"&&d(x.final_xp,x.activity_type,!1)}).subscribe(),w=N.channel("xp-summary-".concat(e.id)).on("postgres_changes",{event:"UPDATE",schema:"public",table:"user_xp",filter:"user_id=eq.".concat(e.id)},b=>{const x=b.new,E=b.old;E.current_level&&x.current_level>E.current_level&&d(0,"level_up",!0,x.current_level),_()}).subscribe(),v=N.channel("achievements-".concat(e.id)).on("postgres_changes",{event:"INSERT",schema:"public",table:"user_achievements",filter:"user_id=eq.".concat(e.id)},async b=>{const{achievement_id:x}=b.new,{data:E}=await N.from("achievements").select("id, display_name, description, rarity, xp_reward, icon_url").eq("id",x).single();E&&d(E.xp_reward||0,"achievement_unlocked",!1,void 0,E)}).subscribe();return()=>{N.removeChannel(f),N.removeChannel(w),N.removeChannel(v)}},[e,d,_]),n.jsx(Ms.Provider,{value:{xpSummary:r,loading:i,toasts:o,dismissToast:u,refreshXP:g},children:t})};function Xr(t){const e=[{maxLevel:1,name:"Newcomer",color:"#6B6560"},{maxLevel:2,name:"Apprentice",color:"#6B6560"},{maxLevel:3,name:"Trader",color:"#4ade80"},{maxLevel:4,name:"Analyst",color:"#4ade80"},{maxLevel:5,name:"Strategist",color:"#60a5fa"},{maxLevel:6,name:"Expert",color:"#60a5fa"},{maxLevel:7,name:"Veteran",color:"#a78bfa"},{maxLevel:8,name:"Master",color:"#a78bfa"},{maxLevel:9,name:"Elite",color:"#C9A96E"},{maxLevel:10,name:"Legend",color:"#C9A96E"}];if(t>=11)return{level:t,rankName:"Grandmaster",rankColor:"#B9F2FF"};const r=e.find(s=>s.maxLevel===t)||e[0];return{level:t,rankName:r.name,rankColor:r.color}}const xo={common:"#6B6560",uncommon:"#4ade80",rare:"#60a5fa",epic:"#a78bfa",legendary:"#C9A96E"};function Eo(){const t=vo(),e=t.xpSummary?Xr(t.xpSummary.current_level):Xr(1);return{...t,levelInfo:e}}function ko(){const{toasts:t,dismissToast:e}=Eo();return t.length===0?null:Js.createPortal(n.jsx("div",{className:"fixed top-20 right-4 z-[9999] flex flex-col gap-2.5 pointer-events-none",children:t.map((r,s)=>n.jsx(jo,{id:r.id,xp:r.xp,description:r.description,levelUp:r.levelUp,newLevel:r.newLevel,achievement:r.achievement,index:s,onDismiss:e},r.id))}),document.body)}function jo({id:t,xp:e,description:r,levelUp:s,newLevel:i,achievement:a,index:o,onDismiss:c}){const[l,u]=y.useState(!1),d=!!a,_=s||d;y.useEffect(()=>{const f=setTimeout(()=>u(!0),_?4e3:2500),w=setTimeout(()=>c(t),_?4400:2900);return()=>{clearTimeout(f),clearTimeout(w)}},[t,c,_]);const g=s?"#E6C88A":d&&xo[a.rarity]||"#C9A96E";return n.jsx("div",{className:"pointer-events-auto flex items-center gap-3 rounded-xl overflow-hidden",style:{padding:_?"14px 18px":"10px 16px",background:"rgba(17, 17, 17, 0.92)",backdropFilter:"blur(16px)",border:"1px solid ".concat(g).concat(_?"50":"20"),boxShadow:_?"0 0 30px ".concat(g,"25, 0 8px 32px rgba(0,0,0,0.5)"):"0 4px 20px rgba(0,0,0,0.4)",animation:l?"xp-toast-exit 0.4s ease-in forwards":"xp-toast-enter 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards",animationDelay:l?"0ms":"".concat(o*50,"ms"),opacity:0,transform:"translateX(40px)"},children:s?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"relative shrink-0",style:{width:42,he
2ight:42},children:[n.jsxs("svg",{width:"42",height:"42",viewBox:"0 0 42 42",className:"block",children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"toast-lvl-grad",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[n.jsx("stop",{offset:"0%",stopColor:"#C9A96E"}),n.jsx("stop",{offset:"100%",stopColor:"#E6C88A"})]})}),n.jsx("circle",{cx:"21",cy:"21",r:"18",fill:"none",stroke:"url(#toast-lvl-grad)",strokeWidth:"3",opacity:"0.3"}),n.jsx("circle",{cx:"21",cy:"21",r:"18",fill:"none",stroke:"url(#toast-lvl-grad)",strokeWidth:"3",strokeDasharray:2*Math.PI*18,strokeDashoffset:0,strokeLinecap:"round",className:"origin-center -rotate-90",style:{animation:"xp-ring-fill 0.8s ease-out 0.3s both"}})]}),n.jsx("span",{className:"absolute inset-0 flex items-center justify-center font-bold text-base",style:{color:"#E6C88A"},children:i})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-sm font-bold tracking-wide",style:{color:"#E6C88A"},children:"LEVEL UP"}),n.jsxs("p",{className:"text-xs",style:{color:"var(--fg-muted)"},children:["You reached level ",i]})]})]}):d?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"shrink-0 flex items-center justify-center rounded-lg text-lg",style:{width:42,he
2ight:42,background:"".concat(g,"15"),border:"2px solid ".concat(g,"40"),boxShadow:"0 0 12px ".concat(g,"20")},children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",children:n.jsx("path",{d:"M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6L12 2z",fill:g})})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] font-bold tracking-[0.15em] uppercase",style:{color:g},children:"Achievement Unlocked"}),n.jsx("p",{className:"text-sm font-semibold",style:{color:"var(--fg)"},children:a.display_name}),a.xp_reward>0&&n.jsxs("p",{className:"text-[11px]",style:{color:g},children:["+",a.xp_reward," XP"]})]})]}):n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"shrink-0 flex items-center justify-center rounded-lg font-bold text-xs",style:{width:36,height:36,background:"".concat(g,"15"),color:g,border:"1px solid ".concat(g,"25")},children:["+",e]}),n.jsxs("div",{children:[n.jsxs("p",{className:"text-sm font-semibold",style:{color:"var(--fg)"},children:["+",e," XP"]}),n.jsx("p",{className:"text-[11px]",style:{color:"var(--fg-dim)"},children:r})]})]})})}function Ao({children:t}){const{isAdmin:e}=ge();return e?n.jsxs(yo,{children:[t,n.jsx(ko,{})]}):n.jsx(n.Fragment,{children:t})}const So=3600*1e3;let Nt=0;async function Yr(){const t=Date.now();if(!(t-Nt<So)){Nt=t;try{await N.rpc("record_app_visit",{p_platform:"web"})}catch(e){Nt=0}}}function To(t){y.useEffect(()=>{if(!t)return;Yr();const e=()=>{document.visibilityState==="visible"&&Yr()};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[t])}const ye=({children:t})=>{const{user:e,authLoading:r,isFreeUser:s,hasActivePlan:i,isAdmin:a}=ge(),o=re();return r?n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-surface-elevated flex items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-bronze-600 mx-auto mb-4"}),n.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Loading..."})]})}):e?e&&(s||i||a)?n.jsx(n.Fragment,{children:t}):n.jsx(z,{to:"/payment-required",state:{from:o},replace:!0}):n.jsx(z,{to:"/payment-required",state:{from:o},replace:!0})},Po=({children:t})=>{const{user:e,authLoading:r,hasActivePlan:s,isAdmin:i}=ge(),a=re();return r?n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-surface-elevated flex items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-bronze-600 mx-auto mb-4"}),n.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Loading..."})]})}):e?!s&&!i?n.jsx(z,{to:"/payment-required",state:{from:a},replace:!0}):n.jsx(n.Fragment,{children:t}):n.jsx(z,{to:"/payment-required",state:{from:a},replace:!0})};/** 3 * @license lucide-react v0.525.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const Ro=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Oo=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,r,s)=>s?s.toUpperCase():r.toLowerCase()),Zr=t=>{const e=Oo(t);return e.charAt(0).toUpperCase()+e.slice(1)},Fs=(...t)=>t.filter((e,r,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===r).join(" ").trim(),Io=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};/** 8 * @license lucide-react v0.525.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */var Co={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** 13 * @license lucide-react v0.525.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const Do=y.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:a,iconNode:o,...c},l)=>y.createElement("svg",{ref:l,...Co,width:e,height:e,stroke:t,strokeWidth:s?Number(r)*24/Number(e):r,className:Fs("lucide",i),...!a&&!Io(c)&&{"aria-hidden":"true"},...c},[...o.map(([u,d])=>y.createElement(u,d)),...Array.isArray(a)?a:[a]]));/** 18 * @license lucide-react v0.525.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree. 22 */const le=(t,e)=>{const r=y.forwardRef(({className:s,...i},a)=>y.createElement(Do,{ref:a,iconNode:e,className:Fs("lucide-".concat(Ro(Zr(t))),"lucide-".concat(t),s),...i}));return r.displayName=Zr(t),r};
22/** 23 * @license lucide-react v0.525.0 - ISC 24 * 25 * This source code is licensed under the ISC license. 26 * See the LICENSE file in the root directory of this source tree. 27 */const Lo=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Qr=le("circle-alert",Lo);/** 28 * @license lucide-react v0.525.0 - ISC 29 * 30 * This source code is licensed under the ISC license. 31 * See the LICENSE file in the root directory of this source tree. 32 */const No=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],$o=le("credit-card",No);/** 33 * @license lucide-react v0.525.0 - ISC 34 * 35 * This source code is licensed under the ISC license. 36 * See the LICENSE file in the root directory of this source tree. 37 */const Uo=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Vo=le("eye-off",Uo);/** 38 * @license lucide-react v0.525.0 - ISC 39 * 40 * This source code is licensed under the ISC license. 41 * See the LICENSE file in the root directory of this source tree. 42 */const qo=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Bo=le("eye",qo);/** 43 * @license lucide-react v0.525.0 - ISC 44 * 45 * This source code is licensed under the ISC license. 46 * See the LICENSE file in the root directory of this source tree. 47 */const Mo=[["path",{d:"m10 17 5-5-5-5",key:"1bsop3"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}]],Fo=le("log-in",Mo);/** 48 * @license lucide-react v0.525.0 - ISC 49 * 50 * This source code is licensed under the ISC license. 51 * See the LICENSE file in the root directory of this source tree. 52 */const zo=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Go=le("lock",zo);/** 53 * @license lucide-react v0.525.0 - ISC 54 * 55 * This source code is licensed under the ISC license. 56 * See the LICENSE file in the root directory of this source tree. 57 */const Ko=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],Wo=le("log-out",Ko);/** 58 * @license lucide-react v0.525.0 - ISC 59 * 60 * This source code is licensed under the ISC license. 61 * See the LICENSE file in the root directory of this source tree. 62 */const Jo=[["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 18h16",key:"19g7jn"}],["path",{d:"M4 6h16",key:"1o0s65"}]],Ho=le("menu",Jo);/** 63 * @license lucide-react v0.525.0 - ISC 64 * 65 * This source code is licensed under the ISC license. 66 * See the LICENSE file in the root directory of this source tree. 67 */const Xo=[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]],Yo=le("message-circle",Xo);/** 68 * @license lucide-react v0.525.0 - ISC 69 * 70 * This source code is licensed under the ISC license. 71 * See the LICENSE file in the root directory of this source tree. 72 */const Zo=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Qo=le("refresh-cw",Zo);/** 73 * @license lucide-react v0.525.0 - ISC 74 * 75 * This source code is licensed under the ISC license. 76 * See the LICENSE file in the root directory of this source tree. 77 */const ec=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],tc=le("shopping-cart",ec);/** 78 * @license lucide-react v0.525.0 - ISC 79 * 80 * This source code is licensed under the ISC license. 81 * See the LICENSE file in the root directory of this source tree. 82 */const rc=[["path",{d:"M18 6 6 18",key:"1bl5f8"}
82],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],ur=le("x",rc);function sc(){const t=new URL(window.location.href),e=t.searchParams;e.delete("via"),e.delete("ref"),e.delete("referral"),e.delete("affiliate"),e.delete("partner"),window.history.replaceState({},"",t.pathname+t.search)}function nc(){typeof window<"u"&&window.addEventListener("Rewardful.initialized",function(){var e;const t=((e=window.Rewardful)==null?void 0:e.referral)||null;t&&console.log("Referral tracking initialized with official API:",t)})}const ic=({isOpen:t,onClose:e,prefilledEmail:r,variant:s="dark",onSuccess:i})=>{const a=s==="light",[o,c]=y.useState(""),[l,u]=y.useState(""),[d,_]=y.useState(!1),[g,f]=y.useState(""),[w,v]=y.useState(!1),[b,x]=y.useState(!1),{language:E}=fo(),{signIn:k}=ge();if(y.useEffect(()=>{c(r!=null?r:"")},[r,t]),!t)return null;const A=()=>!o||!l?(f(E==="en"?"Please fill in all fields":"Bitte alle Felder ausfüllen"),!1):l.length<6?(f(E==="en"?"Password must be at least 6 characters":"Passwort muss mindestens 6 Zeichen lang sein"),!1):!0,q=async C=>{if(C.preventDefault(),f(""),!!A()){v(!0);try{await k(o,l),sc(),e(),i==null||i()}catch(G){f(G.message||(E==="en"?"An error occurred. Please try again.":"Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut."))}finally{v(!1)}}},R=async()=>{f(""),v(!0);try{const{error:C}=await N.auth.signInWithOAuth({provider:"google",options:{redirectTo:window.location.origin+"/dashboard"}});C&&f(C.message||(E==="en"?"Google login failed":"Google-Anmeldung fehlgeschlagen"))}catch(C){f(E==="en"?"Google login failed. Please try again.":"Google-Anmeldung fehlgeschlagen. Bitte versuchen Sie es erneut.")}finally{v(!1)}},D=async()=>{if(f(""),x(!1),!o||!o.includes("@")){f(E==="en"?"Please enter your email address first.":"Bitte gib zuerst deine E-Mail-Adresse ein.");return}v(!0);const{error:C}=await N.auth.resetPasswordForEmail(o,{redirectTo:"https://".concat(O.domain,"/reset-password")});v(!1),C?f(E==="en"?"Could not send reset email. Please try again.":"E-Mail zum Zurücksetzen konnte nicht gesendet werden. Bitte versuche es erneut."):x(!0)};return n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[n.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:e}),n.jsxs("div",{className:"relative rounded-2xl w-full max-w-md p-6 shadow-xl",style:{backgroundColor:a?"#FAF8F4":O.colors.bgSurface},children:[n.jsx("button",{onClick:e,className:"absolute right-4 top-4 transition-colors ".concat(a?"text-gray-400 hover:text-gray-700":"text-gray-400 hover:text-white"),children:n.jsx(ur,{className:"h-5 w-5"})}),n.jsx("h2",{className:"text-2xl font-bold text-center mb-8 ".concat(a?"text-[#1A1714]":"text-white"),children:E==="en"?"Log In":"Anmelden"}),g&&n.jsxs("div",{className:"mb-6 p-4 rounded-lg flex items-start bg-red-500/10 text-red-500",children:[n.jsx(Qr,{className:"h-5 w-5 mt-0.5 mr-2 flex-shrink-0"}),n.jsx("span",{children:g})]}),b&&n.jsxs("div",{className:"mb-6 p-4 rounded-lg flex items-start bg-green-500/10 text-green-600",children:[n.jsx(Qr,{className:"h-5 w-5 mt-0.5 mr-2 flex-shrink-0"}),n.jsx("span",{children:E==="en"?"Password reset email sent! Please check your inbox.":"E-Mail zum Zurücksetzen des Passworts wurde gesendet! Bitte prüfe dein Postfach."})]}),n.jsxs("form",{onSubmit:q,className:"space-y-6",children:[n.jsxs("div",{children:[n.jsx("label",{htmlFor:"login-email",className:"block text-sm font-medium mb-2 ".concat(a?"text-gray-600":"text-gray-300"),children:E==="en"?"Email Address":"E-Mail-Adresse"}),n.jsx("input",{type:"email",id:"login-email",value:o,onChange:C=>c(C.target.value),className:"w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:border-transparent ".concat(a?"bg-white border-[#C9A96E]/30 text-[#1A1714] placeholder-gray-400 focus:ring-[#C9A96E]/50":"border-white/10 text-white placeholder-gray-400"),style:a?void 0:{backgroundColor:O.colors.bgElevated,"--tw-ring-color":O.colors.primary},placeholder:E==="en"?"Enter your email address...":"E-Mail-Adresse eingeben..."})]}),n.jsxs("div",{children:[n.jsx("label",{htmlFor:"password",className:"block text-sm font-medium mb-2 ".concat(a?"text-gray-600":"text-gray-300"),children:E==="en"?"Password":"Passwort"}),n.jsxs("div",{className:"relative",children:[n.jsx("input",{type:d?"text":"password",id:"password",value:l,onCh
82ange:C=>u(C.target.value),className:"w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:border-transparent pr-10 ".concat(a?"bg-white border-[#C9A96E]/30 text-[#1A1714] placeholder-gray-400 focus:ring-[#C9A96E]/50":"border-white/10 text-white placeholder-gray-400"),style:a?void 0:{backgroundColor:O.colors.bgElevated,"--tw-ring-color":O.colors.primary},placeholder:E==="en"?"Enter your password...":"Passwort eingeben..."}),n.jsx("button",{type:"button",onClick:()=>_(!d),className:"absolute right-3 top-1/2 transform -translate-y-1/2 transition-colors ".concat(a?"text-gray-400 hover:text-gray-700":"text-gray-400 hover:text-white"),children:d?n.jsx(Vo,{className:"h-5 w-5"}):n.jsx(Bo,{className:"h-5 w-5"})})]})]}),n.jsx("button",{type:"submit",disabled:w,className:"w-full py-2 px-4 text-white rounded-lg font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed",style:{background:"linear-gradient(135deg, ".concat(O.colors.primaryDark," 0%, ").concat(O.colors.primary," 50%, ").concat(O.colors.primaryLight," 100%)")},children:w?E==="en"?"Logging in...":"Anmeldung läuft...":E==="en"?"Log In":"Anmelden"})]}),n.jsxs("div",{className:"relative my-6",children:[n.jsx("div",{className:"absolute inset-0 flex items-center",children:n.jsx("div",{className:"w-full border-t ".concat(a?"border-gray-200":"border-gray-700")})}),n.jsx("div",{className:"relative flex justify-center text-sm",children:n.jsx("span",{className:"px-2 text-gray-400",style:{backgroundColor:a?"#FAF8F4":O.colors.bgSurface},children:E==="en"?"Or continue with":"Oder fortfahren mit"})})]}),n.jsxs("button",{type:"button",onClick:R,disabled:w,className:"w-full py-2 px-4 rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 ".concat(a?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50":"bg-white text-gray-900 hover:bg-gray-100"),children:[n.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",children:[n.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),n.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),n.jsx("path",{fill:"#FBBC05",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),n.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),w?E==="en"?"Signing in...":"Anmeldung läuft...":E==="en"?"Sign in with Google":"Mit Google anmelden"]}),n.jsx("button",{type:"button",onClick:D,className:"w-full mt-4 text-sm hover:underline",style:{color:O.colors.primaryLight},disabled:w,children:E==="en"?"Forgot password?":"Passwort vergessen?"})]})]})},ac={starter_depot:{name:"Starter Depot",desc:"ETF-Portfolio, Krypto, Anleihen & Strategie â dein vollständiger Einstiegsguide für den Aufbau deines ersten Portfolios.",guideType:"etf_upgrade",price:"â¬8,99"},junior_depot:{name:"Junior-Depot",desc:"Schritt-für-Schritt Anleitung für das Kinderdepot â von der Sparrate bis zur ETF-Auswahl für dein Kind.",guideType:"etf_upgrade",price:"â¬8,99"}},oc=({missingDepot:t,onClose:e})=>{const[r,s]=y.useState(!1),[i,a]=y.useState(null),o=ac[t],c=async()=>{s(!0),a(null);try{const{data:{session:l}}=await N.auth.getSession();if(!(l!=null&&l.access_token))throw new Error("No session");const d=await(await fetch("https://bsmvcmmwkmaqpgrmvjql.supabase.co/functions/v1/create-depot-checkout",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(l.access_token)},body:JSON.stringify({guide_type:o.guideType})})).json();d.url?window.location.href=d.url:a("Checkout konnte nicht gestartet werden. Bitte versuche es erneut.")}catch(l){a("Checkout konnte nicht gestartet werden. Bitte versuche es erneut.")}finally{s(!1)}};return n.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center p-4",children:[n.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm",onClick:e}),n.jsxs("div",{className:"relative bg-white rounded-2xl shadow-2xl max-w-sm w-full p-6 border border-[#C9A96E]/20",children:[n.jsx("button",{onClick:e,className:"absolute top-4 right-4 p-1.5 rounded-full hover:bg-gray-100 transition-colors",children:n.jsx(ur,{className:"w-4 h-4 text-gray-400"})}),n.jsx("div",{className:"flex items-center justify-center w-12 h-12 rounded-2xl bg-amber-50 border border-amber-200 mb-4",children:n.jsx(Go,{className:"w-5 h-5 text-[#C9A96E]"})}),n.jsxs("h2",{className:"text-base font-bold text-gray-900 mb-1",children:[o.name," nicht enthalten"]}),n.jsx("p",{className:"text-sm text-gray-500 mb-4 leading-relaxed",children:o.desc}),i&&n.jsx("p",{className:"text-xs text-red-500 mb-4",children:i}),n.jsxs("button",{onClick:c,disabled:r,className:"w-full flex items-center justify-center gap-2 py-3 px-5 rounded-xl bg-[#C9A96E] text-[#0A0A0A] font-semibold text-sm hover:bg-[#d4b47a] transition-colors disabled:opacity-60",children:[r?n.jsx("div",{className:"w-4 h-4 border-2 border-[#0A0A0A]/30 border-t-[#0A0A0A] rounded-full animate-spin"}
82):n.jsx(tc,{className:"w-4 h-4"}),o.name," hinzufügen â ",o.price," einmalig"]})]})]})},cc=()=>{const{user:t,signOut:e,isAdmin:r,hasStarterGuide:s,hasJuniorGuide:i,hasRebalancing:a}=ge(),[o,c]=y.useState(!1),[l,u]=y.useState(null),[d,_]=y.useState(!1),[g,f]=y.useState(!1),w=y.useRef(null),v=re(),b=cs(),x=v.pathname.startsWith("/beginner-guide"),E=v.pathname.startsWith("/junior-depot-guide");y.useEffect(()=>{const C=G=>{w.current&&!w.current.contains(G.target)&&_(!1)};return d&&document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[d]),y.useEffect(()=>{_(!1)},[v.pathname]);const k=async()=>{_(!1);try{await e()}catch(C){}},A=C=>{C==="starter"?s||r?b("/beginner-guide"):u("starter_depot"):i||r?b("/junior-depot-guide/warum"):u("junior_depot")},q=async()=>{if(t!=null&&t.email){f(!0),_(!1);try{const{data:{session:C}}=await N.auth.getSession(),Je=await(await fetch("https://bsmvcmmwkmaqpgrmvjql.supabase.co/functions/v1/create-portal-session",{method:"POST",headers:{"Content-Type":"application/json",...C!=null&&C.access_token?{Authorization:"Bearer ".concat(C.access_token)}:{}},body:JSON.stringify({email:t.email,brand:"cradermind"})})).json();Je.url&&(window.location.href=Je.url)}finally{f(!1)}}},R=E?"/junior-depot-guide/rebalancing":"/beginner-guide/rebalancing",D=E?"/junior-depot-guide/fragen":"/beginner-guide/fragen";return n.jsxs(n.Fragment,{children:[n.jsx("header",{className:"w-full border-b border-[#C9A96E]/20 bg-[#FAF8F4]/95 backdrop-blur-sm sticky top-0 z-50",children:n.jsxs("div",{className:"max-w-6xl mx-auto px-4 h-14 flex items-center justify-between gap-4 w-full",children:[n.jsxs("div",{className:"flex items-center gap-0.5 p-1 rounded-xl bg-[#EDE8DF] border border-[#C9A96E]/20",children:[n.jsx("button",{onClick:()=>A("starter"),className:"px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all whitespace-nowrap ".concat(x?"bg-[#C9A96E] text-[#0A0A0A] shadow-sm":"text-[#7A6540] hover:text-[#5A4520]"),children:"Starter Depot"}),n.jsx("button",{onClick:()=>A("junior"),className:"px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all whitespace-nowrap ".concat(E?"bg-[#C9A96E] text-[#0A0A0A] shadow-sm":"text-[#7A6540] hover:text-[#5A4520]"),children:"Junior-Depot"})]}),t?n.jsxs("div",{className:"relative flex-shrink-0",ref:w,children:[n.jsx("button",{onClick:()=>_(C=>!C),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-[#C9A96E]/40 hover:bg-[#C9A96E]/10 transition-colors text-[#7A6540]","aria-label":"Menü öffnen",children:d?n.jsx(ur,{className:"w-4 h-4"}):n.jsx(Ho,{className:"w-4 h-4"})}),d&&n.jsxs("div",{className:"absolute right-0 top-full mt-2 w-64 bg-white rounded-2xl shadow-xl border border-[#C9A96E]/20 overflow-hidden z-50",children:[n.jsxs("div",{className:"px-4 py-3 border-b border-gray-100 bg-[#FAF8F4]",children:[n.jsx("p",{className:"text-xs text-gray-400 mb-0.5",children:"Eingeloggt als"}),n.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",children:t.email})]}),n.jsxs("div",{className:"py-1.5",children:[n.jsxs(gr,{to:R,className:"flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-[#FAF8F4] transition-colors",children:[n.jsx(Qo,{className:"w-4 h-4 text-[#C9A96E] flex-shrink-0"}),"Rebalancing"]}),n.jsxs(gr,{to:D,className:"flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-[#FAF8F4] transition-colors",children:[n.jsx(Yo,{className:"w-4 h-4 text-[#C9A96E] flex-shrink-0"}),"Fragen & Support"]}),(a||r)&&n.jsxs("button",{onClick:q,disabled:g,className:"w-full flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-[#FAF8F4] transition-colors disabled:opacity-50",children:[n.jsx($o,{className:"w-4 h-4 text-[#C9A96E] flex-shrink-0"}),g?"Weiterleitung â¦":"Abo verwalten"]}),n.jsx("div",{className:"mx-4 my-1.5 border-t border-gray-100"}),n.jsxs("button",{onClick:k,className:"w-full flex items-center gap-3 px-4 py-2.5 text-sm text-red-500 hover:bg-red-50 transition-colors",children:[n.jsx(Wo,{className:"w-4 h-4 flex-shrink-0"}),"Abmelden"]})]})]})]}):n.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-[#C9A96E]/40 hover:bg-[#C9A96E]/10 transition-colors text-sm text-[#7A6540] flex-shrink-0",children:[n.jsx(Fo,{className:"w-3.5 h-3.5"}),n.jsx("span",{children:"Einloggen"})]})]})}),n.jsx(ic,{isOpen:o,onClose:()=>c(!1),variant:"light"}),l&&n.jsx(oc,{missingDepot:l,onClose:()=>u(null)})]})},es={starter_depot:"/finanzguide",junior_depot:"/finanzguide"},X=({children:t,guideType:e})=>{const{user:r,isAdmin:s,authLoading:i,hasStarterGuide:a,hasJuniorGuide:o}
82=ge(),c=re();return i?n.jsx("div",{className:"min-h-screen bg-[#FAF8F4] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-10 w-10 border-b-2 border-[#C9A96E]"})}):r?!(e==="starter_depot"?a:o)&&!s?n.jsx(z,{to:es[e],replace:!0}):n.jsxs(n.Fragment,{children:[n.jsx(cc,{}),t]}):n.jsx(z,{to:es[e],state:{from:c,openLogin:!0},replace:!0})},lc=t=>{const e="https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/coins/Coin_Icons",r=t.toUpperCase(),i={GOLD:"XAU",SILVER:"XAG",SILBER:"XAG"}[r]||r,a={SPX:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/34.svg",NDX:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/35.svg",COIN:"".concat(e,"/coinbase.png"),META:"".concat(e,"/meta.jpg"),HOOD:"".concat(e,"/robinhood.png"),AMZN:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/amzn.png",ARM:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/arm.png",GOOGL:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/googl.webp",INTC:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/intel.jpg",MSFT:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/msft.png",TSLA:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/tsla.png",APP:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/APP_LOVIN.png"};if(a[i])return a[i];const o={XAU:"XAU.png",XAG:"XAG.png",NATGAS:"GAS%20(1).png",BRENT:"Brent%20Oil.png",WTI:"WTI.jpeg",COFFEE:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/coffee.png",GASOLINE:"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/images/gasoline.png"};if(o[i]){const c=o[i];return c.startsWith("http")?c:"".concat(e,"/").concat(c)}return"".concat(e,"/").concat(i,".png")};function uc({message:t,link:e,symbol:r,type:s,image_url:i,onClose:a}){const o=cs(),c=s==="event"?"https://bsmvcmmwkmaqpgrmvjql.supabase.co/storage/v1/object/public/events/Design%20ohne%20Titel%20(5).png":i||(r?lc(r):null),l=()=>{e&&(a(),e.startsWith("/")?o(e):window.open(e,"_blank"))};return n.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 backdrop-blur-sm",children:n.jsxs("div",{className:"relative w-[90%] max-w-md bg-white dark:bg-[#0A0A0A] text-black dark:text-white p-6 rounded-xl shadow-xl border border-gray-300 dark:border-gray-700 transform transition-all duration-300 hover:scale-[1.02] ".concat(e?"cursor-pointer":""),onClick:l,children:[n.jsx("button",{onClick:u=>{u.stopPropagation(),a()},className:"absolute top-2 right-3 text-xl text-gray-500 hover:text-gray-300 dark:text-gray-300 dark:hover:text-white transition-colors","aria-label":"SchlieÃen",children:"Ã"}),n.jsxs("div",{className:"flex flex-col items-center gap-4",children:[s==="livestream"||s==="gann-stammtisch"?n.jsx("div",{className:"w-16 h-16 flex items-center justify-center bg-red-500 rounded-full border border-gray-400 dark:border-gray-600",children:n.jsx("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"white",xmlns:"http://www.w3.org/2000/svg",children:n.jsx("path",{d:"M8 5v14l11-7z"})})}):s==="news"?n.jsx("div",{className:"w-16 h-16 flex items-center justify-center text-4xl bg-surface-elevated rounded-full border border-gray-400 dark:border-gray-600",children:"ð°"}):c?n.jsx("img",{src:c,alt:r,className:"w-16 h-16 rounded-full border border-gray-400 dark:border-gray-600",onError:u=>{const d=u.target;d.src="https://placehold.co/64x64?text=?"}}):null,n.jsx("h2",{className:"text-lg font-semibold text-center",children:t}),e&&n.jsx("button",{onClick:u=>{u.stopPropagation(),a(),e.startsWith("/")?o(e):window.open(e,"_blank")},className:"mt-2 bg-surface-elevated hover:bg-surface-elevated text-white px-4 py-2 rounded-md transition-all",children:"Jetzt öffnen"})]})]})})}function dc(){const[t,e]=y.useState(null),r=re();return y.useEffect(()=>{const s=N.channel("notifications-global").on("postgres_changes",{event:"INSERT",schema:"public",table:"notifications"},i=>{const{message:a,link:o,symbol:c,type:l,image_url:u}=i.new;if(l==="livestream"||l==="gann-stammtisch"||l==="smallcap_update")return;const d=i.new.brand;d&&d!=="cradermind"||e({msg:a,link:o,symbol:c,type:l,image_url:u})}).subscribe();return()=>{N.removeChannel(s)}},[]),r.pathname==="/"?null:t&&n.jsx(uc,{message:t.msg,link:t.link,symbol:t.symbol,type:t.type,image_url:t.image_url,onClose:()=>e(null)})}function hc(){const{pathname:t}=re();return y.useEffect(()=>{window.scrollTo(0,0)},[t]),null}function fc(){const t=re(),{user:e,authLoading:r}=ge(),s=y.useRef(null);y.useEffect(()=>{s.current&&(clearTimeout(s.current),s.current=null);const i=new URLSearchParams(window.location.search),a=i.get("via")||i.get("ref")||i.get("referral");if(a)localStorage.setItem("rewardful_via",a),e&&!r&&(s.current=setTimeout(()=>{const o=new URLSearchParams(window.location.search);o.delete("via"),o.delete("ref"),o.delete("referral");const c=o.toString()?"".concat(window.location.pathname,"?").concat(o.toString()):window.location.pathname;window.history.replaceState({},"",c)},1e3));else if(!e&&!r){const o=localStorage.getItem("rewardful_via");if(o){const c=new URLSearchParams(window.location.search);c.set("via",o);const l=window.location.pathname+"?"+c.toString();window.history.replaceState({},"",l)}}return()=>{s.current&&(clearTimeout(s.current),s.current=null)}},[t,e,r])}function mc(){const t=new URLSearchParams(window.location.search);return t.get("invite")||t.get("ref")||null}function pc(t){localStorage.setItem("cm_referral_code",t)}function gc(){y.useEffect(()=>{const t=mc();t&&pc(t)},[])}let $t=new Set,er=null;const zd=()=>er,_c=()=>{try{return me.hasAnalyticsConsent()}catch(t){return!1}};function ts(t,e){if(_c())try{N.from("seiten_ereignisse").insert({art:t,knopf:e,pfad:window.location.pathname,besucher:cr()}).then(void 0,()=>{})}catch(r){}}function wc(){const{pathname:t}=re();y.useEffect(()=>{if($t=new Set,er=null,typeof IntersectionObserver>"u")return;const e=new IntersectionObserver(a=>{for(const o of a){if(!o.isIntersecting)continue;const c=o.target.dataset.knopf;e.unobserve(o.target),!(!c||$t.has(c))&&($t.add(c),er=c,ts("sicht",c))}},{threshold:.5}),r=()=>{document.querySelectorAll("[data-knopf]:not([data-knopf-gesehen])").forEach(a=>{a.dataset.knopfGesehen="1",e.observe(a)})};r();const s=new MutationObserver(r);s.observe(document.body,{childList:!0,subtree:!0});const i=a=>{var l,u;const o=(u=(l=a.target)==null?void 0:l.closest)==null?void 0:u.call(l,"[data-knopf]"),c=o==null?void 0:o.dataset.knopf;c&&ts("klick",c)};return document.addEventListener("click",i,{capture:!0,passive:!0}),()=>{e.disconnect(),s.disconnect(),document.removeEventListener("click",i,{capture:!0}),document.querySelectorAll("[data-knopf-gesehen]").forEach(a=>delete a.dataset.knopfGesehen)}},[t])}const vc=p(()=>m(()=>import("./Navbar-6P9PnqFU.js"),[])),bc=p(()=>m(()=>import("./CookieBanner-Bff27kTh.js"),[])),yc=p(()=>m(()=>import("./UpgradePromoModal-Dw2TzShs.js"),[])),xc=p(()=>m(()=>import("./Footer-Dj0SrRjf.js"),[])),Ec=p(()=>m(()=>import("./GoldCartDrawer-CtM3NH6k.js"),[])),Z=({zu:t})=>{const{search:e,hash:r}=re();return n.jsx(z,{to:"".concat(t).concat(e).concat(r),replace:!0})},kc=p(()=>m(()=>
82import("./FloatingChat-Bb67fYT5.js"),[])),jc=p(()=>m(()=>import("./FloatingCalculator-CNkWB-_s.js"),[])),Ac=p(()=>m(()=>import("./LivestreamNotificationPopup-PRIA4Bx2.js"),[])),Sc=p(()=>m(()=>import("./AffiliateLandingPage-DMPUIArx.js"),[])),Tc=p(()=>m(()=>import("./Dashboard-CWbH6lQ_.js"),__vite__mapDeps([0]))),Pc=p(()=>m(()=>import("./MarketOverview-BL0wdQNm.js"),[])),Rc=p(()=>m(()=>import("./PrivacyPolicy-BV_Jp2MN.js"),[])),Oc=p(()=>m(()=>import("./Impressum-DfEu1ilC.js"),[])),Ic=p(()=>m(()=>import("./Terms-FD2RlRbF.js"),[])),Cc=p(()=>m(()=>import("./Signals-BycsQWEw.js"),[])),Dc=p(()=>m(()=>import("./Education-BuObb2hW.js"),[])),Lc=p(()=>m(()=>import("./Akademie-BxbzBZ5h.js"),[])),Nc=p(()=>m(()=>import("./Analysis-X8GrZkKM.js"),[])),$c=p(()=>m(()=>import("./Tools-BIvMWQLv.js"),[])),Uc=p(()=>m(()=>import("./AIAssistant-6zg_asVT.js"),[])),Vc=p(()=>m(()=>import("./Community-Y6SQAefx.js"),[])),rs=p(()=>m(()=>import("./Messages-DHqRYh2v.js"),[])),qc=p(()=>m(()=>import("./Library-BArpr09S.js"),[])),Bc=p(()=>m(()=>import("./Timeframes-DBuI09oa.js"),[])),Mc=p(()=>m(()=>import("./NewsAdmin-Bis5AyvJ.js"),[])),Fc=p(()=>m(()=>import("./NavarinoAdmin-Du5km_lP.js"),[])),zc=p(()=>m(()=>import("./Reports-3JCEAoKt.js"),[])),Gc=p(()=>m(()=>import("./LivestreamAdmin-DIVoflSI.js"),[])),Kc=p(()=>m(()=>import("./BadgeAdmin-BjS7_VZH.js"),[])),Wc=p(()=>m(()=>import("./JournalAccessAdmin-jDD0AtVQ.js"),[])),Jc=p(()=>m(()=>import("./InternalAnalysisAccessAdmin-Bcm81TnI.js"),[])),Hc=p(()=>m(()=>import("./InternalAnalysisTool-sDB6rEGM.js"),[])),Xc=p(()=>m(()=>import("./RetreatAccessAdmin-d7EneZrM.js"),[])),Yc=p(()=>m(()=>import("./Retreat2026Admin-BW1nVT2y.js"),[])),Zc=p(()=>m(()=>import("./TradingRetreatAdmin-BMdy8GqL.js"),[])),Qc=p(()=>m(()=>import("./PortfolioAccessAdmin-1NMO6I5N.js"),[])),el=p(()=>m(()=>import("./ContestAdmin-B4jNvsUt.js"),[])),tl=p(()=>m(()=>import("./EventsAdmin-BUB52Jur.js"),[])),rl=p(()=>m(()=>import("./FomcBingoAdmin-B4syJz0s.js"),[])),sl=p(()=>m(()=>import("./FomcBingo-3ww3zyJE.js"),[])),nl=p(()=>m(()=>import("./GoldShopAdmin-cxtd9KCy.js"),[])),il=p(()=>m(()=>import("./GoldShop-83lCJECB.js"),[])),al=p(()=>m(()=>import("./GoldProductDetail-CyRFHnMy.js"),[])),ol=p(()=>m(()=>import("./GoldCartPage-fKT9Q0aa.js"),[])),cl=p(()=>m(()=>import("./ExchangeAdmin-Dgsc8Ntb.js"),[])),ll=p(()=>m(()=>import("./DailyReportAdmin--4KtBv9G.js"),[])),ul=p(()=>m(()=>import("./index-DqeQqij_.js"),[])),dl=p(()=>m(()=>import("./CustomerDetail-BtrSOxSJ.js"),[])),hl=p(()=>m(()=>import("./ChartOfTheDayAdmin-Dv9u4jRA.js"),[])),fl=p(()=>m(()=>import("./index-DZ4tS8pk.js"),[])),ml=p(()=>m(()=>import("./NewsletterAdmin-BxfpDxsa.js"),[])),pl=p(()=>m(()=>import("./FlowchartAdmin-Dvz_aK7A.js"),[])),gl=p(()=>m(()=>import("./OpsAdmin-CB7s1XUa.js"),[])),_l=p(()=>m(()=>import("./AdminHub-DvJne7Jr.js"),[])),wl=p(()=>m(()=>import("./XPDashboard-DYy6-4zl.js"),[])),vl=p(()=>m(()=>import("./Webinars-pVmRUd9O.js"),[])),bl=p(()=>m(()=>import("./WebinarDetailPage-BCUyNuQD.js").then(t=>t.W),[])),yl=p(()=>m(()=>import("./WebinarHealthCheckPage-_KMLuO2O.js"),[])),xl=p(()=>m(()=>import("./WebinarAccess-Df-mzgbo.js"),[])),El=p(()=>m(()=>import("./WebinarTopicsAdmin-D3K8YWek.js"),[])),kl=p(()=>m(()=>import("./TradingRetreat-g65LigxP.js"),[])),jl=p(()=>m(()=>import("./TradingContest-L4jLe174.js"),[])),Al=p(()=>m(()=>import("./DailyCoinAnalysis-DLnFw8Mg.js"),[])),Sl=p(()=>m(()=>import("./TradingIdeas-CVAALXwI.js"),[])),Tl=p(()=>m(()=>import("./ActiveTrades-E2KM9a2u.js"),[])),Pl=p(()=>m(()=>import("./TradingJournal-DCYVCQeu.js"),[])),Rl=p(()=>m(()=>import("./TradingJournalNew-ntXYyt8j.js").then(t=>t.a),[])),Ol=p(()=>m(()=>import("./TradeDetail-CD6-qTbU.js"),[])),Il=p(()=>m(()=>import("./TradeDetailNew-C6qaT_1K.js"),[])),Cl=p(()=>m(()=>import("./PortfolioTracker-e5-3qpxm.js"),[])),Dl=p(()=>m(()=>import("./Compounding-D94Co0A1.js"),[])),Ll=p(()=>m(()=>import("./LiveCharts-D6iIDiSL.js"),[])),Nl=p(()=>m(()=>import("./Spot-zipqkAKa.js"),[])),$l=p(()=>m(()=>import("./Affiliate-7P4IO7Lg.js"),[])),Ul=p(()=>m(()=>import("./ReferralProgram-NwAkhv3h.js"),[])),Vl=p(()=>m(()=>import("./AppFramework-Cs7qA0kp.js"),[])),ql=p(()=>m(()=>import("./Calendar-D491jFTl.js"),[])),Bl=p(()=>m(()=>import("./Roadmap-CtsKMz5M.js"),[])),Ml=p(()=>m(()=>import("./CoinDetailPage-CLqzhq3U.js"),[])),Fl=p(()=>m(()=>import("./StockDetailPage-BJgj6KK9.js"),[])),zl=p(()=>m(()=>import("./CommodityDetailPage-CT_hrqZS.js"),[])),Gl=p(()=>m(()=>import("./ETF-DgUejf1x.js"),[])),Kl=p(()=>m(()=>import("./ChartOfTheDay-MFaN0wBO.js"),[])),Wl=p(()=>m(()=>import("./ChartOfTheDayLeaderboard-_qY6WGX2.js"),[])),Jl=p(()=>m(()=>import("./GuessThePrice-DxlnsXTK.js"),[])),Hl=p(()=>m(()=>import("./PaymentRequired-BfxCi1St.js"),[])),Xl=p(()=>m(()=>import("./PaymentFailed-BZCnF9q-.js"),[])),ss=p(()=>m(()=>import("./Success-CNLjdy2h.js"),[])),ns=p(()=>m(()=>import("./Profile-DSSYmcMi.js"),[])),Yl=p(()=>m(()=>import("./Discover-TfMNhK3X.js"),[])),Zl=p(()=>m(()=>import("./ResetPassword-BsGc2f0p.js"),[])),Ql=p(()=>m(()=>import("./GetFunded-BC3_Ud2J.js"),[])),eu=p(()=>m(()=>import("./DiscoverUsers-DW1MCihQ.js"),[])),tu=p(()=>m(()=>import("./DogRescue-RVSyvXCA.js"),[])),ru=p(()=>m(()=>import("./NewsletterThankYou-B0MzzLbk.js"),[])),su=p(()=>m(()=>import("./ConfirmNewsletter-DQb-e3eM.js"),[])),nu=p(()=>m(()=>import("./Unsubscribe-BJBHD7Pt.js"),[])),iu=p(()=>m(()=>import("./JoinTelegram-DQh4S5xw.js"),[])),au=p(()=>m(()=>import("./InviteSignup-BUxTpEbK.js"),[])),ou=p(()=>m(()=>import("./InviteJoin-BTO08fA_.js"),[])),cu=p(()=>m(()=>import("./InviteConfirm-D6UO5fgC.js"),[])),lu=p(()=>m(()=>import("./InviteContest-B1t8DkaG.js"),[])),uu=p(()=>m(()=>import("./Goals-BA1nVZKj.js"),[])),du=p(()=>m(()=>import("./BacktestingTool-DtJmvbfj.js").then(t=>t.a),[])),hu=p(()=>m(()=>import("./JitsiMeeting-D8U5OukE.js"),[])),fu=p(()=>m(()=>import("./JuniorDepotWhy-CE3K2OdM.js"),[])),mu=p(()=>m(()=>import("./JuniorDepotGuide-Dp3JZ2Gx.js"),[])),pu=p(()=>m(()=>import("./JuniorDepotOwnership-BSj5Mh3G.js"),[])),gu=p(()=>m(()=>import("./JuniorDepotRechtsstart-DEbXMUx6.js"),[])),_u=p(()=>m(()=>import("./JuniorDepotOpenAccount-1OgiX4rx.js"),[])),wu=p(()=>m(()=>import("./JuniorDepotETFs-DhP5YDGj.js"),[])),vu=p(()=>m(()=>import("./JuniorDepotSparrate-BO14a6we.js"),[])),bu=p(()=>m(()=>import("./JuniorDepotFragen-D0C9TDQW.js"),[])),yu=p(()=>m(()=>import("./NewsletterErfolge-aAM_pZgO.js"),[]));p(()=>m(()=>import("./BeginnerGuideLandingEmotion-Cp8-JGnf.js"),[]));const xu=p(()=>m(()=>import("./BeginnerGuideHub-iiUFDYKx.js"),[])),Eu=p(()=>m(()=>import("./BeginnerGuideBudget-BZ0-Tryk.js"),[])),ku=p(()=>m(()=>import("./BeginnerGuideETF-fx4c5-RZ.js"),[])),ju=p(()=>m(()=>import("./BeginnerGuideCrypto-_XTVNP5T.js"),[])),Au=p(()=>m(()=>import("./BeginnerGuideAnleihen-CSskr82R.js"),[])),Su=p(()=>m(()=>import("./BeginnerGuideStrategie-CqlWTrI4.js"),[])),Tu=p(()=>m(()=>import("./BeginnerGuideDepot-ChFr9nUP.js"),[])),Pu=p(()=>m(()=>import("./BeginnerGuideFragen-CpUKBv8F.js"),[])),Ru=p(()=>m(()=>import("./BeginnerGuideRebalancing-Cn4hRnhA.js"),[])),Ou=p(()=>m(()=>import("./JuniorDepotRebalancing-Cb22iHr4.js"),[]));p(()=>m(()=>import("./SparplanFinder-COYvnV4y.js"),[]));p(()=>m(()=>import("./PortfolioSchnellcheck-BXmlz58i.js"),[]));p(()=>m(()=>import("./JuniorDepotLanding-DUBaTzgZ.js"),[]));const Iu=p(()=>m(()=>import("./MethodeNeu-DVVrW1b_.js"),[])),Cu=p(()=>m(()=>import("./EinsZuEins-CJ0rAXdO.js"),[])),Du=p(()=>m(()=>import("./PricingNeu-KE7JCusf.js"),[])),Lu=p(()=>m(()=>import("./EventsNeu-0Y7MgHG3.js"),[])),Nu=p(()=>m(()=>import("./EventDanke-m4ukQVnA.js"),[])),$u=p(()=>m(()=>import("./FinanzguideNeu-DotYIkgY.js"),[])),Uu=p(()=>m(()=>import("./CoachingNeu-BEPuIRkS.js"),[])),Vu=p(()=>m(()=>import("./KartenTest-edo0DOxt.js"),[])),qu=p(()=>m(()=>import("./RetreatNeu-BJygy0fg.js"),[])),Bu=p(()=>m(()=>import("./TrackRecordNeu-Dmu2ED6m.js"),[])),Mu=p(()=>m(()=>import("./LinksNeu-Dr3o1fE6.js"),[])),Fu=p(()=>m(()=>import("./NewsletterNeu-D9-3xGJo.js"),[])),zu=p(()=>m(()=>import("./UeberUnsNeu-D9M6qZUV.js"),[])),Gu=p(()=>m(()=>import("./PartnerNeu-BH9gCIBU.js"),[])),Ku=p(()=>m(()=>import("./Erstgespraech-CHeZI4dP.js"),[])),is=p(()=>m(()=>import("./Gespraech-DHducIuc.js"),[])),as=p(()=>m(()=>import("./Landing-BZ1NLSki.js"),[])),Wu=p(()=>m(()=>import("./Check-C34Idyn6.js"),[])),Ju=p(()=>m(()=>import("./PortfolioFunnel-D-ZSv6_V.js"),[])),Hu=p(()=>m(()=>import("./PortfolioFunnelErgebnis-dXcTgVD6.js"),[])),Xu=p(()=>m(()=>import("./FinanzGuideDanke-DHgSxSg_.js"),[])),Yu=p(()=>m(()=>import("./KontoNachKauf-j8koA5R8.js"),[])),Zu=()=>n.jsx("div",{className:"min-h-screen bg-white dark:bg-[#0A0A0A] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"})}),Qu=p(()=>m(()=>import("./TeamDashboard-3BVL5eS_.js"),[])),ed=p(()=>m(()=>import("./TeamKanbanBoard-BKKPVegA.js"),[])),td=p(()=>m(()=>
82import("./TeamCalendar-DvkZ2e15.js"),[])),rd=p(()=>m(()=>import("./TeamMembers-DLEuiRzH.js"),[])),sd=p(()=>m(()=>import("./TeamDocuments-7sIuE-Y7.js"),[])),nd=p(()=>m(()=>import("./TeamTime-DGW-Tpao.js"),[])),Me=p(()=>m(()=>import("./TeamProtectedRoute-Bu2ireEv.js"),[])),id=p(()=>m(()=>import("./DemoTrading-Yx7K6ysE.js"),[])),ad=p(()=>m(()=>import("./Support-DyHoqCuX.js"),[])),od=p(()=>m(()=>import("./TicketsAdmin-BVsZZFk_.js"),[])),cd=p(()=>m(()=>import("./AdminDepotRebalancing-DxwU6Fah.js"),[])),ld=p(()=>m(()=>import("./SearchIndexAdmin-eB0tPfz3.js"),[])),ud=p(()=>m(()=>import("./TermineAdmin-BUo2x6kK.js"),[])),dd=p(()=>m(()=>import("./InstagramRadarAdmin-CZODOnEp.js"),[]));function hd(){const t=re();wc();const{user:e}=ge();fc(),gc(),To(e==null?void 0:e.id),y.useEffect(()=>{nc()},[]),y.useEffect(()=>{so(window.location.href)},[t]),y.useEffect(()=>{e!=null&&e.id&&(Wa(N,e.id).catch(()=>{}),Ja(N,e.id).catch(()=>{}),za(N).catch(()=>{}))},[e==null?void 0:e.id]);let s=!["/","/privacy","/impressum","/terms","/partners","/about-us","/calendar","/roadmap","/pricing","/payment-required","/payment-failed","/success","/reset-password","/get-funded","/dog-rescue"].includes(t.pathname)&&!t.pathname.startsWith("/team");t.pathname==="/track-record"&&!e&&(s=!1);const i=t.pathname.replace(/\/+$/,"")||"/",a=rr(t.pathname),o=i==="/mein-portfolio/ergebnis";return n.jsx(Ao,{children:n.jsxs("div",{className:"min-h-screen flex flex-col transition-colors duration-300 bg-white dark:bg-[#0A0A0A]",children:[!a&&n.jsx(xe,{fallback:null,resetKey:t.pathname,children:n.jsx(y.Suspense,{fallback:n.jsx("div",{"aria-hidden":"true",className:"fixed top-0 left-0 right-0 z-50 h-14 border-b bg-white/80 dark:bg-[#0A0A0A]/60 border-gray-200 dark:border-gray-800 backdrop-blur-md shadow-lg"}),children:n.jsx(vc,{})})}),!a&&n.jsx(dc,{}),n.jsx(hc,{}),n.jsx("main",{className:"flex-grow",children:n.jsx(xe,{resetKey:t.pathname,variant:"inline",children:n.jsx(y.Suspense,{fallback:n.jsx(Zu,{}),children:n.jsxs(Hs,{children:[n.jsx(h,{path:"/",element:n.jsx(as,{})}),n.jsx(h,{path:"/lp",element:n.jsx(Sc,{})}),n.jsx(h,{path:"/links",element:n.jsx(Mu,{})}),n.jsx(h,{path:"/beginner",element:n.jsx(Z,{zu:"/finanzguide"})}),n.jsx(h,{path:"/check",element:n.jsx(Wu,{})}),n.jsx(h,{path:"/mein-portfolio",element:n.jsx(Ju,{})}),n.jsx(h,{path:"/mein-portfolio/ergebnis",element:n.jsx(Hu,{})}),n.jsx(h,{path:"/sparplan-test",element:n.jsx(z,{to:"/check",replace:!0})}),n.jsx(h,{path:"/portfolio-schnellcheck",element:n.jsx(z,{to:"/check",replace:!0})}),n.jsx(h,{path:"/junior-depot",element:n.jsx(z,{to:"/junior-depot-guide/warum",replace:!0})}),n.jsx(h,{path:"/beginner-b",element:n.jsx(Z,{zu:"/finanzguide"})}),n.jsx(h,{path:"/newsletter-erfolge",element:n.jsx(yu,{})}),n.jsx(h,{path:"/beginner-c",element:n.jsx(z,{to:"/beginner-guide",replace:!0})}),n.jsx(h,{path:"/methode",element:n.jsx(Iu,{})}),n.jsx(h,{path:"/methode-neu",element:n.jsx(Z,{zu:"/methode"})}),n.jsx(h,{path:"/1zu1",element:n.jsx(Cu,{})}),n.jsx(h,{path:"/pricing-neu",element:n.jsx(Z,{zu:"/pricing"})}),n.jsx(h,{path:"/events-neu",element:n.jsx(Z,{zu:"/events"})}),n.jsx(h,{path:"/finanzguide-neu",element:n.jsx(Z,{zu:"/finanzguide"})}),n.jsx(h,{path:"/coaching",element:n.jsx(Uu,{})}),n.jsx(h,{path:"/coaching-neu",element:n.jsx(Z,{zu:"/coaching"})}),n.jsx(h,{path:"/karten-test",element:n.jsx(Vu,{})}),n.jsx(h,{path:"/retreat",element:n.jsx(qu,{})}),n.jsx(h,{path:"/retreat-neu",element:n.jsx(Z,{zu:"/retreat"})}),n.jsx(h,{path:"/check-neu",element:n.jsx(Z,{zu:"/check"})}),n.jsx(h,{path:"/track-record-neu",element:n.jsx(Z,{zu:"/track-record"})}),n.jsx(h,{path:"/links-neu",element:n.jsx(Z,{zu:"/links"})}),n.jsx(h,{path:"/newsletter-neu",element:n.jsx(Z,{zu:"/newsletter"})}),n.jsx(h,{path:"/about-us-neu",element:n.jsx(Z,{zu:"/about-us"})}),n.jsx(h,{path:"/partners-neu",element:n.jsx(Z,{zu:"/partners"})}),n.jsx(h,{path:"/start",element:n.jsx(Z,{zu:"/finanzguide"})}),n.jsx(h,{path:"/start-b",element:n.jsx(Z,{zu:"/finanzguide"})}),n.jsx(h,{path:"/erstgespraech",element:n.jsx(Ku,{})}),n.jsx(h,{path:"/gespraech/gebucht",element:n.jsx(is,{})}),n.jsx(h,{path:"/gespraech",element:n.jsx(is,{})}),n.jsx(h,{path:"/neu",element:n.jsx(as,{})}),n.jsx(h,{path:"/finanzguide",element:n.jsx($u,{})}),n.jsx(h,{path:"/finanzguide/danke",element:n.jsx(Xu,{})}),n.jsx(h,{path:"/kauf-abschliessen",element:n.jsx(Yu,{})}),n.jsx(h,{path:"/dashboard",element:n.jsx(j,{children:n.jsx(Tc,{})})}),n.jsx(h,{path:"/market-overview",element:n.jsx(j,{children:n.jsx(Pc,{})})}),n.jsx(h,{path:"/coin/:symbol",element:n.jsx(j,{children:n.jsx(Ml,{})})}),n.jsx(h,{path:"/stock/:symbol",element:n.jsx(j,{children:n.jsx(Fl,{})})}),n.jsx(h,{path:"/commodity/:symbol",element:n.jsx(j,{children:n.jsx(zl,{})})}),n.jsx(h,{path:"/signals",element:n.jsx(j,{children:n.jsx(Cc,{})})}),n.jsx(h,{path:"/education",element:n.jsx(j,{children:n.jsx(Dc,{})})}),n.jsx(h,{path:"/junior-depot-guide",element:n.jsx(z,{to:"/junior-depot-guide/warum",replace:!0})}),n.jsx(h,{path:"/junior-depot-guide/warum",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(fu,{})})}),n.jsx(h,{path:"/junior-depot-guide/uebersicht",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(mu,{})})}),n.jsx(h,{path:"/junior-depot-guide/wem-gehoert",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(pu,{})})}),n.jsx(h,{path:"/junior-depot-guide/rechtliches",element:n.jsx(z,{to:"/junior-depot-guide/rechtsstart",replace:!0})}),n.jsx(h,{path:"/junior-depot-guide/rechtsstart",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(gu,{})})}
82),n.jsx(h,{path:"/junior-depot-guide/depot-eroeffnen",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(_u,{})})}),n.jsx(h,{path:"/junior-depot-guide/etfs",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(wu,{})})}),n.jsx(h,{path:"/junior-depot-guide/quartal",element:n.jsx(z,{to:"/junior-depot-guide/etfs",replace:!0})}),n.jsx(h,{path:"/junior-depot-guide/rebalancing",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(Ou,{})})}),n.jsx(h,{path:"/junior-depot-guide/sparrate",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(vu,{})})}),n.jsx(h,{path:"/junior-depot-guide/fragen",element:n.jsx(X,{guideType:"junior_depot",children:n.jsx(bu,{})})}),n.jsx(h,{path:"/beginner-guide",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(xu,{})})}),n.jsx(h,{path:"/beginner-guide/budget",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(Eu,{})})}),n.jsx(h,{path:"/beginner-guide/etf",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(ku,{})})}),n.jsx(h,{path:"/beginner-guide/crypto",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(ju,{})})}),n.jsx(h,{path:"/beginner-guide/anleihen",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(Au,{})})}),n.jsx(h,{path:"/beginner-guide/strategie",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(Su,{})})}),n.jsx(h,{path:"/beginner-guide/depot",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(Tu,{})})}),n.jsx(h,{path:"/beginner-guide/fragen",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(Pu,{})})}),n.jsx(h,{path:"/beginner-guide/rebalancing",element:n.jsx(X,{guideType:"starter_depot",children:n.jsx(Ru,{})})}),n.jsx(h,{path:"/akademie",element:n.jsx(Po,{children:n.jsx(Lc,{})})}),n.jsx(h,{path:"/analysis",element:n.jsx(j,{children:n.jsx(Nc,{})})}),n.jsx(h,{path:"/tools",element:n.jsx(j,{children:n.jsx($c,{})})}),n.jsx(h,{path:"/ai-assistant",element:n.jsx(j,{children:n.jsx(Uc,{})})}),n.jsxs(n.Fragment,{children:[n.jsx(h,{path:"/community",element:n.jsx(j,{children:n.jsx(Vc,{})})}),n.jsx(h,{path:"/messages",element:n.jsx(j,{children:n.jsx(rs,{})})}),n.jsx(h,{path:"/messages/:conversationId",element:n.jsx(j,{children:n.jsx(rs,{})})})]}),n.jsx(h,{path:"/news",element:n.jsx(z,{to:"/dashboard?tab=news",replace:!0})}),n.jsx(h,{path:"/track-record",element:n.jsx(Bu,{})}),n.jsx(h,{path:"/support",element:n.jsx(j,{children:n.jsx(ad,{})})}),n.jsx(h,{path:"/etf",element:n.jsx(j,{children:n.jsx(Gl,{})})}),n.jsx(h,{path:"/library",element:n.jsx(j,{children:n.jsx(qc,{})})}),n.jsx(h,{path:"/timeframes",element:n.jsx(j,{children:n.jsx(Bc,{})})}),n.jsxs(n.Fragment,{children:[n.jsx(h,{path:"/webinar-zugang",element:n.jsx(xl,{})}),n.jsx(h,{path:"/webinars",element:n.jsx(vl,{})}),n.jsx(h,{path:"/webinars/:eventId",element:n.jsx(Hr,{children:n.jsx(bl,{})})}),n.jsx(h,{path:"/webinars/:eventId/market-health-check",element:n.jsx(Hr,{children:n.jsx(yl,{})})})]}),n.jsx(h,{path:"/gold",element:n.jsx(il,{})}),n.jsx(h,{path:"/gold/:slug",element:n.jsx(al,{})}),n.jsx(h,{path:"/gold/cart",element:n.jsx(ol,{})}),n.jsxs(n.Fragment,{children:[n.jsx(h,{path:"/events/success",element:n.jsx(Nu,{})}),n.jsx(h,{path:"/events",element:n.jsx(Lu,{})}),n.jsx(h,{path:"/trading-retreat-2026",element:n.jsx(j,{children:n.jsx(kl,{})})}),n.jsx(h,{path:"/trading-contest",element:n.jsx(j,{children:n.jsx(jl,{})})})]}),n.jsx(h,{path:"/daily-analysis",element:n.jsx(j,{children:n.jsx(Al,{})})}),n.jsx(h,{path:"/trading-ideas",element:n.jsx(j,{children:n.jsx(Sl,{})})}),n.jsx(h,{path:"/active-trades",element:n.jsx(j,{children:n.jsx(Tl,{})})}),n.jsx(h,{path:"/trading-journal",element:n.jsx(j,{requiresJournalAccess:!0,children:n.jsx(Pl,{})})}),n.jsx(h,{path:"/trading-journal-new",element:n.jsx(j,{requiresJournalAccess:!0,children:n.jsx(Rl,{})})}),n.jsx(h,{path:"/portfolio-tracker",element:n.jsx(j,{requiresPortfolioAccess:!0,children:n.jsx(Cl,{})})}),n.jsx(h,{path:"/internal-analysis",element:n.jsx(j,{children:n.jsx(Hc,{})})}),n.jsx(h,{path:"/backtesting",element:n.jsx(ye,{children:n.jsx(du,{})})}),n.jsx(h,{path:"/goals",element:n.jsx(ye,{children:n.jsx(uu,{})})}),n.jsx(h,{path:"/trade/:tradeId",element:n.jsx(j,{requiresJournalAccess:!0,children:n.jsx(Il,{})})}),n.jsx(h,{path:"/trade-old/:tradeId",element:n.jsx(j,{requiresJournalAccess:!0,children:n.jsx(Ol,{})})}),n.jsx(h,{path:"/compounding",element:n.jsx(j,{children:n.jsx(Dl,{})})}),n.jsx(h,{path:"/live-charts",element:n.jsx(j,{children:n.jsx(Ll,{})})}),n.jsx(h,{path:"/spot",element:n.jsx(j,{children:n.jsx(Nl,{})})}),n.jsxs(n.Fragment,{children:[n.jsx(h,{path:"/discover",element:n.jsx(j,{children:n.jsx(Yl,{})})}),n.jsx(h,{path:"/discover-users",element:n.jsx(j,{children:n.jsx(eu,{})})})]}),n.jsx(h,{path:"/profile",element:n.jsx(ye,{children:n.jsx(ns,{})})}),n.jsx(h,{path:"/profile/:handle",element:n.jsx(ye,{children:n.jsx(ns,{})})}),n.jsx(h,{path:"/meeting/:id",element:n.jsx(j,{children:n.jsx(hu,{})})}),n.jsx(h,{path:"/admin/termine",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(ud,{})})}),n.jsx(h,{path:"/admin/news",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Mc,{})})}),n.jsx(h,{path:"/admin/navarino",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Fc,{})})}),n.jsx(h,{path:"/admin/reports",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(zc,{})})}),n.jsx(h,{path:"/admin/daily-report",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(ll,{})})}),n.jsx(h,{path:"/admin/livestream",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Gc,{})})}),n.jsx(h,{path:"/admin/badges",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Kc,{})})}),n.jsx(h,{path:"/admin/fomc-bingo",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(rl,{})})}),n.jsx(h,{path:"/admin/journal-access",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Wc,{})})}),n.jsx(h,{path:"/admin/internal-analysis-access",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Jc,{})})}),n.jsx(h,{path:"/admin/retreat-access",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Xc,{})})}),n.jsx(h,{path:"/admin/retreat-2026",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Yc,{})})}),n.jsx(h,{path:"/admin/retreat",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Zc,{})})}),n.jsx(h,{path:"/admin/portfolio-access",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(Qc,{})})}),n.jsx(h,{path:"/admin/contest",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(el,{})})}),n.jsx(h,{path:"/admin/events",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(tl,{})})}),n.jsx(h,{path:"/admin/gold-shop",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(nl,{})})}),n.jsx(h,{path:"/admin/webinar-topics",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(El,{})})}),n.jsx(h,{path:"/admin/exchanges",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(cl,{})})}),n.jsx(h,{path:"/admin/customers",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(ul,{})})}),n.jsx(h,{path:"/admin/customers/:userId",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(dl,{})})}),n.jsx(h,{path:"/admin/chart-of-the-day",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(hl,{})})}),n.jsx(h,{path:"/admin/analytics",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(fl,{})})}),n.jsx(h,{path:"/admin/newsletter",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(ml,{})})}),n.jsx(h,{path:"/admin/instagram-radar",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(dd,{})})}),n.jsx(h,{path:"/admin/flowchart",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(pl,{})})}),n.jsx(h,{path:"/admin/ops",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(gl,{})})}),n.jsx(h,{path:"/admin/tickets",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(od,{})})}),n.jsx(h,{path:"/admin",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(_l,{})})}),n.jsx(h,{path:"/xp",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(wl,{})})}),n.jsx(h,{path:"/admin/depot-rebalancing",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(cd,{})})}),n.jsx(h,{path:"/admin/search-index",element:n.jsx(j,{requiresAdmin:!0,children:n.jsx(ld,{})})}),n.jsx(h,{path:"/team",element:n.jsx(y.Suspense,{fallback:n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-[#0A0A0A] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"})}),children:n.jsx(Me,{children:n.jsx(Qu,{})})})}),n.jsx(h,{path:"/team/tasks",element:n.jsx(y.Suspense,{fallback:n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-[#0A0A0A] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"})}),children:n.jsx(Me,{children:n.jsx(ed,{})})})}),n.jsx(h,{path:"/team/calendar",element:n.jsx(y.Suspense,{fallback:n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-[#0A0A0A] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"})}),children:n.jsx(Me,{children:n.jsx(td,{})})})}),n.jsx(h,{path:"/team/members",element:n.jsx(y.Suspense,{fallback:n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-[#0A0A0A] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"})}),children:n.jsx(Me,{requiresTeamAdmin:!0,children:n.jsx(rd,{})})})}),n.jsx(h,{path:"/team/documents",element:n.jsx(y.Suspense,{fallback:n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-[#0A0A0A] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"})}),children:n.jsx(Me,{children:n.jsx(sd,{})})})}),n.jsx(h,{path:"/team/time",element:n.jsx(y.Suspense,{fallback:n.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-[#0A0A0A] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"})}),children:n.jsx(Me,{children:n.jsx(nd,{})})})}),n.jsx(h,{path:"/privacy",element:n.jsx(Rc,{})}),n.jsx(h,{path:"/impressum",element:n.jsx(Oc,{})}),n.jsx(h,{path:"/terms",element:n.jsx(Ic,{})}),n.jsx(h,{path:"/affiliate",element:n.jsx($l,{})}),n.jsx(h,{path:"/referral",element:n.jsx(Ul,{})}),n.jsx(h,{path:"/app-framework",element:n.jsx(Vl,{})}),n.jsx(h,{path:"/partners",element:n.jsx(Gu,{})}),n.jsx(h,{path:"/about-us",element:n.jsx(zu,{})}),n.jsx(h,{path:"/calendar",element:n.jsx(ql,{})}),n.jsx(h,{path:"/roadmap",element:n.jsx(Bl,{})}),n.jsx(h,{path:"/pricing",element:n.jsx(Du,{})}),n.jsx(h,{path:"/abo-start",element:n.jsx(Z,{zu:"/pricing"})}),n.jsx(h,{path:"/payment-required",element:n.jsx(Hl,{})}),n.jsx(h,{path:"/payment-failed",element:n.jsx(Xl,{})}),n.jsx(h,{path:"/success",element:n.jsx(ss,{})}),n.jsx(h,{path:"/bf-success",element:n.jsx(ss,{})}),n.jsx(h,{path:"/reset-password",element:n.jsx(Zl,{})}),n.jsx(h,{path:"/get-funded",element:n.jsx(Ql,{})}),n.jsx(h,{path:"/dog-rescue",element:n.jsx(tu,{})}),n.jsx(h,{path:"/newsletter",element:n.jsx(Fu,{})}),n.jsx(h,{path:"/join-telegram",element:n.jsx(iu,{})}),n.jsx(h,{path:"/mitmachen",element:n.jsx(au,{})}),n.jsx(h,{path:"/join/:slug",element:n.jsx(ou,{})}),n.jsx(h,{path:"/einladung-bestaetigen",element:n.jsx(cu,{})}),n.jsx(h,{path:"/contest",element:n.jsx(lu,{})}),n.jsx(h,{path:"/newsletter-thank-you",element:n.jsx(ru,{})}),n.jsx(h,{path:"/confirm-newsletter",element:n.jsx(su,{})}),n.jsx(h,{path:"/unsubscribe",element:n.jsx(nu,{})}),n.jsx(h,{path:"/chart-of-the-day",element:n.jsx(ye,{children:n.jsx(Kl,{})})}),n.jsx(h,{path:"/chart-of-the-day/leaderboard",element:n.jsx(ye,{children:n.jsx(Wl,{})})}),n.jsx(h,{path:"/guess-the-price",element:n.jsx(ye,{children:n.jsx(Jl,{})})}),n.jsx(h,{path:"/fomc-bingo",element:n.jsx(ye,{children:n.jsx(sl,{})})}),n.jsx(h,{path:"/papertrading",element:n.jsx(tr.Suspense,{fallback:n.jsx("div",{className:"min-h-screen bg-[#0A0A0A]"}),children:n.jsx(id,{})})}),n.jsx(h,{path:"*",element:n.jsx(z,{to:"/",replace:!0})})]})})})}),n.jsx(xe,{fallback:null,resetKey:t.pathname,children:!t.pathname.startsWith("/team")&&!a&&n.jsx(y.Suspense,{fallback:null,children:n.jsx(xc,{})})}),n.jsxs(xe,{fallback:null,resetKey:t.pathname,children:[s&&!a&&n.jsx(kc,{}),s&&!a&&n.jsx(jc,{}),!a&&n.jsx(Ac,{})]}),n.jsx(nn,{}),n.jsx(eo,{}),n.jsx(xe,{fallback:null,children:n.jsx(y.Suspense,{fallback:null,children:n.jsx(yc,{})})}),!o&&n.jsx(xe,{fallback:null,children:n.jsx(y.Suspense,{fallback:null,children:n.jsx(bc,{onAcceptAll:()=>me.acceptAll(),onRejectAll:()=>me.rejectAll(),onSavePreferences:c=>me.setPreferences(c)})})})]})})}function fd(){return n.jsx(xe,{children:n.jsx(uo,{children:n.jsx(mo,{children:n.jsx(po,{children:n.jsx(go,{children:n.jsx(_o,{children:n.jsxs(wo,{children:[n.jsx(hd,{}),n.jsx(xe,{fallback:null,children:n.jsx(y.Suspense,{fallback:null,children:n.jsx(Ec,{})})})]})})})})})})})}window.addEventListener("vite:preloadError",t=>{const e=t.payload;_t(e!=null?e:new Error("Failed to fetch dynamically imported module"))&&t.preventDefault()});window.addEventListener("unhandledrejection",t=>{_t(t.reason)});Ba();Fa(N);function zs(){const t=window.innerHeight*.01;document.documentElement.style.setProperty("--vh","".concat(t,"px"))}zs();window.addEventListener("resize",zs);document.documentElement.setAttribute("data-brand",O.id);document.documentElement.classList.remove("light");document.documentElement.classList.add("dark");const U=(t,e)=>{e&&document.documentElement.style.setProperty(t,e)};
82U("--color-primary",O.colors.primary);U("--color-primary-light",O.colors.primaryLight);U("--color-primary-dark",O.colors.primaryDark);U("--color-secondary",O.colors.secondary);U("--color-bg-deep",O.colors.bgDeep);U("--color-bg-surface",O.colors.bgSurface);U("--color-bg-elevated",O.colors.bgElevated);U("--color-bg-navbar",O.colors.bgNavbar);U("--color-success",O.colors.success);U("--color-error",O.colors.error);U("--color-neutral-1",O.colors.neutral1);U("--color-neutral-2",O.colors.neutral2);U("--color-neutral-3",O.colors.neutral3);U("--color-accent-from",O.colors.accentFrom);U("--color-accent-to",O.colors.accentTo);U("--bronze",O.colors.bronze);U("--bronze-light",O.colors.bronzeLight);U("--bronze-dark",O.colors.bronzeDark);U("--bronze-darker",O.colors.bronzeDarker);U("--bg",O.colors.bg);U("--bg-2",O.colors.bg2);U("--bg-3",O.colors.bg3);U("--bg-4",O.colors.bg4);U("--fg",O.colors.fg);U("--fg-muted",O.colors.fgMuted);U("--fg-dim",O.colors.fgDim);U("--line",O.colors.line);U("--line-strong",O.colors.lineStrong);U("--long",O.colors.long);U("--short",O.colors.short);U("--link",O.colors.link);U("--warn",O.colors.warn);const os=document.querySelector('link[rel="icon"]');os&&(os.href=O.logos.icon);Xs.createRoot(document.getElementById("root")).render(n.jsx(Ys,{children:n.jsx(fd,{})}));export{zd as $,$o as A,xo as B,Qr as C,Eo as D,Bo as E,Xr as F,Fo as G,Vd as H,Ud as I,Od as J,wd as K,Go as L,Yo as M,Pd as N,kd as O,Dd as P,Cd as Q,Qo as R,xd as S,Ka as T,bd as U,Ed as V,Rd as W,ur as X,Sd as Y,jd as Z,vd as _,pd as __vite_legacy_guard,Ad as a,yd as a0,Fd as b,qd as c,ge as d,pe as e,le as f,Ga as g,Bd as h,Md as i,O as j,$d as k,p as l,Ld as m,Nd as n,Vo as o,me as p,Ho as q,Wo as r,N as s,_d as t,fo as u,ic as v,Td as w,co as x,cr as y,Id as z};
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.