noterai 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,309 @@
1
+ import{r as b,a as Jv}from"./vendor-react-DHeZC_T5.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))a(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const r of i.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&a(r)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var om={exports:{}},Po={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.js
4
+ *
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var Xv=Symbol.for("react.transitional.element"),Qv=Symbol.for("react.fragment");function cm(e,t,n){var a=null;if(n!==void 0&&(a=""+n),t.key!==void 0&&(a=""+t.key),"key"in t){n={};for(var s in t)s!=="key"&&(n[s]=t[s])}else n=t;return t=n.ref,{$$typeof:Xv,type:e,key:a,ref:t!==void 0?t:null,props:n}}Po.Fragment=Qv;Po.jsx=cm;Po.jsxs=cm;om.exports=Po;var c=om.exports,um={exports:{}},qo={},dm={exports:{}},hm={};/**
10
+ * @license React
11
+ * scheduler.production.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */(function(e){function t(L,U){var k=L.length;L.push(U);e:for(;0<k;){var se=k-1>>>1,j=L[se];if(0<s(j,U))L[se]=U,L[k]=j,k=se;else break e}}function n(L){return L.length===0?null:L[0]}function a(L){if(L.length===0)return null;var U=L[0],k=L.pop();if(k!==U){L[0]=k;e:for(var se=0,j=L.length,V=j>>>1;se<V;){var Re=2*(se+1)-1,ft=L[Re],nt=Re+1,Mt=L[nt];if(0>s(ft,k))nt<j&&0>s(Mt,ft)?(L[se]=Mt,L[nt]=k,se=nt):(L[se]=ft,L[Re]=k,se=Re);else if(nt<j&&0>s(Mt,k))L[se]=Mt,L[nt]=k,se=nt;else break e}}return U}function s(L,U){var k=L.sortIndex-U.sortIndex;return k!==0?k:L.id-U.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var r=Date,l=r.now();e.unstable_now=function(){return r.now()-l}}var o=[],u=[],h=1,f=null,d=3,p=!1,v=!1,_=!1,x=!1,g=typeof setTimeout=="function"?setTimeout:null,m=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;function w(L){for(var U=n(u);U!==null;){if(U.callback===null)a(u);else if(U.startTime<=L)a(u),U.sortIndex=U.expirationTime,t(o,U);else break;U=n(u)}}function C(L){if(_=!1,w(L),!v)if(n(o)!==null)v=!0,R||(R=!0,Ae());else{var U=n(u);U!==null&&$e(C,U.startTime-L)}}var R=!1,O=-1,z=5,q=-1;function K(){return x?!0:!(e.unstable_now()-q<z)}function ve(){if(x=!1,R){var L=e.unstable_now();q=L;var U=!0;try{e:{v=!1,_&&(_=!1,m(O),O=-1),p=!0;var k=d;try{t:{for(w(L),f=n(o);f!==null&&!(f.expirationTime>L&&K());){var se=f.callback;if(typeof se=="function"){f.callback=null,d=f.priorityLevel;var j=se(f.expirationTime<=L);if(L=e.unstable_now(),typeof j=="function"){f.callback=j,w(L),U=!0;break t}f===n(o)&&a(o),w(L)}else a(o);f=n(o)}if(f!==null)U=!0;else{var V=n(u);V!==null&&$e(C,V.startTime-L),U=!1}}break e}finally{f=null,d=k,p=!1}U=void 0}}finally{U?Ae():R=!1}}}var Ae;if(typeof y=="function")Ae=function(){y(ve)};else if(typeof MessageChannel<"u"){var ee=new MessageChannel,yt=ee.port2;ee.port1.onmessage=ve,Ae=function(){yt.postMessage(null)}}else Ae=function(){g(ve,0)};function $e(L,U){O=g(function(){L(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(L){L.callback=null},e.unstable_forceFrameRate=function(L){0>L||125<L?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):z=0<L?Math.floor(1e3/L):5},e.unstable_getCurrentPriorityLevel=function(){return d},e.unstable_next=function(L){switch(d){case 1:case 2:case 3:var U=3;break;default:U=d}var k=d;d=U;try{return L()}finally{d=k}},e.unstable_requestPaint=function(){x=!0},e.unstable_runWithPriority=function(L,U){switch(L){case 1:case 2:case 3:case 4:case 5:break;default:L=3}var k=d;d=L;try{return U()}finally{d=k}},e.unstable_scheduleCallback=function(L,U,k){var se=e.unstable_now();switch(typeof k=="object"&&k!==null?(k=k.delay,k=typeof k=="number"&&0<k?se+k:se):k=se,L){case 1:var j=-1;break;case 2:j=250;break;case 5:j=1073741823;break;case 4:j=1e4;break;default:j=5e3}return j=k+j,L={id:h++,callback:U,priorityLevel:L,startTime:k,expirationTime:j,sortIndex:-1},k>se?(L.sortIndex=k,t(u,L),n(o)===null&&L===n(u)&&(_?(m(O),O=-1):_=!0,$e(C,k-se))):(L.sortIndex=j,t(o,L),v||p||(v=!0,R||(R=!0,Ae()))),L},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(L){var U=d;return function(){var k=d;d=U;try{return L.apply(this,arguments)}finally{d=k}}}})(hm);dm.exports=hm;var Wv=dm.exports;/**
18
+ * @license React
19
+ * react-dom-client.production.js
20
+ *
21
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
22
+ *
23
+ * This source code is licensed under the MIT license found in the
24
+ * LICENSE file in the root directory of this source tree.
25
+ */var gt=Wv,fm=b,Zv=Jv;function N(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function pm(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function qr(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function mm(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function gm(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function Uh(e){if(qr(e)!==e)throw Error(N(188))}function eb(e){var t=e.alternate;if(!t){if(t=qr(e),t===null)throw Error(N(188));return t!==e?null:e}for(var n=e,a=t;;){var s=n.return;if(s===null)break;var i=s.alternate;if(i===null){if(a=s.return,a!==null){n=a;continue}break}if(s.child===i.child){for(i=s.child;i;){if(i===n)return Uh(s),e;if(i===a)return Uh(s),t;i=i.sibling}throw Error(N(188))}if(n.return!==a.return)n=s,a=i;else{for(var r=!1,l=s.child;l;){if(l===n){r=!0,n=s,a=i;break}if(l===a){r=!0,a=s,n=i;break}l=l.sibling}if(!r){for(l=i.child;l;){if(l===n){r=!0,n=i,a=s;break}if(l===a){r=!0,a=i,n=s;break}l=l.sibling}if(!r)throw Error(N(189))}}if(n.alternate!==a)throw Error(N(190))}if(n.tag!==3)throw Error(N(188));return n.stateNode.current===n?e:t}function ym(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=ym(e),t!==null)return t;e=e.sibling}return null}var Fe=Object.assign,tb=Symbol.for("react.element"),dl=Symbol.for("react.transitional.element"),Qi=Symbol.for("react.portal"),Vs=Symbol.for("react.fragment"),vm=Symbol.for("react.strict_mode"),gu=Symbol.for("react.profiler"),bm=Symbol.for("react.consumer"),ra=Symbol.for("react.context"),Od=Symbol.for("react.forward_ref"),yu=Symbol.for("react.suspense"),vu=Symbol.for("react.suspense_list"),Rd=Symbol.for("react.memo"),Ea=Symbol.for("react.lazy"),bu=Symbol.for("react.activity"),nb=Symbol.for("react.memo_cache_sentinel"),Lh=Symbol.iterator;function Hi(e){return e===null||typeof e!="object"?null:(e=Lh&&e[Lh]||e["@@iterator"],typeof e=="function"?e:null)}var ab=Symbol.for("react.client.reference");function Su(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ab?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Vs:return"Fragment";case gu:return"Profiler";case vm:return"StrictMode";case yu:return"Suspense";case vu:return"SuspenseList";case bu:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case Qi:return"Portal";case ra:return e.displayName||"Context";case bm:return(e._context.displayName||"Context")+".Consumer";case Od:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Rd:return t=e.displayName||null,t!==null?t:Su(e.type)||"Memo";case Ea:t=e._payload,e=e._init;try{return Su(e(t))}catch{}}return null}var Wi=Array.isArray,ne=fm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,De=Zv.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,fs={pending:!1,data:null,method:null,action:null},_u=[],Ys=-1;function qn(e){return{current:e}}function Tt(e){0>Ys||(e.current=_u[Ys],_u[Ys]=null,Ys--)}function Ge(e,t){Ys++,_u[Ys]=e.current,e.current=t}var Pn=qn(null),wr=qn(null),Ia=qn(null),ao=qn(null);function so(e,t){switch(Ge(Ia,t),Ge(wr,e),Ge(Pn,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?qf(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=qf(t),e=Iy(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Tt(Pn),Ge(Pn,e)}function pi(){Tt(Pn),Tt(wr),Tt(Ia)}function wu(e){e.memoizedState!==null&&Ge(ao,e);var t=Pn.current,n=Iy(t,e.type);t!==n&&(Ge(wr,e),Ge(Pn,n))}function io(e){wr.current===e&&(Tt(Pn),Tt(wr)),ao.current===e&&(Tt(ao),Dr._currentValue=fs)}var gc,zh;function ls(e){if(gc===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);gc=t&&t[1]||"",zh=-1<n.stack.indexOf(`
26
+ at`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return`
27
+ `+gc+e+zh}var yc=!1;function vc(e,t){if(!e||yc)return"";yc=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(t){var f=function(){throw Error()};if(Object.defineProperty(f.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(f,[])}catch(p){var d=p}Reflect.construct(e,[],f)}else{try{f.call()}catch(p){d=p}e.call(f.prototype)}}else{try{throw Error()}catch(p){d=p}(f=e())&&typeof f.catch=="function"&&f.catch(function(){})}}catch(p){if(p&&d&&typeof p.stack=="string")return[p.stack,d.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var s=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");s&&s.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var i=a.DetermineComponentFrameRoot(),r=i[0],l=i[1];if(r&&l){var o=r.split(`
28
+ `),u=l.split(`
29
+ `);for(s=a=0;a<o.length&&!o[a].includes("DetermineComponentFrameRoot");)a++;for(;s<u.length&&!u[s].includes("DetermineComponentFrameRoot");)s++;if(a===o.length||s===u.length)for(a=o.length-1,s=u.length-1;1<=a&&0<=s&&o[a]!==u[s];)s--;for(;1<=a&&0<=s;a--,s--)if(o[a]!==u[s]){if(a!==1||s!==1)do if(a--,s--,0>s||o[a]!==u[s]){var h=`
30
+ `+o[a].replace(" at new "," at ");return e.displayName&&h.includes("<anonymous>")&&(h=h.replace("<anonymous>",e.displayName)),h}while(1<=a&&0<=s);break}}}finally{yc=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?ls(n):""}function sb(e,t){switch(e.tag){case 26:case 27:case 5:return ls(e.type);case 16:return ls("Lazy");case 13:return e.child!==t&&t!==null?ls("Suspense Fallback"):ls("Suspense");case 19:return ls("SuspenseList");case 0:case 15:return vc(e.type,!1);case 11:return vc(e.type.render,!1);case 1:return vc(e.type,!0);case 31:return ls("Activity");default:return""}}function Bh(e){try{var t="",n=null;do t+=sb(e,n),n=e,e=e.return;while(e);return t}catch(a){return`
31
+ Error generating stack: `+a.message+`
32
+ `+a.stack}}var xu=Object.prototype.hasOwnProperty,Nd=gt.unstable_scheduleCallback,bc=gt.unstable_cancelCallback,ib=gt.unstable_shouldYield,rb=gt.unstable_requestPaint,an=gt.unstable_now,lb=gt.unstable_getCurrentPriorityLevel,Sm=gt.unstable_ImmediatePriority,_m=gt.unstable_UserBlockingPriority,ro=gt.unstable_NormalPriority,ob=gt.unstable_LowPriority,wm=gt.unstable_IdlePriority,cb=gt.log,ub=gt.unstable_setDisableYieldValue,Gr=null,sn=null;function Ma(e){if(typeof cb=="function"&&ub(e),sn&&typeof sn.setStrictMode=="function")try{sn.setStrictMode(Gr,e)}catch{}}var rn=Math.clz32?Math.clz32:fb,db=Math.log,hb=Math.LN2;function fb(e){return e>>>=0,e===0?32:31-(db(e)/hb|0)|0}var hl=256,fl=262144,pl=4194304;function os(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Go(e,t,n){var a=e.pendingLanes;if(a===0)return 0;var s=0,i=e.suspendedLanes,r=e.pingedLanes;e=e.warmLanes;var l=a&134217727;return l!==0?(a=l&~i,a!==0?s=os(a):(r&=l,r!==0?s=os(r):n||(n=l&~e,n!==0&&(s=os(n))))):(l=a&~i,l!==0?s=os(l):r!==0?s=os(r):n||(n=a&~e,n!==0&&(s=os(n)))),s===0?0:t!==0&&t!==s&&!(t&i)&&(i=s&-s,n=t&-t,i>=n||i===32&&(n&4194048)!==0)?t:s}function Kr(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function pb(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function xm(){var e=pl;return pl<<=1,!(pl&62914560)&&(pl=4194304),e}function Sc(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Vr(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function mb(e,t,n,a,s,i){var r=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var l=e.entanglements,o=e.expirationTimes,u=e.hiddenUpdates;for(n=r&~n;0<n;){var h=31-rn(n),f=1<<h;l[h]=0,o[h]=-1;var d=u[h];if(d!==null)for(u[h]=null,h=0;h<d.length;h++){var p=d[h];p!==null&&(p.lane&=-536870913)}n&=~f}a!==0&&Tm(e,a,0),i!==0&&s===0&&e.tag!==0&&(e.suspendedLanes|=i&~(r&~t))}function Tm(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var a=31-rn(t);e.entangledLanes|=t,e.entanglements[a]=e.entanglements[a]|1073741824|n&261930}function Em(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var a=31-rn(n),s=1<<a;s&t|e[a]&t&&(e[a]|=t),n&=~s}}function Am(e,t){var n=t&-t;return n=n&42?1:kd(n),n&(e.suspendedLanes|t)?0:n}function kd(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function jd(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function Cm(){var e=De.p;return e!==0?e:(e=window.event,e===void 0?32:Xy(e.type))}function Ih(e,t){var n=De.p;try{return De.p=e,t()}finally{De.p=n}}var Wa=Math.random().toString(36).slice(2),Ot="__reactFiber$"+Wa,Jt="__reactProps$"+Wa,Ei="__reactContainer$"+Wa,Tu="__reactEvents$"+Wa,gb="__reactListeners$"+Wa,yb="__reactHandles$"+Wa,Hh="__reactResources$"+Wa,Yr="__reactMarker$"+Wa;function Dd(e){delete e[Ot],delete e[Jt],delete e[Tu],delete e[gb],delete e[yb]}function Fs(e){var t=e[Ot];if(t)return t;for(var n=e.parentNode;n;){if(t=n[Ei]||n[Ot]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=Ff(e);e!==null;){if(n=e[Ot])return n;e=Ff(e)}return t}e=n,n=e.parentNode}return null}function Ai(e){if(e=e[Ot]||e[Ei]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Zi(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(N(33))}function ii(e){var t=e[Hh];return t||(t=e[Hh]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function xt(e){e[Yr]=!0}var Om=new Set,Rm={};function xs(e,t){mi(e,t),mi(e+"Capture",t)}function mi(e,t){for(Rm[e]=t,e=0;e<t.length;e++)Om.add(t[e])}var vb=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),$h={},Ph={};function bb(e){return xu.call(Ph,e)?!0:xu.call($h,e)?!1:vb.test(e)?Ph[e]=!0:($h[e]=!0,!1)}function Hl(e,t,n){if(bb(t))if(n===null)e.removeAttribute(t);else{switch(typeof n){case"undefined":case"function":case"symbol":e.removeAttribute(t);return;case"boolean":var a=t.toLowerCase().slice(0,5);if(a!=="data-"&&a!=="aria-"){e.removeAttribute(t);return}}e.setAttribute(t,""+n)}}function ml(e,t,n){if(n===null)e.removeAttribute(t);else{switch(typeof n){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttribute(t,""+n)}}function Fn(e,t,n,a){if(a===null)e.removeAttribute(n);else{switch(typeof a){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(n);return}e.setAttributeNS(t,n,""+a)}}function pn(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Nm(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Sb(e,t,n){var a=Object.getOwnPropertyDescriptor(e.constructor.prototype,t);if(!e.hasOwnProperty(t)&&typeof a<"u"&&typeof a.get=="function"&&typeof a.set=="function"){var s=a.get,i=a.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(r){n=""+r,i.call(this,r)}}),Object.defineProperty(e,t,{enumerable:a.enumerable}),{getValue:function(){return n},setValue:function(r){n=""+r},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Eu(e){if(!e._valueTracker){var t=Nm(e)?"checked":"value";e._valueTracker=Sb(e,t,""+e[t])}}function km(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),a="";return e&&(a=Nm(e)?e.checked?"true":"false":e.value),e=a,e!==n?(t.setValue(e),!0):!1}function lo(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var _b=/[\n"\\]/g;function yn(e){return e.replace(_b,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Au(e,t,n,a,s,i,r,l){e.name="",r!=null&&typeof r!="function"&&typeof r!="symbol"&&typeof r!="boolean"?e.type=r:e.removeAttribute("type"),t!=null?r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+pn(t)):e.value!==""+pn(t)&&(e.value=""+pn(t)):r!=="submit"&&r!=="reset"||e.removeAttribute("value"),t!=null?Cu(e,r,pn(t)):n!=null?Cu(e,r,pn(n)):a!=null&&e.removeAttribute("value"),s==null&&i!=null&&(e.defaultChecked=!!i),s!=null&&(e.checked=s&&typeof s!="function"&&typeof s!="symbol"),l!=null&&typeof l!="function"&&typeof l!="symbol"&&typeof l!="boolean"?e.name=""+pn(l):e.removeAttribute("name")}function jm(e,t,n,a,s,i,r,l){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(e.type=i),t!=null||n!=null){if(!(i!=="submit"&&i!=="reset"||t!=null)){Eu(e);return}n=n!=null?""+pn(n):"",t=t!=null?""+pn(t):n,l||t===e.value||(e.value=t),e.defaultValue=t}a=a??s,a=typeof a!="function"&&typeof a!="symbol"&&!!a,e.checked=l?e.checked:!!a,e.defaultChecked=!!a,r!=null&&typeof r!="function"&&typeof r!="symbol"&&typeof r!="boolean"&&(e.name=r),Eu(e)}function Cu(e,t,n){t==="number"&&lo(e.ownerDocument)===e||e.defaultValue===""+n||(e.defaultValue=""+n)}function ri(e,t,n,a){if(e=e.options,t){t={};for(var s=0;s<n.length;s++)t["$"+n[s]]=!0;for(n=0;n<e.length;n++)s=t.hasOwnProperty("$"+e[n].value),e[n].selected!==s&&(e[n].selected=s),s&&a&&(e[n].defaultSelected=!0)}else{for(n=""+pn(n),t=null,s=0;s<e.length;s++){if(e[s].value===n){e[s].selected=!0,a&&(e[s].defaultSelected=!0);return}t!==null||e[s].disabled||(t=e[s])}t!==null&&(t.selected=!0)}}function Dm(e,t,n){if(t!=null&&(t=""+pn(t),t!==e.value&&(e.value=t),n==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=n!=null?""+pn(n):""}function Mm(e,t,n,a){if(t==null){if(a!=null){if(n!=null)throw Error(N(92));if(Wi(a)){if(1<a.length)throw Error(N(93));a=a[0]}n=a}n==null&&(n=""),t=n}n=pn(t),e.defaultValue=n,a=e.textContent,a===n&&a!==""&&a!==null&&(e.value=a),Eu(e)}function gi(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var wb=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function qh(e,t,n){var a=t.indexOf("--")===0;n==null||typeof n=="boolean"||n===""?a?e.setProperty(t,""):t==="float"?e.cssFloat="":e[t]="":a?e.setProperty(t,n):typeof n!="number"||n===0||wb.has(t)?t==="float"?e.cssFloat=n:e[t]=(""+n).trim():e[t]=n+"px"}function Um(e,t,n){if(t!=null&&typeof t!="object")throw Error(N(62));if(e=e.style,n!=null){for(var a in n)!n.hasOwnProperty(a)||t!=null&&t.hasOwnProperty(a)||(a.indexOf("--")===0?e.setProperty(a,""):a==="float"?e.cssFloat="":e[a]="");for(var s in t)a=t[s],t.hasOwnProperty(s)&&n[s]!==a&&qh(e,s,a)}else for(var i in t)t.hasOwnProperty(i)&&qh(e,i,t[i])}function Md(e){if(e.indexOf("-")===-1)return!1;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var xb=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),Tb=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function $l(e){return Tb.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function la(){}var Ou=null;function Ud(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Js=null,li=null;function Gh(e){var t=Ai(e);if(t&&(e=t.stateNode)){var n=e[Jt]||null;e:switch(e=t.stateNode,t.type){case"input":if(Au(e,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name),t=n.name,n.type==="radio"&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll('input[name="'+yn(""+t)+'"][type="radio"]'),t=0;t<n.length;t++){var a=n[t];if(a!==e&&a.form===e.form){var s=a[Jt]||null;if(!s)throw Error(N(90));Au(a,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name)}}for(t=0;t<n.length;t++)a=n[t],a.form===e.form&&km(a)}break e;case"textarea":Dm(e,n.value,n.defaultValue);break e;case"select":t=n.value,t!=null&&ri(e,!!n.multiple,t,!1)}}}var _c=!1;function Lm(e,t,n){if(_c)return e(t,n);_c=!0;try{var a=e(t);return a}finally{if(_c=!1,(Js!==null||li!==null)&&(nc(),Js&&(t=Js,e=li,li=Js=null,Gh(t),e)))for(t=0;t<e.length;t++)Gh(e[t])}}function xr(e,t){var n=e.stateNode;if(n===null)return null;var a=n[Jt]||null;if(a===null)return null;n=a[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(a=!a.disabled)||(e=e.type,a=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!a;break e;default:e=!1}if(e)return null;if(n&&typeof n!="function")throw Error(N(231,t,typeof n));return n}var ha=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ru=!1;if(ha)try{var $i={};Object.defineProperty($i,"passive",{get:function(){Ru=!0}}),window.addEventListener("test",$i,$i),window.removeEventListener("test",$i,$i)}catch{Ru=!1}var Ua=null,Ld=null,Pl=null;function zm(){if(Pl)return Pl;var e,t=Ld,n=t.length,a,s="value"in Ua?Ua.value:Ua.textContent,i=s.length;for(e=0;e<n&&t[e]===s[e];e++);var r=n-e;for(a=1;a<=r&&t[n-a]===s[i-a];a++);return Pl=s.slice(e,1<a?1-a:void 0)}function ql(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function gl(){return!0}function Kh(){return!1}function Xt(e){function t(n,a,s,i,r){this._reactName=n,this._targetInst=s,this.type=a,this.nativeEvent=i,this.target=r,this.currentTarget=null;for(var l in e)e.hasOwnProperty(l)&&(n=e[l],this[l]=n?n(i):i[l]);return this.isDefaultPrevented=(i.defaultPrevented!=null?i.defaultPrevented:i.returnValue===!1)?gl:Kh,this.isPropagationStopped=Kh,this}return Fe(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=gl)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=gl)},persist:function(){},isPersistent:gl}),t}var Ts={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ko=Xt(Ts),Fr=Fe({},Ts,{view:0,detail:0}),Eb=Xt(Fr),wc,xc,Pi,Vo=Fe({},Fr,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Pi&&(Pi&&e.type==="mousemove"?(wc=e.screenX-Pi.screenX,xc=e.screenY-Pi.screenY):xc=wc=0,Pi=e),wc)},movementY:function(e){return"movementY"in e?e.movementY:xc}}),Vh=Xt(Vo),Ab=Fe({},Vo,{dataTransfer:0}),Cb=Xt(Ab),Ob=Fe({},Fr,{relatedTarget:0}),Tc=Xt(Ob),Rb=Fe({},Ts,{animationName:0,elapsedTime:0,pseudoElement:0}),Nb=Xt(Rb),kb=Fe({},Ts,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),jb=Xt(kb),Db=Fe({},Ts,{data:0}),Yh=Xt(Db),Mb={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Ub={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Lb={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function zb(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=Lb[e])?!!t[e]:!1}function zd(){return zb}var Bb=Fe({},Fr,{key:function(e){if(e.key){var t=Mb[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=ql(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?Ub[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(e){return e.type==="keypress"?ql(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?ql(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),Ib=Xt(Bb),Hb=Fe({},Vo,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Fh=Xt(Hb),$b=Fe({},Fr,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Pb=Xt($b),qb=Fe({},Ts,{propertyName:0,elapsedTime:0,pseudoElement:0}),Gb=Xt(qb),Kb=Fe({},Vo,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),Vb=Xt(Kb),Yb=Fe({},Ts,{newState:0,oldState:0}),Fb=Xt(Yb),Jb=[9,13,27,32],Bd=ha&&"CompositionEvent"in window,rr=null;ha&&"documentMode"in document&&(rr=document.documentMode);var Xb=ha&&"TextEvent"in window&&!rr,Bm=ha&&(!Bd||rr&&8<rr&&11>=rr),Jh=" ",Xh=!1;function Im(e,t){switch(e){case"keyup":return Jb.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hm(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Xs=!1;function Qb(e,t){switch(e){case"compositionend":return Hm(t);case"keypress":return t.which!==32?null:(Xh=!0,Jh);case"textInput":return e=t.data,e===Jh&&Xh?null:e;default:return null}}function Wb(e,t){if(Xs)return e==="compositionend"||!Bd&&Im(e,t)?(e=zm(),Pl=Ld=Ua=null,Xs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return Bm&&t.locale!=="ko"?null:t.data;default:return null}}var Zb={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Qh(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!Zb[e.type]:t==="textarea"}function $m(e,t,n,a){Js?li?li.push(a):li=[a]:Js=a,t=Ao(t,"onChange"),0<t.length&&(n=new Ko("onChange","change",null,n,a),e.push({event:n,listeners:t}))}var lr=null,Tr=null;function e0(e){Ly(e,0)}function Yo(e){var t=Zi(e);if(km(t))return e}function Wh(e,t){if(e==="change")return t}var Pm=!1;if(ha){var Ec;if(ha){var Ac="oninput"in document;if(!Ac){var Zh=document.createElement("div");Zh.setAttribute("oninput","return;"),Ac=typeof Zh.oninput=="function"}Ec=Ac}else Ec=!1;Pm=Ec&&(!document.documentMode||9<document.documentMode)}function ef(){lr&&(lr.detachEvent("onpropertychange",qm),Tr=lr=null)}function qm(e){if(e.propertyName==="value"&&Yo(Tr)){var t=[];$m(t,Tr,e,Ud(e)),Lm(e0,t)}}function t0(e,t,n){e==="focusin"?(ef(),lr=t,Tr=n,lr.attachEvent("onpropertychange",qm)):e==="focusout"&&ef()}function n0(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Yo(Tr)}function a0(e,t){if(e==="click")return Yo(t)}function s0(e,t){if(e==="input"||e==="change")return Yo(t)}function i0(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var on=typeof Object.is=="function"?Object.is:i0;function Er(e,t){if(on(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(a=0;a<n.length;a++){var s=n[a];if(!xu.call(t,s)||!on(e[s],t[s]))return!1}return!0}function tf(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function nf(e,t){var n=tf(e);e=0;for(var a;n;){if(n.nodeType===3){if(a=e+n.textContent.length,e<=t&&a>=t)return{node:n,offset:t-e};e=a}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=tf(n)}}function Gm(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Gm(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Km(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=lo(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=lo(e.document)}return t}function Id(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var r0=ha&&"documentMode"in document&&11>=document.documentMode,Qs=null,Nu=null,or=null,ku=!1;function af(e,t,n){var a=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ku||Qs==null||Qs!==lo(a)||(a=Qs,"selectionStart"in a&&Id(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),or&&Er(or,a)||(or=a,a=Ao(Nu,"onSelect"),0<a.length&&(t=new Ko("onSelect","select",null,t,n),e.push({event:t,listeners:a}),t.target=Qs)))}function ss(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var Ws={animationend:ss("Animation","AnimationEnd"),animationiteration:ss("Animation","AnimationIteration"),animationstart:ss("Animation","AnimationStart"),transitionrun:ss("Transition","TransitionRun"),transitionstart:ss("Transition","TransitionStart"),transitioncancel:ss("Transition","TransitionCancel"),transitionend:ss("Transition","TransitionEnd")},Cc={},Vm={};ha&&(Vm=document.createElement("div").style,"AnimationEvent"in window||(delete Ws.animationend.animation,delete Ws.animationiteration.animation,delete Ws.animationstart.animation),"TransitionEvent"in window||delete Ws.transitionend.transition);function Es(e){if(Cc[e])return Cc[e];if(!Ws[e])return e;var t=Ws[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in Vm)return Cc[e]=t[n];return e}var Ym=Es("animationend"),Fm=Es("animationiteration"),Jm=Es("animationstart"),l0=Es("transitionrun"),o0=Es("transitionstart"),c0=Es("transitioncancel"),Xm=Es("transitionend"),Qm=new Map,ju="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");ju.push("scrollEnd");function jn(e,t){Qm.set(e,t),xs(t,[e])}var oo=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},fn=[],Zs=0,Hd=0;function Fo(){for(var e=Zs,t=Hd=Zs=0;t<e;){var n=fn[t];fn[t++]=null;var a=fn[t];fn[t++]=null;var s=fn[t];fn[t++]=null;var i=fn[t];if(fn[t++]=null,a!==null&&s!==null){var r=a.pending;r===null?s.next=s:(s.next=r.next,r.next=s),a.pending=s}i!==0&&Wm(n,s,i)}}function Jo(e,t,n,a){fn[Zs++]=e,fn[Zs++]=t,fn[Zs++]=n,fn[Zs++]=a,Hd|=a,e.lanes|=a,e=e.alternate,e!==null&&(e.lanes|=a)}function $d(e,t,n,a){return Jo(e,t,n,a),co(e)}function As(e,t){return Jo(e,null,null,t),co(e)}function Wm(e,t,n){e.lanes|=n;var a=e.alternate;a!==null&&(a.lanes|=n);for(var s=!1,i=e.return;i!==null;)i.childLanes|=n,a=i.alternate,a!==null&&(a.childLanes|=n),i.tag===22&&(e=i.stateNode,e===null||e._visibility&1||(s=!0)),e=i,i=i.return;return e.tag===3?(i=e.stateNode,s&&t!==null&&(s=31-rn(n),e=i.hiddenUpdates,a=e[s],a===null?e[s]=[t]:a.push(t),t.lane=n|536870912),i):null}function co(e){if(50<yr)throw yr=0,Zu=null,Error(N(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var ei={};function u0(e,t,n,a){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=a,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Zt(e,t,n,a){return new u0(e,t,n,a)}function Pd(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ca(e,t){var n=e.alternate;return n===null?(n=Zt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&65011712,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n.refCleanup=e.refCleanup,n}function Zm(e,t){e.flags&=65011714;var n=e.alternate;return n===null?(e.childLanes=0,e.lanes=t,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=n.childLanes,e.lanes=n.lanes,e.child=n.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=n.memoizedProps,e.memoizedState=n.memoizedState,e.updateQueue=n.updateQueue,e.type=n.type,t=n.dependencies,e.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function Gl(e,t,n,a,s,i){var r=0;if(a=e,typeof e=="function")Pd(e)&&(r=1);else if(typeof e=="string")r=mS(e,n,Pn.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case bu:return e=Zt(31,n,t,s),e.elementType=bu,e.lanes=i,e;case Vs:return ps(n.children,s,i,t);case vm:r=8,s|=24;break;case gu:return e=Zt(12,n,t,s|2),e.elementType=gu,e.lanes=i,e;case yu:return e=Zt(13,n,t,s),e.elementType=yu,e.lanes=i,e;case vu:return e=Zt(19,n,t,s),e.elementType=vu,e.lanes=i,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case ra:r=10;break e;case bm:r=9;break e;case Od:r=11;break e;case Rd:r=14;break e;case Ea:r=16,a=null;break e}r=29,n=Error(N(130,e===null?"null":typeof e,"")),a=null}return t=Zt(r,n,t,s),t.elementType=e,t.type=a,t.lanes=i,t}function ps(e,t,n,a){return e=Zt(7,e,a,t),e.lanes=n,e}function Oc(e,t,n){return e=Zt(6,e,null,t),e.lanes=n,e}function eg(e){var t=Zt(18,null,null,0);return t.stateNode=e,t}function Rc(e,t,n){return t=Zt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var sf=new WeakMap;function vn(e,t){if(typeof e=="object"&&e!==null){var n=sf.get(e);return n!==void 0?n:(t={value:e,source:t,stack:Bh(t)},sf.set(e,t),t)}return{value:e,source:t,stack:Bh(t)}}var ti=[],ni=0,uo=null,Ar=0,mn=[],gn=0,Fa=null,In=1,Hn="";function sa(e,t){ti[ni++]=Ar,ti[ni++]=uo,uo=e,Ar=t}function tg(e,t,n){mn[gn++]=In,mn[gn++]=Hn,mn[gn++]=Fa,Fa=e;var a=In;e=Hn;var s=32-rn(a)-1;a&=~(1<<s),n+=1;var i=32-rn(t)+s;if(30<i){var r=s-s%5;i=(a&(1<<r)-1).toString(32),a>>=r,s-=r,In=1<<32-rn(t)+s|n<<s|a,Hn=i+e}else In=1<<i|n<<s|a,Hn=e}function qd(e){e.return!==null&&(sa(e,1),tg(e,1,0))}function Gd(e){for(;e===uo;)uo=ti[--ni],ti[ni]=null,Ar=ti[--ni],ti[ni]=null;for(;e===Fa;)Fa=mn[--gn],mn[gn]=null,Hn=mn[--gn],mn[gn]=null,In=mn[--gn],mn[gn]=null}function ng(e,t){mn[gn++]=In,mn[gn++]=Hn,mn[gn++]=Fa,In=t.id,Hn=t.overflow,Fa=e}var Rt=null,Ye=null,we=!1,Ha=null,bn=!1,Du=Error(N(519));function Ja(e){var t=Error(N(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Cr(vn(t,e)),Du}function rf(e){var t=e.stateNode,n=e.type,a=e.memoizedProps;switch(t[Ot]=e,t[Jt]=a,n){case"dialog":ge("cancel",t),ge("close",t);break;case"iframe":case"object":case"embed":ge("load",t);break;case"video":case"audio":for(n=0;n<kr.length;n++)ge(kr[n],t);break;case"source":ge("error",t);break;case"img":case"image":case"link":ge("error",t),ge("load",t);break;case"details":ge("toggle",t);break;case"input":ge("invalid",t),jm(t,a.value,a.defaultValue,a.checked,a.defaultChecked,a.type,a.name,!0);break;case"select":ge("invalid",t);break;case"textarea":ge("invalid",t),Mm(t,a.value,a.defaultValue,a.children)}n=a.children,typeof n!="string"&&typeof n!="number"&&typeof n!="bigint"||t.textContent===""+n||a.suppressHydrationWarning===!0||By(t.textContent,n)?(a.popover!=null&&(ge("beforetoggle",t),ge("toggle",t)),a.onScroll!=null&&ge("scroll",t),a.onScrollEnd!=null&&ge("scrollend",t),a.onClick!=null&&(t.onclick=la),t=!0):t=!1,t||Ja(e,!0)}function lf(e){for(Rt=e.return;Rt;)switch(Rt.tag){case 5:case 31:case 13:bn=!1;return;case 27:case 3:bn=!0;return;default:Rt=Rt.return}}function ks(e){if(e!==Rt)return!1;if(!we)return lf(e),we=!0,!1;var t=e.tag,n;if((n=t!==3&&t!==27)&&((n=t===5)&&(n=e.type,n=!(n!=="form"&&n!=="button")||sd(e.type,e.memoizedProps)),n=!n),n&&Ye&&Ja(e),lf(e),t===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(N(317));Ye=Yf(e)}else if(t===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(N(317));Ye=Yf(e)}else t===27?(t=Ye,Za(e.type)?(e=od,od=null,Ye=e):Ye=t):Ye=Rt?_n(e.stateNode.nextSibling):null;return!0}function vs(){Ye=Rt=null,we=!1}function Nc(){var e=Ha;return e!==null&&(Yt===null?Yt=e:Yt.push.apply(Yt,e),Ha=null),e}function Cr(e){Ha===null?Ha=[e]:Ha.push(e)}var Mu=qn(null),Cs=null,oa=null;function Ca(e,t,n){Ge(Mu,t._currentValue),t._currentValue=n}function ua(e){e._currentValue=Mu.current,Tt(Mu)}function Uu(e,t,n){for(;e!==null;){var a=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,a!==null&&(a.childLanes|=t)):a!==null&&(a.childLanes&t)!==t&&(a.childLanes|=t),e===n)break;e=e.return}}function Lu(e,t,n,a){var s=e.child;for(s!==null&&(s.return=e);s!==null;){var i=s.dependencies;if(i!==null){var r=s.child;i=i.firstContext;e:for(;i!==null;){var l=i;i=s;for(var o=0;o<t.length;o++)if(l.context===t[o]){i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),Uu(i.return,n,e),a||(r=null);break e}i=l.next}}else if(s.tag===18){if(r=s.return,r===null)throw Error(N(341));r.lanes|=n,i=r.alternate,i!==null&&(i.lanes|=n),Uu(r,n,e),r=null}else r=s.child;if(r!==null)r.return=s;else for(r=s;r!==null;){if(r===e){r=null;break}if(s=r.sibling,s!==null){s.return=r.return,r=s;break}r=r.return}s=r}}function Ci(e,t,n,a){e=null;for(var s=t,i=!1;s!==null;){if(!i){if(s.flags&524288)i=!0;else if(s.flags&262144)break}if(s.tag===10){var r=s.alternate;if(r===null)throw Error(N(387));if(r=r.memoizedProps,r!==null){var l=s.type;on(s.pendingProps.value,r.value)||(e!==null?e.push(l):e=[l])}}else if(s===ao.current){if(r=s.alternate,r===null)throw Error(N(387));r.memoizedState.memoizedState!==s.memoizedState.memoizedState&&(e!==null?e.push(Dr):e=[Dr])}s=s.return}e!==null&&Lu(t,e,n,a),t.flags|=262144}function ho(e){for(e=e.firstContext;e!==null;){if(!on(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function bs(e){Cs=e,oa=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function Nt(e){return ag(Cs,e)}function yl(e,t){return Cs===null&&bs(e),ag(e,t)}function ag(e,t){var n=t._currentValue;if(t={context:t,memoizedValue:n,next:null},oa===null){if(e===null)throw Error(N(308));oa=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else oa=oa.next=t;return n}var d0=typeof AbortController<"u"?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(n,a){e.push(a)}};this.abort=function(){t.aborted=!0,e.forEach(function(n){return n()})}},h0=gt.unstable_scheduleCallback,f0=gt.unstable_NormalPriority,ut={$$typeof:ra,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Kd(){return{controller:new d0,data:new Map,refCount:0}}function Jr(e){e.refCount--,e.refCount===0&&h0(f0,function(){e.controller.abort()})}var cr=null,zu=0,yi=0,oi=null;function p0(e,t){if(cr===null){var n=cr=[];zu=0,yi=gh(),oi={status:"pending",value:void 0,then:function(a){n.push(a)}}}return zu++,t.then(of,of),t}function of(){if(--zu===0&&cr!==null){oi!==null&&(oi.status="fulfilled");var e=cr;cr=null,yi=0,oi=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function m0(e,t){var n=[],a={status:"pending",value:null,reason:null,then:function(s){n.push(s)}};return e.then(function(){a.status="fulfilled",a.value=t;for(var s=0;s<n.length;s++)(0,n[s])(t)},function(s){for(a.status="rejected",a.reason=s,s=0;s<n.length;s++)(0,n[s])(void 0)}),a}var cf=ne.S;ne.S=function(e,t){yy=an(),typeof t=="object"&&t!==null&&typeof t.then=="function"&&p0(e,t),cf!==null&&cf(e,t)};var ms=qn(null);function Vd(){var e=ms.current;return e!==null?e:He.pooledCache}function Kl(e,t){t===null?Ge(ms,ms.current):Ge(ms,t.pool)}function sg(){var e=Vd();return e===null?null:{parent:ut._currentValue,pool:e}}var Oi=Error(N(460)),Yd=Error(N(474)),Xo=Error(N(542)),fo={then:function(){}};function uf(e){return e=e.status,e==="fulfilled"||e==="rejected"}function ig(e,t,n){switch(n=e[n],n===void 0?e.push(t):n!==t&&(t.then(la,la),t=n),t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,hf(e),e;default:if(typeof t.status=="string")t.then(la,la);else{if(e=He,e!==null&&100<e.shellSuspendCounter)throw Error(N(482));e=t,e.status="pending",e.then(function(a){if(t.status==="pending"){var s=t;s.status="fulfilled",s.value=a}},function(a){if(t.status==="pending"){var s=t;s.status="rejected",s.reason=a}})}switch(t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,hf(e),e}throw gs=t,Oi}}function cs(e){try{var t=e._init;return t(e._payload)}catch(n){throw n!==null&&typeof n=="object"&&typeof n.then=="function"?(gs=n,Oi):n}}var gs=null;function df(){if(gs===null)throw Error(N(459));var e=gs;return gs=null,e}function hf(e){if(e===Oi||e===Xo)throw Error(N(483))}var ci=null,Or=0;function vl(e){var t=Or;return Or+=1,ci===null&&(ci=[]),ig(ci,e,t)}function qi(e,t){t=t.props.ref,e.ref=t!==void 0?t:null}function bl(e,t){throw t.$$typeof===tb?Error(N(525)):(e=Object.prototype.toString.call(t),Error(N(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)))}function rg(e){function t(g,m){if(e){var y=g.deletions;y===null?(g.deletions=[m],g.flags|=16):y.push(m)}}function n(g,m){if(!e)return null;for(;m!==null;)t(g,m),m=m.sibling;return null}function a(g){for(var m=new Map;g!==null;)g.key!==null?m.set(g.key,g):m.set(g.index,g),g=g.sibling;return m}function s(g,m){return g=ca(g,m),g.index=0,g.sibling=null,g}function i(g,m,y){return g.index=y,e?(y=g.alternate,y!==null?(y=y.index,y<m?(g.flags|=67108866,m):y):(g.flags|=67108866,m)):(g.flags|=1048576,m)}function r(g){return e&&g.alternate===null&&(g.flags|=67108866),g}function l(g,m,y,w){return m===null||m.tag!==6?(m=Oc(y,g.mode,w),m.return=g,m):(m=s(m,y),m.return=g,m)}function o(g,m,y,w){var C=y.type;return C===Vs?h(g,m,y.props.children,w,y.key):m!==null&&(m.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===Ea&&cs(C)===m.type)?(m=s(m,y.props),qi(m,y),m.return=g,m):(m=Gl(y.type,y.key,y.props,null,g.mode,w),qi(m,y),m.return=g,m)}function u(g,m,y,w){return m===null||m.tag!==4||m.stateNode.containerInfo!==y.containerInfo||m.stateNode.implementation!==y.implementation?(m=Rc(y,g.mode,w),m.return=g,m):(m=s(m,y.children||[]),m.return=g,m)}function h(g,m,y,w,C){return m===null||m.tag!==7?(m=ps(y,g.mode,w,C),m.return=g,m):(m=s(m,y),m.return=g,m)}function f(g,m,y){if(typeof m=="string"&&m!==""||typeof m=="number"||typeof m=="bigint")return m=Oc(""+m,g.mode,y),m.return=g,m;if(typeof m=="object"&&m!==null){switch(m.$$typeof){case dl:return y=Gl(m.type,m.key,m.props,null,g.mode,y),qi(y,m),y.return=g,y;case Qi:return m=Rc(m,g.mode,y),m.return=g,m;case Ea:return m=cs(m),f(g,m,y)}if(Wi(m)||Hi(m))return m=ps(m,g.mode,y,null),m.return=g,m;if(typeof m.then=="function")return f(g,vl(m),y);if(m.$$typeof===ra)return f(g,yl(g,m),y);bl(g,m)}return null}function d(g,m,y,w){var C=m!==null?m.key:null;if(typeof y=="string"&&y!==""||typeof y=="number"||typeof y=="bigint")return C!==null?null:l(g,m,""+y,w);if(typeof y=="object"&&y!==null){switch(y.$$typeof){case dl:return y.key===C?o(g,m,y,w):null;case Qi:return y.key===C?u(g,m,y,w):null;case Ea:return y=cs(y),d(g,m,y,w)}if(Wi(y)||Hi(y))return C!==null?null:h(g,m,y,w,null);if(typeof y.then=="function")return d(g,m,vl(y),w);if(y.$$typeof===ra)return d(g,m,yl(g,y),w);bl(g,y)}return null}function p(g,m,y,w,C){if(typeof w=="string"&&w!==""||typeof w=="number"||typeof w=="bigint")return g=g.get(y)||null,l(m,g,""+w,C);if(typeof w=="object"&&w!==null){switch(w.$$typeof){case dl:return g=g.get(w.key===null?y:w.key)||null,o(m,g,w,C);case Qi:return g=g.get(w.key===null?y:w.key)||null,u(m,g,w,C);case Ea:return w=cs(w),p(g,m,y,w,C)}if(Wi(w)||Hi(w))return g=g.get(y)||null,h(m,g,w,C,null);if(typeof w.then=="function")return p(g,m,y,vl(w),C);if(w.$$typeof===ra)return p(g,m,y,yl(m,w),C);bl(m,w)}return null}function v(g,m,y,w){for(var C=null,R=null,O=m,z=m=0,q=null;O!==null&&z<y.length;z++){O.index>z?(q=O,O=null):q=O.sibling;var K=d(g,O,y[z],w);if(K===null){O===null&&(O=q);break}e&&O&&K.alternate===null&&t(g,O),m=i(K,m,z),R===null?C=K:R.sibling=K,R=K,O=q}if(z===y.length)return n(g,O),we&&sa(g,z),C;if(O===null){for(;z<y.length;z++)O=f(g,y[z],w),O!==null&&(m=i(O,m,z),R===null?C=O:R.sibling=O,R=O);return we&&sa(g,z),C}for(O=a(O);z<y.length;z++)q=p(O,g,z,y[z],w),q!==null&&(e&&q.alternate!==null&&O.delete(q.key===null?z:q.key),m=i(q,m,z),R===null?C=q:R.sibling=q,R=q);return e&&O.forEach(function(ve){return t(g,ve)}),we&&sa(g,z),C}function _(g,m,y,w){if(y==null)throw Error(N(151));for(var C=null,R=null,O=m,z=m=0,q=null,K=y.next();O!==null&&!K.done;z++,K=y.next()){O.index>z?(q=O,O=null):q=O.sibling;var ve=d(g,O,K.value,w);if(ve===null){O===null&&(O=q);break}e&&O&&ve.alternate===null&&t(g,O),m=i(ve,m,z),R===null?C=ve:R.sibling=ve,R=ve,O=q}if(K.done)return n(g,O),we&&sa(g,z),C;if(O===null){for(;!K.done;z++,K=y.next())K=f(g,K.value,w),K!==null&&(m=i(K,m,z),R===null?C=K:R.sibling=K,R=K);return we&&sa(g,z),C}for(O=a(O);!K.done;z++,K=y.next())K=p(O,g,z,K.value,w),K!==null&&(e&&K.alternate!==null&&O.delete(K.key===null?z:K.key),m=i(K,m,z),R===null?C=K:R.sibling=K,R=K);return e&&O.forEach(function(Ae){return t(g,Ae)}),we&&sa(g,z),C}function x(g,m,y,w){if(typeof y=="object"&&y!==null&&y.type===Vs&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case dl:e:{for(var C=y.key;m!==null;){if(m.key===C){if(C=y.type,C===Vs){if(m.tag===7){n(g,m.sibling),w=s(m,y.props.children),w.return=g,g=w;break e}}else if(m.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===Ea&&cs(C)===m.type){n(g,m.sibling),w=s(m,y.props),qi(w,y),w.return=g,g=w;break e}n(g,m);break}else t(g,m);m=m.sibling}y.type===Vs?(w=ps(y.props.children,g.mode,w,y.key),w.return=g,g=w):(w=Gl(y.type,y.key,y.props,null,g.mode,w),qi(w,y),w.return=g,g=w)}return r(g);case Qi:e:{for(C=y.key;m!==null;){if(m.key===C)if(m.tag===4&&m.stateNode.containerInfo===y.containerInfo&&m.stateNode.implementation===y.implementation){n(g,m.sibling),w=s(m,y.children||[]),w.return=g,g=w;break e}else{n(g,m);break}else t(g,m);m=m.sibling}w=Rc(y,g.mode,w),w.return=g,g=w}return r(g);case Ea:return y=cs(y),x(g,m,y,w)}if(Wi(y))return v(g,m,y,w);if(Hi(y)){if(C=Hi(y),typeof C!="function")throw Error(N(150));return y=C.call(y),_(g,m,y,w)}if(typeof y.then=="function")return x(g,m,vl(y),w);if(y.$$typeof===ra)return x(g,m,yl(g,y),w);bl(g,y)}return typeof y=="string"&&y!==""||typeof y=="number"||typeof y=="bigint"?(y=""+y,m!==null&&m.tag===6?(n(g,m.sibling),w=s(m,y),w.return=g,g=w):(n(g,m),w=Oc(y,g.mode,w),w.return=g,g=w),r(g)):n(g,m)}return function(g,m,y,w){try{Or=0;var C=x(g,m,y,w);return ci=null,C}catch(O){if(O===Oi||O===Xo)throw O;var R=Zt(29,O,null,g.mode);return R.lanes=w,R.return=g,R}finally{}}}var Ss=rg(!0),lg=rg(!1),Aa=!1;function Fd(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Bu(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function $a(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Pa(e,t,n){var a=e.updateQueue;if(a===null)return null;if(a=a.shared,je&2){var s=a.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),a.pending=t,t=co(e),Wm(e,null,n),t}return Jo(e,a,t,n),co(e)}function ur(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194048)!==0)){var a=t.lanes;a&=e.pendingLanes,n|=a,t.lanes=n,Em(e,n)}}function kc(e,t){var n=e.updateQueue,a=e.alternate;if(a!==null&&(a=a.updateQueue,n===a)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var r={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};i===null?s=i=r:i=i.next=r,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:a.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:a.shared,callbacks:a.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Iu=!1;function dr(){if(Iu){var e=oi;if(e!==null)throw e}}function hr(e,t,n,a){Iu=!1;var s=e.updateQueue;Aa=!1;var i=s.firstBaseUpdate,r=s.lastBaseUpdate,l=s.shared.pending;if(l!==null){s.shared.pending=null;var o=l,u=o.next;o.next=null,r===null?i=u:r.next=u,r=o;var h=e.alternate;h!==null&&(h=h.updateQueue,l=h.lastBaseUpdate,l!==r&&(l===null?h.firstBaseUpdate=u:l.next=u,h.lastBaseUpdate=o))}if(i!==null){var f=s.baseState;r=0,h=u=o=null,l=i;do{var d=l.lane&-536870913,p=d!==l.lane;if(p?(Se&d)===d:(a&d)===d){d!==0&&d===yi&&(Iu=!0),h!==null&&(h=h.next={lane:0,tag:l.tag,payload:l.payload,callback:null,next:null});e:{var v=e,_=l;d=t;var x=n;switch(_.tag){case 1:if(v=_.payload,typeof v=="function"){f=v.call(x,f,d);break e}f=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=_.payload,d=typeof v=="function"?v.call(x,f,d):v,d==null)break e;f=Fe({},f,d);break e;case 2:Aa=!0}}d=l.callback,d!==null&&(e.flags|=64,p&&(e.flags|=8192),p=s.callbacks,p===null?s.callbacks=[d]:p.push(d))}else p={lane:d,tag:l.tag,payload:l.payload,callback:l.callback,next:null},h===null?(u=h=p,o=f):h=h.next=p,r|=d;if(l=l.next,l===null){if(l=s.shared.pending,l===null)break;p=l,l=p.next,p.next=null,s.lastBaseUpdate=p,s.shared.pending=null}}while(!0);h===null&&(o=f),s.baseState=o,s.firstBaseUpdate=u,s.lastBaseUpdate=h,i===null&&(s.shared.lanes=0),Qa|=r,e.lanes=r,e.memoizedState=f}}function og(e,t){if(typeof e!="function")throw Error(N(191,e));e.call(t)}function cg(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;e<n.length;e++)og(n[e],t)}var vi=qn(null),po=qn(0);function ff(e,t){e=ga,Ge(po,e),Ge(vi,t),ga=e|t.baseLanes}function Hu(){Ge(po,ga),Ge(vi,vi.current)}function Jd(){ga=po.current,Tt(vi),Tt(po)}var cn=qn(null),Sn=null;function Oa(e){var t=e.alternate;Ge(at,at.current&1),Ge(cn,e),Sn===null&&(t===null||vi.current!==null||t.memoizedState!==null)&&(Sn=e)}function $u(e){Ge(at,at.current),Ge(cn,e),Sn===null&&(Sn=e)}function ug(e){e.tag===22?(Ge(at,at.current),Ge(cn,e),Sn===null&&(Sn=e)):Ra()}function Ra(){Ge(at,at.current),Ge(cn,cn.current)}function Wt(e){Tt(cn),Sn===e&&(Sn=null),Tt(at)}var at=qn(0);function mo(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||rd(n)||ld(n)))return t}else if(t.tag===19&&(t.memoizedProps.revealOrder==="forwards"||t.memoizedProps.revealOrder==="backwards"||t.memoizedProps.revealOrder==="unstable_legacy-backwards"||t.memoizedProps.revealOrder==="together")){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var fa=0,oe=null,Be=null,ot=null,go=!1,ui=!1,_s=!1,yo=0,Rr=0,di=null,g0=0;function We(){throw Error(N(321))}function Xd(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!on(e[n],t[n]))return!1;return!0}function Qd(e,t,n,a,s,i){return fa=i,oe=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,ne.H=e===null||e.memoizedState===null?$g:oh,_s=!1,i=n(a,s),_s=!1,ui&&(i=hg(t,n,a,s)),dg(e),i}function dg(e){ne.H=Nr;var t=Be!==null&&Be.next!==null;if(fa=0,ot=Be=oe=null,go=!1,Rr=0,di=null,t)throw Error(N(300));e===null||dt||(e=e.dependencies,e!==null&&ho(e)&&(dt=!0))}function hg(e,t,n,a){oe=e;var s=0;do{if(ui&&(di=null),Rr=0,ui=!1,25<=s)throw Error(N(301));if(s+=1,ot=Be=null,e.updateQueue!=null){var i=e.updateQueue;i.lastEffect=null,i.events=null,i.stores=null,i.memoCache!=null&&(i.memoCache.index=0)}ne.H=Pg,i=t(n,a)}while(ui);return i}function y0(){var e=ne.H,t=e.useState()[0];return t=typeof t.then=="function"?Xr(t):t,e=e.useState()[0],(Be!==null?Be.memoizedState:null)!==e&&(oe.flags|=1024),t}function Wd(){var e=yo!==0;return yo=0,e}function Zd(e,t,n){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~n}function eh(e){if(go){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}go=!1}fa=0,ot=Be=oe=null,ui=!1,Rr=yo=0,di=null}function $t(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ot===null?oe.memoizedState=ot=e:ot=ot.next=e,ot}function st(){if(Be===null){var e=oe.alternate;e=e!==null?e.memoizedState:null}else e=Be.next;var t=ot===null?oe.memoizedState:ot.next;if(t!==null)ot=t,Be=e;else{if(e===null)throw oe.alternate===null?Error(N(467)):Error(N(310));Be=e,e={memoizedState:Be.memoizedState,baseState:Be.baseState,baseQueue:Be.baseQueue,queue:Be.queue,next:null},ot===null?oe.memoizedState=ot=e:ot=ot.next=e}return ot}function Qo(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Xr(e){var t=Rr;return Rr+=1,di===null&&(di=[]),e=ig(di,e,t),t=oe,(ot===null?t.memoizedState:ot.next)===null&&(t=t.alternate,ne.H=t===null||t.memoizedState===null?$g:oh),e}function Wo(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return Xr(e);if(e.$$typeof===ra)return Nt(e)}throw Error(N(438,String(e)))}function th(e){var t=null,n=oe.updateQueue;if(n!==null&&(t=n.memoCache),t==null){var a=oe.alternate;a!==null&&(a=a.updateQueue,a!==null&&(a=a.memoCache,a!=null&&(t={data:a.data.map(function(s){return s.slice()}),index:0})))}if(t==null&&(t={data:[],index:0}),n===null&&(n=Qo(),oe.updateQueue=n),n.memoCache=t,n=t.data[t.index],n===void 0)for(n=t.data[t.index]=Array(e),a=0;a<e;a++)n[a]=nb;return t.index++,n}function pa(e,t){return typeof t=="function"?t(e):t}function Vl(e){var t=st();return nh(t,Be,e)}function nh(e,t,n){var a=e.queue;if(a===null)throw Error(N(311));a.lastRenderedReducer=n;var s=e.baseQueue,i=a.pending;if(i!==null){if(s!==null){var r=s.next;s.next=i.next,i.next=r}t.baseQueue=s=i,a.pending=null}if(i=e.baseState,s===null)e.memoizedState=i;else{t=s.next;var l=r=null,o=null,u=t,h=!1;do{var f=u.lane&-536870913;if(f!==u.lane?(Se&f)===f:(fa&f)===f){var d=u.revertLane;if(d===0)o!==null&&(o=o.next={lane:0,revertLane:0,gesture:null,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),f===yi&&(h=!0);else if((fa&d)===d){u=u.next,d===yi&&(h=!0);continue}else f={lane:0,revertLane:u.revertLane,gesture:null,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null},o===null?(l=o=f,r=i):o=o.next=f,oe.lanes|=d,Qa|=d;f=u.action,_s&&n(i,f),i=u.hasEagerState?u.eagerState:n(i,f)}else d={lane:f,revertLane:u.revertLane,gesture:u.gesture,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null},o===null?(l=o=d,r=i):o=o.next=d,oe.lanes|=f,Qa|=f;u=u.next}while(u!==null&&u!==t);if(o===null?r=i:o.next=l,!on(i,e.memoizedState)&&(dt=!0,h&&(n=oi,n!==null)))throw n;e.memoizedState=i,e.baseState=r,e.baseQueue=o,a.lastRenderedState=i}return s===null&&(a.lanes=0),[e.memoizedState,a.dispatch]}function jc(e){var t=st(),n=t.queue;if(n===null)throw Error(N(311));n.lastRenderedReducer=e;var a=n.dispatch,s=n.pending,i=t.memoizedState;if(s!==null){n.pending=null;var r=s=s.next;do i=e(i,r.action),r=r.next;while(r!==s);on(i,t.memoizedState)||(dt=!0),t.memoizedState=i,t.baseQueue===null&&(t.baseState=i),n.lastRenderedState=i}return[i,a]}function fg(e,t,n){var a=oe,s=st(),i=we;if(i){if(n===void 0)throw Error(N(407));n=n()}else n=t();var r=!on((Be||s).memoizedState,n);if(r&&(s.memoizedState=n,dt=!0),s=s.queue,ah(gg.bind(null,a,s,e),[e]),s.getSnapshot!==t||r||ot!==null&&ot.memoizedState.tag&1){if(a.flags|=2048,bi(9,{destroy:void 0},mg.bind(null,a,s,n,t),null),He===null)throw Error(N(349));i||fa&127||pg(a,t,n)}return n}function pg(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=oe.updateQueue,t===null?(t=Qo(),oe.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function mg(e,t,n,a){t.value=n,t.getSnapshot=a,yg(t)&&vg(e)}function gg(e,t,n){return n(function(){yg(t)&&vg(e)})}function yg(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!on(e,n)}catch{return!0}}function vg(e){var t=As(e,2);t!==null&&Ft(t,e,2)}function Pu(e){var t=$t();if(typeof e=="function"){var n=e;if(e=n(),_s){Ma(!0);try{n()}finally{Ma(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:pa,lastRenderedState:e},t}function bg(e,t,n,a){return e.baseState=n,nh(e,Be,typeof a=="function"?a:pa)}function v0(e,t,n,a,s){if(ec(e))throw Error(N(485));if(e=t.action,e!==null){var i={payload:s,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(r){i.listeners.push(r)}};ne.T!==null?n(!0):i.isTransition=!1,a(i),n=t.pending,n===null?(i.next=t.pending=i,Sg(t,i)):(i.next=n.next,t.pending=n.next=i)}}function Sg(e,t){var n=t.action,a=t.payload,s=e.state;if(t.isTransition){var i=ne.T,r={};ne.T=r;try{var l=n(s,a),o=ne.S;o!==null&&o(r,l),pf(e,t,l)}catch(u){qu(e,t,u)}finally{i!==null&&r.types!==null&&(i.types=r.types),ne.T=i}}else try{i=n(s,a),pf(e,t,i)}catch(u){qu(e,t,u)}}function pf(e,t,n){n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(function(a){mf(e,t,a)},function(a){return qu(e,t,a)}):mf(e,t,n)}function mf(e,t,n){t.status="fulfilled",t.value=n,_g(t),e.state=n,t=e.pending,t!==null&&(n=t.next,n===t?e.pending=null:(n=n.next,t.next=n,Sg(e,n)))}function qu(e,t,n){var a=e.pending;if(e.pending=null,a!==null){a=a.next;do t.status="rejected",t.reason=n,_g(t),t=t.next;while(t!==a)}e.action=null}function _g(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function wg(e,t){return t}function gf(e,t){if(we){var n=He.formState;if(n!==null){e:{var a=oe;if(we){if(Ye){t:{for(var s=Ye,i=bn;s.nodeType!==8;){if(!i){s=null;break t}if(s=_n(s.nextSibling),s===null){s=null;break t}}i=s.data,s=i==="F!"||i==="F"?s:null}if(s){Ye=_n(s.nextSibling),a=s.data==="F!";break e}}Ja(a)}a=!1}a&&(t=n[0])}}return n=$t(),n.memoizedState=n.baseState=t,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:wg,lastRenderedState:t},n.queue=a,n=Bg.bind(null,oe,a),a.dispatch=n,a=Pu(!1),i=lh.bind(null,oe,!1,a.queue),a=$t(),s={state:t,dispatch:null,action:e,pending:null},a.queue=s,n=v0.bind(null,oe,s,i,n),s.dispatch=n,a.memoizedState=e,[t,n,!1]}function yf(e){var t=st();return xg(t,Be,e)}function xg(e,t,n){if(t=nh(e,t,wg)[0],e=Vl(pa)[0],typeof t=="object"&&t!==null&&typeof t.then=="function")try{var a=Xr(t)}catch(r){throw r===Oi?Xo:r}else a=t;t=st();var s=t.queue,i=s.dispatch;return n!==t.memoizedState&&(oe.flags|=2048,bi(9,{destroy:void 0},b0.bind(null,s,n),null)),[a,i,e]}function b0(e,t){e.action=t}function vf(e){var t=st(),n=Be;if(n!==null)return xg(t,n,e);st(),t=t.memoizedState,n=st();var a=n.queue.dispatch;return n.memoizedState=e,[t,a,!1]}function bi(e,t,n,a){return e={tag:e,create:n,deps:a,inst:t,next:null},t=oe.updateQueue,t===null&&(t=Qo(),oe.updateQueue=t),n=t.lastEffect,n===null?t.lastEffect=e.next=e:(a=n.next,n.next=e,e.next=a,t.lastEffect=e),e}function Tg(){return st().memoizedState}function Yl(e,t,n,a){var s=$t();oe.flags|=e,s.memoizedState=bi(1|t,{destroy:void 0},n,a===void 0?null:a)}function Zo(e,t,n,a){var s=st();a=a===void 0?null:a;var i=s.memoizedState.inst;Be!==null&&a!==null&&Xd(a,Be.memoizedState.deps)?s.memoizedState=bi(t,i,n,a):(oe.flags|=e,s.memoizedState=bi(1|t,i,n,a))}function bf(e,t){Yl(8390656,8,e,t)}function ah(e,t){Zo(2048,8,e,t)}function S0(e){oe.flags|=4;var t=oe.updateQueue;if(t===null)t=Qo(),oe.updateQueue=t,t.events=[e];else{var n=t.events;n===null?t.events=[e]:n.push(e)}}function Eg(e){var t=st().memoizedState;return S0({ref:t,nextImpl:e}),function(){if(je&2)throw Error(N(440));return t.impl.apply(void 0,arguments)}}function Ag(e,t){return Zo(4,2,e,t)}function Cg(e,t){return Zo(4,4,e,t)}function Og(e,t){if(typeof t=="function"){e=e();var n=t(e);return function(){typeof n=="function"?n():t(null)}}if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Rg(e,t,n){n=n!=null?n.concat([e]):null,Zo(4,4,Og.bind(null,t,e),n)}function sh(){}function Ng(e,t){var n=st();t=t===void 0?null:t;var a=n.memoizedState;return t!==null&&Xd(t,a[1])?a[0]:(n.memoizedState=[e,t],e)}function kg(e,t){var n=st();t=t===void 0?null:t;var a=n.memoizedState;if(t!==null&&Xd(t,a[1]))return a[0];if(a=e(),_s){Ma(!0);try{e()}finally{Ma(!1)}}return n.memoizedState=[a,t],a}function ih(e,t,n){return n===void 0||fa&1073741824&&!(Se&261930)?e.memoizedState=t:(e.memoizedState=n,e=by(),oe.lanes|=e,Qa|=e,n)}function jg(e,t,n,a){return on(n,t)?n:vi.current!==null?(e=ih(e,n,a),on(e,t)||(dt=!0),e):!(fa&42)||fa&1073741824&&!(Se&261930)?(dt=!0,e.memoizedState=n):(e=by(),oe.lanes|=e,Qa|=e,t)}function Dg(e,t,n,a,s){var i=De.p;De.p=i!==0&&8>i?i:8;var r=ne.T,l={};ne.T=l,lh(e,!1,t,n);try{var o=s(),u=ne.S;if(u!==null&&u(l,o),o!==null&&typeof o=="object"&&typeof o.then=="function"){var h=m0(o,a);fr(e,t,h,ln(e))}else fr(e,t,a,ln(e))}catch(f){fr(e,t,{then:function(){},status:"rejected",reason:f},ln())}finally{De.p=i,r!==null&&l.types!==null&&(r.types=l.types),ne.T=r}}function _0(){}function Gu(e,t,n,a){if(e.tag!==5)throw Error(N(476));var s=Mg(e).queue;Dg(e,s,t,fs,n===null?_0:function(){return Ug(e),n(a)})}function Mg(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:fs,baseState:fs,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:pa,lastRenderedState:fs},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:pa,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ug(e){var t=Mg(e);t.next===null&&(t=e.alternate.memoizedState),fr(e,t.next.queue,{},ln())}function rh(){return Nt(Dr)}function Lg(){return st().memoizedState}function zg(){return st().memoizedState}function w0(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=ln();e=$a(n);var a=Pa(t,e,n);a!==null&&(Ft(a,t,n),ur(a,t,n)),t={cache:Kd()},e.payload=t;return}t=t.return}}function x0(e,t,n){var a=ln();n={lane:a,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},ec(e)?Ig(t,n):(n=$d(e,t,n,a),n!==null&&(Ft(n,e,a),Hg(n,t,a)))}function Bg(e,t,n){var a=ln();fr(e,t,n,a)}function fr(e,t,n,a){var s={lane:a,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(ec(e))Ig(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var r=t.lastRenderedState,l=i(r,n);if(s.hasEagerState=!0,s.eagerState=l,on(l,r))return Jo(e,t,s,0),He===null&&Fo(),!1}catch{}finally{}if(n=$d(e,t,s,a),n!==null)return Ft(n,e,a),Hg(n,t,a),!0}return!1}function lh(e,t,n,a){if(a={lane:2,revertLane:gh(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},ec(e)){if(t)throw Error(N(479))}else t=$d(e,n,a,2),t!==null&&Ft(t,e,2)}function ec(e){var t=e.alternate;return e===oe||t!==null&&t===oe}function Ig(e,t){ui=go=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Hg(e,t,n){if(n&4194048){var a=t.lanes;a&=e.pendingLanes,n|=a,t.lanes=n,Em(e,n)}}var Nr={readContext:Nt,use:Wo,useCallback:We,useContext:We,useEffect:We,useImperativeHandle:We,useLayoutEffect:We,useInsertionEffect:We,useMemo:We,useReducer:We,useRef:We,useState:We,useDebugValue:We,useDeferredValue:We,useTransition:We,useSyncExternalStore:We,useId:We,useHostTransitionStatus:We,useFormState:We,useActionState:We,useOptimistic:We,useMemoCache:We,useCacheRefresh:We};Nr.useEffectEvent=We;var $g={readContext:Nt,use:Wo,useCallback:function(e,t){return $t().memoizedState=[e,t===void 0?null:t],e},useContext:Nt,useEffect:bf,useImperativeHandle:function(e,t,n){n=n!=null?n.concat([e]):null,Yl(4194308,4,Og.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Yl(4194308,4,e,t)},useInsertionEffect:function(e,t){Yl(4,2,e,t)},useMemo:function(e,t){var n=$t();t=t===void 0?null:t;var a=e();if(_s){Ma(!0);try{e()}finally{Ma(!1)}}return n.memoizedState=[a,t],a},useReducer:function(e,t,n){var a=$t();if(n!==void 0){var s=n(t);if(_s){Ma(!0);try{n(t)}finally{Ma(!1)}}}else s=t;return a.memoizedState=a.baseState=s,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:s},a.queue=e,e=e.dispatch=x0.bind(null,oe,e),[a.memoizedState,e]},useRef:function(e){var t=$t();return e={current:e},t.memoizedState=e},useState:function(e){e=Pu(e);var t=e.queue,n=Bg.bind(null,oe,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:sh,useDeferredValue:function(e,t){var n=$t();return ih(n,e,t)},useTransition:function(){var e=Pu(!1);return e=Dg.bind(null,oe,e.queue,!0,!1),$t().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var a=oe,s=$t();if(we){if(n===void 0)throw Error(N(407));n=n()}else{if(n=t(),He===null)throw Error(N(349));Se&127||pg(a,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,bf(gg.bind(null,a,i,e),[e]),a.flags|=2048,bi(9,{destroy:void 0},mg.bind(null,a,i,n,t),null),n},useId:function(){var e=$t(),t=He.identifierPrefix;if(we){var n=Hn,a=In;n=(a&~(1<<32-rn(a)-1)).toString(32)+n,t="_"+t+"R_"+n,n=yo++,0<n&&(t+="H"+n.toString(32)),t+="_"}else n=g0++,t="_"+t+"r_"+n.toString(32)+"_";return e.memoizedState=t},useHostTransitionStatus:rh,useFormState:gf,useActionState:gf,useOptimistic:function(e){var t=$t();t.memoizedState=t.baseState=e;var n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=n,t=lh.bind(null,oe,!0,n),n.dispatch=t,[e,t]},useMemoCache:th,useCacheRefresh:function(){return $t().memoizedState=w0.bind(null,oe)},useEffectEvent:function(e){var t=$t(),n={impl:e};return t.memoizedState=n,function(){if(je&2)throw Error(N(440));return n.impl.apply(void 0,arguments)}}},oh={readContext:Nt,use:Wo,useCallback:Ng,useContext:Nt,useEffect:ah,useImperativeHandle:Rg,useInsertionEffect:Ag,useLayoutEffect:Cg,useMemo:kg,useReducer:Vl,useRef:Tg,useState:function(){return Vl(pa)},useDebugValue:sh,useDeferredValue:function(e,t){var n=st();return jg(n,Be.memoizedState,e,t)},useTransition:function(){var e=Vl(pa)[0],t=st().memoizedState;return[typeof e=="boolean"?e:Xr(e),t]},useSyncExternalStore:fg,useId:Lg,useHostTransitionStatus:rh,useFormState:yf,useActionState:yf,useOptimistic:function(e,t){var n=st();return bg(n,Be,e,t)},useMemoCache:th,useCacheRefresh:zg};oh.useEffectEvent=Eg;var Pg={readContext:Nt,use:Wo,useCallback:Ng,useContext:Nt,useEffect:ah,useImperativeHandle:Rg,useInsertionEffect:Ag,useLayoutEffect:Cg,useMemo:kg,useReducer:jc,useRef:Tg,useState:function(){return jc(pa)},useDebugValue:sh,useDeferredValue:function(e,t){var n=st();return Be===null?ih(n,e,t):jg(n,Be.memoizedState,e,t)},useTransition:function(){var e=jc(pa)[0],t=st().memoizedState;return[typeof e=="boolean"?e:Xr(e),t]},useSyncExternalStore:fg,useId:Lg,useHostTransitionStatus:rh,useFormState:vf,useActionState:vf,useOptimistic:function(e,t){var n=st();return Be!==null?bg(n,Be,e,t):(n.baseState=e,[e,n.queue.dispatch])},useMemoCache:th,useCacheRefresh:zg};Pg.useEffectEvent=Eg;function Dc(e,t,n,a){t=e.memoizedState,n=n(a,t),n=n==null?t:Fe({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var Ku={enqueueSetState:function(e,t,n){e=e._reactInternals;var a=ln(),s=$a(a);s.payload=t,n!=null&&(s.callback=n),t=Pa(e,s,a),t!==null&&(Ft(t,e,a),ur(t,e,a))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var a=ln(),s=$a(a);s.tag=1,s.payload=t,n!=null&&(s.callback=n),t=Pa(e,s,a),t!==null&&(Ft(t,e,a),ur(t,e,a))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=ln(),a=$a(n);a.tag=2,t!=null&&(a.callback=t),t=Pa(e,a,n),t!==null&&(Ft(t,e,n),ur(t,e,n))}};function Sf(e,t,n,a,s,i,r){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(a,i,r):t.prototype&&t.prototype.isPureReactComponent?!Er(n,a)||!Er(s,i):!0}function _f(e,t,n,a){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(n,a),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(n,a),t.state!==e&&Ku.enqueueReplaceState(t,t.state,null)}function ws(e,t){var n=t;if("ref"in t){n={};for(var a in t)a!=="ref"&&(n[a]=t[a])}if(e=e.defaultProps){n===t&&(n=Fe({},n));for(var s in e)n[s]===void 0&&(n[s]=e[s])}return n}function qg(e){oo(e)}function Gg(e){console.error(e)}function Kg(e){oo(e)}function vo(e,t){try{var n=e.onUncaughtError;n(t.value,{componentStack:t.stack})}catch(a){setTimeout(function(){throw a})}}function wf(e,t,n){try{var a=e.onCaughtError;a(n.value,{componentStack:n.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(s){setTimeout(function(){throw s})}}function Vu(e,t,n){return n=$a(n),n.tag=3,n.payload={element:null},n.callback=function(){vo(e,t)},n}function Vg(e){return e=$a(e),e.tag=3,e}function Yg(e,t,n,a){var s=n.type.getDerivedStateFromError;if(typeof s=="function"){var i=a.value;e.payload=function(){return s(i)},e.callback=function(){wf(t,n,a)}}var r=n.stateNode;r!==null&&typeof r.componentDidCatch=="function"&&(e.callback=function(){wf(t,n,a),typeof s!="function"&&(qa===null?qa=new Set([this]):qa.add(this));var l=a.stack;this.componentDidCatch(a.value,{componentStack:l!==null?l:""})})}function T0(e,t,n,a,s){if(n.flags|=32768,a!==null&&typeof a=="object"&&typeof a.then=="function"){if(t=n.alternate,t!==null&&Ci(t,n,s,!0),n=cn.current,n!==null){switch(n.tag){case 31:case 13:return Sn===null?xo():n.alternate===null&&et===0&&(et=3),n.flags&=-257,n.flags|=65536,n.lanes=s,a===fo?n.flags|=16384:(t=n.updateQueue,t===null?n.updateQueue=new Set([a]):t.add(a),Gc(e,a,s)),!1;case 22:return n.flags|=65536,a===fo?n.flags|=16384:(t=n.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([a])},n.updateQueue=t):(n=t.retryQueue,n===null?t.retryQueue=new Set([a]):n.add(a)),Gc(e,a,s)),!1}throw Error(N(435,n.tag))}return Gc(e,a,s),xo(),!1}if(we)return t=cn.current,t!==null?(!(t.flags&65536)&&(t.flags|=256),t.flags|=65536,t.lanes=s,a!==Du&&(e=Error(N(422),{cause:a}),Cr(vn(e,n)))):(a!==Du&&(t=Error(N(423),{cause:a}),Cr(vn(t,n))),e=e.current.alternate,e.flags|=65536,s&=-s,e.lanes|=s,a=vn(a,n),s=Vu(e.stateNode,a,s),kc(e,s),et!==4&&(et=2)),!1;var i=Error(N(520),{cause:a});if(i=vn(i,n),gr===null?gr=[i]:gr.push(i),et!==4&&(et=2),t===null)return!0;a=vn(a,n),n=t;do{switch(n.tag){case 3:return n.flags|=65536,e=s&-s,n.lanes|=e,e=Vu(n.stateNode,a,e),kc(n,e),!1;case 1:if(t=n.type,i=n.stateNode,(n.flags&128)===0&&(typeof t.getDerivedStateFromError=="function"||i!==null&&typeof i.componentDidCatch=="function"&&(qa===null||!qa.has(i))))return n.flags|=65536,s&=-s,n.lanes|=s,s=Vg(s),Yg(s,e,n,a),kc(n,s),!1}n=n.return}while(n!==null);return!1}var ch=Error(N(461)),dt=!1;function Ct(e,t,n,a){t.child=e===null?lg(t,null,n,a):Ss(t,e.child,n,a)}function xf(e,t,n,a,s){n=n.render;var i=t.ref;if("ref"in a){var r={};for(var l in a)l!=="ref"&&(r[l]=a[l])}else r=a;return bs(t),a=Qd(e,t,n,r,i,s),l=Wd(),e!==null&&!dt?(Zd(e,t,s),ma(e,t,s)):(we&&l&&qd(t),t.flags|=1,Ct(e,t,a,s),t.child)}function Tf(e,t,n,a,s){if(e===null){var i=n.type;return typeof i=="function"&&!Pd(i)&&i.defaultProps===void 0&&n.compare===null?(t.tag=15,t.type=i,Fg(e,t,i,a,s)):(e=Gl(n.type,null,a,t,t.mode,s),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,!uh(e,s)){var r=i.memoizedProps;if(n=n.compare,n=n!==null?n:Er,n(r,a)&&e.ref===t.ref)return ma(e,t,s)}return t.flags|=1,e=ca(i,a),e.ref=t.ref,e.return=t,t.child=e}function Fg(e,t,n,a,s){if(e!==null){var i=e.memoizedProps;if(Er(i,a)&&e.ref===t.ref)if(dt=!1,t.pendingProps=a=i,uh(e,s))e.flags&131072&&(dt=!0);else return t.lanes=e.lanes,ma(e,t,s)}return Yu(e,t,n,a,s)}function Jg(e,t,n,a){var s=a.children,i=e!==null?e.memoizedState:null;if(e===null&&t.stateNode===null&&(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.mode==="hidden"){if(t.flags&128){if(i=i!==null?i.baseLanes|n:n,e!==null){for(a=t.child=e.child,s=0;a!==null;)s=s|a.lanes|a.childLanes,a=a.sibling;a=s&~i}else a=0,t.child=null;return Ef(e,t,i,n,a)}if(n&536870912)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&Kl(t,i!==null?i.cachePool:null),i!==null?ff(t,i):Hu(),ug(t);else return a=t.lanes=536870912,Ef(e,t,i!==null?i.baseLanes|n:n,n,a)}else i!==null?(Kl(t,i.cachePool),ff(t,i),Ra(),t.memoizedState=null):(e!==null&&Kl(t,null),Hu(),Ra());return Ct(e,t,s,n),t.child}function er(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function Ef(e,t,n,a,s){var i=Vd();return i=i===null?null:{parent:ut._currentValue,pool:i},t.memoizedState={baseLanes:n,cachePool:i},e!==null&&Kl(t,null),Hu(),ug(t),e!==null&&Ci(e,t,a,!0),t.childLanes=s,null}function Fl(e,t){return t=bo({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function Af(e,t,n){return Ss(t,e.child,null,n),e=Fl(t,t.pendingProps),e.flags|=2,Wt(t),t.memoizedState=null,e}function E0(e,t,n){var a=t.pendingProps,s=(t.flags&128)!==0;if(t.flags&=-129,e===null){if(we){if(a.mode==="hidden")return e=Fl(t,a),t.lanes=536870912,er(null,e);if($u(t),(e=Ye)?(e=$y(e,bn),e=e!==null&&e.data==="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Fa!==null?{id:In,overflow:Hn}:null,retryLane:536870912,hydrationErrors:null},n=eg(e),n.return=t,t.child=n,Rt=t,Ye=null)):e=null,e===null)throw Ja(t);return t.lanes=536870912,null}return Fl(t,a)}var i=e.memoizedState;if(i!==null){var r=i.dehydrated;if($u(t),s)if(t.flags&256)t.flags&=-257,t=Af(e,t,n);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(N(558));else if(dt||Ci(e,t,n,!1),s=(n&e.childLanes)!==0,dt||s){if(a=He,a!==null&&(r=Am(a,n),r!==0&&r!==i.retryLane))throw i.retryLane=r,As(e,r),Ft(a,e,r),ch;xo(),t=Af(e,t,n)}else e=i.treeContext,Ye=_n(r.nextSibling),Rt=t,we=!0,Ha=null,bn=!1,e!==null&&ng(t,e),t=Fl(t,a),t.flags|=4096;return t}return e=ca(e.child,{mode:a.mode,children:a.children}),e.ref=t.ref,t.child=e,e.return=t,e}function Jl(e,t){var n=t.ref;if(n===null)e!==null&&e.ref!==null&&(t.flags|=4194816);else{if(typeof n!="function"&&typeof n!="object")throw Error(N(284));(e===null||e.ref!==n)&&(t.flags|=4194816)}}function Yu(e,t,n,a,s){return bs(t),n=Qd(e,t,n,a,void 0,s),a=Wd(),e!==null&&!dt?(Zd(e,t,s),ma(e,t,s)):(we&&a&&qd(t),t.flags|=1,Ct(e,t,n,s),t.child)}function Cf(e,t,n,a,s,i){return bs(t),t.updateQueue=null,n=hg(t,a,n,s),dg(e),a=Wd(),e!==null&&!dt?(Zd(e,t,i),ma(e,t,i)):(we&&a&&qd(t),t.flags|=1,Ct(e,t,n,i),t.child)}function Of(e,t,n,a,s){if(bs(t),t.stateNode===null){var i=ei,r=n.contextType;typeof r=="object"&&r!==null&&(i=Nt(r)),i=new n(a,i),t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,i.updater=Ku,t.stateNode=i,i._reactInternals=t,i=t.stateNode,i.props=a,i.state=t.memoizedState,i.refs={},Fd(t),r=n.contextType,i.context=typeof r=="object"&&r!==null?Nt(r):ei,i.state=t.memoizedState,r=n.getDerivedStateFromProps,typeof r=="function"&&(Dc(t,n,r,a),i.state=t.memoizedState),typeof n.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(r=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),r!==i.state&&Ku.enqueueReplaceState(i,i.state,null),hr(t,a,i,s),dr(),i.state=t.memoizedState),typeof i.componentDidMount=="function"&&(t.flags|=4194308),a=!0}else if(e===null){i=t.stateNode;var l=t.memoizedProps,o=ws(n,l);i.props=o;var u=i.context,h=n.contextType;r=ei,typeof h=="object"&&h!==null&&(r=Nt(h));var f=n.getDerivedStateFromProps;h=typeof f=="function"||typeof i.getSnapshotBeforeUpdate=="function",l=t.pendingProps!==l,h||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(l||u!==r)&&_f(t,i,a,r),Aa=!1;var d=t.memoizedState;i.state=d,hr(t,a,i,s),dr(),u=t.memoizedState,l||d!==u||Aa?(typeof f=="function"&&(Dc(t,n,f,a),u=t.memoizedState),(o=Aa||Sf(t,n,o,a,d,u,r))?(h||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(t.flags|=4194308)):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=a,t.memoizedState=u),i.props=a,i.state=u,i.context=r,a=o):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),a=!1)}else{i=t.stateNode,Bu(e,t),r=t.memoizedProps,h=ws(n,r),i.props=h,f=t.pendingProps,d=i.context,u=n.contextType,o=ei,typeof u=="object"&&u!==null&&(o=Nt(u)),l=n.getDerivedStateFromProps,(u=typeof l=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(r!==f||d!==o)&&_f(t,i,a,o),Aa=!1,d=t.memoizedState,i.state=d,hr(t,a,i,s),dr();var p=t.memoizedState;r!==f||d!==p||Aa||e!==null&&e.dependencies!==null&&ho(e.dependencies)?(typeof l=="function"&&(Dc(t,n,l,a),p=t.memoizedState),(h=Aa||Sf(t,n,h,a,d,p,o)||e!==null&&e.dependencies!==null&&ho(e.dependencies))?(u||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(a,p,o),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(a,p,o)),typeof i.componentDidUpdate=="function"&&(t.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof i.componentDidUpdate!="function"||r===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||r===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),t.memoizedProps=a,t.memoizedState=p),i.props=a,i.state=p,i.context=o,a=h):(typeof i.componentDidUpdate!="function"||r===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||r===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),a=!1)}return i=a,Jl(e,t),a=(t.flags&128)!==0,i||a?(i=t.stateNode,n=a&&typeof n.getDerivedStateFromError!="function"?null:i.render(),t.flags|=1,e!==null&&a?(t.child=Ss(t,e.child,null,s),t.child=Ss(t,null,n,s)):Ct(e,t,n,s),t.memoizedState=i.state,e=t.child):e=ma(e,t,s),e}function Rf(e,t,n,a){return vs(),t.flags|=256,Ct(e,t,n,a),t.child}var Mc={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Uc(e){return{baseLanes:e,cachePool:sg()}}function Lc(e,t,n){return e=e!==null?e.childLanes&~n:0,t&&(e|=nn),e}function Xg(e,t,n){var a=t.pendingProps,s=!1,i=(t.flags&128)!==0,r;if((r=i)||(r=e!==null&&e.memoizedState===null?!1:(at.current&2)!==0),r&&(s=!0,t.flags&=-129),r=(t.flags&32)!==0,t.flags&=-33,e===null){if(we){if(s?Oa(t):Ra(),(e=Ye)?(e=$y(e,bn),e=e!==null&&e.data!=="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Fa!==null?{id:In,overflow:Hn}:null,retryLane:536870912,hydrationErrors:null},n=eg(e),n.return=t,t.child=n,Rt=t,Ye=null)):e=null,e===null)throw Ja(t);return ld(e)?t.lanes=32:t.lanes=536870912,null}var l=a.children;return a=a.fallback,s?(Ra(),s=t.mode,l=bo({mode:"hidden",children:l},s),a=ps(a,s,n,null),l.return=t,a.return=t,l.sibling=a,t.child=l,a=t.child,a.memoizedState=Uc(n),a.childLanes=Lc(e,r,n),t.memoizedState=Mc,er(null,a)):(Oa(t),Fu(t,l))}var o=e.memoizedState;if(o!==null&&(l=o.dehydrated,l!==null)){if(i)t.flags&256?(Oa(t),t.flags&=-257,t=zc(e,t,n)):t.memoizedState!==null?(Ra(),t.child=e.child,t.flags|=128,t=null):(Ra(),l=a.fallback,s=t.mode,a=bo({mode:"visible",children:a.children},s),l=ps(l,s,n,null),l.flags|=2,a.return=t,l.return=t,a.sibling=l,t.child=a,Ss(t,e.child,null,n),a=t.child,a.memoizedState=Uc(n),a.childLanes=Lc(e,r,n),t.memoizedState=Mc,t=er(null,a));else if(Oa(t),ld(l)){if(r=l.nextSibling&&l.nextSibling.dataset,r)var u=r.dgst;r=u,a=Error(N(419)),a.stack="",a.digest=r,Cr({value:a,source:null,stack:null}),t=zc(e,t,n)}else if(dt||Ci(e,t,n,!1),r=(n&e.childLanes)!==0,dt||r){if(r=He,r!==null&&(a=Am(r,n),a!==0&&a!==o.retryLane))throw o.retryLane=a,As(e,a),Ft(r,e,a),ch;rd(l)||xo(),t=zc(e,t,n)}else rd(l)?(t.flags|=192,t.child=e.child,t=null):(e=o.treeContext,Ye=_n(l.nextSibling),Rt=t,we=!0,Ha=null,bn=!1,e!==null&&ng(t,e),t=Fu(t,a.children),t.flags|=4096);return t}return s?(Ra(),l=a.fallback,s=t.mode,o=e.child,u=o.sibling,a=ca(o,{mode:"hidden",children:a.children}),a.subtreeFlags=o.subtreeFlags&65011712,u!==null?l=ca(u,l):(l=ps(l,s,n,null),l.flags|=2),l.return=t,a.return=t,a.sibling=l,t.child=a,er(null,a),a=t.child,l=e.child.memoizedState,l===null?l=Uc(n):(s=l.cachePool,s!==null?(o=ut._currentValue,s=s.parent!==o?{parent:o,pool:o}:s):s=sg(),l={baseLanes:l.baseLanes|n,cachePool:s}),a.memoizedState=l,a.childLanes=Lc(e,r,n),t.memoizedState=Mc,er(e.child,a)):(Oa(t),n=e.child,e=n.sibling,n=ca(n,{mode:"visible",children:a.children}),n.return=t,n.sibling=null,e!==null&&(r=t.deletions,r===null?(t.deletions=[e],t.flags|=16):r.push(e)),t.child=n,t.memoizedState=null,n)}function Fu(e,t){return t=bo({mode:"visible",children:t},e.mode),t.return=e,e.child=t}function bo(e,t){return e=Zt(22,e,null,t),e.lanes=0,e}function zc(e,t,n){return Ss(t,e.child,null,n),e=Fu(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Nf(e,t,n){e.lanes|=t;var a=e.alternate;a!==null&&(a.lanes|=t),Uu(e.return,t,n)}function Bc(e,t,n,a,s,i){var r=e.memoizedState;r===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:a,tail:n,tailMode:s,treeForkCount:i}:(r.isBackwards=t,r.rendering=null,r.renderingStartTime=0,r.last=a,r.tail=n,r.tailMode=s,r.treeForkCount=i)}function Qg(e,t,n){var a=t.pendingProps,s=a.revealOrder,i=a.tail;a=a.children;var r=at.current,l=(r&2)!==0;if(l?(r=r&1|2,t.flags|=128):r&=1,Ge(at,r),Ct(e,t,a,n),a=we?Ar:0,!l&&e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Nf(e,n,t);else if(e.tag===19)Nf(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(s){case"forwards":for(n=t.child,s=null;n!==null;)e=n.alternate,e!==null&&mo(e)===null&&(s=n),n=n.sibling;n=s,n===null?(s=t.child,t.child=null):(s=n.sibling,n.sibling=null),Bc(t,!1,s,n,i,a);break;case"backwards":case"unstable_legacy-backwards":for(n=null,s=t.child,t.child=null;s!==null;){if(e=s.alternate,e!==null&&mo(e)===null){t.child=s;break}e=s.sibling,s.sibling=n,n=s,s=e}Bc(t,!0,n,null,i,a);break;case"together":Bc(t,!1,null,null,void 0,a);break;default:t.memoizedState=null}return t.child}function ma(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Qa|=t.lanes,!(n&t.childLanes))if(e!==null){if(Ci(e,t,n,!1),(n&t.childLanes)===0)return null}else return null;if(e!==null&&t.child!==e.child)throw Error(N(153));if(t.child!==null){for(e=t.child,n=ca(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=ca(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function uh(e,t){return e.lanes&t?!0:(e=e.dependencies,!!(e!==null&&ho(e)))}function A0(e,t,n){switch(t.tag){case 3:so(t,t.stateNode.containerInfo),Ca(t,ut,e.memoizedState.cache),vs();break;case 27:case 5:wu(t);break;case 4:so(t,t.stateNode.containerInfo);break;case 10:Ca(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,$u(t),null;break;case 13:var a=t.memoizedState;if(a!==null)return a.dehydrated!==null?(Oa(t),t.flags|=128,null):n&t.child.childLanes?Xg(e,t,n):(Oa(t),e=ma(e,t,n),e!==null?e.sibling:null);Oa(t);break;case 19:var s=(e.flags&128)!==0;if(a=(n&t.childLanes)!==0,a||(Ci(e,t,n,!1),a=(n&t.childLanes)!==0),s){if(a)return Qg(e,t,n);t.flags|=128}if(s=t.memoizedState,s!==null&&(s.rendering=null,s.tail=null,s.lastEffect=null),Ge(at,at.current),a)break;return null;case 22:return t.lanes=0,Jg(e,t,n,t.pendingProps);case 24:Ca(t,ut,e.memoizedState.cache)}return ma(e,t,n)}function Wg(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps)dt=!0;else{if(!uh(e,n)&&!(t.flags&128))return dt=!1,A0(e,t,n);dt=!!(e.flags&131072)}else dt=!1,we&&t.flags&1048576&&tg(t,Ar,t.index);switch(t.lanes=0,t.tag){case 16:e:{var a=t.pendingProps;if(e=cs(t.elementType),t.type=e,typeof e=="function")Pd(e)?(a=ws(e,a),t.tag=1,t=Of(null,t,e,a,n)):(t.tag=0,t=Yu(null,t,e,a,n));else{if(e!=null){var s=e.$$typeof;if(s===Od){t.tag=11,t=xf(null,t,e,a,n);break e}else if(s===Rd){t.tag=14,t=Tf(null,t,e,a,n);break e}}throw t=Su(e)||e,Error(N(306,t,""))}}return t;case 0:return Yu(e,t,t.type,t.pendingProps,n);case 1:return a=t.type,s=ws(a,t.pendingProps),Of(e,t,a,s,n);case 3:e:{if(so(t,t.stateNode.containerInfo),e===null)throw Error(N(387));a=t.pendingProps;var i=t.memoizedState;s=i.element,Bu(e,t),hr(t,a,null,n);var r=t.memoizedState;if(a=r.cache,Ca(t,ut,a),a!==i.cache&&Lu(t,[ut],n,!0),dr(),a=r.element,i.isDehydrated)if(i={element:a,isDehydrated:!1,cache:r.cache},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){t=Rf(e,t,a,n);break e}else if(a!==s){s=vn(Error(N(424)),t),Cr(s),t=Rf(e,t,a,n);break e}else{switch(e=t.stateNode.containerInfo,e.nodeType){case 9:e=e.body;break;default:e=e.nodeName==="HTML"?e.ownerDocument.body:e}for(Ye=_n(e.firstChild),Rt=t,we=!0,Ha=null,bn=!0,n=lg(t,null,a,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(vs(),a===s){t=ma(e,t,n);break e}Ct(e,t,a,n)}t=t.child}return t;case 26:return Jl(e,t),e===null?(n=Xf(t.type,null,t.pendingProps,null))?t.memoizedState=n:we||(n=t.type,e=t.pendingProps,a=Co(Ia.current).createElement(n),a[Ot]=t,a[Jt]=e,jt(a,n,e),xt(a),t.stateNode=a):t.memoizedState=Xf(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return wu(t),e===null&&we&&(a=t.stateNode=Py(t.type,t.pendingProps,Ia.current),Rt=t,bn=!0,s=Ye,Za(t.type)?(od=s,Ye=_n(a.firstChild)):Ye=s),Ct(e,t,t.pendingProps.children,n),Jl(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&we&&((s=a=Ye)&&(a=nS(a,t.type,t.pendingProps,bn),a!==null?(t.stateNode=a,Rt=t,Ye=_n(a.firstChild),bn=!1,s=!0):s=!1),s||Ja(t)),wu(t),s=t.type,i=t.pendingProps,r=e!==null?e.memoizedProps:null,a=i.children,sd(s,i)?a=null:r!==null&&sd(s,r)&&(t.flags|=32),t.memoizedState!==null&&(s=Qd(e,t,y0,null,null,n),Dr._currentValue=s),Jl(e,t),Ct(e,t,a,n),t.child;case 6:return e===null&&we&&((e=n=Ye)&&(n=aS(n,t.pendingProps,bn),n!==null?(t.stateNode=n,Rt=t,Ye=null,e=!0):e=!1),e||Ja(t)),null;case 13:return Xg(e,t,n);case 4:return so(t,t.stateNode.containerInfo),a=t.pendingProps,e===null?t.child=Ss(t,null,a,n):Ct(e,t,a,n),t.child;case 11:return xf(e,t,t.type,t.pendingProps,n);case 7:return Ct(e,t,t.pendingProps,n),t.child;case 8:return Ct(e,t,t.pendingProps.children,n),t.child;case 12:return Ct(e,t,t.pendingProps.children,n),t.child;case 10:return a=t.pendingProps,Ca(t,t.type,a.value),Ct(e,t,a.children,n),t.child;case 9:return s=t.type._context,a=t.pendingProps.children,bs(t),s=Nt(s),a=a(s),t.flags|=1,Ct(e,t,a,n),t.child;case 14:return Tf(e,t,t.type,t.pendingProps,n);case 15:return Fg(e,t,t.type,t.pendingProps,n);case 19:return Qg(e,t,n);case 31:return E0(e,t,n);case 22:return Jg(e,t,n,t.pendingProps);case 24:return bs(t),a=Nt(ut),e===null?(s=Vd(),s===null&&(s=He,i=Kd(),s.pooledCache=i,i.refCount++,i!==null&&(s.pooledCacheLanes|=n),s=i),t.memoizedState={parent:a,cache:s},Fd(t),Ca(t,ut,s)):(e.lanes&n&&(Bu(e,t),hr(t,null,null,n),dr()),s=e.memoizedState,i=t.memoizedState,s.parent!==a?(s={parent:a,cache:a},t.memoizedState=s,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=s),Ca(t,ut,a)):(a=i.cache,Ca(t,ut,a),a!==s.cache&&Lu(t,[ut],n,!0))),Ct(e,t,t.pendingProps.children,n),t.child;case 29:throw t.pendingProps}throw Error(N(156,t.tag))}function Jn(e){e.flags|=4}function Ic(e,t,n,a,s){if((t=(e.mode&32)!==0)&&(t=!1),t){if(e.flags|=16777216,(s&335544128)===s)if(e.stateNode.complete)e.flags|=8192;else if(wy())e.flags|=8192;else throw gs=fo,Yd}else e.flags&=-16777217}function kf(e,t){if(t.type!=="stylesheet"||t.state.loading&4)e.flags&=-16777217;else if(e.flags|=16777216,!Ky(t))if(wy())e.flags|=8192;else throw gs=fo,Yd}function Sl(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag!==22?xm():536870912,e.lanes|=t,Si|=t)}function Gi(e,t){if(!we)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var a=null;n!==null;)n.alternate!==null&&(a=n),n=n.sibling;a===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:a.sibling=null}}function Ve(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,a=0;if(t)for(var s=e.child;s!==null;)n|=s.lanes|s.childLanes,a|=s.subtreeFlags&65011712,a|=s.flags&65011712,s.return=e,s=s.sibling;else for(s=e.child;s!==null;)n|=s.lanes|s.childLanes,a|=s.subtreeFlags,a|=s.flags,s.return=e,s=s.sibling;return e.subtreeFlags|=a,e.childLanes=n,t}function C0(e,t,n){var a=t.pendingProps;switch(Gd(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ve(t),null;case 1:return Ve(t),null;case 3:return n=t.stateNode,a=null,e!==null&&(a=e.memoizedState.cache),t.memoizedState.cache!==a&&(t.flags|=2048),ua(ut),pi(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(e===null||e.child===null)&&(ks(t)?Jn(t):e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,Nc())),Ve(t),null;case 26:var s=t.type,i=t.memoizedState;return e===null?(Jn(t),i!==null?(Ve(t),kf(t,i)):(Ve(t),Ic(t,s,null,a,n))):i?i!==e.memoizedState?(Jn(t),Ve(t),kf(t,i)):(Ve(t),t.flags&=-16777217):(e=e.memoizedProps,e!==a&&Jn(t),Ve(t),Ic(t,s,e,a,n)),null;case 27:if(io(t),n=Ia.current,s=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==a&&Jn(t);else{if(!a){if(t.stateNode===null)throw Error(N(166));return Ve(t),null}e=Pn.current,ks(t)?rf(t):(e=Py(s,a,n),t.stateNode=e,Jn(t))}return Ve(t),null;case 5:if(io(t),s=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==a&&Jn(t);else{if(!a){if(t.stateNode===null)throw Error(N(166));return Ve(t),null}if(i=Pn.current,ks(t))rf(t);else{var r=Co(Ia.current);switch(i){case 1:i=r.createElementNS("http://www.w3.org/2000/svg",s);break;case 2:i=r.createElementNS("http://www.w3.org/1998/Math/MathML",s);break;default:switch(s){case"svg":i=r.createElementNS("http://www.w3.org/2000/svg",s);break;case"math":i=r.createElementNS("http://www.w3.org/1998/Math/MathML",s);break;case"script":i=r.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof a.is=="string"?r.createElement("select",{is:a.is}):r.createElement("select"),a.multiple?i.multiple=!0:a.size&&(i.size=a.size);break;default:i=typeof a.is=="string"?r.createElement(s,{is:a.is}):r.createElement(s)}}i[Ot]=t,i[Jt]=a;e:for(r=t.child;r!==null;){if(r.tag===5||r.tag===6)i.appendChild(r.stateNode);else if(r.tag!==4&&r.tag!==27&&r.child!==null){r.child.return=r,r=r.child;continue}if(r===t)break e;for(;r.sibling===null;){if(r.return===null||r.return===t)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}t.stateNode=i;e:switch(jt(i,s,a),s){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break e;case"img":a=!0;break e;default:a=!1}a&&Jn(t)}}return Ve(t),Ic(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==a&&Jn(t);else{if(typeof a!="string"&&t.stateNode===null)throw Error(N(166));if(e=Ia.current,ks(t)){if(e=t.stateNode,n=t.memoizedProps,a=null,s=Rt,s!==null)switch(s.tag){case 27:case 5:a=s.memoizedProps}e[Ot]=t,e=!!(e.nodeValue===n||a!==null&&a.suppressHydrationWarning===!0||By(e.nodeValue,n)),e||Ja(t,!0)}else e=Co(e).createTextNode(a),e[Ot]=t,t.stateNode=e}return Ve(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(a=ks(t),n!==null){if(e===null){if(!a)throw Error(N(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(N(557));e[Ot]=t}else vs(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ve(t),e=!1}else n=Nc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Wt(t),t):(Wt(t),null);if(t.flags&128)throw Error(N(558))}return Ve(t),null;case 13:if(a=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(s=ks(t),a!==null&&a.dehydrated!==null){if(e===null){if(!s)throw Error(N(318));if(s=t.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(N(317));s[Ot]=t}else vs(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ve(t),s=!1}else s=Nc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),s=!0;if(!s)return t.flags&256?(Wt(t),t):(Wt(t),null)}return Wt(t),t.flags&128?(t.lanes=n,t):(n=a!==null,e=e!==null&&e.memoizedState!==null,n&&(a=t.child,s=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(s=a.alternate.memoizedState.cachePool.pool),i=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(i=a.memoizedState.cachePool.pool),i!==s&&(a.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Sl(t,t.updateQueue),Ve(t),null);case 4:return pi(),e===null&&yh(t.stateNode.containerInfo),Ve(t),null;case 10:return ua(t.type),Ve(t),null;case 19:if(Tt(at),a=t.memoizedState,a===null)return Ve(t),null;if(s=(t.flags&128)!==0,i=a.rendering,i===null)if(s)Gi(a,!1);else{if(et!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(i=mo(e),i!==null){for(t.flags|=128,Gi(a,!1),e=i.updateQueue,t.updateQueue=e,Sl(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Zm(n,e),n=n.sibling;return Ge(at,at.current&1|2),we&&sa(t,a.treeForkCount),t.child}e=e.sibling}a.tail!==null&&an()>_o&&(t.flags|=128,s=!0,Gi(a,!1),t.lanes=4194304)}else{if(!s)if(e=mo(i),e!==null){if(t.flags|=128,s=!0,e=e.updateQueue,t.updateQueue=e,Sl(t,e),Gi(a,!0),a.tail===null&&a.tailMode==="hidden"&&!i.alternate&&!we)return Ve(t),null}else 2*an()-a.renderingStartTime>_o&&n!==536870912&&(t.flags|=128,s=!0,Gi(a,!1),t.lanes=4194304);a.isBackwards?(i.sibling=t.child,t.child=i):(e=a.last,e!==null?e.sibling=i:t.child=i,a.last=i)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=an(),e.sibling=null,n=at.current,Ge(at,s?n&1|2:n&1),we&&sa(t,a.treeForkCount),e):(Ve(t),null);case 22:case 23:return Wt(t),Jd(),a=t.memoizedState!==null,e!==null?e.memoizedState!==null!==a&&(t.flags|=8192):a&&(t.flags|=8192),a?n&536870912&&!(t.flags&128)&&(Ve(t),t.subtreeFlags&6&&(t.flags|=8192)):Ve(t),n=t.updateQueue,n!==null&&Sl(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),a=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(a=t.memoizedState.cachePool.pool),a!==n&&(t.flags|=2048),e!==null&&Tt(ms),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),ua(ut),Ve(t),null;case 25:return null;case 30:return null}throw Error(N(156,t.tag))}function O0(e,t){switch(Gd(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ua(ut),pi(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return io(t),null;case 31:if(t.memoizedState!==null){if(Wt(t),t.alternate===null)throw Error(N(340));vs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Wt(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(N(340));vs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Tt(at),null;case 4:return pi(),null;case 10:return ua(t.type),null;case 22:case 23:return Wt(t),Jd(),e!==null&&Tt(ms),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return ua(ut),null;case 25:return null;default:return null}}function Zg(e,t){switch(Gd(t),t.tag){case 3:ua(ut),pi();break;case 26:case 27:case 5:io(t);break;case 4:pi();break;case 31:t.memoizedState!==null&&Wt(t);break;case 13:Wt(t);break;case 19:Tt(at);break;case 10:ua(t.type);break;case 22:case 23:Wt(t),Jd(),e!==null&&Tt(ms);break;case 24:ua(ut)}}function Qr(e,t){try{var n=t.updateQueue,a=n!==null?n.lastEffect:null;if(a!==null){var s=a.next;n=s;do{if((n.tag&e)===e){a=void 0;var i=n.create,r=n.inst;a=i(),r.destroy=a}n=n.next}while(n!==s)}}catch(l){Le(t,t.return,l)}}function Xa(e,t,n){try{var a=t.updateQueue,s=a!==null?a.lastEffect:null;if(s!==null){var i=s.next;a=i;do{if((a.tag&e)===e){var r=a.inst,l=r.destroy;if(l!==void 0){r.destroy=void 0,s=t;var o=n,u=l;try{u()}catch(h){Le(s,o,h)}}}a=a.next}while(a!==i)}}catch(h){Le(t,t.return,h)}}function ey(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{cg(t,n)}catch(a){Le(e,e.return,a)}}}function ty(e,t,n){n.props=ws(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(a){Le(e,t,a)}}function pr(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var a=e.stateNode;break;case 30:a=e.stateNode;break;default:a=e.stateNode}typeof n=="function"?e.refCleanup=n(a):n.current=a}}catch(s){Le(e,t,s)}}function $n(e,t){var n=e.ref,a=e.refCleanup;if(n!==null)if(typeof a=="function")try{a()}catch(s){Le(e,t,s)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n=="function")try{n(null)}catch(s){Le(e,t,s)}else n.current=null}function ny(e){var t=e.type,n=e.memoizedProps,a=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":n.autoFocus&&a.focus();break e;case"img":n.src?a.src=n.src:n.srcSet&&(a.srcset=n.srcSet)}}catch(s){Le(e,e.return,s)}}function Hc(e,t,n){try{var a=e.stateNode;X0(a,e.type,n,t),a[Jt]=t}catch(s){Le(e,e.return,s)}}function ay(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Za(e.type)||e.tag===4}function $c(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ay(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Za(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ju(e,t,n){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=la));else if(a!==4&&(a===27&&Za(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Ju(e,t,n),e=e.sibling;e!==null;)Ju(e,t,n),e=e.sibling}function So(e,t,n){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(a!==4&&(a===27&&Za(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(So(e,t,n),e=e.sibling;e!==null;)So(e,t,n),e=e.sibling}function sy(e){var t=e.stateNode,n=e.memoizedProps;try{for(var a=e.type,s=t.attributes;s.length;)t.removeAttributeNode(s[0]);jt(t,a,n),t[Ot]=e,t[Jt]=n}catch(i){Le(e,e.return,i)}}var ia=!1,ct=!1,Pc=!1,jf=typeof WeakSet=="function"?WeakSet:Set,wt=null;function R0(e,t){if(e=e.containerInfo,nd=ko,e=Km(e),Id(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var a=n.getSelection&&n.getSelection();if(a&&a.rangeCount!==0){n=a.anchorNode;var s=a.anchorOffset,i=a.focusNode;a=a.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var r=0,l=-1,o=-1,u=0,h=0,f=e,d=null;t:for(;;){for(var p;f!==n||s!==0&&f.nodeType!==3||(l=r+s),f!==i||a!==0&&f.nodeType!==3||(o=r+a),f.nodeType===3&&(r+=f.nodeValue.length),(p=f.firstChild)!==null;)d=f,f=p;for(;;){if(f===e)break t;if(d===n&&++u===s&&(l=r),d===i&&++h===a&&(o=r),(p=f.nextSibling)!==null)break;f=d,d=f.parentNode}f=p}n=l===-1||o===-1?null:{start:l,end:o}}else n=null}n=n||{start:0,end:0}}else n=null;for(ad={focusedElem:e,selectionRange:n},ko=!1,wt=t;wt!==null;)if(t=wt,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,wt=e;else for(;wt!==null;){switch(t=wt,i=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(n=0;n<e.length;n++)s=e[n],s.ref.impl=s.nextImpl;break;case 11:case 15:break;case 1:if(e&1024&&i!==null){e=void 0,n=t,s=i.memoizedProps,i=i.memoizedState,a=n.stateNode;try{var v=ws(n.type,s);e=a.getSnapshotBeforeUpdate(v,i),a.__reactInternalSnapshotBeforeUpdate=e}catch(_){Le(n,n.return,_)}}break;case 3:if(e&1024){if(e=t.stateNode.containerInfo,n=e.nodeType,n===9)id(e);else if(n===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":id(e);break;default:e.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if(e&1024)throw Error(N(163))}if(e=t.sibling,e!==null){e.return=t.return,wt=e;break}wt=t.return}}function iy(e,t,n){var a=n.flags;switch(n.tag){case 0:case 11:case 15:Qn(e,n),a&4&&Qr(5,n);break;case 1:if(Qn(e,n),a&4)if(e=n.stateNode,t===null)try{e.componentDidMount()}catch(r){Le(n,n.return,r)}else{var s=ws(n.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(s,t,e.__reactInternalSnapshotBeforeUpdate)}catch(r){Le(n,n.return,r)}}a&64&&ey(n),a&512&&pr(n,n.return);break;case 3:if(Qn(e,n),a&64&&(e=n.updateQueue,e!==null)){if(t=null,n.child!==null)switch(n.child.tag){case 27:case 5:t=n.child.stateNode;break;case 1:t=n.child.stateNode}try{cg(e,t)}catch(r){Le(n,n.return,r)}}break;case 27:t===null&&a&4&&sy(n);case 26:case 5:Qn(e,n),t===null&&a&4&&ny(n),a&512&&pr(n,n.return);break;case 12:Qn(e,n);break;case 31:Qn(e,n),a&4&&oy(e,n);break;case 13:Qn(e,n),a&4&&cy(e,n),a&64&&(e=n.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(n=B0.bind(null,n),sS(e,n))));break;case 22:if(a=n.memoizedState!==null||ia,!a){t=t!==null&&t.memoizedState!==null||ct,s=ia;var i=ct;ia=a,(ct=t)&&!i?ta(e,n,(n.subtreeFlags&8772)!==0):Qn(e,n),ia=s,ct=i}break;case 30:break;default:Qn(e,n)}}function ry(e){var t=e.alternate;t!==null&&(e.alternate=null,ry(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&Dd(t)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var Je=null,Vt=!1;function Xn(e,t,n){for(n=n.child;n!==null;)ly(e,t,n),n=n.sibling}function ly(e,t,n){if(sn&&typeof sn.onCommitFiberUnmount=="function")try{sn.onCommitFiberUnmount(Gr,n)}catch{}switch(n.tag){case 26:ct||$n(n,t),Xn(e,t,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode,n.parentNode.removeChild(n));break;case 27:ct||$n(n,t);var a=Je,s=Vt;Za(n.type)&&(Je=n.stateNode,Vt=!1),Xn(e,t,n),vr(n.stateNode),Je=a,Vt=s;break;case 5:ct||$n(n,t);case 6:if(a=Je,s=Vt,Je=null,Xn(e,t,n),Je=a,Vt=s,Je!==null)if(Vt)try{(Je.nodeType===9?Je.body:Je.nodeName==="HTML"?Je.ownerDocument.body:Je).removeChild(n.stateNode)}catch(i){Le(n,t,i)}else try{Je.removeChild(n.stateNode)}catch(i){Le(n,t,i)}break;case 18:Je!==null&&(Vt?(e=Je,Kf(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,n.stateNode),Ti(e)):Kf(Je,n.stateNode));break;case 4:a=Je,s=Vt,Je=n.stateNode.containerInfo,Vt=!0,Xn(e,t,n),Je=a,Vt=s;break;case 0:case 11:case 14:case 15:Xa(2,n,t),ct||Xa(4,n,t),Xn(e,t,n);break;case 1:ct||($n(n,t),a=n.stateNode,typeof a.componentWillUnmount=="function"&&ty(n,t,a)),Xn(e,t,n);break;case 21:Xn(e,t,n);break;case 22:ct=(a=ct)||n.memoizedState!==null,Xn(e,t,n),ct=a;break;default:Xn(e,t,n)}}function oy(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{Ti(e)}catch(n){Le(t,t.return,n)}}}function cy(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{Ti(e)}catch(n){Le(t,t.return,n)}}function N0(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new jf),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new jf),t;default:throw Error(N(435,e.tag))}}function _l(e,t){var n=N0(e);t.forEach(function(a){if(!n.has(a)){n.add(a);var s=I0.bind(null,e,a);a.then(s,s)}})}function qt(e,t){var n=t.deletions;if(n!==null)for(var a=0;a<n.length;a++){var s=n[a],i=e,r=t,l=r;e:for(;l!==null;){switch(l.tag){case 27:if(Za(l.type)){Je=l.stateNode,Vt=!1;break e}break;case 5:Je=l.stateNode,Vt=!1;break e;case 3:case 4:Je=l.stateNode.containerInfo,Vt=!0;break e}l=l.return}if(Je===null)throw Error(N(160));ly(i,r,s),Je=null,Vt=!1,i=s.alternate,i!==null&&(i.return=null),s.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)uy(t,e),t=t.sibling}var Nn=null;function uy(e,t){var n=e.alternate,a=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:qt(t,e),Gt(e),a&4&&(Xa(3,e,e.return),Qr(3,e),Xa(5,e,e.return));break;case 1:qt(t,e),Gt(e),a&512&&(ct||n===null||$n(n,n.return)),a&64&&ia&&(e=e.updateQueue,e!==null&&(a=e.callbacks,a!==null&&(n=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=n===null?a:n.concat(a))));break;case 26:var s=Nn;if(qt(t,e),Gt(e),a&512&&(ct||n===null||$n(n,n.return)),a&4){var i=n!==null?n.memoizedState:null;if(a=e.memoizedState,n===null)if(a===null)if(e.stateNode===null){e:{a=e.type,n=e.memoizedProps,s=s.ownerDocument||s;t:switch(a){case"title":i=s.getElementsByTagName("title")[0],(!i||i[Yr]||i[Ot]||i.namespaceURI==="http://www.w3.org/2000/svg"||i.hasAttribute("itemprop"))&&(i=s.createElement(a),s.head.insertBefore(i,s.querySelector("head > title"))),jt(i,a,n),i[Ot]=e,xt(i),a=i;break e;case"link":var r=Wf("link","href",s).get(a+(n.href||""));if(r){for(var l=0;l<r.length;l++)if(i=r[l],i.getAttribute("href")===(n.href==null||n.href===""?null:n.href)&&i.getAttribute("rel")===(n.rel==null?null:n.rel)&&i.getAttribute("title")===(n.title==null?null:n.title)&&i.getAttribute("crossorigin")===(n.crossOrigin==null?null:n.crossOrigin)){r.splice(l,1);break t}}i=s.createElement(a),jt(i,a,n),s.head.appendChild(i);break;case"meta":if(r=Wf("meta","content",s).get(a+(n.content||""))){for(l=0;l<r.length;l++)if(i=r[l],i.getAttribute("content")===(n.content==null?null:""+n.content)&&i.getAttribute("name")===(n.name==null?null:n.name)&&i.getAttribute("property")===(n.property==null?null:n.property)&&i.getAttribute("http-equiv")===(n.httpEquiv==null?null:n.httpEquiv)&&i.getAttribute("charset")===(n.charSet==null?null:n.charSet)){r.splice(l,1);break t}}i=s.createElement(a),jt(i,a,n),s.head.appendChild(i);break;default:throw Error(N(468,a))}i[Ot]=e,xt(i),a=i}e.stateNode=a}else Zf(s,e.type,e.stateNode);else e.stateNode=Qf(s,a,e.memoizedProps);else i!==a?(i===null?n.stateNode!==null&&(n=n.stateNode,n.parentNode.removeChild(n)):i.count--,a===null?Zf(s,e.type,e.stateNode):Qf(s,a,e.memoizedProps)):a===null&&e.stateNode!==null&&Hc(e,e.memoizedProps,n.memoizedProps)}break;case 27:qt(t,e),Gt(e),a&512&&(ct||n===null||$n(n,n.return)),n!==null&&a&4&&Hc(e,e.memoizedProps,n.memoizedProps);break;case 5:if(qt(t,e),Gt(e),a&512&&(ct||n===null||$n(n,n.return)),e.flags&32){s=e.stateNode;try{gi(s,"")}catch(v){Le(e,e.return,v)}}a&4&&e.stateNode!=null&&(s=e.memoizedProps,Hc(e,s,n!==null?n.memoizedProps:s)),a&1024&&(Pc=!0);break;case 6:if(qt(t,e),Gt(e),a&4){if(e.stateNode===null)throw Error(N(162));a=e.memoizedProps,n=e.stateNode;try{n.nodeValue=a}catch(v){Le(e,e.return,v)}}break;case 3:if(Wl=null,s=Nn,Nn=Oo(t.containerInfo),qt(t,e),Nn=s,Gt(e),a&4&&n!==null&&n.memoizedState.isDehydrated)try{Ti(t.containerInfo)}catch(v){Le(e,e.return,v)}Pc&&(Pc=!1,dy(e));break;case 4:a=Nn,Nn=Oo(e.stateNode.containerInfo),qt(t,e),Gt(e),Nn=a;break;case 12:qt(t,e),Gt(e);break;case 31:qt(t,e),Gt(e),a&4&&(a=e.updateQueue,a!==null&&(e.updateQueue=null,_l(e,a)));break;case 13:qt(t,e),Gt(e),e.child.flags&8192&&e.memoizedState!==null!=(n!==null&&n.memoizedState!==null)&&(tc=an()),a&4&&(a=e.updateQueue,a!==null&&(e.updateQueue=null,_l(e,a)));break;case 22:s=e.memoizedState!==null;var o=n!==null&&n.memoizedState!==null,u=ia,h=ct;if(ia=u||s,ct=h||o,qt(t,e),ct=h,ia=u,Gt(e),a&8192)e:for(t=e.stateNode,t._visibility=s?t._visibility&-2:t._visibility|1,s&&(n===null||o||ia||ct||us(e)),n=null,t=e;;){if(t.tag===5||t.tag===26){if(n===null){o=n=t;try{if(i=o.stateNode,s)r=i.style,typeof r.setProperty=="function"?r.setProperty("display","none","important"):r.display="none";else{l=o.stateNode;var f=o.memoizedProps.style,d=f!=null&&f.hasOwnProperty("display")?f.display:null;l.style.display=d==null||typeof d=="boolean"?"":(""+d).trim()}}catch(v){Le(o,o.return,v)}}}else if(t.tag===6){if(n===null){o=t;try{o.stateNode.nodeValue=s?"":o.memoizedProps}catch(v){Le(o,o.return,v)}}}else if(t.tag===18){if(n===null){o=t;try{var p=o.stateNode;s?Vf(p,!0):Vf(o.stateNode,!1)}catch(v){Le(o,o.return,v)}}}else if((t.tag!==22&&t.tag!==23||t.memoizedState===null||t===e)&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;n===t&&(n=null),t=t.return}n===t&&(n=null),t.sibling.return=t.return,t=t.sibling}a&4&&(a=e.updateQueue,a!==null&&(n=a.retryQueue,n!==null&&(a.retryQueue=null,_l(e,n))));break;case 19:qt(t,e),Gt(e),a&4&&(a=e.updateQueue,a!==null&&(e.updateQueue=null,_l(e,a)));break;case 30:break;case 21:break;default:qt(t,e),Gt(e)}}function Gt(e){var t=e.flags;if(t&2){try{for(var n,a=e.return;a!==null;){if(ay(a)){n=a;break}a=a.return}if(n==null)throw Error(N(160));switch(n.tag){case 27:var s=n.stateNode,i=$c(e);So(e,i,s);break;case 5:var r=n.stateNode;n.flags&32&&(gi(r,""),n.flags&=-33);var l=$c(e);So(e,l,r);break;case 3:case 4:var o=n.stateNode.containerInfo,u=$c(e);Ju(e,u,o);break;default:throw Error(N(161))}}catch(h){Le(e,e.return,h)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function dy(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;dy(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Qn(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)iy(e,t.alternate,t),t=t.sibling}function us(e){for(e=e.child;e!==null;){var t=e;switch(t.tag){case 0:case 11:case 14:case 15:Xa(4,t,t.return),us(t);break;case 1:$n(t,t.return);var n=t.stateNode;typeof n.componentWillUnmount=="function"&&ty(t,t.return,n),us(t);break;case 27:vr(t.stateNode);case 26:case 5:$n(t,t.return),us(t);break;case 22:t.memoizedState===null&&us(t);break;case 30:us(t);break;default:us(t)}e=e.sibling}}function ta(e,t,n){for(n=n&&(t.subtreeFlags&8772)!==0,t=t.child;t!==null;){var a=t.alternate,s=e,i=t,r=i.flags;switch(i.tag){case 0:case 11:case 15:ta(s,i,n),Qr(4,i);break;case 1:if(ta(s,i,n),a=i,s=a.stateNode,typeof s.componentDidMount=="function")try{s.componentDidMount()}catch(u){Le(a,a.return,u)}if(a=i,s=a.updateQueue,s!==null){var l=a.stateNode;try{var o=s.shared.hiddenCallbacks;if(o!==null)for(s.shared.hiddenCallbacks=null,s=0;s<o.length;s++)og(o[s],l)}catch(u){Le(a,a.return,u)}}n&&r&64&&ey(i),pr(i,i.return);break;case 27:sy(i);case 26:case 5:ta(s,i,n),n&&a===null&&r&4&&ny(i),pr(i,i.return);break;case 12:ta(s,i,n);break;case 31:ta(s,i,n),n&&r&4&&oy(s,i);break;case 13:ta(s,i,n),n&&r&4&&cy(s,i);break;case 22:i.memoizedState===null&&ta(s,i,n),pr(i,i.return);break;case 30:break;default:ta(s,i,n)}t=t.sibling}}function dh(e,t){var n=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),e=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),e!==n&&(e!=null&&e.refCount++,n!=null&&Jr(n))}function hh(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&Jr(e))}function Cn(e,t,n,a){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)hy(e,t,n,a),t=t.sibling}function hy(e,t,n,a){var s=t.flags;switch(t.tag){case 0:case 11:case 15:Cn(e,t,n,a),s&2048&&Qr(9,t);break;case 1:Cn(e,t,n,a);break;case 3:Cn(e,t,n,a),s&2048&&(e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&Jr(e)));break;case 12:if(s&2048){Cn(e,t,n,a),e=t.stateNode;try{var i=t.memoizedProps,r=i.id,l=i.onPostCommit;typeof l=="function"&&l(r,t.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(o){Le(t,t.return,o)}}else Cn(e,t,n,a);break;case 31:Cn(e,t,n,a);break;case 13:Cn(e,t,n,a);break;case 23:break;case 22:i=t.stateNode,r=t.alternate,t.memoizedState!==null?i._visibility&2?Cn(e,t,n,a):mr(e,t):i._visibility&2?Cn(e,t,n,a):(i._visibility|=2,Hs(e,t,n,a,(t.subtreeFlags&10256)!==0||!1)),s&2048&&dh(r,t);break;case 24:Cn(e,t,n,a),s&2048&&hh(t.alternate,t);break;default:Cn(e,t,n,a)}}function Hs(e,t,n,a,s){for(s=s&&((t.subtreeFlags&10256)!==0||!1),t=t.child;t!==null;){var i=e,r=t,l=n,o=a,u=r.flags;switch(r.tag){case 0:case 11:case 15:Hs(i,r,l,o,s),Qr(8,r);break;case 23:break;case 22:var h=r.stateNode;r.memoizedState!==null?h._visibility&2?Hs(i,r,l,o,s):mr(i,r):(h._visibility|=2,Hs(i,r,l,o,s)),s&&u&2048&&dh(r.alternate,r);break;case 24:Hs(i,r,l,o,s),s&&u&2048&&hh(r.alternate,r);break;default:Hs(i,r,l,o,s)}t=t.sibling}}function mr(e,t){if(t.subtreeFlags&10256)for(t=t.child;t!==null;){var n=e,a=t,s=a.flags;switch(a.tag){case 22:mr(n,a),s&2048&&dh(a.alternate,a);break;case 24:mr(n,a),s&2048&&hh(a.alternate,a);break;default:mr(n,a)}t=t.sibling}}var tr=8192;function js(e,t,n){if(e.subtreeFlags&tr)for(e=e.child;e!==null;)fy(e,t,n),e=e.sibling}function fy(e,t,n){switch(e.tag){case 26:js(e,t,n),e.flags&tr&&e.memoizedState!==null&&gS(n,Nn,e.memoizedState,e.memoizedProps);break;case 5:js(e,t,n);break;case 3:case 4:var a=Nn;Nn=Oo(e.stateNode.containerInfo),js(e,t,n),Nn=a;break;case 22:e.memoizedState===null&&(a=e.alternate,a!==null&&a.memoizedState!==null?(a=tr,tr=16777216,js(e,t,n),tr=a):js(e,t,n));break;default:js(e,t,n)}}function py(e){var t=e.alternate;if(t!==null&&(e=t.child,e!==null)){t.child=null;do t=e.sibling,e.sibling=null,e=t;while(e!==null)}}function Ki(e){var t=e.deletions;if(e.flags&16){if(t!==null)for(var n=0;n<t.length;n++){var a=t[n];wt=a,gy(a,e)}py(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)my(e),e=e.sibling}function my(e){switch(e.tag){case 0:case 11:case 15:Ki(e),e.flags&2048&&Xa(9,e,e.return);break;case 3:Ki(e);break;case 12:Ki(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,Xl(e)):Ki(e);break;default:Ki(e)}}function Xl(e){var t=e.deletions;if(e.flags&16){if(t!==null)for(var n=0;n<t.length;n++){var a=t[n];wt=a,gy(a,e)}py(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:Xa(8,t,t.return),Xl(t);break;case 22:n=t.stateNode,n._visibility&2&&(n._visibility&=-3,Xl(t));break;default:Xl(t)}e=e.sibling}}function gy(e,t){for(;wt!==null;){var n=wt;switch(n.tag){case 0:case 11:case 15:Xa(8,n,t);break;case 23:case 22:if(n.memoizedState!==null&&n.memoizedState.cachePool!==null){var a=n.memoizedState.cachePool.pool;a!=null&&a.refCount++}break;case 24:Jr(n.memoizedState.cache)}if(a=n.child,a!==null)a.return=n,wt=a;else e:for(n=e;wt!==null;){a=wt;var s=a.sibling,i=a.return;if(ry(a),a===n){wt=null;break e}if(s!==null){s.return=i,wt=s;break e}wt=i}}}var k0={getCacheForType:function(e){var t=Nt(ut),n=t.data.get(e);return n===void 0&&(n=e(),t.data.set(e,n)),n},cacheSignal:function(){return Nt(ut).controller.signal}},j0=typeof WeakMap=="function"?WeakMap:Map,je=0,He=null,ye=null,Se=0,Ue=0,Qt=null,La=!1,Ri=!1,fh=!1,ga=0,et=0,Qa=0,ys=0,ph=0,nn=0,Si=0,gr=null,Yt=null,Xu=!1,tc=0,yy=0,_o=1/0,wo=null,qa=null,mt=0,Ga=null,_i=null,da=0,Qu=0,Wu=null,vy=null,yr=0,Zu=null;function ln(){return je&2&&Se!==0?Se&-Se:ne.T!==null?gh():Cm()}function by(){if(nn===0)if(!(Se&536870912)||we){var e=fl;fl<<=1,!(fl&3932160)&&(fl=262144),nn=e}else nn=536870912;return e=cn.current,e!==null&&(e.flags|=32),nn}function Ft(e,t,n){(e===He&&(Ue===2||Ue===9)||e.cancelPendingCommit!==null)&&(wi(e,0),za(e,Se,nn,!1)),Vr(e,n),(!(je&2)||e!==He)&&(e===He&&(!(je&2)&&(ys|=n),et===4&&za(e,Se,nn,!1)),Gn(e))}function Sy(e,t,n){if(je&6)throw Error(N(327));var a=!n&&(t&127)===0&&(t&e.expiredLanes)===0||Kr(e,t),s=a?U0(e,t):qc(e,t,!0),i=a;do{if(s===0){Ri&&!a&&za(e,t,0,!1);break}else{if(n=e.current.alternate,i&&!D0(n)){s=qc(e,t,!1),i=!1;continue}if(s===2){if(i=t,e.errorRecoveryDisabledLanes&i)var r=0;else r=e.pendingLanes&-536870913,r=r!==0?r:r&536870912?536870912:0;if(r!==0){t=r;e:{var l=e;s=gr;var o=l.current.memoizedState.isDehydrated;if(o&&(wi(l,r).flags|=256),r=qc(l,r,!1),r!==2){if(fh&&!o){l.errorRecoveryDisabledLanes|=i,ys|=i,s=4;break e}i=Yt,Yt=s,i!==null&&(Yt===null?Yt=i:Yt.push.apply(Yt,i))}s=r}if(i=!1,s!==2)continue}}if(s===1){wi(e,0),za(e,t,0,!0);break}e:{switch(a=e,i=s,i){case 0:case 1:throw Error(N(345));case 4:if((t&4194048)!==t)break;case 6:za(a,t,nn,!La);break e;case 2:Yt=null;break;case 3:case 5:break;default:throw Error(N(329))}if((t&62914560)===t&&(s=tc+300-an(),10<s)){if(za(a,t,nn,!La),Go(a,0,!0)!==0)break e;da=t,a.timeoutHandle=Hy(Df.bind(null,a,n,Yt,wo,Xu,t,nn,ys,Si,La,i,"Throttled",-0,0),s);break e}Df(a,n,Yt,wo,Xu,t,nn,ys,Si,La,i,null,-0,0)}}break}while(!0);Gn(e)}function Df(e,t,n,a,s,i,r,l,o,u,h,f,d,p){if(e.timeoutHandle=-1,f=t.subtreeFlags,f&8192||(f&16785408)===16785408){f={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:la},fy(t,i,f);var v=(i&62914560)===i?tc-an():(i&4194048)===i?yy-an():0;if(v=yS(f,v),v!==null){da=i,e.cancelPendingCommit=v(Uf.bind(null,e,t,i,n,a,s,r,l,o,h,f,null,d,p)),za(e,i,r,!u);return}}Uf(e,t,i,n,a,s,r,l,o)}function D0(e){for(var t=e;;){var n=t.tag;if((n===0||n===11||n===15)&&t.flags&16384&&(n=t.updateQueue,n!==null&&(n=n.stores,n!==null)))for(var a=0;a<n.length;a++){var s=n[a],i=s.getSnapshot;s=s.value;try{if(!on(i(),s))return!1}catch{return!1}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function za(e,t,n,a){t&=~ph,t&=~ys,e.suspendedLanes|=t,e.pingedLanes&=~t,a&&(e.warmLanes|=t),a=e.expirationTimes;for(var s=t;0<s;){var i=31-rn(s),r=1<<i;a[i]=-1,s&=~r}n!==0&&Tm(e,n,t)}function nc(){return je&6?!0:(Wr(0),!1)}function mh(){if(ye!==null){if(Ue===0)var e=ye.return;else e=ye,oa=Cs=null,eh(e),ci=null,Or=0,e=ye;for(;e!==null;)Zg(e.alternate,e),e=e.return;ye=null}}function wi(e,t){var n=e.timeoutHandle;n!==-1&&(e.timeoutHandle=-1,Z0(n)),n=e.cancelPendingCommit,n!==null&&(e.cancelPendingCommit=null,n()),da=0,mh(),He=e,ye=n=ca(e.current,null),Se=t,Ue=0,Qt=null,La=!1,Ri=Kr(e,t),fh=!1,Si=nn=ph=ys=Qa=et=0,Yt=gr=null,Xu=!1,t&8&&(t|=t&32);var a=e.entangledLanes;if(a!==0)for(e=e.entanglements,a&=t;0<a;){var s=31-rn(a),i=1<<s;t|=e[s],a&=~i}return ga=t,Fo(),n}function _y(e,t){oe=null,ne.H=Nr,t===Oi||t===Xo?(t=df(),Ue=3):t===Yd?(t=df(),Ue=4):Ue=t===ch?8:t!==null&&typeof t=="object"&&typeof t.then=="function"?6:1,Qt=t,ye===null&&(et=1,vo(e,vn(t,e.current)))}function wy(){var e=cn.current;return e===null?!0:(Se&4194048)===Se?Sn===null:(Se&62914560)===Se||Se&536870912?e===Sn:!1}function xy(){var e=ne.H;return ne.H=Nr,e===null?Nr:e}function Ty(){var e=ne.A;return ne.A=k0,e}function xo(){et=4,La||(Se&4194048)!==Se&&cn.current!==null||(Ri=!0),!(Qa&134217727)&&!(ys&134217727)||He===null||za(He,Se,nn,!1)}function qc(e,t,n){var a=je;je|=2;var s=xy(),i=Ty();(He!==e||Se!==t)&&(wo=null,wi(e,t)),t=!1;var r=et;e:do try{if(Ue!==0&&ye!==null){var l=ye,o=Qt;switch(Ue){case 8:mh(),r=6;break e;case 3:case 2:case 9:case 6:cn.current===null&&(t=!0);var u=Ue;if(Ue=0,Qt=null,ai(e,l,o,u),n&&Ri){r=0;break e}break;default:u=Ue,Ue=0,Qt=null,ai(e,l,o,u)}}M0(),r=et;break}catch(h){_y(e,h)}while(!0);return t&&e.shellSuspendCounter++,oa=Cs=null,je=a,ne.H=s,ne.A=i,ye===null&&(He=null,Se=0,Fo()),r}function M0(){for(;ye!==null;)Ey(ye)}function U0(e,t){var n=je;je|=2;var a=xy(),s=Ty();He!==e||Se!==t?(wo=null,_o=an()+500,wi(e,t)):Ri=Kr(e,t);e:do try{if(Ue!==0&&ye!==null){t=ye;var i=Qt;t:switch(Ue){case 1:Ue=0,Qt=null,ai(e,t,i,1);break;case 2:case 9:if(uf(i)){Ue=0,Qt=null,Mf(t);break}t=function(){Ue!==2&&Ue!==9||He!==e||(Ue=7),Gn(e)},i.then(t,t);break e;case 3:Ue=7;break e;case 4:Ue=5;break e;case 7:uf(i)?(Ue=0,Qt=null,Mf(t)):(Ue=0,Qt=null,ai(e,t,i,7));break;case 5:var r=null;switch(ye.tag){case 26:r=ye.memoizedState;case 5:case 27:var l=ye;if(r?Ky(r):l.stateNode.complete){Ue=0,Qt=null;var o=l.sibling;if(o!==null)ye=o;else{var u=l.return;u!==null?(ye=u,ac(u)):ye=null}break t}}Ue=0,Qt=null,ai(e,t,i,5);break;case 6:Ue=0,Qt=null,ai(e,t,i,6);break;case 8:mh(),et=6;break e;default:throw Error(N(462))}}L0();break}catch(h){_y(e,h)}while(!0);return oa=Cs=null,ne.H=a,ne.A=s,je=n,ye!==null?0:(He=null,Se=0,Fo(),et)}function L0(){for(;ye!==null&&!ib();)Ey(ye)}function Ey(e){var t=Wg(e.alternate,e,ga);e.memoizedProps=e.pendingProps,t===null?ac(e):ye=t}function Mf(e){var t=e,n=t.alternate;switch(t.tag){case 15:case 0:t=Cf(n,t,t.pendingProps,t.type,void 0,Se);break;case 11:t=Cf(n,t,t.pendingProps,t.type.render,t.ref,Se);break;case 5:eh(t);default:Zg(n,t),t=ye=Zm(t,ga),t=Wg(n,t,ga)}e.memoizedProps=e.pendingProps,t===null?ac(e):ye=t}function ai(e,t,n,a){oa=Cs=null,eh(t),ci=null,Or=0;var s=t.return;try{if(T0(e,s,t,n,Se)){et=1,vo(e,vn(n,e.current)),ye=null;return}}catch(i){if(s!==null)throw ye=s,i;et=1,vo(e,vn(n,e.current)),ye=null;return}t.flags&32768?(we||a===1?e=!0:Ri||Se&536870912?e=!1:(La=e=!0,(a===2||a===9||a===3||a===6)&&(a=cn.current,a!==null&&a.tag===13&&(a.flags|=16384))),Ay(t,e)):ac(t)}function ac(e){var t=e;do{if(t.flags&32768){Ay(t,La);return}e=t.return;var n=C0(t.alternate,t,ga);if(n!==null){ye=n;return}if(t=t.sibling,t!==null){ye=t;return}ye=t=e}while(t!==null);et===0&&(et=5)}function Ay(e,t){do{var n=O0(e.alternate,e);if(n!==null){n.flags&=32767,ye=n;return}if(n=e.return,n!==null&&(n.flags|=32768,n.subtreeFlags=0,n.deletions=null),!t&&(e=e.sibling,e!==null)){ye=e;return}ye=e=n}while(e!==null);et=6,ye=null}function Uf(e,t,n,a,s,i,r,l,o){e.cancelPendingCommit=null;do sc();while(mt!==0);if(je&6)throw Error(N(327));if(t!==null){if(t===e.current)throw Error(N(177));if(i=t.lanes|t.childLanes,i|=Hd,mb(e,n,i,r,l,o),e===He&&(ye=He=null,Se=0),_i=t,Ga=e,da=n,Qu=i,Wu=s,vy=a,t.subtreeFlags&10256||t.flags&10256?(e.callbackNode=null,e.callbackPriority=0,H0(ro,function(){return ky(),null})):(e.callbackNode=null,e.callbackPriority=0),a=(t.flags&13878)!==0,t.subtreeFlags&13878||a){a=ne.T,ne.T=null,s=De.p,De.p=2,r=je,je|=4;try{R0(e,t,n)}finally{je=r,De.p=s,ne.T=a}}mt=1,Cy(),Oy(),Ry()}}function Cy(){if(mt===1){mt=0;var e=Ga,t=_i,n=(t.flags&13878)!==0;if(t.subtreeFlags&13878||n){n=ne.T,ne.T=null;var a=De.p;De.p=2;var s=je;je|=4;try{uy(t,e);var i=ad,r=Km(e.containerInfo),l=i.focusedElem,o=i.selectionRange;if(r!==l&&l&&l.ownerDocument&&Gm(l.ownerDocument.documentElement,l)){if(o!==null&&Id(l)){var u=o.start,h=o.end;if(h===void 0&&(h=u),"selectionStart"in l)l.selectionStart=u,l.selectionEnd=Math.min(h,l.value.length);else{var f=l.ownerDocument||document,d=f&&f.defaultView||window;if(d.getSelection){var p=d.getSelection(),v=l.textContent.length,_=Math.min(o.start,v),x=o.end===void 0?_:Math.min(o.end,v);!p.extend&&_>x&&(r=x,x=_,_=r);var g=nf(l,_),m=nf(l,x);if(g&&m&&(p.rangeCount!==1||p.anchorNode!==g.node||p.anchorOffset!==g.offset||p.focusNode!==m.node||p.focusOffset!==m.offset)){var y=f.createRange();y.setStart(g.node,g.offset),p.removeAllRanges(),_>x?(p.addRange(y),p.extend(m.node,m.offset)):(y.setEnd(m.node,m.offset),p.addRange(y))}}}}for(f=[],p=l;p=p.parentNode;)p.nodeType===1&&f.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof l.focus=="function"&&l.focus(),l=0;l<f.length;l++){var w=f[l];w.element.scrollLeft=w.left,w.element.scrollTop=w.top}}ko=!!nd,ad=nd=null}finally{je=s,De.p=a,ne.T=n}}e.current=t,mt=2}}function Oy(){if(mt===2){mt=0;var e=Ga,t=_i,n=(t.flags&8772)!==0;if(t.subtreeFlags&8772||n){n=ne.T,ne.T=null;var a=De.p;De.p=2;var s=je;je|=4;try{iy(e,t.alternate,t)}finally{je=s,De.p=a,ne.T=n}}mt=3}}function Ry(){if(mt===4||mt===3){mt=0,rb();var e=Ga,t=_i,n=da,a=vy;t.subtreeFlags&10256||t.flags&10256?mt=5:(mt=0,_i=Ga=null,Ny(e,e.pendingLanes));var s=e.pendingLanes;if(s===0&&(qa=null),jd(n),t=t.stateNode,sn&&typeof sn.onCommitFiberRoot=="function")try{sn.onCommitFiberRoot(Gr,t,void 0,(t.current.flags&128)===128)}catch{}if(a!==null){t=ne.T,s=De.p,De.p=2,ne.T=null;try{for(var i=e.onRecoverableError,r=0;r<a.length;r++){var l=a[r];i(l.value,{componentStack:l.stack})}}finally{ne.T=t,De.p=s}}da&3&&sc(),Gn(e),s=e.pendingLanes,n&261930&&s&42?e===Zu?yr++:(yr=0,Zu=e):yr=0,Wr(0)}}function Ny(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,Jr(t)))}function sc(){return Cy(),Oy(),Ry(),ky()}function ky(){if(mt!==5)return!1;var e=Ga,t=Qu;Qu=0;var n=jd(da),a=ne.T,s=De.p;try{De.p=32>n?32:n,ne.T=null,n=Wu,Wu=null;var i=Ga,r=da;if(mt=0,_i=Ga=null,da=0,je&6)throw Error(N(331));var l=je;if(je|=4,my(i.current),hy(i,i.current,r,n),je=l,Wr(0,!1),sn&&typeof sn.onPostCommitFiberRoot=="function")try{sn.onPostCommitFiberRoot(Gr,i)}catch{}return!0}finally{De.p=s,ne.T=a,Ny(e,t)}}function Lf(e,t,n){t=vn(n,t),t=Vu(e.stateNode,t,2),e=Pa(e,t,2),e!==null&&(Vr(e,2),Gn(e))}function Le(e,t,n){if(e.tag===3)Lf(e,e,n);else for(;t!==null;){if(t.tag===3){Lf(t,e,n);break}else if(t.tag===1){var a=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(qa===null||!qa.has(a))){e=vn(n,e),n=Vg(2),a=Pa(t,n,2),a!==null&&(Yg(n,a,t,e),Vr(a,2),Gn(a));break}}t=t.return}}function Gc(e,t,n){var a=e.pingCache;if(a===null){a=e.pingCache=new j0;var s=new Set;a.set(t,s)}else s=a.get(t),s===void 0&&(s=new Set,a.set(t,s));s.has(n)||(fh=!0,s.add(n),e=z0.bind(null,e,t,n),t.then(e,e))}function z0(e,t,n){var a=e.pingCache;a!==null&&a.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,He===e&&(Se&n)===n&&(et===4||et===3&&(Se&62914560)===Se&&300>an()-tc?!(je&2)&&wi(e,0):ph|=n,Si===Se&&(Si=0)),Gn(e)}function jy(e,t){t===0&&(t=xm()),e=As(e,t),e!==null&&(Vr(e,t),Gn(e))}function B0(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),jy(e,n)}function I0(e,t){var n=0;switch(e.tag){case 31:case 13:var a=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:a=e.stateNode;break;case 22:a=e.stateNode._retryCache;break;default:throw Error(N(314))}a!==null&&a.delete(t),jy(e,n)}function H0(e,t){return Nd(e,t)}var To=null,$s=null,ed=!1,Eo=!1,Kc=!1,Ba=0;function Gn(e){e!==$s&&e.next===null&&($s===null?To=$s=e:$s=$s.next=e),Eo=!0,ed||(ed=!0,P0())}function Wr(e,t){if(!Kc&&Eo){Kc=!0;do for(var n=!1,a=To;a!==null;){if(e!==0){var s=a.pendingLanes;if(s===0)var i=0;else{var r=a.suspendedLanes,l=a.pingedLanes;i=(1<<31-rn(42|e)+1)-1,i&=s&~(r&~l),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(n=!0,zf(a,i))}else i=Se,i=Go(a,a===He?i:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),!(i&3)||Kr(a,i)||(n=!0,zf(a,i));a=a.next}while(n);Kc=!1}}function $0(){Dy()}function Dy(){Eo=ed=!1;var e=0;Ba!==0&&W0()&&(e=Ba);for(var t=an(),n=null,a=To;a!==null;){var s=a.next,i=My(a,t);i===0?(a.next=null,n===null?To=s:n.next=s,s===null&&($s=n)):(n=a,(e!==0||i&3)&&(Eo=!0)),a=s}mt!==0&&mt!==5||Wr(e),Ba!==0&&(Ba=0)}function My(e,t){for(var n=e.suspendedLanes,a=e.pingedLanes,s=e.expirationTimes,i=e.pendingLanes&-62914561;0<i;){var r=31-rn(i),l=1<<r,o=s[r];o===-1?(!(l&n)||l&a)&&(s[r]=pb(l,t)):o<=t&&(e.expiredLanes|=l),i&=~l}if(t=He,n=Se,n=Go(e,e===t?n:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),a=e.callbackNode,n===0||e===t&&(Ue===2||Ue===9)||e.cancelPendingCommit!==null)return a!==null&&a!==null&&bc(a),e.callbackNode=null,e.callbackPriority=0;if(!(n&3)||Kr(e,n)){if(t=n&-n,t===e.callbackPriority)return t;switch(a!==null&&bc(a),jd(n)){case 2:case 8:n=_m;break;case 32:n=ro;break;case 268435456:n=wm;break;default:n=ro}return a=Uy.bind(null,e),n=Nd(n,a),e.callbackPriority=t,e.callbackNode=n,t}return a!==null&&a!==null&&bc(a),e.callbackPriority=2,e.callbackNode=null,2}function Uy(e,t){if(mt!==0&&mt!==5)return e.callbackNode=null,e.callbackPriority=0,null;var n=e.callbackNode;if(sc()&&e.callbackNode!==n)return null;var a=Se;return a=Go(e,e===He?a:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),a===0?null:(Sy(e,a,t),My(e,an()),e.callbackNode!=null&&e.callbackNode===n?Uy.bind(null,e):null)}function zf(e,t){if(sc())return null;Sy(e,t,!0)}function P0(){eS(function(){je&6?Nd(Sm,$0):Dy()})}function gh(){if(Ba===0){var e=yi;e===0&&(e=hl,hl<<=1,!(hl&261888)&&(hl=256)),Ba=e}return Ba}function Bf(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:$l(""+e)}function If(e,t){var n=t.ownerDocument.createElement("input");return n.name=t.name,n.value=t.value,e.id&&n.setAttribute("form",e.id),t.parentNode.insertBefore(n,t),e=new FormData(e),n.parentNode.removeChild(n),e}function q0(e,t,n,a,s){if(t==="submit"&&n&&n.stateNode===s){var i=Bf((s[Jt]||null).action),r=a.submitter;r&&(t=(t=r[Jt]||null)?Bf(t.formAction):r.getAttribute("formAction"),t!==null&&(i=t,r=null));var l=new Ko("action","action",null,a,s);e.push({event:l,listeners:[{instance:null,listener:function(){if(a.defaultPrevented){if(Ba!==0){var o=r?If(s,r):new FormData(s);Gu(n,{pending:!0,data:o,method:s.method,action:i},null,o)}}else typeof i=="function"&&(l.preventDefault(),o=r?If(s,r):new FormData(s),Gu(n,{pending:!0,data:o,method:s.method,action:i},i,o))},currentTarget:s}]})}}for(var Vc=0;Vc<ju.length;Vc++){var Yc=ju[Vc],G0=Yc.toLowerCase(),K0=Yc[0].toUpperCase()+Yc.slice(1);jn(G0,"on"+K0)}jn(Ym,"onAnimationEnd");jn(Fm,"onAnimationIteration");jn(Jm,"onAnimationStart");jn("dblclick","onDoubleClick");jn("focusin","onFocus");jn("focusout","onBlur");jn(l0,"onTransitionRun");jn(o0,"onTransitionStart");jn(c0,"onTransitionCancel");jn(Xm,"onTransitionEnd");mi("onMouseEnter",["mouseout","mouseover"]);mi("onMouseLeave",["mouseout","mouseover"]);mi("onPointerEnter",["pointerout","pointerover"]);mi("onPointerLeave",["pointerout","pointerover"]);xs("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));xs("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));xs("onBeforeInput",["compositionend","keypress","textInput","paste"]);xs("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));xs("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));xs("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var kr="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),V0=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(kr));function Ly(e,t){t=(t&4)!==0;for(var n=0;n<e.length;n++){var a=e[n],s=a.event;a=a.listeners;e:{var i=void 0;if(t)for(var r=a.length-1;0<=r;r--){var l=a[r],o=l.instance,u=l.currentTarget;if(l=l.listener,o!==i&&s.isPropagationStopped())break e;i=l,s.currentTarget=u;try{i(s)}catch(h){oo(h)}s.currentTarget=null,i=o}else for(r=0;r<a.length;r++){if(l=a[r],o=l.instance,u=l.currentTarget,l=l.listener,o!==i&&s.isPropagationStopped())break e;i=l,s.currentTarget=u;try{i(s)}catch(h){oo(h)}s.currentTarget=null,i=o}}}}function ge(e,t){var n=t[Tu];n===void 0&&(n=t[Tu]=new Set);var a=e+"__bubble";n.has(a)||(zy(t,e,2,!1),n.add(a))}function Fc(e,t,n){var a=0;t&&(a|=4),zy(n,e,a,t)}var wl="_reactListening"+Math.random().toString(36).slice(2);function yh(e){if(!e[wl]){e[wl]=!0,Om.forEach(function(n){n!=="selectionchange"&&(V0.has(n)||Fc(n,!1,e),Fc(n,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[wl]||(t[wl]=!0,Fc("selectionchange",!1,t))}}function zy(e,t,n,a){switch(Xy(t)){case 2:var s=SS;break;case 8:s=_S;break;default:s=_h}n=s.bind(null,t,n,e),s=void 0,!Ru||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(s=!0),a?s!==void 0?e.addEventListener(t,n,{capture:!0,passive:s}):e.addEventListener(t,n,!0):s!==void 0?e.addEventListener(t,n,{passive:s}):e.addEventListener(t,n,!1)}function Jc(e,t,n,a,s){var i=a;if(!(t&1)&&!(t&2)&&a!==null)e:for(;;){if(a===null)return;var r=a.tag;if(r===3||r===4){var l=a.stateNode.containerInfo;if(l===s)break;if(r===4)for(r=a.return;r!==null;){var o=r.tag;if((o===3||o===4)&&r.stateNode.containerInfo===s)return;r=r.return}for(;l!==null;){if(r=Fs(l),r===null)return;if(o=r.tag,o===5||o===6||o===26||o===27){a=i=r;continue e}l=l.parentNode}}a=a.return}Lm(function(){var u=i,h=Ud(n),f=[];e:{var d=Qm.get(e);if(d!==void 0){var p=Ko,v=e;switch(e){case"keypress":if(ql(n)===0)break e;case"keydown":case"keyup":p=Ib;break;case"focusin":v="focus",p=Tc;break;case"focusout":v="blur",p=Tc;break;case"beforeblur":case"afterblur":p=Tc;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":p=Vh;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":p=Cb;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":p=Pb;break;case Ym:case Fm:case Jm:p=Nb;break;case Xm:p=Gb;break;case"scroll":case"scrollend":p=Eb;break;case"wheel":p=Vb;break;case"copy":case"cut":case"paste":p=jb;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":p=Fh;break;case"toggle":case"beforetoggle":p=Fb}var _=(t&4)!==0,x=!_&&(e==="scroll"||e==="scrollend"),g=_?d!==null?d+"Capture":null:d;_=[];for(var m=u,y;m!==null;){var w=m;if(y=w.stateNode,w=w.tag,w!==5&&w!==26&&w!==27||y===null||g===null||(w=xr(m,g),w!=null&&_.push(jr(m,w,y))),x)break;m=m.return}0<_.length&&(d=new p(d,v,null,n,h),f.push({event:d,listeners:_}))}}if(!(t&7)){e:{if(d=e==="mouseover"||e==="pointerover",p=e==="mouseout"||e==="pointerout",d&&n!==Ou&&(v=n.relatedTarget||n.fromElement)&&(Fs(v)||v[Ei]))break e;if((p||d)&&(d=h.window===h?h:(d=h.ownerDocument)?d.defaultView||d.parentWindow:window,p?(v=n.relatedTarget||n.toElement,p=u,v=v?Fs(v):null,v!==null&&(x=qr(v),_=v.tag,v!==x||_!==5&&_!==27&&_!==6)&&(v=null)):(p=null,v=u),p!==v)){if(_=Vh,w="onMouseLeave",g="onMouseEnter",m="mouse",(e==="pointerout"||e==="pointerover")&&(_=Fh,w="onPointerLeave",g="onPointerEnter",m="pointer"),x=p==null?d:Zi(p),y=v==null?d:Zi(v),d=new _(w,m+"leave",p,n,h),d.target=x,d.relatedTarget=y,w=null,Fs(h)===u&&(_=new _(g,m+"enter",v,n,h),_.target=y,_.relatedTarget=x,w=_),x=w,p&&v)t:{for(_=Y0,g=p,m=v,y=0,w=g;w;w=_(w))y++;w=0;for(var C=m;C;C=_(C))w++;for(;0<y-w;)g=_(g),y--;for(;0<w-y;)m=_(m),w--;for(;y--;){if(g===m||m!==null&&g===m.alternate){_=g;break t}g=_(g),m=_(m)}_=null}else _=null;p!==null&&Hf(f,d,p,_,!1),v!==null&&x!==null&&Hf(f,x,v,_,!0)}}e:{if(d=u?Zi(u):window,p=d.nodeName&&d.nodeName.toLowerCase(),p==="select"||p==="input"&&d.type==="file")var R=Wh;else if(Qh(d))if(Pm)R=s0;else{R=n0;var O=t0}else p=d.nodeName,!p||p.toLowerCase()!=="input"||d.type!=="checkbox"&&d.type!=="radio"?u&&Md(u.elementType)&&(R=Wh):R=a0;if(R&&(R=R(e,u))){$m(f,R,n,h);break e}O&&O(e,d,u),e==="focusout"&&u&&d.type==="number"&&u.memoizedProps.value!=null&&Cu(d,"number",d.value)}switch(O=u?Zi(u):window,e){case"focusin":(Qh(O)||O.contentEditable==="true")&&(Qs=O,Nu=u,or=null);break;case"focusout":or=Nu=Qs=null;break;case"mousedown":ku=!0;break;case"contextmenu":case"mouseup":case"dragend":ku=!1,af(f,n,h);break;case"selectionchange":if(r0)break;case"keydown":case"keyup":af(f,n,h)}var z;if(Bd)e:{switch(e){case"compositionstart":var q="onCompositionStart";break e;case"compositionend":q="onCompositionEnd";break e;case"compositionupdate":q="onCompositionUpdate";break e}q=void 0}else Xs?Im(e,n)&&(q="onCompositionEnd"):e==="keydown"&&n.keyCode===229&&(q="onCompositionStart");q&&(Bm&&n.locale!=="ko"&&(Xs||q!=="onCompositionStart"?q==="onCompositionEnd"&&Xs&&(z=zm()):(Ua=h,Ld="value"in Ua?Ua.value:Ua.textContent,Xs=!0)),O=Ao(u,q),0<O.length&&(q=new Yh(q,e,null,n,h),f.push({event:q,listeners:O}),z?q.data=z:(z=Hm(n),z!==null&&(q.data=z)))),(z=Xb?Qb(e,n):Wb(e,n))&&(q=Ao(u,"onBeforeInput"),0<q.length&&(O=new Yh("onBeforeInput","beforeinput",null,n,h),f.push({event:O,listeners:q}),O.data=z)),q0(f,e,u,n,h)}Ly(f,t)})}function jr(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Ao(e,t){for(var n=t+"Capture",a=[];e!==null;){var s=e,i=s.stateNode;if(s=s.tag,s!==5&&s!==26&&s!==27||i===null||(s=xr(e,n),s!=null&&a.unshift(jr(e,s,i)),s=xr(e,t),s!=null&&a.push(jr(e,s,i))),e.tag===3)return a;e=e.return}return[]}function Y0(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Hf(e,t,n,a,s){for(var i=t._reactName,r=[];n!==null&&n!==a;){var l=n,o=l.alternate,u=l.stateNode;if(l=l.tag,o!==null&&o===a)break;l!==5&&l!==26&&l!==27||u===null||(o=u,s?(u=xr(n,i),u!=null&&r.unshift(jr(n,u,o))):s||(u=xr(n,i),u!=null&&r.push(jr(n,u,o)))),n=n.return}r.length!==0&&e.push({event:t,listeners:r})}var F0=/\r\n?/g,J0=/\u0000|\uFFFD/g;function $f(e){return(typeof e=="string"?e:""+e).replace(F0,`
33
+ `).replace(J0,"")}function By(e,t){return t=$f(t),$f(e)===t}function ze(e,t,n,a,s,i){switch(n){case"children":typeof a=="string"?t==="body"||t==="textarea"&&a===""||gi(e,a):(typeof a=="number"||typeof a=="bigint")&&t!=="body"&&gi(e,""+a);break;case"className":ml(e,"class",a);break;case"tabIndex":ml(e,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":ml(e,n,a);break;case"style":Um(e,a,i);break;case"data":if(t!=="object"){ml(e,"data",a);break}case"src":case"href":if(a===""&&(t!=="a"||n!=="href")){e.removeAttribute(n);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){e.removeAttribute(n);break}a=$l(""+a),e.setAttribute(n,a);break;case"action":case"formAction":if(typeof a=="function"){e.setAttribute(n,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof i=="function"&&(n==="formAction"?(t!=="input"&&ze(e,t,"name",s.name,s,null),ze(e,t,"formEncType",s.formEncType,s,null),ze(e,t,"formMethod",s.formMethod,s,null),ze(e,t,"formTarget",s.formTarget,s,null)):(ze(e,t,"encType",s.encType,s,null),ze(e,t,"method",s.method,s,null),ze(e,t,"target",s.target,s,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){e.removeAttribute(n);break}a=$l(""+a),e.setAttribute(n,a);break;case"onClick":a!=null&&(e.onclick=la);break;case"onScroll":a!=null&&ge("scroll",e);break;case"onScrollEnd":a!=null&&ge("scrollend",e);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(N(61));if(n=a.__html,n!=null){if(s.children!=null)throw Error(N(60));e.innerHTML=n}}break;case"multiple":e.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":e.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){e.removeAttribute("xlink:href");break}n=$l(""+a),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?e.setAttribute(n,""+a):e.removeAttribute(n);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?e.setAttribute(n,""):e.removeAttribute(n);break;case"capture":case"download":a===!0?e.setAttribute(n,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?e.setAttribute(n,a):e.removeAttribute(n);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?e.setAttribute(n,a):e.removeAttribute(n);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?e.removeAttribute(n):e.setAttribute(n,a);break;case"popover":ge("beforetoggle",e),ge("toggle",e),Hl(e,"popover",a);break;case"xlinkActuate":Fn(e,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Fn(e,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Fn(e,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Fn(e,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Fn(e,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Fn(e,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Fn(e,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Fn(e,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Fn(e,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Hl(e,"is",a);break;case"innerText":case"textContent":break;default:(!(2<n.length)||n[0]!=="o"&&n[0]!=="O"||n[1]!=="n"&&n[1]!=="N")&&(n=xb.get(n)||n,Hl(e,n,a))}}function td(e,t,n,a,s,i){switch(n){case"style":Um(e,a,i);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(N(61));if(n=a.__html,n!=null){if(s.children!=null)throw Error(N(60));e.innerHTML=n}}break;case"children":typeof a=="string"?gi(e,a):(typeof a=="number"||typeof a=="bigint")&&gi(e,""+a);break;case"onScroll":a!=null&&ge("scroll",e);break;case"onScrollEnd":a!=null&&ge("scrollend",e);break;case"onClick":a!=null&&(e.onclick=la);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Rm.hasOwnProperty(n))e:{if(n[0]==="o"&&n[1]==="n"&&(s=n.endsWith("Capture"),t=n.slice(2,s?n.length-7:void 0),i=e[Jt]||null,i=i!=null?i[n]:null,typeof i=="function"&&e.removeEventListener(t,i,s),typeof a=="function")){typeof i!="function"&&i!==null&&(n in e?e[n]=null:e.hasAttribute(n)&&e.removeAttribute(n)),e.addEventListener(t,a,s);break e}n in e?e[n]=a:a===!0?e.setAttribute(n,""):Hl(e,n,a)}}}function jt(e,t,n){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":ge("error",e),ge("load",e);var a=!1,s=!1,i;for(i in n)if(n.hasOwnProperty(i)){var r=n[i];if(r!=null)switch(i){case"src":a=!0;break;case"srcSet":s=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(N(137,t));default:ze(e,t,i,r,n,null)}}s&&ze(e,t,"srcSet",n.srcSet,n,null),a&&ze(e,t,"src",n.src,n,null);return;case"input":ge("invalid",e);var l=i=r=s=null,o=null,u=null;for(a in n)if(n.hasOwnProperty(a)){var h=n[a];if(h!=null)switch(a){case"name":s=h;break;case"type":r=h;break;case"checked":o=h;break;case"defaultChecked":u=h;break;case"value":i=h;break;case"defaultValue":l=h;break;case"children":case"dangerouslySetInnerHTML":if(h!=null)throw Error(N(137,t));break;default:ze(e,t,a,h,n,null)}}jm(e,i,l,o,u,r,s,!1);return;case"select":ge("invalid",e),a=r=i=null;for(s in n)if(n.hasOwnProperty(s)&&(l=n[s],l!=null))switch(s){case"value":i=l;break;case"defaultValue":r=l;break;case"multiple":a=l;default:ze(e,t,s,l,n,null)}t=i,n=r,e.multiple=!!a,t!=null?ri(e,!!a,t,!1):n!=null&&ri(e,!!a,n,!0);return;case"textarea":ge("invalid",e),i=s=a=null;for(r in n)if(n.hasOwnProperty(r)&&(l=n[r],l!=null))switch(r){case"value":a=l;break;case"defaultValue":s=l;break;case"children":i=l;break;case"dangerouslySetInnerHTML":if(l!=null)throw Error(N(91));break;default:ze(e,t,r,l,n,null)}Mm(e,a,s,i);return;case"option":for(o in n)if(n.hasOwnProperty(o)&&(a=n[o],a!=null))switch(o){case"selected":e.selected=a&&typeof a!="function"&&typeof a!="symbol";break;default:ze(e,t,o,a,n,null)}return;case"dialog":ge("beforetoggle",e),ge("toggle",e),ge("cancel",e),ge("close",e);break;case"iframe":case"object":ge("load",e);break;case"video":case"audio":for(a=0;a<kr.length;a++)ge(kr[a],e);break;case"image":ge("error",e),ge("load",e);break;case"details":ge("toggle",e);break;case"embed":case"source":case"link":ge("error",e),ge("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(u in n)if(n.hasOwnProperty(u)&&(a=n[u],a!=null))switch(u){case"children":case"dangerouslySetInnerHTML":throw Error(N(137,t));default:ze(e,t,u,a,n,null)}return;default:if(Md(t)){for(h in n)n.hasOwnProperty(h)&&(a=n[h],a!==void 0&&td(e,t,h,a,n,void 0));return}}for(l in n)n.hasOwnProperty(l)&&(a=n[l],a!=null&&ze(e,t,l,a,n,null))}function X0(e,t,n,a){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var s=null,i=null,r=null,l=null,o=null,u=null,h=null;for(p in n){var f=n[p];if(n.hasOwnProperty(p)&&f!=null)switch(p){case"checked":break;case"value":break;case"defaultValue":o=f;default:a.hasOwnProperty(p)||ze(e,t,p,null,a,f)}}for(var d in a){var p=a[d];if(f=n[d],a.hasOwnProperty(d)&&(p!=null||f!=null))switch(d){case"type":i=p;break;case"name":s=p;break;case"checked":u=p;break;case"defaultChecked":h=p;break;case"value":r=p;break;case"defaultValue":l=p;break;case"children":case"dangerouslySetInnerHTML":if(p!=null)throw Error(N(137,t));break;default:p!==f&&ze(e,t,d,p,a,f)}}Au(e,r,l,o,u,h,i,s);return;case"select":p=r=l=d=null;for(i in n)if(o=n[i],n.hasOwnProperty(i)&&o!=null)switch(i){case"value":break;case"multiple":p=o;default:a.hasOwnProperty(i)||ze(e,t,i,null,a,o)}for(s in a)if(i=a[s],o=n[s],a.hasOwnProperty(s)&&(i!=null||o!=null))switch(s){case"value":d=i;break;case"defaultValue":l=i;break;case"multiple":r=i;default:i!==o&&ze(e,t,s,i,a,o)}t=l,n=r,a=p,d!=null?ri(e,!!n,d,!1):!!a!=!!n&&(t!=null?ri(e,!!n,t,!0):ri(e,!!n,n?[]:"",!1));return;case"textarea":p=d=null;for(l in n)if(s=n[l],n.hasOwnProperty(l)&&s!=null&&!a.hasOwnProperty(l))switch(l){case"value":break;case"children":break;default:ze(e,t,l,null,a,s)}for(r in a)if(s=a[r],i=n[r],a.hasOwnProperty(r)&&(s!=null||i!=null))switch(r){case"value":d=s;break;case"defaultValue":p=s;break;case"children":break;case"dangerouslySetInnerHTML":if(s!=null)throw Error(N(91));break;default:s!==i&&ze(e,t,r,s,a,i)}Dm(e,d,p);return;case"option":for(var v in n)if(d=n[v],n.hasOwnProperty(v)&&d!=null&&!a.hasOwnProperty(v))switch(v){case"selected":e.selected=!1;break;default:ze(e,t,v,null,a,d)}for(o in a)if(d=a[o],p=n[o],a.hasOwnProperty(o)&&d!==p&&(d!=null||p!=null))switch(o){case"selected":e.selected=d&&typeof d!="function"&&typeof d!="symbol";break;default:ze(e,t,o,d,a,p)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var _ in n)d=n[_],n.hasOwnProperty(_)&&d!=null&&!a.hasOwnProperty(_)&&ze(e,t,_,null,a,d);for(u in a)if(d=a[u],p=n[u],a.hasOwnProperty(u)&&d!==p&&(d!=null||p!=null))switch(u){case"children":case"dangerouslySetInnerHTML":if(d!=null)throw Error(N(137,t));break;default:ze(e,t,u,d,a,p)}return;default:if(Md(t)){for(var x in n)d=n[x],n.hasOwnProperty(x)&&d!==void 0&&!a.hasOwnProperty(x)&&td(e,t,x,void 0,a,d);for(h in a)d=a[h],p=n[h],!a.hasOwnProperty(h)||d===p||d===void 0&&p===void 0||td(e,t,h,d,a,p);return}}for(var g in n)d=n[g],n.hasOwnProperty(g)&&d!=null&&!a.hasOwnProperty(g)&&ze(e,t,g,null,a,d);for(f in a)d=a[f],p=n[f],!a.hasOwnProperty(f)||d===p||d==null&&p==null||ze(e,t,f,d,a,p)}function Pf(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Q0(){if(typeof performance.getEntriesByType=="function"){for(var e=0,t=0,n=performance.getEntriesByType("resource"),a=0;a<n.length;a++){var s=n[a],i=s.transferSize,r=s.initiatorType,l=s.duration;if(i&&l&&Pf(r)){for(r=0,l=s.responseEnd,a+=1;a<n.length;a++){var o=n[a],u=o.startTime;if(u>l)break;var h=o.transferSize,f=o.initiatorType;h&&Pf(f)&&(o=o.responseEnd,r+=h*(o<l?1:(l-u)/(o-u)))}if(--a,t+=8*(i+r)/(s.duration/1e3),e++,10<e)break}}if(0<e)return t/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var nd=null,ad=null;function Co(e){return e.nodeType===9?e:e.ownerDocument}function qf(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function Iy(e,t){if(e===0)switch(t){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&t==="foreignObject"?0:e}function sd(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.children=="bigint"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Xc=null;function W0(){var e=window.event;return e&&e.type==="popstate"?e===Xc?!1:(Xc=e,!0):(Xc=null,!1)}var Hy=typeof setTimeout=="function"?setTimeout:void 0,Z0=typeof clearTimeout=="function"?clearTimeout:void 0,Gf=typeof Promise=="function"?Promise:void 0,eS=typeof queueMicrotask=="function"?queueMicrotask:typeof Gf<"u"?function(e){return Gf.resolve(null).then(e).catch(tS)}:Hy;function tS(e){setTimeout(function(){throw e})}function Za(e){return e==="head"}function Kf(e,t){var n=t,a=0;do{var s=n.nextSibling;if(e.removeChild(n),s&&s.nodeType===8)if(n=s.data,n==="/$"||n==="/&"){if(a===0){e.removeChild(s),Ti(t);return}a--}else if(n==="$"||n==="$?"||n==="$~"||n==="$!"||n==="&")a++;else if(n==="html")vr(e.ownerDocument.documentElement);else if(n==="head"){n=e.ownerDocument.head,vr(n);for(var i=n.firstChild;i;){var r=i.nextSibling,l=i.nodeName;i[Yr]||l==="SCRIPT"||l==="STYLE"||l==="LINK"&&i.rel.toLowerCase()==="stylesheet"||n.removeChild(i),i=r}}else n==="body"&&vr(e.ownerDocument.body);n=s}while(n);Ti(t)}function Vf(e,t){var n=e;e=0;do{var a=n.nextSibling;if(n.nodeType===1?t?(n._stashedDisplay=n.style.display,n.style.display="none"):(n.style.display=n._stashedDisplay||"",n.getAttribute("style")===""&&n.removeAttribute("style")):n.nodeType===3&&(t?(n._stashedText=n.nodeValue,n.nodeValue=""):n.nodeValue=n._stashedText||""),a&&a.nodeType===8)if(n=a.data,n==="/$"){if(e===0)break;e--}else n!=="$"&&n!=="$?"&&n!=="$~"&&n!=="$!"||e++;n=a}while(n)}function id(e){var t=e.firstChild;for(t&&t.nodeType===10&&(t=t.nextSibling);t;){var n=t;switch(t=t.nextSibling,n.nodeName){case"HTML":case"HEAD":case"BODY":id(n),Dd(n);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(n.rel.toLowerCase()==="stylesheet")continue}e.removeChild(n)}}function nS(e,t,n,a){for(;e.nodeType===1;){var s=n;if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!a&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(a){if(!e[Yr])switch(t){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(i=e.getAttribute("rel"),i==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(i!==s.rel||e.getAttribute("href")!==(s.href==null||s.href===""?null:s.href)||e.getAttribute("crossorigin")!==(s.crossOrigin==null?null:s.crossOrigin)||e.getAttribute("title")!==(s.title==null?null:s.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(i=e.getAttribute("src"),(i!==(s.src==null?null:s.src)||e.getAttribute("type")!==(s.type==null?null:s.type)||e.getAttribute("crossorigin")!==(s.crossOrigin==null?null:s.crossOrigin))&&i&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(t==="input"&&e.type==="hidden"){var i=s.name==null?null:""+s.name;if(s.type==="hidden"&&e.getAttribute("name")===i)return e}else return e;if(e=_n(e.nextSibling),e===null)break}return null}function aS(e,t,n){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!n||(e=_n(e.nextSibling),e===null))return null;return e}function $y(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=_n(e.nextSibling),e===null))return null;return e}function rd(e){return e.data==="$?"||e.data==="$~"}function ld(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function sS(e,t){var n=e.ownerDocument;if(e.data==="$~")e._reactRetry=t;else if(e.data!=="$?"||n.readyState!=="loading")t();else{var a=function(){t(),n.removeEventListener("DOMContentLoaded",a)};n.addEventListener("DOMContentLoaded",a),e._reactRetry=a}}function _n(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?"||t==="$~"||t==="&"||t==="F!"||t==="F")break;if(t==="/$"||t==="/&")return null}}return e}var od=null;function Yf(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="/$"||n==="/&"){if(t===0)return _n(e.nextSibling);t--}else n!=="$"&&n!=="$!"&&n!=="$?"&&n!=="$~"&&n!=="&"||t++}e=e.nextSibling}return null}function Ff(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"||n==="$~"||n==="&"){if(t===0)return e;t--}else n!=="/$"&&n!=="/&"||t++}e=e.previousSibling}return null}function Py(e,t,n){switch(t=Co(n),e){case"html":if(e=t.documentElement,!e)throw Error(N(452));return e;case"head":if(e=t.head,!e)throw Error(N(453));return e;case"body":if(e=t.body,!e)throw Error(N(454));return e;default:throw Error(N(451))}}function vr(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);Dd(e)}var wn=new Map,Jf=new Set;function Oo(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var ya=De.d;De.d={f:iS,r:rS,D:lS,C:oS,L:cS,m:uS,X:hS,S:dS,M:fS};function iS(){var e=ya.f(),t=nc();return e||t}function rS(e){var t=Ai(e);t!==null&&t.tag===5&&t.type==="form"?Ug(t):ya.r(e)}var Ni=typeof document>"u"?null:document;function qy(e,t,n){var a=Ni;if(a&&typeof t=="string"&&t){var s=yn(t);s='link[rel="'+e+'"][href="'+s+'"]',typeof n=="string"&&(s+='[crossorigin="'+n+'"]'),Jf.has(s)||(Jf.add(s),e={rel:e,crossOrigin:n,href:t},a.querySelector(s)===null&&(t=a.createElement("link"),jt(t,"link",e),xt(t),a.head.appendChild(t)))}}function lS(e){ya.D(e),qy("dns-prefetch",e,null)}function oS(e,t){ya.C(e,t),qy("preconnect",e,t)}function cS(e,t,n){ya.L(e,t,n);var a=Ni;if(a&&e&&t){var s='link[rel="preload"][as="'+yn(t)+'"]';t==="image"&&n&&n.imageSrcSet?(s+='[imagesrcset="'+yn(n.imageSrcSet)+'"]',typeof n.imageSizes=="string"&&(s+='[imagesizes="'+yn(n.imageSizes)+'"]')):s+='[href="'+yn(e)+'"]';var i=s;switch(t){case"style":i=xi(e);break;case"script":i=ki(e)}wn.has(i)||(e=Fe({rel:"preload",href:t==="image"&&n&&n.imageSrcSet?void 0:e,as:t},n),wn.set(i,e),a.querySelector(s)!==null||t==="style"&&a.querySelector(Zr(i))||t==="script"&&a.querySelector(el(i))||(t=a.createElement("link"),jt(t,"link",e),xt(t),a.head.appendChild(t)))}}function uS(e,t){ya.m(e,t);var n=Ni;if(n&&e){var a=t&&typeof t.as=="string"?t.as:"script",s='link[rel="modulepreload"][as="'+yn(a)+'"][href="'+yn(e)+'"]',i=s;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=ki(e)}if(!wn.has(i)&&(e=Fe({rel:"modulepreload",href:e},t),wn.set(i,e),n.querySelector(s)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(n.querySelector(el(i)))return}a=n.createElement("link"),jt(a,"link",e),xt(a),n.head.appendChild(a)}}}function dS(e,t,n){ya.S(e,t,n);var a=Ni;if(a&&e){var s=ii(a).hoistableStyles,i=xi(e);t=t||"default";var r=s.get(i);if(!r){var l={loading:0,preload:null};if(r=a.querySelector(Zr(i)))l.loading=5;else{e=Fe({rel:"stylesheet",href:e,"data-precedence":t},n),(n=wn.get(i))&&vh(e,n);var o=r=a.createElement("link");xt(o),jt(o,"link",e),o._p=new Promise(function(u,h){o.onload=u,o.onerror=h}),o.addEventListener("load",function(){l.loading|=1}),o.addEventListener("error",function(){l.loading|=2}),l.loading|=4,Ql(r,t,a)}r={type:"stylesheet",instance:r,count:1,state:l},s.set(i,r)}}}function hS(e,t){ya.X(e,t);var n=Ni;if(n&&e){var a=ii(n).hoistableScripts,s=ki(e),i=a.get(s);i||(i=n.querySelector(el(s)),i||(e=Fe({src:e,async:!0},t),(t=wn.get(s))&&bh(e,t),i=n.createElement("script"),xt(i),jt(i,"link",e),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},a.set(s,i))}}function fS(e,t){ya.M(e,t);var n=Ni;if(n&&e){var a=ii(n).hoistableScripts,s=ki(e),i=a.get(s);i||(i=n.querySelector(el(s)),i||(e=Fe({src:e,async:!0,type:"module"},t),(t=wn.get(s))&&bh(e,t),i=n.createElement("script"),xt(i),jt(i,"link",e),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},a.set(s,i))}}function Xf(e,t,n,a){var s=(s=Ia.current)?Oo(s):null;if(!s)throw Error(N(446));switch(e){case"meta":case"title":return null;case"style":return typeof n.precedence=="string"&&typeof n.href=="string"?(t=xi(n.href),n=ii(s).hoistableStyles,a=n.get(t),a||(a={type:"style",instance:null,count:0,state:null},n.set(t,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(n.rel==="stylesheet"&&typeof n.href=="string"&&typeof n.precedence=="string"){e=xi(n.href);var i=ii(s).hoistableStyles,r=i.get(e);if(r||(s=s.ownerDocument||s,r={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(e,r),(i=s.querySelector(Zr(e)))&&!i._p&&(r.instance=i,r.state.loading=5),wn.has(e)||(n={rel:"preload",as:"style",href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},wn.set(e,n),i||pS(s,e,n,r.state))),t&&a===null)throw Error(N(528,""));return r}if(t&&a!==null)throw Error(N(529,""));return null;case"script":return t=n.async,n=n.src,typeof n=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=ki(n),n=ii(s).hoistableScripts,a=n.get(t),a||(a={type:"script",instance:null,count:0,state:null},n.set(t,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(N(444,e))}}function xi(e){return'href="'+yn(e)+'"'}function Zr(e){return'link[rel="stylesheet"]['+e+"]"}function Gy(e){return Fe({},e,{"data-precedence":e.precedence,precedence:null})}function pS(e,t,n,a){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?a.loading=1:(t=e.createElement("link"),a.preload=t,t.addEventListener("load",function(){return a.loading|=1}),t.addEventListener("error",function(){return a.loading|=2}),jt(t,"link",n),xt(t),e.head.appendChild(t))}function ki(e){return'[src="'+yn(e)+'"]'}function el(e){return"script[async]"+e}function Qf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case"style":var a=e.querySelector('style[data-href~="'+yn(n.href)+'"]');if(a)return t.instance=a,xt(a),a;var s=Fe({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return a=(e.ownerDocument||e).createElement("style"),xt(a),jt(a,"style",s),Ql(a,n.precedence,e),t.instance=a;case"stylesheet":s=xi(n.href);var i=e.querySelector(Zr(s));if(i)return t.state.loading|=4,t.instance=i,xt(i),i;a=Gy(n),(s=wn.get(s))&&vh(a,s),i=(e.ownerDocument||e).createElement("link"),xt(i);var r=i;return r._p=new Promise(function(l,o){r.onload=l,r.onerror=o}),jt(i,"link",a),t.state.loading|=4,Ql(i,n.precedence,e),t.instance=i;case"script":return i=ki(n.src),(s=e.querySelector(el(i)))?(t.instance=s,xt(s),s):(a=n,(s=wn.get(i))&&(a=Fe({},n),bh(a,s)),e=e.ownerDocument||e,s=e.createElement("script"),xt(s),jt(s,"link",a),e.head.appendChild(s),t.instance=s);case"void":return null;default:throw Error(N(443,t.type))}else t.type==="stylesheet"&&!(t.state.loading&4)&&(a=t.instance,t.state.loading|=4,Ql(a,n.precedence,e));return t.instance}function Ql(e,t,n){for(var a=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),s=a.length?a[a.length-1]:null,i=s,r=0;r<a.length;r++){var l=a[r];if(l.dataset.precedence===t)i=l;else if(i!==s)break}i?i.parentNode.insertBefore(e,i.nextSibling):(t=n.nodeType===9?n.head:n,t.insertBefore(e,t.firstChild))}function vh(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function bh(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var Wl=null;function Wf(e,t,n){if(Wl===null){var a=new Map,s=Wl=new Map;s.set(n,a)}else s=Wl,a=s.get(n),a||(a=new Map,s.set(n,a));if(a.has(e))return a;for(a.set(e,null),n=n.getElementsByTagName(e),s=0;s<n.length;s++){var i=n[s];if(!(i[Yr]||i[Ot]||e==="link"&&i.getAttribute("rel")==="stylesheet")&&i.namespaceURI!=="http://www.w3.org/2000/svg"){var r=i.getAttribute(t)||"";r=e+r;var l=a.get(r);l?l.push(i):a.set(r,[i])}}return a}function Zf(e,t,n){e=e.ownerDocument||e,e.head.insertBefore(n,t==="title"?e.querySelector("head > title"):null)}function mS(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;switch(t.rel){case"stylesheet":return e=t.disabled,typeof t.precedence=="string"&&e==null;default:return!0}case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function Ky(e){return!(e.type==="stylesheet"&&!(e.state.loading&3))}function gS(e,t,n,a){if(n.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&!(n.state.loading&4)){if(n.instance===null){var s=xi(a.href),i=t.querySelector(Zr(s));if(i){t=i._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Ro.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=i,xt(i);return}i=t.ownerDocument||t,a=Gy(a),(s=wn.get(s))&&vh(a,s),i=i.createElement("link"),xt(i);var r=i;r._p=new Promise(function(l,o){r.onload=l,r.onerror=o}),jt(i,"link",a),n.instance=i}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Ro.bind(e),t.addEventListener("load",n),t.addEventListener("error",n))}}var Qc=0;function yS(e,t){return e.stylesheets&&e.count===0&&Zl(e,e.stylesheets),0<e.count||0<e.imgCount?function(n){var a=setTimeout(function(){if(e.stylesheets&&Zl(e,e.stylesheets),e.unsuspend){var i=e.unsuspend;e.unsuspend=null,i()}},6e4+t);0<e.imgBytes&&Qc===0&&(Qc=62500*Q0());var s=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Zl(e,e.stylesheets),e.unsuspend)){var i=e.unsuspend;e.unsuspend=null,i()}},(e.imgBytes>Qc?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(a),clearTimeout(s)}}:null}function Ro(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Zl(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var No=null;function Zl(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,No=new Map,t.forEach(vS,e),No=null,Ro.call(e))}function vS(e,t){if(!(t.state.loading&4)){var n=No.get(e);if(n)var a=n.get(null);else{n=new Map,No.set(e,n);for(var s=e.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i<s.length;i++){var r=s[i];(r.nodeName==="LINK"||r.getAttribute("media")!=="not all")&&(n.set(r.dataset.precedence,r),a=r)}a&&n.set(null,a)}s=t.instance,r=s.getAttribute("data-precedence"),i=n.get(r)||a,i===a&&n.set(null,s),n.set(r,s),this.count++,a=Ro.bind(this),s.addEventListener("load",a),s.addEventListener("error",a),i?i.parentNode.insertBefore(s,i.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(s,e.firstChild)),t.state.loading|=4}}var Dr={$$typeof:ra,Provider:null,Consumer:null,_currentValue:fs,_currentValue2:fs,_threadCount:0};function bS(e,t,n,a,s,i,r,l,o){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=Sc(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Sc(0),this.hiddenUpdates=Sc(null),this.identifierPrefix=a,this.onUncaughtError=s,this.onCaughtError=i,this.onRecoverableError=r,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=o,this.incompleteTransitions=new Map}function Vy(e,t,n,a,s,i,r,l,o,u,h,f){return e=new bS(e,t,n,r,o,u,h,f,l),t=1,i===!0&&(t|=24),i=Zt(3,null,null,t),e.current=i,i.stateNode=e,t=Kd(),t.refCount++,e.pooledCache=t,t.refCount++,i.memoizedState={element:a,isDehydrated:n,cache:t},Fd(i),e}function Yy(e){return e?(e=ei,e):ei}function Fy(e,t,n,a,s,i){s=Yy(s),a.context===null?a.context=s:a.pendingContext=s,a=$a(t),a.payload={element:n},i=i===void 0?null:i,i!==null&&(a.callback=i),n=Pa(e,a,t),n!==null&&(Ft(n,e,t),ur(n,e,t))}function ep(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function Sh(e,t){ep(e,t),(e=e.alternate)&&ep(e,t)}function Jy(e){if(e.tag===13||e.tag===31){var t=As(e,67108864);t!==null&&Ft(t,e,67108864),Sh(e,67108864)}}function tp(e){if(e.tag===13||e.tag===31){var t=ln();t=kd(t);var n=As(e,t);n!==null&&Ft(n,e,t),Sh(e,t)}}var ko=!0;function SS(e,t,n,a){var s=ne.T;ne.T=null;var i=De.p;try{De.p=2,_h(e,t,n,a)}finally{De.p=i,ne.T=s}}function _S(e,t,n,a){var s=ne.T;ne.T=null;var i=De.p;try{De.p=8,_h(e,t,n,a)}finally{De.p=i,ne.T=s}}function _h(e,t,n,a){if(ko){var s=cd(a);if(s===null)Jc(e,t,a,jo,n),np(e,a);else if(xS(s,e,t,n,a))a.stopPropagation();else if(np(e,a),t&4&&-1<wS.indexOf(e)){for(;s!==null;){var i=Ai(s);if(i!==null)switch(i.tag){case 3:if(i=i.stateNode,i.current.memoizedState.isDehydrated){var r=os(i.pendingLanes);if(r!==0){var l=i;for(l.pendingLanes|=2,l.entangledLanes|=2;r;){var o=1<<31-rn(r);l.entanglements[1]|=o,r&=~o}Gn(i),!(je&6)&&(_o=an()+500,Wr(0))}}break;case 31:case 13:l=As(i,2),l!==null&&Ft(l,i,2),nc(),Sh(i,2)}if(i=cd(a),i===null&&Jc(e,t,a,jo,n),i===s)break;s=i}s!==null&&a.stopPropagation()}else Jc(e,t,a,null,n)}}function cd(e){return e=Ud(e),wh(e)}var jo=null;function wh(e){if(jo=null,e=Fs(e),e!==null){var t=qr(e);if(t===null)e=null;else{var n=t.tag;if(n===13){if(e=mm(t),e!==null)return e;e=null}else if(n===31){if(e=gm(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}}return jo=e,null}function Xy(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(lb()){case Sm:return 2;case _m:return 8;case ro:case ob:return 32;case wm:return 268435456;default:return 32}default:return 32}}var ud=!1,Ka=null,Va=null,Ya=null,Mr=new Map,Ur=new Map,Na=[],wS="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function np(e,t){switch(e){case"focusin":case"focusout":Ka=null;break;case"dragenter":case"dragleave":Va=null;break;case"mouseover":case"mouseout":Ya=null;break;case"pointerover":case"pointerout":Mr.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ur.delete(t.pointerId)}}function Vi(e,t,n,a,s,i){return e===null||e.nativeEvent!==i?(e={blockedOn:t,domEventName:n,eventSystemFlags:a,nativeEvent:i,targetContainers:[s]},t!==null&&(t=Ai(t),t!==null&&Jy(t)),e):(e.eventSystemFlags|=a,t=e.targetContainers,s!==null&&t.indexOf(s)===-1&&t.push(s),e)}function xS(e,t,n,a,s){switch(t){case"focusin":return Ka=Vi(Ka,e,t,n,a,s),!0;case"dragenter":return Va=Vi(Va,e,t,n,a,s),!0;case"mouseover":return Ya=Vi(Ya,e,t,n,a,s),!0;case"pointerover":var i=s.pointerId;return Mr.set(i,Vi(Mr.get(i)||null,e,t,n,a,s)),!0;case"gotpointercapture":return i=s.pointerId,Ur.set(i,Vi(Ur.get(i)||null,e,t,n,a,s)),!0}return!1}function Qy(e){var t=Fs(e.target);if(t!==null){var n=qr(t);if(n!==null){if(t=n.tag,t===13){if(t=mm(n),t!==null){e.blockedOn=t,Ih(e.priority,function(){tp(n)});return}}else if(t===31){if(t=gm(n),t!==null){e.blockedOn=t,Ih(e.priority,function(){tp(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function eo(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=cd(e.nativeEvent);if(n===null){n=e.nativeEvent;var a=new n.constructor(n.type,n);Ou=a,n.target.dispatchEvent(a),Ou=null}else return t=Ai(n),t!==null&&Jy(t),e.blockedOn=n,!1;t.shift()}return!0}function ap(e,t,n){eo(e)&&n.delete(t)}function TS(){ud=!1,Ka!==null&&eo(Ka)&&(Ka=null),Va!==null&&eo(Va)&&(Va=null),Ya!==null&&eo(Ya)&&(Ya=null),Mr.forEach(ap),Ur.forEach(ap)}function xl(e,t){e.blockedOn===t&&(e.blockedOn=null,ud||(ud=!0,gt.unstable_scheduleCallback(gt.unstable_NormalPriority,TS)))}var Tl=null;function sp(e){Tl!==e&&(Tl=e,gt.unstable_scheduleCallback(gt.unstable_NormalPriority,function(){Tl===e&&(Tl=null);for(var t=0;t<e.length;t+=3){var n=e[t],a=e[t+1],s=e[t+2];if(typeof a!="function"){if(wh(a||n)===null)continue;break}var i=Ai(n);i!==null&&(e.splice(t,3),t-=3,Gu(i,{pending:!0,data:s,method:n.method,action:a},a,s))}}))}function Ti(e){function t(o){return xl(o,e)}Ka!==null&&xl(Ka,e),Va!==null&&xl(Va,e),Ya!==null&&xl(Ya,e),Mr.forEach(t),Ur.forEach(t);for(var n=0;n<Na.length;n++){var a=Na[n];a.blockedOn===e&&(a.blockedOn=null)}for(;0<Na.length&&(n=Na[0],n.blockedOn===null);)Qy(n),n.blockedOn===null&&Na.shift();if(n=(e.ownerDocument||e).$$reactFormReplay,n!=null)for(a=0;a<n.length;a+=3){var s=n[a],i=n[a+1],r=s[Jt]||null;if(typeof i=="function")r||sp(n);else if(r){var l=null;if(i&&i.hasAttribute("formAction")){if(s=i,r=i[Jt]||null)l=r.formAction;else if(wh(s)!==null)continue}else l=r.action;typeof l=="function"?n[a+1]=l:(n.splice(a,3),a-=3),sp(n)}}}function Wy(){function e(i){i.canIntercept&&i.info==="react-transition"&&i.intercept({handler:function(){return new Promise(function(r){return s=r})},focusReset:"manual",scroll:"manual"})}function t(){s!==null&&(s(),s=null),a||setTimeout(n,20)}function n(){if(!a&&!navigation.transition){var i=navigation.currentEntry;i&&i.url!=null&&navigation.navigate(i.url,{state:i.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var a=!1,s=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",t),navigation.addEventListener("navigateerror",t),setTimeout(n,100),function(){a=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",t),navigation.removeEventListener("navigateerror",t),s!==null&&(s(),s=null)}}}function xh(e){this._internalRoot=e}ic.prototype.render=xh.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(N(409));var n=t.current,a=ln();Fy(n,a,e,t,null,null)};ic.prototype.unmount=xh.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;Fy(e.current,2,null,e,null,null),nc(),t[Ei]=null}};function ic(e){this._internalRoot=e}ic.prototype.unstable_scheduleHydration=function(e){if(e){var t=Cm();e={blockedOn:null,target:e,priority:t};for(var n=0;n<Na.length&&t!==0&&t<Na[n].priority;n++);Na.splice(n,0,e),n===0&&Qy(e)}};var ip=fm.version;if(ip!=="19.2.4")throw Error(N(527,ip,"19.2.4"));De.findDOMNode=function(e){var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(N(188)):(e=Object.keys(e).join(","),Error(N(268,e)));return e=eb(t),e=e!==null?ym(e):null,e=e===null?null:e.stateNode,e};var ES={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:ne,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var El=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!El.isDisabled&&El.supportsFiber)try{Gr=El.inject(ES),sn=El}catch{}}qo.createRoot=function(e,t){if(!pm(e))throw Error(N(299));var n=!1,a="",s=qg,i=Gg,r=Kg;return t!=null&&(t.unstable_strictMode===!0&&(n=!0),t.identifierPrefix!==void 0&&(a=t.identifierPrefix),t.onUncaughtError!==void 0&&(s=t.onUncaughtError),t.onCaughtError!==void 0&&(i=t.onCaughtError),t.onRecoverableError!==void 0&&(r=t.onRecoverableError)),t=Vy(e,1,!1,null,null,n,a,null,s,i,r,Wy),e[Ei]=t.current,yh(e),new xh(t)};qo.hydrateRoot=function(e,t,n){if(!pm(e))throw Error(N(299));var a=!1,s="",i=qg,r=Gg,l=Kg,o=null;return n!=null&&(n.unstable_strictMode===!0&&(a=!0),n.identifierPrefix!==void 0&&(s=n.identifierPrefix),n.onUncaughtError!==void 0&&(i=n.onUncaughtError),n.onCaughtError!==void 0&&(r=n.onCaughtError),n.onRecoverableError!==void 0&&(l=n.onRecoverableError),n.formState!==void 0&&(o=n.formState)),t=Vy(e,1,!0,t,n??null,a,s,o,i,r,l,Wy),t.context=Yy(null),n=t.current,a=ln(),a=kd(a),s=$a(a),s.callback=null,Pa(n,s,a),n=a,t.current.lanes=n,Vr(t,n),Gn(t),e[Ei]=t.current,yh(e),new ic(t)};qo.version="19.2.4";function Zy(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Zy)}catch(e){console.error(e)}}Zy(),um.exports=qo;var AS=um.exports;const ev="noter-deleted-task-ids";function CS(){try{const e=localStorage.getItem(ev);if(e){const t=JSON.parse(e);if(Array.isArray(t))return new Set(t)}}catch{}return new Set}function tv(e){try{localStorage.setItem(ev,JSON.stringify(Array.from(e)))}catch{}}function OS(e){try{fetch("/api/deleted-tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:Array.from(e)})}).catch(()=>{})}catch{}}const hi=CS();async function RS(){try{const e=await fetch("/api/deleted-tasks");if(e.ok){const t=await e.json();if(Array.isArray(t.ids)){for(const n of t.ids)hi.add(n);tv(hi)}}}catch{}}function Do(e){hi.add(e),tv(hi),OS(hi)}function NS(e){return hi.has(e)}const nv="noter-pinned-task-ids",av="noter-pinned-task-titles";function kS(){try{const e=localStorage.getItem(nv);if(e){const t=JSON.parse(e);if(Array.isArray(t))return new Set(t)}}catch{}return new Set}function jS(){try{const e=localStorage.getItem(av);if(e){const t=JSON.parse(e);if(t&&typeof t=="object")return new Map(Object.entries(t))}}catch{}return new Map}function tl(e){try{localStorage.setItem(nv,JSON.stringify(Array.from(e)))}catch{}}function nl(e){try{localStorage.setItem(av,JSON.stringify(Object.fromEntries(e)))}catch{}}function Th(e){try{fetch("/api/pinned-tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:Array.from(e)})}).catch(()=>{})}catch{}}const tt=kS(),en=jS();async function DS(){try{const e=await fetch("/api/pinned-tasks");if(e.ok){const t=await e.json();if(Array.isArray(t.ids)){const n=new Set(t.ids);for(const a of tt)n.has(a)||en.delete(a);tt.clear();for(const a of n)tt.add(a);tl(tt),nl(en)}}}catch{}}function rp(e){const t=new Set(e);for(const n of tt)t.has(n)||en.delete(n);tt.clear();for(const n of t)tt.add(n);tl(tt),nl(en)}function MS(e,t){tt.add(e),t&&en.set(e,t),tl(tt),nl(en),Th(tt)}function US(e){tt.delete(e),en.delete(e),tl(tt),nl(en),Th(tt)}function Wc(e){return tt.has(e)}function Zc(){return Array.from(tt)}function lp(e){const t=new Set(e.map(a=>a.id)),n=[];for(const a of tt)t.has(a)||n.push(a);if(n.length===0)return e;for(const a of n){const s=en.get(a);if(s){const i=e.find(r=>r.title&&r.title.trim().toLowerCase()===s.trim().toLowerCase());if(i){tt.delete(a),en.delete(a),tt.add(i.id),en.set(i.id,i.title);continue}}tt.delete(a),en.delete(a)}return tl(tt),nl(en),Th(tt),e}const Al=200;function LS(e){if(!e)return!1;const t=(e.whatIsHappening??"").trim(),n=(e.currentGoal??"").trim();return!(t.length===0&&n.length===0||t==="..."||t==="…"||t==="TBD"||t==="TODO"||n==="..."||n==="…"||n==="TBD"||n==="TODO")}class zS{constructor(t=WebSocket){this.ws=null,this.reconnectBaseMs=500,this.reconnectMaxMs=3e4,this.reconnectAttempts=0,this.status="disconnected",this.reconnectTimer=null,this.events=[],this.summary=null,this.suggestions=null,this.notes=null,this.sourceInfo={name:"none",status:"disconnected",lastEventAt:null},this.config={activeSource:"opencode",ollamaModel:"falcon-h1r:7b-q4_K_M"},this.hasReceivedFirstSync=!1,this.isGeneratingSuggestions=!1,this.suggestionsGenerationReason=null,this.statusListeners=new Set,this.eventListeners=new Set,this.summaryListeners=new Set,this.suggestionsListeners=new Set,this.notesListeners=new Set,this.sourceListeners=new Set,this.configListeners=new Set,this.syncListeners=new Set,this.suggestionsStatusListeners=new Set,this.sessionsUpdateListeners=new Set,this.wsImpl=t;const n=window.location.protocol==="https:"?"wss:":"ws:";this.url=`${n}//${window.location.host}/ws`,this.connect()}connect(){var t,n;((t=this.ws)==null?void 0:t.readyState)===WebSocket.CONNECTING||((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN||(this.setStatus("connecting"),this.ws=new this.wsImpl(this.url),this.ws.onopen=()=>{this.setStatus("connected"),this.reconnectAttempts=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer)},this.ws.onmessage=a=>{try{const s=JSON.parse(a.data);this.handleMessage(s)}catch(s){console.error("WebSocket parse error:",s)}},this.ws.onclose=()=>{this.setStatus("disconnected"),this.ws=null,this.scheduleReconnect()},this.ws.onerror=a=>{console.error("WebSocket error:",a)})}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer);const t=Math.min(this.reconnectMaxMs,this.reconnectBaseMs*Math.pow(2,this.reconnectAttempts));this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect()},t)}filterDeleted(t){return t.filter(n=>!NS(n.id))}handleMessage(t){if(t.type==="sync")this.events=t.payload.events.length>Al?t.payload.events.slice(-Al):t.payload.events,this.summary=t.payload.summary??null,this.suggestions=this.filterDeleted(t.payload.suggestions),this.hasReceivedFirstSync=!0,t.payload.pinnedTaskIds&&rp(t.payload.pinnedTaskIds),this.notes=t.payload.notes,t.payload.source&&(this.sourceInfo=t.payload.source,this.sourceListeners.forEach(n=>n(this.sourceInfo))),t.payload.config&&(this.config=t.payload.config,this.configListeners.forEach(n=>n(this.config))),this.notifyAll();else if(t.type==="event")this.events.push(t.payload),this.events.length>Al&&(this.events=this.events.slice(-Al)),this.eventListeners.forEach(n=>n(t.payload));else if(t.type==="summary")LS(t.payload)?(this.summary=t.payload,this.summaryListeners.forEach(n=>n(this.summary))):console.warn("[wsClient] Ignoring placeholder/empty summary event — keeping previous summary");else if(t.type==="suggestions-status")this.isGeneratingSuggestions=!!t.payload.generating,this.suggestionsGenerationReason=t.payload.generating?t.payload.reason??null:null,this.suggestionsStatusListeners.forEach(n=>n({generating:this.isGeneratingSuggestions,reason:this.suggestionsGenerationReason}));else if(t.type==="suggestions"){const n=this.filterDeleted(t.payload);this.suggestions=n,this.suggestionsListeners.forEach(a=>a(this.suggestions))}else t.type==="notes"?(this.notes=t.payload,this.notesListeners.forEach(n=>n(this.notes))):t.type==="pinned-ids"?rp(t.payload):t.type==="sessions-update"&&this.sessionsUpdateListeners.forEach(n=>n(t.payload))}notifyAll(){this.summaryListeners.forEach(t=>t(this.summary)),this.suggestionsListeners.forEach(t=>t(this.suggestions)),this.notesListeners.forEach(t=>t(this.notes)),this.syncListeners.forEach(t=>t())}removeSuggestion(t){if(!this.suggestions)return;const n=this.suggestions.length;this.suggestions=this.suggestions.filter(a=>a.id!==t),this.suggestions.length<n&&this.suggestionsListeners.forEach(a=>a(this.suggestions))}setStatus(t){this.status=t,this.statusListeners.forEach(n=>n(t))}getStatus(){return this.status}subscribe(t,n){return t==="status"?(this.statusListeners.add(n),n(this.status),()=>this.statusListeners.delete(n)):t==="event"?(this.eventListeners.add(n),()=>this.eventListeners.delete(n)):t==="summary"?(this.summaryListeners.add(n),n(this.summary),()=>this.summaryListeners.delete(n)):t==="suggestions"?(this.suggestionsListeners.add(n),n(this.suggestions),()=>this.suggestionsListeners.delete(n)):t==="notes"?(this.notesListeners.add(n),n(this.notes),()=>this.notesListeners.delete(n)):t==="source"?(this.sourceListeners.add(n),n(this.sourceInfo),()=>this.sourceListeners.delete(n)):t==="config"?(this.configListeners.add(n),n(this.config),()=>this.configListeners.delete(n)):t==="sync"?(this.syncListeners.add(n),()=>this.syncListeners.delete(n)):t==="suggestions-status"?(this.suggestionsStatusListeners.add(n),n({generating:this.isGeneratingSuggestions,reason:this.suggestionsGenerationReason}),()=>this.suggestionsStatusListeners.delete(n)):t==="sessions-update"?(this.sessionsUpdateListeners.add(n),()=>this.sessionsUpdateListeners.delete(n)):()=>{}}destroy(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.close(),this.ws=null)}}let to=null;function BS(){return to||(to=new zS),to}const me=new Proxy({},{get(e,t,n){const a=BS()[t];return typeof a=="function"?a.bind(to):a}});/*! @license DOMPurify 3.4.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.11/LICENSE */function op(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,a=Array(t);n<t;n++)a[n]=e[n];return a}function IS(e){if(Array.isArray(e))return e}function HS(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var a,s,i,r,l=[],o=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(o=(a=i.call(n)).done)&&(l.push(a.value),l.length!==t);o=!0);}catch(h){u=!0,s=h}finally{try{if(!o&&n.return!=null&&(r=n.return(),Object(r)!==r))return}finally{if(u)throw s}}return l}}function $S(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
34
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PS(e,t){return IS(e)||HS(e,t)||qS(e,t)||$S()}function qS(e,t){if(e){if(typeof e=="string")return op(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?op(e,t):void 0}}const sv=Object.entries,cp=Object.setPrototypeOf,GS=Object.isFrozen,KS=Object.getPrototypeOf,VS=Object.getOwnPropertyDescriptor;let kt=Object.freeze,Dt=Object.seal,Ps=Object.create,iv=typeof Reflect<"u"&&Reflect,dd=iv.apply,hd=iv.construct;kt||(kt=function(t){return t});Dt||(Dt=function(t){return t});dd||(dd=function(t,n){for(var a=arguments.length,s=new Array(a>2?a-2:0),i=2;i<a;i++)s[i-2]=arguments[i];return t.apply(n,s)});hd||(hd=function(t){for(var n=arguments.length,a=new Array(n>1?n-1:0),s=1;s<n;s++)a[s-1]=arguments[s];return new t(...a)});const Yi=ht(Array.prototype.forEach),YS=ht(Array.prototype.lastIndexOf),up=ht(Array.prototype.pop),Ds=ht(Array.prototype.push),FS=ht(Array.prototype.splice),ka=Array.isArray,nr=ht(String.prototype.toLowerCase),eu=ht(String.prototype.toString),dp=ht(String.prototype.match),Fi=ht(String.prototype.replace),hp=ht(String.prototype.indexOf),JS=ht(String.prototype.trim),XS=ht(Number.prototype.toString),QS=ht(Boolean.prototype.toString),fp=typeof BigInt>"u"?null:ht(BigInt.prototype.toString),pp=typeof Symbol>"u"?null:ht(Symbol.prototype.toString),_t=ht(Object.prototype.hasOwnProperty),Ji=ht(Object.prototype.toString),At=ht(RegExp.prototype.test),is=WS(TypeError);function ht(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,a=new Array(n>1?n-1:0),s=1;s<n;s++)a[s-1]=arguments[s];return dd(e,t,a)}}function WS(e){return function(){for(var t=arguments.length,n=new Array(t),a=0;a<t;a++)n[a]=arguments[a];return hd(e,n)}}function Ee(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nr;if(cp&&cp(e,null),!ka(t))return e;let a=t.length;for(;a--;){let s=t[a];if(typeof s=="string"){const i=n(s);i!==s&&(GS(t)||(t[a]=i),s=i)}e[s]=!0}return e}function ZS(e){for(let t=0;t<e.length;t++)_t(e,t)||(e[t]=null);return e}function Ht(e){const t=Ps(null);for(const a of sv(e)){var n=PS(a,2);const s=n[0],i=n[1];_t(e,s)&&(ka(i)?t[s]=ZS(i):i&&typeof i=="object"&&i.constructor===Object?t[s]=Ht(i):t[s]=i)}return t}function e_(e){switch(typeof e){case"string":return e;case"number":return XS(e);case"boolean":return QS(e);case"bigint":return fp?fp(e):"0";case"symbol":return pp?pp(e):"Symbol()";case"undefined":return Ji(e);case"function":case"object":{if(e===null)return Ji(e);const t=e,n=Ln(t,"toString");if(typeof n=="function"){const a=n(t);return typeof a=="string"?a:Ji(a)}return Ji(e)}default:return Ji(e)}}function Ln(e,t){for(;e!==null;){const a=VS(e,t);if(a){if(a.get)return ht(a.get);if(typeof a.value=="function")return ht(a.value)}e=KS(e)}function n(){return null}return n}function t_(e){try{return At(e,""),!0}catch{return!1}}const mp=kt(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),tu=kt(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),nu=kt(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),n_=kt(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),au=kt(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),a_=kt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),gp=kt(["#text"]),yp=kt(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),su=kt(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),vp=kt(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Cl=kt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),s_=Dt(/{{[\w\W]*|^[\w\W]*}}/g),i_=Dt(/<%[\w\W]*|^[\w\W]*%>/g),r_=Dt(/\${[\w\W]*/g),l_=Dt(/^data-[\-\w.\u00B7-\uFFFF]+$/),o_=Dt(/^aria-[\-\w]+$/),bp=Dt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),c_=Dt(/^(?:\w+script|data):/i),u_=Dt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),d_=Dt(/^html$/i),h_=Dt(/^[a-z][.\w]*(-[.\w]+)+$/i),Sp=Dt(/<[/\w!]/g),f_=Dt(/<[/\w]/g),p_=Dt(/<\/no(script|embed|frames)/i),m_=Dt(/\/>/i),Mn={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},g_=function(){return typeof window>"u"?null:window},y_=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let a=null;const s="data-tt-policy-suffix";n&&n.hasAttribute(s)&&(a=n.getAttribute(s));const i="dompurify"+(a?"#"+a:"");try{return t.createPolicy(i,{createHTML(r){return r},createScriptURL(r){return r}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},_p=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},xa=function(t,n,a,s){return _t(t,n)&&ka(t[n])?Ee(s.base?Ht(s.base):{},t[n],s.transform):a};function rv(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:g_();const t=$=>rv($);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==Mn.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const a=n,s=a.currentScript;e.DocumentFragment;const i=e.HTMLTemplateElement,r=e.Node,l=e.Element,o=e.NodeFilter,u=e.NamedNodeMap;u===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const h=e.DOMParser,f=e.trustedTypes,d=l.prototype,p=Ln(d,"cloneNode"),v=Ln(d,"remove"),_=Ln(d,"nextSibling"),x=Ln(d,"childNodes"),g=Ln(d,"parentNode"),m=Ln(d,"shadowRoot"),y=Ln(d,"attributes"),w=r&&r.prototype?Ln(r.prototype,"nodeType"):null,C=r&&r.prototype?Ln(r.prototype,"nodeName"):null;if(typeof i=="function"){const $=n.createElement("template");$.content&&$.content.ownerDocument&&(n=$.content.ownerDocument)}let R,O="",z,q=!1,K=0;const ve=function(){if(K>0)throw is('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},Ae=function(S){ve(),K++;try{return R.createHTML(S)}finally{K--}},ee=function(S){ve(),K++;try{return R.createScriptURL(S)}finally{K--}},yt=function(){return q||(z=y_(f,s),q=!0),z},$e=n,L=$e.implementation,U=$e.createNodeIterator,k=$e.createDocumentFragment,se=$e.getElementsByTagName,j=a.importNode;let V=_p();t.isSupported=typeof sv=="function"&&typeof g=="function"&&L&&L.createHTMLDocument!==void 0;const Re=s_,ft=i_,nt=r_,Mt=l_,xn=o_,va=c_,Tn=u_,En=h_;let Et=bp,Me=null;const Lt=Ee({},[...mp,...tu,...nu,...au,...gp]);let Ne=null;const vt=Ee({},[...yp,...su,...vp,...Cl]);let ke=Object.seal(Ps(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),B=null,D=null;const I=Object.seal(Ps(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let J=!0,ae=!0,ce=!1,Oe=!0,xe=!1,te=!0,Q=!1,re=!1,E=null,M=null,G=!1,W=!1,ie=!1,de=!1,ue=!0,Te=!1;const he="user-content-";let pe=!0,Ie=!1,it={},be=null;const es=Ee({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Rs=null;const ba=Ee({},["audio","video","img","source","image","track"]);let Qe=null;const Pt=Ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Xe="http://www.w3.org/1998/Math/MathML",zt="http://www.w3.org/2000/svg",un="http://www.w3.org/1999/xhtml";let Sa=un,Mi=!1,Ui=null;const rl=Ee({},[Xe,zt,un],eu),Li=kt(["mi","mo","mn","ms","mtext"]);let zi=Ee({},Li);const ll=kt(["annotation-xml"]);let Bi=Ee({},ll);const hc=Ee({},["title","style","font","a","script"]);let _a=null;const A=["application/xhtml+xml","text/html"],X="text/html";let le=null,_e=null;const Ke=n.createElement("form"),ts=function(S){return S instanceof RegExp||S instanceof Function},Dn=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(_e&&_e===S)return;(!S||typeof S!="object")&&(S={}),S=Ht(S),_a=A.indexOf(S.PARSER_MEDIA_TYPE)===-1?X:S.PARSER_MEDIA_TYPE,le=_a==="application/xhtml+xml"?eu:nr,Me=xa(S,"ALLOWED_TAGS",Lt,{transform:le}),Ne=xa(S,"ALLOWED_ATTR",vt,{transform:le}),Ui=xa(S,"ALLOWED_NAMESPACES",rl,{transform:eu}),Qe=xa(S,"ADD_URI_SAFE_ATTR",Pt,{transform:le,base:Pt}),Rs=xa(S,"ADD_DATA_URI_TAGS",ba,{transform:le,base:ba}),be=xa(S,"FORBID_CONTENTS",es,{transform:le}),B=xa(S,"FORBID_TAGS",Ht({}),{transform:le}),D=xa(S,"FORBID_ATTR",Ht({}),{transform:le}),it=_t(S,"USE_PROFILES")?S.USE_PROFILES&&typeof S.USE_PROFILES=="object"?Ht(S.USE_PROFILES):S.USE_PROFILES:!1,J=S.ALLOW_ARIA_ATTR!==!1,ae=S.ALLOW_DATA_ATTR!==!1,ce=S.ALLOW_UNKNOWN_PROTOCOLS||!1,Oe=S.ALLOW_SELF_CLOSE_IN_ATTR!==!1,xe=S.SAFE_FOR_TEMPLATES||!1,te=S.SAFE_FOR_XML!==!1,Q=S.WHOLE_DOCUMENT||!1,W=S.RETURN_DOM||!1,ie=S.RETURN_DOM_FRAGMENT||!1,de=S.RETURN_TRUSTED_TYPE||!1,G=S.FORCE_BODY||!1,ue=S.SANITIZE_DOM!==!1,Te=S.SANITIZE_NAMED_PROPS||!1,pe=S.KEEP_CONTENT!==!1,Ie=S.IN_PLACE||!1,Et=t_(S.ALLOWED_URI_REGEXP)?S.ALLOWED_URI_REGEXP:bp,Sa=typeof S.NAMESPACE=="string"?S.NAMESPACE:un,zi=_t(S,"MATHML_TEXT_INTEGRATION_POINTS")&&S.MATHML_TEXT_INTEGRATION_POINTS&&typeof S.MATHML_TEXT_INTEGRATION_POINTS=="object"?Ht(S.MATHML_TEXT_INTEGRATION_POINTS):Ee({},Li),Bi=_t(S,"HTML_INTEGRATION_POINTS")&&S.HTML_INTEGRATION_POINTS&&typeof S.HTML_INTEGRATION_POINTS=="object"?Ht(S.HTML_INTEGRATION_POINTS):Ee({},ll);const T=_t(S,"CUSTOM_ELEMENT_HANDLING")&&S.CUSTOM_ELEMENT_HANDLING&&typeof S.CUSTOM_ELEMENT_HANDLING=="object"?Ht(S.CUSTOM_ELEMENT_HANDLING):Ps(null);if(ke=Ps(null),_t(T,"tagNameCheck")&&ts(T.tagNameCheck)&&(ke.tagNameCheck=T.tagNameCheck),_t(T,"attributeNameCheck")&&ts(T.attributeNameCheck)&&(ke.attributeNameCheck=T.attributeNameCheck),_t(T,"allowCustomizedBuiltInElements")&&typeof T.allowCustomizedBuiltInElements=="boolean"&&(ke.allowCustomizedBuiltInElements=T.allowCustomizedBuiltInElements),Dt(ke),xe&&(ae=!1),ie&&(W=!0),it&&(Me=Ee({},gp),Ne=Ps(null),it.html===!0&&(Ee(Me,mp),Ee(Ne,yp)),it.svg===!0&&(Ee(Me,tu),Ee(Ne,su),Ee(Ne,Cl)),it.svgFilters===!0&&(Ee(Me,nu),Ee(Ne,su),Ee(Ne,Cl)),it.mathMl===!0&&(Ee(Me,au),Ee(Ne,vp),Ee(Ne,Cl))),I.tagCheck=null,I.attributeCheck=null,_t(S,"ADD_TAGS")&&(typeof S.ADD_TAGS=="function"?I.tagCheck=S.ADD_TAGS:ka(S.ADD_TAGS)&&(Me===Lt&&(Me=Ht(Me)),Ee(Me,S.ADD_TAGS,le))),_t(S,"ADD_ATTR")&&(typeof S.ADD_ATTR=="function"?I.attributeCheck=S.ADD_ATTR:ka(S.ADD_ATTR)&&(Ne===vt&&(Ne=Ht(Ne)),Ee(Ne,S.ADD_ATTR,le))),_t(S,"ADD_URI_SAFE_ATTR")&&ka(S.ADD_URI_SAFE_ATTR)&&Ee(Qe,S.ADD_URI_SAFE_ATTR,le),_t(S,"FORBID_CONTENTS")&&ka(S.FORBID_CONTENTS)&&(be===es&&(be=Ht(be)),Ee(be,S.FORBID_CONTENTS,le)),_t(S,"ADD_FORBID_CONTENTS")&&ka(S.ADD_FORBID_CONTENTS)&&(be===es&&(be=Ht(be)),Ee(be,S.ADD_FORBID_CONTENTS,le)),pe&&(Me["#text"]=!0),Q&&Ee(Me,["html","head","body"]),Me.table&&(Ee(Me,["tbody"]),delete B.tbody),S.TRUSTED_TYPES_POLICY){if(typeof S.TRUSTED_TYPES_POLICY.createHTML!="function")throw is('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof S.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw is('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const H=R;R=S.TRUSTED_TYPES_POLICY;try{O=Ae("")}catch(F){throw R=H,F}}else S.TRUSTED_TYPES_POLICY===null?(R=void 0,O=""):(R===void 0&&(R=yt()),R&&typeof O=="string"&&(O=Ae("")));kt&&kt(S),_e=S},ns=Ee({},[...tu,...nu,...n_]),Vn=Ee({},[...au,...a_]),Bv=function(S,T,H){return T.namespaceURI===un?S==="svg":T.namespaceURI===Xe?S==="svg"&&(H==="annotation-xml"||zi[H]):!!ns[S]},Iv=function(S,T,H){return T.namespaceURI===un?S==="math":T.namespaceURI===zt?S==="math"&&Bi[H]:!!Vn[S]},Hv=function(S,T,H){return T.namespaceURI===zt&&!Bi[H]||T.namespaceURI===Xe&&!zi[H]?!1:!Vn[S]&&(hc[S]||!ns[S])},$v=function(S){let T=g(S);(!T||!T.tagName)&&(T={namespaceURI:Sa,tagName:"template"});const H=nr(S.tagName),F=nr(T.tagName);return Ui[S.namespaceURI]?S.namespaceURI===zt?Bv(H,T,F):S.namespaceURI===Xe?Iv(H,T,F):S.namespaceURI===un?Hv(H,T,F):!!(_a==="application/xhtml+xml"&&Ui[S.namespaceURI]):!1},wa=function(S){Ds(t.removed,{element:S});try{g(S).removeChild(S)}catch{if(v(S),!g(S))throw is("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Oh=function(S){const T=x(S);if(T){const F=[];Yi(T,fe=>{Ds(F,fe)}),Yi(F,fe=>{try{v(fe)}catch{}})}const H=y(S);if(H)for(let F=H.length-1;F>=0;--F){const fe=H[F],Ce=fe&&fe.name;if(typeof Ce=="string")try{S.removeAttribute(Ce)}catch{}}},as=function(S,T){try{Ds(t.removed,{attribute:T.getAttributeNode(S),from:T})}catch{Ds(t.removed,{attribute:null,from:T})}if(T.removeAttribute(S),S==="is")if(W||ie)try{wa(T)}catch{}else try{T.setAttribute(S,"")}catch{}},Pv=function(S){const T=y(S);if(T)for(let H=T.length-1;H>=0;--H){const F=T[H],fe=F&&F.name;if(!(typeof fe!="string"||Ne[le(fe)]))try{S.removeAttribute(fe)}catch{}}},qv=function(S){const T=[S];for(;T.length>0;){const H=T.pop();(w?w(H):H.nodeType)===Mn.element&&Pv(H);const fe=x(H);if(fe)for(let Ce=fe.length-1;Ce>=0;--Ce)T.push(fe[Ce])}},Rh=function(S){let T=null,H=null;if(G)S="<remove></remove>"+S;else{const Ce=dp(S,/^[\r\n\t ]+/);H=Ce&&Ce[0]}_a==="application/xhtml+xml"&&Sa===un&&(S='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+S+"</body></html>");const F=R?Ae(S):S;if(Sa===un)try{T=new h().parseFromString(F,_a)}catch{}if(!T||!T.documentElement){T=L.createDocument(Sa,"template",null);try{T.documentElement.innerHTML=Mi?O:F}catch{}}const fe=T.body||T.documentElement;return S&&H&&fe.insertBefore(n.createTextNode(H),fe.childNodes[0]||null),Sa===un?se.call(T,Q?"html":"body")[0]:Q?T.documentElement:fe},Nh=function(S){return U.call(S.ownerDocument||S,S,o.SHOW_ELEMENT|o.SHOW_COMMENT|o.SHOW_TEXT|o.SHOW_PROCESSING_INSTRUCTION|o.SHOW_CDATA_SECTION,null)},ol=function(S){return S=Fi(S,Re," "),S=Fi(S,ft," "),S=Fi(S,nt," "),S},fc=function(S){var T;S.normalize();const H=U.call(S.ownerDocument||S,S,o.SHOW_TEXT|o.SHOW_COMMENT|o.SHOW_CDATA_SECTION|o.SHOW_PROCESSING_INSTRUCTION,null);let F=H.nextNode();for(;F;)F.data=ol(F.data),F=H.nextNode();const fe=(T=S.querySelectorAll)===null||T===void 0?void 0:T.call(S,"template");fe&&Yi(fe,Ce=>{Ns(Ce.content)&&fc(Ce.content)})},cl=function(S){const T=C?C(S):null;return typeof T!="string"||le(T)!=="form"?!1:typeof S.nodeName!="string"||typeof S.textContent!="string"||typeof S.removeChild!="function"||S.attributes!==y(S)||typeof S.removeAttribute!="function"||typeof S.setAttribute!="function"||typeof S.namespaceURI!="string"||typeof S.insertBefore!="function"||typeof S.hasChildNodes!="function"||S.nodeType!==w(S)||S.childNodes!==x(S)},Ns=function(S){if(!w||typeof S!="object"||S===null)return!1;try{return w(S)===Mn.documentFragment}catch{return!1}},Ii=function(S){if(!w||typeof S!="object"||S===null)return!1;try{return typeof w(S)=="number"}catch{return!1}};function Yn($,S,T){$.length!==0&&Yi($,H=>{H.call(t,S,T,_e)})}const Gv=function(S,T){return!!(te&&S.hasChildNodes()&&!Ii(S.firstElementChild)&&At(Sp,S.textContent)&&At(Sp,S.innerHTML)||te&&S.namespaceURI===un&&T==="style"&&Ii(S.firstElementChild)||S.nodeType===Mn.processingInstruction||te&&S.nodeType===Mn.comment&&At(f_,S.data))},Kv=function(S,T){if(!B[T]&&Dh(T)&&(ke.tagNameCheck instanceof RegExp&&At(ke.tagNameCheck,T)||ke.tagNameCheck instanceof Function&&ke.tagNameCheck(T)))return!1;if(pe&&!be[T]){const H=g(S),F=x(S);if(F&&H){const fe=F.length;for(let Ce=fe-1;Ce>=0;--Ce){const bt=Ie?F[Ce]:p(F[Ce],!0);H.insertBefore(bt,_(S))}}}return wa(S),!0},kh=function(S){if(Yn(V.beforeSanitizeElements,S,null),cl(S))return wa(S),!0;const T=le(C?C(S):S.nodeName);if(Yn(V.uponSanitizeElement,S,{tagName:T,allowedTags:Me}),Gv(S,T))return wa(S),!0;if(B[T]||!(I.tagCheck instanceof Function&&I.tagCheck(T))&&!Me[T])return Kv(S,T);if((w?w(S):S.nodeType)===Mn.element&&!$v(S)||(T==="noscript"||T==="noembed"||T==="noframes")&&At(p_,S.innerHTML))return wa(S),!0;if(xe&&S.nodeType===Mn.text){const F=ol(S.textContent);S.textContent!==F&&(Ds(t.removed,{element:S.cloneNode()}),S.textContent=F)}return Yn(V.afterSanitizeElements,S,null),!1},jh=function(S,T,H){if(D[T]||ue&&(T==="id"||T==="name")&&(H in n||H in Ke))return!1;const F=Ne[T]||I.attributeCheck instanceof Function&&I.attributeCheck(T,S);if(!(ae&&At(Mt,T))){if(!(J&&At(xn,T))){if(F){if(!Qe[T]){if(!At(Et,Fi(H,Tn,""))){if(!((T==="src"||T==="xlink:href"||T==="href")&&S!=="script"&&hp(H,"data:")===0&&Rs[S])){if(!(ce&&!At(va,Fi(H,Tn,"")))){if(H)return!1}}}}}else if(!(Dh(S)&&(ke.tagNameCheck instanceof RegExp&&At(ke.tagNameCheck,S)||ke.tagNameCheck instanceof Function&&ke.tagNameCheck(S))&&(ke.attributeNameCheck instanceof RegExp&&At(ke.attributeNameCheck,T)||ke.attributeNameCheck instanceof Function&&ke.attributeNameCheck(T,S))||T==="is"&&ke.allowCustomizedBuiltInElements&&(ke.tagNameCheck instanceof RegExp&&At(ke.tagNameCheck,H)||ke.tagNameCheck instanceof Function&&ke.tagNameCheck(H))))return!1}}return!0},Vv=Ee({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Dh=function(S){return!Vv[nr(S)]&&At(En,S)},Yv=function(S,T,H,F){if(R&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!H)switch(f.getAttributeType(S,T)){case"TrustedHTML":return Ae(F);case"TrustedScriptURL":return ee(F)}return F},Fv=function(S,T,H,F){try{H?S.setAttributeNS(H,T,F):S.setAttribute(T,F),cl(S)?wa(S):up(t.removed)}catch{as(T,S)}},Mh=function(S){Yn(V.beforeSanitizeAttributes,S,null);const T=S.attributes;if(!T||cl(S))return;const H={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ne,forceKeepAttr:void 0};let F=T.length;const fe=le(S.nodeName);for(;F--;){const Ce=T[F],bt=Ce.name,rt=Ce.namespaceURI,dn=Ce.value,An=le(bt),mc=dn;let Bt=bt==="value"?mc:JS(mc);if(H.attrName=An,H.attrValue=Bt,H.keepAttr=!0,H.forceKeepAttr=void 0,Yn(V.uponSanitizeAttribute,S,H),Bt=H.attrValue,Te&&(An==="id"||An==="name")&&hp(Bt,he)!==0&&(as(bt,S),Bt=he+Bt),te&&At(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Bt)){as(bt,S);continue}if(An==="attributename"&&dp(Bt,"href")){as(bt,S);continue}if(!H.forceKeepAttr){if(!H.keepAttr){as(bt,S);continue}if(!Oe&&At(m_,Bt)){as(bt,S);continue}if(xe&&(Bt=ol(Bt)),!jh(fe,An,Bt)){as(bt,S);continue}Bt=Yv(fe,An,rt,Bt),Bt!==mc&&Fv(S,bt,rt,Bt)}}Yn(V.afterSanitizeAttributes,S,null)},ul=function(S){let T=null;const H=Nh(S);for(Yn(V.beforeSanitizeShadowDOM,S,null);T=H.nextNode();)if(Yn(V.uponSanitizeShadowNode,T,null),kh(T),Mh(T),Ns(T.content)&&ul(T.content),(w?w(T):T.nodeType)===Mn.element){const fe=m(T);Ns(fe)&&(pc(fe),ul(fe))}Yn(V.afterSanitizeShadowDOM,S,null)},pc=function(S){const T=[{node:S,shadow:null}];for(;T.length>0;){const H=T.pop();if(H.shadow){ul(H.shadow);continue}const F=H.node,Ce=(w?w(F):F.nodeType)===Mn.element,bt=x(F);if(bt)for(let rt=bt.length-1;rt>=0;--rt)T.push({node:bt[rt],shadow:null});if(Ce){const rt=C?C(F):null;if(typeof rt=="string"&&le(rt)==="template"){const dn=F.content;Ns(dn)&&T.push({node:dn,shadow:null})}}if(Ce){const rt=m(F);Ns(rt)&&T.push({node:null,shadow:rt},{node:rt,shadow:null})}}};return t.sanitize=function($){let S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},T=null,H=null,F=null,fe=null;if(Mi=!$,Mi&&($="<!-->"),typeof $!="string"&&!Ii($)&&($=e_($),typeof $!="string"))throw is("dirty is not a string, aborting");if(!t.isSupported)return $;re?(Me=E,Ne=M):Dn(S),(V.uponSanitizeElement.length>0||V.uponSanitizeAttribute.length>0)&&(Me=Ht(Me)),V.uponSanitizeAttribute.length>0&&(Ne=Ht(Ne)),t.removed=[];const Ce=Ie&&typeof $!="string"&&Ii($);if(Ce){const dn=C?C($):$.nodeName;if(typeof dn=="string"){const An=le(dn);if(!Me[An]||B[An])throw is("root node is forbidden and cannot be sanitized in-place")}if(cl($))throw is("root node is clobbered and cannot be sanitized in-place");try{pc($)}catch(An){throw Oh($),An}}else if(Ii($))T=Rh("<!---->"),H=T.ownerDocument.importNode($,!0),H.nodeType===Mn.element&&H.nodeName==="BODY"||H.nodeName==="HTML"?T=H:T.appendChild(H),pc(H);else{if(!W&&!xe&&!Q&&$.indexOf("<")===-1)return R&&de?Ae($):$;if(T=Rh($),!T)return W?null:de?O:""}T&&G&&wa(T.firstChild);const bt=Nh(Ce?$:T);try{for(;F=bt.nextNode();)kh(F),Mh(F),Ns(F.content)&&ul(F.content)}catch(dn){throw Ce&&Oh($),dn}if(Ce)return Yi(t.removed,dn=>{dn.element&&qv(dn.element)}),xe&&fc($),$;if(W){if(xe&&fc(T),ie)for(fe=k.call(T.ownerDocument);T.firstChild;)fe.appendChild(T.firstChild);else fe=T;return(Ne.shadowroot||Ne.shadowrootmode)&&(fe=j.call(a,fe,!0)),fe}let rt=Q?T.outerHTML:T.innerHTML;return Q&&Me["!doctype"]&&T.ownerDocument&&T.ownerDocument.doctype&&T.ownerDocument.doctype.name&&At(d_,T.ownerDocument.doctype.name)&&(rt="<!DOCTYPE "+T.ownerDocument.doctype.name+`>
35
+ `+rt),xe&&(rt=ol(rt)),R&&de?Ae(rt):rt},t.setConfig=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Dn($),re=!0,E=Me,M=Ne},t.clearConfig=function(){_e=null,re=!1,E=null,M=null,R=z,O=""},t.isValidAttribute=function($,S,T){_e||Dn({});const H=le($),F=le(S);return jh(H,F,T)},t.addHook=function($,S){typeof S=="function"&&_t(V,$)&&Ds(V[$],S)},t.removeHook=function($,S){if(_t(V,$)){if(S!==void 0){const T=YS(V[$],S);return T===-1?void 0:FS(V[$],T,1)[0]}return up(V[$])}},t.removeHooks=function($){_t(V,$)&&(V[$]=[])},t.removeAllHooks=function(){V=_p()},t}var v_=rv();const wp=[{key:"h1",label:"Heading 1",prefix:"# ",description:"Large heading"},{key:"h2",label:"Heading 2",prefix:"## ",description:"Medium heading"},{key:"h3",label:"Heading 3",prefix:"### ",description:"Small heading"},{key:"ul",label:"Bullet List",prefix:"- ",aliases:["bullet"],description:"Bulleted list item"},{key:"ol",label:"Numbered List",prefix:"1. ",aliases:["numbered"],description:"Numbered list item"},{key:"todo",label:"Checklist",prefix:"- [ ] ",aliases:["check"],description:"Checklist item"},{key:"quote",label:"Quote",prefix:"> ",description:"Quote block"},{key:"code",label:"Code Block",prefix:"```\n",description:"Code block"},{key:"divider",label:"Divider",prefix:`---
36
+ `,aliases:["hr"],description:"Horizontal divider"},{key:"callout",label:"Callout",prefix:"> **!** ",description:"Highlighted note"}];function b_(e){const t=e.toLowerCase().replace(/^\//,"");if(!t)return wp.map(a=>({...a,matchLabel:a.label}));const n=[];for(const a of wp){if(a.key.startsWith(t)){n.push({...a,matchLabel:a.label});continue}if(a.aliases){for(const s of a.aliases)if(s.startsWith(t)){n.push({...a,matchLabel:a.label});break}}}return n}const fd=new Set(["h1","h2","h3","ul","ol","todo","quote","callout","code","divider"]);function S_(e){const t=window.getSelection();if(!t||!t.isCollapsed||t.rangeCount===0)return!1;const n=t.getRangeAt(0),a=document.createRange();return a.setStart(e,0),a.setEnd(n.startContainer,n.startOffset),a.toString()===""}let __=0;function qe(){return`b-${++__}`}function Ol(e){const t=e.split(`
37
+ `),n=[];let a=!1,s=[];for(let i=0;i<t.length;i++){const r=t[i];if(r.startsWith("```")){a?(n.push({id:qe(),type:"code",text:s.join(`
38
+ `),codeFence:!0}),s=[],a=!1):a=!0;continue}if(a){s.push(r);continue}if(r.trim()===""){n.push({id:qe(),type:"blank",text:""});continue}if(/^---+$/.test(r.trim())){n.push({id:qe(),type:"divider",text:""});continue}const l=r.match(/^# (.+)$/);if(l){n.push({id:qe(),type:"h1",text:l[1]});continue}const o=r.match(/^## (.+)$/);if(o){n.push({id:qe(),type:"h2",text:o[1]});continue}const u=r.match(/^### (.+)$/);if(u){n.push({id:qe(),type:"h3",text:u[1]});continue}const h=r.match(/^- \[([ xX])\] (.+)$/);if(h){n.push({id:qe(),type:"todo",text:h[2],checked:h[1]!==" "});continue}const f=r.match(/^[-*] (.+)$/);if(f){n.push({id:qe(),type:"ul",text:f[1]});continue}const d=r.match(/^\d+\. (.+)$/);if(d){n.push({id:qe(),type:"ol",text:d[1]});continue}const p=r.match(/^> (.+)$/);if(p){const v=p[1];v.startsWith("**!** ")||v.startsWith("⚠ ")?n.push({id:qe(),type:"callout",text:v.replace(/^\*\*!\*\*\s*/,"").replace(/^⚠\s*/,"")}):n.push({id:qe(),type:"quote",text:v});continue}n.push({id:qe(),type:"paragraph",text:r})}return a&&s.length>0&&n.push({id:qe(),type:"code",text:s.join(`
39
+ `),codeFence:!1}),n}function Un(e){let t=0;return e.map(n=>{switch(n.type){case"h1":return t=0,`# ${n.text}`;case"h2":return t=0,`## ${n.text}`;case"h3":return t=0,`### ${n.text}`;case"ul":return t=0,`- ${n.text}`;case"ol":return t++,`${t}. ${n.text}`;case"todo":return t=0,`- [${n.checked?"x":" "}] ${n.text}`;case"quote":return t=0,`> ${n.text}`;case"callout":return t=0,`> **!** ${n.text}`;case"code":return t=0,n.codeFence?`\`\`\`
40
+ ${n.text}
41
+ \`\`\``:`\`\`\`
42
+ ${n.text}`;case"divider":return t=0,"---";case"blank":return t=0,"";case"paragraph":return t=0,n.text;default:return t=0,""}}).join(`
43
+ `)}function w_(e){let t=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");const n=[];return t=t.replace(/`([^`]+)`/g,(a,s)=>(n.push(`<code>${s}</code>`),`\0CODE${n.length-1}\0`)),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*([^*]+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/\x00CODE(\d+)\x00/g,(a,s)=>n[parseInt(s)]),t}function x_({block:e,olNumber:t,onChange:n,onEnter:a,onBackspace:s,onToggleCheck:i}){const r=b.useRef(null);b.useLayoutEffect(()=>{const d=r.current;if(d){if(e.htmlContent){const p=v_.sanitize(e.htmlContent);d.innerHTML!==p&&(d.innerHTML=p)}else d.textContent!==e.text&&(d.textContent=e.text);d.hasChildNodes()||d.appendChild(document.createElement("br"))}},[e.id]);const l=()=>{const d=r.current;if(!d)return;const p=d.innerText??"";n(e.id,p),!p&&!d.querySelector("br")&&d.appendChild(document.createElement("br"))},o=d=>{var p,v,_;if(d.key==="Enter"){if(e.type==="code"){if(!d.shiftKey)return}else if(d.shiftKey)return;d.preventDefault();const x=window.getSelection();let g="";if(x&&x.rangeCount>0&&r.current){const m=x.getRangeAt(0);if(r.current.contains(m.endContainer)){const y=document.createRange();y.setStart(m.endContainer,m.endOffset),y.setEnd(r.current,r.current.childNodes.length),g=y.toString(),y.deleteContents()}}a(e.id,g);return}if(d.key==="Backspace"){const x=e.text,g=window.getSelection();if(g&&!g.isCollapsed&&g.rangeCount>0){const w=g.getRangeAt(0),C=((p=r.current)==null?void 0:p.closest("[data-block-id]"))??null,R=w.startContainer instanceof HTMLElement?w.startContainer.closest("[data-block-id]"):(v=w.startContainer.parentElement)==null?void 0:v.closest("[data-block-id]"),O=w.endContainer instanceof HTMLElement?w.endContainer.closest("[data-block-id]"):(_=w.endContainer.parentElement)==null?void 0:_.closest("[data-block-id]");if(R===C&&O===C)return;d.preventDefault();return}const m=S_(r.current),y=fd.has(e.type);if(x===""&&y){d.preventDefault(),s(e.id);return}if(x===""){d.preventDefault(),s(e.id);return}if(m&&y){d.preventDefault(),s(e.id);return}if(m){d.preventDefault(),s(e.id);return}}d.key};if(e.type==="divider")return c.jsx("hr",{className:"note-divider","data-block-id":e.id,tabIndex:0,onKeyDown:d=>{(d.key==="Backspace"||d.key==="Delete")&&(d.preventDefault(),s(e.id))}});if(e.type==="blank")return c.jsx("div",{className:"note-blank","data-block-id":e.id});if(e.type==="code")return c.jsx("pre",{className:"note-code","data-block-id":e.id,children:c.jsx("code",{ref:r,contentEditable:!0,suppressContentEditableWarning:!0,onInput:l,onKeyDown:o,style:{display:"block",outline:"none",whiteSpace:"pre-wrap"}})});const h={h1:"note-h1",h2:"note-h2",h3:"note-h3",paragraph:"note-p",ul:"note-ul",ol:"note-ol",todo:"note-todo",quote:"note-quote",callout:"note-callout"}[e.type]||"note-p",f=()=>e.type==="ul"?c.jsx("span",{className:"note-bullet",children:"•"}):e.type==="ol"?c.jsxs("span",{className:"note-ol-marker",children:[t??1,"."]}):e.type==="todo"?c.jsx("span",{className:`note-checkbox${e.checked?" checked":""}`,onClick:d=>{d.stopPropagation(),i(e.id)},role:"checkbox","aria-checked":e.checked,children:e.checked?"✓":"○"}):e.type==="callout"?c.jsx("span",{className:"note-callout-marker",children:"⚠"}):null;return c.jsxs("div",{className:h,"data-block-id":e.id,children:[f(),c.jsx("div",{ref:r,contentEditable:!0,suppressContentEditableWarning:!0,onInput:l,onKeyDown:o,style:{flex:1,outline:"none",minWidth:0}})]})}function T_({commands:e,selectedIndex:t,onSelect:n}){return e.length===0?null:c.jsx("div",{className:"slash-menu",role:"listbox","aria-label":"Slash commands",children:e.map((a,s)=>c.jsxs("div",{role:"option","aria-selected":s===t,className:`slash-menu-item${s===t?" selected":""}`,onMouseDown:i=>{i.preventDefault(),n(a)},children:[c.jsxs("span",{className:"slash-menu-key",children:["/",a.key]}),c.jsx("span",{className:"slash-menu-label",children:a.matchLabel}),c.jsx("span",{className:"slash-menu-desc",children:a.description})]},a.key))})}function E_({refinedContent:e,onAccept:t,onReject:n}){return c.jsxs("div",{className:"refine-review-overlay",children:[c.jsxs("div",{className:"refine-review-header",children:[c.jsx("span",{className:"refine-review-title",children:"REFINED NOTES"}),c.jsxs("div",{className:"refine-review-actions",children:[c.jsx("button",{className:"btn-tertiary",onClick:n,children:"REJECT"}),c.jsx("button",{className:"btn-primary",onClick:t,children:"ACCEPT"})]})]}),c.jsx("div",{className:"refine-review-body text-mono text-body-md",children:c.jsx("pre",{className:"refine-review-pre",children:e})})]})}function lv({storageKey:e,onContentChange:t,onClearRef:n}={}){const[a,s]=b.useState([]),i=b.useMemo(()=>Un(a),[a]),r=b.useRef(i);r.current=i;const[l,o]=b.useState("idle"),[u,h]=b.useState(null),[f,d]=b.useState(!1),[p,v]=b.useState("idle"),[_,x]=b.useState(""),[g,m]=b.useState(null),[y,w]=b.useState(""),[C,R]=b.useState(!1),[O,z]=b.useState(0),[q,K]=b.useState(0),ve=b.useRef(null),Ae=b.useRef(null);b.useRef(-1);const ee=b.useRef(null),yt=b.useRef(0),$e=b.useRef(t);$e.current=t;const L=b.useMemo(()=>b_(y),[y]);b.useEffect(()=>{C&&O>=L.length&&z(Math.max(0,L.length-1))},[L.length,C,O]),b.useEffect(()=>{if(e){const D=localStorage.getItem(e);D&&D.trim()!==""&&s(Ol(D));return}if(me.notes){const D=me.notes.content;s(D.trim()===""?[]:Ol(D))}return me.subscribe("notes",D=>{D&&D.content!==r.current&&Date.now()-yt.current>2e3&&s(D.content.trim()===""?[]:Ol(D.content))})},[e]);const U=b.useCallback(async B=>{var D;if(e){localStorage.setItem(e,B),o("saved"),(D=$e.current)==null||D.call($e,B);return}try{o("saving"),h(null);const I=await fetch("/api/notes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:B,updatedAt:Date.now()})});if(I.ok)o("saved");else{const J=await I.json().catch(()=>({}));h(J.error||`Failed to save: ${I.status}`),o("idle")}}catch(I){console.error("Failed to save notes",I),h("Network error. Unable to reach server."),o("idle")}},[e]),k=b.useCallback(B=>{yt.current=Date.now(),o("saving"),Ae.current&&clearTimeout(Ae.current),Ae.current=setTimeout(()=>{U(B)},500)},[U]),se=b.useCallback(B=>{s(B),k(Un(B))},[k]),j=b.useCallback((B,D)=>{s(I=>{const J=I.findIndex(ce=>ce.id===B);if(J===-1)return I;const ae=[...I];return ae[J]={...ae[J],text:D,htmlContent:void 0},k(Un(ae)),ae})},[k]),V=b.useCallback((B,D)=>{s(I=>{const J=I.findIndex(E=>E.id===B);if(J===-1)return I;const ae=I[J],ce=ae.type==="ol"||ae.type==="ul"||ae.type==="todo",Oe=fd.has(ae.type),xe=ae.text===""&&D==="",te={...ae,text:ae.text.substring(0,ae.text.length-D.length)};let Q;ce&&xe?Q={id:qe(),type:"paragraph",text:""}:Oe&&xe&&!ce?Q={id:qe(),type:"paragraph",text:""}:ce?Q={id:qe(),type:ae.type,text:D,checked:ae.type==="todo"?!1:void 0}:ae.type==="code"?Q={id:qe(),type:"paragraph",text:D}:Q={id:qe(),type:"paragraph",text:D};const re=[...I.slice(0,J),te,Q,...I.slice(J+1)];return k(Un(re)),requestAnimationFrame(()=>{const E=document.querySelector(`[data-block-id="${Q.id}"] [contenteditable]`);if(E){E.focus();const M=document.createRange();M.setStart(E.firstChild||E,0),M.collapse(!0);const G=window.getSelection();G&&(G.removeAllRanges(),G.addRange(M))}}),re})},[k]),Re=b.useCallback(B=>{s(D=>{const I=D.findIndex(Q=>Q.id===B);if(I===-1)return D;const J=D[I];if(fd.has(J.type)){const Q={...J,type:"paragraph"};Q.checked=void 0,Q.codeFence=void 0;const re=[...D.slice(0,I),Q,...D.slice(I+1)];return k(Un(re)),requestAnimationFrame(()=>{const E=document.querySelector(`[data-block-id="${Q.id}"] [contenteditable]`);if(E){E.focus();const M=document.createRange();E.firstChild?M.setStart(E.firstChild,0):M.setStart(E,0),M.collapse(!0);const G=window.getSelection();G&&(G.removeAllRanges(),G.addRange(M))}}),re}if(I===0&&D.length===1&&J.text==="")return k(""),[];if(I<=0)return D;const ce=D[I-1];if(ce.type==="divider"||ce.type==="blank"){const Q=[...D.slice(0,I-1),J,...D.slice(I+1)];return k(Un(Q)),requestAnimationFrame(()=>{const re=document.querySelector(`[data-block-id="${J.id}"] [contenteditable]`);if(re){re.focus();const E=document.createRange();E.setStart(re.firstChild||re,0),E.collapse(!0);const M=window.getSelection();M&&(M.removeAllRanges(),M.addRange(E))}}),Q}const Oe=ce.text+J.text,xe={...ce,text:Oe},te=[...D.slice(0,I-1),xe,...D.slice(I+1)];return k(Un(te)),requestAnimationFrame(()=>{const Q=document.querySelector(`[data-block-id="${xe.id}"] [contenteditable]`);if(Q){Q.focus();const re=Q.firstChild,E=document.createRange();re?(E.setStart(re,ce.text.length),E.collapse(!0)):(E.setStart(Q,0),E.collapse(!0));const M=window.getSelection();M&&(M.removeAllRanges(),M.addRange(E))}}),te})},[k]),ft=b.useCallback(B=>{s(D=>{const I=D.findIndex(ae=>ae.id===B);if(I===-1)return D;const J=[...D];return J[I]={...J[I],checked:!J[I].checked},k(Un(J)),J})},[k]),nt=b.useCallback(B=>{s(D=>{const I=ee.current,J=I?D.findIndex(E=>E.id===I):D.length-1;if(J===-1)return D;const ae=D[J],ce=ae.text.lastIndexOf("/"),Oe=ce>=0?ae.text.substring(0,ce):ae.text,xe=ce>=0?ae.text.substring(ce).replace(/^\/\w*/,"").trimStart():"";let te="paragraph";switch(B.key){case"h1":te="h1";break;case"h2":te="h2";break;case"h3":te="h3";break;case"ul":te="ul";break;case"ol":te="ol";break;case"todo":te="todo";break;case"quote":te="quote";break;case"code":te="code";break;case"divider":te="divider";break;case"callout":te="callout";break}let Q;B.key==="code"?Q={id:qe(),type:"code",text:xe,codeFence:!0}:B.key==="divider"?Q={id:qe(),type:"divider",text:""}:Q={id:qe(),type:te,text:Oe+xe};const re=[...D.slice(0,J),Q,...D.slice(J+1)];return k(Un(re)),R(!1),w(""),requestAnimationFrame(()=>{const E=document.querySelector(`[data-block-id="${Q.id}"] [contenteditable]`);if(E){E.focus();const M=document.createRange();M.selectNodeContents(E),M.collapse(!1);const G=window.getSelection();G&&(G.removeAllRanges(),G.addRange(M))}}),re})},[k]),Mt=b.useCallback(B=>{if((B.metaKey||B.ctrlKey)&&B.key==="a"){const D=ve.current;if(!D)return;B.preventDefault();const I=document.createRange();I.selectNodeContents(D);const J=window.getSelection();J&&(J.removeAllRanges(),J.addRange(I));return}if(B.key==="Delete"||B.key==="Backspace"){const D=window.getSelection();if(!D||D.isCollapsed)return;const I=ve.current;if(!I)return;const J=te=>{const Q=te.nodeType===Node.TEXT_NODE?te.parentElement:te;return!Q||Q===I?null:Q.closest("[data-block-id]")},ae=D.getRangeAt(0),ce=J(ae.startContainer),Oe=J(ae.endContainer);if(ce===null||Oe===null||ce!==Oe){B.preventDefault();const te=I.querySelectorAll("[data-block-id]"),Q=[];if(ce===null||Oe===null)for(const re of te)Q.push(re.getAttribute("data-block-id"));else{let re=!1;for(const E of te)if((E===ce||E.contains(ae.startContainer))&&(re=!0),re&&Q.push(E.getAttribute("data-block-id")),E===Oe||E.contains(ae.endContainer))break}s(re=>{var de;if(Q.length===0)return re;const E=re.findIndex(ue=>ue.id===Q[0]),M=re.findIndex(ue=>ue.id===Q[Q.length-1]);if(E===-1||M===-1)return re;re[E];let G="";if(Oe){const ue=window.getSelection();if(ue&&ue.rangeCount>0){const Te=ue.getRangeAt(0);G=((de=Te.endContainer.textContent)==null?void 0:de.substring(Te.endOffset))??""}}const W=G===""?{id:qe(),type:"paragraph",text:""}:{id:qe(),type:"paragraph",text:G},ie=[...re.slice(0,E),W,...re.slice(M+1)];return k(Un(ie)),requestAnimationFrame(()=>{const ue=document.querySelector(`[data-block-id="${W.id}"] [contenteditable]`);if(ue){ue.focus();const Te=document.createRange();Te.setStart(ue,0),Te.collapse(!0);const he=window.getSelection();he&&(he.removeAllRanges(),he.addRange(Te))}}),ie});return}}if(C){if(B.key==="ArrowDown"){B.preventDefault(),z(D=>Math.min(D+1,L.length-1));return}if(B.key==="ArrowUp"){B.preventDefault(),z(D=>Math.max(D-1,0));return}if(B.key==="Enter"){B.preventDefault(),L[O]&&nt(L[O]);return}if(B.key==="Escape"){B.preventDefault(),R(!1),w("");return}}},[C,L,O,nt]),xn=b.useCallback(B=>{var ae;const D=ve.current;if(!((D==null?void 0:D.querySelector('[contenteditable="true"]'))!==null)){const ce={id:qe(),type:"paragraph",text:""};s(Oe=>[...Oe,ce]),requestAnimationFrame(()=>{const Oe=document.querySelector(`[data-block-id="${ce.id}"] [contenteditable]`);if(Oe){Oe.focus();const xe=document.createRange();xe.setStart(Oe,0),xe.collapse(!0);const te=window.getSelection();te&&(te.removeAllRanges(),te.addRange(xe))}});return}const J=B.target;if(J===ve.current||J.classList.contains("notes-placeholder")){const ce=(ae=ve.current)==null?void 0:ae.querySelectorAll('[contenteditable="true"]'),Oe=ce!=null&&ce.length?ce[ce.length-1]:null;if(Oe){Oe.focus();const xe=document.createRange();xe.selectNodeContents(Oe),xe.collapse(!1);const te=window.getSelection();te&&(te.removeAllRanges(),te.addRange(xe))}else{const xe={id:qe(),type:"paragraph",text:""};s(te=>[...te,xe]),requestAnimationFrame(()=>{const te=document.querySelector(`[data-block-id="${xe.id}"] [contenteditable]`);if(te){te.focus();const Q=document.createRange();Q.setStart(te,0),Q.collapse(!0);const re=window.getSelection();re&&(re.removeAllRanges(),re.addRange(Q))}})}}},[a.length,i]),va=b.useCallback(B=>{B.currentTarget;const D=document.activeElement,I=D==null?void 0:D.closest("[data-block-id]");if(I&&(ee.current=I.getAttribute("data-block-id")),D&&D.getAttribute("contenteditable")==="true"){const ae=(D.textContent??"").match(/^\/(\w*)$/);if(ae){R(!0),w("/"+ae[1]),z(0);const ce=a.findIndex(Oe=>Oe.id===ee.current);K(Math.max(0,ce))}else C&&(R(!1),w(""))}},[C,a]),Tn=B=>{B.preventDefault(),B.dataTransfer.dropEffect="copy",d(!0)},En=()=>d(!1),Et=B=>{B.preventDefault(),d(!1);const D=B.dataTransfer.getData("text/plain"),I=B.dataTransfer.getData("taskId");if(D){const J={id:qe(),type:"paragraph",text:D},ae=[...a,J];se(ae)}I&&(Do(I),me.removeSuggestion(I))},Me=b.useCallback(async()=>{const B=r.current;if(B.trim()!==""){v("refining"),m(null);try{const D=await fetch("/api/notes/refine",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:B})});if(!D.ok){const J=await D.json().catch(()=>({}));throw new Error(J.error||`Refinement failed: ${D.status}`)}const I=await D.json();x(I.refinedContent),v("review")}catch(D){m(D instanceof Error?D.message:"Refinement failed"),v("error"),setTimeout(()=>{v("idle"),m(null)},5e3)}}},[]),Lt=b.useCallback(()=>{const D=(_.trim()===""?[]:Ol(_)).map(I=>{if(I.type==="code"||I.type==="divider"||I.type==="blank")return I;const J=w_(I.text);return J!==I.text?{...I,htmlContent:J}:I});s(D),v("idle"),x(""),k(_)},[_,k]),Ne=b.useCallback(()=>{v("idle"),x("")},[]),vt=i.trim()==="";b.useEffect(()=>{n&&(n.current=()=>{var B;s([]),e&&localStorage.removeItem(e),r.current="",(B=$e.current)==null||B.call($e,"")})},[n,e]);const ke=b.useMemo(()=>C?{top:`${Math.min(q*28+40,300)}px`,left:"8px"}:{display:"none"},[C,q]);return c.jsxs("div",{className:"panel notes-panel",role:"region","aria-label":"Developer Notes",tabIndex:0,style:{backgroundColor:f?"rgba(255, 255, 255, 0.05)":"transparent",transition:"background-color 0.2s"},onDragOver:Tn,onDragLeave:En,onDrop:Et,children:[c.jsxs("header",{className:"panel-header notes-panel-header",children:[c.jsx("h2",{className:"panel-title",children:"01_DEVELOPER_NOTES"}),c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[u&&c.jsx("span",{style:{color:"#FF0000",fontFamily:"var(--font-sans)",fontSize:"0.65rem",textTransform:"uppercase"},children:u}),g&&c.jsx("span",{style:{color:"#FF0000",fontFamily:"var(--font-sans)",fontSize:"0.65rem",textTransform:"uppercase"},children:g}),c.jsx("button",{className:"btn-tertiary refine-btn",onClick:Me,disabled:vt||p==="refining"||p==="review","aria-label":"Refine notes",children:p==="refining"?"REFINING…":"REFINE NOTES"}),c.jsxs("div",{style:{fontFamily:"var(--font-sans)",fontSize:"0.65rem",color:"var(--panel-label)",textTransform:"uppercase",display:"flex",alignItems:"center",gap:"6px"},children:[l==="saving"&&"Saving…",l==="saved"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"status-dot",style:{backgroundColor:"var(--panel-label)"}}),"SAVED"]})]})]})]}),f&&c.jsx("div",{className:"drag-overlay",children:c.jsx("span",{className:"text-mono",style:{color:"var(--primary)",fontSize:"0.875rem"},children:"Drop to add task"})}),p==="review"?c.jsx(E_,{refinedContent:_,onAccept:Lt,onReject:Ne}):c.jsxs("div",{className:"notes-editor-wrapper",children:[c.jsxs("div",{ref:ve,className:"notes-block-editor",onKeyDown:Mt,onInput:va,onFocus:B=>{const D=B.target.closest("[data-block-id]");D&&(ee.current=D.getAttribute("data-block-id"))},onClick:xn,"aria-label":"Developer notes editor",role:"textbox",children:[a.length===0&&vt&&c.jsx("div",{className:"notes-placeholder",children:"Write your notes here. Type / for commands..."}),a.map((B,D)=>{let I;if(B.type==="ol"){I=1;for(let J=D-1;J>=0&&a[J].type==="ol";J--)I++}return c.jsx(x_,{block:B,olNumber:I,onChange:j,onEnter:V,onBackspace:Re,onToggleCheck:ft},B.id)})]}),C&&L.length>0&&c.jsx("div",{className:"slash-menu-container",style:ke,children:c.jsx(T_,{commands:L,selectedIndex:O,onSelect:nt})})]})]})}function rc(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,a=Object.getOwnPropertySymbols(e);s<a.length;s++)t.indexOf(a[s])<0&&Object.prototype.propertyIsEnumerable.call(e,a[s])&&(n[a[s]]=e[a[s]]);return n}function A_(e,t,n,a){function s(i){return i instanceof n?i:new n(function(r){r(i)})}return new(n||(n=Promise))(function(i,r){function l(h){try{u(a.next(h))}catch(f){r(f)}}function o(h){try{u(a.throw(h))}catch(f){r(f)}}function u(h){h.done?i(h.value):s(h.value).then(l,o)}u((a=a.apply(e,t||[])).next())})}const C_=e=>e?(...t)=>e(...t):(...t)=>fetch(...t);class Eh extends Error{constructor(t,n="FunctionsError",a){super(t),this.name=n,this.context=a}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class O_ extends Eh{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class xp extends Eh{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Tp extends Eh{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var pd;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(pd||(pd={}));class R_{constructor(t,{headers:n={},customFetch:a,region:s=pd.Any}={}){this.url=t,this.headers=n,this.region=s,this.fetch=C_(a)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return A_(this,arguments,void 0,function*(n,a={}){var s;let i,r;try{const{headers:l,method:o,body:u,signal:h,timeout:f}=a;let d={},{region:p}=a;p||(p=this.region);const v=new URL(`${this.url}/${n}`);p&&p!=="any"&&(d["x-region"]=p,v.searchParams.set("forceFunctionRegion",p));let _;u&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",_=u):typeof u=="string"?(d["Content-Type"]="text/plain",_=u):typeof FormData<"u"&&u instanceof FormData?_=u:(d["Content-Type"]="application/json",_=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?_=JSON.stringify(u):_=u;let x=h;f&&(r=new AbortController,i=setTimeout(()=>r.abort(),f),h?(x=r.signal,h.addEventListener("abort",()=>r.abort())):x=r.signal);const g=yield this.fetch(v.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),l),body:_,signal:x}).catch(C=>{throw new O_(C)}),m=g.headers.get("x-relay-error");if(m&&m==="true")throw new xp(g);if(!g.ok)throw new Tp(g);let y=((s=g.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),w;return y==="application/json"?w=yield g.json():y==="application/octet-stream"||y==="application/pdf"?w=yield g.blob():y==="text/event-stream"?w=g:y==="multipart/form-data"?w=yield g.formData():w=yield g.text(),{data:w,error:null,response:g}}catch(l){return{data:null,error:l,response:l instanceof Tp||l instanceof xp?l.context:void 0}}finally{i&&clearTimeout(i)}})}}const ov=3,Ep=e=>Math.min(1e3*2**e,3e4),N_=[520,503],cv=["GET","HEAD","OPTIONS"];var Ap=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Cp(e,t){return new Promise(n=>{if(t!=null&&t.aborted){n();return}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",s),n()},e);function s(){clearTimeout(a),n()}t==null||t.addEventListener("abort",s)})}function k_(e,t,n,a){return!(!a||n>=ov||!cv.includes(e)||!N_.includes(t))}var j_=class{constructor(e){var t,n,a,s,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(n=e.isMaybeSingle)!==null&&n!==void 0?n:!1,this.shouldStripNulls=(a=e.shouldStripNulls)!==null&&a!==void 0?a:!1,this.urlLengthLimit=(s=e.urlLengthLimit)!==null&&s!==void 0?s:8e3,this.retryEnabled=(i=e.retry)!==null&&i!==void 0?i:!0,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var n=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const r=this.headers.get("Accept");r==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!r||r==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const a=this.fetch;let i=(async()=>{let r=0;for(;;){const u=new Headers(n.headers);r>0&&u.set("X-Retry-Count",String(r));let h;try{h=await a(n.url.toString(),{method:n.method,headers:u,body:JSON.stringify(n.body,(f,d)=>typeof d=="bigint"?d.toString():d),signal:n.signal})}catch(f){if((f==null?void 0:f.name)==="AbortError"||(f==null?void 0:f.code)==="ABORT_ERR"||!cv.includes(n.method))throw f;if(n.retryEnabled&&r<ov){const d=Ep(r);r++,await Cp(d,n.signal);continue}throw f}if(k_(n.method,h.status,r,n.retryEnabled)){var l,o;const f=(l=(o=h.headers)===null||o===void 0?void 0:o.get("Retry-After"))!==null&&l!==void 0?l:null,d=f!==null?Math.max(0,parseInt(f,10)||0)*1e3:Ep(r);await h.text(),r++,await Cp(d,n.signal);continue}return await n.processResponse(h)}})();return this.shouldThrowOnError||(i=i.catch(r=>{var l;let o="",u="",h="";const f=r==null?void 0:r.cause;if(f){var d,p,v,_;const m=(d=f==null?void 0:f.message)!==null&&d!==void 0?d:"",y=(p=f==null?void 0:f.code)!==null&&p!==void 0?p:"";o=`${(v=r==null?void 0:r.name)!==null&&v!==void 0?v:"FetchError"}: ${r==null?void 0:r.message}`,o+=`
44
+
45
+ Caused by: ${(_=f==null?void 0:f.name)!==null&&_!==void 0?_:"Error"}: ${m}`,y&&(o+=` (${y})`),f!=null&&f.stack&&(o+=`
46
+ ${f.stack}`)}else{var x;o=(x=r==null?void 0:r.stack)!==null&&x!==void 0?x:""}const g=this.url.toString().length;return(r==null?void 0:r.name)==="AbortError"||(r==null?void 0:r.code)==="ABORT_ERR"?(h="",u="Request was aborted (timeout or manual cancellation)",g>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${g} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((f==null?void 0:f.name)==="HeadersOverflowError"||(f==null?void 0:f.code)==="UND_ERR_HEADERS_OVERFLOW")&&(h="",u="HTTP headers exceeded server limits (typically 16KB)",g>this.urlLengthLimit&&(u+=`. Your request URL is ${g} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(l=r==null?void 0:r.name)!==null&&l!==void 0?l:"FetchError"}: ${r==null?void 0:r.message}`,details:o,hint:u,code:h},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}async processResponse(e){var t=this;let n=null,a=null,s=null,i=e.status,r=e.statusText;if(e.ok){var l,o;if(t.method!=="HEAD"){var u;const d=await e.text();if(d!=="")if(t.headers.get("Accept")==="text/csv")a=d;else if(t.headers.get("Accept")&&(!((u=t.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text")))a=d;else try{a=JSON.parse(d)}catch{if(n={message:d},a=null,t.shouldThrowOnError)throw new Ap({message:d,details:"",hint:"",code:""})}}const h=(l=t.headers.get("Prefer"))===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),f=(o=e.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");h&&f&&f.length>1&&(s=parseInt(f[1])),t.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(n={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,s=null,i=406,r="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{const h=await e.text();try{n=JSON.parse(h),Array.isArray(n)&&e.status===404&&(a=[],n=null,i=200,r="OK")}catch{e.status===404&&h===""?(i=204,r="No Content"):n={message:h}}if(n&&t.shouldThrowOnError)throw new Ap(n)}return{success:n===null,error:n,data:a,count:s,status:i,statusText:r}}returns(){return this}overrideTypes(){return this}},D_=class extends j_{select(e){let t=!1;const n=(e??"*").split("").map(a=>/\s/.test(a)&&!t?"":(a==='"'&&(t=!t),a)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:a,referencedTable:s=a}={}){const i=s?`${s}.order`:"order",r=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${r?`${r},`:""}${e}.${t?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){const a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:a=n}={}){const s=typeof a>"u"?"offset":`${a}.offset`,i=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:a=!1,wal:s=!1,format:i="text"}={}){var r;const l=[e?"analyze":null,t?"verbose":null,n?"settings":null,a?"buffers":null,s?"wal":null].filter(Boolean).join("|"),o=(r=this.headers.get("Accept"))!==null&&r!==void 0?r:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${o}"; options=${l};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const Op=new RegExp("[,()]");var qs=class extends D_{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const n=Array.from(new Set(t)).map(a=>typeof a=="string"&&Op.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){const n=Array.from(new Set(t)).map(a=>typeof a=="string"&&Op.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:a}={}){let s="";a==="plain"?s="pl":a==="phrase"?s="ph":a==="websearch"&&(s="w");const i=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${s}fts${i}.${t}`),this}match(e){return Object.entries(e).filter(([t,n])=>n!==void 0).forEach(([t,n])=>{this.url.searchParams.append(t,`eq.${n}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){const a=n?`${n}.or`:"or";return this.url.searchParams.append(a,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},M_=class{constructor(e,{headers:t={},schema:n,fetch:a,urlLengthLimit:s=8e3,retry:i}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=a,this.urlLengthLimit=s,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:n=!1,count:a}=t??{},s=n?"HEAD":"GET";let i=!1;const r=(e??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:l,headers:o}=this.cloneRequestState();return l.searchParams.set("select",r),a&&o.append("Prefer",`count=${a}`),new qs({method:s,url:l,headers:o,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:n=!0}={}){var a;const s="POST",{url:i,headers:r}=this.cloneRequestState();if(t&&r.append("Prefer",`count=${t}`),n||r.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((o,u)=>o.concat(Object.keys(u)),[]);if(l.length>0){const o=[...new Set(l)].map(u=>`"${u}"`);i.searchParams.set("columns",o.join(","))}}return new qs({method:s,url:i,headers:r,schema:this.schema,body:e,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:a,defaultToNull:s=!0}={}){var i;const r="POST",{url:l,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${n?"ignore":"merge"}-duplicates`),t!==void 0&&l.searchParams.set("on_conflict",t),a&&o.append("Prefer",`count=${a}`),s||o.append("Prefer","missing=default"),Array.isArray(e)){const u=e.reduce((h,f)=>h.concat(Object.keys(f)),[]);if(u.length>0){const h=[...new Set(u)].map(f=>`"${f}"`);l.searchParams.set("columns",h.join(","))}}return new qs({method:r,url:l,headers:o,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var n;const a="PATCH",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new qs({method:a,url:s,headers:i,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;const n="DELETE",{url:a,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new qs({method:n,url:a,headers:s,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Lr(e){"@babel/helpers - typeof";return Lr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lr(e)}function U_(e,t){if(Lr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(Lr(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function L_(e){var t=U_(e,"string");return Lr(t)=="symbol"?t:t+""}function z_(e,t,n){return(t=L_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Rp(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,a)}return n}function Rl(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Rp(Object(n),!0).forEach(function(a){z_(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Rp(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}var B_=class uv{constructor(t,{headers:n={},schema:a,fetch:s,timeout:i,urlLengthLimit:r=8e3,retry:l}={}){this.url=t,this.headers=new Headers(n),this.schemaName=a,this.urlLengthLimit=r;const o=s??globalThis.fetch;i!==void 0&&i>0?this.fetch=(u,h)=>{const f=new AbortController,d=setTimeout(()=>f.abort(),i),p=h==null?void 0:h.signal;if(p){if(p.aborted)return clearTimeout(d),o(u,h);const v=()=>{clearTimeout(d),f.abort()};return p.addEventListener("abort",v,{once:!0}),o(u,Rl(Rl({},h),{},{signal:f.signal})).finally(()=>{clearTimeout(d),p.removeEventListener("abort",v)})}return o(u,Rl(Rl({},h),{},{signal:f.signal})).finally(()=>clearTimeout(d))}:this.fetch=o,this.retry=l}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new M_(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new uv(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(t,n={},{head:a=!1,get:s=!1,count:i}={}){var r;let l;const o=new URL(`${this.url}/rpc/${t}`);let u;const h=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(h)),f=a&&Object.values(n).some(h);f?(l="POST",u=n):a||s?(l=a?"HEAD":"GET",Object.entries(n).filter(([p,v])=>v!==void 0).map(([p,v])=>[p,Array.isArray(v)?`{${v.join(",")}}`:`${v}`]).forEach(([p,v])=>{o.searchParams.append(p,v)})):(l="POST",u=n);const d=new Headers(this.headers);return f?d.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&d.set("Prefer",`count=${i}`),new qs({method:l,url:o,headers:d,schema:this.schemaName,body:u,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class I_{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const n=globalThis;if(typeof globalThis<"u"&&typeof n.WebSocket<"u")return{type:"native",wsConstructor:n.WebSocket};const a=typeof global<"u"?global:void 0;if(a&&typeof a.WebSocket<"u")return{type:"native",wsConstructor:a.WebSocket};if(typeof globalThis<"u"&&typeof n.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"&&n.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const s=globalThis.process;if(s){const i=s.versions;if(i&&i.node){const r=i.node,l=parseInt(r.replace(/^v/,"").split(".")[0]);return l>=22?typeof globalThis.WebSocket<"u"?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${l} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${l} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
47
+ import ws from "ws"
48
+ new 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 t=this.detectEnvironment();if(t.wsConstructor)return t.wsConstructor;let n=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(n+=`
49
+
50
+ Suggested solution: ${t.workaround}`),new Error(n)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}}const H_="2.107.0",$_=`realtime-js/${H_}`,P_="1.0.0",dv="2.0.0",q_=dv,G_=1e4,K_=100,ja={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},hv={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},md={connecting:"connecting",closing:"closing",closed:"closed"};class V_{constructor(t){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=t??[]}encode(t,n){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return n(this._binaryEncodeUserBroadcastPush(t));let a=[t.join_ref,t.ref,t.topic,t.event,t.payload];return n(JSON.stringify(a))}_binaryEncodeUserBroadcastPush(t){var n;return this._isArrayBuffer((n=t.payload)===null||n===void 0?void 0:n.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var n,a;const s=(a=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&a!==void 0?a:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(t){var n,a;const s=(a=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&a!==void 0?a:{},r=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,r)}_encodeUserBroadcastPush(t,n,a){var s,i;const r=t.topic,l=(s=t.ref)!==null&&s!==void 0?s:"",o=(i=t.join_ref)!==null&&i!==void 0?i:"",u=t.payload.event,h=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},f=Object.keys(h).length===0?"":JSON.stringify(h);if(o.length>255)throw new Error(`joinRef length ${o.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(r.length>255)throw new Error(`topic length ${r.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);const d=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+l.length+r.length+u.length+f.length,p=new ArrayBuffer(this.HEADER_LENGTH+d);let v=new DataView(p),_=0;v.setUint8(_++,this.KINDS.userBroadcastPush),v.setUint8(_++,o.length),v.setUint8(_++,l.length),v.setUint8(_++,r.length),v.setUint8(_++,u.length),v.setUint8(_++,f.length),v.setUint8(_++,n),Array.from(o,g=>v.setUint8(_++,g.charCodeAt(0))),Array.from(l,g=>v.setUint8(_++,g.charCodeAt(0))),Array.from(r,g=>v.setUint8(_++,g.charCodeAt(0))),Array.from(u,g=>v.setUint8(_++,g.charCodeAt(0))),Array.from(f,g=>v.setUint8(_++,g.charCodeAt(0)));var x=new Uint8Array(p.byteLength+a.byteLength);return x.set(new Uint8Array(p),0),x.set(new Uint8Array(a),p.byteLength),x.buffer}decode(t,n){if(this._isArrayBuffer(t)){let a=this._binaryDecode(t);return n(a)}if(typeof t=="string"){const a=JSON.parse(t),[s,i,r,l,o]=a;return n({join_ref:s,ref:i,topic:r,event:l,payload:o})}return n({})}_binaryDecode(t){const n=new DataView(t),a=n.getUint8(0),s=new TextDecoder;switch(a){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,n,s)}}_decodeUserBroadcast(t,n,a){const s=n.getUint8(1),i=n.getUint8(2),r=n.getUint8(3),l=n.getUint8(4);let o=this.HEADER_LENGTH+4;const u=a.decode(t.slice(o,o+s));o=o+s;const h=a.decode(t.slice(o,o+i));o=o+i;const f=a.decode(t.slice(o,o+r));o=o+r;const d=t.slice(o,t.byteLength),p=l===this.JSON_ENCODING?JSON.parse(a.decode(d)):d,v={type:this.BROADCAST_EVENT,event:h,payload:p};return r>0&&(v.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:v}}_isArrayBuffer(t){var n;return t instanceof ArrayBuffer||((n=t==null?void 0:t.constructor)===null||n===void 0?void 0:n.name)==="ArrayBuffer"}_pick(t,n){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([a])=>n.includes(a)))}}var Pe;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(Pe||(Pe={}));const Np=(e,t,n={})=>{var a;const s=(a=n.skipTypes)!==null&&a!==void 0?a:[];return t?Object.keys(t).reduce((i,r)=>(i[r]=Y_(r,e,t,s),i),{}):{}},Y_=(e,t,n,a)=>{const s=t.find(l=>l.name===e),i=s==null?void 0:s.type,r=n[e];return i&&!a.includes(i)?fv(i,r):gd(r)},fv=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return Q_(t,n)}switch(e){case Pe.bool:return F_(t);case Pe.float4:case Pe.float8:case Pe.int2:case Pe.int4:case Pe.int8:case Pe.numeric:case Pe.oid:return J_(t);case Pe.json:case Pe.jsonb:return X_(t);case Pe.timestamp:return W_(t);case Pe.abstime:case Pe.date:case Pe.daterange:case Pe.int4range:case Pe.int8range:case Pe.money:case Pe.reltime:case Pe.text:case Pe.time:case Pe.timestamptz:case Pe.timetz:case Pe.tsrange:case Pe.tstzrange:return gd(t);default:return gd(t)}},gd=e=>e,F_=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},J_=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},X_=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},Q_=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,a=e[n];if(e[0]==="{"&&a==="}"){let i;const r=e.slice(1,n);try{i=JSON.parse("["+r+"]")}catch{i=r?r.split(","):[]}return i.map(l=>fv(t,l))}return e},W_=e=>typeof e=="string"?e.replace(" ","T"):e,pv=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/"?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var br=e=>typeof e=="function"?e:function(){return e},Z_=typeof self<"u"?self:null,Gs=typeof window<"u"?window:null,zn=Z_||Gs||globalThis,ew="2.0.0",tw=1e4,nw=1e3,Bn={connecting:0,open:1,closing:2,closed:3},Kt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},na={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},yd={longpoll:"longpoll",websocket:"websocket"},aw={complete:4},vd="base64url.bearer.phx.",Nl=class{constructor(e,t,n,a){this.channel=e,this.event=t,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=a,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:n}){this.recHooks.filter(a=>a.status===e).forEach(a=>a.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},mv=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},sw=class{constructor(e,t,n){this.state=Kt.closed,this.topic=e,this.params=br(t||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Nl(this,na.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new mv(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Kt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this.joinPush.receive("error",a=>{this.state=Kt.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Kt.closed,this.socket.remove(this)}),this.onError(a=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.isJoining()&&this.joinPush.reset(),this.state=Kt.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Nl(this,na.leave,br({}),this.timeout).send(),this.state=Kt.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(na.reply,(a,s)=>{this.trigger(this.replyEventName(s),a)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Kt.closed,this.bindings=[]}onClose(e){this.on(na.close,e)}onError(e){return this.on(na.error,t=>e(t))}on(e,t){let n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}off(e,t){this.bindings=this.bindings.filter(n=>!(n.event===e&&(typeof t>"u"||t===n.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,n=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let a=new Nl(this,e,function(){return t},n);return this.canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Kt.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(na.close,"leave")},n=new Nl(this,na.leave,br({}),e);return n.receive("ok",()=>t()).receive("timeout",()=>t()),n.send(),this.canPush()||n.trigger("ok",{}),n}onMessage(e,t,n){return t}filterBindings(e,t,n){return!0}isMember(e,t,n,a){return this.topic!==e?!1:a&&a!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:n,joinRef:a}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Kt.joining,this.joinPush.resend(e))}trigger(e,t,n,a){let s=this.onMessage(e,t,n,a);if(t&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(r=>r.event===e&&this.filterBindings(r,t,n));for(let r=0;r<i.length;r++)i[r].callback(s,n,a||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===Kt.closed}isErrored(){return this.state===Kt.errored}isJoined(){return this.state===Kt.joined}isJoining(){return this.state===Kt.joining}isLeaving(){return this.state===Kt.leaving}},Mo=class{static request(e,t,n,a,s,i,r){if(zn.XDomainRequest){let l=new zn.XDomainRequest;return this.xdomainRequest(l,e,t,a,s,i,r)}else if(zn.XMLHttpRequest){let l=new zn.XMLHttpRequest;return this.xhrRequest(l,e,t,n,a,s,i,r)}else{if(zn.fetch&&zn.AbortController)return this.fetchRequest(e,t,n,a,s,i,r);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(e,t,n,a,s,i,r){let l={method:e,headers:n,body:a},o=null;return s&&(o=new AbortController,setTimeout(()=>o.abort(),s),l.signal=o.signal),zn.fetch(t,l).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>r&&r(u)).catch(u=>{u.name==="AbortError"&&i?i():r&&r(null)}),o}static xdomainRequest(e,t,n,a,s,i,r){return e.timeout=s,e.open(t,n),e.onload=()=>{let l=this.parseJSON(e.responseText);r&&r(l)},i&&(e.ontimeout=i),e.onprogress=()=>{},e.send(a),e}static xhrRequest(e,t,n,a,s,i,r,l){e.open(t,n,!0),e.timeout=i;for(let[o,u]of Object.entries(a))e.setRequestHeader(o,u);return e.onerror=()=>l&&l(null),e.onreadystatechange=()=>{if(e.readyState===aw.complete&&l){let o=this.parseJSON(e.responseText);l(o)}},r&&(e.ontimeout=r),e.send(s),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let n=[];for(var a in e){if(!Object.prototype.hasOwnProperty.call(e,a))continue;let s=t?`${t}[${a}]`:a,i=e[a];typeof i=="object"?n.push(this.serialize(i,s)):n.push(encodeURIComponent(s)+"="+encodeURIComponent(i))}return n.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let n=e.match(/\?/)?"&":"?";return`${e}${n}${this.serialize(t)}`}},iw=e=>{let t="",n=new Uint8Array(e),a=n.byteLength;for(let s=0;s<a;s++)t+=String.fromCharCode(n[s]);return btoa(t)},Ms=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(vd)&&(this.authToken=atob(t[1].slice(vd.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=Bn.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+yd.websocket),"$1/"+yd.longpoll)}endpointURL(){return Mo.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,n){this.close(e,t,n),this.readyState=Bn.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Bn.open||this.readyState===Bn.connecting}poll(){const e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),t=>{if(t){var{status:n,token:a,messages:s}=t;if(n===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=a}else n=0;switch(n){case 200:s.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Bn.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${n}`)}})}send(e){typeof e!="string"&&(e=iw(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(`
51
+ `),()=>this.onerror("timeout"),t=>{this.awaitingBatchAck=!1,!t||t.status!==200?(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(e,t,n){for(let s of this.reqs)s.abort();this.readyState=Bn.closed;let a=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",a)):this.onclose(a)}ajax(e,t,n,a,s){let i,r=()=>{this.reqs.delete(i),a()};i=Mo.request(e,this.endpointURL(),t,n,this.timeout,r,l=>{this.reqs.delete(i),this.isActive()&&s(l)}),this.reqs.add(i)}},rw=class ar{constructor(t,n={}){let a=n.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(a.state,s=>{let{onJoin:i,onLeave:r,onSync:l}=this.caller;this.joinRef=this.channel.joinRef(),this.state=ar.syncState(this.state,s,i,r),this.pendingDiffs.forEach(o=>{this.state=ar.syncDiff(this.state,o,i,r)}),this.pendingDiffs=[],l()}),this.channel.on(a.diff,s=>{let{onJoin:i,onLeave:r,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=ar.syncDiff(this.state,s,i,r),l())})}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}list(t){return ar.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(t,n,a,s){let i=this.clone(t),r={},l={};return this.map(i,(o,u)=>{n[o]||(l[o]=u)}),this.map(n,(o,u)=>{let h=i[o];if(h){let f=u.metas.map(_=>_.phx_ref),d=h.metas.map(_=>_.phx_ref),p=u.metas.filter(_=>d.indexOf(_.phx_ref)<0),v=h.metas.filter(_=>f.indexOf(_.phx_ref)<0);p.length>0&&(r[o]=u,r[o].metas=p),v.length>0&&(l[o]=this.clone(h),l[o].metas=v)}else r[o]=u}),this.syncDiff(i,{joins:r,leaves:l},a,s)}static syncDiff(t,n,a,s){let{joins:i,leaves:r}=this.clone(n);return a||(a=function(){}),s||(s=function(){}),this.map(i,(l,o)=>{let u=t[l];if(t[l]=this.clone(o),u){let h=t[l].metas.map(d=>d.phx_ref),f=u.metas.filter(d=>h.indexOf(d.phx_ref)<0);t[l].metas.unshift(...f)}a(l,u,o)}),this.map(r,(l,o)=>{let u=t[l];if(!u)return;let h=o.metas.map(f=>f.phx_ref);u.metas=u.metas.filter(f=>h.indexOf(f.phx_ref)<0),s(l,u,o),u.metas.length===0&&delete t[l]}),t}static list(t,n){return n||(n=function(a,s){return s}),this.map(t,(a,s)=>n(a,s))}static map(t,n){return Object.getOwnPropertyNames(t).map(a=>n(a,t[a]))}static clone(t){return JSON.parse(JSON.stringify(t))}},kl={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[n,a,s,i,r]=JSON.parse(e);return t({join_ref:n,ref:a,topic:s,event:i,payload:r})}},binaryEncode(e){let{join_ref:t,ref:n,event:a,topic:s,payload:i}=e,r=this.META_LENGTH+t.length+n.length+s.length+a.length,l=new ArrayBuffer(this.HEADER_LENGTH+r),o=new DataView(l),u=0;o.setUint8(u++,this.KINDS.push),o.setUint8(u++,t.length),o.setUint8(u++,n.length),o.setUint8(u++,s.length),o.setUint8(u++,a.length),Array.from(t,f=>o.setUint8(u++,f.charCodeAt(0))),Array.from(n,f=>o.setUint8(u++,f.charCodeAt(0))),Array.from(s,f=>o.setUint8(u++,f.charCodeAt(0))),Array.from(a,f=>o.setUint8(u++,f.charCodeAt(0)));var h=new Uint8Array(l.byteLength+i.byteLength);return h.set(new Uint8Array(l),0),h.set(new Uint8Array(i),l.byteLength),h.buffer},binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),a=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,a);case this.KINDS.reply:return this.decodeReply(e,t,a);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,a)}},decodePush(e,t,n){let a=t.getUint8(1),s=t.getUint8(2),i=t.getUint8(3),r=this.HEADER_LENGTH+this.META_LENGTH-1,l=n.decode(e.slice(r,r+a));r=r+a;let o=n.decode(e.slice(r,r+s));r=r+s;let u=n.decode(e.slice(r,r+i));r=r+i;let h=e.slice(r,e.byteLength);return{join_ref:l,ref:null,topic:o,event:u,payload:h}},decodeReply(e,t,n){let a=t.getUint8(1),s=t.getUint8(2),i=t.getUint8(3),r=t.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,o=n.decode(e.slice(l,l+a));l=l+a;let u=n.decode(e.slice(l,l+s));l=l+s;let h=n.decode(e.slice(l,l+i));l=l+i;let f=n.decode(e.slice(l,l+r));l=l+r;let d=e.slice(l,e.byteLength),p={status:f,response:d};return{join_ref:o,ref:u,topic:h,event:na.reply,payload:p}},decodeBroadcast(e,t,n){let a=t.getUint8(1),s=t.getUint8(2),i=this.HEADER_LENGTH+2,r=n.decode(e.slice(i,i+a));i=i+a;let l=n.decode(e.slice(i,i+s));i=i+s;let o=e.slice(i,e.byteLength);return{join_ref:null,ref:null,topic:r,event:l,payload:o}}},lw=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||tw,this.transport=t.transport||zn.WebSocket||Ms,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let n=null;try{n=zn&&zn.sessionStorage}catch{}this.sessionStore=t.sessionStorage||n,this.establishedConnections=0,this.defaultEncoder=kl.encode.bind(kl),this.defaultDecoder=kl.decode.bind(kl),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Ms?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let a=null;Gs&&Gs.addEventListener&&(Gs.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),a=this.connectClock)}),Gs.addEventListener("pageshow",s=>{a===this.connectClock&&(a=null,this.connect())}),Gs.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>t.rejoinAfterMs?t.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>t.reconnectAfterMs?t.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(s,i,r)=>{console.log(`${s}: ${i}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=br(t.params||{}),this.endPoint=`${e}/${yd.websocket}`,this.vsn=t.vsn||ew,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new mv(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return Ms}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Mo.appendParams(Mo.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,n){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,n)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=br(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ms?this.connectWithFallback(Ms,this.longPollFallbackMs):this.transportConnect())}log(e,t,n){this.logger&&this.logger(e,t,n)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),n=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let a=this.onMessage(s=>{s.ref===t&&(this.off([a]),e(Date.now()-n))});return!0}transportName(e){switch(e){case Ms:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["phoenix",`${vd}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let n=!1,a=!0,s,i,r=this.transportName(e),l=o=>{this.log("transport",`falling back to ${r}...`,o),this.off([s,i]),a=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${r}`))return l("memorized");this.fallbackTimer=setTimeout(l,t),i=this.onError(o=>{this.log("transport","error",o),a&&!n&&(clearTimeout(this.fallbackTimer),l(o))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!a){let o=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${o}`,"true"),this.log("transport",`established ${o} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(l,t),this.ping(o=>{this.log("transport","connected to primary after",o),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),nw,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,n){if(!this.conn)return e&&e();const a=this.conn;this.waitForBufferDone(a,()=>{t?a.close(t,n||""):a.close(),this.waitForSocketClosed(a,()=>{this.conn===a&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,n=1){if(n===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,n+1)},150*n)}waitForSocketClosed(e,t,n=1){if(n===5||e.readyState===Bn.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,n+1)},150*n)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,n=this.establishedConnections;this.triggerStateCallbacks("error",e,t,n),(t===this.transport||n>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(na.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case Bn.connecting:return"connecting";case Bn.open:return"open";case Bn.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([n])=>e.indexOf(n)===-1)}channel(e,t={}){let n=new sw(e,t,this);return this.channels.push(n),n}push(e){if(this.hasLogger()){let{topic:t,event:n,payload:a,ref:s,join_ref:i}=e;this.log("push",`${t} ${n} (${i}, ${s})`,a)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:n,event:a,payload:s,ref:i,join_ref:r}=t;if(i&&i===this.pendingHeartbeatRef){const l=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(s.status==="ok"?"ok":"error",l)}catch(o){this.log("error","error in heartbeat callback",o)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${s.status||""} ${n} ${a} ${i&&"("+i+")"||""}`.trim(),s);for(let l=0;l<this.channels.length;l++){const o=this.channels[l];o.isMember(n,a,s,r)&&o.trigger(a,s,i,r)}this.triggerStateCallbacks("message",t)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([n,a])=>{try{a(...t)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}leaveOpenTopic(e){let t=this.channels.find(n=>n.topic===e&&(n.isJoined()||n.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};class Sr{constructor(t,n){const a=cw(n);this.presence=new rw(t.getChannel(),a),this.presence.onJoin((s,i,r)=>{const l=Sr.onJoinPayload(s,i,r);t.getChannel().trigger("presence",l)}),this.presence.onLeave((s,i,r)=>{const l=Sr.onLeavePayload(s,i,r);t.getChannel().trigger("presence",l)}),this.presence.onSync(()=>{t.getChannel().trigger("presence",{event:"sync"})})}get state(){return Sr.transformState(this.presence.state)}static transformState(t){return t=ow(t),Object.getOwnPropertyNames(t).reduce((n,a)=>{const s=t[a];return n[a]=no(s),n},{})}static onJoinPayload(t,n,a){const s=kp(n),i=no(a);return{event:"join",key:t,currentPresences:s,newPresences:i}}static onLeavePayload(t,n,a){const s=kp(n),i=no(a);return{event:"leave",key:t,currentPresences:s,leftPresences:i}}}function no(e){return e.metas.map(t=>(t.presence_ref=t.phx_ref,delete t.phx_ref,delete t.phx_ref_prev,t))}function ow(e){return JSON.parse(JSON.stringify(e))}function cw(e){return(e==null?void 0:e.events)&&{events:e.events}}function kp(e){return e!=null&&e.metas?no(e):[]}var jp;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(jp||(jp={}));class uw{get state(){return this.presenceAdapter.state}constructor(t,n){this.channel=t,this.presenceAdapter=new Sr(this.channel.channelAdapter,n)}}function dw(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);if(e&&typeof e=="object"){const t=e;if(typeof t.code=="number"){const n=typeof t.reason=="string"&&t.reason?` (${t.reason})`:"";return new Error(`socket closed: ${t.code}${n}`,{cause:e})}return new Error("channel error: transport failure",{cause:e})}return new Error("channel error: connection lost")}class hw{constructor(t,n,a){const s=fw(a);this.channel=t.getSocket().channel(n,s),this.socket=t}get state(){return this.channel.state}set state(t){this.channel.state=t}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(t,n){return this.channel.on(t,n)}off(t,n){this.channel.off(t,n)}subscribe(t){return this.channel.join(t)}unsubscribe(t){return this.channel.leave(t)}teardown(){this.channel.teardown()}onClose(t){this.channel.onClose(t)}onError(t){return this.channel.onError(t)}push(t,n,a){let s;try{s=this.channel.push(t,n,a)}catch{throw new Error(`tried to push '${t}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>K_){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return s}updateJoinPayload(t){const n=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},n),t)}canPush(){return this.socket.isConnected()&&this.state===ja.joined}isJoined(){return this.state===ja.joined}isJoining(){return this.state===ja.joining}isClosed(){return this.state===ja.closed}isLeaving(){return this.state===ja.leaving}updateFilterBindings(t){this.channel.filterBindings=t}updatePayloadTransform(t){this.channel.onMessage=t}getChannel(){return this.channel}}function fw(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}var Dp;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(Dp||(Dp={}));var si;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(si||(si={}));var aa;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(aa||(aa={}));class _r{get state(){return this.channelAdapter.state}set state(t){this.channelAdapter.state=t}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(t,n={config:{}},a){var s,i;if(this.topic=t,this.params=n,this.socket=a,this.bindings={},this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.channelAdapter=new hw(this.socket.socketAdapter,t,this.params),this.presence=new uw(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=pv(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(t,n=this.timeout){var a,s,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:r,presence:l,private:o}}=this.params,u=(s=(a=this.bindings.postgres_changes)===null||a===void 0?void 0:a.map(p=>p.filter))!==null&&s!==void 0?s:[],h=!!this.bindings[si.PRESENCE]&&this.bindings[si.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,f={},d={broadcast:r,presence:Object.assign(Object.assign({},l),{enabled:h}),postgres_changes:u,private:o};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(p=>{t==null||t(aa.CHANNEL_ERROR,dw(p))}),this._onClose(()=>t==null?void 0:t(aa.CLOSED)),this.updateJoinPayload(Object.assign({config:d},f)),this._updateFilterMessage(),this.channelAdapter.subscribe(n).receive("ok",async({postgres_changes:p})=>{if(this.socket._isManualToken()||this.socket.setAuth(),p===void 0){t==null||t(aa.SUBSCRIBED);return}this._updatePostgresBindings(p,t)}).receive("error",p=>{this.state=ja.errored;const v=Object.values(p).join(", ")||"error";t==null||t(aa.CHANNEL_ERROR,new Error(v,{cause:p}))}).receive("timeout",()=>{t==null||t(aa.TIMED_OUT)})}return this}_updatePostgresBindings(t,n){var a;const s=this.bindings.postgres_changes,i=(a=s==null?void 0:s.length)!==null&&a!==void 0?a:0,r=[];for(let l=0;l<i;l++){const o=s[l],{filter:{event:u,schema:h,table:f,filter:d}}=o,p=t&&t[l];if(p&&p.event===u&&_r.isFilterValueEqual(p.schema,h)&&_r.isFilterValueEqual(p.table,f)&&_r.isFilterValueEqual(p.filter,d))r.push(Object.assign(Object.assign({},o),{id:p.id}));else{this.unsubscribe(),this.state=ja.errored,n==null||n(aa.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=r,this.state!=ja.errored&&n&&n(aa.SUBSCRIBED)}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,a){const s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=t===si.PRESENCE||t===si.POSTGRES_CHANGES;if(s&&i)throw this.socket.log("channel",`cannot add \`${t}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${t}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(t,n,a)}async httpSend(t,n,a={}){var s;if(n==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i=n instanceof ArrayBuffer||ArrayBuffer.isView(n),r={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(r.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l=new URL(this.broadcastEndpointURL);l.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(t)}`,this.private&&l.searchParams.set("private","true");const o={method:"POST",headers:r,body:i?n:JSON.stringify(n)},u=await this._fetchWithTimeout(l.toString(),o,(s=a.timeout)!==null&&s!==void 0?s:this.timeout);if(u.status===202)return{success:!0};let h=u.statusText;try{const f=await u.json();h=f.error||f.message||h}catch{}return Promise.reject(new Error(h))}async send(t,n={}){var a,s;if(!this.channelAdapter.canPush()&&t.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:i,payload:r}=t,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:r,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(a=n.timeout)!==null&&a!==void 0?a:this.timeout);return await((s=u.body)===null||s===void 0?void 0:s.cancel()),u.ok?"ok":"error"}catch(u){return u instanceof Error&&u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var r,l,o;const u=this.channelAdapter.push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((o=(l=(r=this.params)===null||r===void 0?void 0:r.config)===null||l===void 0?void 0:l.broadcast)===null||o===void 0)&&o.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.channelAdapter.updateJoinPayload(t)}async unsubscribe(t=this.timeout){return new Promise(n=>{this.channelAdapter.unsubscribe(t).receive("ok",()=>n("ok")).receive("timeout",()=>n("timed out")).receive("error",()=>n("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(t,n,a){const s=new AbortController,i=setTimeout(()=>s.abort(),a),r=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:s.signal}));return clearTimeout(i),r}_on(t,n,a){const s=t.toLocaleLowerCase(),i=this.channelAdapter.on(t,a),r={type:s,filter:n,callback:a,ref:i};return this.bindings[s]?this.bindings[s].push(r):this.bindings[s]=[r],this._updateFilterMessage(),this}_onClose(t){this.channelAdapter.onClose(t)}_onError(t){this.channelAdapter.onError(t)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((t,n,a)=>{var s,i,r,l,o,u,h;const f=t.event.toLocaleLowerCase();if(this._notThisChannelEvent(f,a))return!1;const d=(s=this.bindings[f])===null||s===void 0?void 0:s.find(p=>p.ref===t.ref);if(!d)return!0;if(["broadcast","presence","postgres_changes"].includes(f))if("id"in d){const p=d.id,v=(i=d.filter)===null||i===void 0?void 0:i.event;return p&&((r=n.ids)===null||r===void 0?void 0:r.includes(p))&&(v==="*"||(v==null?void 0:v.toLocaleLowerCase())===((l=n.data)===null||l===void 0?void 0:l.type.toLocaleLowerCase()))}else{const p=(u=(o=d==null?void 0:d.filter)===null||o===void 0?void 0:o.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return p==="*"||p===((h=n==null?void 0:n.event)===null||h===void 0?void 0:h.toLocaleLowerCase())}else return d.type.toLocaleLowerCase()===f})}_notThisChannelEvent(t,n){const{close:a,error:s,leave:i,join:r}=hv;return n&&[a,s,i,r].includes(t)&&n!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((t,n,a)=>{if(typeof n=="object"&&"ids"in n){const s=n.data,{schema:i,table:r,commit_timestamp:l,type:o,errors:u}=s;return Object.assign(Object.assign({},{schema:i,table:r,commit_timestamp:l,eventType:o,new:{},old:{},errors:u}),this._getPayloadRecords(s))}return n})}copyBindings(t){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const n in t.bindings)for(const a of t.bindings[n])this._on(a.type,a.filter,a.callback)}static isFilterValueEqual(t,n){return(t??void 0)===(n??void 0)}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Np(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Np(t.columns,t.old_record)),n}}class pw{constructor(t,n){this.socket=new lw(t,n)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(t){this.socket.heartbeatCallback=t}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(t,n,a,s=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),s),this.socket.disconnect(()=>{t(),i("ok")},n,a)})}push(t){this.socket.push(t)}log(t,n,a){this.socket.log(t,n,a)}makeRef(){return this.socket.makeRef()}onOpen(t){this.socket.onOpen(t)}onClose(t){this.socket.onClose(t)}onError(t){this.socket.onError(t)}onMessage(t){this.socket.onMessage(t)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==md.connecting}isDisconnecting(){return this.socket.connectionState()==md.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Mp={HEARTBEAT_INTERVAL:25e3},mw=[1e3,2e3,5e3,1e4],gw=1e4;function yw(){const e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.has(t)?e.get(t):null},key(t){var n;return(n=Array.from(e.keys())[t])!==null&&n!==void 0?n:null},removeItem(t){e.delete(t)},setItem(t,n){e.set(t,String(n))}}}function vw(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return yw()}const bw=`
52
+ addEventListener("message", (e) => {
53
+ if (e.data.event === "start") {
54
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
55
+ }
56
+ });`;class Sw{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(t,n){var a;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new V_,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...r)=>i(...r):(...r)=>fetch(...r),!(!((a=n==null?void 0:n.params)===null||a===void 0)&&a.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=n.params.apikey;const s=this._initializeOptions(n);this.socketAdapter=new pw(t,s),this.httpEndpoint=pv(t),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){const n=t.message;throw n.includes("Node.js")?new Error(`${n}
57
+
58
+ To use Realtime in Node.js, you need to provide a WebSocket implementation:
59
+
60
+ Option 1: Use Node.js 22+ which has native WebSocket support
61
+ Option 2: Install and provide the "ws" package:
62
+
63
+ npm install ws
64
+
65
+ import ws from "ws"
66
+ const client = new RealtimeClient(url, {
67
+ ...options,
68
+ transport: ws
69
+ })`):new Error(`WebSocket not available: ${n}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(t,n){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},t,n)}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return n==="ok"&&t.teardown(),n}async removeAllChannels(){const t=this.channels.map(async a=>{const s=await a.unsubscribe();return a.teardown(),s}),n=await Promise.all(t);return await this.disconnect(),n}log(t,n,a){this.socketAdapter.log(t,n,a)}connectionState(){return this.socketAdapter.connectionState()||md.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(t,n={config:{}}){const a=`realtime:${t}`,s=this.getChannels().find(i=>i.topic===a);if(s)return s;{const i=new _r(`realtime:${t}`,n,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(t){this.socketAdapter.push(t)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(t){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(t)}_makeRef(){return this.socketAdapter.makeRef()}_remove(t){this.channels=this.channels.filter(n=>n.topic!==t.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(t=null){let n,a=!1;if(t)n=t,a=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),n=this.accessTokenValue}else n=this.accessTokenValue;a?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(s=>{const i={access_token:n,version:$_};n&&s.updateJoinPayload(i),s.joinedOnce&&s.channelAdapter.isJoined()&&s.channelAdapter.push(hv.access_token,{access_token:n})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(n=>{this.log("error",`Error setting auth in ${t}`,n)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(n=>{this.log("error","error waiting for auth on connect",n)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(t=>{t.ref&&t.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(t){return(n,a)=>{n=="sent"&&this._setAuthSafely(),t&&t(n,a)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=n=>{n.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(t){let n;if(t)n=t;else{const a=new Blob([bw],{type:"application/javascript"});n=URL.createObjectURL(a)}return n}_initializeOptions(t){var n,a,s,i,r,l,o,u,h,f,d,p;this.worker=(n=t==null?void 0:t.worker)!==null&&n!==void 0?n:!1,this.accessToken=(a=t==null?void 0:t.accessToken)!==null&&a!==void 0?a:null;const v={};v.timeout=(s=t==null?void 0:t.timeout)!==null&&s!==void 0?s:G_,v.heartbeatIntervalMs=(i=t==null?void 0:t.heartbeatIntervalMs)!==null&&i!==void 0?i:Mp.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(r=t==null?void 0:t.disconnectOnEmptyChannelsAfterMs)!==null&&r!==void 0?r:2*((l=t==null?void 0:t.heartbeatIntervalMs)!==null&&l!==void 0?l:Mp.HEARTBEAT_INTERVAL),v.transport=(o=t==null?void 0:t.transport)!==null&&o!==void 0?o:I_.getWebSocketConstructor(),v.params=t==null?void 0:t.params,v.logger=t==null?void 0:t.logger,v.heartbeatCallback=this._wrapHeartbeatCallback(t==null?void 0:t.heartbeatCallback),v.sessionStorage=(u=t==null?void 0:t.sessionStorage)!==null&&u!==void 0?u:vw(),v.reconnectAfterMs=(h=t==null?void 0:t.reconnectAfterMs)!==null&&h!==void 0?h:m=>mw[m-1]||gw;let _,x;const g=(f=t==null?void 0:t.vsn)!==null&&f!==void 0?f:q_;switch(g){case P_:_=(m,y)=>y(JSON.stringify(m)),x=(m,y)=>y(JSON.parse(m));break;case dv:_=this.serializer.encode.bind(this.serializer),x=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${v.vsn}`)}if(v.vsn=g,v.encode=(d=t==null?void 0:t.encode)!==null&&d!==void 0?d:_,v.decode=(p=t==null?void 0:t.decode)!==null&&p!==void 0?p:x,v.beforeReconnect=this._reconnectAuth.bind(this),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,v.params=Object.assign(Object.assign({},v.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl,v.autoSendHeartbeat=!this.worker}return v}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var zr=class extends Error{constructor(e,t){var n;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&((n=t.icebergType)==null?void 0:n.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function _w(e,t,n){const a=new URL(t,e);if(n)for(const[s,i]of Object.entries(n))i!==void 0&&a.searchParams.set(s,i);return a.toString()}async function ww(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function xw(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:a,query:s,body:i,headers:r}){const l=_w(e.baseUrl,a,s),o=await ww(e.auth),u=await t(l,{method:n,headers:{...i?{"Content-Type":"application/json"}:{},...o,...r},body:i?JSON.stringify(i):void 0}),h=await u.text(),f=(u.headers.get("content-type")||"").includes("application/json"),d=f&&h?JSON.parse(h):h;if(!u.ok){const p=f?d:void 0,v=p==null?void 0:p.error;throw new zr((v==null?void 0:v.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:v==null?void 0:v.type,icebergCode:v==null?void 0:v.code,details:p})}return{status:u.status,headers:u.headers,data:d}}}}function jl(e){return e.join("")}var Tw=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:jl(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(a=>({namespace:a}))}async createNamespace(e,t){const n={namespace:e.namespace,properties:t==null?void 0:t.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${jl(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${jl(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${jl(e.namespace)}`}),!0}catch(t){if(t instanceof zr&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(n){if(n instanceof zr&&n.status===409)return;throw n}}};function Us(e){return e.join("")}var Ew=class{constructor(e,t="",n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Us(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Us(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Us(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Us(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((t==null?void 0:t.purge)??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Us(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Us(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(n){if(n instanceof zr&&n.status===404)return!1;throw n}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof zr&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Aw=class{constructor(e){var a;let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const n=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=xw({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(a=e.accessDelegation)==null?void 0:a.join(","),this.namespaceOps=new Tw(this.client,t),this.tableOps=new Ew(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};function Br(e){"@babel/helpers - typeof";return Br=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Br(e)}function Cw(e,t){if(Br(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(Br(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ow(e){var t=Cw(e,"string");return Br(t)=="symbol"?t:t+""}function Rw(e,t,n){return(t=Ow(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Up(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,a)}return n}function Z(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Up(Object(n),!0).forEach(function(a){Rw(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Up(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}var lc=class extends Error{constructor(e,t="storage",n,a){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=n,this.statusCode=a}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function oc(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}var bd=class extends lc{constructor(e,t,n,a="storage"){super(e,a,t,n),this.name=a==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=n}toJSON(){return Z({},super.toJSON())}},gv=class extends lc{constructor(e,t,n="storage"){super(e,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function Uo(e,t,n){const a=Z({},e),s=t.toLowerCase();for(const i of Object.keys(a))i.toLowerCase()===s&&delete a[i];return a[s]=n,a}function Nw(e){const t={};for(const[n,a]of Object.entries(e))t[n.toLowerCase()]=a;return t}const kw=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),jw=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Sd=e=>{if(Array.isArray(e))return e.map(n=>Sd(n));if(typeof e=="function"||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([n,a])=>{const s=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[s]=Sd(a)}),t},Dw=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),Lp=e=>{if(typeof e=="object"&&e!==null){const t=e;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message;if(typeof t.error_description=="string")return t.error_description;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const n=t.error;if(typeof n.message=="string")return n.message}}return JSON.stringify(e)},Mw=async(e,t,n,a)=>{if(e!==null&&typeof e=="object"&&"json"in e&&typeof e.json=="function"){const s=e;let i=parseInt(String(s.status),10);Number.isFinite(i)||(i=500),s.json().then(r=>{const l=(r==null?void 0:r.statusCode)||(r==null?void 0:r.code)||i+"";t(new bd(Lp(r),i,l,a))}).catch(()=>{const r=i+"";t(new bd(s.statusText||`HTTP ${i} error`,i,r,a))})}else t(new gv(Lp(e),e,a))},Uw=(e,t,n,a)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};if(e==="GET"||e==="HEAD"||!a)return Z(Z({},s),n);if(jw(a)){var i;const r=(t==null?void 0:t.headers)||{};let l;for(const[o,u]of Object.entries(r))o.toLowerCase()==="content-type"&&(l=u);s.headers=Uo(r,"Content-Type",(i=l)!==null&&i!==void 0?i:"application/json"),s.body=JSON.stringify(a)}else s.body=a;return t!=null&&t.duplex&&(s.duplex=t.duplex),Z(Z({},s),n)};async function Xi(e,t,n,a,s,i,r){return new Promise((l,o)=>{e(n,Uw(t,a,s,i)).then(u=>{if(!u.ok)throw u;if(a!=null&&a.noResolveJson)return u;if(r==="vectors"){const h=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!h||!h.includes("application/json"))return{}}return u.json()}).then(u=>l(u)).catch(u=>Mw(u,o,a,r))})}function yv(e="storage"){return{get:async(t,n,a,s)=>Xi(t,"GET",n,a,s,void 0,e),post:async(t,n,a,s,i)=>Xi(t,"POST",n,s,i,a,e),put:async(t,n,a,s,i)=>Xi(t,"PUT",n,s,i,a,e),head:async(t,n,a,s)=>Xi(t,"HEAD",n,Z(Z({},a),{},{noResolveJson:!0}),s,void 0,e),remove:async(t,n,a,s,i)=>Xi(t,"DELETE",n,s,i,a,e)}}const Lw=yv("storage"),{get:Ir,post:Rn,put:_d,head:zw,remove:Ah}=Lw,tn=yv("vectors");var ji=class{constructor(e,t={},n,a="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=Nw(t),this.fetch=kw(n),this.namespace=a}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Uo(this.headers,e,t),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(n){if(t.shouldThrowOnError)throw n;if(oc(n))return{data:null,error:n};throw n}}};let vv;vv=Symbol.toStringTag;var Bw=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[vv]="StreamDownloadBuilder",this.promise=null}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(oc(t))return{data:null,error:t};throw t}}};let bv;bv=Symbol.toStringTag;var Iw=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[bv]="BlobDownloadBuilder",this.promise=null}asStream(){return new Bw(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(oc(t))return{data:null,error:t};throw t}}};const Hw={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},zp={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var $w=class extends ji{constructor(e,t={},n,a){super(e,t,a,"storage"),this.bucketId=n}async uploadOrUpdate(e,t,n,a){var s=this;return s.handleOperation(async()=>{let i;const r=Z(Z({},zp),a);let l=Z(Z({},s.headers),e==="POST"&&{"x-upsert":String(r.upsert)});const o=r.metadata;if(typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",r.cacheControl),o&&i.append("metadata",s.encodeMetadata(o)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.has("cacheControl")||i.append("cacheControl",r.cacheControl),o&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(o))):(i=n,l["cache-control"]=`max-age=${r.cacheControl}`,l["content-type"]=r.contentType,o&&(l["x-metadata"]=s.toBase64(s.encodeMetadata(o))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!r.duplex&&(r.duplex="half")),a!=null&&a.headers)for(const[d,p]of Object.entries(a.headers))l=Uo(l,d,p);const u=s._removeEmptyFolders(t),h=s._getFinalPath(u),f=await(e=="PUT"?_d:Rn)(s.fetch,`${s.url}/object/${h}`,i,Z({headers:l},r!=null&&r.duplex?{duplex:r.duplex}:{}));return{path:u,id:f.Id,fullPath:f.Key}})}async upload(e,t,n){return this.uploadOrUpdate("POST",e,t,n)}async uploadToSignedUrl(e,t,n,a){var s=this;const i=s._removeEmptyFolders(e),r=s._getFinalPath(i),l=new URL(s.url+`/object/upload/sign/${r}`);return l.searchParams.set("token",t),s.handleOperation(async()=>{let o;const u=Z(Z({},zp),a);let h=Z(Z({},s.headers),{"x-upsert":String(u.upsert)});const f=u.metadata;if(typeof Blob<"u"&&n instanceof Blob?(o=new FormData,o.append("cacheControl",u.cacheControl),f&&o.append("metadata",s.encodeMetadata(f)),o.append("",n)):typeof FormData<"u"&&n instanceof FormData?(o=n,o.has("cacheControl")||o.append("cacheControl",u.cacheControl),f&&!o.has("metadata")&&o.append("metadata",s.encodeMetadata(f))):(o=n,h["cache-control"]=`max-age=${u.cacheControl}`,h["content-type"]=u.contentType,f&&(h["x-metadata"]=s.toBase64(s.encodeMetadata(f))),(typeof ReadableStream<"u"&&o instanceof ReadableStream||o&&typeof o=="object"&&"pipe"in o&&typeof o.pipe=="function")&&!u.duplex&&(u.duplex="half")),a!=null&&a.headers)for(const[d,p]of Object.entries(a.headers))h=Uo(h,d,p);return{path:i,fullPath:(await _d(s.fetch,l.toString(),o,Z({headers:h},u!=null&&u.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let a=n._getFinalPath(e);const s=Z({},n.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");const i=await Rn(n.fetch,`${n.url}/object/upload/sign/${a}`,{},{headers:s}),r=new URL(n.url+i.url),l=r.searchParams.get("token");if(!l)throw new lc("No token returned by API");return{signedUrl:r.toString(),path:e,token:l}})}async update(e,t,n){return this.uploadOrUpdate("PUT",e,t,n)}async move(e,t,n){var a=this;return a.handleOperation(async()=>await Rn(a.fetch,`${a.url}/object/move`,{bucketId:a.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:a.headers}))}async copy(e,t,n){var a=this;return a.handleOperation(async()=>({path:(await Rn(a.fetch,`${a.url}/object/copy`,{bucketId:a.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:a.headers})).Key}))}async createSignedUrl(e,t,n){var a=this;return a.handleOperation(async()=>{let s=a._getFinalPath(e);const i=typeof(n==null?void 0:n.transform)=="object"&&n.transform!==null&&Object.keys(n.transform).length>0;let r=await Rn(a.fetch,`${a.url}/object/sign/${s}`,Z({expiresIn:t},i?{transform:n.transform}:{}),{headers:a.headers});const l=new URLSearchParams;n!=null&&n.download&&l.set("download",n.download===!0?"":n.download),(n==null?void 0:n.cacheNonce)!=null&&l.set("cacheNonce",String(n.cacheNonce));const o=l.toString();return{signedUrl:encodeURI(`${a.url}${r.signedURL}${o?`&${o}`:""}`)}})}async createSignedUrls(e,t,n){var a=this;return a.handleOperation(async()=>{const s=await Rn(a.fetch,`${a.url}/object/sign/${a.bucketId}`,{expiresIn:t,paths:e},{headers:a.headers}),i=new URLSearchParams;n!=null&&n.download&&i.set("download",n.download===!0?"":n.download),(n==null?void 0:n.cacheNonce)!=null&&i.set("cacheNonce",String(n.cacheNonce));const r=i.toString();return s.map(l=>Z(Z({},l),{},{signedUrl:l.signedURL?encodeURI(`${a.url}${l.signedURL}${r?`&${r}`:""}`):null}))})}download(e,t,n){const a=typeof(t==null?void 0:t.transform)=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",s=new URLSearchParams;t!=null&&t.transform&&this.applyTransformOptsToQuery(s,t.transform),(t==null?void 0:t.cacheNonce)!=null&&s.set("cacheNonce",String(t.cacheNonce));const i=s.toString(),r=this._getFinalPath(e),l=()=>Ir(this.fetch,`${this.url}/${a}/${r}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},n);return new Iw(l,this.shouldThrowOnError)}async info(e){var t=this;const n=t._getFinalPath(e);return t.handleOperation(async()=>Sd(await Ir(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;const n=t._getFinalPath(e);try{return await zw(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(s){if(t.shouldThrowOnError)throw s;if(oc(s)){var a;const i=s instanceof bd?s.status:s instanceof gv?(a=s.originalError)===null||a===void 0?void 0:a.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:s}}throw s}}getPublicUrl(e,t){const n=this._getFinalPath(e),a=new URLSearchParams;t!=null&&t.download&&a.set("download",t.download===!0?"":t.download),t!=null&&t.transform&&this.applyTransformOptsToQuery(a,t.transform),(t==null?void 0:t.cacheNonce)!=null&&a.set("cacheNonce",String(t.cacheNonce));const s=a.toString(),i=typeof(t==null?void 0:t.transform)=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${n}`)+(s?`?${s}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await Ah(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,n){var a=this;return a.handleOperation(async()=>{const s=Z(Z(Z({},Hw),t),{},{prefix:e||""});return await Rn(a.fetch,`${a.url}/object/list/${a.bucketId}`,s,{headers:a.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{const a=Z({},e);return await Rn(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,a,{headers:n.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("quality",t.quality.toString()),e}};const Pw="2.107.0",al={"X-Client-Info":`storage-js/${Pw}`};var qw=class extends ji{constructor(e,t={},n,a){const s=new URL(e);a!=null&&a.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));const i=s.href.replace(/\/$/,""),r=Z(Z({},al),t);super(i,r,n,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=t.listBucketOptionsToQueryString(e);return await Ir(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Ir(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await Rn(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await _d(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await Rn(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Ah(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},Gw=class extends ji{constructor(e,t={},n){const a=e.replace(/\/$/,""),s=Z(Z({},al),t);super(a,s,n,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await Rn(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&n.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&n.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&n.set("sortOrder",e.sortOrder),e!=null&&e.search&&n.set("search",e.search);const a=n.toString(),s=a?`${t.url}/bucket?${a}`:`${t.url}/bucket`;return await Ir(t.fetch,s,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Ah(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!Dw(e))throw new lc("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 n=new Aw({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),a=this.shouldThrowOnError;return new Proxy(n,{get(s,i){const r=s[i];return typeof r!="function"?r:async(...l)=>{try{return{data:await r.apply(s,l),error:null}}catch(o){if(a)throw o;return{data:null,error:o}}}}})}},Kw=class extends ji{constructor(e,t={},n){const a=e.replace(/\/$/,""),s=Z(Z({},al),{},{"Content-Type":"application/json"},t);super(a,s,n,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await tn.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await tn.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},Vw=class extends ji{constructor(e,t={},n){const a=e.replace(/\/$/,""),s=Z(Z({},al),{},{"Content-Type":"application/json"},t);super(a,s,n,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},Yw=class extends ji{constructor(e,t={},n){const a=e.replace(/\/$/,""),s=Z(Z({},al),{},{"Content-Type":"application/json"},t);super(a,s,n,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await tn.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},Fw=class extends Yw{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Jw(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},Jw=class extends Kw{constructor(e,t,n,a){super(e,t,a),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,Z(Z({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,Z(Z({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new Xw(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Xw=class extends Vw{constructor(e,t,n,a,s){super(e,t,s),this.vectorBucketName=n,this.indexName=a}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,Z(Z({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,Z(Z({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,Z(Z({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,Z(Z({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,Z(Z({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},Qw=class extends qw{constructor(e,t={},n,a){super(e,t,n,a)}from(e){return new $w(this.url,this.headers,e,this.fetch)}get vectors(){return new Fw(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Gw(this.url+"/iceberg",this.headers,this.fetch)}};const Sv="2.107.0",Ta=30*1e3,sr=3,iu=sr*Ta,Ww="http://localhost:9999",Zw="supabase.auth.token",ex={"X-Client-Info":`gotrue-js/${Sv}`},wd="X-Supabase-Api-Version",_v={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},tx=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,nx=10*60*1e3;class Hr extends Error{constructor(t,n,a){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=a}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function P(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class ax extends Hr{constructor(t,n,a){super(t,n,a),this.name="AuthApiError",this.status=n,this.code=a}}function sx(e){return P(e)&&e.name==="AuthApiError"}class kn extends Hr{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class Kn extends Hr{constructor(t,n,a,s){super(t,a,s),this.name=n,this.status=a}}class St extends Kn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Dl(e){return P(e)&&e.name==="AuthSessionMissingError"}class Ls extends Kn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Ml extends Kn{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class Ul extends Kn{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function ix(e){return P(e)&&e.name==="AuthImplicitGrantRedirectError"}class Bp extends Kn{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class rx extends Kn{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 xd extends Kn{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function ru(e){return P(e)&&e.name==="AuthRetryableFetchError"}class Ip extends Kn{constructor(t="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(t,"AuthRefreshDiscardedError",409,void 0)}}function lx(e){return P(e)&&e.name==="AuthRefreshDiscardedError"}class Hp extends Kn{constructor(t,n,a){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=a}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class Lo extends Kn{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const zo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),$p=`
70
+ \r=`.split(""),ox=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<$p.length;t+=1)e[$p[t].charCodeAt(0)]=-2;for(let t=0;t<zo.length;t+=1)e[zo[t].charCodeAt(0)]=t;return e})();function Pp(e,t,n){if(e!==null)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const a=t.queue>>t.queuedBits-6&63;n(zo[a]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const a=t.queue>>t.queuedBits-6&63;n(zo[a]),t.queuedBits-=6}}function wv(e,t,n){const a=ox[e];if(a>-1)for(t.queue=t.queue<<6|a,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(a===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function qp(e){const t=[],n=r=>{t.push(String.fromCodePoint(r))},a={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=r=>{dx(r,a,n)};for(let r=0;r<e.length;r+=1)wv(e.charCodeAt(r),s,i);return t.join("")}function cx(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function ux(e,t){for(let n=0;n<e.length;n+=1){let a=e.charCodeAt(n);if(a>55295&&a<=56319){const s=(a-55296)*1024&65535;a=(e.charCodeAt(n+1)-56320&65535|s)+65536,n+=1}cx(a,t)}}function dx(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let a=1;a<6;a+=1)if(!(e>>7-a&1)){t.utf8seq=a;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function fi(e){const t=[],n={queue:0,queuedBits:0},a=s=>{t.push(s)};for(let s=0;s<e.length;s+=1)wv(e.charCodeAt(s),n,a);return new Uint8Array(t)}function hx(e){const t=[];return ux(e,n=>t.push(n)),new Uint8Array(t)}function hs(e){const t=[],n={queue:0,queuedBits:0},a=s=>{t.push(s)};return e.forEach(s=>Pp(s,n,a)),Pp(null,n,a),t.join("")}function fx(e){return Math.round(Date.now()/1e3)+e}function px(){return Symbol("auth-callback")}const Ut=()=>typeof window<"u"&&typeof document<"u",rs={tested:!1,writable:!1},xv=()=>{if(!Ut())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(rs.tested)return rs.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),rs.tested=!0,rs.writable=!0}catch{rs.tested=!0,rs.writable=!1}return rs.writable};function mx(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((s,i)=>{t[i]=s})}catch{}return n.searchParams.forEach((a,s)=>{t[s]=a}),t}const Tv=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),gx=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",Ks=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Wn=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return null}},pt=async(e,t)=>{await e.removeItem(t)};class cc{constructor(){this.promise=new cc.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}cc.promiseConstructor=Promise;function Ll(e){const t=e.split(".");if(t.length!==3)throw new Lo("Invalid JWT structure");for(let a=0;a<t.length;a++)if(!tx.test(t[a]))throw new Lo("JWT not in base64url format");return{header:JSON.parse(qp(t[0])),payload:JSON.parse(qp(t[1])),signature:fi(t[2]),raw:{header:t[0],payload:t[1]}}}async function yx(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function vx(e,t){return new Promise((a,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const r=await e(i);if(!t(i,null,r)){a(r);return}}catch(r){if(!t(i,r)){s(r);return}}})()})}function bx(e){return("0"+e.toString(16)).substr(-2)}function Sx(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",a=n.length;let s="";for(let i=0;i<56;i++)s+=n.charAt(Math.floor(Math.random()*a));return s}return crypto.getRandomValues(t),Array.from(t,bx).join("")}async function _x(e){const n=new TextEncoder().encode(e),a=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(a);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function wx(e){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."),e;const n=await _x(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function zs(e,t,n=!1){const a=Sx();let s=a;n&&(s+="/recovery"),await Ks(e,`${t}-code-verifier`,s);const i=await wx(a);return[i,a===i?"plain":"s256"]}const xx=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Tx(e){const t=e.headers.get(wd);if(!t||!t.match(xx))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Ex(e){if(!e)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function Ax(e){switch(e){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 Cx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Zn(e){if(!Cx.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function On(e){if(!e.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function lu(){const e={};return new Proxy(e,{get:(t,n)=>{if(n==="__isUserNotAvailableProxy")return!0;if(typeof n=="symbol"){const a=n.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="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 "${n}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Ox(e,t){return new Proxy(e,{get:(n,a,s)=>{if(a==="__isInsecureUserWarningProxy")return!0;if(typeof a=="symbol"){const i=a.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,a,s)}return!t.value&&typeof a=="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."),t.value=!0),Reflect.get(n,a,s)}})}function Gp(e){return JSON.parse(JSON.stringify(e))}const ds=e=>{if(typeof e=="object"&&e!==null){const t=e;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message;if(typeof t.error_description=="string")return t.error_description;if(typeof t.error=="string")return t.error}return JSON.stringify(e)},Rx=[502,503,504,520,521,522,523,524,530];async function Kp(e){var t;if(!gx(e))throw new xd(ds(e),0);if(Rx.includes(e.status))throw new xd(ds(e),e.status);let n;try{n=await e.json()}catch(i){throw new kn(ds(i),i)}let a;const s=Tx(e);if(s&&s.getTime()>=_v["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?a=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(a=n.error_code),a){if(a==="weak_password")throw new Hp(ds(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(a==="session_not_found")throw new St}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((i,r)=>i&&typeof r=="string",!0))throw new Hp(ds(n),e.status,n.weak_password.reasons);throw new ax(ds(n),e.status||500,a)}const Nx=(e,t,n,a)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),s.body=JSON.stringify(a),Object.assign(Object.assign({},s),n))};async function Y(e,t,n,a){var s;const i=Object.assign({},a==null?void 0:a.headers);i[wd]||(i[wd]=_v["2024-01-01"].name),a!=null&&a.jwt&&(i.Authorization=`Bearer ${a.jwt}`);const r=(s=a==null?void 0:a.query)!==null&&s!==void 0?s:{};a!=null&&a.redirectTo&&(r.redirect_to=a.redirectTo);const l=Object.keys(r).length?"?"+new URLSearchParams(r).toString():"",o=await kx(e,t,n+l,{headers:i,noResolveJson:a==null?void 0:a.noResolveJson},{},a==null?void 0:a.body);return a!=null&&a.xform?a==null?void 0:a.xform(o):{data:Object.assign({},o),error:null}}async function kx(e,t,n,a,s,i){const r=Nx(t,a,s,i);let l;try{l=await e(n,Object.assign({},r))}catch(o){throw console.error(o),new xd(ds(o),0)}if(l.ok||await Kp(l),a!=null&&a.noResolveJson)return l;try{return await l.json()}catch(o){await Kp(o)}}function hn(e){var t;let n=null;Mx(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=fx(e.expires_in)));const a=(t=e.user)!==null&&t!==void 0?t:typeof(e==null?void 0:e.id)=="string"?e:null;return{data:{session:n,user:a},error:null}}function Vp(e){const t=hn(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,a)=>n&&typeof a=="string",!0)&&(t.data.weak_password=e.weak_password),t}function Da(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function jx(e){return{data:e,error:null}}function Dx(e){const{action_link:t,email_otp:n,hashed_token:a,redirect_to:s,verification_type:i}=e,r=rc(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:n,hashed_token:a,redirect_to:s,verification_type:i},o=Object.assign({},r);return{data:{properties:l,user:o},error:null}}function Yp(e){return e}function Mx(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in}const ou=["global","local","others"];class Ux{constructor({url:t="",headers:n={},fetch:a,experimental:s}){this.url=t,this.headers=n,this.fetch=Tv(a),this.experimental=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)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(t,n=ou[0]){if(ou.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ou.join(", ")}`);try{return await Y(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(a){if(P(a))return{data:null,error:a};throw a}}async inviteUserByEmail(t,n={}){try{return await Y(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:Da})}catch(a){if(P(a))return{data:{user:null},error:a};throw a}}async generateLink(t){try{const{options:n}=t,a=rc(t,["options"]),s=Object.assign(Object.assign({},a),n);return"newEmail"in a&&(s.new_email=a==null?void 0:a.newEmail,delete s.newEmail),await Y(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Dx,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(P(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await Y(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:Da})}catch(n){if(P(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,a,s,i,r,l,o;try{const u={nextPage:null,lastPage:0,total:0},h=await Y(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Yp});if(h.error)throw h.error;const f=await h.json(),d=(r=h.headers.get("x-total-count"))!==null&&r!==void 0?r:0,p=(o=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&o!==void 0?o:[];return p.length>0&&(p.forEach(v=>{const _=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(v.split(";")[1].split("=")[1]);u[`${x}Page`]=_}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(P(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){Zn(t);try{return await Y(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:Da})}catch(n){if(P(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){Zn(t);try{return await Y(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:Da})}catch(a){if(P(a))return{data:{user:null},error:a};throw a}}async deleteUser(t,n=!1){Zn(t);try{return await Y(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:Da})}catch(a){if(P(a))return{data:{user:null},error:a};throw a}}async _listFactors(t){Zn(t.userId);try{const{data:n,error:a}=await Y(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:n,error:a}}catch(n){if(P(n))return{data:null,error:n};throw n}}async _deleteFactor(t){Zn(t.userId),Zn(t.id);try{return{data:await Y(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(P(n))return{data:null,error:n};throw n}}async _listOAuthClients(t){var n,a,s,i,r,l,o;try{const u={nextPage:null,lastPage:0,total:0},h=await Y(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Yp});if(h.error)throw h.error;const f=await h.json(),d=(r=h.headers.get("x-total-count"))!==null&&r!==void 0?r:0,p=(o=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&o!==void 0?o:[];return p.length>0&&(p.forEach(v=>{const _=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(v.split(";")[1].split("=")[1]);u[`${x}Page`]=_}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(P(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(t){try{return await Y(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(P(n))return{data:null,error:n};throw n}}async _getOAuthClient(t){try{return await Y(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(P(n))return{data:null,error:n};throw n}}async _updateOAuthClient(t,n){try{return await Y(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:n,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(P(a))return{data:null,error:a};throw a}}async _deleteOAuthClient(t){try{return await Y(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(P(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(t){try{return await Y(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(P(n))return{data:null,error:n};throw n}}async _listCustomProviders(t){try{const n={};return t!=null&&t.type&&(n.type=t.type),await Y(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:n,xform:a=>{var s;return{data:{providers:(s=a==null?void 0:a.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(n){if(P(n))return{data:{providers:[]},error:n};throw n}}async _createCustomProvider(t){try{return await Y(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(P(n))return{data:null,error:n};throw n}}async _getCustomProvider(t){try{return await Y(this.fetch,"GET",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(P(n))return{data:null,error:n};throw n}}async _updateCustomProvider(t,n){try{return await Y(this.fetch,"PUT",`${this.url}/admin/custom-providers/${t}`,{body:n,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(P(a))return{data:null,error:a};throw a}}async _deleteCustomProvider(t){try{return await Y(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(P(n))return{data:null,error:n};throw n}}async _adminListPasskeys(t){On(this.experimental),Zn(t.userId);try{return await Y(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/passkeys`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(P(n))return{data:null,error:n};throw n}}async _adminDeletePasskey(t){On(this.experimental),Zn(t.userId),Zn(t.passkeyId);try{return await Y(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/passkeys/${t.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(P(n))return{data:null,error:n};throw n}}}function Fp(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}globalThis&&xv()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class Lx extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}function zx(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Ev(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Bx(e){return parseInt(e,16)}function Ix(e){const t=new TextEncoder().encode(e);return"0x"+Array.from(t,a=>a.toString(16).padStart(2,"0")).join("")}function Hx(e){var t;const{chainId:n,domain:a,expirationTime:s,issuedAt:i=new Date,nonce:r,notBefore:l,requestId:o,resources:u,scheme:h,uri:f,version:d}=e;{if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!a)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(r&&r.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${r}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(d!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(`
71
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const p=Ev(e.address),v=h?`${h}://${a}`:a,_=e.statement?`${e.statement}
72
+ `:"",x=`${v} wants you to sign in with your Ethereum account:
73
+ ${p}
74
+
75
+ ${_}`;let g=`URI: ${f}
76
+ Version: ${d}
77
+ Chain ID: ${n}${r?`
78
+ Nonce: ${r}`:""}
79
+ Issued At: ${i.toISOString()}`;if(s&&(g+=`
80
+ Expiration Time: ${s.toISOString()}`),l&&(g+=`
81
+ Not Before: ${l.toISOString()}`),o&&(g+=`
82
+ Request ID: ${o}`),u){let m=`
83
+ Resources:`;for(const y of u){if(!y||typeof y!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${y}`);m+=`
84
+ - ${y}`}g+=m}return`${x}
85
+ ${g}`}class lt extends Error{constructor({message:t,code:n,cause:a,name:s}){var i;super(t,{cause:a}),this.__isWebAuthnError=!0,this.name=(i=s??(a instanceof Error?a.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=n}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Bo extends lt{constructor(t,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:t}),this.name="WebAuthnUnknownError",this.originalError=n}}function $x({error:e,options:t}){var n,a,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new lt({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new lt({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((a=i.authenticatorSelection)===null||a===void 0?void 0:a.userVerification)==="required")return new lt({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new lt({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new lt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new lt({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new lt({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new lt({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const r=window.location.hostname;if(Av(r)){if(i.rp.id!==r)return new lt({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new lt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new lt({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new lt({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new lt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Px({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new lt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new lt({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const a=window.location.hostname;if(Av(a)){if(n.rpId!==a)return new lt({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new lt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new lt({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new lt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class qx{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}}const Td=new qx;function Jp(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:a}=e,s=rc(e,["challenge","user","excludeCredentials"]),i=fi(t).buffer,r=Object.assign(Object.assign({},n),{id:fi(n.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:r});if(a&&a.length>0){l.excludeCredentials=new Array(a.length);for(let o=0;o<a.length;o++){const u=a[o];l.excludeCredentials[o]=Object.assign(Object.assign({},u),{id:fi(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return l}function Xp(e){if(!e)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:n}=e,a=rc(e,["challenge","allowCredentials"]),s=fi(t).buffer,i=Object.assign(Object.assign({},a),{challenge:s});if(n&&n.length>0){i.allowCredentials=new Array(n.length);for(let r=0;r<n.length;r++){const l=n[r];i.allowCredentials[r]=Object.assign(Object.assign({},l),{id:fi(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function Qp(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const n=e;return{id:e.id,rawId:e.id,response:{attestationObject:hs(new Uint8Array(e.response.attestationObject)),clientDataJSON:hs(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(t=n.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function Wp(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const n=e,a=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:hs(new Uint8Array(s.authenticatorData)),clientDataJSON:hs(new Uint8Array(s.clientDataJSON)),signature:hs(new Uint8Array(s.signature)),userHandle:s.userHandle?hs(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:a,authenticatorAttachment:(t=n.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function Av(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Io(){var e,t;return!!(Ut()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.create)=="function"&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.get)=="function")}async function Cv(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Bo("Browser returned unexpected credential type",t)}:{data:null,error:new Bo("Empty credential response",t)}}catch(t){return{data:null,error:$x({error:t,options:e})}}}async function Ov(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Bo("Browser returned unexpected credential type",t)}:{data:null,error:new Bo("Empty credential response",t)}}catch(t){return{data:null,error:Px({error:t,options:e})}}}const Gx={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Kx={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ho(...e){const t=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),n=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),a={};for(const s of e)if(s)for(const i in s){const r=s[i];if(r!==void 0)if(Array.isArray(r))a[i]=r;else if(n(r))a[i]=r;else if(t(r)){const l=a[i];t(l)?a[i]=Ho(l,r):a[i]=Ho(r)}else a[i]=r}return a}function Vx(e,t){return Ho(Gx,e,t||{})}function Yx(e,t){return Ho(Kx,e,t||{})}class Fx{constructor(t){this.client=t,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:n,friendlyName:a,signal:s},i){var r;try{const{data:l,error:o}=await this.client.mfa.challenge({factorId:t,webauthn:n});if(!l)return{data:null,error:o};const u=s??Td.createNewAbortSignal();if(l.webauthn.type==="create"){const{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){const f=a;if(f)h.name=`${h.id}:${f}`;else{const p=(await this.client.getUser()).data.user,v=((r=p==null?void 0:p.user_metadata)===null||r===void 0?void 0:r.name)||(p==null?void 0:p.email)||(p==null?void 0:p.id)||"User";h.name=`${h.id}:${v}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{const h=Vx(l.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:f,error:d}=await Cv({publicKey:h,signal:u});return f?{data:{factorId:t,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:d}}case"request":{const h=Yx(l.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:f,error:d}=await Ov(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:t,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:d}}}}catch(l){return P(l)?{data:null,error:l}:{data:null,error:new kn("Unexpected error in challenge",l)}}}async _verify({challengeId:t,factorId:n,webauthn:a}){return this.client.mfa.verify({factorId:n,challengeId:t,webauthn:a})}async _authenticate({factorId:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new Hr("rpId is required for WebAuthn authentication")};try{if(!Io())return{data:null,error:new kn("Browser does not support WebAuthn",null)};const{data:r,error:l}=await this.challenge({factorId:t,webauthn:{rpId:n,rpOrigins:a},signal:s},{request:i});if(!r)return{data:null,error:l};const{webauthn:o}=r;return this._verify({factorId:t,challengeId:r.challengeId,webauthn:{type:o.type,rpId:n,rpOrigins:a,credential_response:o.credential_response}})}catch(r){return P(r)?{data:null,error:r}:{data:null,error:new kn("Unexpected error in authenticate",r)}}}async _register({friendlyName:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new Hr("rpId is required for WebAuthn registration")};try{if(!Io())return{data:null,error:new kn("Browser does not support WebAuthn",null)};const{data:r,error:l}=await this._enroll({friendlyName:t});if(!r)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(d=>d.factor_type==="webauthn"&&d.friendly_name===t&&d.status!=="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h==null?void 0:h.id}):void 0),{data:null,error:l};const{data:o,error:u}=await this._challenge({factorId:r.id,friendlyName:r.friendly_name,webauthn:{rpId:n,rpOrigins:a},signal:s},{create:i});return o?this._verify({factorId:r.id,challengeId:o.challengeId,webauthn:{rpId:n,rpOrigins:a,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:u}}catch(r){return P(r)?{data:null,error:r}:{data:null,error:new kn("Unexpected error in register",r)}}}}zx();const Jx={url:Ww,storageKey:Zw,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ex,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Bs={};class $r{get jwks(){var t,n;return(n=(t=Bs[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(t){Bs[this.storageKey]=Object.assign(Object.assign({},Bs[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,n;return(n=(t=Bs[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){Bs[this.storageKey]=Object.assign(Object.assign({},Bs[this.storageKey]),{cachedAt:t})}constructor(t){var n,a,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},Jx),t);if(this.storageKey=i.storageKey,this.instanceID=(n=$r.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,$r.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&Ut()){const r=`${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(r),this.logDebugMessages&&console.trace(r)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(a=i.experimental)!==null&&a!==void 0?a:{},this.admin=new Ux({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Tv(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock),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 Fx(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:xv()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Fp(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Fp(this.memoryStorage)),Ut()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(r){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",r)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async r=>{this._debug("received broadcast notification from other tab or client",r);try{await this._notifyAllSubscribers(r.data.event,r.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(r=>{this._debug("#initialize()","error",r)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Sv}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())(),await this.initializePromise)}async _initialize(){var t;try{let n={},a="none";if(Ut()&&(n=mx(window.location.href),this._isImplicitGrantCallback(n)?a="implicit":await this._isPKCECallback(n)&&(a="pkce")),Ut()&&this.detectSessionInUrl&&a!=="none"){const{data:s,error:i}=await this._getSessionFromURL(n,a);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ix(i)){const o=(t=i.details)===null||t===void 0?void 0:t.code;if(o==="identity_already_exists"||o==="identity_not_found"||o==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:r,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",r,"redirect type",l),await this._saveSession(r),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return P(n)?this._returnResult({error:n}):this._returnResult({error:new kn("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,a,s;try{const i=await Y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(a=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&a!==void 0?a:{},gotrue_meta_security:{captcha_token:(s=t==null?void 0:t.options)===null||s===void 0?void 0:s.captchaToken}},xform:hn}),{data:r,error:l}=i;if(l||!r)return this._returnResult({data:{user:null,session:null},error:l});const o=r.session,u=r.user;return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:u,session:o},error:null})}catch(i){if(P(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var n,a,s;try{let i;if("email"in t){const{email:h,password:f,options:d}=t;let p=null,v=null;this.flowType==="pkce"&&([p,v]=await zs(this.storage,this.storageKey)),i=await Y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:h,password:f,data:(n=d==null?void 0:d.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:p,code_challenge_method:v},xform:hn})}else if("phone"in t){const{phone:h,password:f,options:d}=t;i=await Y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:f,data:(a=d==null?void 0:d.data)!==null&&a!==void 0?a:{},channel:(s=d==null?void 0:d.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:hn})}else throw new Ml("You must provide either an email or phone number and a password");const{data:r,error:l}=i;if(l||!r)return await pt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const o=r.session,u=r.user;return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:u,session:o},error:null})}catch(i){if(await pt(this.storage,`${this.storageKey}-code-verifier`),P(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:r,options:l}=t;n=await Y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:r,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Vp})}else if("phone"in t){const{phone:i,password:r,options:l}=t;n=await Y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:r,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Vp})}else throw new Ml("You must provide either an email or phone number and a password");const{data:a,error:s}=n;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!a||!a.session||!a.user){const i=new Ls;return this._returnResult({data:{user:null,session:null},error:i})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign({user:a.user,session:a.session},a.weak_password?{weakPassword:a.weak_password}:null),error:s})}catch(n){if(P(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(t){var n,a,s,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(a=t.options)===null||a===void 0?void 0:a.scopes,queryParams:(s=t.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t)):this._exchangeCodeForSession(t)}async signInWithWeb3(t){const{chain:n}=t;switch(n){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}}async signInWithEthereum(t){var n,a,s,i,r,l,o,u,h,f,d;let p,v;if("message"in t)p=t.message,v=t.signature;else{const{chain:_,wallet:x,statement:g,options:m}=t;let y;if(Ut())if(typeof x=="object")y=x;else{const q=window;if("ethereum"in q&&typeof q.ethereum=="object"&&"request"in q.ethereum&&typeof q.ethereum.request=="function")y=q.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 x!="object"||!(m!=null&&m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=x}const w=new URL((n=m==null?void 0:m.url)!==null&&n!==void 0?n:window.location.href),C=await y.request({method:"eth_requestAccounts"}).then(q=>q).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!C||C.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const R=Ev(C[0]);let O=(a=m==null?void 0:m.signInWithEthereum)===null||a===void 0?void 0:a.chainId;if(!O){const q=await y.request({method:"eth_chainId"});O=Bx(q)}const z={domain:w.host,address:R,statement:g,uri:w.href,version:"1",chainId:O,nonce:(s=m==null?void 0:m.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(r=(i=m==null?void 0:m.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&r!==void 0?r:new Date,expirationTime:(l=m==null?void 0:m.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(o=m==null?void 0:m.signInWithEthereum)===null||o===void 0?void 0:o.notBefore,requestId:(u=m==null?void 0:m.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=m==null?void 0:m.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=Hx(z),v=await y.request({method:"personal_sign",params:[Ix(p),R]})}try{const{data:_,error:x}=await Y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:v},!((f=t.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(d=t.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:hn});if(x)throw x;if(!_||!_.session||!_.user){const g=new Ls;return this._returnResult({data:{user:null,session:null},error:g})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:x})}catch(_){if(P(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async signInWithSolana(t){var n,a,s,i,r,l,o,u,h,f,d,p;let v,_;if("message"in t)v=t.message,_=t.signature;else{const{chain:x,wallet:g,statement:m,options:y}=t;let w;if(Ut())if(typeof g=="object")w=g;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"))w=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 g!="object"||!(y!=null&&y.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=g}const C=new URL((n=y==null?void 0:y.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in w&&w.signIn){const R=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y==null?void 0:y.signInWithSolana),{version:"1",domain:C.host,uri:C.href}),m?{statement:m}:null));let O;if(Array.isArray(R)&&R[0]&&typeof R[0]=="object")O=R[0];else if(R&&typeof R=="object"&&"signedMessage"in R&&"signature"in R)O=R;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in O&&"signature"in O&&(typeof O.signedMessage=="string"||O.signedMessage instanceof Uint8Array)&&O.signature instanceof Uint8Array)v=typeof O.signedMessage=="string"?O.signedMessage:new TextDecoder().decode(O.signedMessage),_=O.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in w)||typeof w.signMessage!="function"||!("publicKey"in w)||typeof w!="object"||!w.publicKey||!("toBase58"in w.publicKey)||typeof w.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");v=[`${C.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${C.href}`,`Issued At: ${(s=(a=y==null?void 0:y.signInWithSolana)===null||a===void 0?void 0:a.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=y==null?void 0:y.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...!((r=y==null?void 0:y.signInWithSolana)===null||r===void 0)&&r.expirationTime?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...!((l=y==null?void 0:y.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...!((o=y==null?void 0:y.signInWithSolana)===null||o===void 0)&&o.nonce?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...!((u=y==null?void 0:y.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...!((f=(h=y==null?void 0:y.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...y.signInWithSolana.resources.map(O=>`- ${O}`)]:[]].join(`
86
+ `);const R=await w.signMessage(new TextEncoder().encode(v),"utf8");if(!R||!(R instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");_=R}}try{const{data:x,error:g}=await Y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:v,signature:hs(_)},!((d=t.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(p=t.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:hn});if(g)throw g;if(!x||!x.session||!x.user){const m=new Ls;return this._returnResult({data:{user:null,session:null},error:m})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:g})}catch(x){if(P(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async _exchangeCodeForSession(t){const n=await Wn(this.storage,`${this.storageKey}-code-verifier`),[a,s]=(n??"").split("/");try{if(!a&&this.flowType==="pkce")throw new rx;const{data:i,error:r}=await Y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:a},xform:hn});if(await pt(this.storage,`${this.storageKey}-code-verifier`),r)throw r;if(!i||!i.session||!i.user){const l=new Ls;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers(s==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:r})}catch(i){if(await pt(this.storage,`${this.storageKey}-code-verifier`),P(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(t){try{const{options:n,provider:a,token:s,access_token:i,nonce:r}=t,l=await Y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:a,id_token:s,access_token:i,nonce:r,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:hn}),{data:o,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!o||!o.session||!o.user){const h=new Ls;return this._returnResult({data:{user:null,session:null},error:h})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:u})}catch(n){if(P(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(t){var n,a,s,i,r;try{if("email"in t){const{email:l,options:o}=t;let u=null,h=null;this.flowType==="pkce"&&([u,h]=await zs(this.storage,this.storageKey));const{error:f}=await Y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(n=o==null?void 0:o.data)!==null&&n!==void 0?n:{},create_user:(a=o==null?void 0:o.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken},code_challenge:u,code_challenge_method:h},redirectTo:o==null?void 0:o.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in t){const{phone:l,options:o}=t,{data:u,error:h}=await Y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(s=o==null?void 0:o.data)!==null&&s!==void 0?s:{},create_user:(i=o==null?void 0:o.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken},channel:(r=o==null?void 0:o.channel)!==null&&r!==void 0?r:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:h})}throw new Ml("You must provide either an email or phone number.")}catch(l){if(await pt(this.storage,`${this.storageKey}-code-verifier`),P(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(t){var n,a;try{let s,i;"options"in t&&(s=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(a=t.options)===null||a===void 0?void 0:a.captchaToken);const{data:r,error:l}=await Y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:hn});if(l)throw l;if(!r)throw new Error("An error occurred on token verification.");const o=r.session,u=r.user;return o!=null&&o.access_token&&(await this._saveSession(o),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:u,session:o},error:null})}catch(s){if(P(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(t){var n,a,s,i,r;try{let l=null,o=null;this.flowType==="pkce"&&([l,o]=await zs(this.storage,this.storageKey));const u=await Y(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(a=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&a!==void 0?a:void 0}),!((s=t==null?void 0:t.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:o}),headers:this.headers,xform:jx});return!((i=u.data)===null||i===void 0)&&i.url&&Ut()&&!(!((r=t.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await pt(this.storage,`${this.storageKey}-code-verifier`),P(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:a}=t;if(a)throw a;if(!n)throw new St;const{error:s}=await Y(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(t){if(P(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{const n=`${this.url}/resend`;if("email"in t){const{email:a,type:s,options:i}=t,{error:r}=await Y(this.fetch,"POST",n,{headers:this.headers,body:{email:a,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:r})}else if("phone"in t){const{phone:a,type:s,options:i}=t,{data:r,error:l}=await Y(this.fetch,"POST",n,{headers:this.headers,body:{phone:a,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:r==null?void 0:r.message_id},error:l})}throw new Ml("You must provide either an email or phone number and a type")}catch(n){if(P(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t)):await this._useSession(async t=>t)}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const a=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await a,await n()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const a=n();for(this.pendingInLock.push((async()=>{try{await a}catch{}})()),await a;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await a}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await Wn(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const a=t.expires_at?t.expires_at*1e3-Date.now()<iu:!1;if(this._debug("#__loadSession()",`session has${a?"":" not"} expired`,"expires_at",t.expires_at),!a){if(this.userStorage){const r=await Wn(this.userStorage,this.storageKey+"-user");r!=null&&r.user?t.user=r.user:t.user=lu()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){const r={value:this.suppressGetSessionWarning};t.user=Ox(t.user,r),r.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}const{data:s,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(t){if(t)return await this._getUser(t);await this.initializePromise;let n;return this.lock!=null?n=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):n=await this._getUser(),n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(t){try{return t?await Y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:Da}):await this._useSession(async n=>{var a,s,i;const{data:r,error:l}=n;if(l)throw l;return!(!((a=r.session)===null||a===void 0)&&a.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new St}:await Y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=r.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:Da})})}catch(n){if(P(n))return Dl(n)&&(await this._removeSession(),await pt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(t,n={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,n)):await this._updateUser(t,n)}async _updateUser(t,n={}){try{return await this._useSession(async a=>{const{data:s,error:i}=a;if(i)throw i;if(!s.session)throw new St;const r=s.session;let l=null,o=null;this.flowType==="pkce"&&t.email!=null&&([l,o]=await zs(this.storage,this.storageKey));const{data:u,error:h}=await Y(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:l,code_challenge_method:o}),jwt:r.access_token,xform:Da});if(h)throw h;return r.user=u.user,await this._saveSession(r),await this._notifyAllSubscribers("USER_UPDATED",r),this._returnResult({data:{user:r.user},error:null})})}catch(a){if(await pt(this.storage,`${this.storageKey}-code-verifier`),P(a))return this._returnResult({data:{user:null},error:a});throw a}}async setSession(t){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t)):await this._setSession(t)}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new St;const n=Date.now()/1e3;let a=n,s=!0,i=null;const{payload:r}=Ll(t.access_token);if(r.exp&&(a=r.exp,s=a<=n),s){const{data:l,error:o}=await this._callRefreshToken(t.refresh_token);if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:o}=await this._getUser(t.access_token);if(o)return this._returnResult({data:{user:null,session:null},error:o});i={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:a-n,expires_at:a},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(n){if(P(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(t){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t)):await this._refreshSession(t)}async _refreshSession(t){try{return await this._useSession(async n=>{var a;if(!t){const{data:r,error:l}=n;if(l)throw l;t=(a=r.session)!==null&&a!==void 0?a:void 0}if(!(t!=null&&t.refresh_token))throw new St;const{data:s,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(P(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(t,n){var a;try{if(!Ut())throw new Ul("No browser detected.");if(t.error||t.error_description||t.error_code)throw new Ul(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new Bp("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ul("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new Bp("No code detected.");const{data:y,error:w}=await this._exchangeCodeForSession(t.code);if(w)throw w;const C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:y.session,redirectType:(a=y.redirectType)!==null&&a!==void 0?a:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:r,refresh_token:l,expires_in:o,expires_at:u,token_type:h}=t;if(!r||!o||!l||!h)throw new Ul("No session defined in URL");const f=Math.round(Date.now()/1e3),d=parseInt(o);let p=f+d;u&&(p=parseInt(u));const v=p-f;v*1e3<=Ta&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${v}s, should have been closer to ${d}s`);const _=p-d;f-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,p,f):f-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",_,p,f);const{data:x,error:g}=await this._getUser(r);if(g)throw g;const m={provider_token:s,provider_refresh_token:i,access_token:r,expires_in:d,expires_at:p,refresh_token:l,token_type:h,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:m,redirectType:t.type},error:null})}catch(s){if(P(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),t):!!(t.access_token||t.error||t.error_description||t.error_code)}async _isPKCECallback(t){const n=await Wn(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t)):await this._signOut(t)}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var a;const{data:s,error:i}=n;if(i&&!Dl(i))return this._returnResult({error:i});const r=(a=s.session)===null||a===void 0?void 0:a.access_token;if(r){const{error:l}=await this.admin.signOut(r,t);if(l&&!(sx(l)&&(l.status===404||l.status===401||l.status===403)||Dl(l)))return this._returnResult({error:l})}return t!=="others"&&(await this._removeSession(),await pt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(t){const n=px(),a={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,a),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)}):await this._emitInitialSession(n)))(),{data:{subscription:a}}}async _emitInitialSession(t){return await this._useSession(async n=>{var a,s;try{const{data:{session:i},error:r}=n;if(r)throw r;await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(t))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),Dl(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(t,n={}){let a=null,s=null;this.flowType==="pkce"&&([a,s]=await zs(this.storage,this.storageKey,!0));try{return await Y(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:a,code_challenge_method:s,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(await pt(this.storage,`${this.storageKey}-code-verifier`),P(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var t;try{const{data:n,error:a}=await this.getUser();if(a)throw a;return this._returnResult({data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var n;try{const{data:a,error:s}=await this._useSession(async i=>{var r,l,o,u,h;const{data:f,error:d}=i;if(d)throw d;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(r=t.options)===null||r===void 0?void 0:r.redirectTo,scopes:(l=t.options)===null||l===void 0?void 0:l.scopes,queryParams:(o=t.options)===null||o===void 0?void 0:o.queryParams,skipBrowserRedirect:!0});return await Y(this.fetch,"GET",p,{headers:this.headers,jwt:(h=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&h!==void 0?h:void 0})});if(s)throw s;return Ut()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(a==null?void 0:a.url),this._returnResult({data:{provider:t.provider,url:a==null?void 0:a.url},error:null})}catch(a){if(P(a))return this._returnResult({data:{provider:t.provider,url:null},error:a});throw a}}async linkIdentityIdToken(t){return await this._useSession(async n=>{var a;try{const{error:s,data:{session:i}}=n;if(s)throw s;const{options:r,provider:l,token:o,access_token:u,nonce:h}=t,f=await Y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(a=i==null?void 0:i.access_token)!==null&&a!==void 0?a:void 0,body:{provider:l,id_token:o,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:hn}),{data:d,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new Ls}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:p}))}catch(s){if(await pt(this.storage,`${this.storageKey}-code-verifier`),P(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(t){try{return await this._useSession(async n=>{var a,s;const{data:i,error:r}=n;if(r)throw r;return await Y(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(s=(a=i.session)===null||a===void 0?void 0:a.access_token)!==null&&s!==void 0?s:void 0})})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(t){const n="#_refreshAccessToken()";this._debug(n,"begin");try{const a=Date.now();return await vx(async s=>(s>0&&await yx(200*Math.pow(2,s-1)),this._debug(n,"refreshing attempt",s),await Y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:hn})),(s,i)=>{const r=200*Math.pow(2,s);return i&&ru(i)&&Date.now()+r-a<Ta})}catch(a){if(this._debug(n,"error",a),P(a))return this._returnResult({data:{session:null,user:null},error:a});throw a}finally{this._debug(n,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,n){const a=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",n,"url",a),Ut()&&!n.skipBrowserRedirect&&window.location.assign(a),{data:{provider:t,url:a},error:null}}async _recoverAndRefresh(){var t,n;const a="#_recoverAndRefresh()";this._debug(a,"begin");try{const s=await Wn(this.storage,this.storageKey);if(s&&this.userStorage){let r=await Wn(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!r&&(r={user:s.user},await Ks(this.userStorage,this.storageKey+"-user",r)),s.user=(t=r==null?void 0:r.user)!==null&&t!==void 0?t:lu()}else if(s&&!s.user&&!s.user){const r=await Wn(this.storage,this.storageKey+"-user");r&&(r!=null&&r.user)?(s.user=r.user,await pt(this.storage,this.storageKey+"-user"),await Ks(this.storage,this.storageKey,s)):s.user=lu()}if(this._debug(a,"session from storage",s),!this._isValidSession(s)){this._debug(a,"session is not valid"),s!==null&&await this._removeSession();return}const i=((n=s.expires_at)!==null&&n!==void 0?n:1/0)*1e3-Date.now()<iu;if(this._debug(a,`session has${i?"":" not"} expired with margin of ${iu}s`),i){if(this.autoRefreshToken&&s.refresh_token){const{error:r}=await this._callRefreshToken(s.refresh_token);r&&(lx(r)?this._debug(a,"refresh discarded by commit guard",r):(console.error(r),ru(r)||(this._debug(a,"refresh failed with a non-retryable error, removing the session",r),await this._removeSession())))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{const{data:r,error:l}=await this._getUser(s.access_token);!l&&(r!=null&&r.user)?(s.user=r.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(a,"could not get user data, skipping SIGNED_IN notification")}catch(r){console.error("Error getting user data:",r),this._debug(a,"error getting user data, skipping SIGNED_IN notification",r)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(a,"error",s),console.error(s);return}finally{this._debug(a,"end")}}async _callRefreshToken(t){var n,a;if(!t)throw new St;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s="#_callRefreshToken()";this._debug(s,"begin");try{this.refreshingDeferred=new cc;const i=await Wn(this.storage,this.storageKey),{data:r,error:l}=await this._refreshAccessToken(t);if(l)throw l;if(!r.session)throw new St;const o=await Wn(this.storage,this.storageKey);if(i!==null&&(o===null||o.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:o?"replaced":"cleared"});const d={data:null,error:new Ip};return this.refreshingDeferred.resolve(d),d}const h=this._sessionRemovalEpoch;if(await this._saveSession(r.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await pt(this.storage,this.storageKey),this.userStorage&&await pt(this.userStorage,this.storageKey+"-user");const d={data:null,error:new Ip};return this.refreshingDeferred.resolve(d),d}await this._notifyAllSubscribers("TOKEN_REFRESHED",r.session);const f={data:r.session,error:null};return this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),P(i)){const r={data:null,error:i};return ru(i)||await this._removeSession(),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(r),r}throw(a=this.refreshingDeferred)===null||a===void 0||a.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(t,n,a=!0){const s=`#_notifyAllSubscribers(${t})`;this._debug(s,"begin",n,`broadcast = ${a}`);try{this.broadcastChannel&&a&&this.broadcastChannel.postMessage({event:t,session:n});const i=[],r=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,n)}catch(o){i.push(o)}});if(await Promise.all(r),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0,await pt(this.storage,`${this.storageKey}-code-verifier`);const n=Object.assign({},t),a=n.user&&n.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!a&&n.user&&await Ks(this.userStorage,this.storageKey+"-user",{user:n.user});const s=Object.assign({},n);delete s.user;const i=Gp(s);await Ks(this.storage,this.storageKey,i)}else{const s=Gp(n);await Ks(this.storage,this.storageKey,s)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await pt(this.storage,this.storageKey),await pt(this.storage,this.storageKey+"-code-verifier"),await pt(this.storage,this.storageKey+"-user"),this.userStorage&&await pt(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&Ut()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Ta);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);const n=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);const n=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,n&&clearTimeout(n)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var t;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(t=this.broadcastChannel)===null||t===void 0||t.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:a}}=n;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((a.expires_at*1e3-t)/Ta);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Ta}ms, refresh threshold is ${sr} ticks`),s<=sr&&await this._callRefreshToken(a.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t instanceof Lx)this._debug("auto refresh token tick lock not available");else throw t}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const t=Date.now();try{await this._useSession(async n=>{const{data:{session:a}}=n;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((a.expires_at*1e3-t)/Ta);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Ta}ms, refresh threshold is ${sr} ticks`),s<=sr&&await this._callRefreshToken(a.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ut()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;if(this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!t)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(n,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,a){const s=[`provider=${encodeURIComponent(n)}`];if(a!=null&&a.redirectTo&&s.push(`redirect_to=${encodeURIComponent(a.redirectTo)}`),a!=null&&a.scopes&&s.push(`scopes=${encodeURIComponent(a.scopes)}`),this.flowType==="pkce"){const[i,r]=await zs(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(r)}`});s.push(l.toString())}if(a!=null&&a.queryParams){const i=new URLSearchParams(a.queryParams);s.push(i.toString())}return a!=null&&a.skipBrowserRedirect&&s.push(`skip_http_redirect=${a.skipBrowserRedirect}`),`${t}?${s.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var a;const{data:s,error:i}=n;return i?this._returnResult({data:null,error:i}):await Y(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(a=s==null?void 0:s.session)===null||a===void 0?void 0:a.access_token})})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(t){try{return await this._useSession(async n=>{var a,s;const{data:i,error:r}=n;if(r)return this._returnResult({data:null,error:r});const l=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:o,error:u}=await Y(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(a=i==null?void 0:i.session)===null||a===void 0?void 0:a.access_token});return u?this._returnResult({data:null,error:u}):(t.factorType==="totp"&&o.type==="totp"&&(!((s=o==null?void 0:o.totp)===null||s===void 0)&&s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async _verify(t){const n=async()=>{try{return await this._useSession(async a=>{var s;const{data:i,error:r}=a;if(r)return this._returnResult({data:null,error:r});const l=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?Qp(t.webauthn.credential_response):Wp(t.webauthn.credential_response)})}:{code:t.code}),{data:o,error:u}=await Y(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:u}))})}catch(a){if(P(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,n):n()}async _challenge(t){const n=async()=>{try{return await this._useSession(async a=>{var s;const{data:i,error:r}=a;if(r)return this._returnResult({data:null,error:r});const l=await Y(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;const{data:o}=l;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Jp(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Xp(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if(P(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,n):n()}async _challengeAndVerify(t){const{data:n,error:a}=await this._challenge({factorId:t.factorId});return a?this._returnResult({data:null,error:a}):await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){var t;const{data:{user:n},error:a}=await this.getUser();if(a)return{data:null,error:a};const s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(t=n==null?void 0:n.factors)!==null&&t!==void 0?t:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(t){var n,a,s,i;if(t)try{const{payload:p}=Ll(t);let v=null;p.aal&&(v=p.aal);let _=v;const{data:{user:x},error:g}=await this.getUser(t);if(g)return this._returnResult({data:null,error:g});((a=(n=x==null?void 0:x.factors)===null||n===void 0?void 0:n.filter(w=>w.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(_="aal2");const y=p.amr||[];return{data:{currentLevel:v,nextLevel:_,currentAuthenticationMethods:y},error:null}}catch(p){if(P(p))return this._returnResult({data:null,error:p});throw p}const{data:{session:r},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=Ll(r.access_token);let u=null;o.aal&&(u=o.aal);let h=u;((i=(s=r.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");const d=o.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async n=>{const{data:{session:a},error:s}=n;return s?this._returnResult({data:null,error:s}):a?await Y(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:a.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new St})})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(t,n){try{return await this._useSession(async a=>{const{data:{session:s},error:i}=a;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new St});const r=await Y(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return r.data&&r.data.redirect_url&&Ut()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(r.data.redirect_url),r})}catch(a){if(P(a))return this._returnResult({data:null,error:a});throw a}}async _denyAuthorization(t,n){try{return await this._useSession(async a=>{const{data:{session:s},error:i}=a;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new St});const r=await Y(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return r.data&&r.data.redirect_url&&Ut()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(r.data.redirect_url),r})}catch(a){if(P(a))return this._returnResult({data:null,error:a});throw a}}async _listOAuthGrants(){try{return await this._useSession(async t=>{const{data:{session:n},error:a}=t;return a?this._returnResult({data:null,error:a}):n?await Y(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new St})})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async n=>{const{data:{session:a},error:s}=n;return s?this._returnResult({data:null,error:s}):a?(await Y(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:a.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new St})})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(t,n={keys:[]}){let a=n.keys.find(l=>l.kid===t);if(a)return a;const s=Date.now();if(a=this.jwks.keys.find(l=>l.kid===t),a&&this.jwks_cached_at+nx>s)return a;const{data:i,error:r}=await Y(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(r)throw r;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,a=i.keys.find(l=>l.kid===t),!a)?null:a}async getClaims(t,n={}){try{let a=t;if(!a){const{data:p,error:v}=await this.getSession();if(v||!p.session)return this._returnResult({data:null,error:v});a=p.session.access_token}const{header:s,payload:i,signature:r,raw:{header:l,payload:o}}=Ll(a);if(!(n!=null&&n.allowExpired))try{Ex(i.exp)}catch(p){throw new Lo(p instanceof Error?p.message:"JWT validation failed")}const u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,n!=null&&n.keys?{keys:n.keys}:n==null?void 0:n.jwks);if(!u){const{error:p}=await this.getUser(a);if(p)throw p;return{data:{claims:i,header:s,signature:r},error:null}}const h=Ax(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,r,hx(`${l}.${o}`)))throw new Lo("Invalid JWT signature");return{data:{claims:i,header:s,signature:r},error:null}}catch(a){if(P(a))return this._returnResult({data:null,error:a});throw a}}async signInWithPasskey(t){var n,a,s;On(this.experimental);try{if(!Io())return this._returnResult({data:null,error:new kn("Browser does not support WebAuthn",null)});const{data:i,error:r}=await this._startPasskeyAuthentication({options:{captchaToken:(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.captchaToken}});if(r||!i)return this._returnResult({data:null,error:r});const l=Xp(i.options),o=(s=(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.signal)!==null&&s!==void 0?s:Td.createNewAbortSignal(),{data:u,error:h}=await Ov({publicKey:l,signal:o});if(h||!u)return this._returnResult({data:null,error:h??new kn("WebAuthn ceremony failed",null)});const f=Wp(u);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:f})}catch(i){if(P(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(t){var n,a;On(this.experimental);try{if(!Io())return this._returnResult({data:null,error:new kn("Browser does not support WebAuthn",null)});const{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});const r=Jp(s.options),l=(a=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.signal)!==null&&a!==void 0?a:Td.createNewAbortSignal(),{data:o,error:u}=await Cv({publicKey:r,signal:l});if(u||!o)return this._returnResult({data:null,error:u??new kn("WebAuthn ceremony failed",null)});const h=Qp(o);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(P(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){On(this.experimental);try{return await this._useSession(async t=>{const{data:{session:n},error:a}=t;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new St});const{data:s,error:i}=await Y(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:n.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async _verifyPasskeyRegistration(t){On(this.experimental);try{return await this._useSession(async n=>{const{data:{session:a},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!a)return this._returnResult({data:null,error:new St});const{data:i,error:r}=await Y(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:a.access_token,body:{challenge_id:t.challengeId,credential:t.credential}});return r?this._returnResult({data:null,error:r}):this._returnResult({data:i,error:null})})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyAuthentication(t){var n;On(this.experimental);try{const{data:a,error:s}=await Y(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:a,error:null})}catch(a){if(P(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyAuthentication(t){On(this.experimental);try{const{data:n,error:a}=await Y(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:t.challengeId,credential:t.credential},xform:hn});return a?this._returnResult({data:null,error:a}):(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:n,error:null}))}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async _listPasskeys(){On(this.experimental);try{return await this._useSession(async t=>{const{data:{session:n},error:a}=t;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new St});const{data:s,error:i}=await Y(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:n.access_token,xform:r=>({data:r,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async _updatePasskey(t){On(this.experimental);try{return await this._useSession(async n=>{const{data:{session:a},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!a)return this._returnResult({data:null,error:new St});const{data:i,error:r}=await Y(this.fetch,"PATCH",`${this.url}/passkeys/${t.passkeyId}`,{headers:this.headers,jwt:a.access_token,body:{friendly_name:t.friendlyName}});return r?this._returnResult({data:null,error:r}):this._returnResult({data:i,error:null})})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}async _deletePasskey(t){On(this.experimental);try{return await this._useSession(async n=>{const{data:{session:a},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!a)return this._returnResult({data:null,error:new St});const{error:i}=await Y(this.fetch,"DELETE",`${this.url}/passkeys/${t.passkeyId}`,{headers:this.headers,jwt:a.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(n){if(P(n))return this._returnResult({data:null,error:n});throw n}}}$r.nextInstanceID={};const Xx=$r,Qx="2.107.0";let ir="",$o;if(typeof Deno<"u"){var cu;ir="deno",$o=(cu=Deno.version)===null||cu===void 0?void 0:cu.deno}else if(typeof document<"u")ir="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")ir="react-native";else{var uu;ir="node",$o=typeof process<"u"?(uu=process.version)===null||uu===void 0?void 0:uu.replace(/^v/,""):void 0}const Rv=[`runtime=${ir}`];$o&&Rv.push(`runtime-version=${$o}`);const Wx={"X-Client-Info":`supabase-js/${Qx}; ${Rv.join("; ")}`},Zx={headers:Wx},eT={schema:"public"},tT={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},nT={},aT={enabled:!1,respectSamplingDecision:!0};function sT(e,t,n,a){function s(i){return i instanceof n?i:new n(function(r){r(i)})}return new(n||(n=Promise))(function(i,r){function l(h){try{u(a.next(h))}catch(f){r(f)}}function o(h){try{u(a.throw(h))}catch(f){r(f)}}function u(h){h.done?i(h.value):s(h.value).then(l,o)}u((a=a.apply(e,[])).next())})}let du=null;const iT="@opentelemetry/api";function rT(){return du===null&&(du=import(iT).catch(()=>null)),du}function lT(){return sT(this,void 0,void 0,function*(){try{const e=yield rT();if(!e||!e.propagation||!e.context)return null;const t={};e.propagation.inject(e.context.active(),t);const n=t.traceparent;return n?{traceparent:n,tracestate:t.tracestate,baggage:t.baggage}:null}catch{return null}})}function oT(e){if(!e||typeof e!="string")return null;const t=e.split("-");if(t.length!==4)return null;const[n,a,s,i]=t;if(n.length!==2||a.length!==32||s.length!==16||i.length!==2)return null;const r=/^[0-9a-f]+$/i;return!r.test(n)||!r.test(a)||!r.test(s)||!r.test(i)||a==="00000000000000000000000000000000"||s==="0000000000000000"?null:{version:n,traceId:a,parentId:s,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function cT(e,t){if(!e||!t||t.length===0)return!1;let n;if(e instanceof URL)n=e;else try{n=new URL(e)}catch{return!1}for(const a of t)try{if(typeof a=="string"){if(uT(n.hostname,a))return!0}else if(a instanceof RegExp){if(a.test(n.hostname))return!0}else if(typeof a=="function"&&a(n))return!0}catch{continue}return!1}function uT(e,t){if(t===e)return!0;if(t.startsWith("*.")){const n=t.slice(2);if(e.endsWith(n)&&(e===n||e.endsWith("."+n)))return!0}return!1}function dT(e){const t=[];try{const n=new URL(e);t.push(n.hostname)}catch{}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}function Pr(e){"@babel/helpers - typeof";return Pr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pr(e)}function hT(e,t){if(Pr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(Pr(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function fT(e){var t=hT(e,"string");return Pr(t)=="symbol"?t:t+""}function pT(e,t,n){return(t=fT(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Zp(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,a)}return n}function Ze(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Zp(Object(n),!0).forEach(function(a){pT(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Zp(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}const mT=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),gT=()=>Headers,yT=(e,t,n,a,s)=>{const i=mT(a),r=gT(),l=(s==null?void 0:s.enabled)===!0,o=(s==null?void 0:s.respectSamplingDecision)!==!1,u=l?dT(t):null;return async(h,f)=>{var d;const p=(d=await n())!==null&&d!==void 0?d:e;let v=new r(f==null?void 0:f.headers);if(v.has("apikey")||v.set("apikey",e),v.has("Authorization")||v.set("Authorization",`Bearer ${p}`),u){const _=await vT(h,u,o);_&&(_.traceparent&&!v.has("traceparent")&&v.set("traceparent",_.traceparent),_.tracestate&&!v.has("tracestate")&&v.set("tracestate",_.tracestate),_.baggage&&!v.has("baggage")&&v.set("baggage",_.baggage))}return i(h,Ze(Ze({},f),{},{headers:v}))}};async function vT(e,t,n){if(!cT(typeof e=="string"||e instanceof URL?e:e.url,t))return null;const a=await lT();if(!a||!a.traceparent)return null;if(n){const s=oT(a.traceparent);if(s&&!s.isSampled)return null}return a}function em(e){return typeof e=="boolean"?{enabled:e}:e}function bT(e){return e.endsWith("/")?e:e+"/"}function ST(e,t){var n,a,s,i,r,l;const{db:o,auth:u,realtime:h,global:f}=e,{db:d,auth:p,realtime:v,global:_}=t,x=em(e.tracePropagation),g=em(t.tracePropagation),m={db:Ze(Ze({},d),o),auth:Ze(Ze({},p),u),realtime:Ze(Ze({},v),h),storage:{},global:Ze(Ze(Ze({},_),f),{},{headers:Ze(Ze({},(n=_==null?void 0:_.headers)!==null&&n!==void 0?n:{}),(a=f==null?void 0:f.headers)!==null&&a!==void 0?a:{})}),tracePropagation:{enabled:(s=(i=x==null?void 0:x.enabled)!==null&&i!==void 0?i:g==null?void 0:g.enabled)!==null&&s!==void 0?s:!1,respectSamplingDecision:(r=(l=x==null?void 0:x.respectSamplingDecision)!==null&&l!==void 0?l:g==null?void 0:g.respectSamplingDecision)!==null&&r!==void 0?r:!0},accessToken:async()=>""};return e.accessToken?m.accessToken=e.accessToken:delete m.accessToken,m}function _T(e){const t=e==null?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(bT(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var wT=class extends Xx{constructor(e){super(e)}},xT=class{constructor(e,t,n){var a,s;this.supabaseUrl=e,this.supabaseKey=t;const i=_T(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const r=`sb-${i.hostname.split(".")[0]}-auth-token`,l={db:eT,realtime:nT,auth:Ze(Ze({},tT),{},{storageKey:r}),global:Zx,tracePropagation:aT},o=ST(n??{},l);if(this.settings=o,this.storageKey=(a=o.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(s=o.global.headers)!==null&&s!==void 0?s:{},o.accessToken)this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(h,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=o.auth)!==null&&u!==void 0?u:{},this.headers,o.global.fetch)}this.fetch=yT(t,e,this._getAccessToken.bind(this),o.global.fetch,o.tracePropagation),this.realtime=this._initRealtimeClient(Ze({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new B_(new URL("rest/v1",i).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch,timeout:o.db.timeout,urlLengthLimit:o.db.urlLengthLimit}),this.storage=new Qw(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new R_(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,t,n;if(e.accessToken)return await e.accessToken();const{data:a}=await e.auth.getSession();return(t=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:a,userStorage:s,storageKey:i,flowType:r,lock:l,debug:o,throwOnError:u,experimental:h,lockAcquireTimeout:f,skipAutoInitialize:d},p,v){const _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new wT({url:this.authUrl.href,headers:Ze(Ze({},_),p),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:a,userStorage:s,flowType:r,lock:l,debug:o,throwOnError:u,experimental:h,fetch:v,lockAcquireTimeout:f,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(x=>x.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Sw(this.realtimeUrl.href,Ze(Ze({},e),{},{params:Ze(Ze({},{apikey:this.supabaseKey}),e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t==null?void 0:t.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const TT=(e,t,n)=>new xT(e,t,n);function ET(){if(typeof window<"u")return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(t==null)return!1;const n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}ET()&&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 AT="https://xmbghgovoqwsqpcbfeiq.supabase.co",CT="sb_publishable_XkURWGjMlINTEqG9qptIPA_J5zv30Te",Is=TT(AT,CT),Nv=b.createContext(null);function OT({children:e}){const[t,n]=b.useState(null),[a,s]=b.useState(null),[i,r]=b.useState(null),[l,o]=b.useState(!0),[u,h]=b.useState(null),f=(i==null?void 0:i.plan)==="pro"&&(i==null?void 0:i.status)==="active",d=b.useCallback(async g=>{try{const{data:m,error:y}=await Is.from("profiles").select("plan").eq("id",g).maybeSingle();if(y){console.error("[Auth] Entitlement fetch error:",y.message);return}const w=(m==null?void 0:m.plan)==="pro"?"pro":"free";r({status:w==="pro"?"active":"inactive",plan:w})}catch{r({status:"inactive",plan:"free"})}},[]);b.useEffect(()=>{Is.auth.getSession().then(({data:{session:m}})=>{s(m),n((m==null?void 0:m.user)??null),m!=null&&m.user&&d(m.user.id),o(!1)}).catch(m=>{console.error("[Auth] Session initialization failed:",m),h("Unable to reach authentication service. Working in offline mode."),o(!1)});const{data:{subscription:g}}=Is.auth.onAuthStateChange((m,y)=>{s(y),n((y==null?void 0:y.user)??null),y!=null&&y.user?d(y.user.id):r(null),h(null)});return()=>{g.unsubscribe()}},[d]);const p=b.useCallback(async(g,m)=>{h(null);const{error:y}=await Is.auth.signInWithPassword({email:g,password:m});return y&&h(y.message),y?y.message:null},[]),v=b.useCallback(async(g,m)=>{h(null);const{data:y,error:w}=await Is.auth.signUp({email:g,password:m});return w?(h(w.message),{error:w.message,needsConfirmation:!1}):{error:null,needsConfirmation:!y.session}},[]),_=b.useCallback(async()=>{await Is.auth.signOut(),n(null),s(null),r(null)},[]),x=b.useCallback(()=>h(null),[]);return c.jsx(Nv.Provider,{value:{user:t,session:a,subscription:i,isSubscribed:f,signInWithEmail:p,signUpWithEmail:v,signOut:_,loading:l,authError:u,clearAuthError:x},children:e})}function Os(){const e=b.useContext(Nv);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}const kv="https://noterai.tech/#pricing";function jv(){const{user:e,isSubscribed:t}=Os();return t?null:e?c.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"16px",padding:"48px 24px",height:"100%",width:"100%"},children:[c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.875rem",color:"var(--panel-label)",textTransform:"uppercase",letterSpacing:"0.05rem"},children:"This feature requires a Pro plan"}),c.jsx("a",{href:kv,target:"_blank",rel:"noopener noreferrer",style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",padding:"10px 20px",background:"var(--on-surface)",color:"var(--surface)",border:"none",cursor:"pointer",borderRadius:0,textDecoration:"none",display:"inline-block"},children:"Upgrade to Pro — 3€/month"})]}):c.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"16px",padding:"48px 24px",height:"100%",width:"100%"},children:c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.875rem",color:"var(--panel-label)",textTransform:"uppercase",letterSpacing:"0.05rem"},children:"Sign in to unlock this feature"})})}function RT(){const{isSubscribed:e}=Os(),[t,n]=b.useState([]),[a,s]=b.useState({high:!0,medium:!0,low:!0}),[i,r]=b.useState(new Set),[l,o]=b.useState(!1),[u,h]=b.useState(!1);b.useEffect(()=>{DS().then(()=>{r(new Set(Zc()))})},[]),b.useEffect(()=>{me.suggestions&&me.suggestions.length>0&&n(lp(me.suggestions)),me.hasReceivedFirstSync&&o(!0),me.isGeneratingSuggestions&&h(!0);const _=me.subscribe("suggestions",g=>{if(g){const m=lp(g);n(m),r(new Set(Zc()))}o(!0)}),x=me.subscribe("suggestions-status",({generating:g})=>{h(g)});return()=>{_(),x()}},[]);const f=b.useCallback(()=>{const _=t.filter(x=>!Wc(x.id)).map(x=>x.id);for(const x of _)Do(x),me.removeSuggestion(x);n(x=>x.filter(g=>Wc(g.id)))},[t]),d=b.useCallback(_=>{s(x=>({...x,[_]:!x[_]}))},[]),p=b.useCallback((_,x)=>{Wc(_)?US(_):MS(_,x),r(new Set(Zc()))},[]);if(!e)return c.jsx(jv,{});const v=t.filter(_=>a[_.priority]);return t.filter(_=>_.priority==="high").length,t.filter(_=>_.priority==="medium").length,t.filter(_=>_.priority==="low").length,c.jsxs("div",{className:"panel panel-content",role:"region","aria-label":"Suggested Tasks","aria-live":"polite",tabIndex:0,style:{gap:"24px"},children:[c.jsxs("header",{className:"panel-header",children:[c.jsx("h2",{className:"panel-title",children:"02_SUGGESTED_TASKS"}),c.jsxs("div",{style:{display:"flex",gap:"8px",flexWrap:"nowrap",alignItems:"center"},children:[["high","medium","low"].map(_=>c.jsx("button",{onClick:()=>d(_),"aria-label":`Filter ${_} priority tasks`,"aria-pressed":a[_],className:`priority-filter-btn ${a[_]?"priority-filter-btn--active":"priority-filter-btn--inactive"}`,children:_},_)),t.length>0&&c.jsx("button",{onClick:f,"aria-label":"Clear non-pinned tasks",className:"btn-tertiary",style:{fontFamily:"var(--font-mono)",fontSize:"0.6rem",textTransform:"uppercase",letterSpacing:"0.05em",padding:"2px 8px",border:"1px solid var(--outline-variant)",background:"transparent",color:"var(--panel-label)",cursor:"pointer",borderRadius:0},children:"CLEAR"})]})]}),c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",overflowY:"visible"},children:[u&&c.jsx("div",{className:"suggestions-generating-indicator","aria-live":"polite","data-testid":"suggestions-generating",children:c.jsx("span",{className:"text-mono animate-pulse",style:{color:"var(--panel-label)",fontSize:"0.65rem",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Generating task…"})}),l?!u&&v.length===0?c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px",alignItems:"center",padding:"16px 0"},children:c.jsx("span",{className:"text-body-md",style:{color:"var(--panel-label)"},children:"No suggestions yet."})}):v.filter(_=>_.title?!0:(console.warn("[SuggestionsPanel] Skipping task with missing title:",_.id),!1)).map(_=>c.jsx(NT,{task:_,isPinned:i.has(_.id),onTogglePin:p,onDelete:x=>{Do(x),n(g=>g.filter(m=>m.id!==x))}},_.id)):c.jsx(kT,{})]})]})}function NT({task:e,isPinned:t,onTogglePin:n,onDelete:a}){return c.jsxs("div",{draggable:!0,onDragStart:s,className:`task-card${e.conflictsWithNotes?" task-card--conflict":""}`,children:[e.conflictsWithNotes&&c.jsx("div",{className:"conflict-bar"}),c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"8px"},children:[c.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:c.jsx("span",{className:`badge badge--${e.priority}`,children:e.priority})}),c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[c.jsx("button",{onClick:i=>{i.stopPropagation(),n(e.id,e.title)},className:"pin-btn","aria-label":t?"Unpin task":"Pin task",title:t?"Unpin":"Pin",style:{background:"transparent",border:t?"1px solid var(--outline-variant)":"1px solid transparent",color:t?"var(--on-surface)":"var(--panel-label)",cursor:"pointer",fontSize:"0.7rem",lineHeight:1,padding:"2px 4px",opacity:t?1:.5},children:t?"⬥":"⬦"}),c.jsx("button",{onClick:i=>{i.stopPropagation(),a(e.id)},className:"delete-btn","aria-label":"Delete task",children:"×"})]})]}),c.jsx("h3",{style:{fontFamily:"var(--font-sans)",fontWeight:500,fontSize:"1rem",margin:0,color:"var(--on-surface)"},children:e.title}),e.conflictsWithNotes&&e.conflictExplanation&&c.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start",marginTop:"12px"},children:[c.jsx("span",{style:{color:"#FFCC00",fontSize:"14px"},children:"⚠"}),c.jsxs("p",{style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",fontStyle:"italic",color:"var(--panel-label)",margin:0},children:[c.jsx("span",{style:{color:"#FF4444",textTransform:"uppercase",fontStyle:"normal",marginRight:"6px",fontSize:"0.65rem"},children:"Conflict Warning"}),e.conflictExplanation]})]})]});function s(i){i.dataTransfer.setData("text/plain",`- ${e.title}: ${e.rationale}`),i.dataTransfer.setData("taskId",e.id),i.dataTransfer.effectAllowed="copy"}}function kT(){return c.jsx(c.Fragment,{children:[1,2,3].map(e=>c.jsxs("div",{className:"task-card animate-pulse",style:{padding:"16px",backgroundColor:"var(--surface-container-high)"},children:[c.jsx("div",{className:"skeleton-line",style:{width:"40px",height:"14px",marginBottom:"12px"}}),c.jsx("div",{className:"skeleton-line",style:{width:"80%",height:"20px",marginBottom:"8px"}}),c.jsx("div",{className:"skeleton-line",style:{width:"100%",height:"14px",marginBottom:"4px"}}),c.jsx("div",{className:"skeleton-line",style:{width:"60%",height:"14px"}})]},e))})}function jT(){const[e,t]=b.useState([]),[n,a]=b.useState(!1),[s,i]=b.useState(!1),[r,l]=b.useState(null),[o,u]=b.useState(!1);b.useEffect(()=>{const _=async()=>{try{a(!0);const g=await fetch("/api/ollama/status");if(g.ok){const m=await g.json();t(m.models||[])}else l("Unable to fetch Ollama status")}catch{l("Ollama not running")}finally{a(!1)}};_();const x=setInterval(_,3e4);return()=>clearInterval(x)},[]);const h=async()=>{try{i(!0),l(null);const _=await fetch("/api/ollama/offload",{method:"POST"});if(_.ok)u(!0),setTimeout(()=>u(!1),3e3),t([]);else{const x=await _.json().catch(()=>({}));l(x.error||"Offload failed")}}catch{l("Failed to offload")}finally{i(!1)}},f=e.reduce((_,x)=>_+(x.size||0),0),d=e.reduce((_,x)=>_+(x.sizeVram||0),0),p=(f/1024**3).toFixed(1),v=(d/1024**3).toFixed(1);return n&&e.length===0?c.jsx("div",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)",padding:"8px 0"},children:"Loading Ollama status..."}):r&&e.length===0?c.jsx("div",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)",padding:"8px 0"},children:r}):c.jsxs("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:"1px solid var(--outline-variant)"},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"},children:[c.jsx("span",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)"},children:e.length>0?e[0].name:"No model loaded"}),e.length>0&&c.jsxs("span",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)"},children:[p," GB disk / ",v," GB VRAM"]})]}),e.length>0&&c.jsx("button",{onClick:h,disabled:s,style:{fontFamily:"var(--font-sans)",fontSize:"0.7rem",textTransform:"uppercase",padding:"4px 10px",border:"1px solid var(--outline-variant)",borderRadius:"0px",background:"transparent",color:"var(--on-surface)",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:o?"Offloaded":s?"Offloading...":"Offload"}),r&&e.length>0&&c.jsx("div",{className:"text-mono",style:{fontSize:"0.65rem",color:"#FF0000",marginTop:"4px"},children:r})]})}function DT(){const[e,t]=b.useState([]),[n,a]=b.useState(!1),[s,i]=b.useState(null);if(b.useEffect(()=>{const l=async()=>{try{a(!0);const u=await fetch("/api/lmstudio/models");if(u.ok){const h=await u.json();t(h.modelsWithMeta||[]),i(null)}else{const h=await u.json().catch(()=>({error:"Failed to fetch LM Studio status"}));i(h.error||"LM Studio not reachable")}}catch{i("LM Studio not running")}finally{a(!1)}};l();const o=setInterval(l,3e4);return()=>clearInterval(o)},[]),n&&e.length===0)return c.jsx("div",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)",padding:"8px 0"},children:"Loading LM Studio status…"});if(s&&e.length===0)return c.jsx("div",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)",padding:"8px 0"},children:s});const r=e.length>0?e[0]:null;return c.jsxs("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:"1px solid var(--outline-variant)"},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"},children:[c.jsx("span",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)"},children:r?r.id:"No model loaded"}),r&&c.jsxs("span",{className:"text-mono",style:{fontSize:"0.65rem",color:"var(--panel-label)"},children:[r.arch&&`${r.arch} · `,r.maxContextLength?`${(r.maxContextLength/1024).toFixed(0)}K ctx`:"ctx N/A",r.type?` · ${r.type}`:""]})]}),s&&e.length>0&&c.jsx("div",{className:"text-mono",style:{fontSize:"0.65rem",color:"#FF4444",marginTop:"4px"},children:s})]})}function MT(){const[e,t]=b.useState(me.sourceInfo);return b.useEffect(()=>me.subscribe("source",a=>t(a)),[]),e}function UT(){const[e,t]=b.useState(me.config.llmProvider||"ollama");return b.useEffect(()=>me.subscribe("config",a=>{t(a.llmProvider||"ollama")}),[]),e}function LT(){const[e,t]=b.useState(me.getStatus());return b.useEffect(()=>me.subscribe("status",a=>t(a)),[]),e}function zT(e,t){if(t!=="connected")return{label:"DISCONNECTED",sublabel:"WebSocket offline"};const n=e.name.toUpperCase(),a=e.status==="active"||e.sessionConnected===!0;if(a&&e.lastEventAt){const s=Math.floor((Date.now()-e.lastEventAt)/1e3);return{label:`${n} — ACTIVE`,sublabel:`last event ${s}s ago`}}return a?{label:`${n} — ACTIVE`,sublabel:"session connected"}:e.status==="waiting"?{label:`${n} — WAITING`,sublabel:"adapter running, no events yet"}:{label:`${n} — DISCONNECTED`,sublabel:"adapter not running"}}function BT(){const[e,t]=b.useState(null),[n,a]=b.useState(!1),[s,i]=b.useState(null),[r,l]=b.useState(180),[o,u]=b.useState([]),[h,f]=b.useState(null),[d,p]=b.useState(null),[v,_]=b.useState(!1),x=MT(),g=LT(),m=UT(),[y,w]=b.useState(!1),[C,R]=b.useState(!1),O=b.useRef(x.name),z=b.useRef(null),q=b.useRef(null),K=b.useRef(!1),ve=b.useRef(null);b.useEffect(()=>(me.summary&&(t(me.summary),i(me.summary.generatedAt)),me.hasReceivedFirstSync&&_(!0),me.subscribe("summary",k=>{t(k),_(!0),k&&(i(k.generatedAt),l(180))})),[]),b.useEffect(()=>{me.events.length>0&&u(me.events.slice(0,5));const U=me.subscribe("event",se=>{u(j=>[se,...j].slice(0,5)),w(!1)}),k=me.subscribe("sync",()=>{u(me.events.slice(0,5))});return()=>{U(),k()}},[]),b.useEffect(()=>{O.current==="generic"&&x.name!=="generic"&&R(!1),O.current=x.name,v&&x.name==="generic"&&o.length===0&&!C?w(!0):w(!1)},[v,x.name,o.length,C]),b.useEffect(()=>{if(m!=="ollama"){f(null),p(null);return}const U=async()=>{try{const se=await fetch("/api/ollama/status");if(se.ok){const j=await se.json();j.memory&&f(j.memory),j.vram&&p(j.vram)}}catch{}};U();const k=setInterval(U,3e4);return()=>clearInterval(k)},[m]),b.useEffect(()=>{const U=setInterval(()=>{l(k=>k<=1?180:k-1)},1e3);return()=>{clearInterval(U),z.current&&(clearInterval(z.current),z.current=null),q.current&&(clearInterval(q.current),q.current=null)}},[]);const Ae=b.useCallback(async()=>{if(!K.current){K.current=!0,a(!0);try{const U=await fetch("/api/summarize",{method:"POST"});if(U.status===202)z.current&&clearInterval(z.current),z.current=setInterval(()=>{const k=me.summary;k&&k.generatedAt>(s||0)&&(z.current&&(clearInterval(z.current),z.current=null),a(!1),K.current=!1,l(180))},500),setTimeout(()=>{z.current&&(clearInterval(z.current),z.current=null),a(!1),K.current=!1},3e4);else if(U.ok){const k=await U.json();k!=null&&k.id&&(t(k),i(k.generatedAt),l(180)),a(!1),K.current=!1}else a(!1),K.current=!1}catch{a(!1),K.current=!1}}},[s]);b.useEffect(()=>{if(!v)return;const U=`${x.name}:${x.status}`;return ve.current!==U&&(ve.current=U,Ae()),q.current&&clearInterval(q.current),q.current=setInterval(()=>{Ae()},12e4),()=>{q.current&&(clearInterval(q.current),q.current=null)}},[v,x.name,x.status,Ae]);const ee=U=>{const k=Math.floor(U/60),se=U%60;return`${k}:${se.toString().padStart(2,"0")}`},yt=b.useCallback(U=>{const k=new Date(U);return`${k.getHours().toString().padStart(2,"0")}:${k.getMinutes().toString().padStart(2,"0")}:${k.getSeconds().toString().padStart(2,"0")}`},[]),$e=b.useCallback(U=>U.type==="tool.before"&&U.tool?`WRITING: ${U.tool}${U.args?` — ${Object.keys(U.args).join(", ")}`:""}...`:U.type==="tool.after"&&U.tool?`ANALYSIS_COMPLETE: ${U.tool} finished.`:U.type==="message"&&U.text?U.text.length>60?U.text.substring(0,57)+"...":U.text:U.type==="session.idle"?"SESSION: Idle — waiting for input.":`${U.type.toUpperCase()}: ${U.tool||U.text||"event received"}`,[]),L=b.useMemo(()=>zT(x,g),[x,g]);return c.jsxs("div",{className:"panel panel-content",role:"region","aria-label":"Agent Context",tabIndex:0,children:[c.jsxs("header",{className:"panel-header",children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.jsx("h2",{className:"panel-title",children:"03_AGENT_CONTEXT"}),c.jsx("button",{onClick:Ae,disabled:n,"aria-label":"Refresh context summary",className:"refresh-btn",title:`Refresh context (next auto in ${ee(r)})`,children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n?"animate-spin":"",children:c.jsx("path",{d:"M21 12a9 9 0 11-6.219-8.56"})})})]}),c.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end"},children:[c.jsx("span",{className:"text-label-sm",style:{fontSize:"0.65rem",color:"var(--on-surface)"},children:L.label}),c.jsx("span",{className:"text-mono",style:{fontSize:"0.6rem",color:"var(--panel-label)"},children:L.sublabel})]})]}),v?c.jsxs("div",{"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:"24px",flex:1},children:[y&&c.jsx(IT,{sourceName:x.name,onDismiss:()=>{R(!0),w(!1)}}),e?c.jsxs(c.Fragment,{children:[m==="ollama"&&c.jsx(HT,{vramData:d}),c.jsx(hu,{label:"What is happening:",value:e.whatIsHappening}),c.jsx(hu,{label:"Current goal:",value:e.currentGoal}),c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[c.jsx("span",{className:"field-label",children:"Files changed:"}),e.filesChanged.length>0?c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px"},children:e.filesChanged.map(U=>c.jsx("span",{className:"file-tag",children:U.split("/").pop()},U))}):c.jsx("span",{className:"text-mono",style:{color:"var(--panel-label)",fontStyle:"italic",fontSize:"0.875rem"},children:"None"})]}),c.jsx(hu,{label:"Blockers:",value:e.blockers.length>0?e.blockers.join(", "):"None detected in workspace",isItalic:e.blockers.length===0})]}):c.jsx("div",{className:"text-body-md",style:{color:"var(--panel-label)"},children:"No context summary yet. Start an agent session to generate one."}),c.jsx($T,{events:o,formatTime:yt,formatLine:$e})]}):c.jsx("div",{className:"animate-pulse",style:{flex:1,display:"flex",flexDirection:"column",gap:"24px"},children:[1,2,3,4].map(U=>c.jsxs("div",{children:[c.jsx("div",{className:"skeleton-line",style:{width:"120px",height:"12px",marginBottom:"8px"}}),c.jsx("div",{className:"skeleton-line",style:{width:U===3?"60%":"80%",height:"18px"}})]},U))}),m==="ollama"&&c.jsx(jT,{}),m==="lm-studio"&&c.jsx(DT,{})]})}function IT({sourceName:e,onDismiss:t}){const[n,a]=b.useState(!1),s="/tmp/noter-generic-events.jsonl",i=()=>{navigator.clipboard.writeText(s),a(!0),setTimeout(()=>a(!1),2e3)};return c.jsxs("div",{style:{border:"1px solid var(--outline-variant)",padding:"16px",display:"flex",flexDirection:"column",gap:"12px"},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[c.jsx("span",{className:"field-label",children:"ONBOARDING"}),c.jsx("button",{onClick:t,className:"delete-btn","aria-label":"Dismiss onboarding",children:"×"})]}),c.jsx("div",{className:"text-body-md",style:{color:"var(--on-surface)",fontSize:"0.875rem"},children:"No harness detected. Using generic connector."}),c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[c.jsx("span",{className:"text-label-sm",style:{fontSize:"0.6rem"},children:"WATCHING"}),c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.jsx("span",{className:"text-mono",style:{fontSize:"0.75rem",color:"var(--on-surface)"},children:s}),c.jsx("button",{onClick:i,className:"text-label-sm",style:{fontSize:"0.6rem",border:"1px solid var(--outline-variant)",padding:"2px 6px",cursor:"pointer",background:"transparent",color:n?"var(--on-surface)":"var(--panel-label)"},children:n?"COPIED":"COPY"})]})]}),c.jsx("div",{className:"text-mono",style:{fontSize:"0.7rem",color:"var(--panel-label)",lineHeight:1.5},children:"Point your agent to write JSONL events to the path above to get started."})]})}function HT({vramData:e}){if(!e||!e.available)return c.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[c.jsx("span",{className:"field-label",children:"VRAM"}),c.jsx("span",{className:"text-mono",style:{fontSize:"0.75rem",color:"var(--panel-label)"},children:"VRAM data unavailable"})]});const t=e.totalGb>0?Math.min(100,e.usedGb/e.totalGb*100):0;return c.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[c.jsx("span",{className:"field-label",children:"VRAM"}),c.jsxs("span",{className:"text-label-sm",style:{fontSize:"0.75rem"},children:[t.toFixed(1),"% used"]})]}),c.jsx("div",{className:"memory-bar-track",children:c.jsx("div",{className:"memory-bar-fill",style:{width:`${t}%`}})}),c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[c.jsxs("span",{className:"text-label-sm",style:{fontSize:"0.7rem"},children:["USED: ",e.usedGb.toFixed(1)," GB"]}),c.jsxs("span",{className:"text-label-sm",style:{fontSize:"0.7rem"},children:["TOTAL: ",e.totalGb.toFixed(0)," GB"]})]})]})}function $T({events:e,formatTime:t,formatLine:n}){return e.length===0?null:c.jsxs("div",{className:"activity-log",children:[e.slice(0,3).reverse().map((a,s)=>c.jsxs("div",{className:"activity-log-entry",children:["[",t(a.timestamp),"] ",n(a)]},a.id||s)),c.jsx("span",{className:"activity-log-cursor"})]})}function hu({label:e,value:t,isItalic:n=!1}){return c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[c.jsx("span",{className:"field-label",children:e}),c.jsx("span",{className:"text-mono text-body-md",style:{color:"var(--on-surface)",fontStyle:n?"italic":"normal"},children:t})]})}function PT(){const[e,t]=b.useState([]),[n,a]=b.useState({});return b.useEffect(()=>(me.suggestions&&me.suggestions.length>0&&t(me.suggestions),me.subscribe("suggestions",i=>{i&&(t(i),a(r=>{const l=new Set(i.map(u=>u.id)),o={};for(const[u,h]of Object.entries(r))l.has(u)&&(o[u]=h);return o}))})),[]),c.jsxs("div",{className:"panel panel-content",role:"region","aria-label":"Suggested Prompts","aria-live":"polite",tabIndex:0,style:{gap:"24px"},children:[c.jsxs("header",{className:"panel-header",children:[c.jsx("h2",{className:"panel-title",children:"04_SUGGESTED_PROMPTS"}),c.jsxs("span",{className:"text-label-sm",children:[e.length," ACTIVE"]})]}),c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:e.length===0?c.jsx("div",{className:"text-body-md",style:{color:"var(--panel-label)"},children:"No tasks available for prompts."}):e.map(s=>c.jsx(qT,{task:s,promptData:n[s.id]||null,onSetPromptData:i=>a(r=>({...r,[s.id]:i})),onDelete:i=>{Do(i),t(r=>r.filter(l=>l.id!==i)),a(r=>{const l={...r};return delete l[i],l})}},s.id))})]})}function qT({task:e,promptData:t,onSetPromptData:n,onDelete:a}){const[s,i]=b.useState(!1),[r,l]=b.useState(null),[o,u]=b.useState(!1),h=async()=>{i(!0),l(null);try{const p=await fetch("/api/prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taskId:e.id,taskTitle:e.title})}),v=await p.json();if(!p.ok)throw new Error(v.error||"Failed to build prompt");n(v)}catch(p){l(p.message)}finally{i(!1)}},f=()=>{t!=null&&t.prompt&&(navigator.clipboard.writeText(t.prompt),u(!0),setTimeout(()=>u(!1),2e3))},d=()=>{n(null)};return c.jsxs("div",{className:"prompt-card",children:[c.jsx("div",{style:{display:"grid",gridTemplateRows:t?"0fr":"1fr",transition:"grid-template-rows 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},children:c.jsx("div",{style:{overflow:"hidden"},children:c.jsxs("div",{style:{opacity:t?0:1,transition:"opacity 0.2s",display:"flex",flexDirection:"column",gap:"8px"},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"8px"},children:[c.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:c.jsx("span",{className:`badge badge--${e.priority}`,children:e.priority})}),c.jsx("button",{onClick:()=>a(e.id),className:"delete-btn","aria-label":"Delete task",children:"×"})]}),c.jsx("h3",{style:{fontFamily:"var(--font-sans)",fontWeight:500,fontSize:"1rem",margin:0,color:"var(--on-surface)"},children:e.title}),c.jsx("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.jsx("button",{onClick:h,disabled:s,"aria-label":`Build prompt for ${e.title}`,style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",color:"var(--primary)",background:"transparent",border:"none",fontWeight:600,padding:0,textTransform:"uppercase",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:s?"Building...":"Build →"}),r&&c.jsx("span",{className:"text-mono",style:{color:"#FF0000",fontSize:"0.65rem"},children:r})]})})]})})}),c.jsx("div",{style:{display:"grid",gridTemplateRows:t?"1fr":"0fr",transition:"grid-template-rows 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},children:c.jsx("div",{style:{overflow:"hidden"},children:c.jsxs("div",{style:{opacity:t?1:0,transition:"opacity 0.2s 0.1s"},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[c.jsx("button",{onClick:d,"aria-label":"Back to task list",style:{background:"transparent",border:"none",color:"var(--panel-label)",cursor:"pointer",fontSize:"0.65rem",textTransform:"uppercase",fontFamily:"var(--font-mono)",padding:0,display:"flex",alignItems:"center",gap:"4px"},children:"← BACK TO LIST"}),c.jsxs("div",{style:{position:"relative"},children:[c.jsx("button",{onClick:f,"aria-label":"Copy prompt to clipboard",style:{background:"transparent",border:"none",color:"var(--panel-label)",cursor:"pointer",padding:0,display:"flex",alignItems:"center",opacity:o?.5:1},title:"Copy Prompt",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"})]})}),o&&c.jsx("span",{className:"text-label-sm",style:{position:"absolute",right:"20px",top:"0",fontSize:"0.5rem",color:"var(--primary)",lineHeight:"14px",whiteSpace:"nowrap"},children:"COPIED!"})]})]}),c.jsx("div",{className:"field-label",style:{marginBottom:"8px"},children:"EXPANDED PROMPT DEFINITION"}),c.jsx("div",{className:"prompt-code-block",children:t==null?void 0:t.prompt})]})})})]})}const GT=["opencode","claude-code","pi","codex","factory-droid","generic"],KT={opencode:"opencode","claude-code":"claude-code",pi:"pi",codex:"codex","factory-droid":"factory-droid",generic:"generic"},VT=["ollama","anthropic","openai","gemini","lm-studio","custom"],YT=new Set(["anthropic","openai","gemini"]);function FT(){const[e,t]=b.useState(me.config);return b.useEffect(()=>me.subscribe("config",a=>t(a)),[]),e}function JT({isOpen:e,onClose:t}){var _a;const{user:n,isSubscribed:a,signOut:s}=Os(),i=FT(),r=b.useRef(null),l=b.useRef(null),[o,u]=b.useState(null),h=b.useRef(null),[f,d]=b.useState([]),p=b.useRef([]),[v,_]=b.useState(!1),[x,g]=b.useState(0),m=5,y=b.useRef(0),[w,C]=b.useState(null),[R,O]=b.useState(null),z=b.useRef(null),[q,K]=b.useState(!1),[ve,Ae]=b.useState(0),[ee,yt]=b.useState(!1),[$e,L]=b.useState(null),[U,k]=b.useState({}),[se,j]=b.useState(null),[V,Re]=b.useState(!1),[ft,nt]=b.useState(!1),[Mt,xn]=b.useState([]),[va,Tn]=b.useState(!1),[En,Et]=b.useState(null),[Me,Lt]=b.useState([]),[Ne,vt]=b.useState(!1),[ke,B]=b.useState(null),[D,I]=b.useState(i.ollamaContextSize||0),[J,ae]=b.useState(i.lmStudioContextLength||0),[ce,Oe]=b.useState(null),[xe,te]=b.useState(null),[Q,re]=b.useState(i.customProviderName||""),[E,M]=b.useState(i.customProviderBaseUrl||""),[G,W]=b.useState(""),[ie,de]=b.useState(i.customProviderModel||"");b.useEffect(()=>{if(!e)return;const A=r.current;if(!A)return;const X='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',le=A.querySelector(X);le==null||le.focus();function _e(Ke){if(Ke.key==="Escape"){Ke.preventDefault(),t();return}if(Ke.key!=="Tab")return;const ts=r.current;if(!ts)return;const Dn=Array.from(ts.querySelectorAll(X));if(Dn.length===0)return;const ns=Dn[0],Vn=Dn[Dn.length-1];Ke.shiftKey?document.activeElement===ns&&(Ke.preventDefault(),Vn.focus()):document.activeElement===Vn&&(Ke.preventDefault(),ns.focus())}return document.addEventListener("keydown",_e),()=>document.removeEventListener("keydown",_e)},[e,t]);const ue=b.useCallback(A=>{u(A),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>u(null),2e3)},[]),Te=b.useCallback(async A=>{if(A.length!==0){Re(!0),nt(!0);try{const X=await fetch("/api/sessions/resolve-titles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionIds:A})});if(!X.ok)return;const _e=(await X.json()).titles??{};p.current=p.current.map(Ke=>_e[Ke.id]?{...Ke,title:_e[Ke.id]}:Ke),d([...p.current])}catch{}finally{Re(!1),nt(!1)}}},[]),he=b.useCallback(async(A=0,X=!1)=>{_(!0);try{const le=await fetch(`/api/sessions?limit=${m}&offset=${A}`);if(!le.ok)return;const _e=await le.json(),Ke=_e.sessions??[];if(A===0&&!X)p.current=Ke,y.current=Ke.length,d(Ke);else if(X){const ts=p.current.slice(m),Dn=new Set(Ke.map(Vn=>Vn.id)),ns=ts.filter(Vn=>!Dn.has(Vn.id));p.current=[...Ke,...ns],y.current=Ke.length,d(p.current)}else p.current=[...p.current,...Ke],y.current=p.current.length,d(p.current);g(_e.total??0),Ae(_e.pendingCount??0),yt(_e.hasMore??!1),(X||A===0)&&K(!1),_e.pendingCount&&_e.pendingCount>0}catch{}finally{_(!1)}},[m]),pe=b.useRef(null),Ie=b.useRef(null);b.useEffect(()=>{if(!e){z.current&&(clearInterval(z.current),z.current=null);return}return he(0),z.current=setInterval(()=>he(0,!0),1e4),()=>{z.current&&(clearInterval(z.current),z.current=null)}},[e,he]),b.useEffect(()=>{if(!e)return;const A=me.subscribe("event",()=>{pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{he(0,!0)},500)});return()=>{A(),pe.current&&(clearTimeout(pe.current),pe.current=null)}},[e,he]),b.useEffect(()=>{const A=me.subscribe("sessions-update",()=>{e&&(Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{he(0,!0)},200))});return()=>{A(),Ie.current&&(clearTimeout(Ie.current),Ie.current=null)}},[e,he]);const it=b.useCallback(async A=>{C(A),O(null);try{const X=await fetch("/api/sessions/select",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A})});if(X.ok)await he(0);else{const le=await X.json().catch(()=>({error:"Unknown error"}));O({id:A,message:le.error||"Failed to switch session"})}}catch{O({id:A,message:"Network error"})}finally{C(null)}},[he]),be=b.useCallback(async A=>{try{const X=await fetch("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});X.ok||console.error("Config update failed:",await X.text())}catch(X){console.error("Config update network error:",X)}},[]),es=A=>{K(!0),p.current=[],y.current=0,d([]),Ae(0),yt(!1),be({activeSource:A})},Rs=A=>{be({llmProvider:A})};b.useEffect(()=>{if(i.llmProvider!=="ollama"){xn([]),Et(null);return}let A=!1;return Tn(!0),Et(null),fetch("/api/ollama/tags").then(async X=>{if(A)return;if(!X.ok){const Ke=await X.json().catch(()=>({error:"Failed to fetch models"}));Et(Ke.error||"Failed to fetch models"),xn([]);return}const _e=(await X.json()).models??[];xn(_e),_e.length>0&&i.ollamaModel&&!_e.includes(i.ollamaModel)&&be({ollamaModel:_e[0]})}).catch(X=>{A||(Et(X instanceof Error?X.message:"Network error"),xn([]))}).finally(()=>{A||Tn(!1)}),()=>{A=!0}},[i.llmProvider,i.ollamaModel,be]),b.useEffect(()=>{if(i.llmProvider!=="lm-studio"){Lt([]),B(null);return}let A=!1;return vt(!0),B(null),fetch("/api/lmstudio/models").then(async X=>{if(A)return;if(!X.ok){const Ke=await X.json().catch(()=>({error:"Failed to fetch models"}));B(Ke.error||`LM Studio not reachable (${X.status})`),Lt([]);return}const _e=(await X.json()).models??[];Lt(_e),_e.length>0&&i.lmStudioModel&&!_e.includes(i.lmStudioModel)&&be({lmStudioModel:_e[0]})}).catch(()=>{A||(B("LM Studio not detected. Ensure it is running and the base URL is configured."),Lt([]))}).finally(()=>{A||vt(!1)}),()=>{A=!0}},[i.llmProvider,i.lmStudioModel,be]);const ba=A=>{A&&(be({apiKey:A}),ue("apiKey"))},Qe=A=>{A&&(be({ollamaModel:A}),ue("ollamaModel"))},Pt=A=>{A&&(be({lmStudioModel:A}),ue("lmStudioModel"))},Xe=A=>{A&&(be({lmStudioBaseUrl:A}),ue("lmStudioBaseUrl"))},zt=A=>{A&&(re(A),be({customProviderName:A}),ue("customProviderName"))},un=A=>{A&&(M(A),be({customProviderBaseUrl:A}),ue("customProviderBaseUrl"))},Sa=A=>{A&&(W(A),be({customProviderApiKey:A}),ue("customProviderApiKey"))},Mi=A=>{A&&(de(A),be({customProviderModel:A}),ue("customProviderModel"))},Ui=A=>{A&&(be({genericLogPath:A}),ue("genericLogPath"))},rl=A=>{const X=parseInt(A,10);if(A.trim()===""){I(0),Oe(null),be({ollamaContextSize:"0"}),ue("ollamaContextSize");return}if(isNaN(X)||X<512||X>131072){Oe("Must be 512–131072 or empty");return}Oe(null),I(X),be({ollamaContextSize:String(X)}),ue("ollamaContextSize")},Li=A=>{const X=parseInt(A,10);if(A.trim()===""){ae(0),te(null),be({lmStudioContextSize:"0"}),ue("lmStudioContextSize");return}if(isNaN(X)||X<512||X>131072){te("Must be 512–131072 or empty");return}te(null),ae(X),be({lmStudioContextSize:String(X)}),ue("lmStudioContextSize")},zi=b.useCallback(async A=>{if(se!==A){j(A),L(A);try{const X=await fetch("/api/sessions/summary",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A})});if(X.ok){const le=await X.json();k(_e=>({..._e,[A]:le.summary||""}))}else{const le=await X.json().catch(()=>({error:"Unknown error"}));k(_e=>({..._e,[A]:le.error||"Failed to generate summary"}))}}catch{k(X=>({...X,[A]:"Network error"}))}finally{j(null)}}},[se]),ll=YT.has(i.llmProvider||""),Bi=i.activeSource==="generic",hc=ee;return c.jsxs(c.Fragment,{children:[c.jsx("style",{children:`
87
+ @media (prefers-reduced-motion: reduce) {
88
+ .settings-drawer-panel { transition: none !important; }
89
+ }
90
+ `}),c.jsx("style",{children:`
91
+ @keyframes harnessProgress {
92
+ 0% { transform: scaleX(0); }
93
+ 50% { transform: scaleX(0.5); }
94
+ 100% { transform: scaleX(1); }
95
+ }
96
+ @media (prefers-reduced-motion: reduce) {
97
+ .settings-drawer-panel { transition: none !important; }
98
+ @keyframes harnessProgress {
99
+ 0% { transform: scaleX(1); }
100
+ 100% { transform: scaleX(1); }
101
+ }
102
+ }
103
+ `}),e&&c.jsx("div",{role:"presentation",onClick:t,style:{position:"fixed",inset:0,backgroundColor:"color-mix(in srgb, var(--surface) 60%, transparent)",zIndex:100}}),c.jsx("style",{children:`
104
+ @keyframes spin {
105
+ to { transform: rotate(360deg); }
106
+ }
107
+ `}),c.jsxs("div",{ref:r,role:"dialog","aria-modal":"true","aria-label":"Settings",className:"settings-drawer-panel",style:{position:"fixed",top:0,right:0,bottom:0,width:"380px",maxWidth:"100vw",backgroundColor:"var(--surface)",borderLeft:"1px solid var(--outline-variant)",zIndex:101,display:"flex",flexDirection:"column",transform:e?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out",borderRadius:0,overflowX:"hidden"},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"20px 24px",borderBottom:"1px solid var(--outline-variant)"},children:[c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",color:"var(--panel-label)"},children:"Settings"}),c.jsx("button",{ref:l,onClick:t,"aria-label":"Close settings",style:{background:"transparent",border:"none",color:"var(--panel-label)",cursor:"pointer",fontSize:"1rem",lineHeight:1,padding:"4px"},children:"×"})]}),c.jsxs("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden",minWidth:0,padding:"24px",display:"flex",flexDirection:"column",gap:"28px"},children:[c.jsxs(It,{label:"ACTIVE SOURCE",children:[c.jsx(zl,{value:i.resolvedSource||i.activeSource,options:GT.map(A=>({value:A,label:KT[A]??A})),onChange:es}),i.activeSource==="auto"&&i.resolvedSource&&c.jsxs("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:["auto-detected: ",i.resolvedSource]})]}),c.jsx(It,{label:"LLM PROVIDER",children:c.jsx(zl,{value:i.llmProvider||"ollama",options:VT.map(A=>({value:A,label:A})),onChange:Rs})}),ll&&c.jsx(It,{label:`API KEY — ${(i.llmProvider||"").toUpperCase()}`,children:c.jsx(ea,{type:"password",placeholder:"Enter API key",onSave:ba,saved:o==="apiKey"})}),Bi&&c.jsx(It,{label:"LOG PATH",children:c.jsx(ea,{type:"text",placeholder:i.genericLogPath||"/tmp/noter-generic-events.jsonl",onSave:Ui,saved:o==="genericLogPath"})}),(i.llmProvider||"ollama")==="ollama"&&c.jsx(It,{label:"OLLAMA MODEL",children:(i.llmProvider||"ollama")==="ollama"?c.jsx(c.Fragment,{children:va?c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)",padding:"10px 12px",border:"1px solid var(--outline-variant)",display:"block"},children:"LOADING MODELS…"}):En?c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"#FF4444",padding:"10px 12px",border:"1px solid var(--outline-variant)",display:"block"},children:En}):Mt.length===0?c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)",padding:"10px 12px",border:"1px solid var(--outline-variant)",display:"block"},children:"NO MODELS FOUND"}):c.jsx(zl,{value:i.ollamaModel||Mt[0],options:Mt.map(A=>({value:A,label:A})),onChange:Qe})}):c.jsx(ea,{type:"text",defaultValue:i.ollamaModel,placeholder:"e.g. llama3:8b",onSave:Qe,saved:o==="ollamaModel"})}),(i.llmProvider||"ollama")==="ollama"&&c.jsx(It,{label:"CONTEXT SIZE",children:c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[c.jsxs("div",{style:{display:"flex",gap:"8px"},children:[c.jsx("input",{type:"number",value:D||"",placeholder:"4096 (Ollama default)",min:512,max:131072,onChange:A=>I(parseInt(A.target.value,10)||0),onKeyDown:A=>{A.key==="Enter"&&rl(A.target.value)},style:{flex:1,backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-mono)",fontSize:"0.875rem",padding:"10px 12px",outline:"none",borderRadius:0}}),c.jsx("button",{onClick:()=>{const A=document.querySelector('[placeholder="4096 (Ollama default)"]');A&&rl(A.value)},style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",border:"1px solid var(--outline-variant)",padding:"8px 14px",backgroundColor:"transparent",color:"var(--on-surface)",cursor:"pointer",borderRadius:0},children:"SAVE"})]}),ce&&c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"#FF4444"},children:ce}),c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:"Maximum context tokens to allocate for this local model. Leave empty for Ollama default."}),o==="ollamaContextSize"&&c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:"SAVED"})]})}),i.llmProvider==="lm-studio"&&c.jsxs(c.Fragment,{children:[c.jsx(It,{label:"LM STUDIO BASE URL",children:c.jsx(ea,{type:"text",defaultValue:i.lmStudioBaseUrl||"http://localhost:1234/v1",placeholder:"http://localhost:1234/v1",onSave:Xe,saved:o==="lmStudioBaseUrl"})}),c.jsx(It,{label:"LM STUDIO MODEL",children:Ne?c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)",padding:"10px 12px",border:"1px solid var(--outline-variant)",display:"block"},children:"LOADING MODELS…"}):ke?c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"#FF4444",padding:"10px 12px",border:"1px solid var(--outline-variant)",display:"block"},children:ke}),c.jsx("button",{className:"btn-tertiary",onClick:()=>{B(null),vt(!0),fetch("/api/lmstudio/models").then(async A=>{if(!A.ok){const _e=await A.json().catch(()=>({error:"Failed to fetch models"}));B(_e.error||`LM Studio not reachable (${A.status})`),Lt([]);return}const le=(await A.json()).models??[];Lt(le),le.length>0&&be({lmStudioModel:le[0]})}).catch(()=>{B("LM Studio not detected. Ensure it is running and accessible."),Lt([])}).finally(()=>vt(!1))},style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",padding:"6px 12px",border:"1px solid var(--outline-variant)",background:"transparent",color:"var(--on-surface)",cursor:"pointer",borderRadius:0},children:"RETRY"})]}):Me.length===0?c.jsx(ea,{type:"text",defaultValue:i.lmStudioModel,placeholder:"e.g. my-model.gguf",onSave:Pt,saved:o==="lmStudioModel"}):c.jsx(zl,{value:i.lmStudioModel||Me[0],options:Me.map(A=>({value:A,label:A})),onChange:Pt})}),c.jsx(It,{label:"CONTEXT SIZE",children:c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[c.jsxs("div",{style:{display:"flex",gap:"8px"},children:[c.jsx("input",{type:"number",value:J||"",placeholder:"Set by LM Studio model config",min:512,max:131072,onChange:A=>ae(parseInt(A.target.value,10)||0),onKeyDown:A=>{A.key==="Enter"&&Li(A.target.value)},style:{flex:1,backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-mono)",fontSize:"0.875rem",padding:"10px 12px",outline:"none",borderRadius:0}}),c.jsx("button",{onClick:()=>{const A=document.querySelector('[placeholder="Set by LM Studio model config"]');A&&Li(A.value)},style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",border:"1px solid var(--outline-variant)",padding:"8px 14px",backgroundColor:"transparent",color:"var(--on-surface)",cursor:"pointer",borderRadius:0},children:"SAVE"})]}),xe&&c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"#FF4444"},children:xe}),c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:"Requested context allocation for the loaded local model. Configure in LM Studio if per-request override is unsupported."}),o==="lmStudioContextSize"&&c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:"SAVED"})]})})]}),i.llmProvider==="custom"&&c.jsxs(c.Fragment,{children:[c.jsx(It,{label:"PROVIDER NAME",children:c.jsx(ea,{type:"text",defaultValue:Q,placeholder:"My Provider",onSave:zt,saved:o==="customProviderName"})}),c.jsx(It,{label:"ENDPOINT URL",children:c.jsx(ea,{type:"text",defaultValue:E,placeholder:"https://your-api.com/v1/chat/completions",onSave:un,saved:o==="customProviderBaseUrl"})}),c.jsx(It,{label:"API KEY",children:c.jsx(ea,{type:"password",placeholder:"Enter API key",onSave:Sa,saved:o==="customProviderApiKey"})}),c.jsx(It,{label:"MODEL NAME",children:c.jsx(ea,{type:"text",defaultValue:ie,placeholder:"e.g. my-model-v2",onSave:Mi,saved:o==="customProviderModel"})})]}),c.jsxs(It,{label:"SESSION",children:[q&&c.jsx("div",{style:{height:"1px",width:"100%",backgroundColor:"var(--outline-variant)",transformOrigin:"left",animation:"harnessProgress 1.2s ease-in-out infinite",marginBottom:"8px"}}),v&&p.current.length===0||q?c.jsx(QT,{count:3}):p.current.length===0?c.jsx("div",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)",padding:"8px 0"},children:"NO SESSIONS FOUND"}):c.jsx(XT,{sessions:f,loadingSessionId:w,error:R,onSelect:it,onSummarize:zi,openSummaryId:$e,summaryMap:U,summaryLoadingId:se}),ft&&V&&c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 12px",marginTop:"8px",border:"1px solid var(--outline-variant)"},children:[c.jsx("div",{style:{width:"12px",height:"12px",border:"2px solid var(--outline-variant)",borderTopColor:"var(--on-surface)",animation:"spin 1s linear infinite",borderRadius:0}}),c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:"GENERATING TITLES…"})]}),hc&&c.jsx("button",{onClick:async()=>{await he(p.current.length);const A=p.current.filter(X=>!X.title||X.title===X.id).map(X=>X.id);A.length>0&&Te(A)},disabled:v||V,style:{width:"100%",backgroundColor:"transparent",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",padding:"10px 12px",cursor:v||V?"default":"pointer",marginTop:"8px",borderRadius:0,opacity:v||V?.7:1},onMouseEnter:A=>{!v&&!V&&(A.currentTarget.style.backgroundColor="var(--surface-container-high)")},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="transparent"},children:v?"LOADING…":V?"GENERATING TITLES…":`LOAD MORE (${ve} pending)`})]}),c.jsx(It,{label:"ACCOUNT",children:n?c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.875rem",color:"var(--on-surface)"},children:n.email||((_a=n.user_metadata)==null?void 0:_a.user_name)||"User"}),c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.7rem",textTransform:"uppercase",letterSpacing:"0.05rem",color:a?"var(--on-surface)":"var(--panel-label)",border:`1px solid ${a?"var(--on-surface)":"var(--outline-variant)"}`,padding:"2px 8px",display:"inline-block",width:"fit-content"},children:a?"PRO":"FREE"}),c.jsx("button",{onClick:async()=>{await s()},style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",padding:"8px 14px",border:"1px solid var(--outline-variant)",background:"transparent",color:"var(--panel-label)",cursor:"pointer",borderRadius:0},onMouseEnter:A=>{A.currentTarget.style.backgroundColor="var(--surface-container-high)"},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="transparent"},children:"SIGN OUT"})]}):c.jsx("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.875rem",color:"var(--panel-label)"},children:"Not signed in"})})]})]})]})}function It({label:e,children:t}){return c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[c.jsx("label",{style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",color:"var(--panel-label)"},children:e}),t]})}function zl({value:e,options:t,onChange:n}){const[a,s]=b.useState(!1),i=b.useRef(null);return b.useEffect(()=>{function r(l){i.current&&!i.current.contains(l.target)&&s(!1)}if(a)return document.addEventListener("mousedown",r),()=>document.removeEventListener("mousedown",r)},[a]),c.jsxs("div",{ref:i,style:{position:"relative"},children:[c.jsxs("button",{onClick:()=>s(r=>!r),"aria-haspopup":"listbox","aria-expanded":a,style:{width:"100%",backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-mono)",fontSize:"0.875rem",padding:"10px 12px",textAlign:"left",cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center",borderRadius:0},children:[c.jsx("span",{children:e}),c.jsx("span",{style:{fontSize:"0.65rem",color:"var(--panel-label)"},children:a?"▲":"▼"})]}),a&&c.jsx("ul",{role:"listbox",style:{position:"absolute",top:"100%",left:0,right:0,margin:0,padding:0,listStyle:"none",backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",borderTop:"none",zIndex:10,maxHeight:"240px",overflowY:"auto",borderRadius:0},children:t.map(r=>c.jsx("li",{role:"option","aria-selected":r.value===e,onClick:()=>{n(r.value),s(!1)},style:{padding:"10px 12px",fontFamily:"var(--font-mono)",fontSize:"0.875rem",color:"var(--on-surface)",cursor:"pointer",backgroundColor:r.value===e?"var(--surface)":"transparent"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="var(--surface)"},onMouseLeave:l=>{l.currentTarget.style.backgroundColor=r.value===e?"var(--surface)":"transparent"},children:r.label},r.value))})]})}function XT({sessions:e,loadingSessionId:t,error:n,onSelect:a,onSummarize:s,openSummaryId:i,summaryMap:r,summaryLoadingId:l}){return c.jsx("div",{style:{display:"flex",flexDirection:"column"},children:e.map((o,u)=>c.jsxs("div",{children:[u>0&&c.jsx("div",{style:{borderTop:"1px solid var(--outline-variant)"}}),c.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[c.jsxs("button",{onClick:()=>!o.active&&!t&&a(o.id),disabled:o.active||t===o.id,style:{width:"100%",backgroundColor:o.active?"var(--surface-container-high)":"transparent",border:"none",padding:"10px 12px",textAlign:"left",cursor:o.active?"default":"pointer",display:"flex",flexDirection:"column",gap:"4px",borderRadius:0,opacity:t&&t!==o.id?.5:1},onMouseEnter:h=>{o.active||(h.currentTarget.style.backgroundColor="var(--surface-container-high)")},onMouseLeave:h=>{o.active||(h.currentTarget.style.backgroundColor="transparent")},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.875rem",fontWeight:400,color:"var(--on-surface)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:o.title||o.id,children:o.title||o.id}),c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[o.active&&c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.65rem",textTransform:"uppercase",color:"var(--panel-label)",letterSpacing:"0.05em"},children:"● ACTIVE"}),t===o.id&&c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.65rem",textTransform:"uppercase",color:"var(--panel-label)",letterSpacing:"0.05em"},children:"SWITCHING…"})]})]}),c.jsx("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:c.jsxs("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:[WT(o.lastEventAt)," ·"," ",o.eventCount," events"]})}),n&&n.id===o.id&&c.jsxs("span",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)"},children:["FAILED — ",n.message]})]}),c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px",width:"100%",minWidth:0,padding:"0 12px 10px 12px",marginTop:"12px"},children:[i===o.id&&c.jsx("div",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--on-surface)",padding:"6px 8px",border:"1px solid var(--outline-variant)",backgroundColor:"var(--surface-container-lowest)",borderRadius:0,minWidth:0,overflow:"hidden",wordBreak:"break-word",whiteSpace:"normal"},children:r[o.id]||"…"}),c.jsx("span",{onClick:()=>s(o.id),style:{fontFamily:"var(--font-sans)",fontSize:"0.65rem",textTransform:"uppercase",color:"var(--panel-label)",letterSpacing:"0.05em",cursor:"pointer",border:"1px solid var(--outline-variant)",padding:"2px 6px",borderRadius:0,alignSelf:"flex-end"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="var(--surface-container-high)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent"},children:l===o.id?"SUMMARIZING…":"SUMMARIZE"})]})]})]},o.id))})}function QT({count:e}){return c.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Array.from({length:e}).map((t,n)=>c.jsxs("div",{children:[n>0&&c.jsx("div",{style:{borderTop:"1px solid var(--outline-variant)"}}),c.jsxs("div",{style:{padding:"10px 12px",display:"flex",flexDirection:"column",gap:"6px"},children:[c.jsx("div",{style:{height:"16px",width:"60%",backgroundColor:"var(--surface-container-high)",borderRadius:0}}),c.jsx("div",{style:{height:"12px",width:"40%",backgroundColor:"var(--surface-container-high)",borderRadius:0}})]})]},n))})}function WT(e){if(!e||e<=0)return"—";const n=Date.now()-e,a=Math.floor(n/1e3),s=Math.floor(a/60),i=Math.floor(s/60),r=Math.floor(i/24);return a<60?"just now":a<60?`${a}s ago`:s<60?`${s}m ago`:i<24?`${i}h ago`:r<7?`${r}d ago`:new Date(e).toLocaleDateString()}function ea({type:e,placeholder:t,defaultValue:n,onSave:a,saved:s}){const[i,r]=b.useState(n||""),l=b.useRef(null);b.useEffect(()=>{n!==void 0&&r(n)},[n]);const o=u=>{u.key==="Enter"&&a(i)};return c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[c.jsxs("div",{style:{display:"flex",gap:"8px"},children:[c.jsx("input",{ref:l,type:e,value:i,onChange:u=>r(u.target.value),onKeyDown:o,placeholder:t,style:{flex:1,backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-mono)",fontSize:"0.875rem",padding:"10px 12px",outline:"none",borderRadius:0}}),c.jsx("button",{onClick:()=>a(i),className:"btn-tertiary",style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",border:"1px solid var(--outline-variant)",padding:"8px 14px",backgroundColor:"transparent",color:"var(--on-surface)",cursor:"pointer",borderRadius:0},children:"SAVE"})]}),s&&c.jsx("span",{className:"text-mono",style:{fontSize:"0.75rem",color:"var(--panel-label)"},children:"SAVED"})]})}function ZT({content:e,onContentChange:t,onEditWithAI:n,isEditing:a}){const[s,i]=b.useState(!1),[r,l]=b.useState(!1),[o,u]=b.useState(e),[h,f]=b.useState(""),[d,p]=b.useState(!1),v=b.useRef(null);b.useEffect(()=>{u(e)},[e]);const _=b.useCallback(()=>{t(o),l(!1)},[o,t]),x=b.useCallback(()=>{u(e),l(!1)},[e]),g=b.useCallback(async()=>{h.trim()&&(await n(h),f(""),p(!1))},[h,n]),m=b.useCallback(y=>{y.key==="Escape"&&(d?(p(!1),f("")):r&&x()),y.key==="Enter"&&d&&!y.shiftKey&&(y.preventDefault(),g())},[d,r,x,g]);return s?c.jsxs("div",{className:"agentsmd-bar agentsmd-bar--collapsed",onClick:()=>i(!1),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&i(!1)},children:[c.jsx("span",{className:"agentsmd-bar__title",children:"AGENTS.md"}),c.jsx("span",{className:"agentsmd-bar__expand",children:"▼"})]}):c.jsxs("div",{className:"agentsmd-bar",onKeyDown:m,children:[c.jsxs("div",{className:"agentsmd-bar__header",children:[c.jsx("span",{className:"agentsmd-bar__title",children:"AGENTS.md"}),c.jsxs("div",{className:"agentsmd-bar__actions",children:[a&&c.jsx("span",{className:"agentsmd-bar__status",children:"EDITING…"}),!r&&!d&&c.jsxs(c.Fragment,{children:[c.jsx("button",{className:"btn-tertiary agentsmd-bar__btn",onClick:()=>l(!0),disabled:a,children:"EDIT"}),c.jsx("button",{className:"btn-tertiary agentsmd-bar__btn",onClick:()=>p(!0),disabled:a,children:"EDIT WITH AI"})]}),r&&c.jsxs(c.Fragment,{children:[c.jsx("button",{className:"btn-primary agentsmd-bar__btn",onClick:_,children:"SAVE"}),c.jsx("button",{className:"btn-tertiary agentsmd-bar__btn",onClick:x,children:"CANCEL"})]}),c.jsx("button",{className:"agentsmd-bar__collapse-btn",onClick:()=>i(!0),"aria-label":"Collapse AGENTS.md bar",children:"▲"})]})]}),r?c.jsx("textarea",{ref:v,className:"agentsmd-bar__editor",value:o,onChange:y=>u(y.target.value),autoFocus:!0}):c.jsx("div",{className:"agentsmd-bar__content",children:e?c.jsx("pre",{className:"agentsmd-bar__pre",children:e}):c.jsx("span",{className:"agentsmd-bar__empty",children:"No AGENTS.md found in repo root"})}),d&&c.jsxs("div",{className:"agentsmd-bar__ai-input",children:[c.jsx("input",{className:"agentsmd-bar__ai-field",type:"text",value:h,onChange:y=>f(y.target.value),placeholder:"Describe the change…",autoFocus:!0,disabled:a}),c.jsx("button",{className:"btn-primary agentsmd-bar__btn",onClick:g,disabled:a||!h.trim(),children:"APPLY"}),c.jsx("button",{className:"btn-tertiary agentsmd-bar__btn",onClick:()=>{p(!1),f("")},children:"CANCEL"})]})]})}const eE={done:"var(--outline-variant)",pending:"var(--outline-variant)",generating:"var(--outline-variant)",regenerating:"var(--outline-variant)"};function tm({phase:e,onRegenerate:t,isRegenerating:n,isUpdating:a=!1}){const[s,i]=b.useState(!1),[r,l]=b.useState(!1),o=b.useRef(null),u=b.useCallback(async()=>{try{await navigator.clipboard.writeText(e.prompt),l(!0),setTimeout(()=>l(!1),1500)}catch{const v=document.createRange();if(o.current){v.selectNodeContents(o.current);const _=window.getSelection();_&&(_.removeAllRanges(),_.addRange(v)),document.execCommand("copy"),_==null||_.removeAllRanges(),l(!0),setTimeout(()=>l(!1),1500)}}},[e.prompt]),h=b.useCallback(()=>{t(e.phaseNumber)},[t,e.phaseNumber]),f=n||a,d=n?"REGENERATING…":a?"UPDATING…":e.fresh?"UPDATED":e.status==="done"?"DONE":"PENDING",p=f||e.fresh?"var(--on-surface)":eE[e.status]||"var(--outline-variant)";return c.jsxs("div",{className:`spec-phase-card${f?" spec-phase-card--updating":""}${e.fresh&&!f?" spec-phase-card--fresh":""}`,style:{borderLeft:`3px solid ${p}`},role:f?void 0:"button",tabIndex:f?-1:0,onKeyDown:f?void 0:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),i(_=>!_))},onClick:f?void 0:()=>i(v=>!v),children:[c.jsxs("div",{className:"spec-phase-card__header",children:[c.jsxs("div",{className:"spec-phase-card__title-row",children:[c.jsxs("span",{className:"spec-phase-card__number",children:["PHASE ",e.phaseNumber]}),c.jsx("span",{className:"spec-phase-card__title",children:e.title})]}),c.jsxs("div",{className:"spec-phase-card__meta",children:[c.jsx("span",{className:"spec-phase-card__status",children:d}),c.jsxs("span",{className:"spec-phase-card__tokens",children:[e.tokenCount," tokens"]}),c.jsx("span",{className:"spec-phase-card__expand-icon",children:s?"▼":"▶"})]})]}),s&&c.jsxs("div",{className:"spec-phase-card__body",onClick:v=>v.stopPropagation(),children:[e.techStack.length>0&&c.jsxs("div",{className:"spec-phase-card__section",children:[c.jsx("span",{className:"spec-phase-card__label",children:"TECH STACK"}),c.jsx("div",{className:"spec-phase-card__tags",children:e.techStack.map((v,_)=>c.jsx("span",{className:"file-tag",children:v},_))})]}),c.jsxs("div",{className:"spec-phase-card__section",children:[c.jsx("span",{className:"spec-phase-card__label",children:"RATIONALE"}),c.jsx("p",{className:"spec-phase-card__rationale",children:e.rationale})]}),c.jsxs("div",{className:"spec-phase-card__section",children:[c.jsxs("div",{className:"spec-phase-card__prompt-header",children:[c.jsx("span",{className:"spec-phase-card__label",children:"PROMPT BLOCK"}),c.jsxs("span",{className:"spec-phase-card__tokens-detail",children:[e.tokenCount," tokens"]})]}),c.jsx("div",{className:"spec-phase-card__prompt",ref:o,children:c.jsx("pre",{className:"spec-phase-card__prompt-pre",children:e.prompt})}),c.jsxs("div",{className:"spec-phase-card__prompt-actions",children:[c.jsx("button",{className:"btn-tertiary spec-phase-card__action-btn",onClick:u,disabled:a,children:r?"COPIED":"COPY PROMPT"}),c.jsx("button",{className:"btn-tertiary spec-phase-card__action-btn",onClick:h,disabled:f,children:a?"UPDATING…":n?"REGENERATING…":"REGENERATE"})]})]})]})]})}const nm={clarification:{borderColor:"#3B82F6",label:"CLARIFICATION"},decision:{borderColor:"#F59E0B",label:"DECISION"},confirmation:{borderColor:"#6B7280",label:"CONFIRMATION"}};function tE({question:e,anchorRect:t,onAnswer:n,onSkip:a}){const[s,i]=b.useState(""),r=b.useRef(null);b.useEffect(()=>{var x;(x=r.current)==null||x.focus()},[]);const l=b.useCallback(()=>{s.trim()&&n(e.id,s.trim())},[s,e.id,n]),o=b.useCallback(()=>{a(e.id)},[e.id,a]),u=b.useCallback(x=>{x.key==="Escape"&&(x.stopPropagation(),o()),x.key==="Enter"&&(x.preventDefault(),l())},[o,l]),h=nm[e.type]||nm.confirmation,f=400;let d=120,p=16;t&&(d=t.bottom+4,p=t.left);const v=typeof window<"u"?window.innerWidth:1200;p+f>v-16&&(p=Math.max(16,v-f-16));const _=typeof window<"u"?window.innerHeight:800;return t&&d+200>_-16&&(d=Math.max(16,t.top-4-200)),c.jsxs("div",{className:"clarification-popup",style:{borderTop:`2px solid ${h.borderColor}`,top:`${d}px`,left:`${p}px`},onKeyDown:u,children:[c.jsx("div",{className:"clarification-popup__type",children:h.label}),c.jsxs("div",{className:"clarification-popup__anchor",children:["Context: “",e.anchorText,"”"]}),c.jsx("div",{className:"clarification-popup__question",children:e.question}),e.options&&e.options.length>0&&c.jsx("div",{className:"clarification-popup__options",children:e.options.map((x,g)=>c.jsx("button",{className:"btn-tertiary clarification-popup__option-btn",onClick:()=>n(e.id,x),children:x},g))}),e.assumption&&c.jsxs("div",{className:"clarification-popup__assumption",children:["Assumption if skipped: ",e.assumption]}),c.jsxs("div",{className:"clarification-popup__input-row",children:[c.jsx("input",{ref:r,className:"clarification-popup__input",type:"text",value:s,onChange:x=>i(x.target.value),placeholder:"Your answer…"}),c.jsx("button",{className:"btn-primary clarification-popup__submit-btn",onClick:l,disabled:!s.trim(),children:"SUBMIT"}),c.jsx("button",{className:"btn-tertiary clarification-popup__skip-btn",onClick:o,children:"SKIP"})]})]})}const nE=["openai","anthropic","google","ollama","lm-studio","custom"],am={openai:"OpenAI",anthropic:"Anthropic",google:"Google",ollama:"Ollama","lm-studio":"LM Studio",custom:"Custom Provider"},aE={openai:"e.g. gpt-4o",anthropic:"e.g. claude-sonnet-4-5",google:"e.g. gemini-2.5-pro"};function sE(e){return e==="openai"||e==="anthropic"||e==="google"}function fu(e){return{...e,apiKeys:{...e.apiKeys},models:{...e.models}}}function iE({isOpen:e,onClose:t,config:n,onSave:a}){const[s,i]=b.useState(()=>fu(n)),[r,l]=b.useState(!1),[o,u]=b.useState(!1),[h,f]=b.useState([]),[d,p]=b.useState(!1),[v,_]=b.useState(!1),[x,g]=b.useState([]),[m,y]=b.useState(!1),[w,C]=b.useState(!1),[R,O]=b.useState({});b.useEffect(()=>{e&&(i(fu(n)),l(!1),u(!1),z(),q())},[e,n]);const z=b.useCallback(async()=>{_(!0);try{const j=await fetch("/api/ollama/tags");if(j.ok){const V=await j.json(),Re=Array.isArray(V.models)?V.models:[];f(Re),p(Re.length>0),Re.length>0&&!s.ollamaModel&&i(ft=>({...ft,ollamaModel:Re[0]}))}else f([]),p(!1)}catch{f([]),p(!1)}finally{_(!1)}},[s.ollamaModel]),q=b.useCallback(async()=>{C(!0);try{const j=await fetch("/api/lmstudio/models");if(j.ok){const Re=(await j.json()).models??[];g(Re),y(Re.length>0),Re.length>0&&!s.lmStudioModel&&i(ft=>({...ft,lmStudioModel:Re[0]}))}else g([]),y(!1)}catch{g([]),y(!1)}finally{C(!1)}},[s.lmStudioModel]),K=b.useCallback(j=>{i(V=>({...V,...j})),l(!0)},[]),ve=b.useCallback(j=>{i(V=>({...V,provider:j})),l(!0)},[]),Ae=b.useCallback((j,V)=>{i(Re=>({...Re,apiKeys:{...Re.apiKeys,[j]:V}})),l(!0)},[]),ee=b.useCallback((j,V)=>{i(Re=>({...Re,models:{...Re.models,[j]:V}})),l(!0)},[]),yt=b.useCallback(()=>{r&&!o?u(!0):t()},[r,o,t]),$e=b.useCallback(()=>{a(s),t()},[s,a,t]),L=b.useCallback(()=>{u(!1),i(fu(n)),l(!1),t()},[n,t]);b.useEffect(()=>{if(!e)return;const j=V=>{V.key==="Escape"&&yt()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[e,yt]);const U=b.useCallback(j=>{O(V=>({...V,[j]:!V[j]}))},[]);if(!e)return null;const k=sE(s.provider)?s.provider:null,se=s.provider==="custom"?!!(s.customName.trim()&&s.customEndpoint.trim()&&s.customApiKey.trim()&&s.customModel.trim()):s.provider==="lm-studio"?!!(s.lmStudioModel.trim()&&m):s.provider==="ollama"?!!(s.ollamaModel.trim()&&d):k?!!(s.apiKeys[k].trim()&&s.models[k].trim()):!1;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"model-drawer-backdrop",onClick:yt}),c.jsxs("div",{className:"model-drawer",children:[c.jsxs("div",{className:"model-drawer__header",children:[c.jsx("span",{className:"model-drawer__title",children:"Model Settings"}),c.jsx("button",{className:"model-drawer__close",onClick:yt,"aria-label":"Close drawer",children:"✕"})]}),o&&c.jsxs("div",{className:"model-drawer__unsaved",children:[c.jsx("span",{className:"model-drawer__unsaved-text",children:"Unsaved changes — Save or discard?"}),c.jsxs("div",{className:"model-drawer__unsaved-actions",children:[c.jsx("button",{className:"btn-tertiary",onClick:()=>u(!1),children:"Cancel"}),c.jsx("button",{className:"btn-tertiary",onClick:L,children:"Discard"}),c.jsx("button",{className:"btn-primary",onClick:$e,children:"Save"})]})]}),c.jsxs("div",{className:"model-drawer__content",children:[c.jsxs("div",{className:"model-drawer__section",children:[c.jsx("span",{className:"model-drawer__label",children:"Provider"}),c.jsx("div",{className:"model-drawer__providers",children:nE.map(j=>c.jsx("button",{className:`model-drawer__provider-btn${s.provider===j?" model-drawer__provider-btn--active":""}`,onClick:()=>ve(j),children:am[j]},j))})]}),k&&c.jsxs("div",{className:"model-drawer__section",children:[c.jsxs("span",{className:"model-drawer__label",children:[am[k]," Configuration"]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"API Key"}),c.jsxs("div",{className:"model-drawer__password-row",children:[c.jsx("input",{type:R[`apikey-${k}`]?"text":"password",className:"model-drawer__input",placeholder:"Enter API key",value:s.apiKeys[k],onChange:j=>Ae(k,j.target.value)}),c.jsx("button",{className:"btn-tertiary model-drawer__show-btn",onClick:()=>U(`apikey-${k}`),children:R[`apikey-${k}`]?"HIDE":"SHOW"})]})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Model Name"}),c.jsx("input",{type:"text",className:"model-drawer__input",placeholder:aE[k],value:s.models[k],onChange:j=>ee(k,j.target.value)})]})]}),s.provider==="ollama"&&c.jsxs("div",{className:"model-drawer__section",children:[c.jsx("span",{className:"model-drawer__label",children:"Ollama"}),v?c.jsx("span",{className:"model-drawer__hint",children:"Detecting..."}):d?c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Model"}),c.jsx("select",{className:"model-drawer__select",value:s.ollamaModel,onChange:j=>K({ollamaModel:j.target.value}),children:h.map(j=>c.jsx("option",{value:j,children:j},j))})]}):c.jsxs("div",{className:"model-drawer__ollama-missing",children:[c.jsxs("span",{className:"model-drawer__hint",children:["Ollama not detected at ",s.ollamaBaseUrl||"localhost:11434"]}),c.jsx("button",{className:"btn-tertiary",onClick:z,children:"Retry"})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Base URL"}),c.jsx("input",{type:"text",className:"model-drawer__input",placeholder:"http://localhost:11434",value:s.ollamaBaseUrl,onChange:j=>K({ollamaBaseUrl:j.target.value})})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Context Size (tokens)"}),c.jsx("input",{type:"number",className:"model-drawer__input",placeholder:"4096 (Ollama default)",value:s.ollamaContextSize||"",min:512,max:131072,onChange:j=>{const V=parseInt(j.target.value,10);K({ollamaContextSize:isNaN(V)?0:Math.min(131072,Math.max(0,V))})}}),c.jsx("span",{className:"model-drawer__hint",children:"Leave empty for Ollama default. Range: 512–131072"})]})]}),s.provider==="lm-studio"&&c.jsxs("div",{className:"model-drawer__section",children:[c.jsx("span",{className:"model-drawer__label",children:"LM Studio"}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Base URL"}),c.jsx("input",{type:"text",className:"model-drawer__input",placeholder:"http://localhost:1234/v1",value:s.lmStudioBaseUrl,onChange:j=>K({lmStudioBaseUrl:j.target.value})})]}),w?c.jsx("span",{className:"model-drawer__hint",children:"Detecting…"}):m?c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Model"}),c.jsx("select",{className:"model-drawer__select",value:s.lmStudioModel,onChange:j=>K({lmStudioModel:j.target.value}),children:x.map(j=>c.jsx("option",{value:j,children:j},j))})]}):c.jsxs("div",{className:"model-drawer__ollama-missing",children:[c.jsxs("span",{className:"model-drawer__hint",children:["LM Studio not detected at ",s.lmStudioBaseUrl||"http://localhost:1234/v1"]}),c.jsx("button",{className:"btn-tertiary",onClick:q,children:"Retry"})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Context Length (tokens)"}),c.jsx("input",{type:"number",className:"model-drawer__input",placeholder:"Set by LM Studio model config",value:s.lmStudioContextLength||"",readOnly:!m,onChange:j=>{const V=parseInt(j.target.value,10);K({lmStudioContextLength:isNaN(V)?0:V})}}),!m&&c.jsx("span",{className:"model-drawer__hint",children:"Configure context length in LM Studio directly"})]})]}),s.provider==="custom"&&c.jsxs("div",{className:"model-drawer__section",children:[c.jsx("span",{className:"model-drawer__label",children:"Custom Provider"}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Provider Name"}),c.jsx("input",{type:"text",className:"model-drawer__input",placeholder:"My Provider",value:s.customName,onChange:j=>K({customName:j.target.value})})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Endpoint URL"}),c.jsx("input",{type:"text",className:"model-drawer__input",placeholder:"https://your-api.com/v1/chat/completions",value:s.customEndpoint,onChange:j=>K({customEndpoint:j.target.value})})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"API Key"}),c.jsxs("div",{className:"model-drawer__password-row",children:[c.jsx("input",{type:R["custom-apikey"]?"text":"password",className:"model-drawer__input",placeholder:"Enter API key",value:s.customApiKey,onChange:j=>K({customApiKey:j.target.value})}),c.jsx("button",{className:"btn-tertiary model-drawer__show-btn",onClick:()=>U("custom-apikey"),children:R["custom-apikey"]?"HIDE":"SHOW"})]})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Model Name"}),c.jsx("input",{type:"text",className:"model-drawer__input",placeholder:"e.g. my-custom-model-v2",value:s.customModel,onChange:j=>K({customModel:j.target.value})})]})]}),c.jsx("div",{className:"model-drawer__section",children:c.jsxs("div",{className:"model-drawer__toggle-row",children:[c.jsx("span",{className:"model-drawer__label",children:"Stream output"}),c.jsx("button",{className:`model-drawer__toggle${s.streamOutput?" model-drawer__toggle--on":""}`,onClick:()=>K({streamOutput:!s.streamOutput}),role:"switch","aria-checked":s.streamOutput,children:c.jsx("span",{className:"model-drawer__toggle-thumb"})})]})}),c.jsxs("div",{className:"model-drawer__section",children:[c.jsx("span",{className:"model-drawer__label",children:"Grounding Tools"}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Context7 API Key"}),c.jsxs("div",{className:"model-drawer__password-row",children:[c.jsx("input",{type:R.context7?"text":"password",className:"model-drawer__input",placeholder:"Enter Context7 API key",value:s.context7ApiKey,onChange:j=>K({context7ApiKey:j.target.value})}),c.jsx("button",{className:"btn-tertiary model-drawer__show-btn",onClick:()=>U("context7"),children:R.context7?"HIDE":"SHOW"})]})]}),c.jsxs("div",{className:"model-drawer__field",children:[c.jsx("span",{className:"model-drawer__field-label",children:"Exa API Key"}),c.jsxs("div",{className:"model-drawer__password-row",children:[c.jsx("input",{type:R.exa?"text":"password",className:"model-drawer__input",placeholder:"Enter Exa web search API key",value:s.exaApiKey,onChange:j=>K({exaApiKey:j.target.value})}),c.jsx("button",{className:"btn-tertiary model-drawer__show-btn",onClick:()=>U("exa"),children:R.exa?"HIDE":"SHOW"})]})]})]}),c.jsx("div",{className:"model-drawer__footer",children:c.jsx("button",{className:"btn-primary model-drawer__save-btn",onClick:$e,disabled:!se,children:"Save"})})]})]})]})}const rE=[/\bmamba\b/i,/\bssm\b/i,/\bstate\.space\b/i,/\bzamba\b/i,/\bfalcon-mamba\b/i],lE=[/\bqwq\b/i,/\bdeepseek-r\d\b/i,/\bdeepseek-reasoner\b/i,/\bo1-(?:mini|preview|pro)\b/i,/\bo3-(?:mini|pro)\b/i,/\bclaude.*thinking\b/i,/\bthinking\b/i],oE=[/\b0\.\d+b\b/,/\b1\.\d+b\b(?!y)/,/\b2\.\d+b\b(?!y)/,/\b3\.\d+b\b(?!y)/,/\b\d{1,2}m\b/,/\btiny/i,/\bmini(?![\w-]*(?:pro|max|large))/i,/\bsmall\b/i,/\bmicro\b/i],cE=[/\bgpt-4o\b/i,/\bgpt-4-turbo\b/i,/\bclaude-sonnet/i,/\bclaude-opus/i,/\bclaude-3\.5/i,/\bgemini-2\.5/i,/\bgemini-1\.5/i];function Ch(e,t){return e?rE.some(n=>n.test(e)):!1}function sl(e){return e?lE.some(t=>t.test(e)):!1}function uE(e){return!e||Ch(e)?!1:oE.some(t=>t.test(e))}function Di(e,t,n){if(!e)return"native";if(Ch(e)||uE(e))return"json-schema";if(cE.some(s=>s.test(e)))return"native";const a=e.match(/(\d+\.?\d*)b/i);if(a){const s=parseFloat(a[1]);if(s>=7)return"native";if(s>=1)return"json-schema"}return"native"}function il(e){let t=e.replace(/<think>[\s\S]*?<\/think>/gi,"");return t=t.replace(/[◁◂][\s\S]*?[▷▸]/g,""),t=t.replace(/```thinking[\s\S]*?```/gi,""),t.trim()}function dE(e,t){return`${e}
108
+
109
+ ---
110
+
111
+ ${t}`}async function*uc(e){if(!e)return;const t=e.getReader(),n=new TextDecoder;let a="";for(;;){const{done:s,value:i}=await t.read();if(s)break;a+=n.decode(i,{stream:!0});const r=a.split(`
112
+ `);a=r.pop()||"";for(const l of r)yield l}a&&(yield a)}function hE(e){return e.provider==="custom"?e.customModel:e.provider==="ollama"?e.ollamaModel:e.provider==="lm-studio"?e.lmStudioModel:e.models[e.provider]||""}function fE(e){if(!e||!e.trim())throw new Error("LM Studio base URL is not configured");let t=e.trim();try{new URL(t)}catch{throw new Error("Invalid LM Studio endpoint configuration")}return t=t.replace(/\/+$/,""),t.endsWith("/v1")?t:t+"/v1"}function dc(e,t){return Di(t)==="json-schema"?dE("You are a helpful Spec-Driven Development architect. Respond with structured JSON output following the specified schema.",e):e}async function*sm(e,t,n,a,s,i){var h,f,d;Di(n);const r=sl(n),l=dc(a,n),o={model:n,messages:[{role:"user",content:l}],stream:!0};let u;try{u=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(o),signal:s})}catch(p){if(p instanceof DOMException&&p.name==="AbortError")throw p;const v="provider";throw new Error(`${v} server is unreachable at ${e.replace(/\/chat\/completions$/,"").replace(/\/v1$/,"")}. Check if the service is running and the endpoint URL is correct.`)}if(!u.ok){const p=await u.text().catch(()=>"");throw u.status===404?new Error(`Model endpoint not found at ${e}. Verify the model name and base URL.`):u.status===401||u.status===403?new Error("Authentication failed for provider. Check your API key."):new Error(`Provider request failed (${u.status}): ${p.slice(0,200)}`)}for await(const p of uc(u.body)){if(!p.startsWith("data: "))continue;const v=p.slice(6).trim();if(v==="[DONE]")break;try{const x=((d=(f=(h=JSON.parse(v).choices)==null?void 0:h[0])==null?void 0:f.delta)==null?void 0:d.content)||"";x&&(yield r?il(x):x)}catch{}}}async function*pE(e,t,n,a){var o;Di(t);const s=sl(t),i=dc(n,t),r={model:t,max_tokens:4096,messages:[{role:"user",content:i}],stream:!0};s&&(r.thinking={type:"enabled",budget_tokens:8192});let l;try{l=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json"},body:JSON.stringify(r),signal:a})}catch(u){throw u instanceof DOMException&&u.name==="AbortError"?u:new Error("Cannot reach Anthropic API. Check your network connection.")}if(!l.ok){const u=await l.text().catch(()=>"");throw l.status===401||l.status===403?new Error("Authentication failed for Anthropic API. Check your API key."):new Error(`Anthropic request failed (${l.status}): ${u.slice(0,200)}`)}for await(const u of uc(l.body)){if(!u.startsWith("data: "))continue;const h=u.slice(6).trim();if(h==="[DONE]")break;try{const f=JSON.parse(h);if(f.type==="content_block_delta"){const d=((o=f.delta)==null?void 0:o.text)||"";d&&(yield s?il(d):d)}}catch{}}}async function*mE(e,t,n,a){var u,h,f,d,p;Di(t);const s=sl(t),r={contents:[{parts:[{text:dc(n,t)}]}]},l=`https://generativelanguage.googleapis.com/v1beta/models/${t}:streamGenerateContent?alt=sse&key=${e}`;let o;try{o=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:a})}catch(v){throw v instanceof DOMException&&v.name==="AbortError"?v:new Error("Cannot reach Google Gemini API. Check your network connection.")}if(!o.ok){const v=await o.text().catch(()=>"");throw o.status===401||o.status===403?new Error("Authentication failed for Google Gemini API. Check your API key."):new Error(`Gemini request failed (${o.status}): ${v.slice(0,200)}`)}for await(const v of uc(o.body)){if(!v.startsWith("data: "))continue;const _=v.slice(6).trim();try{const g=((p=(d=(f=(h=(u=JSON.parse(_).candidates)==null?void 0:u[0])==null?void 0:h.content)==null?void 0:f.parts)==null?void 0:d[0])==null?void 0:p.text)||"";g&&(yield s?il(g):g)}catch{}}}async function*gE(e,t,n,a,s){Di(e);const i=sl(e),r=dc(t,e),l={model:e,prompt:r,stream:!0};a&&a>0&&(l.options={...l.options||{},num_ctx:a});const o=(s||"http://localhost:11434").replace(/\/$/,"")+"/api/generate";let u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),signal:n})}catch(p){throw p instanceof DOMException&&p.name==="AbortError"?p:new Error(`Cannot reach Ollama at ${o}. Ensure Ollama is running and the base URL is correct.`)}if(!u.ok){const p=await u.text().catch(()=>"");throw u.status===404?new Error(`Ollama model not found. Check if "${e}" is pulled and Ollama is running.`):u.status===400?new Error(`Invalid request to Ollama: ${p.slice(0,200)}`):new Error(`Ollama request failed (${u.status}): ${p.slice(0,200)}`)}const h=u.body.getReader(),f=new TextDecoder;let d="";for(;;){const{done:p,value:v}=await h.read();if(p)break;d+=f.decode(v,{stream:!0});const _=d.split(`
113
+ `);d=_.pop()||"";for(const x of _)if(x.trim())try{const m=JSON.parse(x).response||"";m&&(yield i?il(m):m)}catch{}}}async function*yE(e,t,n,a,s){var o,u,h;let i;try{i=fE(e)}catch(f){throw new Error(f instanceof Error?f.message:"Invalid LM Studio configuration")}const r={baseUrl:i,model:t,prompt:n};s&&s>0&&(r.contextLength=s);let l;try{l=await fetch("/api/blueprint/lm-studio-stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:a})}catch(f){throw f instanceof DOMException&&f.name==="AbortError"?f:new Error("Cannot reach Noter server to proxy LM Studio request. Check if the server is running.")}if(!l.ok){let f=`LM Studio request failed (${l.status})`;try{const d=await l.json();d.error&&(f=d.error)}catch{}throw new Error(f)}for await(const f of uc(l.body)){if(!f.startsWith("data: "))continue;const d=f.slice(6).trim();if(d==="[DONE]")break;try{const v=((h=(u=(o=JSON.parse(d).choices)==null?void 0:o[0])==null?void 0:u.delta)==null?void 0:h.content)||"";v&&(yield v)}catch{}}}async function*Ed(e,t,n){const{provider:a}=t;if(a==="openai")yield*sm("https://api.openai.com/v1/chat/completions",t.apiKeys.openai,t.models.openai,e,n);else if(a==="anthropic")yield*pE(t.apiKeys.anthropic,t.models.anthropic,e,n);else if(a==="google")yield*mE(t.apiKeys.google,t.models.google,e,n);else if(a==="ollama")yield*gE(t.ollamaModel,e,n,t.ollamaContextSize,t.ollamaBaseUrl);else if(a==="lm-studio")yield*yE(t.lmStudioBaseUrl,t.lmStudioModel,e,n,t.lmStudioContextLength);else if(a==="custom")yield*sm(t.customEndpoint,t.customApiKey,t.customModel,e,n);else throw new Error(`Unknown provider: ${a}`)}async function vE(e,t,n){let a="";for await(const i of Ed(e,t,n))a+=i;const s=hE(t);return sl(s)&&(a=il(a)),a}const Dv="noter_blueprint_state";function bE(){return fetch("/api/blueprint-state").then(e=>e.ok?e.json():null).then(e=>(e==null?void 0:e.blueprint)||null).catch(()=>null)}function Bl(e){return fetch("/api/blueprint-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).then(t=>t.ok).catch(()=>!1)}function Il(e){try{localStorage.setItem(Dv,JSON.stringify(e))}catch{}}function SE(){try{const e=localStorage.getItem(Dv);if(e)return JSON.parse(e)}catch{}return null}const Ad=.05,_E=.3,wE=.15,Cd=1500,Mv=new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","is","it","this","that","are","be","as","was","were","been","have","has","had","do","does","did","will","would","could","should","may","might","can","shall","not","no","nor","so","if","then","than","too","very","just","about","above","after","before","between","into","through","during","each","few","more","most","other","some","such","only","own","same","also","how","what","when","where","which","who","whom","why","all","both","each","every","any"]);function Uv(e,t){const n=e.split(`
114
+ `),a=t.split(`
115
+ `),s=new Set(n),i=new Set(a),r=a.filter(o=>!s.has(o)),l=n.filter(o=>!i.has(o));return{added:r,removed:l}}const xE=[{pattern:/^#{1,4}\s/m,label:"heading"},{pattern:/^[-*+]\s/m,label:"list"},{pattern:/^\d+\.\s/m,label:"numbered_list"},{pattern:/^```/m,label:"code_block"},{pattern:/^>\s/m,label:"blockquote"},{pattern:/^---+/m,label:"horizontal_rule"}];function TE(e,t){const n=[],a=Uv(e,t).added.join(`
116
+ `);for(const{pattern:s,label:i}of xE){const r=(e.match(s)||[]).length;(t.match(s)||[]).length!==r&&n.push(i),a&&s.test(a)&&(n.includes(i)||n.push(i))}return{hasStructuralChange:n.length>0,changes:n}}function Lv(e){return new Set(e.toLowerCase().split(/[^a-zA-Z0-9]+/).filter(t=>t.length>2&&!Mv.has(t)))}function EE(e){return e.map(t=>({id:t.id,titleWords:Lv(t.title),techStack:t.techStack.map(n=>n.toLowerCase()),promptPreview:(t.prompt||"").slice(0,150).toLowerCase()}))}function AE(e,t){let n=0,a=0;for(const s of e)t.titleWords.has(s)&&(n+=2),t.techStack.some(i=>i.includes(s)||s.includes(i))&&(n+=2),t.promptPreview.includes(s)&&(n+=1),a++;return a>0?n/a:0}function zv(e,t){if(!e&&!t)return{changeRatio:0,addedText:"",removedText:"",hasStructuralChange:!1,structuralChanges:[],changedLineCount:0,totalLineCount:0};if(!e)return{changeRatio:1/0,addedText:t,removedText:"",hasStructuralChange:!0,structuralChanges:["heading"],changedLineCount:t.split(`
117
+ `).length,totalLineCount:0};const{added:n,removed:a}=Uv(e,t),s=TE(e,t),i=n.join(`
118
+ `),r=a.join(`
119
+ `),l=e.replace(/\s+/g," ").trim(),o=t.replace(/\s+/g," ").trim();if(l===o)return{changeRatio:0,addedText:"",removedText:"",hasStructuralChange:!1,structuralChanges:[],changedLineCount:0,totalLineCount:e.split(`
120
+ `).length};const u=i.length+r.length;return{changeRatio:e.length>0?u/e.length:t.length>0?1/0:0,addedText:i,removedText:r,hasStructuralChange:s.hasStructuralChange,structuralChanges:s.changes,changedLineCount:n.length+a.length,totalLineCount:e.split(`
121
+ `).length}}function pu(e,t){if(t.length===0)return[];if(e.hasStructuralChange&&e.structuralChanges.includes("heading")&&e.changeRatio>Ad)return t.map(r=>r.id);const n=EE(t),a=`${e.addedText} ${e.removedText}`.slice(0,Cd),s=Lv(a),i=[];for(const r of n)AE(s,r)>=wE&&i.push(r.id);return i}function CE(e,t,n,a,s){if(s.length===0)return{decision:"full_update",affectedPhaseIds:[],reason:"No existing phases — first generation required",confidence:"high"};const i=zv(e,t),r=OE(n,a);if(r.hasNewAnswers&&i.changeRatio===0){const l=pu({...i,addedText:r.newAnswerText,removedText:"",changeRatio:r.newAnswerText.length/Math.max(e.length,1)},s);return{decision:l.length>0?"partial_update":"full_update",affectedPhaseIds:l.length>0?l:s.map(o=>o.id),reason:l.length>0?`Clarification answer affects ${l.length} phase(s)`:"New clarification answers — full review needed",confidence:l.length>0?"high":"medium"}}if(i.changeRatio===0&&!r.hasNewAnswers)return{decision:"no_update",affectedPhaseIds:[],reason:"No change detected",confidence:"high"};if(i.changeRatio<Ad&&!i.hasStructuralChange){const l=pu(i,s);return l.length===0?{decision:"no_update",affectedPhaseIds:[],reason:`Change too minor (${(i.changeRatio*100).toFixed(1)}% of input) and no phase overlap`,confidence:"high"}:`${i.addedText} ${i.removedText}`.trim().split(/[^a-zA-Z0-9]+/).filter(h=>h.length>2&&!Mv.has(h.toLowerCase())).filter(h=>h.toLowerCase()!=="the"&&h.toLowerCase()!=="and").length<2?{decision:"no_update",affectedPhaseIds:[],reason:"Change too minor — fewer than 2 meaningful content words changed",confidence:"high"}:{decision:"partial_update",affectedPhaseIds:l,reason:`Minor change affects ${l.length} phase(s)`,confidence:"medium"}}if(i.changeRatio<_E||i.changeRatio>=Ad&&!i.hasStructuralChange){const l=pu(i,s);return l.length>0&&l.length<s.length?{decision:"partial_update",affectedPhaseIds:l,reason:`Change affects ${l.length}/${s.length} phase(s)`,confidence:"high"}:{decision:"full_update",affectedPhaseIds:s.map(o=>o.id),reason:`Change scope covers most/all phases (${i.changeRatio.toFixed(2)} ratio)`,confidence:"medium"}}return{decision:"full_update",affectedPhaseIds:s.map(l=>l.id),reason:`Major change (${(i.changeRatio*100).toFixed(1)}% of input, structural: ${i.structuralChanges.join(", ")||"none"})`,confidence:i.changeRatio>=.5?"high":"medium"}}function OE(e,t){const n=[],a=[],s=[];for(const[i,r]of Object.entries(t))i in e?e[i]!==r&&(a.push(i),s.push(r)):(n.push(i),s.push(r));return{hasNewAnswers:n.length>0||a.length>0,newAnswerIds:n,newAnswerText:s.join(" "),changedAnswerIds:a}}function RE(e,t){const n=e.filter(a=>t.includes(a.id));return JSON.stringify(n.map(a=>{var s;return{id:a.id,phaseNumber:a.phaseNumber,title:a.title,techStack:a.techStack,rationale:a.rationale,promptPreview:((s=a.prompt)==null?void 0:s.slice(0,200))||""}}))}function im(e,t,n,a,s,i){const r=s!=null&&s.trim()?`
122
+ ## Project Constraints (AGENTS.md)
123
+ ${s}
124
+ `:"",l=i&&Object.keys(i).length>0?`
125
+ ## Answered Clarifications
126
+ ${Object.entries(i).map(([f,d])=>`- ${f}: ${d}`).join(`
127
+ `)}
128
+ `:"",o=`
129
+ ## Change Summary
130
+ Added:
131
+ ${a.addedText.slice(0,Cd)||"(none)"}
132
+
133
+ Removed:
134
+ ${a.removedText.slice(0,Cd)||"(none)"}
135
+ `,u=RE(t,n),h=JSON.stringify(t.filter(f=>!n.includes(f.id)).map(f=>({id:f.id,phaseNumber:f.phaseNumber,title:f.title})));return`You are a Spec-Driven Development architect performing a targeted UPDATE of specific phases.
136
+
137
+ ${r}
138
+ ${l}
139
+ ${o}
140
+ ## Current Notes (Left Column)
141
+ ${e}
142
+
143
+ ## Affected Phases (UPDATE these)
144
+ ${u}
145
+
146
+ ## Unaffected Phases (preserve as-is — do NOT include in response)
147
+ ${h}
148
+
149
+ ## Your Task
150
+ Return ONLY the affected phases with updates. Do NOT return unchanged phases.
151
+
152
+ Return a JSON object:
153
+ {
154
+ "phases": [
155
+ {
156
+ "id": "phase-N",
157
+ "phaseNumber": N,
158
+ "title": "Updated title",
159
+ "techStack": ["library@version"],
160
+ "rationale": "Why these choices",
161
+ "prompt": "Self-contained prompt. Include AGENTS.md constraints prefix if present.",
162
+ "tokenCount": 0
163
+ }
164
+ ],
165
+ "removedPhases": [],
166
+ "clarifications": []
167
+ }
168
+
169
+ Rules:
170
+ - Return ONLY the affected phases in "phases". Do NOT include unaffected phases.
171
+ - Each phase prompt must be SELF-CONTAINED.
172
+ - Prepend AGENTS.md content to every prompt as constraint layer if present.
173
+ - If the change doesn't actually require updating a phase, return {"phases":[],"removedPhases":[],"clarifications":[]}.
174
+ - Token count ≈ prompt.length / 4.
175
+ - Return ONLY JSON, no markdown fences`}class mu{constructor(t=5*60*1e3){this.cache=new Map,this.ttlMs=t}get(t){const n=this.cache.get(t);return n?Date.now()-n.timestamp>this.ttlMs?(this.cache.delete(t),null):n.result:null}set(t,n){this.cache.set(t,{result:n,timestamp:Date.now()})}clear(){this.cache.clear()}static contentKey(t){return t.slice(0,500)}}function NE(){const e={provider:"anthropic",apiKeys:{openai:"",anthropic:"",google:""},models:{openai:"",anthropic:"",google:""},ollamaModel:"",ollamaBaseUrl:"http://localhost:11434",ollamaContextSize:0,lmStudioBaseUrl:"http://localhost:1234/v1",lmStudioModel:"",lmStudioContextLength:0,customName:"",customEndpoint:"",customApiKey:"",customModel:"",streamOutput:!0,context7ApiKey:"",exaApiKey:""};try{const t=localStorage.getItem("blueprint_provider");t&&(e.provider=t);const n=["openai","anthropic","google"];for(const d of n){const p=localStorage.getItem(`blueprint_apikey_${d}`);p!==null&&(e.apiKeys[d]=p);const v=localStorage.getItem(`blueprint_model_${d}`);v!==null&&(e.models[d]=v)}const a=localStorage.getItem("blueprint_custom_provider");if(a){const d=JSON.parse(a);d.name!==void 0&&(e.customName=d.name),d.endpoint!==void 0&&(e.customEndpoint=d.endpoint),d.apiKey!==void 0&&(e.customApiKey=d.apiKey),d.model!==void 0&&(e.customModel=d.model)}const s=localStorage.getItem("blueprint_ollama_model");s!==null&&(e.ollamaModel=s);const i=localStorage.getItem("blueprint_ollama_base_url");i!==null&&(e.ollamaBaseUrl=i);const r=localStorage.getItem("blueprint_ollama_context_size");if(r!==null){const d=parseInt(r,10);isNaN(d)||(e.ollamaContextSize=d)}const l=localStorage.getItem("blueprint_lm_studio");if(l){const d=JSON.parse(l);d.baseUrl!==void 0&&(e.lmStudioBaseUrl=d.baseUrl),d.model!==void 0&&(e.lmStudioModel=d.model)}const o=localStorage.getItem("blueprint_lm_studio_context_length");if(o!==null){const d=parseInt(o,10);isNaN(d)||(e.lmStudioContextLength=d)}const u=localStorage.getItem("blueprint_stream_output");u!==null&&(e.streamOutput=u==="true");const h=localStorage.getItem("blueprint_context7_apikey");h!==null&&(e.context7ApiKey=h);const f=localStorage.getItem("blueprint_exa_apikey");f!==null&&(e.exaApiKey=f)}catch{}return e}function kE(e){localStorage.setItem("blueprint_provider",e.provider);const t=["openai","anthropic","google"];for(const n of t)localStorage.setItem(`blueprint_apikey_${n}`,e.apiKeys[n]),localStorage.setItem(`blueprint_model_${n}`,e.models[n]);localStorage.setItem("blueprint_custom_provider",JSON.stringify({name:e.customName,endpoint:e.customEndpoint,apiKey:e.customApiKey,model:e.customModel})),localStorage.setItem("blueprint_ollama_model",e.ollamaModel),e.ollamaBaseUrl?localStorage.setItem("blueprint_ollama_base_url",e.ollamaBaseUrl):localStorage.removeItem("blueprint_ollama_base_url"),e.ollamaContextSize>0?localStorage.setItem("blueprint_ollama_context_size",String(e.ollamaContextSize)):localStorage.removeItem("blueprint_ollama_context_size"),localStorage.setItem("blueprint_lm_studio",JSON.stringify({baseUrl:e.lmStudioBaseUrl,model:e.lmStudioModel})),e.lmStudioContextLength>0?localStorage.setItem("blueprint_lm_studio_context_length",String(e.lmStudioContextLength)):localStorage.removeItem("blueprint_lm_studio_context_length"),localStorage.setItem("blueprint_stream_output",String(e.streamOutput)),localStorage.setItem("blueprint_context7_apikey",e.context7ApiKey),localStorage.setItem("blueprint_exa_apikey",e.exaApiKey)}const jE=800,rm="blueprint_spec_input";function DE(){var re;const{isSubscribed:e}=Os(),[t,n]=b.useState(""),[a,s]=b.useState(!1),[i,r]=b.useState([]),[l,o]=b.useState([]),[u,h]=b.useState(null),[f,d]=b.useState(null),[p,v]=b.useState(!1),[_,x]=b.useState(""),[g,m]=b.useState(null),[y,w]=b.useState(new Set),[C,R]=b.useState(null),[O,z]=b.useState({}),[q,K]=b.useState(!1),[ve,Ae]=b.useState(!1),[ee,yt]=b.useState(NE),[$e,L]=b.useState("");b.useEffect(()=>{kE(ee),ee.context7ApiKey&&fetch("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({context7ApiKey:ee.context7ApiKey})}).catch(()=>{}),ee.exaApiKey&&fetch("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({exaApiKey:ee.exaApiKey})}).catch(()=>{})},[ee]),b.useEffect(()=>{const E=ee.provider==="custom"?ee.customModel:ee.provider==="ollama"?ee.ollamaModel:ee.provider==="lm-studio"?ee.lmStudioModel:ee.models[ee.provider]||"",M=Di(E);Ch(E)?L("Mamba — JSON tool mode"):L(M==="json-schema"?"Small model — JSON tool mode":"")},[ee]);const U=b.useMemo(()=>ee.provider==="custom"?`${ee.customName||"Custom"} — ${ee.customModel||""}`:ee.provider==="ollama"?`Ollama — ${ee.ollamaModel||""}`:ee.provider==="lm-studio"?`LM Studio — ${ee.lmStudioModel||""}`:`${{openai:"OpenAI",anthropic:"Anthropic",google:"Google"}[ee.provider]} — ${ee.models[ee.provider]||""}`,[ee]),k=b.useRef(""),se=b.useRef(null),j=b.useRef(null),V=b.useRef(null),Re=b.useRef(null),ft=b.useRef(""),nt=b.useRef({}),Mt=b.useRef(new mu);b.useEffect(()=>{async function E(){try{const M=await fetch("/api/repo-context");if(M.ok){const W=(await M.json()).repoContext;W!=null&&W.repoInstructions&&n(W.repoInstructions)}}catch{}}E()},[]),b.useEffect(()=>{async function E(){const M=await bE();if(M&&M.phases.length>0){r(M.phases),o(M.clarifications||[]),z(M.annotations||{});return}const G=SE();G&&G.phases.length>0&&(r(G.phases),o(G.clarifications||[]),z(G.annotations||{}))}E()},[]),b.useEffect(()=>{if(i.length===0&&Object.keys(O).length===0)return;const E={phases:i,clarifications:l,annotations:O,updatedAt:Date.now()};Il(E),Bl(E).catch(()=>{})},[i,l,O]);const xn=b.useRef(async()=>{}),va=b.useRef(async()=>{}),Tn=b.useRef([]),En=b.useRef({});b.useEffect(()=>{Tn.current=i},[i]),b.useEffect(()=>{En.current=O},[O]),b.useEffect(()=>{if(!i.some(G=>G.fresh))return;const M=setTimeout(()=>{r(G=>G.map(W=>W.fresh?{...W,fresh:!1}:W))},2e3);return()=>clearTimeout(M)},[i]);const Et=b.useCallback(()=>{se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{Tn.current.length>0?va.current():xn.current()},jE)},[]),Me=b.useCallback(E=>{const M=k.current;k.current=E,E!==M&&(ft.current||(ft.current=M||E),Et())},[Et]),Lt=b.useCallback((E,M,G,W)=>{const ie=t!=null&&t.trim()?`
176
+ ## Project Constraints (AGENTS.md)
177
+ ${t}
178
+ `:"",de=W!=null&&W.trim()?`
179
+ ## External Grounding (verified via search)
180
+ ${W}
181
+
182
+ All spec decisions should be consistent with the grounding above where applicable.
183
+ `:"",ue=Object.keys(G).length>0?`
184
+ ## Answered Clarifications
185
+ ${Object.entries(G).map(([he,pe])=>`- ${he}: ${pe}`).join(`
186
+ `)}
187
+ `:"",Te=M.map(he=>({id:he.id,phaseNumber:he.phaseNumber,title:he.title,techStack:he.techStack,rationale:he.rationale,prompt:he.prompt}));return`You are a Spec-Driven Development architect performing an incremental UPDATE of an existing plan.
188
+
189
+ ${ie}
190
+ ${de}
191
+ ${ue}
192
+ ## Current Notes (Left Column)
193
+ ${E}
194
+
195
+ ## Current Plan
196
+ ${JSON.stringify(Te)}
197
+
198
+ ## Your Task
199
+ Compare the current notes, answered clarifications, and current plan. Return ONLY the phases that need to change — updated phases, new phases, or phases to remove. Do NOT return unchanged phases.
200
+
201
+ Return a JSON object with this exact structure:
202
+ {
203
+ "phases": [
204
+ // Include ONLY phases that are new or have changes. Use same phaseNumber for updates.
205
+ {
206
+ "id": "phase-1",
207
+ "phaseNumber": 1,
208
+ "title": "Updated or new title",
209
+ "techStack": ["library@version"],
210
+ "rationale": "Why these choices",
211
+ "prompt": "Self-contained prompt for coding agent. MUST include AGENTS.md constraints as prefix if present.",
212
+ "tokenCount": 0
213
+ }
214
+ ],
215
+ "removedPhases": [2, 5],
216
+ "clarifications": [
217
+ // Only if new ambiguities arise that weren't in previous clarifications
218
+ {
219
+ "id": "cl-new-1",
220
+ "type": "clarification",
221
+ "anchorText": "The ambiguous text",
222
+ "question": "What do you mean by X?",
223
+ "assumption": "I assumed X means Y",
224
+ "options": ["Option A", "Option B"]
225
+ }
226
+ ]
227
+ }
228
+
229
+ Rules:
230
+ - Return ONLY changed/new phases in "phases". Omit unchanged phases entirely.
231
+ - Use "removedPhases" array to list phase numbers that should be deleted.
232
+ - Each phase prompt must be SELF-CONTAINED.
233
+ - Prepend AGENTS.md content to every prompt as constraint layer if present.
234
+ - If no changes are needed, return {"phases":[],"removedPhases":[],"clarifications":[]}.
235
+ - Token count ≈ prompt.length / 4.
236
+ - Return ONLY JSON, no markdown fences`},[t]),Ne=b.useCallback((E,M,G)=>{const W=t!=null&&t.trim()?`
237
+ ## Project Constraints (AGENTS.md)
238
+ ${t}
239
+
240
+ All spec decisions must respect these constraints. Every generated prompt must include the AGENTS.md content as a constraint prefix.
241
+ `:"",ie=M?`
242
+ Regenerate ONLY Phase ${M}. Use the current notes and constraints to produce an updated version of that single phase.
243
+ `:"",de=G!=null&&G.trim()?`
244
+ ## External Grounding (verified via search)
245
+ Use the following verified information to fill knowledge gaps and validate assumptions:
246
+ ${G}
247
+
248
+ All spec decisions should be consistent with the grounding above where applicable.
249
+ `:"";return`You are a Spec-Driven Development architect. Generate a phased implementation spec from developer intent.
250
+
251
+ ${W}
252
+ ${de}
253
+ ## Developer Intent (Left Column)
254
+ ${E}
255
+
256
+ ${ie}
257
+ ## Your Task
258
+ 1. Analyze the developer's intent above
259
+ 2. Break the work into numbered implementation phases
260
+ 3. For each phase, provide:
261
+ - Phase number and title
262
+ - Tech stack decisions (specific library names and versions)
263
+ - Rationale: why these choices were made
264
+ - A self-contained prompt block that a coding agent can execute with no prior context beyond the AGENTS.md constraints
265
+ 4. If you detect genuine ambiguity in the intent, list clarification questions (max 3)
266
+
267
+ ## Output Format
268
+ Return a JSON object with this exact structure:
269
+ {
270
+ "phases": [
271
+ {
272
+ "id": "phase-1",
273
+ "phaseNumber": 1,
274
+ "title": "Phase title",
275
+ "techStack": ["library@version"],
276
+ "rationale": "Why these choices",
277
+ "prompt": "Self-contained prompt for coding agent. MUST include AGENTS.md constraints as prefix if present.",
278
+ "tokenCount": 0
279
+ }
280
+ ],
281
+ "clarifications": [
282
+ {
283
+ "id": "cl-1",
284
+ "type": "clarification",
285
+ "anchorText": "The ambiguous text from intent",
286
+ "question": "What do you mean by X?",
287
+ "assumption": "I assumed X means Y",
288
+ "options": ["Option A", "Option B"]
289
+ }
290
+ ]
291
+ }
292
+
293
+ Rules:
294
+ - Each phase prompt must be SELF-CONTAINED — a coding agent must execute it with no prior context
295
+ - Prepend AGENTS.md content to every prompt as constraint layer
296
+ - Use "clarification" type for ambiguous intent, "decision" for architectural choices, "confirmation" for assumptions
297
+ - Ask only questions the developer can answer — never ask questions resolvable by web search
298
+ - Token count is approximate character count / 4
299
+ - Return ONLY the JSON, no markdown fences`},[t]),vt=b.useCallback(E=>{if(!(t!=null&&t.trim()))return E;const M=`## Project Constraints (AGENTS.md)
300
+ ${t}
301
+
302
+ `;return E.map(G=>{var ie;const W=(ie=G.prompt)!=null&&ie.startsWith(M)?G.prompt:`${M}${G.prompt||""}`;return{...G,prompt:W}})},[t]),[ke,B]=b.useState(!1),D=b.useCallback(async E=>{const M=[],G=`modern best practices for: ${E.slice(0,300)}`;try{const W=await fetch("/api/blueprint/ground",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:G})});if(W.ok){const ie=await W.json();ie.grounding&&M.push(ie.grounding)}}catch{}return M.join(`
303
+
304
+ `)},[]),I=b.useCallback(async()=>{const E=k.current;if(!(E!=null&&E.trim()))return;j.current&&j.current.abort();const M=new AbortController;j.current=M,v(!0),x(""),R(null),o([]),h(null),B(!0);let G="";try{G=await D(E)}catch{}B(!1);const W=Ne(E,void 0,G);try{let ie="";for await(const de of Ed(W,ee,M.signal))ie+=de,x(ie);try{const de=ie.replace(/^```json?\n?/,"").replace(/\n?```$/,"").trim(),ue=JSON.parse(de);let Te=(ue.phases||[]).map(pe=>({...pe,tokenCount:pe.tokenCount||Math.ceil((pe.prompt||"").length/4),id:pe.id||`phase-${pe.phaseNumber}`,status:"done"}));Te=vt(Te),Te=Te.sort((pe,Ie)=>pe.phaseNumber-Ie.phaseNumber).map((pe,Ie)=>({...pe,phaseNumber:Ie+1})),r(Te);const he=ue.clarifications||[];o(he),he.length>0&&h(he[0])}catch{const de={id:"phase-1",phaseNumber:1,title:"Implementation Plan",techStack:[],rationale:"Generated from developer intent",prompt:ie,tokenCount:Math.ceil(ie.length/4),status:"done"};r(vt([de]))}}catch(ie){if(ie instanceof DOMException&&ie.name==="AbortError")return;const de=ie instanceof Error?ie.message:"Generation failed";R(de),setTimeout(()=>R(null),8e3)}finally{M.signal.aborted||(v(!1),x("")),j.current===M&&(j.current=null)}},[Ne,vt,ee]);xn.current=I;const J=b.useCallback(async()=>{const E=k.current;if(!(E!=null&&E.trim()))return;const M=Tn.current,G=En.current;if(M.length===0)return;const W=CE(ft.current,E,nt.current,G,M),ie=zv(ft.current,E);if(ft.current=E,nt.current={...G},W.decision==="no_update"){v(!1),x(""),B(!1),V.current&&(clearTimeout(V.current),V.current=null),w(new Set);return}j.current&&j.current.abort();const de=new AbortController;j.current=de,v(!0),x(""),R(null);const ue=W.decision==="partial_update";B(!0);let Te="";if(ue){const pe=mu.contentKey(E),Ie=Mt.current.get(pe);if(Ie)Te=Ie;else try{Te=await D(E),Mt.current.set(pe,Te)}catch{}}else try{Te=await D(E);const pe=mu.contentKey(E);Mt.current.set(pe,Te)}catch{}B(!1);let he;ue?(he=im(E,M,W.affectedPhaseIds,ie,t||void 0,G),Te!=null&&Te.trim()&&(he=`
305
+ ## External Grounding (verified via search)
306
+ ${Te}
307
+
308
+ All spec decisions should be consistent with the grounding above where applicable.
309
+ ${he}`)):he=Lt(E,M,G,Te);try{let pe="";for await(const Ie of Ed(he,ee,de.signal))pe+=Ie,x(pe);try{const Ie=pe.replace(/^```json?\n?/,"").replace(/\n?```$/,"").trim(),it=JSON.parse(Ie),be=(it.phases||[]).map(Qe=>({...Qe,tokenCount:Qe.tokenCount||Math.ceil((Qe.prompt||"").length/4),id:Qe.id||`phase-${Qe.phaseNumber}`,status:"done",fresh:!0})),es=it.removedPhases||[],Rs=new Set(be.map(Qe=>Qe.id));V.current&&clearTimeout(V.current),w(Rs),V.current=setTimeout(()=>{w(new Set),V.current=null},500),r(Qe=>{const Pt=new Map(Qe.map(Xe=>[Xe.phaseNumber,{...Xe,status:"done",fresh:!1}]));for(const Xe of vt(be))Pt.set(Xe.phaseNumber,Xe);for(const Xe of es)Pt.delete(Xe);return Array.from(Pt.entries()).sort(([Xe],[zt])=>Xe-zt).map(([,Xe],zt)=>({...Xe,phaseNumber:zt+1}))});const ba=it.clarifications||[];ba.length>0&&(o(Qe=>{const Pt=new Set(Qe.map(zt=>zt.id)),Xe=[...Qe];for(const zt of ba)Pt.has(zt.id)||Xe.push(zt);return Xe}),z(Qe=>{const Pt=ba.filter(Xe=>!Qe[Xe.id]);return Pt.length>0&&h(Pt[0]),Qe}))}catch{console.warn("[Blueprint] Update response was not valid JSON — preserving existing phases."),r(Ie=>Ie.map(it=>({...it,status:"done"})))}}catch(pe){if(pe instanceof DOMException&&pe.name==="AbortError")return;const Ie=pe instanceof Error?pe.message:"Update failed";R(Ie),r(it=>it.map(be=>({...be,status:"done"}))),setTimeout(()=>R(null),8e3)}finally{de.signal.aborted||(v(!1),x("")),j.current===de&&(j.current=null)}},[Lt,im,vt,D,ee,t]);va.current=J;const ae=b.useCallback(async()=>{const E=k.current;!(E!=null&&E.trim())||p||await I()},[I,p]);b.useEffect(()=>()=>{se.current&&clearTimeout(se.current),j.current&&j.current.abort(),V.current&&clearTimeout(V.current)},[]);const ce=b.useCallback(async E=>{var ie;const M=k.current;if(!(M!=null&&M.trim()))return;m(E);let G="";try{G=await D(M)}catch{}const W=Ne(M,E,G);try{const de=await vE(W,ee);let ue=de.replace(/^```json?\n?/,"").replace(/\n?```$/,"").trim(),Te;try{Te=JSON.parse(ue)}catch{Te={phases:[{id:`phase-${E}`,phaseNumber:E,title:`Phase ${E}`,techStack:[],rationale:"Regenerated from developer intent",prompt:de,tokenCount:Math.ceil(de.length/4),status:"done"}]}}const he=(ie=Te.phases)==null?void 0:ie[0];if(he){const pe=vt([he]);r(Ie=>Ie.map(it=>it.phaseNumber===E?{...pe[0],id:it.id,status:"done"}:it))}}catch(de){R(de instanceof Error?de.message:"Regeneration failed"),setTimeout(()=>R(null),5e3)}finally{m(null)}},[Ne,vt,ee]),Oe=b.useCallback(async E=>{s(!0);try{const M=await fetch("/api/blueprint/agents-md-edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentsMdContent:t,editInstruction:E})});if(!M.ok){const W=await M.json().catch(()=>({}));throw new Error(W.error||`Edit failed: ${M.status}`)}const G=await M.json();n(G.updatedContent)}catch(M){R(M instanceof Error?M.message:"AGENTS.md edit failed"),setTimeout(()=>R(null),5e3)}finally{s(!1)}},[t]),xe=b.useCallback((E,M)=>{nt.current={...En.current},z(G=>{const W={...G,[E]:M},ie=l.filter(de=>de.id!==E&&!W[de.id]);return ie.length>0?h(ie[0]):h(null),W}),Et()},[l,Et]),te=b.useCallback(E=>{const M=l.find(W=>W.id===E),G=M!=null&&M.assumption?`[SKIPPED] ${M.assumption}`:"[SKIPPED]";nt.current={...En.current},z(W=>{const ie={...W,[E]:G},de=l.filter(ue=>ue.id!==E&&!ie[ue.id]);return de.length>0?h(de[0]):h(null),ie}),Et()},[l,Et]),Q=b.useCallback(E=>{const M=document.querySelector(".notes-block-editor");if(!M)return null;const G=M.querySelectorAll('[contenteditable="true"]');for(const W of G)if((W.textContent||"").includes(E))return W.getBoundingClientRect();return null},[]);return b.useEffect(()=>{if(u){const E=Q(u.anchorText);d(E)}else d(null)},[u,Q]),e?c.jsxs("div",{className:"blueprint-page",children:[c.jsx(ZT,{content:t,onContentChange:n,onEditWithAI:Oe,isEditing:a}),c.jsxs("div",{className:"blueprint-columns",children:[c.jsxs("div",{className:"blueprint-left",children:[c.jsxs("header",{className:"blueprint-left__header blueprint-column-header",children:[c.jsx("h2",{className:"panel-title",children:"SPEC_INPUT"}),c.jsx("button",{className:"btn-tertiary btn-clear",onClick:()=>{if((k.current.trim()!==""||Object.keys(O).length>0||l.length>0)&&!window.confirm("Clear all input, questions, and responses? This cannot be undone."))return;r([]),o([]),z({}),x(""),R(null),localStorage.removeItem(rm),k.current="";const M={phases:[],clarifications:[],annotations:{},updatedAt:Date.now()};Il(M),Bl(M).catch(()=>{}),Re.current&&Re.current()},"aria-label":"Clear spec input",children:"CLEAR"})]}),c.jsx(lv,{storageKey:rm,onContentChange:Me,onClearRef:Re}),u&&c.jsx(tE,{question:u,anchorRect:f,onAnswer:xe,onSkip:te}),Object.keys(O).length>0&&c.jsx("div",{className:`blueprint-responses${ve?" blueprint-responses--collapsed":""}`,onClick:ve?()=>Ae(!1):void 0,role:ve?"button":void 0,tabIndex:ve?0:void 0,onKeyDown:ve?E=>{(E.key==="Enter"||E.key===" ")&&Ae(!1)}:void 0,children:ve?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"panel-title",children:"QUESTIONS_RESPONSES"}),c.jsx("span",{className:"blueprint-responses__arrow",children:"▼"})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"blueprint-responses__header",children:[c.jsx("span",{className:"panel-title",children:"QUESTIONS_RESPONSES"}),c.jsxs("div",{className:"blueprint-responses__header-actions",children:[c.jsx("button",{className:"btn-tertiary btn-clear",onClick:()=>{o([]),z({}),h(null);const E={phases:i,clarifications:[],annotations:{},updatedAt:Date.now()};Il(E),Bl(E).catch(()=>{})},"aria-label":"Clear all clarification questions and responses",children:"CLEAR"}),c.jsx("button",{className:"blueprint-responses__collapse-btn",onClick:()=>Ae(!0),"aria-label":"Collapse questions and responses panel",children:"▲"})]})]}),c.jsx("div",{className:"blueprint-annotations",children:Object.entries(O).map(([E,M])=>{const G=l.find(W=>W.id===E);return c.jsxs("div",{className:"blueprint-annotation",children:[c.jsx("div",{className:"blueprint-annotation__question",children:(G==null?void 0:G.question)||E}),c.jsx("input",{type:"text",value:M,onChange:W=>{z(ie=>({...ie,[E]:W.target.value})),Et()},className:"blueprint-annotation__input","aria-label":`Edit response for ${(G==null?void 0:G.question)||E}`})]},E)})})]})})]}),c.jsx("div",{className:"blueprint-divider"}),c.jsxs("div",{className:"blueprint-right",children:[c.jsxs("header",{className:"blueprint-right__header blueprint-column-header",children:[c.jsx("h2",{className:"panel-title",children:"SPEC_OUTPUT"}),c.jsxs("div",{className:"blueprint-right__actions",children:[C&&c.jsx("span",{className:"blueprint-right__error",children:C}),$e&&c.jsx("span",{className:"blueprint-right__mamba-notice text-mono",style:{color:"var(--panel-label, #888)",fontSize:"0.6rem",textTransform:"uppercase",letterSpacing:"0.05em"},children:$e}),c.jsx("button",{className:"btn-tertiary btn-regenerate",onClick:ae,disabled:p||!((re=k.current)!=null&&re.trim()),"aria-label":"Regenerate spec",title:"Regenerate spec from current input",children:p?"GENERATING…":"REGENERATE"}),c.jsx("button",{className:"btn-tertiary btn-clear",onClick:()=>{if((i.length>0||_!=="")&&!window.confirm("Clear spec output? This cannot be undone."))return;j.current&&j.current.abort(),r([]),o([]),h(null),x(""),v(!1),B(!1),R(null);const M={phases:[],clarifications:[],annotations:{},updatedAt:Date.now()};Il(M),Bl(M).catch(()=>{})},"aria-label":"Clear spec output",children:"CLEAR"}),c.jsx("button",{className:"nav-icon-btn",onClick:()=>K(!0),"aria-label":"Spec generation model settings",title:"Model Settings",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"3"}),c.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]})]}),c.jsx("div",{className:"blueprint-right__subtitle-bar",children:c.jsx("span",{className:"blueprint-right__model-subtitle",children:U})}),c.jsxs("div",{className:"blueprint-right__content",children:[i.length===0&&!p&&!_&&c.jsx("div",{className:"blueprint-right__empty",children:c.jsx("span",{className:"text-mono",style:{color:"var(--panel-label)",fontSize:"0.875rem"},children:"Write your intent in the left column. Spec generates as you type."})}),p&&_&&i.length===0&&c.jsxs("div",{className:"blueprint-right__streaming",children:[c.jsx("div",{className:"blueprint-right__streaming-indicator",children:c.jsx("span",{className:"text-mono animate-pulse",style:{color:"var(--panel-label)",fontSize:"0.65rem",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Generating…"})}),ke&&c.jsx("div",{className:"blueprint-right__tool-indicator",children:c.jsx("span",{className:"text-mono",style:{color:"var(--on-surface)",fontSize:"0.65rem",textTransform:"uppercase",letterSpacing:"0.05em"},children:"⚙ Verifying assumptions…"})}),c.jsx("pre",{className:"blueprint-right__streaming-text",children:_})]}),p&&!_&&i.length===0&&c.jsx("div",{className:"blueprint-right__loading",children:c.jsx("span",{className:"text-mono animate-pulse",style:{color:"var(--panel-label)",fontSize:"0.65rem",textTransform:"uppercase",letterSpacing:"0.05em"},children:ke?"Verifying assumptions…":"Generating…"})}),i.length>0&&p&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"blueprint-right__update-indicator",children:c.jsx("span",{className:"text-mono animate-pulse",style:{color:"var(--panel-label)",fontSize:"0.65rem",textTransform:"uppercase",letterSpacing:"0.05em"},children:ke?"Verifying assumptions…":"Updating…"})}),i.map(E=>c.jsx(tm,{phase:E,onRegenerate:ce,isRegenerating:g===E.phaseNumber,isUpdating:y.has(E.id)},E.id))]}),!p&&i.length>0&&i.map(E=>c.jsx(tm,{phase:E,onRegenerate:ce,isRegenerating:g===E.phaseNumber,isUpdating:y.has(E.id)},E.id))]})]})]}),c.jsx(iE,{isOpen:q,onClose:()=>K(!1),config:ee,onSave:yt})]}):c.jsx(jv,{})}function ME({onClick:e}){var i;const{user:t}=Os();if(!t)return c.jsx("button",{className:"nav-icon-btn",onClick:e,"aria-label":"Sign in",title:"Sign in",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]})});const n=(i=t.user_metadata)==null?void 0:i.avatar_url,a=t.email||"",s=a.slice(0,2).toUpperCase();return n?c.jsx("button",{onClick:e,"aria-label":"Account menu",title:a,style:{width:32,height:32,padding:0,border:"1px solid var(--outline-variant)",background:"transparent",cursor:"pointer",borderRadius:0,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"},children:c.jsx("img",{src:n,alt:"",width:32,height:32,style:{borderRadius:0,objectFit:"cover"}})}):c.jsx("button",{onClick:e,"aria-label":"Account menu",title:a,style:{width:32,height:32,padding:0,border:"1px solid var(--outline-variant)",background:"var(--surface-container-high)",color:"var(--on-surface)",cursor:"pointer",borderRadius:0,display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"var(--font-mono)",fontSize:"0.7rem",fontWeight:500},children:s})}const UE="https://noterai.tech/forgot-password";function LE({open:e,onClose:t}){const{signInWithEmail:n,signUpWithEmail:a,authError:s,clearAuthError:i,loading:r}=Os(),[l,o]=b.useState(!1),[u,h]=b.useState(""),[f,d]=b.useState(""),[p,v]=b.useState(""),[_,x]=b.useState(null),[g,m]=b.useState(null);if(b.useEffect(()=>{e&&(x(null),m(null),i())},[e,i]),!e)return null;const y=async C=>{if(C.preventDefault(),x(null),m(null),l){if(f!==p){x("Passwords do not match");return}if(f.length<6){x("Password must be at least 6 characters");return}const{error:R,needsConfirmation:O}=await a(u,f);if(R)return;O?(m("Check your email to confirm your account before signing in."),h(""),d(""),v("")):(t(),h(""),d(""),v(""))}else await n(u,f)||(t(),h(""),d(""),v(""))},w=_||s;return c.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Sign in",onClick:C=>{C.target===C.currentTarget&&t()},style:{position:"fixed",inset:0,backgroundColor:"color-mix(in srgb, var(--surface) 70%, transparent)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:200},children:c.jsxs("div",{style:{backgroundColor:"var(--surface)",border:"1px solid var(--outline-variant)",width:"360px",maxWidth:"90vw",maxHeight:"90vh",overflowY:"auto",borderRadius:0},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"16px 20px",borderBottom:"1px solid var(--outline-variant)"},children:[c.jsx("span",{style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",color:"var(--panel-label)"},children:l?"Sign Up":"Sign In"}),c.jsx("button",{onClick:t,"aria-label":"Close sign in",style:{background:"transparent",border:"none",color:"var(--panel-label)",cursor:"pointer",fontSize:"1rem",lineHeight:1,padding:"4px"},children:"×"})]}),c.jsxs("div",{style:{padding:"20px"},children:[g&&c.jsx("div",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--on-surface)",padding:"8px 12px",border:"1px solid var(--outline-variant)",marginBottom:"16px",borderRadius:0},children:g}),w&&c.jsx("div",{style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"#FF4444",padding:"8px 12px",border:"1px solid #FF4444",marginBottom:"16px",borderRadius:0},children:w}),c.jsxs("form",{onSubmit:y,style:{display:"flex",flexDirection:"column",gap:"12px"},children:[c.jsx("input",{type:"email",placeholder:"Email",value:u,onChange:C=>h(C.target.value),required:!0,style:{backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-mono)",fontSize:"0.875rem",padding:"10px 12px",outline:"none",borderRadius:0}}),c.jsx("input",{type:"password",placeholder:"Password",value:f,onChange:C=>d(C.target.value),required:!0,minLength:6,style:{backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-mono)",fontSize:"0.875rem",padding:"10px 12px",outline:"none",borderRadius:0}}),l&&c.jsx("input",{type:"password",placeholder:"Confirm password",value:p,onChange:C=>v(C.target.value),required:!0,style:{backgroundColor:"var(--surface-container-high)",border:"1px solid var(--outline-variant)",color:"var(--on-surface)",fontFamily:"var(--font-mono)",fontSize:"0.875rem",padding:"10px 12px",outline:"none",borderRadius:0}}),c.jsx("button",{type:"submit",disabled:r,style:{fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",padding:"10px",background:r?"var(--outline-variant)":"var(--on-surface)",color:r?"var(--panel-label)":"var(--surface)",border:"none",cursor:r?"default":"pointer",borderRadius:0},children:r?"LOADING…":l?"SIGN UP":"SIGN IN"}),c.jsx("button",{type:"button",onClick:()=>{o(!l),x(null),m(null)},style:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--panel-label)",background:"transparent",border:"none",cursor:"pointer",padding:"4px 0",borderRadius:0},children:l?"Already have an account? Sign in":"Don't have an account? Sign up"}),!l&&c.jsx("a",{href:UE,target:"_blank",rel:"noopener noreferrer",style:{fontFamily:"var(--font-mono)",fontSize:"0.7rem",color:"var(--panel-label)",textDecoration:"none",padding:"2px 0"},onMouseEnter:C=>{C.currentTarget.style.color="var(--on-surface)"},onMouseLeave:C=>{C.currentTarget.style.color="var(--panel-label)"},children:"Forgot password?"})]})]})]})})}class lm extends b.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n)}render(){var t;return this.state.hasError?c.jsxs("div",{style:{padding:"24px",color:"#FF4444",fontFamily:"var(--font-mono)",fontSize:"0.875rem"},children:[c.jsx("div",{style:{marginBottom:"8px"},children:"UNHANDLED ERROR"}),c.jsx("div",{children:(t=this.state.error)==null?void 0:t.message}),c.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{marginTop:"12px",border:"1px solid #FF4444",background:"transparent",color:"#FF4444",padding:"4px 12px",cursor:"pointer",fontSize:"0.75rem",textTransform:"uppercase"},children:"Dismiss"})]}):this.props.children}}function zE(){var m;const[e,t]=b.useState(!0),[n,a]=b.useState("connecting"),[s,i]=b.useState(!1),[r,l]=b.useState(!1),[o,u]=b.useState("mission-control"),[h,f]=b.useState(!1),[d,p]=b.useState(!1),v=b.useRef(null),{user:_,isSubscribed:x,signOut:g}=Os();return b.useEffect(()=>{e?document.documentElement.classList.remove("dark"):document.documentElement.classList.add("dark")},[e]),b.useEffect(()=>me.subscribe("status",w=>{a(w)}),[]),b.useEffect(()=>{let y;return n==="disconnected"||n==="connecting"?y=setTimeout(()=>{i(!0)},2e3):i(!1),()=>clearTimeout(y)},[n]),b.useEffect(()=>{if(!d)return;function y(w){v.current&&!v.current.contains(w.target)&&p(!1)}return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[d]),c.jsxs("div",{className:"app-container",children:[s&&c.jsxs("div",{className:"connection-overlay",children:[c.jsx("div",{className:"connection-overlay__title",children:"Connecting to Noter..."}),c.jsx("div",{className:"connection-overlay__subtitle",children:n==="connecting"?"Attempting to connect...":"Connection lost. Retrying..."}),c.jsx("div",{className:"connection-overlay__hint",children:"Ensure the backend server is running on the correct port."})]}),c.jsxs("nav",{className:"top-nav",children:[c.jsx("div",{className:"nav-title",children:"Noter"}),c.jsxs("div",{className:"nav-page-buttons",children:[c.jsx("button",{className:`nav-page-btn${o==="mission-control"?" nav-page-btn--active":""}`,onClick:()=>u("mission-control"),children:"MISSION CONTROL"}),c.jsx("button",{className:`nav-page-btn${o==="blueprint"?" nav-page-btn--active":""}`,onClick:()=>u("blueprint"),children:"BLUEPRINT"})]}),c.jsxs("div",{className:"nav-icons",children:[c.jsx("button",{className:"nav-icon-btn",onClick:()=>t(!e),"aria-label":"Toggle Dark Mode",role:"switch","aria-checked":e,title:e?"Switch to light mode":"Switch to dark mode",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}),c.jsx("button",{className:"nav-icon-btn",onClick:()=>l(!0),"aria-label":"Open Settings",title:"Settings",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"3"}),c.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),c.jsxs("div",{ref:v,style:{position:"relative"},children:[c.jsx(ME,{onClick:()=>{_?p(!d):f(!0)}}),d&&_&&c.jsxs("div",{style:{position:"absolute",top:"40px",right:0,width:"220px",backgroundColor:"var(--surface)",border:"1px solid var(--outline-variant)",zIndex:150,borderRadius:0},children:[c.jsx("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--outline-variant)",fontFamily:"var(--font-mono)",fontSize:"0.75rem",color:"var(--on-surface)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_.email||((m=_.user_metadata)==null?void 0:m.user_name)||"User"}),c.jsx("div",{style:{padding:"8px 16px",borderBottom:"1px solid var(--outline-variant)",fontFamily:"var(--font-sans)",fontSize:"0.7rem",textTransform:"uppercase",letterSpacing:"0.05rem"},children:c.jsx("span",{style:{color:x?"var(--on-surface)":"var(--panel-label)",border:`1px solid ${x?"var(--on-surface)":"var(--outline-variant)"}`,padding:"2px 8px"},children:x?"PRO":"FREE"})}),c.jsx("a",{href:x?"https://noterai.tech/account":kv,target:"_blank",rel:"noopener noreferrer",style:{display:"block",padding:"10px 16px",fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",color:"var(--on-surface)",textDecoration:"none",borderBottom:"1px solid var(--outline-variant)",borderRadius:0},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="var(--surface-container-high)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent"},children:x?"Manage Subscription":"Upgrade to Pro"}),c.jsx("button",{onClick:async()=>{p(!1),await g()},style:{display:"block",width:"100%",padding:"10px 16px",fontFamily:"var(--font-sans)",fontSize:"0.75rem",textTransform:"uppercase",letterSpacing:"0.05rem",color:"var(--panel-label)",background:"transparent",border:"none",cursor:"pointer",textAlign:"left",borderRadius:0},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="var(--surface-container-high)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent"},children:"Sign Out"})]})]})]})]}),c.jsx(JT,{isOpen:r,onClose:()=>l(!1)}),c.jsx(LE,{open:h,onClose:()=>f(!1)}),c.jsx("main",{className:"app-grid",style:{display:o==="mission-control"?"":"none"},children:c.jsxs(lm,{children:[c.jsx(lv,{}),c.jsx(RT,{}),c.jsx(BT,{}),c.jsx(PT,{})]})}),c.jsx("main",{className:"blueprint-container",style:{display:o==="blueprint"?"":"none"},children:c.jsx(lm,{children:c.jsx(DE,{})})})]})}RS();AS.createRoot(document.getElementById("root")).render(c.jsx(b.StrictMode,{children:c.jsx(OT,{children:c.jsx(zE,{})})}));