@mmmbuto/nexuscrew 0.9.77 → 0.9.78

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,169 @@
1
+ (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function s(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();function mv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var rp={exports:{}},ql={},op={exports:{}},Kt={};/**
2
+ * @license React
3
+ * react.production.min.js
4
+ *
5
+ * Copyright (c) Facebook, Inc. and its 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 Xb;function c5(){if(Xb)return Kt;Xb=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),c=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),_=Symbol.iterator;function g(M){return M===null||typeof M!="object"?null:(M=_&&M[_]||M["@@iterator"],typeof M=="function"?M:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,N={};function C(M,U,ee){this.props=M,this.context=U,this.refs=N,this.updater=ee||w}C.prototype.isReactComponent={},C.prototype.setState=function(M,U){if(typeof M!="object"&&typeof M!="function"&&M!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,M,U,"setState")},C.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function j(){}j.prototype=C.prototype;function E(M,U,ee){this.props=M,this.context=U,this.refs=N,this.updater=ee||w}var R=E.prototype=new j;R.constructor=E,S(R,C.prototype),R.isPureReactComponent=!0;var x=Array.isArray,W=Object.prototype.hasOwnProperty,$={current:null},Y={key:!0,ref:!0,__self:!0,__source:!0};function q(M,U,ee){var re,oe={},je=null,te=null;if(U!=null)for(re in U.ref!==void 0&&(te=U.ref),U.key!==void 0&&(je=""+U.key),U)W.call(U,re)&&!Y.hasOwnProperty(re)&&(oe[re]=U[re]);var ie=arguments.length-2;if(ie===1)oe.children=ee;else if(1<ie){for(var pe=Array(ie),xe=0;xe<ie;xe++)pe[xe]=arguments[xe+2];oe.children=pe}if(M&&M.defaultProps)for(re in ie=M.defaultProps,ie)oe[re]===void 0&&(oe[re]=ie[re]);return{$$typeof:e,type:M,key:je,ref:te,props:oe,_owner:$.current}}function K(M,U){return{$$typeof:e,type:M.type,key:U,ref:M.ref,props:M.props,_owner:M._owner}}function se(M){return typeof M=="object"&&M!==null&&M.$$typeof===e}function V(M){var U={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(ee){return U[ee]})}var B=/\/+/g;function D(M,U){return typeof M=="object"&&M!==null&&M.key!=null?V(""+M.key):U.toString(36)}function O(M,U,ee,re,oe){var je=typeof M;(je==="undefined"||je==="boolean")&&(M=null);var te=!1;if(M===null)te=!0;else switch(je){case"string":case"number":te=!0;break;case"object":switch(M.$$typeof){case e:case t:te=!0}}if(te)return te=M,oe=oe(te),M=re===""?"."+D(te,0):re,x(oe)?(ee="",M!=null&&(ee=M.replace(B,"$&/")+"/"),O(oe,U,ee,"",function(xe){return xe})):oe!=null&&(se(oe)&&(oe=K(oe,ee+(!oe.key||te&&te.key===oe.key?"":(""+oe.key).replace(B,"$&/")+"/")+M)),U.push(oe)),1;if(te=0,re=re===""?".":re+":",x(M))for(var ie=0;ie<M.length;ie++){je=M[ie];var pe=re+D(je,ie);te+=O(je,U,ee,pe,oe)}else if(pe=g(M),typeof pe=="function")for(M=pe.call(M),ie=0;!(je=M.next()).done;)je=je.value,pe=re+D(je,ie++),te+=O(je,U,ee,pe,oe);else if(je==="object")throw U=String(M),Error("Objects are not valid as a React child (found: "+(U==="[object Object]"?"object with keys {"+Object.keys(M).join(", ")+"}":U)+"). If you meant to render a collection of children, use an array instead.");return te}function P(M,U,ee){if(M==null)return M;var re=[],oe=0;return O(M,re,"","",function(je){return U.call(ee,je,oe++)}),re}function z(M){if(M._status===-1){var U=M._result;U=U(),U.then(function(ee){(M._status===0||M._status===-1)&&(M._status=1,M._result=ee)},function(ee){(M._status===0||M._status===-1)&&(M._status=2,M._result=ee)}),M._status===-1&&(M._status=0,M._result=U)}if(M._status===1)return M._result.default;throw M._result}var A={current:null},T={transition:null},L={ReactCurrentDispatcher:A,ReactCurrentBatchConfig:T,ReactCurrentOwner:$};function H(){throw Error("act(...) is not supported in production builds of React.")}return Kt.Children={map:P,forEach:function(M,U,ee){P(M,function(){U.apply(this,arguments)},ee)},count:function(M){var U=0;return P(M,function(){U++}),U},toArray:function(M){return P(M,function(U){return U})||[]},only:function(M){if(!se(M))throw Error("React.Children.only expected to receive a single React element child.");return M}},Kt.Component=C,Kt.Fragment=n,Kt.Profiler=i,Kt.PureComponent=E,Kt.StrictMode=s,Kt.Suspense=h,Kt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=L,Kt.act=H,Kt.cloneElement=function(M,U,ee){if(M==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+M+".");var re=S({},M.props),oe=M.key,je=M.ref,te=M._owner;if(U!=null){if(U.ref!==void 0&&(je=U.ref,te=$.current),U.key!==void 0&&(oe=""+U.key),M.type&&M.type.defaultProps)var ie=M.type.defaultProps;for(pe in U)W.call(U,pe)&&!Y.hasOwnProperty(pe)&&(re[pe]=U[pe]===void 0&&ie!==void 0?ie[pe]:U[pe])}var pe=arguments.length-2;if(pe===1)re.children=ee;else if(1<pe){ie=Array(pe);for(var xe=0;xe<pe;xe++)ie[xe]=arguments[xe+2];re.children=ie}return{$$typeof:e,type:M.type,key:oe,ref:je,props:re,_owner:te}},Kt.createContext=function(M){return M={$$typeof:c,_currentValue:M,_currentValue2:M,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},M.Provider={$$typeof:l,_context:M},M.Consumer=M},Kt.createElement=q,Kt.createFactory=function(M){var U=q.bind(null,M);return U.type=M,U},Kt.createRef=function(){return{current:null}},Kt.forwardRef=function(M){return{$$typeof:u,render:M}},Kt.isValidElement=se,Kt.lazy=function(M){return{$$typeof:v,_payload:{_status:-1,_result:M},_init:z}},Kt.memo=function(M,U){return{$$typeof:p,type:M,compare:U===void 0?null:U}},Kt.startTransition=function(M){var U=T.transition;T.transition={};try{M()}finally{T.transition=U}},Kt.unstable_act=H,Kt.useCallback=function(M,U){return A.current.useCallback(M,U)},Kt.useContext=function(M){return A.current.useContext(M)},Kt.useDebugValue=function(){},Kt.useDeferredValue=function(M){return A.current.useDeferredValue(M)},Kt.useEffect=function(M,U){return A.current.useEffect(M,U)},Kt.useId=function(){return A.current.useId()},Kt.useImperativeHandle=function(M,U,ee){return A.current.useImperativeHandle(M,U,ee)},Kt.useInsertionEffect=function(M,U){return A.current.useInsertionEffect(M,U)},Kt.useLayoutEffect=function(M,U){return A.current.useLayoutEffect(M,U)},Kt.useMemo=function(M,U){return A.current.useMemo(M,U)},Kt.useReducer=function(M,U,ee){return A.current.useReducer(M,U,ee)},Kt.useRef=function(M){return A.current.useRef(M)},Kt.useState=function(M){return A.current.useState(M)},Kt.useSyncExternalStore=function(M,U,ee){return A.current.useSyncExternalStore(M,U,ee)},Kt.useTransition=function(){return A.current.useTransition()},Kt.version="18.3.1",Kt}var Jb;function gv(){return Jb||(Jb=1,op.exports=c5()),op.exports}/**
10
+ * @license React
11
+ * react-jsx-runtime.production.min.js
12
+ *
13
+ * Copyright (c) Facebook, Inc. and its 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
+ */var Qb;function u5(){if(Qb)return ql;Qb=1;var e=gv(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function c(u,h,p){var v,_={},g=null,w=null;p!==void 0&&(g=""+p),h.key!==void 0&&(g=""+h.key),h.ref!==void 0&&(w=h.ref);for(v in h)s.call(h,v)&&!l.hasOwnProperty(v)&&(_[v]=h[v]);if(u&&u.defaultProps)for(v in h=u.defaultProps,h)_[v]===void 0&&(_[v]=h[v]);return{$$typeof:t,type:u,key:g,ref:w,props:_,_owner:i.current}}return ql.Fragment=n,ql.jsx=c,ql.jsxs=c,ql}var Zb;function d5(){return Zb||(Zb=1,rp.exports=u5()),rp.exports}var o=d5(),y=gv();const h5=mv(y);var Zu={},ap={exports:{}},Vs={},lp={exports:{}},cp={};/**
18
+ * @license React
19
+ * scheduler.production.min.js
20
+ *
21
+ * Copyright (c) Facebook, Inc. and its 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 ew;function f5(){return ew||(ew=1,(function(e){function t(T,L){var H=T.length;T.push(L);e:for(;0<H;){var M=H-1>>>1,U=T[M];if(0<i(U,L))T[M]=L,T[H]=U,H=M;else break e}}function n(T){return T.length===0?null:T[0]}function s(T){if(T.length===0)return null;var L=T[0],H=T.pop();if(H!==L){T[0]=H;e:for(var M=0,U=T.length,ee=U>>>1;M<ee;){var re=2*(M+1)-1,oe=T[re],je=re+1,te=T[je];if(0>i(oe,H))je<U&&0>i(te,oe)?(T[M]=te,T[je]=H,M=je):(T[M]=oe,T[re]=H,M=re);else if(je<U&&0>i(te,H))T[M]=te,T[je]=H,M=je;else break e}}return L}function i(T,L){var H=T.sortIndex-L.sortIndex;return H!==0?H:T.id-L.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var c=Date,u=c.now();e.unstable_now=function(){return c.now()-u}}var h=[],p=[],v=1,_=null,g=3,w=!1,S=!1,N=!1,C=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(T){for(var L=n(p);L!==null;){if(L.callback===null)s(p);else if(L.startTime<=T)s(p),L.sortIndex=L.expirationTime,t(h,L);else break;L=n(p)}}function x(T){if(N=!1,R(T),!S)if(n(h)!==null)S=!0,z(W);else{var L=n(p);L!==null&&A(x,L.startTime-T)}}function W(T,L){S=!1,N&&(N=!1,j(q),q=-1),w=!0;var H=g;try{for(R(L),_=n(h);_!==null&&(!(_.expirationTime>L)||T&&!V());){var M=_.callback;if(typeof M=="function"){_.callback=null,g=_.priorityLevel;var U=M(_.expirationTime<=L);L=e.unstable_now(),typeof U=="function"?_.callback=U:_===n(h)&&s(h),R(L)}else s(h);_=n(h)}if(_!==null)var ee=!0;else{var re=n(p);re!==null&&A(x,re.startTime-L),ee=!1}return ee}finally{_=null,g=H,w=!1}}var $=!1,Y=null,q=-1,K=5,se=-1;function V(){return!(e.unstable_now()-se<K)}function B(){if(Y!==null){var T=e.unstable_now();se=T;var L=!0;try{L=Y(!0,T)}finally{L?D():($=!1,Y=null)}}else $=!1}var D;if(typeof E=="function")D=function(){E(B)};else if(typeof MessageChannel<"u"){var O=new MessageChannel,P=O.port2;O.port1.onmessage=B,D=function(){P.postMessage(null)}}else D=function(){C(B,0)};function z(T){Y=T,$||($=!0,D())}function A(T,L){q=C(function(){T(e.unstable_now())},L)}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(T){T.callback=null},e.unstable_continueExecution=function(){S||w||(S=!0,z(W))},e.unstable_forceFrameRate=function(T){0>T||125<T?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):K=0<T?Math.floor(1e3/T):5},e.unstable_getCurrentPriorityLevel=function(){return g},e.unstable_getFirstCallbackNode=function(){return n(h)},e.unstable_next=function(T){switch(g){case 1:case 2:case 3:var L=3;break;default:L=g}var H=g;g=L;try{return T()}finally{g=H}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(T,L){switch(T){case 1:case 2:case 3:case 4:case 5:break;default:T=3}var H=g;g=T;try{return L()}finally{g=H}},e.unstable_scheduleCallback=function(T,L,H){var M=e.unstable_now();switch(typeof H=="object"&&H!==null?(H=H.delay,H=typeof H=="number"&&0<H?M+H:M):H=M,T){case 1:var U=-1;break;case 2:U=250;break;case 5:U=1073741823;break;case 4:U=1e4;break;default:U=5e3}return U=H+U,T={id:v++,callback:L,priorityLevel:T,startTime:H,expirationTime:U,sortIndex:-1},H>M?(T.sortIndex=H,t(p,T),n(h)===null&&T===n(p)&&(N?(j(q),q=-1):N=!0,A(x,H-M))):(T.sortIndex=U,t(h,T),S||w||(S=!0,z(W))),T},e.unstable_shouldYield=V,e.unstable_wrapCallback=function(T){var L=g;return function(){var H=g;g=L;try{return T.apply(this,arguments)}finally{g=H}}}})(cp)),cp}var tw;function p5(){return tw||(tw=1,lp.exports=f5()),lp.exports}/**
26
+ * @license React
27
+ * react-dom.production.min.js
28
+ *
29
+ * Copyright (c) Facebook, Inc. and its affiliates.
30
+ *
31
+ * This source code is licensed under the MIT license found in the
32
+ * LICENSE file in the root directory of this source tree.
33
+ */var nw;function m5(){if(nw)return Vs;nw=1;var e=gv(),t=p5();function n(r){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+r,d=1;d<arguments.length;d++)a+="&args[]="+encodeURIComponent(arguments[d]);return"Minified React error #"+r+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var s=new Set,i={};function l(r,a){c(r,a),c(r+"Capture",a)}function c(r,a){for(i[r]=a,r=0;r<a.length;r++)s.add(a[r])}var u=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),h=Object.prototype.hasOwnProperty,p=/^[: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]*$/,v={},_={};function g(r){return h.call(_,r)?!0:h.call(v,r)?!1:p.test(r)?_[r]=!0:(v[r]=!0,!1)}function w(r,a,d,m){if(d!==null&&d.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return m?!1:d!==null?!d.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function S(r,a,d,m){if(a===null||typeof a>"u"||w(r,a,d,m))return!0;if(m)return!1;if(d!==null)switch(d.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function N(r,a,d,m,b,k,F){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=m,this.attributeNamespace=b,this.mustUseProperty=d,this.propertyName=r,this.type=a,this.sanitizeURL=k,this.removeEmptyString=F}var C={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){C[r]=new N(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var a=r[0];C[a]=new N(a,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){C[r]=new N(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){C[r]=new N(r,2,!1,r,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(r){C[r]=new N(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){C[r]=new N(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){C[r]=new N(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){C[r]=new N(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){C[r]=new N(r,5,!1,r.toLowerCase(),null,!1,!1)});var j=/[\-:]([a-z])/g;function E(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var a=r.replace(j,E);C[a]=new N(a,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var a=r.replace(j,E);C[a]=new N(a,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var a=r.replace(j,E);C[a]=new N(a,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){C[r]=new N(r,1,!1,r.toLowerCase(),null,!1,!1)}),C.xlinkHref=new N("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){C[r]=new N(r,1,!1,r.toLowerCase(),null,!0,!0)});function R(r,a,d,m){var b=C.hasOwnProperty(a)?C[a]:null;(b!==null?b.type!==0:m||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(S(a,d,b,m)&&(d=null),m||b===null?g(a)&&(d===null?r.removeAttribute(a):r.setAttribute(a,""+d)):b.mustUseProperty?r[b.propertyName]=d===null?b.type===3?!1:"":d:(a=b.attributeName,m=b.attributeNamespace,d===null?r.removeAttribute(a):(b=b.type,d=b===3||b===4&&d===!0?"":""+d,m?r.setAttributeNS(m,a,d):r.setAttribute(a,d))))}var x=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,W=Symbol.for("react.element"),$=Symbol.for("react.portal"),Y=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),K=Symbol.for("react.profiler"),se=Symbol.for("react.provider"),V=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),D=Symbol.for("react.suspense"),O=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),z=Symbol.for("react.lazy"),A=Symbol.for("react.offscreen"),T=Symbol.iterator;function L(r){return r===null||typeof r!="object"?null:(r=T&&r[T]||r["@@iterator"],typeof r=="function"?r:null)}var H=Object.assign,M;function U(r){if(M===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);M=a&&a[1]||""}return`
34
+ `+M+r}var ee=!1;function re(r,a){if(!r||ee)return"";ee=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a)if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(a,[])}catch(Ne){var m=Ne}Reflect.construct(r,[],a)}else{try{a.call()}catch(Ne){m=Ne}r.call(a.prototype)}else{try{throw Error()}catch(Ne){m=Ne}r()}}catch(Ne){if(Ne&&m&&typeof Ne.stack=="string"){for(var b=Ne.stack.split(`
35
+ `),k=m.stack.split(`
36
+ `),F=b.length-1,ne=k.length-1;1<=F&&0<=ne&&b[F]!==k[ne];)ne--;for(;1<=F&&0<=ne;F--,ne--)if(b[F]!==k[ne]){if(F!==1||ne!==1)do if(F--,ne--,0>ne||b[F]!==k[ne]){var de=`
37
+ `+b[F].replace(" at new "," at ");return r.displayName&&de.includes("<anonymous>")&&(de=de.replace("<anonymous>",r.displayName)),de}while(1<=F&&0<=ne);break}}}finally{ee=!1,Error.prepareStackTrace=d}return(r=r?r.displayName||r.name:"")?U(r):""}function oe(r){switch(r.tag){case 5:return U(r.type);case 16:return U("Lazy");case 13:return U("Suspense");case 19:return U("SuspenseList");case 0:case 2:case 15:return r=re(r.type,!1),r;case 11:return r=re(r.type.render,!1),r;case 1:return r=re(r.type,!0),r;default:return""}}function je(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case Y:return"Fragment";case $:return"Portal";case K:return"Profiler";case q:return"StrictMode";case D:return"Suspense";case O:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case V:return(r.displayName||"Context")+".Consumer";case se:return(r._context.displayName||"Context")+".Provider";case B:var a=r.render;return r=r.displayName,r||(r=a.displayName||a.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case P:return a=r.displayName||null,a!==null?a:je(r.type)||"Memo";case z:a=r._payload,r=r._init;try{return je(r(a))}catch{}}return null}function te(r){var a=r.type;switch(r.tag){case 24:return"Cache";case 9:return(a.displayName||"Context")+".Consumer";case 10:return(a._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=a.render,r=r.displayName||r.name||"",a.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return a;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return je(a);case 8:return a===q?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a}return null}function ie(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function pe(r){var a=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function xe(r){var a=pe(r)?"checked":"value",d=Object.getOwnPropertyDescriptor(r.constructor.prototype,a),m=""+r[a];if(!r.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var b=d.get,k=d.set;return Object.defineProperty(r,a,{configurable:!0,get:function(){return b.call(this)},set:function(F){m=""+F,k.call(this,F)}}),Object.defineProperty(r,a,{enumerable:d.enumerable}),{getValue:function(){return m},setValue:function(F){m=""+F},stopTracking:function(){r._valueTracker=null,delete r[a]}}}}function Be(r){r._valueTracker||(r._valueTracker=xe(r))}function Te(r){if(!r)return!1;var a=r._valueTracker;if(!a)return!0;var d=a.getValue(),m="";return r&&(m=pe(r)?r.checked?"true":"false":r.value),r=m,r!==d?(a.setValue(r),!0):!1}function Me(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function J(r,a){var d=a.checked;return H({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??r._wrapperState.initialChecked})}function le(r,a){var d=a.defaultValue==null?"":a.defaultValue,m=a.checked!=null?a.checked:a.defaultChecked;d=ie(a.value!=null?a.value:d),r._wrapperState={initialChecked:m,initialValue:d,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Q(r,a){a=a.checked,a!=null&&R(r,"checked",a,!1)}function ge(r,a){Q(r,a);var d=ie(a.value),m=a.type;if(d!=null)m==="number"?(d===0&&r.value===""||r.value!=d)&&(r.value=""+d):r.value!==""+d&&(r.value=""+d);else if(m==="submit"||m==="reset"){r.removeAttribute("value");return}a.hasOwnProperty("value")?fe(r,a.type,d):a.hasOwnProperty("defaultValue")&&fe(r,a.type,ie(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(r.defaultChecked=!!a.defaultChecked)}function Z(r,a,d){if(a.hasOwnProperty("value")||a.hasOwnProperty("defaultValue")){var m=a.type;if(!(m!=="submit"&&m!=="reset"||a.value!==void 0&&a.value!==null))return;a=""+r._wrapperState.initialValue,d||a===r.value||(r.value=a),r.defaultValue=a}d=r.name,d!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,d!==""&&(r.name=d)}function fe(r,a,d){(a!=="number"||Me(r.ownerDocument)!==r)&&(d==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+d&&(r.defaultValue=""+d))}var ve=Array.isArray;function ke(r,a,d,m){if(r=r.options,a){a={};for(var b=0;b<d.length;b++)a["$"+d[b]]=!0;for(d=0;d<r.length;d++)b=a.hasOwnProperty("$"+r[d].value),r[d].selected!==b&&(r[d].selected=b),b&&m&&(r[d].defaultSelected=!0)}else{for(d=""+ie(d),a=null,b=0;b<r.length;b++){if(r[b].value===d){r[b].selected=!0,m&&(r[b].defaultSelected=!0);return}a!==null||r[b].disabled||(a=r[b])}a!==null&&(a.selected=!0)}}function Ve(r,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return H({},a,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function ot(r,a){var d=a.value;if(d==null){if(d=a.children,a=a.defaultValue,d!=null){if(a!=null)throw Error(n(92));if(ve(d)){if(1<d.length)throw Error(n(93));d=d[0]}a=d}a==null&&(a=""),d=a}r._wrapperState={initialValue:ie(d)}}function rt(r,a){var d=ie(a.value),m=ie(a.defaultValue);d!=null&&(d=""+d,d!==r.value&&(r.value=d),a.defaultValue==null&&r.defaultValue!==d&&(r.defaultValue=d)),m!=null&&(r.defaultValue=""+m)}function $e(r){var a=r.textContent;a===r._wrapperState.initialValue&&a!==""&&a!==null&&(r.value=a)}function _e(r){switch(r){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function ze(r,a){return r==null||r==="http://www.w3.org/1999/xhtml"?_e(a):r==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var Je,He=(function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(a,d,m,b){MSApp.execUnsafeLocalFunction(function(){return r(a,d,m,b)})}:r})(function(r,a){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=a;else{for(Je=Je||document.createElement("div"),Je.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=Je.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;a.firstChild;)r.appendChild(a.firstChild)}});function nt(r,a){if(a){var d=r.firstChild;if(d&&d===r.lastChild&&d.nodeType===3){d.nodeValue=a;return}}r.textContent=a}var lt={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},X=["Webkit","ms","Moz","O"];Object.keys(lt).forEach(function(r){X.forEach(function(a){a=a+r.charAt(0).toUpperCase()+r.substring(1),lt[a]=lt[r]})});function I(r,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||lt.hasOwnProperty(r)&&lt[r]?(""+a).trim():a+"px"}function ce(r,a){r=r.style;for(var d in a)if(a.hasOwnProperty(d)){var m=d.indexOf("--")===0,b=I(d,a[d],m);d==="float"&&(d="cssFloat"),m?r.setProperty(d,b):r[d]=b}}var ye=H({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Re(r,a){if(a){if(ye[r]&&(a.children!=null||a.dangerouslySetInnerHTML!=null))throw Error(n(137,r));if(a.dangerouslySetInnerHTML!=null){if(a.children!=null)throw Error(n(60));if(typeof a.dangerouslySetInnerHTML!="object"||!("__html"in a.dangerouslySetInnerHTML))throw Error(n(61))}if(a.style!=null&&typeof a.style!="object")throw Error(n(62))}}function ae(r,a){if(r.indexOf("-")===-1)return typeof a.is=="string";switch(r){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 Oe=null;function gt(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var At=null,Lt=null,Rt=null;function zt(r){if(r=Rl(r)){if(typeof At!="function")throw Error(n(280));var a=r.stateNode;a&&(a=pu(a),At(r.stateNode,r.type,a))}}function ft(r){Lt?Rt?Rt.push(r):Rt=[r]:Lt=r}function Yt(){if(Lt){var r=Lt,a=Rt;if(Rt=Lt=null,zt(r),a)for(r=0;r<a.length;r++)zt(a[r])}}function $t(r,a){return r(a)}function Zt(){}var Bt=!1;function Yn(r,a,d){if(Bt)return r(a,d);Bt=!0;try{return $t(r,a,d)}finally{Bt=!1,(Lt!==null||Rt!==null)&&(Zt(),Yt())}}function nn(r,a){var d=r.stateNode;if(d===null)return null;var m=pu(d);if(m===null)return null;d=m[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(m=!m.disabled)||(r=r.type,m=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!m;break e;default:r=!1}if(r)return null;if(d&&typeof d!="function")throw Error(n(231,a,typeof d));return d}var rn=!1;if(u)try{var sn={};Object.defineProperty(sn,"passive",{get:function(){rn=!0}}),window.addEventListener("test",sn,sn),window.removeEventListener("test",sn,sn)}catch{rn=!1}function wn(r,a,d,m,b,k,F,ne,de){var Ne=Array.prototype.slice.call(arguments,3);try{a.apply(d,Ne)}catch(qe){this.onError(qe)}}var Ft=!1,on=null,un=!1,Xt=null,dn={onError:function(r){Ft=!0,on=r}};function Js(r,a,d,m,b,k,F,ne,de){Ft=!1,on=null,wn.apply(dn,arguments)}function ds(r,a,d,m,b,k,F,ne,de){if(Js.apply(this,arguments),Ft){if(Ft){var Ne=on;Ft=!1,on=null}else throw Error(n(198));un||(un=!0,Xt=Ne)}}function Vt(r){var a=r,d=r;if(r.alternate)for(;a.return;)a=a.return;else{r=a;do a=r,(a.flags&4098)!==0&&(d=a.return),r=a.return;while(r)}return a.tag===3?d:null}function Ms(r){if(r.tag===13){var a=r.memoizedState;if(a===null&&(r=r.alternate,r!==null&&(a=r.memoizedState)),a!==null)return a.dehydrated}return null}function Xn(r){if(Vt(r)!==r)throw Error(n(188))}function Ts(r){var a=r.alternate;if(!a){if(a=Vt(r),a===null)throw Error(n(188));return a!==r?null:r}for(var d=r,m=a;;){var b=d.return;if(b===null)break;var k=b.alternate;if(k===null){if(m=b.return,m!==null){d=m;continue}break}if(b.child===k.child){for(k=b.child;k;){if(k===d)return Xn(b),r;if(k===m)return Xn(b),a;k=k.sibling}throw Error(n(188))}if(d.return!==m.return)d=b,m=k;else{for(var F=!1,ne=b.child;ne;){if(ne===d){F=!0,d=b,m=k;break}if(ne===m){F=!0,m=b,d=k;break}ne=ne.sibling}if(!F){for(ne=k.child;ne;){if(ne===d){F=!0,d=k,m=b;break}if(ne===m){F=!0,m=k,d=b;break}ne=ne.sibling}if(!F)throw Error(n(189))}}if(d.alternate!==m)throw Error(n(190))}if(d.tag!==3)throw Error(n(188));return d.stateNode.current===d?r:a}function kt(r){return r=Ts(r),r!==null?ue(r):null}function ue(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var a=ue(r);if(a!==null)return a;r=r.sibling}return null}var De=t.unstable_scheduleCallback,Xe=t.unstable_cancelCallback,ct=t.unstable_shouldYield,It=t.unstable_requestPaint,G=t.unstable_now,he=t.unstable_getCurrentPriorityLevel,Ie=t.unstable_ImmediatePriority,Qe=t.unstable_UserBlockingPriority,Ae=t.unstable_NormalPriority,Et=t.unstable_LowPriority,Ct=t.unstable_IdlePriority,Ze=null,Ee=null;function ut(r){if(Ee&&typeof Ee.onCommitFiberRoot=="function")try{Ee.onCommitFiberRoot(Ze,r,void 0,(r.current.flags&128)===128)}catch{}}var Pe=Math.clz32?Math.clz32:we,We=Math.log,vt=Math.LN2;function we(r){return r>>>=0,r===0?32:31-(We(r)/vt|0)|0}var Le=64,Ke=4194304;function at(r){switch(r&-r){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: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 r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function wt(r,a){var d=r.pendingLanes;if(d===0)return 0;var m=0,b=r.suspendedLanes,k=r.pingedLanes,F=d&268435455;if(F!==0){var ne=F&~b;ne!==0?m=at(ne):(k&=F,k!==0&&(m=at(k)))}else F=d&~b,F!==0?m=at(F):k!==0&&(m=at(k));if(m===0)return 0;if(a!==0&&a!==m&&(a&b)===0&&(b=m&-m,k=a&-a,b>=k||b===16&&(k&4194240)!==0))return a;if((m&4)!==0&&(m|=d&16),a=r.entangledLanes,a!==0)for(r=r.entanglements,a&=m;0<a;)d=31-Pe(a),b=1<<d,m|=r[d],a&=~b;return m}function Nn(r,a){switch(r){case 1:case 2:case 4:return a+250;case 8:case 16:case 32:case 64: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 a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function hs(r,a){for(var d=r.suspendedLanes,m=r.pingedLanes,b=r.expirationTimes,k=r.pendingLanes;0<k;){var F=31-Pe(k),ne=1<<F,de=b[F];de===-1?((ne&d)===0||(ne&m)!==0)&&(b[F]=Nn(ne,a)):de<=a&&(r.expiredLanes|=ne),k&=~ne}}function Gt(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function Hn(){var r=Le;return Le<<=1,(Le&4194240)===0&&(Le=64),r}function Pt(r){for(var a=[],d=0;31>d;d++)a.push(r);return a}function ws(r,a,d){r.pendingLanes|=a,a!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,a=31-Pe(a),r[a]=d}function $i(r,a){var d=r.pendingLanes&~a;r.pendingLanes=a,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=a,r.mutableReadLanes&=a,r.entangledLanes&=a,a=r.entanglements;var m=r.eventTimes;for(r=r.expirationTimes;0<d;){var b=31-Pe(d),k=1<<b;a[b]=0,m[b]=-1,r[b]=-1,d&=~k}}function xi(r,a){var d=r.entangledLanes|=a;for(r=r.entanglements;d;){var m=31-Pe(d),b=1<<m;b&a|r[m]&a&&(r[m]|=a),d&=~b}}var Jt=0;function hl(r){return r&=-r,1<r?4<r?(r&268435455)!==0?16:536870912:4:1}var fl,ra,Qs,pl,ml,oa=!1,lr=[],Ss=null,Zs=null,ki=null,cr=new Map,Pr=new Map,Is=[],ru="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 submit".split(" ");function ur(r,a){switch(r){case"focusin":case"focusout":Ss=null;break;case"dragenter":case"dragleave":Zs=null;break;case"mouseover":case"mouseout":ki=null;break;case"pointerover":case"pointerout":cr.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Pr.delete(a.pointerId)}}function xs(r,a,d,m,b,k){return r===null||r.nativeEvent!==k?(r={blockedOn:a,domEventName:d,eventSystemFlags:m,nativeEvent:k,targetContainers:[b]},a!==null&&(a=Rl(a),a!==null&&ra(a)),r):(r.eventSystemFlags|=m,a=r.targetContainers,b!==null&&a.indexOf(b)===-1&&a.push(b),r)}function gl(r,a,d,m,b){switch(a){case"focusin":return Ss=xs(Ss,r,a,d,m,b),!0;case"dragenter":return Zs=xs(Zs,r,a,d,m,b),!0;case"mouseover":return ki=xs(ki,r,a,d,m,b),!0;case"pointerover":var k=b.pointerId;return cr.set(k,xs(cr.get(k)||null,r,a,d,m,b)),!0;case"gotpointercapture":return k=b.pointerId,Pr.set(k,xs(Pr.get(k)||null,r,a,d,m,b)),!0}return!1}function vl(r){var a=wo(r.target);if(a!==null){var d=Vt(a);if(d!==null){if(a=d.tag,a===13){if(a=Ms(d),a!==null){r.blockedOn=a,ml(r.priority,function(){Qs(d)});return}}else if(a===3&&d.stateNode.current.memoizedState.isDehydrated){r.blockedOn=d.tag===3?d.stateNode.containerInfo:null;return}}}r.blockedOn=null}function Jn(r){if(r.blockedOn!==null)return!1;for(var a=r.targetContainers;0<a.length;){var d=ua(r.domEventName,r.eventSystemFlags,a[0],r.nativeEvent);if(d===null){d=r.nativeEvent;var m=new d.constructor(d.type,d);Oe=m,d.target.dispatchEvent(m),Oe=null}else return a=Rl(d),a!==null&&ra(a),r.blockedOn=d,!1;a.shift()}return!0}function _l(r,a,d){Jn(r)&&d.delete(a)}function aa(){oa=!1,Ss!==null&&Jn(Ss)&&(Ss=null),Zs!==null&&Jn(Zs)&&(Zs=null),ki!==null&&Jn(ki)&&(ki=null),cr.forEach(_l),Pr.forEach(_l)}function Ci(r,a){r.blockedOn===a&&(r.blockedOn=null,oa||(oa=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,aa)))}function zi(r){function a(b){return Ci(b,r)}if(0<lr.length){Ci(lr[0],r);for(var d=1;d<lr.length;d++){var m=lr[d];m.blockedOn===r&&(m.blockedOn=null)}}for(Ss!==null&&Ci(Ss,r),Zs!==null&&Ci(Zs,r),ki!==null&&Ci(ki,r),cr.forEach(a),Pr.forEach(a),d=0;d<Is.length;d++)m=Is[d],m.blockedOn===r&&(m.blockedOn=null);for(;0<Is.length&&(d=Is[0],d.blockedOn===null);)vl(d),d.blockedOn===null&&Is.shift()}var dr=x.ReactCurrentBatchConfig,hr=!0;function ou(r,a,d,m){var b=Jt,k=dr.transition;dr.transition=null;try{Jt=1,ca(r,a,d,m)}finally{Jt=b,dr.transition=k}}function la(r,a,d,m){var b=Jt,k=dr.transition;dr.transition=null;try{Jt=4,ca(r,a,d,m)}finally{Jt=b,dr.transition=k}}function ca(r,a,d,m){if(hr){var b=ua(r,a,d,m);if(b===null)Gh(r,a,m,yo,d),ur(r,m);else if(gl(b,r,a,d,m))m.stopPropagation();else if(ur(r,m),a&4&&-1<ru.indexOf(r)){for(;b!==null;){var k=Rl(b);if(k!==null&&fl(k),k=ua(r,a,d,m),k===null&&Gh(r,a,m,yo,d),k===b)break;b=k}b!==null&&m.stopPropagation()}else Gh(r,a,m,null,d)}}var yo=null;function ua(r,a,d,m){if(yo=null,r=gt(m),r=wo(r),r!==null)if(a=Vt(r),a===null)r=null;else if(d=a.tag,d===13){if(r=Ms(a),r!==null)return r;r=null}else if(d===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;r=null}else a!==r&&(r=null);return yo=r,null}function yl(r){switch(r){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"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 1;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"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(he()){case Ie:return 1;case Qe:return 4;case Ae:case Et:return 16;case Ct:return 536870912;default:return 16}default:return 16}}var Ei=null,da=null,be=null;function Ye(){if(be)return be;var r,a=da,d=a.length,m,b="value"in Ei?Ei.value:Ei.textContent,k=b.length;for(r=0;r<d&&a[r]===b[r];r++);var F=d-r;for(m=1;m<=F&&a[d-m]===b[k-m];m++);return be=b.slice(r,1<m?1-m:void 0)}function tt(r){var a=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&a===13&&(r=13)):r=a,r===10&&(r=13),32<=r||r===13?r:0}function pt(){return!0}function Mt(){return!1}function xt(r){function a(d,m,b,k,F){this._reactName=d,this._targetInst=b,this.type=m,this.nativeEvent=k,this.target=F,this.currentTarget=null;for(var ne in r)r.hasOwnProperty(ne)&&(d=r[ne],this[ne]=d?d(k):k[ne]);return this.isDefaultPrevented=(k.defaultPrevented!=null?k.defaultPrevented:k.returnValue===!1)?pt:Mt,this.isPropagationStopped=Mt,this}return H(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var d=this.nativeEvent;d&&(d.preventDefault?d.preventDefault():typeof d.returnValue!="unknown"&&(d.returnValue=!1),this.isDefaultPrevented=pt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=pt)},persist:function(){},isPersistent:pt}),a}var Qt={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},hn=xt(Qt),Dn=H({},Qt,{view:0,detail:0}),Tn=xt(Dn),ks,ai,bo,bl=H({},Dn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Oh,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==bo&&(bo&&r.type==="mousemove"?(ks=r.screenX-bo.screenX,ai=r.screenY-bo.screenY):ai=ks=0,bo=r),ks)},movementY:function(r){return"movementY"in r?r.movementY:ai}}),$_=xt(bl),ON=H({},bl,{dataTransfer:0}),BN=xt(ON),$N=H({},Dn,{relatedTarget:0}),Dh=xt($N),zN=H({},Qt,{animationName:0,elapsedTime:0,pseudoElement:0}),FN=xt(zN),HN=H({},Qt,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),UN=xt(HN),WN=H({},Qt,{data:0}),z_=xt(WN),qN={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},KN={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"},VN={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function GN(r){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(r):(r=VN[r])?!!a[r]:!1}function Oh(){return GN}var YN=H({},Dn,{key:function(r){if(r.key){var a=qN[r.key]||r.key;if(a!=="Unidentified")return a}return r.type==="keypress"?(r=tt(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?KN[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Oh,charCode:function(r){return r.type==="keypress"?tt(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?tt(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),XN=xt(YN),JN=H({},bl,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),F_=xt(JN),QN=H({},Dn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Oh}),ZN=xt(QN),e2=H({},Qt,{propertyName:0,elapsedTime:0,pseudoElement:0}),t2=xt(e2),n2=H({},bl,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),s2=xt(n2),i2=[9,13,27,32],Bh=u&&"CompositionEvent"in window,wl=null;u&&"documentMode"in document&&(wl=document.documentMode);var r2=u&&"TextEvent"in window&&!wl,H_=u&&(!Bh||wl&&8<wl&&11>=wl),U_=" ",W_=!1;function q_(r,a){switch(r){case"keyup":return i2.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function K_(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var ha=!1;function o2(r,a){switch(r){case"compositionend":return K_(a);case"keypress":return a.which!==32?null:(W_=!0,U_);case"textInput":return r=a.data,r===U_&&W_?null:r;default:return null}}function a2(r,a){if(ha)return r==="compositionend"||!Bh&&q_(r,a)?(r=Ye(),be=da=Ei=null,ha=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return H_&&a.locale!=="ko"?null:a.data;default:return null}}var l2={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 V_(r){var a=r&&r.nodeName&&r.nodeName.toLowerCase();return a==="input"?!!l2[r.type]:a==="textarea"}function G_(r,a,d,m){ft(m),a=du(a,"onChange"),0<a.length&&(d=new hn("onChange","change",null,d,m),r.push({event:d,listeners:a}))}var Sl=null,xl=null;function c2(r){hy(r,0)}function au(r){var a=va(r);if(Te(a))return r}function u2(r,a){if(r==="change")return a}var Y_=!1;if(u){var $h;if(u){var zh="oninput"in document;if(!zh){var X_=document.createElement("div");X_.setAttribute("oninput","return;"),zh=typeof X_.oninput=="function"}$h=zh}else $h=!1;Y_=$h&&(!document.documentMode||9<document.documentMode)}function J_(){Sl&&(Sl.detachEvent("onpropertychange",Q_),xl=Sl=null)}function Q_(r){if(r.propertyName==="value"&&au(xl)){var a=[];G_(a,xl,r,gt(r)),Yn(c2,a)}}function d2(r,a,d){r==="focusin"?(J_(),Sl=a,xl=d,Sl.attachEvent("onpropertychange",Q_)):r==="focusout"&&J_()}function h2(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return au(xl)}function f2(r,a){if(r==="click")return au(a)}function p2(r,a){if(r==="input"||r==="change")return au(a)}function m2(r,a){return r===a&&(r!==0||1/r===1/a)||r!==r&&a!==a}var Ni=typeof Object.is=="function"?Object.is:m2;function kl(r,a){if(Ni(r,a))return!0;if(typeof r!="object"||r===null||typeof a!="object"||a===null)return!1;var d=Object.keys(r),m=Object.keys(a);if(d.length!==m.length)return!1;for(m=0;m<d.length;m++){var b=d[m];if(!h.call(a,b)||!Ni(r[b],a[b]))return!1}return!0}function Z_(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function ey(r,a){var d=Z_(r);r=0;for(var m;d;){if(d.nodeType===3){if(m=r+d.textContent.length,r<=a&&m>=a)return{node:d,offset:a-r};r=m}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=Z_(d)}}function ty(r,a){return r&&a?r===a?!0:r&&r.nodeType===3?!1:a&&a.nodeType===3?ty(r,a.parentNode):"contains"in r?r.contains(a):r.compareDocumentPosition?!!(r.compareDocumentPosition(a)&16):!1:!1}function ny(){for(var r=window,a=Me();a instanceof r.HTMLIFrameElement;){try{var d=typeof a.contentWindow.location.href=="string"}catch{d=!1}if(d)r=a.contentWindow;else break;a=Me(r.document)}return a}function Fh(r){var a=r&&r.nodeName&&r.nodeName.toLowerCase();return a&&(a==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||a==="textarea"||r.contentEditable==="true")}function g2(r){var a=ny(),d=r.focusedElem,m=r.selectionRange;if(a!==d&&d&&d.ownerDocument&&ty(d.ownerDocument.documentElement,d)){if(m!==null&&Fh(d)){if(a=m.start,r=m.end,r===void 0&&(r=a),"selectionStart"in d)d.selectionStart=a,d.selectionEnd=Math.min(r,d.value.length);else if(r=(a=d.ownerDocument||document)&&a.defaultView||window,r.getSelection){r=r.getSelection();var b=d.textContent.length,k=Math.min(m.start,b);m=m.end===void 0?k:Math.min(m.end,b),!r.extend&&k>m&&(b=m,m=k,k=b),b=ey(d,k);var F=ey(d,m);b&&F&&(r.rangeCount!==1||r.anchorNode!==b.node||r.anchorOffset!==b.offset||r.focusNode!==F.node||r.focusOffset!==F.offset)&&(a=a.createRange(),a.setStart(b.node,b.offset),r.removeAllRanges(),k>m?(r.addRange(a),r.extend(F.node,F.offset)):(a.setEnd(F.node,F.offset),r.addRange(a)))}}for(a=[],r=d;r=r.parentNode;)r.nodeType===1&&a.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;d<a.length;d++)r=a[d],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var v2=u&&"documentMode"in document&&11>=document.documentMode,fa=null,Hh=null,Cl=null,Uh=!1;function sy(r,a,d){var m=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;Uh||fa==null||fa!==Me(m)||(m=fa,"selectionStart"in m&&Fh(m)?m={start:m.selectionStart,end:m.selectionEnd}:(m=(m.ownerDocument&&m.ownerDocument.defaultView||window).getSelection(),m={anchorNode:m.anchorNode,anchorOffset:m.anchorOffset,focusNode:m.focusNode,focusOffset:m.focusOffset}),Cl&&kl(Cl,m)||(Cl=m,m=du(Hh,"onSelect"),0<m.length&&(a=new hn("onSelect","select",null,a,d),r.push({event:a,listeners:m}),a.target=fa)))}function lu(r,a){var d={};return d[r.toLowerCase()]=a.toLowerCase(),d["Webkit"+r]="webkit"+a,d["Moz"+r]="moz"+a,d}var pa={animationend:lu("Animation","AnimationEnd"),animationiteration:lu("Animation","AnimationIteration"),animationstart:lu("Animation","AnimationStart"),transitionend:lu("Transition","TransitionEnd")},Wh={},iy={};u&&(iy=document.createElement("div").style,"AnimationEvent"in window||(delete pa.animationend.animation,delete pa.animationiteration.animation,delete pa.animationstart.animation),"TransitionEvent"in window||delete pa.transitionend.transition);function cu(r){if(Wh[r])return Wh[r];if(!pa[r])return r;var a=pa[r],d;for(d in a)if(a.hasOwnProperty(d)&&d in iy)return Wh[r]=a[d];return r}var ry=cu("animationend"),oy=cu("animationiteration"),ay=cu("animationstart"),ly=cu("transitionend"),cy=new Map,uy="abort auxClick 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(" ");function Dr(r,a){cy.set(r,a),l(a,[r])}for(var qh=0;qh<uy.length;qh++){var Kh=uy[qh],_2=Kh.toLowerCase(),y2=Kh[0].toUpperCase()+Kh.slice(1);Dr(_2,"on"+y2)}Dr(ry,"onAnimationEnd"),Dr(oy,"onAnimationIteration"),Dr(ay,"onAnimationStart"),Dr("dblclick","onDoubleClick"),Dr("focusin","onFocus"),Dr("focusout","onBlur"),Dr(ly,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var El="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(" "),b2=new Set("cancel close invalid load scroll toggle".split(" ").concat(El));function dy(r,a,d){var m=r.type||"unknown-event";r.currentTarget=d,ds(m,a,void 0,r),r.currentTarget=null}function hy(r,a){a=(a&4)!==0;for(var d=0;d<r.length;d++){var m=r[d],b=m.event;m=m.listeners;e:{var k=void 0;if(a)for(var F=m.length-1;0<=F;F--){var ne=m[F],de=ne.instance,Ne=ne.currentTarget;if(ne=ne.listener,de!==k&&b.isPropagationStopped())break e;dy(b,ne,Ne),k=de}else for(F=0;F<m.length;F++){if(ne=m[F],de=ne.instance,Ne=ne.currentTarget,ne=ne.listener,de!==k&&b.isPropagationStopped())break e;dy(b,ne,Ne),k=de}}}if(un)throw r=Xt,un=!1,Xt=null,r}function fn(r,a){var d=a[ef];d===void 0&&(d=a[ef]=new Set);var m=r+"__bubble";d.has(m)||(fy(a,r,2,!1),d.add(m))}function Vh(r,a,d){var m=0;a&&(m|=4),fy(d,r,m,a)}var uu="_reactListening"+Math.random().toString(36).slice(2);function Nl(r){if(!r[uu]){r[uu]=!0,s.forEach(function(d){d!=="selectionchange"&&(b2.has(d)||Vh(d,!1,r),Vh(d,!0,r))});var a=r.nodeType===9?r:r.ownerDocument;a===null||a[uu]||(a[uu]=!0,Vh("selectionchange",!1,a))}}function fy(r,a,d,m){switch(yl(a)){case 1:var b=ou;break;case 4:b=la;break;default:b=ca}d=b.bind(null,a,d,r),b=void 0,!rn||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(b=!0),m?b!==void 0?r.addEventListener(a,d,{capture:!0,passive:b}):r.addEventListener(a,d,!0):b!==void 0?r.addEventListener(a,d,{passive:b}):r.addEventListener(a,d,!1)}function Gh(r,a,d,m,b){var k=m;if((a&1)===0&&(a&2)===0&&m!==null)e:for(;;){if(m===null)return;var F=m.tag;if(F===3||F===4){var ne=m.stateNode.containerInfo;if(ne===b||ne.nodeType===8&&ne.parentNode===b)break;if(F===4)for(F=m.return;F!==null;){var de=F.tag;if((de===3||de===4)&&(de=F.stateNode.containerInfo,de===b||de.nodeType===8&&de.parentNode===b))return;F=F.return}for(;ne!==null;){if(F=wo(ne),F===null)return;if(de=F.tag,de===5||de===6){m=k=F;continue e}ne=ne.parentNode}}m=m.return}Yn(function(){var Ne=k,qe=gt(d),Ge=[];e:{var Ue=cy.get(r);if(Ue!==void 0){var ht=hn,_t=r;switch(r){case"keypress":if(tt(d)===0)break e;case"keydown":case"keyup":ht=XN;break;case"focusin":_t="focus",ht=Dh;break;case"focusout":_t="blur",ht=Dh;break;case"beforeblur":case"afterblur":ht=Dh;break;case"click":if(d.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":ht=$_;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":ht=BN;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":ht=ZN;break;case ry:case oy:case ay:ht=FN;break;case ly:ht=t2;break;case"scroll":ht=Tn;break;case"wheel":ht=s2;break;case"copy":case"cut":case"paste":ht=UN;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":ht=F_}var bt=(a&4)!==0,In=!bt&&r==="scroll",Se=bt?Ue!==null?Ue+"Capture":null:Ue;bt=[];for(var me=Ne,Ce;me!==null;){Ce=me;var et=Ce.stateNode;if(Ce.tag===5&&et!==null&&(Ce=et,Se!==null&&(et=nn(me,Se),et!=null&&bt.push(jl(me,et,Ce)))),In)break;me=me.return}0<bt.length&&(Ue=new ht(Ue,_t,null,d,qe),Ge.push({event:Ue,listeners:bt}))}}if((a&7)===0){e:{if(Ue=r==="mouseover"||r==="pointerover",ht=r==="mouseout"||r==="pointerout",Ue&&d!==Oe&&(_t=d.relatedTarget||d.fromElement)&&(wo(_t)||_t[fr]))break e;if((ht||Ue)&&(Ue=qe.window===qe?qe:(Ue=qe.ownerDocument)?Ue.defaultView||Ue.parentWindow:window,ht?(_t=d.relatedTarget||d.toElement,ht=Ne,_t=_t?wo(_t):null,_t!==null&&(In=Vt(_t),_t!==In||_t.tag!==5&&_t.tag!==6)&&(_t=null)):(ht=null,_t=Ne),ht!==_t)){if(bt=$_,et="onMouseLeave",Se="onMouseEnter",me="mouse",(r==="pointerout"||r==="pointerover")&&(bt=F_,et="onPointerLeave",Se="onPointerEnter",me="pointer"),In=ht==null?Ue:va(ht),Ce=_t==null?Ue:va(_t),Ue=new bt(et,me+"leave",ht,d,qe),Ue.target=In,Ue.relatedTarget=Ce,et=null,wo(qe)===Ne&&(bt=new bt(Se,me+"enter",_t,d,qe),bt.target=Ce,bt.relatedTarget=In,et=bt),In=et,ht&&_t)t:{for(bt=ht,Se=_t,me=0,Ce=bt;Ce;Ce=ma(Ce))me++;for(Ce=0,et=Se;et;et=ma(et))Ce++;for(;0<me-Ce;)bt=ma(bt),me--;for(;0<Ce-me;)Se=ma(Se),Ce--;for(;me--;){if(bt===Se||Se!==null&&bt===Se.alternate)break t;bt=ma(bt),Se=ma(Se)}bt=null}else bt=null;ht!==null&&py(Ge,Ue,ht,bt,!1),_t!==null&&In!==null&&py(Ge,In,_t,bt,!0)}}e:{if(Ue=Ne?va(Ne):window,ht=Ue.nodeName&&Ue.nodeName.toLowerCase(),ht==="select"||ht==="input"&&Ue.type==="file")var St=u2;else if(V_(Ue))if(Y_)St=p2;else{St=h2;var Nt=d2}else(ht=Ue.nodeName)&&ht.toLowerCase()==="input"&&(Ue.type==="checkbox"||Ue.type==="radio")&&(St=f2);if(St&&(St=St(r,Ne))){G_(Ge,St,d,qe);break e}Nt&&Nt(r,Ue,Ne),r==="focusout"&&(Nt=Ue._wrapperState)&&Nt.controlled&&Ue.type==="number"&&fe(Ue,"number",Ue.value)}switch(Nt=Ne?va(Ne):window,r){case"focusin":(V_(Nt)||Nt.contentEditable==="true")&&(fa=Nt,Hh=Ne,Cl=null);break;case"focusout":Cl=Hh=fa=null;break;case"mousedown":Uh=!0;break;case"contextmenu":case"mouseup":case"dragend":Uh=!1,sy(Ge,d,qe);break;case"selectionchange":if(v2)break;case"keydown":case"keyup":sy(Ge,d,qe)}var jt;if(Bh)e:{switch(r){case"compositionstart":var Dt="onCompositionStart";break e;case"compositionend":Dt="onCompositionEnd";break e;case"compositionupdate":Dt="onCompositionUpdate";break e}Dt=void 0}else ha?q_(r,d)&&(Dt="onCompositionEnd"):r==="keydown"&&d.keyCode===229&&(Dt="onCompositionStart");Dt&&(H_&&d.locale!=="ko"&&(ha||Dt!=="onCompositionStart"?Dt==="onCompositionEnd"&&ha&&(jt=Ye()):(Ei=qe,da="value"in Ei?Ei.value:Ei.textContent,ha=!0)),Nt=du(Ne,Dt),0<Nt.length&&(Dt=new z_(Dt,r,null,d,qe),Ge.push({event:Dt,listeners:Nt}),jt?Dt.data=jt:(jt=K_(d),jt!==null&&(Dt.data=jt)))),(jt=r2?o2(r,d):a2(r,d))&&(Ne=du(Ne,"onBeforeInput"),0<Ne.length&&(qe=new z_("onBeforeInput","beforeinput",null,d,qe),Ge.push({event:qe,listeners:Ne}),qe.data=jt))}hy(Ge,a)})}function jl(r,a,d){return{instance:r,listener:a,currentTarget:d}}function du(r,a){for(var d=a+"Capture",m=[];r!==null;){var b=r,k=b.stateNode;b.tag===5&&k!==null&&(b=k,k=nn(r,d),k!=null&&m.unshift(jl(r,k,b)),k=nn(r,a),k!=null&&m.push(jl(r,k,b))),r=r.return}return m}function ma(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function py(r,a,d,m,b){for(var k=a._reactName,F=[];d!==null&&d!==m;){var ne=d,de=ne.alternate,Ne=ne.stateNode;if(de!==null&&de===m)break;ne.tag===5&&Ne!==null&&(ne=Ne,b?(de=nn(d,k),de!=null&&F.unshift(jl(d,de,ne))):b||(de=nn(d,k),de!=null&&F.push(jl(d,de,ne)))),d=d.return}F.length!==0&&r.push({event:a,listeners:F})}var w2=/\r\n?/g,S2=/\u0000|\uFFFD/g;function my(r){return(typeof r=="string"?r:""+r).replace(w2,`
38
+ `).replace(S2,"")}function hu(r,a,d){if(a=my(a),my(r)!==a&&d)throw Error(n(425))}function fu(){}var Yh=null,Xh=null;function Jh(r,a){return r==="textarea"||r==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var Qh=typeof setTimeout=="function"?setTimeout:void 0,x2=typeof clearTimeout=="function"?clearTimeout:void 0,gy=typeof Promise=="function"?Promise:void 0,k2=typeof queueMicrotask=="function"?queueMicrotask:typeof gy<"u"?function(r){return gy.resolve(null).then(r).catch(C2)}:Qh;function C2(r){setTimeout(function(){throw r})}function Zh(r,a){var d=a,m=0;do{var b=d.nextSibling;if(r.removeChild(d),b&&b.nodeType===8)if(d=b.data,d==="/$"){if(m===0){r.removeChild(b),zi(a);return}m--}else d!=="$"&&d!=="$?"&&d!=="$!"||m++;d=b}while(d);zi(a)}function Or(r){for(;r!=null;r=r.nextSibling){var a=r.nodeType;if(a===1||a===3)break;if(a===8){if(a=r.data,a==="$"||a==="$!"||a==="$?")break;if(a==="/$")return null}}return r}function vy(r){r=r.previousSibling;for(var a=0;r;){if(r.nodeType===8){var d=r.data;if(d==="$"||d==="$!"||d==="$?"){if(a===0)return r;a--}else d==="/$"&&a++}r=r.previousSibling}return null}var ga=Math.random().toString(36).slice(2),Fi="__reactFiber$"+ga,Ll="__reactProps$"+ga,fr="__reactContainer$"+ga,ef="__reactEvents$"+ga,E2="__reactListeners$"+ga,N2="__reactHandles$"+ga;function wo(r){var a=r[Fi];if(a)return a;for(var d=r.parentNode;d;){if(a=d[fr]||d[Fi]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(r=vy(r);r!==null;){if(d=r[Fi])return d;r=vy(r)}return a}r=d,d=r.parentNode}return null}function Rl(r){return r=r[Fi]||r[fr],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function va(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(n(33))}function pu(r){return r[Ll]||null}var tf=[],_a=-1;function Br(r){return{current:r}}function pn(r){0>_a||(r.current=tf[_a],tf[_a]=null,_a--)}function ln(r,a){_a++,tf[_a]=r.current,r.current=a}var $r={},Cs=Br($r),Hs=Br(!1),So=$r;function ya(r,a){var d=r.type.contextTypes;if(!d)return $r;var m=r.stateNode;if(m&&m.__reactInternalMemoizedUnmaskedChildContext===a)return m.__reactInternalMemoizedMaskedChildContext;var b={},k;for(k in d)b[k]=a[k];return m&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=a,r.__reactInternalMemoizedMaskedChildContext=b),b}function Us(r){return r=r.childContextTypes,r!=null}function mu(){pn(Hs),pn(Cs)}function _y(r,a,d){if(Cs.current!==$r)throw Error(n(168));ln(Cs,a),ln(Hs,d)}function yy(r,a,d){var m=r.stateNode;if(a=a.childContextTypes,typeof m.getChildContext!="function")return d;m=m.getChildContext();for(var b in m)if(!(b in a))throw Error(n(108,te(r)||"Unknown",b));return H({},d,m)}function gu(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||$r,So=Cs.current,ln(Cs,r),ln(Hs,Hs.current),!0}function by(r,a,d){var m=r.stateNode;if(!m)throw Error(n(169));d?(r=yy(r,a,So),m.__reactInternalMemoizedMergedChildContext=r,pn(Hs),pn(Cs),ln(Cs,r)):pn(Hs),ln(Hs,d)}var pr=null,vu=!1,nf=!1;function wy(r){pr===null?pr=[r]:pr.push(r)}function j2(r){vu=!0,wy(r)}function zr(){if(!nf&&pr!==null){nf=!0;var r=0,a=Jt;try{var d=pr;for(Jt=1;r<d.length;r++){var m=d[r];do m=m(!0);while(m!==null)}pr=null,vu=!1}catch(b){throw pr!==null&&(pr=pr.slice(r+1)),De(Ie,zr),b}finally{Jt=a,nf=!1}}return null}var ba=[],wa=0,_u=null,yu=0,li=[],ci=0,xo=null,mr=1,gr="";function ko(r,a){ba[wa++]=yu,ba[wa++]=_u,_u=r,yu=a}function Sy(r,a,d){li[ci++]=mr,li[ci++]=gr,li[ci++]=xo,xo=r;var m=mr;r=gr;var b=32-Pe(m)-1;m&=~(1<<b),d+=1;var k=32-Pe(a)+b;if(30<k){var F=b-b%5;k=(m&(1<<F)-1).toString(32),m>>=F,b-=F,mr=1<<32-Pe(a)+b|d<<b|m,gr=k+r}else mr=1<<k|d<<b|m,gr=r}function sf(r){r.return!==null&&(ko(r,1),Sy(r,1,0))}function rf(r){for(;r===_u;)_u=ba[--wa],ba[wa]=null,yu=ba[--wa],ba[wa]=null;for(;r===xo;)xo=li[--ci],li[ci]=null,gr=li[--ci],li[ci]=null,mr=li[--ci],li[ci]=null}var ei=null,ti=null,_n=!1,ji=null;function xy(r,a){var d=fi(5,null,null,0);d.elementType="DELETED",d.stateNode=a,d.return=r,a=r.deletions,a===null?(r.deletions=[d],r.flags|=16):a.push(d)}function ky(r,a){switch(r.tag){case 5:var d=r.type;return a=a.nodeType!==1||d.toLowerCase()!==a.nodeName.toLowerCase()?null:a,a!==null?(r.stateNode=a,ei=r,ti=Or(a.firstChild),!0):!1;case 6:return a=r.pendingProps===""||a.nodeType!==3?null:a,a!==null?(r.stateNode=a,ei=r,ti=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=xo!==null?{id:mr,overflow:gr}:null,r.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=fi(18,null,null,0),d.stateNode=a,d.return=r,r.child=d,ei=r,ti=null,!0):!1;default:return!1}}function of(r){return(r.mode&1)!==0&&(r.flags&128)===0}function af(r){if(_n){var a=ti;if(a){var d=a;if(!ky(r,a)){if(of(r))throw Error(n(418));a=Or(d.nextSibling);var m=ei;a&&ky(r,a)?xy(m,d):(r.flags=r.flags&-4097|2,_n=!1,ei=r)}}else{if(of(r))throw Error(n(418));r.flags=r.flags&-4097|2,_n=!1,ei=r}}}function Cy(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;ei=r}function bu(r){if(r!==ei)return!1;if(!_n)return Cy(r),_n=!0,!1;var a;if((a=r.tag!==3)&&!(a=r.tag!==5)&&(a=r.type,a=a!=="head"&&a!=="body"&&!Jh(r.type,r.memoizedProps)),a&&(a=ti)){if(of(r))throw Ey(),Error(n(418));for(;a;)xy(r,a),a=Or(a.nextSibling)}if(Cy(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(n(317));e:{for(r=r.nextSibling,a=0;r;){if(r.nodeType===8){var d=r.data;if(d==="/$"){if(a===0){ti=Or(r.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}r=r.nextSibling}ti=null}}else ti=ei?Or(r.stateNode.nextSibling):null;return!0}function Ey(){for(var r=ti;r;)r=Or(r.nextSibling)}function Sa(){ti=ei=null,_n=!1}function lf(r){ji===null?ji=[r]:ji.push(r)}var L2=x.ReactCurrentBatchConfig;function Al(r,a,d){if(r=d.ref,r!==null&&typeof r!="function"&&typeof r!="object"){if(d._owner){if(d=d._owner,d){if(d.tag!==1)throw Error(n(309));var m=d.stateNode}if(!m)throw Error(n(147,r));var b=m,k=""+r;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===k?a.ref:(a=function(F){var ne=b.refs;F===null?delete ne[k]:ne[k]=F},a._stringRef=k,a)}if(typeof r!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,r))}return r}function wu(r,a){throw r=Object.prototype.toString.call(a),Error(n(31,r==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":r))}function Ny(r){var a=r._init;return a(r._payload)}function jy(r){function a(Se,me){if(r){var Ce=Se.deletions;Ce===null?(Se.deletions=[me],Se.flags|=16):Ce.push(me)}}function d(Se,me){if(!r)return null;for(;me!==null;)a(Se,me),me=me.sibling;return null}function m(Se,me){for(Se=new Map;me!==null;)me.key!==null?Se.set(me.key,me):Se.set(me.index,me),me=me.sibling;return Se}function b(Se,me){return Se=Gr(Se,me),Se.index=0,Se.sibling=null,Se}function k(Se,me,Ce){return Se.index=Ce,r?(Ce=Se.alternate,Ce!==null?(Ce=Ce.index,Ce<me?(Se.flags|=2,me):Ce):(Se.flags|=2,me)):(Se.flags|=1048576,me)}function F(Se){return r&&Se.alternate===null&&(Se.flags|=2),Se}function ne(Se,me,Ce,et){return me===null||me.tag!==6?(me=Zf(Ce,Se.mode,et),me.return=Se,me):(me=b(me,Ce),me.return=Se,me)}function de(Se,me,Ce,et){var St=Ce.type;return St===Y?qe(Se,me,Ce.props.children,et,Ce.key):me!==null&&(me.elementType===St||typeof St=="object"&&St!==null&&St.$$typeof===z&&Ny(St)===me.type)?(et=b(me,Ce.props),et.ref=Al(Se,me,Ce),et.return=Se,et):(et=qu(Ce.type,Ce.key,Ce.props,null,Se.mode,et),et.ref=Al(Se,me,Ce),et.return=Se,et)}function Ne(Se,me,Ce,et){return me===null||me.tag!==4||me.stateNode.containerInfo!==Ce.containerInfo||me.stateNode.implementation!==Ce.implementation?(me=ep(Ce,Se.mode,et),me.return=Se,me):(me=b(me,Ce.children||[]),me.return=Se,me)}function qe(Se,me,Ce,et,St){return me===null||me.tag!==7?(me=Mo(Ce,Se.mode,et,St),me.return=Se,me):(me=b(me,Ce),me.return=Se,me)}function Ge(Se,me,Ce){if(typeof me=="string"&&me!==""||typeof me=="number")return me=Zf(""+me,Se.mode,Ce),me.return=Se,me;if(typeof me=="object"&&me!==null){switch(me.$$typeof){case W:return Ce=qu(me.type,me.key,me.props,null,Se.mode,Ce),Ce.ref=Al(Se,null,me),Ce.return=Se,Ce;case $:return me=ep(me,Se.mode,Ce),me.return=Se,me;case z:var et=me._init;return Ge(Se,et(me._payload),Ce)}if(ve(me)||L(me))return me=Mo(me,Se.mode,Ce,null),me.return=Se,me;wu(Se,me)}return null}function Ue(Se,me,Ce,et){var St=me!==null?me.key:null;if(typeof Ce=="string"&&Ce!==""||typeof Ce=="number")return St!==null?null:ne(Se,me,""+Ce,et);if(typeof Ce=="object"&&Ce!==null){switch(Ce.$$typeof){case W:return Ce.key===St?de(Se,me,Ce,et):null;case $:return Ce.key===St?Ne(Se,me,Ce,et):null;case z:return St=Ce._init,Ue(Se,me,St(Ce._payload),et)}if(ve(Ce)||L(Ce))return St!==null?null:qe(Se,me,Ce,et,null);wu(Se,Ce)}return null}function ht(Se,me,Ce,et,St){if(typeof et=="string"&&et!==""||typeof et=="number")return Se=Se.get(Ce)||null,ne(me,Se,""+et,St);if(typeof et=="object"&&et!==null){switch(et.$$typeof){case W:return Se=Se.get(et.key===null?Ce:et.key)||null,de(me,Se,et,St);case $:return Se=Se.get(et.key===null?Ce:et.key)||null,Ne(me,Se,et,St);case z:var Nt=et._init;return ht(Se,me,Ce,Nt(et._payload),St)}if(ve(et)||L(et))return Se=Se.get(Ce)||null,qe(me,Se,et,St,null);wu(me,et)}return null}function _t(Se,me,Ce,et){for(var St=null,Nt=null,jt=me,Dt=me=0,es=null;jt!==null&&Dt<Ce.length;Dt++){jt.index>Dt?(es=jt,jt=null):es=jt.sibling;var tn=Ue(Se,jt,Ce[Dt],et);if(tn===null){jt===null&&(jt=es);break}r&&jt&&tn.alternate===null&&a(Se,jt),me=k(tn,me,Dt),Nt===null?St=tn:Nt.sibling=tn,Nt=tn,jt=es}if(Dt===Ce.length)return d(Se,jt),_n&&ko(Se,Dt),St;if(jt===null){for(;Dt<Ce.length;Dt++)jt=Ge(Se,Ce[Dt],et),jt!==null&&(me=k(jt,me,Dt),Nt===null?St=jt:Nt.sibling=jt,Nt=jt);return _n&&ko(Se,Dt),St}for(jt=m(Se,jt);Dt<Ce.length;Dt++)es=ht(jt,Se,Dt,Ce[Dt],et),es!==null&&(r&&es.alternate!==null&&jt.delete(es.key===null?Dt:es.key),me=k(es,me,Dt),Nt===null?St=es:Nt.sibling=es,Nt=es);return r&&jt.forEach(function(Yr){return a(Se,Yr)}),_n&&ko(Se,Dt),St}function bt(Se,me,Ce,et){var St=L(Ce);if(typeof St!="function")throw Error(n(150));if(Ce=St.call(Ce),Ce==null)throw Error(n(151));for(var Nt=St=null,jt=me,Dt=me=0,es=null,tn=Ce.next();jt!==null&&!tn.done;Dt++,tn=Ce.next()){jt.index>Dt?(es=jt,jt=null):es=jt.sibling;var Yr=Ue(Se,jt,tn.value,et);if(Yr===null){jt===null&&(jt=es);break}r&&jt&&Yr.alternate===null&&a(Se,jt),me=k(Yr,me,Dt),Nt===null?St=Yr:Nt.sibling=Yr,Nt=Yr,jt=es}if(tn.done)return d(Se,jt),_n&&ko(Se,Dt),St;if(jt===null){for(;!tn.done;Dt++,tn=Ce.next())tn=Ge(Se,tn.value,et),tn!==null&&(me=k(tn,me,Dt),Nt===null?St=tn:Nt.sibling=tn,Nt=tn);return _n&&ko(Se,Dt),St}for(jt=m(Se,jt);!tn.done;Dt++,tn=Ce.next())tn=ht(jt,Se,Dt,tn.value,et),tn!==null&&(r&&tn.alternate!==null&&jt.delete(tn.key===null?Dt:tn.key),me=k(tn,me,Dt),Nt===null?St=tn:Nt.sibling=tn,Nt=tn);return r&&jt.forEach(function(l5){return a(Se,l5)}),_n&&ko(Se,Dt),St}function In(Se,me,Ce,et){if(typeof Ce=="object"&&Ce!==null&&Ce.type===Y&&Ce.key===null&&(Ce=Ce.props.children),typeof Ce=="object"&&Ce!==null){switch(Ce.$$typeof){case W:e:{for(var St=Ce.key,Nt=me;Nt!==null;){if(Nt.key===St){if(St=Ce.type,St===Y){if(Nt.tag===7){d(Se,Nt.sibling),me=b(Nt,Ce.props.children),me.return=Se,Se=me;break e}}else if(Nt.elementType===St||typeof St=="object"&&St!==null&&St.$$typeof===z&&Ny(St)===Nt.type){d(Se,Nt.sibling),me=b(Nt,Ce.props),me.ref=Al(Se,Nt,Ce),me.return=Se,Se=me;break e}d(Se,Nt);break}else a(Se,Nt);Nt=Nt.sibling}Ce.type===Y?(me=Mo(Ce.props.children,Se.mode,et,Ce.key),me.return=Se,Se=me):(et=qu(Ce.type,Ce.key,Ce.props,null,Se.mode,et),et.ref=Al(Se,me,Ce),et.return=Se,Se=et)}return F(Se);case $:e:{for(Nt=Ce.key;me!==null;){if(me.key===Nt)if(me.tag===4&&me.stateNode.containerInfo===Ce.containerInfo&&me.stateNode.implementation===Ce.implementation){d(Se,me.sibling),me=b(me,Ce.children||[]),me.return=Se,Se=me;break e}else{d(Se,me);break}else a(Se,me);me=me.sibling}me=ep(Ce,Se.mode,et),me.return=Se,Se=me}return F(Se);case z:return Nt=Ce._init,In(Se,me,Nt(Ce._payload),et)}if(ve(Ce))return _t(Se,me,Ce,et);if(L(Ce))return bt(Se,me,Ce,et);wu(Se,Ce)}return typeof Ce=="string"&&Ce!==""||typeof Ce=="number"?(Ce=""+Ce,me!==null&&me.tag===6?(d(Se,me.sibling),me=b(me,Ce),me.return=Se,Se=me):(d(Se,me),me=Zf(Ce,Se.mode,et),me.return=Se,Se=me),F(Se)):d(Se,me)}return In}var xa=jy(!0),Ly=jy(!1),Su=Br(null),xu=null,ka=null,cf=null;function uf(){cf=ka=xu=null}function df(r){var a=Su.current;pn(Su),r._currentValue=a}function hf(r,a,d){for(;r!==null;){var m=r.alternate;if((r.childLanes&a)!==a?(r.childLanes|=a,m!==null&&(m.childLanes|=a)):m!==null&&(m.childLanes&a)!==a&&(m.childLanes|=a),r===d)break;r=r.return}}function Ca(r,a){xu=r,cf=ka=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&a)!==0&&(Ws=!0),r.firstContext=null)}function ui(r){var a=r._currentValue;if(cf!==r)if(r={context:r,memoizedValue:a,next:null},ka===null){if(xu===null)throw Error(n(308));ka=r,xu.dependencies={lanes:0,firstContext:r}}else ka=ka.next=r;return a}var Co=null;function ff(r){Co===null?Co=[r]:Co.push(r)}function Ry(r,a,d,m){var b=a.interleaved;return b===null?(d.next=d,ff(a)):(d.next=b.next,b.next=d),a.interleaved=d,vr(r,m)}function vr(r,a){r.lanes|=a;var d=r.alternate;for(d!==null&&(d.lanes|=a),d=r,r=r.return;r!==null;)r.childLanes|=a,d=r.alternate,d!==null&&(d.childLanes|=a),d=r,r=r.return;return d.tag===3?d.stateNode:null}var Fr=!1;function pf(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ay(r,a){r=r.updateQueue,a.updateQueue===r&&(a.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function _r(r,a){return{eventTime:r,lane:a,tag:0,payload:null,callback:null,next:null}}function Hr(r,a,d){var m=r.updateQueue;if(m===null)return null;if(m=m.shared,(en&2)!==0){var b=m.pending;return b===null?a.next=a:(a.next=b.next,b.next=a),m.pending=a,vr(r,d)}return b=m.interleaved,b===null?(a.next=a,ff(m)):(a.next=b.next,b.next=a),m.interleaved=a,vr(r,d)}function ku(r,a,d){if(a=a.updateQueue,a!==null&&(a=a.shared,(d&4194240)!==0)){var m=a.lanes;m&=r.pendingLanes,d|=m,a.lanes=d,xi(r,d)}}function My(r,a){var d=r.updateQueue,m=r.alternate;if(m!==null&&(m=m.updateQueue,d===m)){var b=null,k=null;if(d=d.firstBaseUpdate,d!==null){do{var F={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};k===null?b=k=F:k=k.next=F,d=d.next}while(d!==null);k===null?b=k=a:k=k.next=a}else b=k=a;d={baseState:m.baseState,firstBaseUpdate:b,lastBaseUpdate:k,shared:m.shared,effects:m.effects},r.updateQueue=d;return}r=d.lastBaseUpdate,r===null?d.firstBaseUpdate=a:r.next=a,d.lastBaseUpdate=a}function Cu(r,a,d,m){var b=r.updateQueue;Fr=!1;var k=b.firstBaseUpdate,F=b.lastBaseUpdate,ne=b.shared.pending;if(ne!==null){b.shared.pending=null;var de=ne,Ne=de.next;de.next=null,F===null?k=Ne:F.next=Ne,F=de;var qe=r.alternate;qe!==null&&(qe=qe.updateQueue,ne=qe.lastBaseUpdate,ne!==F&&(ne===null?qe.firstBaseUpdate=Ne:ne.next=Ne,qe.lastBaseUpdate=de))}if(k!==null){var Ge=b.baseState;F=0,qe=Ne=de=null,ne=k;do{var Ue=ne.lane,ht=ne.eventTime;if((m&Ue)===Ue){qe!==null&&(qe=qe.next={eventTime:ht,lane:0,tag:ne.tag,payload:ne.payload,callback:ne.callback,next:null});e:{var _t=r,bt=ne;switch(Ue=a,ht=d,bt.tag){case 1:if(_t=bt.payload,typeof _t=="function"){Ge=_t.call(ht,Ge,Ue);break e}Ge=_t;break e;case 3:_t.flags=_t.flags&-65537|128;case 0:if(_t=bt.payload,Ue=typeof _t=="function"?_t.call(ht,Ge,Ue):_t,Ue==null)break e;Ge=H({},Ge,Ue);break e;case 2:Fr=!0}}ne.callback!==null&&ne.lane!==0&&(r.flags|=64,Ue=b.effects,Ue===null?b.effects=[ne]:Ue.push(ne))}else ht={eventTime:ht,lane:Ue,tag:ne.tag,payload:ne.payload,callback:ne.callback,next:null},qe===null?(Ne=qe=ht,de=Ge):qe=qe.next=ht,F|=Ue;if(ne=ne.next,ne===null){if(ne=b.shared.pending,ne===null)break;Ue=ne,ne=Ue.next,Ue.next=null,b.lastBaseUpdate=Ue,b.shared.pending=null}}while(!0);if(qe===null&&(de=Ge),b.baseState=de,b.firstBaseUpdate=Ne,b.lastBaseUpdate=qe,a=b.shared.interleaved,a!==null){b=a;do F|=b.lane,b=b.next;while(b!==a)}else k===null&&(b.shared.lanes=0);jo|=F,r.lanes=F,r.memoizedState=Ge}}function Ty(r,a,d){if(r=a.effects,a.effects=null,r!==null)for(a=0;a<r.length;a++){var m=r[a],b=m.callback;if(b!==null){if(m.callback=null,m=d,typeof b!="function")throw Error(n(191,b));b.call(m)}}}var Ml={},Hi=Br(Ml),Tl=Br(Ml),Il=Br(Ml);function Eo(r){if(r===Ml)throw Error(n(174));return r}function mf(r,a){switch(ln(Il,a),ln(Tl,r),ln(Hi,Ml),r=a.nodeType,r){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:ze(null,"");break;default:r=r===8?a.parentNode:a,a=r.namespaceURI||null,r=r.tagName,a=ze(a,r)}pn(Hi),ln(Hi,a)}function Ea(){pn(Hi),pn(Tl),pn(Il)}function Iy(r){Eo(Il.current);var a=Eo(Hi.current),d=ze(a,r.type);a!==d&&(ln(Tl,r),ln(Hi,d))}function gf(r){Tl.current===r&&(pn(Hi),pn(Tl))}var Sn=Br(0);function Eu(r){for(var a=r;a!==null;){if(a.tag===13){var d=a.memoizedState;if(d!==null&&(d=d.dehydrated,d===null||d.data==="$?"||d.data==="$!"))return a}else if(a.tag===19&&a.memoizedProps.revealOrder!==void 0){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===r)break;for(;a.sibling===null;){if(a.return===null||a.return===r)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var vf=[];function _f(){for(var r=0;r<vf.length;r++)vf[r]._workInProgressVersionPrimary=null;vf.length=0}var Nu=x.ReactCurrentDispatcher,yf=x.ReactCurrentBatchConfig,No=0,xn=null,Un=null,Qn=null,ju=!1,Pl=!1,Dl=0,R2=0;function Es(){throw Error(n(321))}function bf(r,a){if(a===null)return!1;for(var d=0;d<a.length&&d<r.length;d++)if(!Ni(r[d],a[d]))return!1;return!0}function wf(r,a,d,m,b,k){if(No=k,xn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,Nu.current=r===null||r.memoizedState===null?I2:P2,r=d(m,b),Pl){k=0;do{if(Pl=!1,Dl=0,25<=k)throw Error(n(301));k+=1,Qn=Un=null,a.updateQueue=null,Nu.current=D2,r=d(m,b)}while(Pl)}if(Nu.current=Au,a=Un!==null&&Un.next!==null,No=0,Qn=Un=xn=null,ju=!1,a)throw Error(n(300));return r}function Sf(){var r=Dl!==0;return Dl=0,r}function Ui(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Qn===null?xn.memoizedState=Qn=r:Qn=Qn.next=r,Qn}function di(){if(Un===null){var r=xn.alternate;r=r!==null?r.memoizedState:null}else r=Un.next;var a=Qn===null?xn.memoizedState:Qn.next;if(a!==null)Qn=a,Un=r;else{if(r===null)throw Error(n(310));Un=r,r={memoizedState:Un.memoizedState,baseState:Un.baseState,baseQueue:Un.baseQueue,queue:Un.queue,next:null},Qn===null?xn.memoizedState=Qn=r:Qn=Qn.next=r}return Qn}function Ol(r,a){return typeof a=="function"?a(r):a}function xf(r){var a=di(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=r;var m=Un,b=m.baseQueue,k=d.pending;if(k!==null){if(b!==null){var F=b.next;b.next=k.next,k.next=F}m.baseQueue=b=k,d.pending=null}if(b!==null){k=b.next,m=m.baseState;var ne=F=null,de=null,Ne=k;do{var qe=Ne.lane;if((No&qe)===qe)de!==null&&(de=de.next={lane:0,action:Ne.action,hasEagerState:Ne.hasEagerState,eagerState:Ne.eagerState,next:null}),m=Ne.hasEagerState?Ne.eagerState:r(m,Ne.action);else{var Ge={lane:qe,action:Ne.action,hasEagerState:Ne.hasEagerState,eagerState:Ne.eagerState,next:null};de===null?(ne=de=Ge,F=m):de=de.next=Ge,xn.lanes|=qe,jo|=qe}Ne=Ne.next}while(Ne!==null&&Ne!==k);de===null?F=m:de.next=ne,Ni(m,a.memoizedState)||(Ws=!0),a.memoizedState=m,a.baseState=F,a.baseQueue=de,d.lastRenderedState=m}if(r=d.interleaved,r!==null){b=r;do k=b.lane,xn.lanes|=k,jo|=k,b=b.next;while(b!==r)}else b===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function kf(r){var a=di(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=r;var m=d.dispatch,b=d.pending,k=a.memoizedState;if(b!==null){d.pending=null;var F=b=b.next;do k=r(k,F.action),F=F.next;while(F!==b);Ni(k,a.memoizedState)||(Ws=!0),a.memoizedState=k,a.baseQueue===null&&(a.baseState=k),d.lastRenderedState=k}return[k,m]}function Py(){}function Dy(r,a){var d=xn,m=di(),b=a(),k=!Ni(m.memoizedState,b);if(k&&(m.memoizedState=b,Ws=!0),m=m.queue,Cf($y.bind(null,d,m,r),[r]),m.getSnapshot!==a||k||Qn!==null&&Qn.memoizedState.tag&1){if(d.flags|=2048,Bl(9,By.bind(null,d,m,b,a),void 0,null),Zn===null)throw Error(n(349));(No&30)!==0||Oy(d,a,b)}return b}function Oy(r,a,d){r.flags|=16384,r={getSnapshot:a,value:d},a=xn.updateQueue,a===null?(a={lastEffect:null,stores:null},xn.updateQueue=a,a.stores=[r]):(d=a.stores,d===null?a.stores=[r]:d.push(r))}function By(r,a,d,m){a.value=d,a.getSnapshot=m,zy(a)&&Fy(r)}function $y(r,a,d){return d(function(){zy(a)&&Fy(r)})}function zy(r){var a=r.getSnapshot;r=r.value;try{var d=a();return!Ni(r,d)}catch{return!0}}function Fy(r){var a=vr(r,1);a!==null&&Mi(a,r,1,-1)}function Hy(r){var a=Ui();return typeof r=="function"&&(r=r()),a.memoizedState=a.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ol,lastRenderedState:r},a.queue=r,r=r.dispatch=T2.bind(null,xn,r),[a.memoizedState,r]}function Bl(r,a,d,m){return r={tag:r,create:a,destroy:d,deps:m,next:null},a=xn.updateQueue,a===null?(a={lastEffect:null,stores:null},xn.updateQueue=a,a.lastEffect=r.next=r):(d=a.lastEffect,d===null?a.lastEffect=r.next=r:(m=d.next,d.next=r,r.next=m,a.lastEffect=r)),r}function Uy(){return di().memoizedState}function Lu(r,a,d,m){var b=Ui();xn.flags|=r,b.memoizedState=Bl(1|a,d,void 0,m===void 0?null:m)}function Ru(r,a,d,m){var b=di();m=m===void 0?null:m;var k=void 0;if(Un!==null){var F=Un.memoizedState;if(k=F.destroy,m!==null&&bf(m,F.deps)){b.memoizedState=Bl(a,d,k,m);return}}xn.flags|=r,b.memoizedState=Bl(1|a,d,k,m)}function Wy(r,a){return Lu(8390656,8,r,a)}function Cf(r,a){return Ru(2048,8,r,a)}function qy(r,a){return Ru(4,2,r,a)}function Ky(r,a){return Ru(4,4,r,a)}function Vy(r,a){if(typeof a=="function")return r=r(),a(r),function(){a(null)};if(a!=null)return r=r(),a.current=r,function(){a.current=null}}function Gy(r,a,d){return d=d!=null?d.concat([r]):null,Ru(4,4,Vy.bind(null,a,r),d)}function Ef(){}function Yy(r,a){var d=di();a=a===void 0?null:a;var m=d.memoizedState;return m!==null&&a!==null&&bf(a,m[1])?m[0]:(d.memoizedState=[r,a],r)}function Xy(r,a){var d=di();a=a===void 0?null:a;var m=d.memoizedState;return m!==null&&a!==null&&bf(a,m[1])?m[0]:(r=r(),d.memoizedState=[r,a],r)}function Jy(r,a,d){return(No&21)===0?(r.baseState&&(r.baseState=!1,Ws=!0),r.memoizedState=d):(Ni(d,a)||(d=Hn(),xn.lanes|=d,jo|=d,r.baseState=!0),a)}function A2(r,a){var d=Jt;Jt=d!==0&&4>d?d:4,r(!0);var m=yf.transition;yf.transition={};try{r(!1),a()}finally{Jt=d,yf.transition=m}}function Qy(){return di().memoizedState}function M2(r,a,d){var m=Kr(r);if(d={lane:m,action:d,hasEagerState:!1,eagerState:null,next:null},Zy(r))eb(a,d);else if(d=Ry(r,a,d,m),d!==null){var b=Ds();Mi(d,r,m,b),tb(d,a,m)}}function T2(r,a,d){var m=Kr(r),b={lane:m,action:d,hasEagerState:!1,eagerState:null,next:null};if(Zy(r))eb(a,b);else{var k=r.alternate;if(r.lanes===0&&(k===null||k.lanes===0)&&(k=a.lastRenderedReducer,k!==null))try{var F=a.lastRenderedState,ne=k(F,d);if(b.hasEagerState=!0,b.eagerState=ne,Ni(ne,F)){var de=a.interleaved;de===null?(b.next=b,ff(a)):(b.next=de.next,de.next=b),a.interleaved=b;return}}catch{}finally{}d=Ry(r,a,b,m),d!==null&&(b=Ds(),Mi(d,r,m,b),tb(d,a,m))}}function Zy(r){var a=r.alternate;return r===xn||a!==null&&a===xn}function eb(r,a){Pl=ju=!0;var d=r.pending;d===null?a.next=a:(a.next=d.next,d.next=a),r.pending=a}function tb(r,a,d){if((d&4194240)!==0){var m=a.lanes;m&=r.pendingLanes,d|=m,a.lanes=d,xi(r,d)}}var Au={readContext:ui,useCallback:Es,useContext:Es,useEffect:Es,useImperativeHandle:Es,useInsertionEffect:Es,useLayoutEffect:Es,useMemo:Es,useReducer:Es,useRef:Es,useState:Es,useDebugValue:Es,useDeferredValue:Es,useTransition:Es,useMutableSource:Es,useSyncExternalStore:Es,useId:Es,unstable_isNewReconciler:!1},I2={readContext:ui,useCallback:function(r,a){return Ui().memoizedState=[r,a===void 0?null:a],r},useContext:ui,useEffect:Wy,useImperativeHandle:function(r,a,d){return d=d!=null?d.concat([r]):null,Lu(4194308,4,Vy.bind(null,a,r),d)},useLayoutEffect:function(r,a){return Lu(4194308,4,r,a)},useInsertionEffect:function(r,a){return Lu(4,2,r,a)},useMemo:function(r,a){var d=Ui();return a=a===void 0?null:a,r=r(),d.memoizedState=[r,a],r},useReducer:function(r,a,d){var m=Ui();return a=d!==void 0?d(a):a,m.memoizedState=m.baseState=a,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:a},m.queue=r,r=r.dispatch=M2.bind(null,xn,r),[m.memoizedState,r]},useRef:function(r){var a=Ui();return r={current:r},a.memoizedState=r},useState:Hy,useDebugValue:Ef,useDeferredValue:function(r){return Ui().memoizedState=r},useTransition:function(){var r=Hy(!1),a=r[0];return r=A2.bind(null,r[1]),Ui().memoizedState=r,[a,r]},useMutableSource:function(){},useSyncExternalStore:function(r,a,d){var m=xn,b=Ui();if(_n){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),Zn===null)throw Error(n(349));(No&30)!==0||Oy(m,a,d)}b.memoizedState=d;var k={value:d,getSnapshot:a};return b.queue=k,Wy($y.bind(null,m,k,r),[r]),m.flags|=2048,Bl(9,By.bind(null,m,k,d,a),void 0,null),d},useId:function(){var r=Ui(),a=Zn.identifierPrefix;if(_n){var d=gr,m=mr;d=(m&~(1<<32-Pe(m)-1)).toString(32)+d,a=":"+a+"R"+d,d=Dl++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=R2++,a=":"+a+"r"+d.toString(32)+":";return r.memoizedState=a},unstable_isNewReconciler:!1},P2={readContext:ui,useCallback:Yy,useContext:ui,useEffect:Cf,useImperativeHandle:Gy,useInsertionEffect:qy,useLayoutEffect:Ky,useMemo:Xy,useReducer:xf,useRef:Uy,useState:function(){return xf(Ol)},useDebugValue:Ef,useDeferredValue:function(r){var a=di();return Jy(a,Un.memoizedState,r)},useTransition:function(){var r=xf(Ol)[0],a=di().memoizedState;return[r,a]},useMutableSource:Py,useSyncExternalStore:Dy,useId:Qy,unstable_isNewReconciler:!1},D2={readContext:ui,useCallback:Yy,useContext:ui,useEffect:Cf,useImperativeHandle:Gy,useInsertionEffect:qy,useLayoutEffect:Ky,useMemo:Xy,useReducer:kf,useRef:Uy,useState:function(){return kf(Ol)},useDebugValue:Ef,useDeferredValue:function(r){var a=di();return Un===null?a.memoizedState=r:Jy(a,Un.memoizedState,r)},useTransition:function(){var r=kf(Ol)[0],a=di().memoizedState;return[r,a]},useMutableSource:Py,useSyncExternalStore:Dy,useId:Qy,unstable_isNewReconciler:!1};function Li(r,a){if(r&&r.defaultProps){a=H({},a),r=r.defaultProps;for(var d in r)a[d]===void 0&&(a[d]=r[d]);return a}return a}function Nf(r,a,d,m){a=r.memoizedState,d=d(m,a),d=d==null?a:H({},a,d),r.memoizedState=d,r.lanes===0&&(r.updateQueue.baseState=d)}var Mu={isMounted:function(r){return(r=r._reactInternals)?Vt(r)===r:!1},enqueueSetState:function(r,a,d){r=r._reactInternals;var m=Ds(),b=Kr(r),k=_r(m,b);k.payload=a,d!=null&&(k.callback=d),a=Hr(r,k,b),a!==null&&(Mi(a,r,b,m),ku(a,r,b))},enqueueReplaceState:function(r,a,d){r=r._reactInternals;var m=Ds(),b=Kr(r),k=_r(m,b);k.tag=1,k.payload=a,d!=null&&(k.callback=d),a=Hr(r,k,b),a!==null&&(Mi(a,r,b,m),ku(a,r,b))},enqueueForceUpdate:function(r,a){r=r._reactInternals;var d=Ds(),m=Kr(r),b=_r(d,m);b.tag=2,a!=null&&(b.callback=a),a=Hr(r,b,m),a!==null&&(Mi(a,r,m,d),ku(a,r,m))}};function nb(r,a,d,m,b,k,F){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(m,k,F):a.prototype&&a.prototype.isPureReactComponent?!kl(d,m)||!kl(b,k):!0}function sb(r,a,d){var m=!1,b=$r,k=a.contextType;return typeof k=="object"&&k!==null?k=ui(k):(b=Us(a)?So:Cs.current,m=a.contextTypes,k=(m=m!=null)?ya(r,b):$r),a=new a(d,k),r.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Mu,r.stateNode=a,a._reactInternals=r,m&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=b,r.__reactInternalMemoizedMaskedChildContext=k),a}function ib(r,a,d,m){r=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(d,m),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(d,m),a.state!==r&&Mu.enqueueReplaceState(a,a.state,null)}function jf(r,a,d,m){var b=r.stateNode;b.props=d,b.state=r.memoizedState,b.refs={},pf(r);var k=a.contextType;typeof k=="object"&&k!==null?b.context=ui(k):(k=Us(a)?So:Cs.current,b.context=ya(r,k)),b.state=r.memoizedState,k=a.getDerivedStateFromProps,typeof k=="function"&&(Nf(r,a,k,d),b.state=r.memoizedState),typeof a.getDerivedStateFromProps=="function"||typeof b.getSnapshotBeforeUpdate=="function"||typeof b.UNSAFE_componentWillMount!="function"&&typeof b.componentWillMount!="function"||(a=b.state,typeof b.componentWillMount=="function"&&b.componentWillMount(),typeof b.UNSAFE_componentWillMount=="function"&&b.UNSAFE_componentWillMount(),a!==b.state&&Mu.enqueueReplaceState(b,b.state,null),Cu(r,d,b,m),b.state=r.memoizedState),typeof b.componentDidMount=="function"&&(r.flags|=4194308)}function Na(r,a){try{var d="",m=a;do d+=oe(m),m=m.return;while(m);var b=d}catch(k){b=`
39
+ Error generating stack: `+k.message+`
40
+ `+k.stack}return{value:r,source:a,stack:b,digest:null}}function Lf(r,a,d){return{value:r,source:null,stack:d??null,digest:a??null}}function Rf(r,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var O2=typeof WeakMap=="function"?WeakMap:Map;function rb(r,a,d){d=_r(-1,d),d.tag=3,d.payload={element:null};var m=a.value;return d.callback=function(){$u||($u=!0,qf=m),Rf(r,a)},d}function ob(r,a,d){d=_r(-1,d),d.tag=3;var m=r.type.getDerivedStateFromError;if(typeof m=="function"){var b=a.value;d.payload=function(){return m(b)},d.callback=function(){Rf(r,a)}}var k=r.stateNode;return k!==null&&typeof k.componentDidCatch=="function"&&(d.callback=function(){Rf(r,a),typeof m!="function"&&(Wr===null?Wr=new Set([this]):Wr.add(this));var F=a.stack;this.componentDidCatch(a.value,{componentStack:F!==null?F:""})}),d}function ab(r,a,d){var m=r.pingCache;if(m===null){m=r.pingCache=new O2;var b=new Set;m.set(a,b)}else b=m.get(a),b===void 0&&(b=new Set,m.set(a,b));b.has(d)||(b.add(d),r=J2.bind(null,r,a,d),a.then(r,r))}function lb(r){do{var a;if((a=r.tag===13)&&(a=r.memoizedState,a=a!==null?a.dehydrated!==null:!0),a)return r;r=r.return}while(r!==null);return null}function cb(r,a,d,m,b){return(r.mode&1)===0?(r===a?r.flags|=65536:(r.flags|=128,d.flags|=131072,d.flags&=-52805,d.tag===1&&(d.alternate===null?d.tag=17:(a=_r(-1,1),a.tag=2,Hr(d,a,1))),d.lanes|=1),r):(r.flags|=65536,r.lanes=b,r)}var B2=x.ReactCurrentOwner,Ws=!1;function Ps(r,a,d,m){a.child=r===null?Ly(a,null,d,m):xa(a,r.child,d,m)}function ub(r,a,d,m,b){d=d.render;var k=a.ref;return Ca(a,b),m=wf(r,a,d,m,k,b),d=Sf(),r!==null&&!Ws?(a.updateQueue=r.updateQueue,a.flags&=-2053,r.lanes&=~b,yr(r,a,b)):(_n&&d&&sf(a),a.flags|=1,Ps(r,a,m,b),a.child)}function db(r,a,d,m,b){if(r===null){var k=d.type;return typeof k=="function"&&!Qf(k)&&k.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=k,hb(r,a,k,m,b)):(r=qu(d.type,null,m,a,a.mode,b),r.ref=a.ref,r.return=a,a.child=r)}if(k=r.child,(r.lanes&b)===0){var F=k.memoizedProps;if(d=d.compare,d=d!==null?d:kl,d(F,m)&&r.ref===a.ref)return yr(r,a,b)}return a.flags|=1,r=Gr(k,m),r.ref=a.ref,r.return=a,a.child=r}function hb(r,a,d,m,b){if(r!==null){var k=r.memoizedProps;if(kl(k,m)&&r.ref===a.ref)if(Ws=!1,a.pendingProps=m=k,(r.lanes&b)!==0)(r.flags&131072)!==0&&(Ws=!0);else return a.lanes=r.lanes,yr(r,a,b)}return Af(r,a,d,m,b)}function fb(r,a,d){var m=a.pendingProps,b=m.children,k=r!==null?r.memoizedState:null;if(m.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},ln(La,ni),ni|=d;else{if((d&1073741824)===0)return r=k!==null?k.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:r,cachePool:null,transitions:null},a.updateQueue=null,ln(La,ni),ni|=r,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},m=k!==null?k.baseLanes:d,ln(La,ni),ni|=m}else k!==null?(m=k.baseLanes|d,a.memoizedState=null):m=d,ln(La,ni),ni|=m;return Ps(r,a,b,d),a.child}function pb(r,a){var d=a.ref;(r===null&&d!==null||r!==null&&r.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Af(r,a,d,m,b){var k=Us(d)?So:Cs.current;return k=ya(a,k),Ca(a,b),d=wf(r,a,d,m,k,b),m=Sf(),r!==null&&!Ws?(a.updateQueue=r.updateQueue,a.flags&=-2053,r.lanes&=~b,yr(r,a,b)):(_n&&m&&sf(a),a.flags|=1,Ps(r,a,d,b),a.child)}function mb(r,a,d,m,b){if(Us(d)){var k=!0;gu(a)}else k=!1;if(Ca(a,b),a.stateNode===null)Iu(r,a),sb(a,d,m),jf(a,d,m,b),m=!0;else if(r===null){var F=a.stateNode,ne=a.memoizedProps;F.props=ne;var de=F.context,Ne=d.contextType;typeof Ne=="object"&&Ne!==null?Ne=ui(Ne):(Ne=Us(d)?So:Cs.current,Ne=ya(a,Ne));var qe=d.getDerivedStateFromProps,Ge=typeof qe=="function"||typeof F.getSnapshotBeforeUpdate=="function";Ge||typeof F.UNSAFE_componentWillReceiveProps!="function"&&typeof F.componentWillReceiveProps!="function"||(ne!==m||de!==Ne)&&ib(a,F,m,Ne),Fr=!1;var Ue=a.memoizedState;F.state=Ue,Cu(a,m,F,b),de=a.memoizedState,ne!==m||Ue!==de||Hs.current||Fr?(typeof qe=="function"&&(Nf(a,d,qe,m),de=a.memoizedState),(ne=Fr||nb(a,d,ne,m,Ue,de,Ne))?(Ge||typeof F.UNSAFE_componentWillMount!="function"&&typeof F.componentWillMount!="function"||(typeof F.componentWillMount=="function"&&F.componentWillMount(),typeof F.UNSAFE_componentWillMount=="function"&&F.UNSAFE_componentWillMount()),typeof F.componentDidMount=="function"&&(a.flags|=4194308)):(typeof F.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=m,a.memoizedState=de),F.props=m,F.state=de,F.context=Ne,m=ne):(typeof F.componentDidMount=="function"&&(a.flags|=4194308),m=!1)}else{F=a.stateNode,Ay(r,a),ne=a.memoizedProps,Ne=a.type===a.elementType?ne:Li(a.type,ne),F.props=Ne,Ge=a.pendingProps,Ue=F.context,de=d.contextType,typeof de=="object"&&de!==null?de=ui(de):(de=Us(d)?So:Cs.current,de=ya(a,de));var ht=d.getDerivedStateFromProps;(qe=typeof ht=="function"||typeof F.getSnapshotBeforeUpdate=="function")||typeof F.UNSAFE_componentWillReceiveProps!="function"&&typeof F.componentWillReceiveProps!="function"||(ne!==Ge||Ue!==de)&&ib(a,F,m,de),Fr=!1,Ue=a.memoizedState,F.state=Ue,Cu(a,m,F,b);var _t=a.memoizedState;ne!==Ge||Ue!==_t||Hs.current||Fr?(typeof ht=="function"&&(Nf(a,d,ht,m),_t=a.memoizedState),(Ne=Fr||nb(a,d,Ne,m,Ue,_t,de)||!1)?(qe||typeof F.UNSAFE_componentWillUpdate!="function"&&typeof F.componentWillUpdate!="function"||(typeof F.componentWillUpdate=="function"&&F.componentWillUpdate(m,_t,de),typeof F.UNSAFE_componentWillUpdate=="function"&&F.UNSAFE_componentWillUpdate(m,_t,de)),typeof F.componentDidUpdate=="function"&&(a.flags|=4),typeof F.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof F.componentDidUpdate!="function"||ne===r.memoizedProps&&Ue===r.memoizedState||(a.flags|=4),typeof F.getSnapshotBeforeUpdate!="function"||ne===r.memoizedProps&&Ue===r.memoizedState||(a.flags|=1024),a.memoizedProps=m,a.memoizedState=_t),F.props=m,F.state=_t,F.context=de,m=Ne):(typeof F.componentDidUpdate!="function"||ne===r.memoizedProps&&Ue===r.memoizedState||(a.flags|=4),typeof F.getSnapshotBeforeUpdate!="function"||ne===r.memoizedProps&&Ue===r.memoizedState||(a.flags|=1024),m=!1)}return Mf(r,a,d,m,k,b)}function Mf(r,a,d,m,b,k){pb(r,a);var F=(a.flags&128)!==0;if(!m&&!F)return b&&by(a,d,!1),yr(r,a,k);m=a.stateNode,B2.current=a;var ne=F&&typeof d.getDerivedStateFromError!="function"?null:m.render();return a.flags|=1,r!==null&&F?(a.child=xa(a,r.child,null,k),a.child=xa(a,null,ne,k)):Ps(r,a,ne,k),a.memoizedState=m.state,b&&by(a,d,!0),a.child}function gb(r){var a=r.stateNode;a.pendingContext?_y(r,a.pendingContext,a.pendingContext!==a.context):a.context&&_y(r,a.context,!1),mf(r,a.containerInfo)}function vb(r,a,d,m,b){return Sa(),lf(b),a.flags|=256,Ps(r,a,d,m),a.child}var Tf={dehydrated:null,treeContext:null,retryLane:0};function If(r){return{baseLanes:r,cachePool:null,transitions:null}}function _b(r,a,d){var m=a.pendingProps,b=Sn.current,k=!1,F=(a.flags&128)!==0,ne;if((ne=F)||(ne=r!==null&&r.memoizedState===null?!1:(b&2)!==0),ne?(k=!0,a.flags&=-129):(r===null||r.memoizedState!==null)&&(b|=1),ln(Sn,b&1),r===null)return af(a),r=a.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?((a.mode&1)===0?a.lanes=1:r.data==="$!"?a.lanes=8:a.lanes=1073741824,null):(F=m.children,r=m.fallback,k?(m=a.mode,k=a.child,F={mode:"hidden",children:F},(m&1)===0&&k!==null?(k.childLanes=0,k.pendingProps=F):k=Ku(F,m,0,null),r=Mo(r,m,d,null),k.return=a,r.return=a,k.sibling=r,a.child=k,a.child.memoizedState=If(d),a.memoizedState=Tf,r):Pf(a,F));if(b=r.memoizedState,b!==null&&(ne=b.dehydrated,ne!==null))return $2(r,a,F,m,ne,b,d);if(k){k=m.fallback,F=a.mode,b=r.child,ne=b.sibling;var de={mode:"hidden",children:m.children};return(F&1)===0&&a.child!==b?(m=a.child,m.childLanes=0,m.pendingProps=de,a.deletions=null):(m=Gr(b,de),m.subtreeFlags=b.subtreeFlags&14680064),ne!==null?k=Gr(ne,k):(k=Mo(k,F,d,null),k.flags|=2),k.return=a,m.return=a,m.sibling=k,a.child=m,m=k,k=a.child,F=r.child.memoizedState,F=F===null?If(d):{baseLanes:F.baseLanes|d,cachePool:null,transitions:F.transitions},k.memoizedState=F,k.childLanes=r.childLanes&~d,a.memoizedState=Tf,m}return k=r.child,r=k.sibling,m=Gr(k,{mode:"visible",children:m.children}),(a.mode&1)===0&&(m.lanes=d),m.return=a,m.sibling=null,r!==null&&(d=a.deletions,d===null?(a.deletions=[r],a.flags|=16):d.push(r)),a.child=m,a.memoizedState=null,m}function Pf(r,a){return a=Ku({mode:"visible",children:a},r.mode,0,null),a.return=r,r.child=a}function Tu(r,a,d,m){return m!==null&&lf(m),xa(a,r.child,null,d),r=Pf(a,a.pendingProps.children),r.flags|=2,a.memoizedState=null,r}function $2(r,a,d,m,b,k,F){if(d)return a.flags&256?(a.flags&=-257,m=Lf(Error(n(422))),Tu(r,a,F,m)):a.memoizedState!==null?(a.child=r.child,a.flags|=128,null):(k=m.fallback,b=a.mode,m=Ku({mode:"visible",children:m.children},b,0,null),k=Mo(k,b,F,null),k.flags|=2,m.return=a,k.return=a,m.sibling=k,a.child=m,(a.mode&1)!==0&&xa(a,r.child,null,F),a.child.memoizedState=If(F),a.memoizedState=Tf,k);if((a.mode&1)===0)return Tu(r,a,F,null);if(b.data==="$!"){if(m=b.nextSibling&&b.nextSibling.dataset,m)var ne=m.dgst;return m=ne,k=Error(n(419)),m=Lf(k,m,void 0),Tu(r,a,F,m)}if(ne=(F&r.childLanes)!==0,Ws||ne){if(m=Zn,m!==null){switch(F&-F){case 4:b=2;break;case 16:b=8;break;case 64: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:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:b=32;break;case 536870912:b=268435456;break;default:b=0}b=(b&(m.suspendedLanes|F))!==0?0:b,b!==0&&b!==k.retryLane&&(k.retryLane=b,vr(r,b),Mi(m,r,b,-1))}return Jf(),m=Lf(Error(n(421))),Tu(r,a,F,m)}return b.data==="$?"?(a.flags|=128,a.child=r.child,a=Q2.bind(null,r),b._reactRetry=a,null):(r=k.treeContext,ti=Or(b.nextSibling),ei=a,_n=!0,ji=null,r!==null&&(li[ci++]=mr,li[ci++]=gr,li[ci++]=xo,mr=r.id,gr=r.overflow,xo=a),a=Pf(a,m.children),a.flags|=4096,a)}function yb(r,a,d){r.lanes|=a;var m=r.alternate;m!==null&&(m.lanes|=a),hf(r.return,a,d)}function Df(r,a,d,m,b){var k=r.memoizedState;k===null?r.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:m,tail:d,tailMode:b}:(k.isBackwards=a,k.rendering=null,k.renderingStartTime=0,k.last=m,k.tail=d,k.tailMode=b)}function bb(r,a,d){var m=a.pendingProps,b=m.revealOrder,k=m.tail;if(Ps(r,a,m.children,d),m=Sn.current,(m&2)!==0)m=m&1|2,a.flags|=128;else{if(r!==null&&(r.flags&128)!==0)e:for(r=a.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&yb(r,d,a);else if(r.tag===19)yb(r,d,a);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===a)break e;for(;r.sibling===null;){if(r.return===null||r.return===a)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}m&=1}if(ln(Sn,m),(a.mode&1)===0)a.memoizedState=null;else switch(b){case"forwards":for(d=a.child,b=null;d!==null;)r=d.alternate,r!==null&&Eu(r)===null&&(b=d),d=d.sibling;d=b,d===null?(b=a.child,a.child=null):(b=d.sibling,d.sibling=null),Df(a,!1,b,d,k);break;case"backwards":for(d=null,b=a.child,a.child=null;b!==null;){if(r=b.alternate,r!==null&&Eu(r)===null){a.child=b;break}r=b.sibling,b.sibling=d,d=b,b=r}Df(a,!0,d,null,k);break;case"together":Df(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Iu(r,a){(a.mode&1)===0&&r!==null&&(r.alternate=null,a.alternate=null,a.flags|=2)}function yr(r,a,d){if(r!==null&&(a.dependencies=r.dependencies),jo|=a.lanes,(d&a.childLanes)===0)return null;if(r!==null&&a.child!==r.child)throw Error(n(153));if(a.child!==null){for(r=a.child,d=Gr(r,r.pendingProps),a.child=d,d.return=a;r.sibling!==null;)r=r.sibling,d=d.sibling=Gr(r,r.pendingProps),d.return=a;d.sibling=null}return a.child}function z2(r,a,d){switch(a.tag){case 3:gb(a),Sa();break;case 5:Iy(a);break;case 1:Us(a.type)&&gu(a);break;case 4:mf(a,a.stateNode.containerInfo);break;case 10:var m=a.type._context,b=a.memoizedProps.value;ln(Su,m._currentValue),m._currentValue=b;break;case 13:if(m=a.memoizedState,m!==null)return m.dehydrated!==null?(ln(Sn,Sn.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?_b(r,a,d):(ln(Sn,Sn.current&1),r=yr(r,a,d),r!==null?r.sibling:null);ln(Sn,Sn.current&1);break;case 19:if(m=(d&a.childLanes)!==0,(r.flags&128)!==0){if(m)return bb(r,a,d);a.flags|=128}if(b=a.memoizedState,b!==null&&(b.rendering=null,b.tail=null,b.lastEffect=null),ln(Sn,Sn.current),m)break;return null;case 22:case 23:return a.lanes=0,fb(r,a,d)}return yr(r,a,d)}var wb,Of,Sb,xb;wb=function(r,a){for(var d=a.child;d!==null;){if(d.tag===5||d.tag===6)r.appendChild(d.stateNode);else if(d.tag!==4&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===a)break;for(;d.sibling===null;){if(d.return===null||d.return===a)return;d=d.return}d.sibling.return=d.return,d=d.sibling}},Of=function(){},Sb=function(r,a,d,m){var b=r.memoizedProps;if(b!==m){r=a.stateNode,Eo(Hi.current);var k=null;switch(d){case"input":b=J(r,b),m=J(r,m),k=[];break;case"select":b=H({},b,{value:void 0}),m=H({},m,{value:void 0}),k=[];break;case"textarea":b=Ve(r,b),m=Ve(r,m),k=[];break;default:typeof b.onClick!="function"&&typeof m.onClick=="function"&&(r.onclick=fu)}Re(d,m);var F;d=null;for(Ne in b)if(!m.hasOwnProperty(Ne)&&b.hasOwnProperty(Ne)&&b[Ne]!=null)if(Ne==="style"){var ne=b[Ne];for(F in ne)ne.hasOwnProperty(F)&&(d||(d={}),d[F]="")}else Ne!=="dangerouslySetInnerHTML"&&Ne!=="children"&&Ne!=="suppressContentEditableWarning"&&Ne!=="suppressHydrationWarning"&&Ne!=="autoFocus"&&(i.hasOwnProperty(Ne)?k||(k=[]):(k=k||[]).push(Ne,null));for(Ne in m){var de=m[Ne];if(ne=b!=null?b[Ne]:void 0,m.hasOwnProperty(Ne)&&de!==ne&&(de!=null||ne!=null))if(Ne==="style")if(ne){for(F in ne)!ne.hasOwnProperty(F)||de&&de.hasOwnProperty(F)||(d||(d={}),d[F]="");for(F in de)de.hasOwnProperty(F)&&ne[F]!==de[F]&&(d||(d={}),d[F]=de[F])}else d||(k||(k=[]),k.push(Ne,d)),d=de;else Ne==="dangerouslySetInnerHTML"?(de=de?de.__html:void 0,ne=ne?ne.__html:void 0,de!=null&&ne!==de&&(k=k||[]).push(Ne,de)):Ne==="children"?typeof de!="string"&&typeof de!="number"||(k=k||[]).push(Ne,""+de):Ne!=="suppressContentEditableWarning"&&Ne!=="suppressHydrationWarning"&&(i.hasOwnProperty(Ne)?(de!=null&&Ne==="onScroll"&&fn("scroll",r),k||ne===de||(k=[])):(k=k||[]).push(Ne,de))}d&&(k=k||[]).push("style",d);var Ne=k;(a.updateQueue=Ne)&&(a.flags|=4)}},xb=function(r,a,d,m){d!==m&&(a.flags|=4)};function $l(r,a){if(!_n)switch(r.tailMode){case"hidden":a=r.tail;for(var d=null;a!==null;)a.alternate!==null&&(d=a),a=a.sibling;d===null?r.tail=null:d.sibling=null;break;case"collapsed":d=r.tail;for(var m=null;d!==null;)d.alternate!==null&&(m=d),d=d.sibling;m===null?a||r.tail===null?r.tail=null:r.tail.sibling=null:m.sibling=null}}function Ns(r){var a=r.alternate!==null&&r.alternate.child===r.child,d=0,m=0;if(a)for(var b=r.child;b!==null;)d|=b.lanes|b.childLanes,m|=b.subtreeFlags&14680064,m|=b.flags&14680064,b.return=r,b=b.sibling;else for(b=r.child;b!==null;)d|=b.lanes|b.childLanes,m|=b.subtreeFlags,m|=b.flags,b.return=r,b=b.sibling;return r.subtreeFlags|=m,r.childLanes=d,a}function F2(r,a,d){var m=a.pendingProps;switch(rf(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ns(a),null;case 1:return Us(a.type)&&mu(),Ns(a),null;case 3:return m=a.stateNode,Ea(),pn(Hs),pn(Cs),_f(),m.pendingContext&&(m.context=m.pendingContext,m.pendingContext=null),(r===null||r.child===null)&&(bu(a)?a.flags|=4:r===null||r.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,ji!==null&&(Gf(ji),ji=null))),Of(r,a),Ns(a),null;case 5:gf(a);var b=Eo(Il.current);if(d=a.type,r!==null&&a.stateNode!=null)Sb(r,a,d,m,b),r.ref!==a.ref&&(a.flags|=512,a.flags|=2097152);else{if(!m){if(a.stateNode===null)throw Error(n(166));return Ns(a),null}if(r=Eo(Hi.current),bu(a)){m=a.stateNode,d=a.type;var k=a.memoizedProps;switch(m[Fi]=a,m[Ll]=k,r=(a.mode&1)!==0,d){case"dialog":fn("cancel",m),fn("close",m);break;case"iframe":case"object":case"embed":fn("load",m);break;case"video":case"audio":for(b=0;b<El.length;b++)fn(El[b],m);break;case"source":fn("error",m);break;case"img":case"image":case"link":fn("error",m),fn("load",m);break;case"details":fn("toggle",m);break;case"input":le(m,k),fn("invalid",m);break;case"select":m._wrapperState={wasMultiple:!!k.multiple},fn("invalid",m);break;case"textarea":ot(m,k),fn("invalid",m)}Re(d,k),b=null;for(var F in k)if(k.hasOwnProperty(F)){var ne=k[F];F==="children"?typeof ne=="string"?m.textContent!==ne&&(k.suppressHydrationWarning!==!0&&hu(m.textContent,ne,r),b=["children",ne]):typeof ne=="number"&&m.textContent!==""+ne&&(k.suppressHydrationWarning!==!0&&hu(m.textContent,ne,r),b=["children",""+ne]):i.hasOwnProperty(F)&&ne!=null&&F==="onScroll"&&fn("scroll",m)}switch(d){case"input":Be(m),Z(m,k,!0);break;case"textarea":Be(m),$e(m);break;case"select":case"option":break;default:typeof k.onClick=="function"&&(m.onclick=fu)}m=b,a.updateQueue=m,m!==null&&(a.flags|=4)}else{F=b.nodeType===9?b:b.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=_e(d)),r==="http://www.w3.org/1999/xhtml"?d==="script"?(r=F.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof m.is=="string"?r=F.createElement(d,{is:m.is}):(r=F.createElement(d),d==="select"&&(F=r,m.multiple?F.multiple=!0:m.size&&(F.size=m.size))):r=F.createElementNS(r,d),r[Fi]=a,r[Ll]=m,wb(r,a,!1,!1),a.stateNode=r;e:{switch(F=ae(d,m),d){case"dialog":fn("cancel",r),fn("close",r),b=m;break;case"iframe":case"object":case"embed":fn("load",r),b=m;break;case"video":case"audio":for(b=0;b<El.length;b++)fn(El[b],r);b=m;break;case"source":fn("error",r),b=m;break;case"img":case"image":case"link":fn("error",r),fn("load",r),b=m;break;case"details":fn("toggle",r),b=m;break;case"input":le(r,m),b=J(r,m),fn("invalid",r);break;case"option":b=m;break;case"select":r._wrapperState={wasMultiple:!!m.multiple},b=H({},m,{value:void 0}),fn("invalid",r);break;case"textarea":ot(r,m),b=Ve(r,m),fn("invalid",r);break;default:b=m}Re(d,b),ne=b;for(k in ne)if(ne.hasOwnProperty(k)){var de=ne[k];k==="style"?ce(r,de):k==="dangerouslySetInnerHTML"?(de=de?de.__html:void 0,de!=null&&He(r,de)):k==="children"?typeof de=="string"?(d!=="textarea"||de!=="")&&nt(r,de):typeof de=="number"&&nt(r,""+de):k!=="suppressContentEditableWarning"&&k!=="suppressHydrationWarning"&&k!=="autoFocus"&&(i.hasOwnProperty(k)?de!=null&&k==="onScroll"&&fn("scroll",r):de!=null&&R(r,k,de,F))}switch(d){case"input":Be(r),Z(r,m,!1);break;case"textarea":Be(r),$e(r);break;case"option":m.value!=null&&r.setAttribute("value",""+ie(m.value));break;case"select":r.multiple=!!m.multiple,k=m.value,k!=null?ke(r,!!m.multiple,k,!1):m.defaultValue!=null&&ke(r,!!m.multiple,m.defaultValue,!0);break;default:typeof b.onClick=="function"&&(r.onclick=fu)}switch(d){case"button":case"input":case"select":case"textarea":m=!!m.autoFocus;break e;case"img":m=!0;break e;default:m=!1}}m&&(a.flags|=4)}a.ref!==null&&(a.flags|=512,a.flags|=2097152)}return Ns(a),null;case 6:if(r&&a.stateNode!=null)xb(r,a,r.memoizedProps,m);else{if(typeof m!="string"&&a.stateNode===null)throw Error(n(166));if(d=Eo(Il.current),Eo(Hi.current),bu(a)){if(m=a.stateNode,d=a.memoizedProps,m[Fi]=a,(k=m.nodeValue!==d)&&(r=ei,r!==null))switch(r.tag){case 3:hu(m.nodeValue,d,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&hu(m.nodeValue,d,(r.mode&1)!==0)}k&&(a.flags|=4)}else m=(d.nodeType===9?d:d.ownerDocument).createTextNode(m),m[Fi]=a,a.stateNode=m}return Ns(a),null;case 13:if(pn(Sn),m=a.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(_n&&ti!==null&&(a.mode&1)!==0&&(a.flags&128)===0)Ey(),Sa(),a.flags|=98560,k=!1;else if(k=bu(a),m!==null&&m.dehydrated!==null){if(r===null){if(!k)throw Error(n(318));if(k=a.memoizedState,k=k!==null?k.dehydrated:null,!k)throw Error(n(317));k[Fi]=a}else Sa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ns(a),k=!1}else ji!==null&&(Gf(ji),ji=null),k=!0;if(!k)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=d,a):(m=m!==null,m!==(r!==null&&r.memoizedState!==null)&&m&&(a.child.flags|=8192,(a.mode&1)!==0&&(r===null||(Sn.current&1)!==0?Wn===0&&(Wn=3):Jf())),a.updateQueue!==null&&(a.flags|=4),Ns(a),null);case 4:return Ea(),Of(r,a),r===null&&Nl(a.stateNode.containerInfo),Ns(a),null;case 10:return df(a.type._context),Ns(a),null;case 17:return Us(a.type)&&mu(),Ns(a),null;case 19:if(pn(Sn),k=a.memoizedState,k===null)return Ns(a),null;if(m=(a.flags&128)!==0,F=k.rendering,F===null)if(m)$l(k,!1);else{if(Wn!==0||r!==null&&(r.flags&128)!==0)for(r=a.child;r!==null;){if(F=Eu(r),F!==null){for(a.flags|=128,$l(k,!1),m=F.updateQueue,m!==null&&(a.updateQueue=m,a.flags|=4),a.subtreeFlags=0,m=d,d=a.child;d!==null;)k=d,r=m,k.flags&=14680066,F=k.alternate,F===null?(k.childLanes=0,k.lanes=r,k.child=null,k.subtreeFlags=0,k.memoizedProps=null,k.memoizedState=null,k.updateQueue=null,k.dependencies=null,k.stateNode=null):(k.childLanes=F.childLanes,k.lanes=F.lanes,k.child=F.child,k.subtreeFlags=0,k.deletions=null,k.memoizedProps=F.memoizedProps,k.memoizedState=F.memoizedState,k.updateQueue=F.updateQueue,k.type=F.type,r=F.dependencies,k.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),d=d.sibling;return ln(Sn,Sn.current&1|2),a.child}r=r.sibling}k.tail!==null&&G()>Ra&&(a.flags|=128,m=!0,$l(k,!1),a.lanes=4194304)}else{if(!m)if(r=Eu(F),r!==null){if(a.flags|=128,m=!0,d=r.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),$l(k,!0),k.tail===null&&k.tailMode==="hidden"&&!F.alternate&&!_n)return Ns(a),null}else 2*G()-k.renderingStartTime>Ra&&d!==1073741824&&(a.flags|=128,m=!0,$l(k,!1),a.lanes=4194304);k.isBackwards?(F.sibling=a.child,a.child=F):(d=k.last,d!==null?d.sibling=F:a.child=F,k.last=F)}return k.tail!==null?(a=k.tail,k.rendering=a,k.tail=a.sibling,k.renderingStartTime=G(),a.sibling=null,d=Sn.current,ln(Sn,m?d&1|2:d&1),a):(Ns(a),null);case 22:case 23:return Xf(),m=a.memoizedState!==null,r!==null&&r.memoizedState!==null!==m&&(a.flags|=8192),m&&(a.mode&1)!==0?(ni&1073741824)!==0&&(Ns(a),a.subtreeFlags&6&&(a.flags|=8192)):Ns(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function H2(r,a){switch(rf(a),a.tag){case 1:return Us(a.type)&&mu(),r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 3:return Ea(),pn(Hs),pn(Cs),_f(),r=a.flags,(r&65536)!==0&&(r&128)===0?(a.flags=r&-65537|128,a):null;case 5:return gf(a),null;case 13:if(pn(Sn),r=a.memoizedState,r!==null&&r.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Sa()}return r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 19:return pn(Sn),null;case 4:return Ea(),null;case 10:return df(a.type._context),null;case 22:case 23:return Xf(),null;case 24:return null;default:return null}}var Pu=!1,js=!1,U2=typeof WeakSet=="function"?WeakSet:Set,mt=null;function ja(r,a){var d=r.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(m){jn(r,a,m)}else d.current=null}function Bf(r,a,d){try{d()}catch(m){jn(r,a,m)}}var kb=!1;function W2(r,a){if(Yh=hr,r=ny(),Fh(r)){if("selectionStart"in r)var d={start:r.selectionStart,end:r.selectionEnd};else e:{d=(d=r.ownerDocument)&&d.defaultView||window;var m=d.getSelection&&d.getSelection();if(m&&m.rangeCount!==0){d=m.anchorNode;var b=m.anchorOffset,k=m.focusNode;m=m.focusOffset;try{d.nodeType,k.nodeType}catch{d=null;break e}var F=0,ne=-1,de=-1,Ne=0,qe=0,Ge=r,Ue=null;t:for(;;){for(var ht;Ge!==d||b!==0&&Ge.nodeType!==3||(ne=F+b),Ge!==k||m!==0&&Ge.nodeType!==3||(de=F+m),Ge.nodeType===3&&(F+=Ge.nodeValue.length),(ht=Ge.firstChild)!==null;)Ue=Ge,Ge=ht;for(;;){if(Ge===r)break t;if(Ue===d&&++Ne===b&&(ne=F),Ue===k&&++qe===m&&(de=F),(ht=Ge.nextSibling)!==null)break;Ge=Ue,Ue=Ge.parentNode}Ge=ht}d=ne===-1||de===-1?null:{start:ne,end:de}}else d=null}d=d||{start:0,end:0}}else d=null;for(Xh={focusedElem:r,selectionRange:d},hr=!1,mt=a;mt!==null;)if(a=mt,r=a.child,(a.subtreeFlags&1028)!==0&&r!==null)r.return=a,mt=r;else for(;mt!==null;){a=mt;try{var _t=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(_t!==null){var bt=_t.memoizedProps,In=_t.memoizedState,Se=a.stateNode,me=Se.getSnapshotBeforeUpdate(a.elementType===a.type?bt:Li(a.type,bt),In);Se.__reactInternalSnapshotBeforeUpdate=me}break;case 3:var Ce=a.stateNode.containerInfo;Ce.nodeType===1?Ce.textContent="":Ce.nodeType===9&&Ce.documentElement&&Ce.removeChild(Ce.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(et){jn(a,a.return,et)}if(r=a.sibling,r!==null){r.return=a.return,mt=r;break}mt=a.return}return _t=kb,kb=!1,_t}function zl(r,a,d){var m=a.updateQueue;if(m=m!==null?m.lastEffect:null,m!==null){var b=m=m.next;do{if((b.tag&r)===r){var k=b.destroy;b.destroy=void 0,k!==void 0&&Bf(a,d,k)}b=b.next}while(b!==m)}}function Du(r,a){if(a=a.updateQueue,a=a!==null?a.lastEffect:null,a!==null){var d=a=a.next;do{if((d.tag&r)===r){var m=d.create;d.destroy=m()}d=d.next}while(d!==a)}}function $f(r){var a=r.ref;if(a!==null){var d=r.stateNode;switch(r.tag){case 5:r=d;break;default:r=d}typeof a=="function"?a(r):a.current=r}}function Cb(r){var a=r.alternate;a!==null&&(r.alternate=null,Cb(a)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(a=r.stateNode,a!==null&&(delete a[Fi],delete a[Ll],delete a[ef],delete a[E2],delete a[N2])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function Eb(r){return r.tag===5||r.tag===3||r.tag===4}function Nb(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||Eb(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function zf(r,a,d){var m=r.tag;if(m===5||m===6)r=r.stateNode,a?d.nodeType===8?d.parentNode.insertBefore(r,a):d.insertBefore(r,a):(d.nodeType===8?(a=d.parentNode,a.insertBefore(r,d)):(a=d,a.appendChild(r)),d=d._reactRootContainer,d!=null||a.onclick!==null||(a.onclick=fu));else if(m!==4&&(r=r.child,r!==null))for(zf(r,a,d),r=r.sibling;r!==null;)zf(r,a,d),r=r.sibling}function Ff(r,a,d){var m=r.tag;if(m===5||m===6)r=r.stateNode,a?d.insertBefore(r,a):d.appendChild(r);else if(m!==4&&(r=r.child,r!==null))for(Ff(r,a,d),r=r.sibling;r!==null;)Ff(r,a,d),r=r.sibling}var fs=null,Ri=!1;function Ur(r,a,d){for(d=d.child;d!==null;)jb(r,a,d),d=d.sibling}function jb(r,a,d){if(Ee&&typeof Ee.onCommitFiberUnmount=="function")try{Ee.onCommitFiberUnmount(Ze,d)}catch{}switch(d.tag){case 5:js||ja(d,a);case 6:var m=fs,b=Ri;fs=null,Ur(r,a,d),fs=m,Ri=b,fs!==null&&(Ri?(r=fs,d=d.stateNode,r.nodeType===8?r.parentNode.removeChild(d):r.removeChild(d)):fs.removeChild(d.stateNode));break;case 18:fs!==null&&(Ri?(r=fs,d=d.stateNode,r.nodeType===8?Zh(r.parentNode,d):r.nodeType===1&&Zh(r,d),zi(r)):Zh(fs,d.stateNode));break;case 4:m=fs,b=Ri,fs=d.stateNode.containerInfo,Ri=!0,Ur(r,a,d),fs=m,Ri=b;break;case 0:case 11:case 14:case 15:if(!js&&(m=d.updateQueue,m!==null&&(m=m.lastEffect,m!==null))){b=m=m.next;do{var k=b,F=k.destroy;k=k.tag,F!==void 0&&((k&2)!==0||(k&4)!==0)&&Bf(d,a,F),b=b.next}while(b!==m)}Ur(r,a,d);break;case 1:if(!js&&(ja(d,a),m=d.stateNode,typeof m.componentWillUnmount=="function"))try{m.props=d.memoizedProps,m.state=d.memoizedState,m.componentWillUnmount()}catch(ne){jn(d,a,ne)}Ur(r,a,d);break;case 21:Ur(r,a,d);break;case 22:d.mode&1?(js=(m=js)||d.memoizedState!==null,Ur(r,a,d),js=m):Ur(r,a,d);break;default:Ur(r,a,d)}}function Lb(r){var a=r.updateQueue;if(a!==null){r.updateQueue=null;var d=r.stateNode;d===null&&(d=r.stateNode=new U2),a.forEach(function(m){var b=Z2.bind(null,r,m);d.has(m)||(d.add(m),m.then(b,b))})}}function Ai(r,a){var d=a.deletions;if(d!==null)for(var m=0;m<d.length;m++){var b=d[m];try{var k=r,F=a,ne=F;e:for(;ne!==null;){switch(ne.tag){case 5:fs=ne.stateNode,Ri=!1;break e;case 3:fs=ne.stateNode.containerInfo,Ri=!0;break e;case 4:fs=ne.stateNode.containerInfo,Ri=!0;break e}ne=ne.return}if(fs===null)throw Error(n(160));jb(k,F,b),fs=null,Ri=!1;var de=b.alternate;de!==null&&(de.return=null),b.return=null}catch(Ne){jn(b,a,Ne)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)Rb(a,r),a=a.sibling}function Rb(r,a){var d=r.alternate,m=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(Ai(a,r),Wi(r),m&4){try{zl(3,r,r.return),Du(3,r)}catch(bt){jn(r,r.return,bt)}try{zl(5,r,r.return)}catch(bt){jn(r,r.return,bt)}}break;case 1:Ai(a,r),Wi(r),m&512&&d!==null&&ja(d,d.return);break;case 5:if(Ai(a,r),Wi(r),m&512&&d!==null&&ja(d,d.return),r.flags&32){var b=r.stateNode;try{nt(b,"")}catch(bt){jn(r,r.return,bt)}}if(m&4&&(b=r.stateNode,b!=null)){var k=r.memoizedProps,F=d!==null?d.memoizedProps:k,ne=r.type,de=r.updateQueue;if(r.updateQueue=null,de!==null)try{ne==="input"&&k.type==="radio"&&k.name!=null&&Q(b,k),ae(ne,F);var Ne=ae(ne,k);for(F=0;F<de.length;F+=2){var qe=de[F],Ge=de[F+1];qe==="style"?ce(b,Ge):qe==="dangerouslySetInnerHTML"?He(b,Ge):qe==="children"?nt(b,Ge):R(b,qe,Ge,Ne)}switch(ne){case"input":ge(b,k);break;case"textarea":rt(b,k);break;case"select":var Ue=b._wrapperState.wasMultiple;b._wrapperState.wasMultiple=!!k.multiple;var ht=k.value;ht!=null?ke(b,!!k.multiple,ht,!1):Ue!==!!k.multiple&&(k.defaultValue!=null?ke(b,!!k.multiple,k.defaultValue,!0):ke(b,!!k.multiple,k.multiple?[]:"",!1))}b[Ll]=k}catch(bt){jn(r,r.return,bt)}}break;case 6:if(Ai(a,r),Wi(r),m&4){if(r.stateNode===null)throw Error(n(162));b=r.stateNode,k=r.memoizedProps;try{b.nodeValue=k}catch(bt){jn(r,r.return,bt)}}break;case 3:if(Ai(a,r),Wi(r),m&4&&d!==null&&d.memoizedState.isDehydrated)try{zi(a.containerInfo)}catch(bt){jn(r,r.return,bt)}break;case 4:Ai(a,r),Wi(r);break;case 13:Ai(a,r),Wi(r),b=r.child,b.flags&8192&&(k=b.memoizedState!==null,b.stateNode.isHidden=k,!k||b.alternate!==null&&b.alternate.memoizedState!==null||(Wf=G())),m&4&&Lb(r);break;case 22:if(qe=d!==null&&d.memoizedState!==null,r.mode&1?(js=(Ne=js)||qe,Ai(a,r),js=Ne):Ai(a,r),Wi(r),m&8192){if(Ne=r.memoizedState!==null,(r.stateNode.isHidden=Ne)&&!qe&&(r.mode&1)!==0)for(mt=r,qe=r.child;qe!==null;){for(Ge=mt=qe;mt!==null;){switch(Ue=mt,ht=Ue.child,Ue.tag){case 0:case 11:case 14:case 15:zl(4,Ue,Ue.return);break;case 1:ja(Ue,Ue.return);var _t=Ue.stateNode;if(typeof _t.componentWillUnmount=="function"){m=Ue,d=Ue.return;try{a=m,_t.props=a.memoizedProps,_t.state=a.memoizedState,_t.componentWillUnmount()}catch(bt){jn(m,d,bt)}}break;case 5:ja(Ue,Ue.return);break;case 22:if(Ue.memoizedState!==null){Tb(Ge);continue}}ht!==null?(ht.return=Ue,mt=ht):Tb(Ge)}qe=qe.sibling}e:for(qe=null,Ge=r;;){if(Ge.tag===5){if(qe===null){qe=Ge;try{b=Ge.stateNode,Ne?(k=b.style,typeof k.setProperty=="function"?k.setProperty("display","none","important"):k.display="none"):(ne=Ge.stateNode,de=Ge.memoizedProps.style,F=de!=null&&de.hasOwnProperty("display")?de.display:null,ne.style.display=I("display",F))}catch(bt){jn(r,r.return,bt)}}}else if(Ge.tag===6){if(qe===null)try{Ge.stateNode.nodeValue=Ne?"":Ge.memoizedProps}catch(bt){jn(r,r.return,bt)}}else if((Ge.tag!==22&&Ge.tag!==23||Ge.memoizedState===null||Ge===r)&&Ge.child!==null){Ge.child.return=Ge,Ge=Ge.child;continue}if(Ge===r)break e;for(;Ge.sibling===null;){if(Ge.return===null||Ge.return===r)break e;qe===Ge&&(qe=null),Ge=Ge.return}qe===Ge&&(qe=null),Ge.sibling.return=Ge.return,Ge=Ge.sibling}}break;case 19:Ai(a,r),Wi(r),m&4&&Lb(r);break;case 21:break;default:Ai(a,r),Wi(r)}}function Wi(r){var a=r.flags;if(a&2){try{e:{for(var d=r.return;d!==null;){if(Eb(d)){var m=d;break e}d=d.return}throw Error(n(160))}switch(m.tag){case 5:var b=m.stateNode;m.flags&32&&(nt(b,""),m.flags&=-33);var k=Nb(r);Ff(r,k,b);break;case 3:case 4:var F=m.stateNode.containerInfo,ne=Nb(r);zf(r,ne,F);break;default:throw Error(n(161))}}catch(de){jn(r,r.return,de)}r.flags&=-3}a&4096&&(r.flags&=-4097)}function q2(r,a,d){mt=r,Ab(r)}function Ab(r,a,d){for(var m=(r.mode&1)!==0;mt!==null;){var b=mt,k=b.child;if(b.tag===22&&m){var F=b.memoizedState!==null||Pu;if(!F){var ne=b.alternate,de=ne!==null&&ne.memoizedState!==null||js;ne=Pu;var Ne=js;if(Pu=F,(js=de)&&!Ne)for(mt=b;mt!==null;)F=mt,de=F.child,F.tag===22&&F.memoizedState!==null?Ib(b):de!==null?(de.return=F,mt=de):Ib(b);for(;k!==null;)mt=k,Ab(k),k=k.sibling;mt=b,Pu=ne,js=Ne}Mb(r)}else(b.subtreeFlags&8772)!==0&&k!==null?(k.return=b,mt=k):Mb(r)}}function Mb(r){for(;mt!==null;){var a=mt;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:js||Du(5,a);break;case 1:var m=a.stateNode;if(a.flags&4&&!js)if(d===null)m.componentDidMount();else{var b=a.elementType===a.type?d.memoizedProps:Li(a.type,d.memoizedProps);m.componentDidUpdate(b,d.memoizedState,m.__reactInternalSnapshotBeforeUpdate)}var k=a.updateQueue;k!==null&&Ty(a,k,m);break;case 3:var F=a.updateQueue;if(F!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}Ty(a,F,d)}break;case 5:var ne=a.stateNode;if(d===null&&a.flags&4){d=ne;var de=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":de.autoFocus&&d.focus();break;case"img":de.src&&(d.src=de.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(a.memoizedState===null){var Ne=a.alternate;if(Ne!==null){var qe=Ne.memoizedState;if(qe!==null){var Ge=qe.dehydrated;Ge!==null&&zi(Ge)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}js||a.flags&512&&$f(a)}catch(Ue){jn(a,a.return,Ue)}}if(a===r){mt=null;break}if(d=a.sibling,d!==null){d.return=a.return,mt=d;break}mt=a.return}}function Tb(r){for(;mt!==null;){var a=mt;if(a===r){mt=null;break}var d=a.sibling;if(d!==null){d.return=a.return,mt=d;break}mt=a.return}}function Ib(r){for(;mt!==null;){var a=mt;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{Du(4,a)}catch(de){jn(a,d,de)}break;case 1:var m=a.stateNode;if(typeof m.componentDidMount=="function"){var b=a.return;try{m.componentDidMount()}catch(de){jn(a,b,de)}}var k=a.return;try{$f(a)}catch(de){jn(a,k,de)}break;case 5:var F=a.return;try{$f(a)}catch(de){jn(a,F,de)}}}catch(de){jn(a,a.return,de)}if(a===r){mt=null;break}var ne=a.sibling;if(ne!==null){ne.return=a.return,mt=ne;break}mt=a.return}}var K2=Math.ceil,Ou=x.ReactCurrentDispatcher,Hf=x.ReactCurrentOwner,hi=x.ReactCurrentBatchConfig,en=0,Zn=null,On=null,ps=0,ni=0,La=Br(0),Wn=0,Fl=null,jo=0,Bu=0,Uf=0,Hl=null,qs=null,Wf=0,Ra=1/0,br=null,$u=!1,qf=null,Wr=null,zu=!1,qr=null,Fu=0,Ul=0,Kf=null,Hu=-1,Uu=0;function Ds(){return(en&6)!==0?G():Hu!==-1?Hu:Hu=G()}function Kr(r){return(r.mode&1)===0?1:(en&2)!==0&&ps!==0?ps&-ps:L2.transition!==null?(Uu===0&&(Uu=Hn()),Uu):(r=Jt,r!==0||(r=window.event,r=r===void 0?16:yl(r.type)),r)}function Mi(r,a,d,m){if(50<Ul)throw Ul=0,Kf=null,Error(n(185));ws(r,d,m),((en&2)===0||r!==Zn)&&(r===Zn&&((en&2)===0&&(Bu|=d),Wn===4&&Vr(r,ps)),Ks(r,m),d===1&&en===0&&(a.mode&1)===0&&(Ra=G()+500,vu&&zr()))}function Ks(r,a){var d=r.callbackNode;hs(r,a);var m=wt(r,r===Zn?ps:0);if(m===0)d!==null&&Xe(d),r.callbackNode=null,r.callbackPriority=0;else if(a=m&-m,r.callbackPriority!==a){if(d!=null&&Xe(d),a===1)r.tag===0?j2(Db.bind(null,r)):wy(Db.bind(null,r)),k2(function(){(en&6)===0&&zr()}),d=null;else{switch(hl(m)){case 1:d=Ie;break;case 4:d=Qe;break;case 16:d=Ae;break;case 536870912:d=Ct;break;default:d=Ae}d=Wb(d,Pb.bind(null,r))}r.callbackPriority=a,r.callbackNode=d}}function Pb(r,a){if(Hu=-1,Uu=0,(en&6)!==0)throw Error(n(327));var d=r.callbackNode;if(Aa()&&r.callbackNode!==d)return null;var m=wt(r,r===Zn?ps:0);if(m===0)return null;if((m&30)!==0||(m&r.expiredLanes)!==0||a)a=Wu(r,m);else{a=m;var b=en;en|=2;var k=Bb();(Zn!==r||ps!==a)&&(br=null,Ra=G()+500,Ro(r,a));do try{Y2();break}catch(ne){Ob(r,ne)}while(!0);uf(),Ou.current=k,en=b,On!==null?a=0:(Zn=null,ps=0,a=Wn)}if(a!==0){if(a===2&&(b=Gt(r),b!==0&&(m=b,a=Vf(r,b))),a===1)throw d=Fl,Ro(r,0),Vr(r,m),Ks(r,G()),d;if(a===6)Vr(r,m);else{if(b=r.current.alternate,(m&30)===0&&!V2(b)&&(a=Wu(r,m),a===2&&(k=Gt(r),k!==0&&(m=k,a=Vf(r,k))),a===1))throw d=Fl,Ro(r,0),Vr(r,m),Ks(r,G()),d;switch(r.finishedWork=b,r.finishedLanes=m,a){case 0:case 1:throw Error(n(345));case 2:Ao(r,qs,br);break;case 3:if(Vr(r,m),(m&130023424)===m&&(a=Wf+500-G(),10<a)){if(wt(r,0)!==0)break;if(b=r.suspendedLanes,(b&m)!==m){Ds(),r.pingedLanes|=r.suspendedLanes&b;break}r.timeoutHandle=Qh(Ao.bind(null,r,qs,br),a);break}Ao(r,qs,br);break;case 4:if(Vr(r,m),(m&4194240)===m)break;for(a=r.eventTimes,b=-1;0<m;){var F=31-Pe(m);k=1<<F,F=a[F],F>b&&(b=F),m&=~k}if(m=b,m=G()-m,m=(120>m?120:480>m?480:1080>m?1080:1920>m?1920:3e3>m?3e3:4320>m?4320:1960*K2(m/1960))-m,10<m){r.timeoutHandle=Qh(Ao.bind(null,r,qs,br),m);break}Ao(r,qs,br);break;case 5:Ao(r,qs,br);break;default:throw Error(n(329))}}}return Ks(r,G()),r.callbackNode===d?Pb.bind(null,r):null}function Vf(r,a){var d=Hl;return r.current.memoizedState.isDehydrated&&(Ro(r,a).flags|=256),r=Wu(r,a),r!==2&&(a=qs,qs=d,a!==null&&Gf(a)),r}function Gf(r){qs===null?qs=r:qs.push.apply(qs,r)}function V2(r){for(var a=r;;){if(a.flags&16384){var d=a.updateQueue;if(d!==null&&(d=d.stores,d!==null))for(var m=0;m<d.length;m++){var b=d[m],k=b.getSnapshot;b=b.value;try{if(!Ni(k(),b))return!1}catch{return!1}}}if(d=a.child,a.subtreeFlags&16384&&d!==null)d.return=a,a=d;else{if(a===r)break;for(;a.sibling===null;){if(a.return===null||a.return===r)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Vr(r,a){for(a&=~Uf,a&=~Bu,r.suspendedLanes|=a,r.pingedLanes&=~a,r=r.expirationTimes;0<a;){var d=31-Pe(a),m=1<<d;r[d]=-1,a&=~m}}function Db(r){if((en&6)!==0)throw Error(n(327));Aa();var a=wt(r,0);if((a&1)===0)return Ks(r,G()),null;var d=Wu(r,a);if(r.tag!==0&&d===2){var m=Gt(r);m!==0&&(a=m,d=Vf(r,m))}if(d===1)throw d=Fl,Ro(r,0),Vr(r,a),Ks(r,G()),d;if(d===6)throw Error(n(345));return r.finishedWork=r.current.alternate,r.finishedLanes=a,Ao(r,qs,br),Ks(r,G()),null}function Yf(r,a){var d=en;en|=1;try{return r(a)}finally{en=d,en===0&&(Ra=G()+500,vu&&zr())}}function Lo(r){qr!==null&&qr.tag===0&&(en&6)===0&&Aa();var a=en;en|=1;var d=hi.transition,m=Jt;try{if(hi.transition=null,Jt=1,r)return r()}finally{Jt=m,hi.transition=d,en=a,(en&6)===0&&zr()}}function Xf(){ni=La.current,pn(La)}function Ro(r,a){r.finishedWork=null,r.finishedLanes=0;var d=r.timeoutHandle;if(d!==-1&&(r.timeoutHandle=-1,x2(d)),On!==null)for(d=On.return;d!==null;){var m=d;switch(rf(m),m.tag){case 1:m=m.type.childContextTypes,m!=null&&mu();break;case 3:Ea(),pn(Hs),pn(Cs),_f();break;case 5:gf(m);break;case 4:Ea();break;case 13:pn(Sn);break;case 19:pn(Sn);break;case 10:df(m.type._context);break;case 22:case 23:Xf()}d=d.return}if(Zn=r,On=r=Gr(r.current,null),ps=ni=a,Wn=0,Fl=null,Uf=Bu=jo=0,qs=Hl=null,Co!==null){for(a=0;a<Co.length;a++)if(d=Co[a],m=d.interleaved,m!==null){d.interleaved=null;var b=m.next,k=d.pending;if(k!==null){var F=k.next;k.next=b,m.next=F}d.pending=m}Co=null}return r}function Ob(r,a){do{var d=On;try{if(uf(),Nu.current=Au,ju){for(var m=xn.memoizedState;m!==null;){var b=m.queue;b!==null&&(b.pending=null),m=m.next}ju=!1}if(No=0,Qn=Un=xn=null,Pl=!1,Dl=0,Hf.current=null,d===null||d.return===null){Wn=1,Fl=a,On=null;break}e:{var k=r,F=d.return,ne=d,de=a;if(a=ps,ne.flags|=32768,de!==null&&typeof de=="object"&&typeof de.then=="function"){var Ne=de,qe=ne,Ge=qe.tag;if((qe.mode&1)===0&&(Ge===0||Ge===11||Ge===15)){var Ue=qe.alternate;Ue?(qe.updateQueue=Ue.updateQueue,qe.memoizedState=Ue.memoizedState,qe.lanes=Ue.lanes):(qe.updateQueue=null,qe.memoizedState=null)}var ht=lb(F);if(ht!==null){ht.flags&=-257,cb(ht,F,ne,k,a),ht.mode&1&&ab(k,Ne,a),a=ht,de=Ne;var _t=a.updateQueue;if(_t===null){var bt=new Set;bt.add(de),a.updateQueue=bt}else _t.add(de);break e}else{if((a&1)===0){ab(k,Ne,a),Jf();break e}de=Error(n(426))}}else if(_n&&ne.mode&1){var In=lb(F);if(In!==null){(In.flags&65536)===0&&(In.flags|=256),cb(In,F,ne,k,a),lf(Na(de,ne));break e}}k=de=Na(de,ne),Wn!==4&&(Wn=2),Hl===null?Hl=[k]:Hl.push(k),k=F;do{switch(k.tag){case 3:k.flags|=65536,a&=-a,k.lanes|=a;var Se=rb(k,de,a);My(k,Se);break e;case 1:ne=de;var me=k.type,Ce=k.stateNode;if((k.flags&128)===0&&(typeof me.getDerivedStateFromError=="function"||Ce!==null&&typeof Ce.componentDidCatch=="function"&&(Wr===null||!Wr.has(Ce)))){k.flags|=65536,a&=-a,k.lanes|=a;var et=ob(k,ne,a);My(k,et);break e}}k=k.return}while(k!==null)}zb(d)}catch(St){a=St,On===d&&d!==null&&(On=d=d.return);continue}break}while(!0)}function Bb(){var r=Ou.current;return Ou.current=Au,r===null?Au:r}function Jf(){(Wn===0||Wn===3||Wn===2)&&(Wn=4),Zn===null||(jo&268435455)===0&&(Bu&268435455)===0||Vr(Zn,ps)}function Wu(r,a){var d=en;en|=2;var m=Bb();(Zn!==r||ps!==a)&&(br=null,Ro(r,a));do try{G2();break}catch(b){Ob(r,b)}while(!0);if(uf(),en=d,Ou.current=m,On!==null)throw Error(n(261));return Zn=null,ps=0,Wn}function G2(){for(;On!==null;)$b(On)}function Y2(){for(;On!==null&&!ct();)$b(On)}function $b(r){var a=Ub(r.alternate,r,ni);r.memoizedProps=r.pendingProps,a===null?zb(r):On=a,Hf.current=null}function zb(r){var a=r;do{var d=a.alternate;if(r=a.return,(a.flags&32768)===0){if(d=F2(d,a,ni),d!==null){On=d;return}}else{if(d=H2(d,a),d!==null){d.flags&=32767,On=d;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{Wn=6,On=null;return}}if(a=a.sibling,a!==null){On=a;return}On=a=r}while(a!==null);Wn===0&&(Wn=5)}function Ao(r,a,d){var m=Jt,b=hi.transition;try{hi.transition=null,Jt=1,X2(r,a,d,m)}finally{hi.transition=b,Jt=m}return null}function X2(r,a,d,m){do Aa();while(qr!==null);if((en&6)!==0)throw Error(n(327));d=r.finishedWork;var b=r.finishedLanes;if(d===null)return null;if(r.finishedWork=null,r.finishedLanes=0,d===r.current)throw Error(n(177));r.callbackNode=null,r.callbackPriority=0;var k=d.lanes|d.childLanes;if($i(r,k),r===Zn&&(On=Zn=null,ps=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||zu||(zu=!0,Wb(Ae,function(){return Aa(),null})),k=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||k){k=hi.transition,hi.transition=null;var F=Jt;Jt=1;var ne=en;en|=4,Hf.current=null,W2(r,d),Rb(d,r),g2(Xh),hr=!!Yh,Xh=Yh=null,r.current=d,q2(d),It(),en=ne,Jt=F,hi.transition=k}else r.current=d;if(zu&&(zu=!1,qr=r,Fu=b),k=r.pendingLanes,k===0&&(Wr=null),ut(d.stateNode),Ks(r,G()),a!==null)for(m=r.onRecoverableError,d=0;d<a.length;d++)b=a[d],m(b.value,{componentStack:b.stack,digest:b.digest});if($u)throw $u=!1,r=qf,qf=null,r;return(Fu&1)!==0&&r.tag!==0&&Aa(),k=r.pendingLanes,(k&1)!==0?r===Kf?Ul++:(Ul=0,Kf=r):Ul=0,zr(),null}function Aa(){if(qr!==null){var r=hl(Fu),a=hi.transition,d=Jt;try{if(hi.transition=null,Jt=16>r?16:r,qr===null)var m=!1;else{if(r=qr,qr=null,Fu=0,(en&6)!==0)throw Error(n(331));var b=en;for(en|=4,mt=r.current;mt!==null;){var k=mt,F=k.child;if((mt.flags&16)!==0){var ne=k.deletions;if(ne!==null){for(var de=0;de<ne.length;de++){var Ne=ne[de];for(mt=Ne;mt!==null;){var qe=mt;switch(qe.tag){case 0:case 11:case 15:zl(8,qe,k)}var Ge=qe.child;if(Ge!==null)Ge.return=qe,mt=Ge;else for(;mt!==null;){qe=mt;var Ue=qe.sibling,ht=qe.return;if(Cb(qe),qe===Ne){mt=null;break}if(Ue!==null){Ue.return=ht,mt=Ue;break}mt=ht}}}var _t=k.alternate;if(_t!==null){var bt=_t.child;if(bt!==null){_t.child=null;do{var In=bt.sibling;bt.sibling=null,bt=In}while(bt!==null)}}mt=k}}if((k.subtreeFlags&2064)!==0&&F!==null)F.return=k,mt=F;else e:for(;mt!==null;){if(k=mt,(k.flags&2048)!==0)switch(k.tag){case 0:case 11:case 15:zl(9,k,k.return)}var Se=k.sibling;if(Se!==null){Se.return=k.return,mt=Se;break e}mt=k.return}}var me=r.current;for(mt=me;mt!==null;){F=mt;var Ce=F.child;if((F.subtreeFlags&2064)!==0&&Ce!==null)Ce.return=F,mt=Ce;else e:for(F=me;mt!==null;){if(ne=mt,(ne.flags&2048)!==0)try{switch(ne.tag){case 0:case 11:case 15:Du(9,ne)}}catch(St){jn(ne,ne.return,St)}if(ne===F){mt=null;break e}var et=ne.sibling;if(et!==null){et.return=ne.return,mt=et;break e}mt=ne.return}}if(en=b,zr(),Ee&&typeof Ee.onPostCommitFiberRoot=="function")try{Ee.onPostCommitFiberRoot(Ze,r)}catch{}m=!0}return m}finally{Jt=d,hi.transition=a}}return!1}function Fb(r,a,d){a=Na(d,a),a=rb(r,a,1),r=Hr(r,a,1),a=Ds(),r!==null&&(ws(r,1,a),Ks(r,a))}function jn(r,a,d){if(r.tag===3)Fb(r,r,d);else for(;a!==null;){if(a.tag===3){Fb(a,r,d);break}else if(a.tag===1){var m=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof m.componentDidCatch=="function"&&(Wr===null||!Wr.has(m))){r=Na(d,r),r=ob(a,r,1),a=Hr(a,r,1),r=Ds(),a!==null&&(ws(a,1,r),Ks(a,r));break}}a=a.return}}function J2(r,a,d){var m=r.pingCache;m!==null&&m.delete(a),a=Ds(),r.pingedLanes|=r.suspendedLanes&d,Zn===r&&(ps&d)===d&&(Wn===4||Wn===3&&(ps&130023424)===ps&&500>G()-Wf?Ro(r,0):Uf|=d),Ks(r,a)}function Hb(r,a){a===0&&((r.mode&1)===0?a=1:(a=Ke,Ke<<=1,(Ke&130023424)===0&&(Ke=4194304)));var d=Ds();r=vr(r,a),r!==null&&(ws(r,a,d),Ks(r,d))}function Q2(r){var a=r.memoizedState,d=0;a!==null&&(d=a.retryLane),Hb(r,d)}function Z2(r,a){var d=0;switch(r.tag){case 13:var m=r.stateNode,b=r.memoizedState;b!==null&&(d=b.retryLane);break;case 19:m=r.stateNode;break;default:throw Error(n(314))}m!==null&&m.delete(a),Hb(r,d)}var Ub;Ub=function(r,a,d){if(r!==null)if(r.memoizedProps!==a.pendingProps||Hs.current)Ws=!0;else{if((r.lanes&d)===0&&(a.flags&128)===0)return Ws=!1,z2(r,a,d);Ws=(r.flags&131072)!==0}else Ws=!1,_n&&(a.flags&1048576)!==0&&Sy(a,yu,a.index);switch(a.lanes=0,a.tag){case 2:var m=a.type;Iu(r,a),r=a.pendingProps;var b=ya(a,Cs.current);Ca(a,d),b=wf(null,a,m,r,b,d);var k=Sf();return a.flags|=1,typeof b=="object"&&b!==null&&typeof b.render=="function"&&b.$$typeof===void 0?(a.tag=1,a.memoizedState=null,a.updateQueue=null,Us(m)?(k=!0,gu(a)):k=!1,a.memoizedState=b.state!==null&&b.state!==void 0?b.state:null,pf(a),b.updater=Mu,a.stateNode=b,b._reactInternals=a,jf(a,m,r,d),a=Mf(null,a,m,!0,k,d)):(a.tag=0,_n&&k&&sf(a),Ps(null,a,b,d),a=a.child),a;case 16:m=a.elementType;e:{switch(Iu(r,a),r=a.pendingProps,b=m._init,m=b(m._payload),a.type=m,b=a.tag=t5(m),r=Li(m,r),b){case 0:a=Af(null,a,m,r,d);break e;case 1:a=mb(null,a,m,r,d);break e;case 11:a=ub(null,a,m,r,d);break e;case 14:a=db(null,a,m,Li(m.type,r),d);break e}throw Error(n(306,m,""))}return a;case 0:return m=a.type,b=a.pendingProps,b=a.elementType===m?b:Li(m,b),Af(r,a,m,b,d);case 1:return m=a.type,b=a.pendingProps,b=a.elementType===m?b:Li(m,b),mb(r,a,m,b,d);case 3:e:{if(gb(a),r===null)throw Error(n(387));m=a.pendingProps,k=a.memoizedState,b=k.element,Ay(r,a),Cu(a,m,null,d);var F=a.memoizedState;if(m=F.element,k.isDehydrated)if(k={element:m,isDehydrated:!1,cache:F.cache,pendingSuspenseBoundaries:F.pendingSuspenseBoundaries,transitions:F.transitions},a.updateQueue.baseState=k,a.memoizedState=k,a.flags&256){b=Na(Error(n(423)),a),a=vb(r,a,m,d,b);break e}else if(m!==b){b=Na(Error(n(424)),a),a=vb(r,a,m,d,b);break e}else for(ti=Or(a.stateNode.containerInfo.firstChild),ei=a,_n=!0,ji=null,d=Ly(a,null,m,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Sa(),m===b){a=yr(r,a,d);break e}Ps(r,a,m,d)}a=a.child}return a;case 5:return Iy(a),r===null&&af(a),m=a.type,b=a.pendingProps,k=r!==null?r.memoizedProps:null,F=b.children,Jh(m,b)?F=null:k!==null&&Jh(m,k)&&(a.flags|=32),pb(r,a),Ps(r,a,F,d),a.child;case 6:return r===null&&af(a),null;case 13:return _b(r,a,d);case 4:return mf(a,a.stateNode.containerInfo),m=a.pendingProps,r===null?a.child=xa(a,null,m,d):Ps(r,a,m,d),a.child;case 11:return m=a.type,b=a.pendingProps,b=a.elementType===m?b:Li(m,b),ub(r,a,m,b,d);case 7:return Ps(r,a,a.pendingProps,d),a.child;case 8:return Ps(r,a,a.pendingProps.children,d),a.child;case 12:return Ps(r,a,a.pendingProps.children,d),a.child;case 10:e:{if(m=a.type._context,b=a.pendingProps,k=a.memoizedProps,F=b.value,ln(Su,m._currentValue),m._currentValue=F,k!==null)if(Ni(k.value,F)){if(k.children===b.children&&!Hs.current){a=yr(r,a,d);break e}}else for(k=a.child,k!==null&&(k.return=a);k!==null;){var ne=k.dependencies;if(ne!==null){F=k.child;for(var de=ne.firstContext;de!==null;){if(de.context===m){if(k.tag===1){de=_r(-1,d&-d),de.tag=2;var Ne=k.updateQueue;if(Ne!==null){Ne=Ne.shared;var qe=Ne.pending;qe===null?de.next=de:(de.next=qe.next,qe.next=de),Ne.pending=de}}k.lanes|=d,de=k.alternate,de!==null&&(de.lanes|=d),hf(k.return,d,a),ne.lanes|=d;break}de=de.next}}else if(k.tag===10)F=k.type===a.type?null:k.child;else if(k.tag===18){if(F=k.return,F===null)throw Error(n(341));F.lanes|=d,ne=F.alternate,ne!==null&&(ne.lanes|=d),hf(F,d,a),F=k.sibling}else F=k.child;if(F!==null)F.return=k;else for(F=k;F!==null;){if(F===a){F=null;break}if(k=F.sibling,k!==null){k.return=F.return,F=k;break}F=F.return}k=F}Ps(r,a,b.children,d),a=a.child}return a;case 9:return b=a.type,m=a.pendingProps.children,Ca(a,d),b=ui(b),m=m(b),a.flags|=1,Ps(r,a,m,d),a.child;case 14:return m=a.type,b=Li(m,a.pendingProps),b=Li(m.type,b),db(r,a,m,b,d);case 15:return hb(r,a,a.type,a.pendingProps,d);case 17:return m=a.type,b=a.pendingProps,b=a.elementType===m?b:Li(m,b),Iu(r,a),a.tag=1,Us(m)?(r=!0,gu(a)):r=!1,Ca(a,d),sb(a,m,b),jf(a,m,b,d),Mf(null,a,m,!0,r,d);case 19:return bb(r,a,d);case 22:return fb(r,a,d)}throw Error(n(156,a.tag))};function Wb(r,a){return De(r,a)}function e5(r,a,d,m){this.tag=r,this.key=d,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=m,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function fi(r,a,d,m){return new e5(r,a,d,m)}function Qf(r){return r=r.prototype,!(!r||!r.isReactComponent)}function t5(r){if(typeof r=="function")return Qf(r)?1:0;if(r!=null){if(r=r.$$typeof,r===B)return 11;if(r===P)return 14}return 2}function Gr(r,a){var d=r.alternate;return d===null?(d=fi(r.tag,a,r.key,r.mode),d.elementType=r.elementType,d.type=r.type,d.stateNode=r.stateNode,d.alternate=r,r.alternate=d):(d.pendingProps=a,d.type=r.type,d.flags=0,d.subtreeFlags=0,d.deletions=null),d.flags=r.flags&14680064,d.childLanes=r.childLanes,d.lanes=r.lanes,d.child=r.child,d.memoizedProps=r.memoizedProps,d.memoizedState=r.memoizedState,d.updateQueue=r.updateQueue,a=r.dependencies,d.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},d.sibling=r.sibling,d.index=r.index,d.ref=r.ref,d}function qu(r,a,d,m,b,k){var F=2;if(m=r,typeof r=="function")Qf(r)&&(F=1);else if(typeof r=="string")F=5;else e:switch(r){case Y:return Mo(d.children,b,k,a);case q:F=8,b|=8;break;case K:return r=fi(12,d,a,b|2),r.elementType=K,r.lanes=k,r;case D:return r=fi(13,d,a,b),r.elementType=D,r.lanes=k,r;case O:return r=fi(19,d,a,b),r.elementType=O,r.lanes=k,r;case A:return Ku(d,b,k,a);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case se:F=10;break e;case V:F=9;break e;case B:F=11;break e;case P:F=14;break e;case z:F=16,m=null;break e}throw Error(n(130,r==null?r:typeof r,""))}return a=fi(F,d,a,b),a.elementType=r,a.type=m,a.lanes=k,a}function Mo(r,a,d,m){return r=fi(7,r,m,a),r.lanes=d,r}function Ku(r,a,d,m){return r=fi(22,r,m,a),r.elementType=A,r.lanes=d,r.stateNode={isHidden:!1},r}function Zf(r,a,d){return r=fi(6,r,null,a),r.lanes=d,r}function ep(r,a,d){return a=fi(4,r.children!==null?r.children:[],r.key,a),a.lanes=d,a.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},a}function n5(r,a,d,m,b){this.tag=a,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Pt(0),this.expirationTimes=Pt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Pt(0),this.identifierPrefix=m,this.onRecoverableError=b,this.mutableSourceEagerHydrationData=null}function tp(r,a,d,m,b,k,F,ne,de){return r=new n5(r,a,d,ne,de),a===1?(a=1,k===!0&&(a|=8)):a=0,k=fi(3,null,null,a),r.current=k,k.stateNode=r,k.memoizedState={element:m,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},pf(k),r}function s5(r,a,d){var m=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:$,key:m==null?null:""+m,children:r,containerInfo:a,implementation:d}}function qb(r){if(!r)return $r;r=r._reactInternals;e:{if(Vt(r)!==r||r.tag!==1)throw Error(n(170));var a=r;do{switch(a.tag){case 3:a=a.stateNode.context;break e;case 1:if(Us(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break e}}a=a.return}while(a!==null);throw Error(n(171))}if(r.tag===1){var d=r.type;if(Us(d))return yy(r,d,a)}return a}function Kb(r,a,d,m,b,k,F,ne,de){return r=tp(d,m,!0,r,b,k,F,ne,de),r.context=qb(null),d=r.current,m=Ds(),b=Kr(d),k=_r(m,b),k.callback=a??null,Hr(d,k,b),r.current.lanes=b,ws(r,b,m),Ks(r,m),r}function Vu(r,a,d,m){var b=a.current,k=Ds(),F=Kr(b);return d=qb(d),a.context===null?a.context=d:a.pendingContext=d,a=_r(k,F),a.payload={element:r},m=m===void 0?null:m,m!==null&&(a.callback=m),r=Hr(b,a,F),r!==null&&(Mi(r,b,F,k),ku(r,b,F)),F}function Gu(r){if(r=r.current,!r.child)return null;switch(r.child.tag){case 5:return r.child.stateNode;default:return r.child.stateNode}}function Vb(r,a){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var d=r.retryLane;r.retryLane=d!==0&&d<a?d:a}}function np(r,a){Vb(r,a),(r=r.alternate)&&Vb(r,a)}function i5(){return null}var Gb=typeof reportError=="function"?reportError:function(r){console.error(r)};function sp(r){this._internalRoot=r}Yu.prototype.render=sp.prototype.render=function(r){var a=this._internalRoot;if(a===null)throw Error(n(409));Vu(r,a,null,null)},Yu.prototype.unmount=sp.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var a=r.containerInfo;Lo(function(){Vu(null,r,null,null)}),a[fr]=null}};function Yu(r){this._internalRoot=r}Yu.prototype.unstable_scheduleHydration=function(r){if(r){var a=pl();r={blockedOn:null,target:r,priority:a};for(var d=0;d<Is.length&&a!==0&&a<Is[d].priority;d++);Is.splice(d,0,r),d===0&&vl(r)}};function ip(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Xu(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function Yb(){}function r5(r,a,d,m,b){if(b){if(typeof m=="function"){var k=m;m=function(){var Ne=Gu(F);k.call(Ne)}}var F=Kb(a,m,r,0,null,!1,!1,"",Yb);return r._reactRootContainer=F,r[fr]=F.current,Nl(r.nodeType===8?r.parentNode:r),Lo(),F}for(;b=r.lastChild;)r.removeChild(b);if(typeof m=="function"){var ne=m;m=function(){var Ne=Gu(de);ne.call(Ne)}}var de=tp(r,0,!1,null,null,!1,!1,"",Yb);return r._reactRootContainer=de,r[fr]=de.current,Nl(r.nodeType===8?r.parentNode:r),Lo(function(){Vu(a,de,d,m)}),de}function Ju(r,a,d,m,b){var k=d._reactRootContainer;if(k){var F=k;if(typeof b=="function"){var ne=b;b=function(){var de=Gu(F);ne.call(de)}}Vu(a,F,r,b)}else F=r5(d,a,r,b,m);return Gu(F)}fl=function(r){switch(r.tag){case 3:var a=r.stateNode;if(a.current.memoizedState.isDehydrated){var d=at(a.pendingLanes);d!==0&&(xi(a,d|1),Ks(a,G()),(en&6)===0&&(Ra=G()+500,zr()))}break;case 13:Lo(function(){var m=vr(r,1);if(m!==null){var b=Ds();Mi(m,r,1,b)}}),np(r,1)}},ra=function(r){if(r.tag===13){var a=vr(r,134217728);if(a!==null){var d=Ds();Mi(a,r,134217728,d)}np(r,134217728)}},Qs=function(r){if(r.tag===13){var a=Kr(r),d=vr(r,a);if(d!==null){var m=Ds();Mi(d,r,a,m)}np(r,a)}},pl=function(){return Jt},ml=function(r,a){var d=Jt;try{return Jt=r,a()}finally{Jt=d}},At=function(r,a,d){switch(a){case"input":if(ge(r,d),a=d.name,d.type==="radio"&&a!=null){for(d=r;d.parentNode;)d=d.parentNode;for(d=d.querySelectorAll("input[name="+JSON.stringify(""+a)+'][type="radio"]'),a=0;a<d.length;a++){var m=d[a];if(m!==r&&m.form===r.form){var b=pu(m);if(!b)throw Error(n(90));Te(m),ge(m,b)}}}break;case"textarea":rt(r,d);break;case"select":a=d.value,a!=null&&ke(r,!!d.multiple,a,!1)}},$t=Yf,Zt=Lo;var o5={usingClientEntryPoint:!1,Events:[Rl,va,pu,ft,Yt,Yf]},Wl={findFiberByHostInstance:wo,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},a5={bundleType:Wl.bundleType,version:Wl.version,rendererPackageName:Wl.rendererPackageName,rendererConfig:Wl.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:x.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=kt(r),r===null?null:r.stateNode},findFiberByHostInstance:Wl.findFiberByHostInstance||i5,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Qu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Qu.isDisabled&&Qu.supportsFiber)try{Ze=Qu.inject(a5),Ee=Qu}catch{}}return Vs.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=o5,Vs.createPortal=function(r,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!ip(a))throw Error(n(200));return s5(r,a,null,d)},Vs.createRoot=function(r,a){if(!ip(r))throw Error(n(299));var d=!1,m="",b=Gb;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(m=a.identifierPrefix),a.onRecoverableError!==void 0&&(b=a.onRecoverableError)),a=tp(r,1,!1,null,null,d,!1,m,b),r[fr]=a.current,Nl(r.nodeType===8?r.parentNode:r),new sp(a)},Vs.findDOMNode=function(r){if(r==null)return null;if(r.nodeType===1)return r;var a=r._reactInternals;if(a===void 0)throw typeof r.render=="function"?Error(n(188)):(r=Object.keys(r).join(","),Error(n(268,r)));return r=kt(a),r=r===null?null:r.stateNode,r},Vs.flushSync=function(r){return Lo(r)},Vs.hydrate=function(r,a,d){if(!Xu(a))throw Error(n(200));return Ju(null,r,a,!0,d)},Vs.hydrateRoot=function(r,a,d){if(!ip(r))throw Error(n(405));var m=d!=null&&d.hydratedSources||null,b=!1,k="",F=Gb;if(d!=null&&(d.unstable_strictMode===!0&&(b=!0),d.identifierPrefix!==void 0&&(k=d.identifierPrefix),d.onRecoverableError!==void 0&&(F=d.onRecoverableError)),a=Kb(a,null,r,1,d??null,b,!1,k,F),r[fr]=a.current,Nl(r),m)for(r=0;r<m.length;r++)d=m[r],b=d._getVersion,b=b(d._source),a.mutableSourceEagerHydrationData==null?a.mutableSourceEagerHydrationData=[d,b]:a.mutableSourceEagerHydrationData.push(d,b);return new Yu(a)},Vs.render=function(r,a,d){if(!Xu(a))throw Error(n(200));return Ju(null,r,a,!1,d)},Vs.unmountComponentAtNode=function(r){if(!Xu(r))throw Error(n(40));return r._reactRootContainer?(Lo(function(){Ju(null,null,r,!1,function(){r._reactRootContainer=null,r[fr]=null})}),!0):!1},Vs.unstable_batchedUpdates=Yf,Vs.unstable_renderSubtreeIntoContainer=function(r,a,d,m){if(!Xu(d))throw Error(n(200));if(r==null||r._reactInternals===void 0)throw Error(n(38));return Ju(r,a,d,!1,m)},Vs.version="18.3.1-next-f1338f8080-20240426",Vs}var sw;function g5(){if(sw)return ap.exports;sw=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),ap.exports=m5(),ap.exports}var iw;function v5(){if(iw)return Zu;iw=1;var e=g5();return Zu.createRoot=e.createRoot,Zu.hydrateRoot=e.hydrateRoot,Zu}var _5=v5();const y5=mv(_5),Rm="nc_token",Am="nc:auth-invalid",Mm="nc:token-not-remembered";function b5(e){return typeof e=="string"&&e.startsWith("/api/")&&!e.startsWith("/api/route/")}const jc=(e,t)=>{try{return e()}catch{return t}};function o1(e={}){return{local:e.local!==void 0?e.local:jc(()=>globalThis.localStorage,null),session:e.session!==void 0?e.session:jc(()=>globalThis.sessionStorage,null)}}const rw=e=>jc(()=>e?String(e.getItem(Rm)||"").trim():"","");function w5(e){const{local:t,session:n}=o1(e);return rw(t)||rw(n)||""}function a1(e,{remember:t=!0,local:n,session:s}={}){const i=String(e||"").trim();if(!i)return{ok:!1,where:null};const l=o1({local:n,session:s}),c=t?[["local",l.local,l.session],["session",l.session,l.local]]:[["session",l.session,l.local],["local",l.local,l.session]];for(const[u,h,p]of c)if(h&&jc(()=>(h.setItem(Rm,i),!0),!1))return jc(()=>{p&&p.removeItem(Rm)},null),{ok:!0,where:u};return{ok:!1,where:null}}function ow(e,t,n){if(!(!n||n.status!==401||!b5(e)))try{window.dispatchEvent(new CustomEvent(Am,{detail:{token:t,path:e}}))}catch{}}const S5=8e3,x5=4e3,l1=8e3;function k5(e){const t=new AbortController,n=setTimeout(()=>t.abort(new DOMException("timeout","TimeoutError")),e);return{signal:t.signal,cancel:()=>clearTimeout(n),controller:t}}function aw(e,t){return t.redirect!==void 0?t:/^\/(?:api\/route|node)\//.test(String(e))?{...t,redirect:"error"}:t}function Vn(e,t,n={}){const s=Number(n.timeoutMs);if(!Number.isFinite(s)||s<=0)return fetch(e,{...aw(e,n),headers:{...n.headers||{},Authorization:`Bearer ${t}`}}).then(g=>(ow(e,t,g),g));const{signal:i,cancel:l,controller:c}=k5(s),u=n.signal,h=()=>c.abort(u.reason),p=()=>{l(),u&&u.removeEventListener("abort",h)};if(u){if(u.aborted)return p(),c.abort(u.reason),Promise.reject(u.reason instanceof Error?u.reason:new DOMException("aborted","AbortError"));u.addEventListener("abort",h,{once:!0})}const{timeoutMs:v,..._}=n;return fetch(e,{...aw(e,_),signal:i,headers:{..._.headers||{},Authorization:`Bearer ${t}`}}).then(g=>(g.__cleanupTimeout=p,ow(e,t,g),g),g=>{throw p(),g})}const c1=e=>`nc_seen_${e}`;async function it(e,t,n={}){const s=await Vn(e,t,{method:n.method||"GET",headers:{"content-type":"application/json"},body:n.body?JSON.stringify(n.body):void 0,timeoutMs:n.timeoutMs,signal:n.signal});let i;try{try{i=await s.json()}catch(l){if(l&&(l.name==="AbortError"||l.name==="TimeoutError"))throw l;i={}}}finally{typeof s.__cleanupTimeout=="function"&&s.__cleanupTimeout()}if(!s.ok){const l=new Error(i.error||`HTTP ${s.status}`);throw l.status=s.status,l.data=i,l}return i}const bn=e=>Array.isArray(e)&&e.length?`/api/route/${e.map(encodeURIComponent).join("/")}/_`:"/api",En=(e,t)=>`${bn(e)}/fleet/${t}`;async function C5(e,t,n,{signal:s}={}){const i=await Vn(`${bn(t)}/panel/${encodeURIComponent(n)}/ticket`,e,{method:"POST",signal:s}),l=await i.json().catch(()=>({}));return i.status===200&&l&&typeof l.ticket=="string"?{ok:!0,ticket:l.ticket}:i.status===403&&l&&l.reason==="panel-not-granted"?{ok:!1,cause:"not-granted"}:i.status===403?{ok:!1,cause:"node-refused"}:i.status===404?{ok:!1,cause:"no-panel"}:i.status===401?{ok:!1,cause:"unauthorized"}:{ok:!1,cause:"denied"}}const rl=(e,t,n)=>it(En(t,"status"),e,n),vv=6e4,E5=(e,t,n)=>it(En(n,"up"),e,{method:"POST",body:t,timeoutMs:vv}),u1=(e,t,n)=>it(En(n,"down"),e,{method:"POST",body:t,timeoutMs:vv}),d1=(e,t,n)=>it(En(n,"boot"),e,{method:"POST",body:t}),uc=(e,t,n)=>it(En(n,"restart"),e,{method:"POST",body:{cell:t}}),uh=(e,t)=>it(En(t,"definitions"),e),N5=(e,t)=>it(En(t,"credentials/status"),e),lw=(e,t,n,s)=>it(En(s,"credentials/set"),e,{method:"POST",body:{envKey:t,value:n}}),j5=(e,t,n)=>it(En(n,"credentials/remove"),e,{method:"POST",body:{envKey:t}}),L5=(e,t,n)=>it(En(n,"define-engine"),e,{method:"POST",body:{def:t}}),R5=(e,t,n,s,i)=>it(En(i,"edit-engine"),e,{method:"POST",body:{id:t,patch:n,envChanges:s}}),A5=(e,t,n)=>it(En(n,"remove-engine"),e,{method:"POST",body:{id:t}}),cw=(e,t,n)=>it(En(n,"define-model"),e,{method:"POST",body:{def:t}}),uw=(e,t,n,s,i)=>it(En(i,"edit-model"),e,{method:"POST",body:{id:t,engine:n,patch:s}}),M5=(e,t,n,s)=>it(En(s,"remove-model"),e,{method:"POST",body:{id:t,engine:n}}),T5=(e,t,n,s)=>it(En(s,"model-test"),e,{method:"POST",body:{engine:t,model:n}}),I5=(e,t,n=!1,s)=>it(`${En(s,"engine-models")}?engine=${encodeURIComponent(t)}${n?"&refresh=1":""}`,e,{timeoutMs:vv}),P5=(e,t,n)=>it(En(n,"define-cell"),e,{method:"POST",body:{def:t}}),h1=(e,t,n,s)=>it(En(s,"edit-cell"),e,{method:"POST",body:{id:t,patch:n}}),f1=(e,t,n=!1,s)=>it(En(s,"remove-cell"),e,{method:"POST",body:{id:t,stop:n}}),D5=(e,t,n)=>it(En(n,"import-cell"),e,{method:"POST",body:t}),O5=(e,t,n)=>it(En(n,"restore-cells"),e,{method:"POST",body:{cells:t}}),B5=(e,t,n,s,i)=>it(En(s,"restore-engines"),e,{method:"POST",body:{engines:t,overwrite:!!n,...Array.isArray(i)&&i.length?{models:i}:{}}}),_v=(e,t,n)=>it(`${bn(n)}/sessions/${encodeURIComponent(t)}`,e,{method:"DELETE"}),p1=(e,t,n,s)=>it(`${bn(s)}/sessions/${encodeURIComponent(t)}/visibility`,e,{method:"PATCH",body:{technical:!!n}}),yv=(e,t,n)=>it(`${bn(n)}/fs/dirs${t?`?path=${encodeURIComponent(t)}`:""}`,e),m1=(e,t={})=>it("/api/settings",e,t),$5=(e,t={})=>it("/api/nodes",e,t),z5=(e,t={})=>it("/api/peers",e,t),g1=(e,t=[],n={})=>it(`${bn(t)}/vl-nodes`,e,{timeoutMs:x5,...n}),dw=(e,t,n,s={},i=[])=>it(`${bn(i)}/vl-nodes/${encodeURIComponent(t)}/commands`,e,{method:"POST",body:{kind:n,args:s}}),F5=(e,t,n=0,s=[])=>it(`${bn(s)}/vl-nodes/${encodeURIComponent(t)}/events${n?`?after=${encodeURIComponent(n)}`:""}`,e),v1=(e,t={})=>it("/api/topology",e,t),bv=(e,t,n={})=>it(`${bn(t)}/sessions`,e,n),Yc=(e,t,n={})=>it(`${bn(t)}/config`,e,n),hw=(e,t,n={})=>it(`${bn(t)}/topology`,e,n),Bd=(e,t)=>it("/api/settings/config",e,{method:"POST",body:t}),H5=e=>it("/api/settings/ai-desktop",e),_1=(e,t)=>it("/api/settings/ai-desktop",e,{method:"POST",body:{enabled:t}}),U5=e=>it("/api/settings/token/rotate",e,{method:"POST"}),W5=(e,t)=>it("/api/settings/nodes/pair",e,{method:"POST",body:t}),q5=(e,t,n=[])=>it(`${bn(n)}/settings/peering/invite`,e,{method:"POST",body:t||{}}),y1=(e,t,n)=>it(`/api/settings/nodes/${encodeURIComponent(t)}/label`,e,{method:"PATCH",body:{label:n}}),K5=(e,t={})=>it("/api/settings/node-aliases",e,t),V5=(e,t,n)=>it(`/api/settings/node-aliases/${encodeURIComponent(t)}`,e,{method:"PATCH",body:{alias:n}}),fw=(e,t)=>it(`/api/settings/node-aliases/${encodeURIComponent(t)}`,e,{method:"DELETE"}),up=(e,t,n)=>it(`/api/settings/nodes/${encodeURIComponent(t)}`,e,{method:"PATCH",body:n}),G5=(e,t)=>it(`/api/settings/nodes/${encodeURIComponent(t)}`,e,{method:"DELETE"}),wv=(e,t,n)=>it(`/api/settings/nodes/${encodeURIComponent(t)}/${n}`,e,{method:"POST"}),Y5=(e,t,n)=>it(`/api/settings/nodes/${encodeURIComponent(t)}/share`,e,{method:"PATCH",body:{shared:n}}),X5=(e,t,n,s=[])=>it(`/api/settings/nodes/${encodeURIComponent(t)}/visibility`,e,{method:"PATCH",body:{visibility:n,selected:s}}),J5=e=>it("/api/settings/audio",e),Q5=(e,t)=>it("/api/settings/audio/consent",e,{method:"PATCH",body:{consent:t}}),Z5=e=>it("/api/settings/audio/test",e,{method:"POST",body:{}}),ej=e=>it("/api/settings/audio/stop",e,{method:"POST",body:{}}),tj=e=>it("/api/settings/audio/groups",e),nj=(e,t,n)=>it(`/api/settings/audio/groups/${encodeURIComponent(t)}`,e,{method:"PUT",body:n}),sj=(e,t)=>it(`/api/settings/audio/groups/${encodeURIComponent(t)}`,e,{method:"DELETE"}),ij=e=>it("/api/settings/service/regenerate",e,{method:"POST"}),rj=e=>it("/api/settings/update/check",e,{method:"POST"}),oj=e=>it("/api/settings/update/apply",e,{method:"POST"}),dh=(e,t)=>`${bn(e)}/diagnostics/${t}`,aj=(e,t=[])=>it(dh(t,"status"),e),lj=(e,{after:t=0,limit:n=200}={},s=[])=>it(`${dh(s,"logs")}?after=${encodeURIComponent(t)}&limit=${encodeURIComponent(n)}`,e),pw=(e,t,n,s=[])=>it(dh(s,"verbose"),e,{method:"PATCH",body:{enabled:t,durationSeconds:n}}),cj=(e,t=[])=>it(dh(t,"logs"),e,{method:"DELETE"}),uj=(e,t=!0)=>it(`/api/asks${t?"?open=1":""}`,e),dj=(e,t,n)=>it(`/api/asks/${encodeURIComponent(t)}/answer`,e,{method:"POST",body:{text:n}}),hj=(e,t)=>it(`/api/asks/${encodeURIComponent(t)}`,e,{method:"DELETE"}),fj=(e,{ownerId:t,askId:n,text:s,requestId:i})=>it("/api/asks-relay",e,{method:"POST",body:{ownerId:t,askId:n,text:s,requestId:i}}),pj=(e,{ownerId:t,askId:n,requestId:s})=>it("/api/asks-relay",e,{method:"POST",body:{action:"verify",ownerId:t,askId:n,requestId:s}}),mj=(e,{ownerId:t,askId:n},s={})=>it(`/api/asks-relay/capability?ownerId=${encodeURIComponent(t)}&askId=${encodeURIComponent(n)}&dismissals=1`,e,{timeoutMs:8e3,...s}),gj=e=>it("/api/asks-relay/state",e),vj=(e,{ownerId:t,askId:n})=>it("/api/asks-relay",e,{method:"POST",body:{action:"dismiss",ownerId:t,askId:n}}),_j=(e,{ownerId:t,askId:n})=>it("/api/asks-relay",e,{method:"POST",body:{action:"dismiss-local",ownerId:t,askId:n}}),yj=e=>it("/api/feed-state",e),bj=(e,{ownerId:t,eventId:n})=>it("/api/notices-relay",e,{method:"POST",body:{action:"dismiss",ownerId:t,eventId:n}}),wj=(e,{owners:t})=>it("/api/notices-relay",e,{method:"POST",body:{action:"dismiss-all",owners:t}}),ed=(e,t=[])=>it(`${bn(t)}/decks`,e,t.length?{timeoutMs:S5}:{}),mw=(e,t,n=[])=>it(`${bn(n)}/decks`,e,{method:"POST",body:{name:t}}),td=(e,t,n,s,i=[],l)=>it(`${bn(i)}/decks/${encodeURIComponent(t)}`,e,{method:"PUT",body:{layout:n,expectedRevision:s,...l?{floating:l}:{}}}),Sj=(e,t,n,s,i=[],l)=>Vn(`${bn(i)}/decks/${encodeURIComponent(t)}`,e,{method:"PUT",keepalive:!0,headers:{"content-type":"application/json"},body:JSON.stringify({layout:n,expectedRevision:s,...l?{floating:l}:{}})}),xj=(e,t,n,s,i=[])=>it(`${bn(i)}/decks/${encodeURIComponent(t)}`,e,{method:"PATCH",body:{name:n,expectedRevision:s}}),kj=(e,t,n,s=[])=>it(`${bn(s)}/decks/${encodeURIComponent(t)}`,e,{method:"DELETE",body:{expectedRevision:n}}),hh=(e,t=[],n)=>it(`${bn(t)}/live-host`,e,n),fh=(e,t,n,s=[])=>it(`${bn(s)}/live-host/designate`,e,{method:"POST",body:{cellId:t,expectedRevision:n}}),ph=(e,t,n=[])=>it(`${bn(n)}/live-host/clear`,e,{method:"POST",body:{expectedRevision:t}});function mh(){let e=0,t=!1;return{begin(){return t?null:(t=!0,e+=1,e)},end(n){n===e&&(t=!1)},reset(){e+=1,t=!1},isCurrent(n){return n!==null&&n===e}}}const b1=4e3,gw=3500,ao=new Map,w1=()=>typeof document<"u"&&document.visibilityState==="hidden";let vw=!1;function Cj(){vw||typeof document>"u"||!document.addEventListener||(vw=!0,document.addEventListener("visibilitychange",()=>{const e=w1();for(const t of ao.values())e?t.timer!==null&&(clearInterval(t.timer),t.timer=null):t.timer===null&&(t.timer=setInterval(t.cycle,b1),t.cycle())}))}const Sv=(e,t)=>`${e}|${JSON.stringify(t||[])}`;function Ej(e){return e&&e.length?`/api/route/${e.map(encodeURIComponent).join("/")}/_`:"/api"}function Nj(e,t){const n=mh(),s={token:e,route:t,consumers:new Set,snapshot:null,timer:null},i=async()=>{const l=n.begin();if(l!==null)try{let c=null,u=null;try{c=await(await Vn(`${Ej(t)}/sessions`,e,{timeoutMs:gw})).json()}catch(v){u=v}let h=null,p=null;try{h=await rl(e,t,{timeoutMs:gw})}catch(v){p=v}if(!n.isCurrent(l))return;s.snapshot={at:Date.now(),sessionsJson:c,sessionsError:u,fs:h,fleetError:p};for(const v of s.consumers)v(s.snapshot)}finally{n.end(l)}};return s.cycle=i,Cj(),w1()||(s.timer=setInterval(i,b1)),i(),s}function Lc(e,t,n){const s=Sv(e,t);let i=ao.get(s);return i||(i=Nj(e,t),ao.set(s,i)),i.consumers.add(n),i.snapshot&&n(i.snapshot),()=>{const l=ao.get(s);l&&(l.consumers.delete(n),l.consumers.size===0&&(l.timer!==null&&clearInterval(l.timer),ao.delete(s)))}}function dc(e,t=null){if(t!==null){const s=ao.get(Sv(t,e));return s?s.snapshot:null}const n=`|${JSON.stringify(e||[])}`;for(const[s,i]of ao)if(s.endsWith(n))return i.snapshot;return null}function hc(e,t=null){const n=`|${JSON.stringify(e||[])}`;for(const[s,i]of ao)(t!==null?s===Sv(t,e):s.endsWith(n))&&i.cycle()}const jj={power:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 3v8"}),o.jsx("path",{d:"M6.6 6.6a8 8 0 1 0 10.8 0"})]}),folder:o.jsx("path",{d:"M4 6a2 2 0 0 1 2-2h3.6a2 2 0 0 1 1.4.6L12.4 6H18a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z"}),keyboard:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"6",width:"18",height:"12",rx:"2"}),o.jsx("path",{d:"M7 10h.01M11 10h.01M15 10h.01M17 14h.01M7 14h7"})]}),mic:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),o.jsx("path",{d:"M5 11a7 7 0 0 0 14 0"}),o.jsx("path",{d:"M12 18v3"})]}),enter:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M20 5v6a2 2 0 0 1-2 2H5"}),o.jsx("polyline",{points:"9 9 5 13 9 17"})]}),send:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M22 2 15 22 11 13 2 9Z"}),o.jsx("path",{d:"M22 2 11 13"})]}),trash:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M4 7h16"}),o.jsx("path",{d:"M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"}),o.jsx("path",{d:"M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12"}),o.jsx("path",{d:"M10 11v6M14 11v6"})]}),x:o.jsx("path",{d:"M6 6l12 12M18 6 6 18"}),broadcast:o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor",stroke:"none"}),o.jsx("path",{d:"M7.6 16.4a6.2 6.2 0 0 1 0-8.8"}),o.jsx("path",{d:"M16.4 7.6a6.2 6.2 0 0 1 0 8.8"}),o.jsx("path",{d:"M4.6 19.4a10.6 10.6 0 0 1 0-14.8"}),o.jsx("path",{d:"M19.4 4.6a10.6 10.6 0 0 1 0 14.8"})]}),monitor:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"12",rx:"2"}),o.jsx("path",{d:"M8 20h8M12 16v4"})]}),refresh:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M21 12a9 9 0 1 1-2.64-6.36L21 8"}),o.jsx("polyline",{points:"21 3 21 8 16 8"})]}),boot:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"13",rx:"2"}),o.jsx("path",{d:"M8 21h8M12 17v4M12 12V7"}),o.jsx("polyline",{points:"9 10 12 7 15 10"})]}),upload:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 16V5"}),o.jsx("polyline",{points:"8 9 12 5 16 9"}),o.jsx("path",{d:"M5 20h14"})]}),download:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 4v10"}),o.jsx("polyline",{points:"8 10 12 14 16 10"}),o.jsx("path",{d:"M5 15v4a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-4"})]}),chevronLeft:o.jsx("polyline",{points:"14 6 8 12 14 18"}),chevronUp:o.jsx("polyline",{points:"6 14 12 8 18 14"}),chevronDown:o.jsx("polyline",{points:"6 10 12 16 18 10"}),history:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),o.jsx("polyline",{points:"3 3 3 8 8 8"}),o.jsx("path",{d:"M12 7v5l3 2"})]}),attach:o.jsx("path",{d:"M21.44 11.05 12.25 20.24a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"}),file:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),o.jsx("polyline",{points:"14 2 14 8 20 8"})]}),camera:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M14.5 4h-5L7.5 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3.5z"}),o.jsx("circle",{cx:"12",cy:"13",r:"3.5"})]}),image:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),o.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),o.jsx("path",{d:"M21 15l-5-5L5 21"})]}),gpu:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"}),o.jsx("rect",{x:"10",y:"10",width:"4",height:"4",rx:"1"}),o.jsx("path",{d:"M9 3v3M15 3v3M9 18v3M15 18v3M3 9h3M3 15h3M18 9h3M18 15h3"})]}),zoomIn:o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"11",cy:"11",r:"7"}),o.jsx("path",{d:"M21 21l-4.35-4.35"}),o.jsx("path",{d:"M8 11h6M11 8v6"})]}),zoomOut:o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"11",cy:"11",r:"7"}),o.jsx("path",{d:"M21 21l-4.35-4.35"}),o.jsx("path",{d:"M8 11h6"})]}),gear:o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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"})]}),splitView:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3.5",y:"5.5",width:"17",height:"13",rx:"1.5"}),o.jsx("line",{x1:"14.5",y1:"5.5",x2:"14.5",y2:"18.5"})]}),copy:o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),more:o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"5",cy:"12",r:"1.6",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.6",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"19",cy:"12",r:"1.6",fill:"currentColor",stroke:"none"})]}),eye:o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12Z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),search:o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"11",cy:"11",r:"7"}),o.jsx("path",{d:"M21 21l-4.35-4.35"})]})};function yt({name:e,size:t=20}){return o.jsx("svg",{className:"nc-icon",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:jj[e]||null})}const xv=["it","en","es"];function Lj(){try{const e=typeof navigator<"u"&&navigator.language||"",t=String(e).slice(0,2).toLowerCase();return xv.includes(t)?t:"en"}catch{return"en"}}const xd=Lj(),S1="nc_lang",Tm="nc-lang";function x1(){return typeof localStorage<"u"?localStorage:null}const nd={it:{"update-available":"nuova versione {v} disponibile","update-stale":"interfaccia non allineata: stai eseguendo la v{browser}, il nodo serve la v{ui}. ricarica senza cache; se persiste, riavvia il nodo","reload-no-cache":"ricarica senza cache","update-installed-restart":"versione {v} installata: riavvia il nodo","update-dismiss":"chiudi","install-version-mismatch":"installazione incompleta: frontend e server non coincidono (v{v})",reload:"ricarica","grid-empty":"trascina qui una sessione dalla sidebar, o doppio-clic per la vista singola","grid-full":"il deck può mostrare al massimo 9 sessioni",pin:"fissa in cima",reorder:"riordina","host-lease-live":"host live: supervisione attiva","host-lease-grace":"host live: supervisione in recupero (grace)","host-lease-expired":"host live: supervisione scaduta","host-lease-none":"host live: mai supervisionata","host-lease-unavailable":"host live: garanzia di supervisione non disponibile su questo nodo","reorder-help":"trascina la maniglia; frecce su/giu da tastiera","rename-node":"rinomina nodo","rename-node-prompt":"Nuovo nome del nodo in NexusCrew","rename-node-invalid":"Nome non valido: massimo 64 caratteri, senza a capo.","reorder-deck-help":"trascina il deck; frecce sinistra/destra da tastiera",sessions:"sessioni","new-session":"nuova sessione",new:"nuova",fleet:"Flotta","fleet-tmux":"flotta tmux","other-sessions":"Altre sessioni","view-all":"tutte","view-pinned":"fissate","view-active":"attive","view-off":"spente","view-technical":"tecniche","mark-technical":"nascondi come sessione tecnica","mark-normal":"mostra come sessione normale","position-local":"Locale",files:"file",refresh:"aggiorna","filter-placeholder":"filtra sessioni…","loading-fleet":"carico la flotta…","no-sessions":"nessuna sessione tmux viva — la flotta parte al boot (systemd)","no-match":'nessuna sessione contiene "{q}"',"copy-url":"clicca per copiare l'URL","ssh-only":"solo tunnel SSH/VPN","new-files-outbox":"nuovi file in outbox",terminate:"termina","terminate-confirm":'Terminare la sessione "{name}"?',"cell-on":"tmux vivo","cell-off":"spenta","node-sessions-unverified":"sessioni non verificate","tile-unverified":"dato non verificato","cell-working":"al lavoro","cell-idle":"in attesa","cell-stopped":"ferma","cell-permission":"attesa permesso","cell-unknown":"non verificato","cell-degraded":"degradata: unit attiva, tmux morto","power-on":"accendi","power-off":"spegni","boot-enable":"attiva al boot","boot-disable":"disattiva al boot","state-on":"accesa","state-off":"spenta","power-starting":"avvio…","power-stopping":"arresto…","fleet-up-slow":"avvio in corso: controlla lo stato","fleet-down-slow":"arresto in corso: controlla lo stato","fleet-up-duplicate":"già in esecuzione",engine:"Engine",model:"Modello","model-default":"Modello predefinito del provider","model-remembered":"Ultimo modello usato con questo engine","boot-persist":"avvia al boot","remove-boot":"togli anche dal boot","power-config-in-settings":"Engine, provider, profilo, modello e permessi si modificano in Impostazioni → Flotta.","no-remote-control":"⚠ engine non-native: niente RC da app claude.ai (da qui la piloti comunque)",cancel:"annulla",name:"nome","name-invalid":"nome non valido: a-zA-Z0-9._- max 64, senza '-' iniziale",cwd:"cartella",browse:"sfoglia","fs-home":"home","fs-parent":".. su",preset:"preset","preset-2x2":"griglia 2×2","preset-columns":"colonne","preset-equalize":"equalizza",collapse:"comprimi",expand:"espandi",create:"crea","auth-prompt":"Incolla il token (stampato dal server):","auth-invalid":"Il nodo non accetta più questo token (ruotato o sostituito). Inserisci quello nuovo: le tue preferenze non vengono toccate.","auth-not-remembered":"Il browser non ha permesso di ricordare il token su questo device: dovrai reinserirlo alla prossima apertura.","remember-device":"ricorda su questo device","zoom-out":"testo più piccolo","zoom-in":"testo più grande","dual-swap":"scambia le due celle","dual-go-to":"Vai a {cell}","dual-close":"chiudi la seconda cella","dual-focus":"cella col focus","terminal-renderer-webgl":"WebGL","terminal-renderer-dom":"DOM","terminal-renderer-switch":"motore grafico: richiesto {requested}, in uso {effective} — tocca per cambiare (ricarica il terminale)",composer:"composer",panel:"pannello","panel-none":"Nessun pannello configurato per questa cella.","panel-checking":"Apertura del pannello…","panel-not-granted":"Questo nodo non concede il pannello a chi lo chiede: l'accesso va concesso sul nodo che possiede la cella, non riprovando qui.","panel-denied":"Ingresso al pannello rifiutato: il biglietto non è più valido. Riprova: verrà chiesto un biglietto nuovo.","cell-peek":"Sbircia senza cambiare cella","cell-tele-ctx":"contesto","cell-tele-free":"libero","cell-tele-5h":"5h usati","cell-tele-7d":"7g usati","cell-activity":"attività","cell-activity-now":"adesso","cell-peek-preview":"Anteprima","cell-peek-stream":"Flusso","cell-peek-panel":"Pannello","cell-peek-vuoto":"Nessuna anteprima disponibile per questa cella.","panel-node-refused":"Il nodo che possiede la cella rifiuta la richiesta: è in sola lettura, o la sua policy blocca questa operazione. Riprovare qui non cambia l'esito.","panel-unauthorized":"Credenziale non valida per questo nodo: va corretta dove è configurata, non riprovando da qui.","panel-unreachable":"Il pannello non è raggiungibile attraverso questo nodo: riprova tra poco.","panel-frame-loading":"pannello montato: caricamento in corso","panel-frame-error":"Il frame del pannello non si è caricato: il biglietto può essere scaduto (30 s di vita, monouso) o la destinazione è irraggiungibile. Riprova: verrà chiesto un biglietto nuovo.","popup-drag-hint":"trascina per spostare; doppio clic per tornare al centro","popup-resize-hint":"trascina per ridimensionare","panel-timeout":"Il pannello non ha risposto in tempo: servizio lento a partire o sovraccarico. Riprova tra poco.","panel-retry":"Riprova","live-host-indicator":"Live host: {cell} · {mode} · {state}","live-host-indicator-none":"Live host: nessuna cella designata","live-host-remote":"altro nodo","live-host-mode-native":"nativa (thread)","live-host-mode-tmux":"tmux","live-host-mode-unknown":"modalità sconosciuta","live-host-state-none":"nessuna designazione","live-host-state-designated":"designata, thread assente","live-host-state-thread-present":"thread presente ma inattivo","live-host-state-thread-active":"thread attivo","live-host-state-thread-unknown":"stato del thread sconosciuto","live-badge":"Live","live-badge-native":"Live attiva (thread nativo)","live-badge-tmux":"Live attiva in modalità tmux: non riceve messaggi","live-host-designated":"Live host: {cell}","live-host-cleared":"Live host rimosso","live-host-action-use":"Usa come host Live","live-host-action-remove":"Rimuovi host Live","cell-actions-title":"Azioni di {cell}","cell-actions-open":"Azioni cella","cell-actions-live-assign":"Assegna la Live","cell-actions-live-remove":"Togli la Live","cell-actions-pin":"Fissa in cima","cell-actions-unpin":"Togli in cima","cell-actions-boot":"Avvio al boot","cell-actions-watch":"Guarda dal vivo","bar-menu-open":"Altre azioni","bar-menu-keyboard":"Tastiera di scrittura","bar-menu-keyboard-desc":"sotto il terminale","bar-menu-files":"File della cella","bar-menu-files-desc":"inbox · outbox","bar-menu-files-setting-desc":"mostra il tasto nella barra","bar-menu-panel":"Pannello della cella","bar-menu-panel-desc":"solo se la cella ne ha uno","bar-menu-renderer":"Renderer GPU","bar-menu-renderer-desc":"cambiarlo ricarica la pagina","bar-keyboard-button":"Tasto tastiera in barra","bar-keyboard-button-desc":"mostra il tasto della tastiera di scrittura","bar-panel-button":"Tasto AI Desktop in barra","bar-panel-button-desc":"mostra il tasto, se la cella ha un pannello","cell-switcher-group":"Celle {node}","cell-switcher-group-local":"locale","cell-switcher-tap-hint":"Tocca una cella per l'anteprima · tocca di nuovo per aprirla","cell-switcher-two-taps":"2 tocchi = apri","cell-switcher-side-add":"affianca nella doppia vista","cell-switcher-side-remove":"togli dalla doppia vista","cell-switcher-preview-word":"ANTEPRIMA","cell-switcher-preview-readonly":"sola lettura","cell-peek-expand":"Apri la finestra","ai-desktop-title":"Desktop grafico","ai-desktop":"Desktop grafico attivo","ai-desktop-help":"Il container del desktop parte con la spunta e si ferma senza; il tasto del pannello appare solo con il desktop attivo.","ai-desktop-confirm-stop":"Il desktop è in esecuzione: spegnerlo chiude le sessioni aperte nel container. Continuare?","panel-start-desktop":"Avvia il desktop","live-host-stale-revision":"designazione non applicata: lo stato e' cambiato nel frattempo, riprova","live-host-not-local":"quella cella non appartiene a questo nodo","live-host-unavailable":"flotta non disponibile su questo nodo, riprova tra poco","live-host-not-granted":"Questo nodo non concede la designazione della cella ospite Live a chi la chiede: va concessa sul nodo che possiede la cella (nodes live-host <nodo> on), non riprovando qui.","live-host-error":"La designazione della cella ospite Live non è riuscita: riprova tra poco.","host-thread-designated":"cella designata; thread assente","host-thread-present":"thread presente ma inattivo","host-thread-active":"thread attivo","host-thread-unknown":"stato del thread sconosciuto",windows:"{n} finestre","empty-files":"vuota","files-download":"scarica file","files-download-action":"Scarica","files-outbox":"Outbox · {n}","files-inbox":"Inbox · {n}","files-search":"cerca file","files-search-ph":"cerca per nome…","files-no-match":'nessun file contiene "{q}"',"files-actions":"azioni del file","files-sheet-title":"Azioni del file","files-original-name":"nome originale","files-preview":"Anteprima","files-preview-failed":"anteprima non riuscita","files-preview-blocked":"anteprima non disponibile per questo tipo: scaricalo","files-copy-name":"Copia nome completo","files-copied-name":"nome completo copiato","files-delete-ellipsis":"Elimina…","files-delete-confirm":'Eliminare "{name}"?',"files-delete-confirm-help":"Il file viene eliminato definitivamente dalla cartella della cella.","files-today":"Oggi","files-dupes":"{n} copie","files-of":"File di {session}","files-upload":"Carica file","files-upload-failed":"errore caricamento: {e}","files-filter-all":"Tutti","files-filter-docs":"Documenti","files-filter-images":"Immagini","files-open":"Apri","files-detail-none":"Seleziona un file per vederne i dettagli.","files-meta-date":"Data","files-meta-size":"Dimensione","files-meta-folder":"Cartella","files-meta-type":"Tipo","files-footer-count":"{n} file · {size}","files-kbd-enter":"Invio","files-kbd-hint":"↑↓ sposta la selezione · {enter} apre le azioni · / cerca","no-sessions-short":"nessuna sessione","composer-placeholder":"scrivi o detta…","composer-history-tools":"cronologia e dimensione input","composer-history":"cronologia della cella","composer-history-empty":"nessun input inviato","composer-history-clear":"cancella cronologia di questa cella","composer-expand":"espandi input","composer-collapse":"riduci input","composer-clear-data":"cancella bozze e cronologia","composer-clear-data-help":"Rimuove da questo browser tutte le bozze e la cronologia input delle celle.","composer-clear-confirm":"Cancellare tutte le bozze e la cronologia input salvate in questo browser?","composer-clear-done":"Bozze e cronologia cancellate.","composer-clear-failed":"Impossibile cancellare i dati del composer in questo browser.",attach:"allega","attach-file":"File","attach-camera":"Fotocamera","attach-gallery":"Galleria","attach-inbox":"Inbox","attach-inbox-done":"{n} file aggiunti all'inbox","attach-uploading":"carico…","attach-upload-progress":"allegato {n}/{total}…","attach-uploaded":"{n} allegati caricati",voice:"voice",send:"invia","composer-send-failed":"connessione non pronta — testo conservato, riprova",close:"chiudi","lang-label":"lingua",decks:"deck","new-deck":"nuovo deck","deck-name":"nome deck","open-deck-window":"apri in una nuova finestra","detach-deck":"stacca in una nuova finestra","deck-current":"questo deck (finestra corrente)","deck-stale":"aggiornamento in ritardo","deck-stale-badge":"in ritardo","deck-owner-unavailable":"nodo owner non condiviso o non raggiungibile","deck-owner-reconnecting":"riconnessione…","deck-owner-stale":"owner stale (route in cache)","rename-deck":"rinomina deck","delete-deck":"elimina deck","delete-deck-confirm":'Eliminare il deck "{name}"?',"send-to-deck":"manda al deck…","deck-autosave":"salvataggio automatico",saving:"salvataggio…",saved:"salvato","popup-blocked":"popup bloccato: apri qui","expand-owner":"espandi i deck di {owner}","collapse-owner":"comprimi i deck di {owner}","owner-deck-count-one":"{count} deck","owner-deck-count-many":"{count} deck","dot-working":"in uso (finestra attiva)","dot-on":"aperta in background","dot-neutral":"non aperta","dot-warn":"nodo offline","select-drag":"trascina per selezionare","copy-manual":"seleziona e copia manualmente","toggle-sidebar":"mostra/nascondi la barra laterale",settings:"impostazioni","tab-roles":"ruoli","tab-nodes":"nodi",local:"Locale",location:"Dove","pairing-link":"link di pairing","pairing-required":"nome, alias SSH e link di pairing sono obbligatori","pairing-connect-help":"Per collegare un nodo servono: nome, Host SSH già funzionante e link/QR creato sull’altra installazione NexusCrew.","pairing-localhost-hint":"127.0.0.1 nel link è corretto: non aprirlo qui. NexusCrew usa invito e porta attraverso l’Host SSH.","scan-qr":"scansiona QR","pairing-qr-invalid":"QR di pairing non valido","invite-node":"invita un nodo","create-pairing-link":"crea link / QR","visibility-network":"tutta la rete","visibility-relay":"solo relay","visibility-selected":"nodi selezionati","hydra-simple":"locale + nodi, una sola rete","tile-detach":"Stacca e fai flottare","tile-reattach":"Rimetti nella griglia","tile-minimize":"Riduci","tile-restore":"Ripristina","grid-resize-cols":"Trascina per ridimensionare le due colonne; doppio clic: metà e metà. Alt: niente aggancio.","grid-resize-rows":"Trascina per ridimensionare le due finestre; doppio clic: metà e metà. Alt: niente aggancio.","device-name-ask-title":"Come si chiama questo dispositivo?","device-name-ask-text":"Il nome non è ricavabile dall’host: serve per mostrarti il nodo Locale e per presentarti ai nuovi nodi.","device-name-save":"Salva nome","device-name-later":"Più tardi","wizard-device-name":"Dai un nome a questo dispositivo (lo vedrai come nodo Locale e i nuovi nodi lo useranno).","local-ready":"Questo dispositivo è pronto. Puoi usarlo da solo o collegarlo a un nodo.","local-only":"solo locale","add-node":"aggiungi nodo",connect:"collega","node-connected":"Nodo collegato. La rete verrà sincronizzata automaticamente.","pair-authkeys-title":"Riga da sostituire in ~/.ssh/authorized_keys sul peer","pair-authkeys-hint":"Senza questa riga il forward del pannello resta rifiutato: il tunnel sembra attivo e il pannello non risponde.","pair-authkeys-copy":"Copia la riga","pair-authkeys-copied":"Riga copiata","tab-system":"sistema","tab-fleet":"flotta","tab-audio":"audio","system-general":"generale","system-diagnostics":"diagnostica","system-this-node":"questo nodo","system-updates":"aggiornamenti","system-security":"sicurezza","system-local-data":"dati locali del browser","system-terminal":"terminale","alternate-screen":"schermo alternato","alternate-screen-help":"Mantiene il comportamento tmux standard per le nuove sessioni NexusCrew. Un’applicazione che segue il mouse scorre da sé; le altre fanno scorrere la storia di tmux. Non modifica le celle già attive.","tab-input":"input","tab-diagnostics":"diagnostica","input-settings-local":"Preferenze locali di questo browser. Si applicano subito a vista singola e deck, senza modificare il nodo remoto.","terminal-keyboard-gesture":"Apertura tastiera virtuale dal terminale","terminal-keyboard-double-tap":"Doppio tap (predefinito)","terminal-keyboard-single-tap":"Tap singolo","terminal-keyboard-never":"Mai dal terminale","terminal-keyboard-gesture-help":"Il tastierino e STT seguono i controlli separati sotto. Mouse e tastiera fisica restano utilizzabili.","keybar-ime-lock":"Tastierino: mantieni chiusa la tastiera virtuale","keybar-ime-lock-help":"ESC, frecce, PgUp/PgDn, Enter e menu inviano direttamente al PTY senza dare focus a un campo di testo.","voice-ime-lock":"Microfono STT: mantieni chiusa la tastiera virtuale","voice-ime-lock-help":"Il tap sul microfono avvia o ferma la voce senza focalizzare il composer.","keybar-enter-show":"Mostra Enter verticale nel tastierino","keybar-enter-show-help":"Enter resta a destra di PgUp/PgDn ed è alto quanto entrambe le righe.","keybar-layout":"Layout tastierino","keybar-layout-full":"Esteso (predefinito)","keybar-layout-compact":"Compatto","keybar-layout-help":"Compatto: una riga con expand ⊞ per accedere al set completo senza cambiare la preferenza.","input-settings-reset":"ripristina predefiniti input","diagnostics-local":"Questo nodo","diagnostics-target":"Nodo da diagnosticare","diagnostics-verbose":"Log verbosi temporanei","diagnostics-duration":"Durata verbose","diagnostics-expires":"Verbose attivo fino alle {time}","diagnostics-off":"Verbose spento; warning ed errori operativi restano disponibili.","diagnostics-level":"Livello","diagnostics-all-levels":"tutti i livelli","diagnostics-component":"componente","diagnostics-pause":"pausa","diagnostics-autoscroll":"scorrimento automatico","diagnostics-log":"Log diagnostico sanitizzato","diagnostics-empty":"Nessun evento diagnostico.","diagnostics-export":"esporta JSON","diagnostics-export-failed":"Esportazione non disponibile in questo browser.","diagnostics-clear":"svuota","diagnostics-clear-confirm":"Svuotare il buffer diagnostico di questo nodo?","diagnostics-unsupported":"Questo peer è offline o non supporta la diagnostica strutturata.","fleet-editor-loading":"Caricamento dell'editor Fleet…","fleet-editor-load-error":"Impossibile caricare l'editor Fleet.","fleet-editor-unavailable":"Editor Fleet non disponibile in questa posizione.","fleet-stale":"Lettura della flotta non riuscita: l’elenco delle celle potrebbe non essere aggiornato.","reorder-blocked":"Riordino non applicato: la lista è incompleta in questo momento, il tuo ordine è al sicuro.","prefs-journal":"Diario preferenze (ultime 50 scritture)","prefs-journal-empty":"Nessuna modifica registrata finora.","prefs-journal-copy":"Copia diario","prefs-journal-clear":"Svuota diario","prefs-persist":"Storage persistente","prefs-persist-unknown":"non ancora verificato","prefs-before":"prima","prefs-after":"dopo","prefs-visible":"visibili","prefs-backup":"Backup preferenze","prefs-sync":"Copia sul nodo","prefs-conflict":"Le preferenze di questo dispositivo e la copia sul nodo sono diverse. Quale tieni?","prefs-keep-local":"Tieni questo dispositivo","prefs-use-server":"Usa la copia del nodo","prefs-export":"Esporta preferenze","prefs-import":"Importa preferenze","prefs-export-done":"File di preferenze creato (senza token).","prefs-import-done":"Preferenze importate.","prefs-import-confirm":"Sostituire le preferenze di questo dispositivo con quelle del file?","prefs-import-wrong":"Il file non è un file di preferenze NexusCrew.","prefs-import-bad":"Il file di preferenze non è valido: non è stato importato nulla.","prefs-import-storage":"Il browser ha rifiutato la scrittura: nulla è stato importato e le preferenze di questo dispositivo sono intatte.","fleet-off":"Flotta non disponibile: nessuna cella.","fleet-managed":"gestito da NexusCrew","fleet-custom":"comando personalizzato","fleet-managed-help":"Client, provider e avvio sono gestiti internamente; i segreti non vengono mostrati.","fleet-vl-binary":"percorso assoluto del binario vl (vuoto = PATH)","fleet-vl-config-file":"catalogo profili vl condiviso (config.toml, percorso assoluto)","fleet-vl-profile":"profilo vl (-p)","fleet-vl-effort":"effort (VL_EFFORT)","fleet-vl-fields-help":"Ogni cella vl ha stato e config propri. Binario e catalogo sono percorsi del nodo che esegue la cella; profilo ed effort validati all’avvio. Nessun segreto qui.","fleet-shell-engine-help":"Shell locale risolta sul dispositivo al momento dell’avvio; nessun percorso viene salvato nel backup.","fleet-shell-command-placeholder":"comando opzionale, es. npm test","fleet-shell-command-help":"Esecuzione tramite shell login interattiva (-lic), con PATH e alias utente. La cella si ferma quando il comando termina; gli errori immediati vengono segnalati.","fleet-shell-command-metachar":"Pipe, redirect, variabili e altri metacaratteri vengono interpretati dalla shell del dispositivo.","fleet-shell-interactive":"Vuoto: apre una shell interattiva locale e mantiene la cella attiva.","fleet-shell-launch-help":"Il comando Shell si configura nella cella da Impostazioni → Flotta.","fleet-credential-title":"API key su questo dispositivo","fleet-credential-help":"La key resta solo sul nodo selezionato e non viene mai mostrata né esportata. Se il nodo è remoto, il valore viaggia fino a lui sul canale accoppiato.","fleet-credential-set":"imposta key","fleet-credential-change":"cambia key","fleet-credential-forget":"dimentica","fleet-credential-saved":"Key salvata localmente.","fleet-credential-removed":"Key locale rimossa.","fleet-credential-remove-confirm":"Rimuovere la key locale {key}?","fleet-credential-source-environment":"ambiente","fleet-credential-source-local":"store locale","fleet-credential-source-compatibility":"config compatibile","fleet-credential-source-missing":"mancante","fleet-credential-source-providers-shell":"shell dell'utente","fleet-credential-source-keys-file":"file chiavi","fleet-credential-source-secure-file":"file secure (precede)","fleet-credential-source-legacy":"file legacy","fleet-credential-source-nexuscrew-store":"store NexusCrew","fleet-credential-source-unreadable":"non verificabile","fleet-credential-source-login":"login del client","fleet-credential-source-none":"nessuna","fleet-credential-source-policy":"origine credenziale","fleet-credential-source-policy-auto":"auto (precedenza legacy)","fleet-credential-source-policy-nexuscrew-store":"solo store NexusCrew","fleet-credential-source-policy-environment":"solo ambiente","fleet-key-section":"KEY","fleet-key-variable":"Variabile","fleet-key-value":"Valore per {key}","fleet-key-used-by":"Usata da: {engines}","fleet-key-used-by-none":"Non ancora usata da engine configurati su questo nodo.","fleet-key-shared-impact":"Sostituire o rimuovere {key} interessa tutti gli engine elencati: {engines}.","fleet-key-enter":"inserisci la key","fleet-key-blank-keeps":"vuoto = mantieni la fonte attuale","fleet-key-reveal":"mostra","fleet-key-hide":"nascondi","fleet-key-local-help":"Il valore resta write-only sul nodo selezionato: non viene mai riletto dalla rete e non entra in engine o backup. Se il nodo selezionato è remoto, il valore lo raggiunge attraverso il canale accoppiato.","fleet-key-create-missing":"Crea esplicitamente l’engine senza key (resterà “key richiesta”).","fleet-key-partial-create":"Engine creato; la key non è stata salvata. Puoi riprovare senza creare duplicati.","fleet-key-partial-edit":"Engine aggiornato; la key non è stata salvata. Le modifiche all’engine restano applicate.","fleet-provider-notice-claude-openrouter":"Claude Code è ottimizzato per modelli Anthropic: altri provider potrebbero non funzionare correttamente. Fast mode richiede il provider Anthropic first-party.","fleet-provider-notice-codex-openrouter":"OpenRouter Responses è beta e stateless; Codex-VL non usa fallback Chat Completions.","fleet-provider-notice-claude-kimi-code":"Kimi Code usa una configurazione Claude isolata con onboarding e fast mode dedicati; la configurazione Claude nativa non viene modificata, ma i suoi strumenti MCP vengono ereditati.","fleet-provider-notice-alibaba-token-plan":"Token Plan Personal usa solo ALIBABA_CODE_API_KEY dal credential layer locale; qwen3.8-max è il modello predefinito e non viene usato alcun fallback OpenAI/PAYG.","fleet-provider-notice-kimi-native":'Kimi Code CLI nativo usa il login del CLI (device-code) e la propria configurazione: NexusCrew non legge né copia credenziali. Distinto dal provider "Kimi Code" di Claude Code, che resta il percorso K3 gestito.',"fleet-provider-notice-opencode-native":"OpenCode client nativo: auth delegata al login locale di opencode (i modelli free del gateway rispondono anche senza login). NexusCrew non legge né copia credenziali e non scrive la tua opencode.jsonc; modelli e MCP restano nella configurazione del client.","fleet-model-default":"modello predefinito (opzionale)","fleet-model-required":"modello (obbligatorio)","fleet-models-title":"Modelli","fleet-models-usable":"Puoi usare questi","fleet-models-refresh":"Aggiorna modelli","fleet-models-refreshing":"Aggiorno…","fleet-models-loading":"Cerco i modelli dell’engine…","fleet-models-error":"Aggiornamento modelli non riuscito (rete o nodo): l’editor resta utilizzabile","fleet-models-stale":"Dati non freschi: mostro l’ultima lettura riuscita","fleet-models-unsupported":"Questo engine non espone un elenco modelli","fleet-models-none":"Nessun modello trovato","fleet-models-not-in-api":"non disponibile nelle API","fleet-models-use":"Usa il modello {model}","fleet-models-cap":"Si attivano i modelli che vuoi, entro il tetto di {cap} per engine","fleet-models-field-context":"contesto","fleet-models-field-output":"output","fleet-models-field-tools":"tool","fleet-models-field-vision":"vision","fleet-models-field-reasoning":"reasoning","fleet-models-source-of":"provenienza: {source}","fleet-models-source-user":"utente","fleet-models-source-api":"API","fleet-models-source-public":"catalogo","fleet-models-source-backup":"backup","fleet-models-missing-title":"Dato mancante","fleet-models-missing-why":"Per {model} manca un dato che serve all’engine:","fleet-models-missing-backup":"backup proposto: {value}","fleet-models-missing-user":"Quello che confermi diventa il tuo valore: precedenza più alta, mai riscritto dalla scoperta.","fleet-models-missing-confirm":"Conferma","fleet-models-missing-empty":"Lascia vuoto","fleet-models-missing-open":"Dato mancante per {model}","fleet-models-default-badge":"models.dev · default","fleet-models-make-mine":"Rendilo mio","fleet-models-make-mine-field":"Rendilo mio: {field} di {model}","fleet-models-make-mine-row":"Rendilo mio: {model}","fleet-models-make-mine-title":"Conferma i valori di {model}","fleet-models-make-mine-why":"Quello che confermi diventa una dichiarazione tua: resta sopra al catalogo e non cambia al prossimo aggiornamento.","fleet-models-make-mine-confirm":"Conferma","fleet-models-write-failed":"La scrittura non è riuscita: i valori sono ancora qui.","fleet-models-value-absent":"Lascia vuoto","fleet-models-value-true":"Sì","fleet-models-value-false":"No","fleet-models-auth-missing-key":"L’elenco modelli richiede un’autenticazione: la chiave {key} non è configurata su questo nodo","fleet-models-auth-missing-key-anonymous":"L’elenco modelli richiede un’autenticazione, ma la richiesta di questo engine è anonima: nessuna chiave è configurata.","fleet-models-auth-key-rejected":"La chiave inviata non è stata accettata per l’elenco modelli.","fleet-models-auth-access-denied":"Accesso all’elenco modelli negato: possono essere permessi o policy, non necessariamente la chiave.","fleet-models-auth-credential-unavailable":"La chiave non è leggibile o verificabile su questo nodo: non risulta assente, è indisponibile.","fleet-models-auth-endpoint-unreachable":"Endpoint non raggiungibile (rete o timeout): non è un problema di chiave.","fleet-models-auth-provider-error":"Il provider ha risposto con un errore per l’elenco modelli.","fleet-models-auth-invalid-response":"La risposta del provider per l’elenco modelli non è valida.","fleet-models-auth-anonymous-success":"Elenco modelli ottenuto senza chiave.","fleet-standard-permissions":"permessi standard","fleet-unsafe-permissions":"non sicuro · ignora approvazioni/sandbox","fleet-unsafe-warning":"Modalità non sicura esplicita: il worker può agire senza le normali approvazioni o protezioni sandbox.","fleet-provider-display":"nome visualizzato del provider","fleet-custom-provider-default":"Provider personalizzato","fleet-api-key-env":"NOME_VARIABILE_API_KEY","fleet-provider-id":"id-provider","fleet-custom-secret-help":"NexusCrew salva solo il nome della variabile d’ambiente, mai il suo valore.","cell-prompt":"Prompt di avvio della cella","cell-prompt-help":"Inviato alla cella quando parte: e’ il suo incarico permanente. Vuoto = nessun prompt, la cella parte e basta.","fleet-boot":"avvio automatico","fleet-remote-control":"controllo remoto","cell-mcp":"Strumenti MCP","cell-mcp-all":"tutti","cell-mcp-none":"nessuno","cell-mcp-some":"scelti","cell-mcp-inert":"Per questo client gli strumenti MCP li registra il client nel proprio config, non NexusCrew: la selezione qui non ha effetto.","cell-mcp-help":"«Tutti» è il comportamento di sempre. «Nessuno» è l’unica esclusione CERTA: toglie ogni strumento e non dipende da dove i server sono definiti — è ciò che serve per una cella di cui non ci si fida. Con «scelti» si concede per nome, ma l’elenco copre solo i server che questo nodo sa enumerare: plugin e connettori non compaiono e resterebbero disponibili.","fleet-model-override":"modello alternativo","fleet-ready":"pronto","fleet-not-ready":"non configurato","fleet-engines":"Engine","fleet-cells":"Celle / sessioni cloud","fleet-engine-group-standard":"Standard","fleet-engine-group-other":"Altri","fleet-models":"Modelli dichiarati","fleet-no-models":"Nessun modello dichiarato: si usano quelli del catalogo.","model-editor-engine":"Profilo","model-editor-id":"Id del modello","model-editor-id-help":"L’id esatto che il fornitore si aspetta. Profilo e id non si cambiano dopo: si ritira e si ridichiara.","model-editor-context":"Finestra di contesto (token)","model-editor-max-tokens":"Massimo di token in uscita","model-editor-reasoning":"Supporta il ragionamento esteso","model-editor-tools":"Supporta gli strumenti","model-editor-vision":"Legge le immagini","model-editor-absent":"Lascia vuoto","model-editor-true":"Sì","model-editor-false":"No","model-editor-limit-invalid":"La finestra deve stare fra 1024 e 100000000.","model-editor-effort-levels":"Livelli di effort dichiarati","model-editor-effort-invalid":"Livelli non conformi: token brevi in minuscolo, senza ripetizioni.","fleet-models-field-effort":"Livelli di effort","model-test":"Prova sull’API","model-test-running":"Provo…","model-test-ok":"risponde","model-test-unknown-model":"il fornitore non conosce questo id","model-test-auth":"credenziale mancante o rifiutata","model-test-unreachable":"endpoint non raggiungibile","model-test-unverified":"non verificato","model-test-unverified-help":"Non significa che non funzioni: questo fornitore non espone l’elenco dei modelli, quindi la prova non ha potuto dire né sì né no.","model-remove":"Ritira","model-in-use":"in uso","fleet-backup":"backup / ripristino","fleet-backup-help":"Esporta o ripristina selettivamente engine, celle, modelli dichiarati e system prompt. Token, API key e segreti provider non entrano mai nel file.","fleet-backup-export":"esporta","fleet-backup-import":"importa","fleet-backup-download":"scarica backup","fleet-backup-restore":"ripristina selezionate","fleet-backup-import-help":"Scegli un backup JSON, controlla le celle e seleziona l’engine di destinazione prima del ripristino.","fleet-backup-overwrite":"sovrascrive la cella esistente","fleet-backup-new":"nuova cella","fleet-backup-engine-missing":"scegli un engine disponibile","fleet-backup-restore-unavailable":"Il nodo selezionato supporta solo l’esportazione; aggiornalo per ripristinare backup.","fleet-backup-restored":"{n} celle ripristinate","fleet-backup-confirm-overwrite":"Sovrascrivere queste celle? {cells}","fleet-backup-needs-restart":"riavvio necessario: {cells}","fleet-backup-empty":"nessuna cella da esportare","fleet-backup-select-one":"seleziona almeno una cella","fleet-backup-too-large":"backup troppo grande (massimo 1 MB)","fleet-backup-invalid-json":"il file non contiene JSON valido","fleet-backup-invalid-format":"formato o versione del backup non supportati","fleet-backup-invalid-cell":"il backup contiene una cella non valida","fleet-backup-duplicate-cell":"il backup contiene ID cella duplicati","fleet-backup-invalid-engine":"il backup contiene un engine non valido","fleet-backup-duplicate-engine":"il backup contiene ID engine duplicati","fleet-backup-invalid-model":"il backup contiene un modello non valido","fleet-backup-duplicate-model":"il backup contiene modelli duplicati","fleet-backup-confirm-engine-overwrite":"Sovrascrivere questi engine? I valori ambiente già configurati sul target restano invariati. {engines}","fleet-backup-env-names":"nomi ambiente","fleet-backup-env-values-required":"i valori ambiente vanno configurati sul dispositivo","fleet-system-prompt":"system prompt",characters:"caratteri","select-all":"seleziona tutte","select-none":"nessuna",edit:"modifica",save:"salva",label:"etichetta","command-path":"path assoluto del comando","args-lines":"argomenti, uno per riga","env-write-only":"I valori env sono write-only: vuoto mantiene il valore esistente.","fleet-new-engine":"Nuovo engine","fleet-new-cell":"Nuova cella","fleet-saved":"Definizione salvata.","fleet-restart-confirm":"Modifica salvata. Riavviare ora: {cells}?","fleet-remove-engine":'Eliminare l’engine "{id}"?',"fleet-remove-cell":'Eliminare la cella "{id}"? Se è attiva verrà prima fermata.',"fleet-cwd-needs-repair":"cartella da riparare","fleet-cwd-repair":"ripara","fleet-cwd-repair-title":"Ripara cartella cella {id}","fleet-cwd-repair-help":"La cartella attuale non è portabile su questo dispositivo: appartiene a un altro dispositivo o non esiste sotto la home. Scegli una cartella home-relative (~) sul dispositivo target; il backend ricalcolerà il percorso assoluto.","fleet-cwd-repair-no-source-path":"Il percorso originale non viene mostrato: è specifico del dispositivo di origine.","fleet-cwd-repair-placeholder":"es. Alpha","fleet-cwd-repair-preview":"Nuova cartella: {path}","fleet-cwd-repair-browse":"sfoglia sotto ~","fleet-cwd-repair-fs-empty":"nessuna sottocartella","fleet-cwd-repair-use-current":"usa questa cartella","fleet-cwd-repair-invalid":'percorso non valido: niente assoluto, "..", barra rovesciata o lettera disco',"fleet-cwd-repair-confirm":"Impostare la cartella della cella {id} su {path}? Verrà ricalcolata sul dispositivo target.","fleet-cwd-repair-unportable":"Il percorso scelto non è portabile su questo dispositivo: deve esistere sotto la home.","fleet-cwd-repair-suggestion":"Suggerimento dal dispositivo:","fleet-cwd-repair-use-suggestion":"usa {path}","fleet-cwd-repaired":"Cartella della cella riparata.","fleet-recovery-kimi-code-consent-yes":"Kimi Code: conferma la custom API key (Yes) nel terminale della cella, poi riavvia la cella.","fleet-recovery-kimi-code-config-custom-api-key":'Kimi Code: nel terminale della cella apri /config e abilita "Use custom API key", poi riavvia la cella. Se la chiave è cambiata, aggiorna la credenziale e riprova.',"fleet-recovery-kimi-cli-login":"Kimi Code CLI: nel terminale della cella esegui /login (device-code Kimi) oppure /provider, poi riavvia la cella.","fleet-readiness-degraded":"Avviata senza conferma di prontezza: potrebbe non elaborare subito. Verifica nel terminale prima di affidarle un incarico.","fleet-mcp-degraded":"Avviata in degrado, server MCP non pronti:","fleet-vl-prompt-degraded":"Avviata senza il prompt di cella: la versione di vl sul nodo non lo supporta (serve 0.3.1+). La cella lavora senza la sua identità: aggiorna vl prima di affidarle un incarico.","fleet-recovery-client-terminal-dialog":"Completa il dialogo mostrato nel terminale della cella, poi riavvia la cella.","settings-readonly":"READONLY attivo: le modifiche sono bloccate dal server (NEXUSCREW_READONLY=1)","role-client":"client (hub)","role-client-desc":"questa macchina guarda altri nodi via tunnel SSH","role-node":"nodo (raggiungibile)","published-port":"porta pubblicata (opzionale)","no-nodes":"nessun nodo remoto configurato","node-add":"collega installazione NexusCrew","node-connect-help":"La porta SSH serve a raggiungere il server SSH. La porta NexusCrew è invece la porta locale mostrata da `nexuscrew status` sul nodo remoto.","node-name-label":"Nome del nodo","node-ssh-label":"Host SSH","pair-ssh-local-label":"Host o alias SSH su questo dispositivo","node-ssh-local-help":"Puoi sostituire l’indirizzo del link con lo stesso alias che funziona usando ssh su questo dispositivo. Alias, agent e chiavi restano locali e non viaggiano nel link.","node-ssh-port-label":"Porta SSH","node-ssh-port-help":"Di solito 22; usa la porta pubblica del server SSH.","node-app-port-label":"Porta NexusCrew sul nodo","node-app-port-help":"È la porta mostrata da `nexuscrew status` sul nodo remoto.","node-name-ph":"nome (a-z 0-9 -)","node-ssh-ph":"ssh (user@host)","node-port-ph":"porta remota (opz.)","node-remove-confirm":'Rimuovere il nodo "{name}"?',"node-remove-warning":"Elimina associazione, credenziali e tunnel locale. Non spegne il dispositivo remoto.","peer-inventory-title":"Nodi collegati al hub","peer-group-hubs":"Hub diretti","peer-group-clients":"Client collegati","peer-group-routed":"Nodi raggiungibili tramite la rete","peer-group-vl":"Nodi VL","vl-owners-unavailable":"Owner VL non raggiunti","peer-routed":"instradato","peer-routed-stale":"instradato, non raggiungibile","peer-visibility":"Visibilità nella rete","node-test":"test","tunnel-start":"avvia tunnel","tunnel-stop":"ferma tunnel","tunnel-restart":"riavvia tunnel","share-node":"Condividi questo nodo","share-local-heading":"Condivisione di questo dispositivo","share-local-hub":"Hub di condivisione","share-local-through":"Condividi {device} tramite {hub}","share-local-active":"Condiviso e raggiungibile dalla rete collegata all’hub.","share-local-pending":"Condivisione richiesta, ma il tunnel è giù: questo dispositivo non è ancora raggiungibile.","share-local-private":"Privato: solo questo dispositivo può usare il collegamento all’hub.","share-local-private-down":"Privato, ma il collegamento all’hub è giù. Riconnetti per applicare e verificare la modalità privata.","share-local-reconnect":"Riconnetti e riconcilia","share-off-hub-reconcile-pending":"Stato privato salvato; la revoca sull’hub è ancora in attesa.","fleet-cell-label":"nome leggibile (facoltativo)","fleet-panel-url":"URL pannello (opzionale)","fleet-panel-url-help":"Endpoint del pannello grafico della cella (es. il noVNC di un container): solo http/https verso un host loopback — il proxy risolve la destinazione sulla macchina che ospita la cella.","fleet-panel-url-invalid":"Il pannello non è un port-forward: chi lo apre sceglie quale cella, mai dove connettersi. L’indirizzo viene risolto sulla macchina che ospita la cella, quindi deve essere raggiungibile lì in loopback — 127.0.0.1, localhost o [::1]. L’indirizzo di un container (es. 172.17.0.2) non lo è.","share-off-local-reconcile-pending":"Revoca confermata dall’hub; il tunnel locale deve ancora riconciliarsi.","share-reverse-pool-pending":"Il canale reverse non risulta spento in modo dimostrabile: resta in quarantena, non chiuso.","share-node-off-desc":"Privato: resta collegato al nodo hub, ma gli altri client non possono raggiungerlo.","share-node-on-desc":"Condiviso: il nodo hub può mostrarlo e smistare celle e deck autorizzati.","peer-shared":"Nodo client condiviso nella rete Hydra","peer-private":"Nodo client privato: collegato, non pubblicato nella rete Hydra","peer-vl-federated":"Nodo VL: federato","row-vl-federated":"federato","node-connected-client":"client collegato","transport-used":"in uso","tunnel-up":"tunnel su","tunnel-down":"tunnel giù","vl-poll-online":"online (poll)","vl-poll-offline":"non risponde","authorized-keys-hint":"incolla questa riga in ~/.ssh/authorized_keys sull'host remoto:",copy:"copia",copied:"copiato","token-rotate":"ruota token","token-rotate-explain":"Il nuovo token NON verrà mostrato: recuperalo con `nexuscrew show token`. La sessione corrente verrà invalidata.","service-regenerate":"rigenera service","npm-auto-update":"aggiornamenti automatici da npm","npm-auto-update-help":"Controlla periodicamente latest e installa solo versioni più recenti. Mai downgrade.","npm-update-current":"installata","npm-update-latest":"npm latest","npm-update-check":"controlla ora","npm-update-install":"aggiorna ora","npm-update-restarting":"Aggiornamento avviato; NexusCrew si riaprirà dopo il riavvio del servizio.","npm-update-idle":"aggiornato","npm-update-never":"mai controllato","npm-update-checking":"controllo in corso","npm-update-available":"aggiornamento disponibile","npm-update-installing":"installazione in corso","npm-update-installed":"installato, riavvio in corso","npm-update-error":"controllo fallito","npm-update-unsupported":"disponibile solo con installazione npm globale","service-installed":"service installato","service-missing":"service non installato","service-active":"attivo","service-inactive":"non attivo",confirm:"conferma",add:"aggiungi",enable:"attiva","wizard-title":"benvenuto in NexusCrew","wizard-skip":"configura dopo dai settings","wizard-step-roles":"ruoli di questa installazione","wizard-step-node":"primo nodo remoto (opzionale)","wizard-done":"tutto pronto","wizard-done-desc":"setup completato — puoi cambiare tutto dai settings",next:"continua",back:"indietro",skip:"salta",finish:"fine","err-node-name":"nome non valido (a-z, 0-9, -, max 32)","err-local-name":"nome locale non valido: usa uno slug univoco, non “localhost”","err-ssh":"ssh non valido (atteso user@host o alias)","err-port":"porta non valida (1–65535)","err-ssh-port":"porta SSH non valida (1–65535)","err-node-port":"porta NexusCrew non valida (1–65535)","node-sessions":"{n} sessioni","tunnel-down-since":"tunnel giù da {t}","node-unreachable":"nodo non raggiungibile","peer-cause-assente":"peer non risponde — in attesa che torni (interrogazioni diradate)","peer-cause-nega":"peer nega l'accesso — concedi il permesso sul nodo remoto","peer-cause-rotta":"rotta inesistente sul peer — aggiorna il nodo","node-passive":"client offline · stato normale","node-offline":"nodo offline","node-offline-seen":"offline · visto {t} fa","node-needs-repair":"legacy · ripeti il pairing","asks-title":"domande dalle celle","remote-notices-title":"Notifiche da altri nodi","remote-notices-clear":"Pulisci","remote-notices-dismiss":"scarta questa notifica","remote-notices-dismiss-failed":"scarto non confermato: la notifica resta","remote-notices-clear-failed":"pulizia non confermata: le notifiche restano","ask-dismiss":"Scarta la domanda","ask-dismiss-local":"Scarta su questo nodo","ask-dismiss-local-pending":"Chiusura sul nodo origine in attesa","ask-dismiss-local-blocked":"Scarto solo locale: chiusura remota non autorizzata","ask-dismiss-unconfirmed":"Scarto locale non confermato: la domanda resta visibile.","ask-reply-ph":"scrivi la risposta…","push-enable":"attiva notifiche push","push-disable":"disattiva notifiche push","push-on":"push attive su questo device","push-local-off":"silenzia su questo browser","push-local-on":"riattiva su questo browser","push-local-help":"solo questo browser: la UI e le notifiche dell’owner restano attive","push-local-off-note":"avvisi di sistema spenti su questo browser; la UI resta attiva","push-local-disabled":"gli avvisi push sono spenti su questo browser: riattivali qui","push-off":"push non attive","push-denied":"permesso notifiche negato dal browser","push-unsupported":"push non supportate in questo browser","notification-speech-enable":"leggi le notifiche ad alta voce","notification-speech-help":"Usa la voce del browser solo per nuove notifiche mentre questa PWA è visibile e in primo piano. Con l’app chiusa resta la notifica di sistema.","notification-speech-test":"prova voce","notification-speech-testing":"prova in corso…","notification-speech-preview":"NexusCrew. Notifiche vocali attive.","notification-speech-preview-ok":"Prova vocale completata.","notification-speech-preview-failed":"Il browser non ha avviato la prova vocale. Interagisci con la pagina e riprova.","notification-speech-preview-voice-error":"La prova vocale è fallita: voce o audio non disponibili. Controlla la voce selezionata e riprova.","notification-speech-preview-timeout":"La prova vocale è fallita: nessuna risposta dal motore vocale. Controlla la voce selezionata e riprova.","notification-speech-needs-test":"Per questa sessione dell’app, premi “prova voce” prima di ricevere annunci vocali.","notification-speech-unsupported":"Sintesi vocale non supportata in questo browser.","audio-title":"Audio nativo del nodo","audio-help":"Consenso e controlli valgono solo per questo dispositivo. Share e visibilità non autorizzano suoni.","audio-consent":"consenti TTS su questo nodo","audio-consent-help":"Permette a celle autorizzate, locali o remote, di consegnare un comando vocale. Puoi revocarlo in ogni momento.","audio-capability":"Capability locale","audio-loading":"leggo lo stato audio locale…","audio-adapter":"adapter","audio-adapter-none":"nessuno","audio-installed":"installato","audio-installed-yes":"sì","audio-installed-no":"no","audio-liveness":"disponibilità","audio-liveness-ready":"pronto ad accettare","audio-liveness-unavailable":"non disponibile","audio-languages":"lingue dichiarate","audio-limits":"limiti","audio-test":"prova audio locale","audio-testing":"prova in corso…","audio-stop":"ferma audio locale","audio-stopping":"stop in corso…","audio-test-needs-consent":"Attiva il consenso locale prima di provare la voce.","audio-unavailable":"Nessun adapter TTS nativo disponibile su questo nodo.","audio-test-accepted":"Il nodo ha accettato la prova. Non dimostra che qualcuno l’abbia udita.","audio-test-refused":"Il nodo ha rifiutato la prova.","audio-test-unknown":"Esito della prova sconosciuto: il nodo non può confermare l’avvio.","audio-stop-stopped":"Audio locale fermato.","audio-stop-idle":"Nessun enunciato locale da fermare.","audio-groups-title":"Gruppi audio condivisi","audio-groups-help":"Decide su quali dispositivi si sente la voce quando una cella parla. Il gruppo è una preferenza locale di consegna, non un consenso. Ogni nodo conserva consenso, ACL, disponibilità e Stop locale.","audio-groups-empty":"Nessun gruppo: la voce esce solo su questo nodo.","audio-group-name":"nome gruppo","audio-group-mode":"modalità consegna","audio-group-primary":"primo disponibile (in ordine)","audio-group-fanout":"tutti i nodi elencati","audio-group-targets":"nodi target esatti","audio-group-local":"questo nodo","audio-group-unavailable-target":"non rilevato ora","audio-group-no-targets":"Nessun nodo con instanceId disponibile. Il gruppo non può usare nomi, wildcard o “tutti”.","audio-group-new":"nuovo gruppo","audio-group-edit":"modifica","audio-group-delete":"elimina","audio-group-save":"salva gruppo","audio-group-cancel":"annulla","audio-group-invalid":"Il gruppo richiede un nome valido e almeno un nodeId esatto.","audio-group-save-failed":"Salvataggio gruppo audio non riuscito.","node-display-label":"Nome (etichetta)","routed-node-aliases":"Alias nodi instradati","routed-node-aliases-help":"Visibili solo su questo dispositivo; route e nome remoto non cambiano.","node-local-alias":"Alias su questo dispositivo","alias-on-device":"Alias su questo dispositivo","reset-alias":"Ripristina nome remoto","node-slug-hint":"routing su slug: {slug}","device-name-label":"Nome dispositivo","device-name-hint":"come ti vedono i peer (modificabile)","local-route-name-label":"Nome locale / route","local-route-name-hint":"handle tecnico stabile: label leggibile + suffisso del nodeId; modificabile prima della connessione","err-label":"etichetta non valida (max 64 char, niente a capo)","fleet-inventory":"Celle e sessioni","fleet-inventory-help":"tutte le posizioni (Locale + route Hydra)","fleet-manage-location":"Gestisci posizione","fleet-network-overview":"Panoramica rete","fleet-manage-help":"crea e configura celle nella posizione selezionata","fleet-overview-help":"stato operativo di tutte le posizioni, senza duplicare l’editor","fleet-inventory-empty":"nessuna cella o sessione","cell-switcher-refreshing":"aggiorno le celle…","cell-switcher-empty-active":"nessuna cella attiva verificata","cell-switcher-not-confirmed":"stato non confermato","cell-switcher-not-active":"questa cella non è più attiva","cell-switcher-verify-failed":"Verifica non riuscita: riprova tra poco.","cell-switcher-select":"seleziona una cella","cell-switcher-open":"apri cella","cell-switcher-show-all":"tutte","cell-switcher-title":"Celle","cell-switcher-filter":"filtro: attive o tutte","cell-switcher-live-strip":"Live su {cell} · {mode}","cell-switcher-show-active":"attive","cell-switcher-close":"chiudi selettore celle","cell-switcher-here":"sei qui","fleet-not-available":"fleet non disponibile su questa posizione",start:"avvia",stop:"ferma",restart:"riavvia",delete:"elimina","copy-manual":"copia non riuscita — seleziona e Cmd+C, o copia a mano","copy-empty":"niente selezione: trascina con Shift per selezionare","selection-held":"evidenziazione persa, testo ancora in mano","selection-changed":"il testo sotto la selezione è cambiato","invite-hub-only":"Un invito si conia sull’hub. Ammettere un nodo nuovo è la sola cosa che un nodo collegato non può chiedere per conto di un altro: apri NexusCrew sull’hub e crea l’invito da lì.","row-private":"privato","node-detail-open":"apri il dettaglio","node-detail-reach":"Raggiungibilità","node-detail-route":"percorso","node-detail-ssh":"SSH","node-detail-transport":"trasporto","node-detail-owner":"owner","node-detail-authority":"Cosa può fare questo nodo","authority-owner-equivalent":"Autorità pari alla tua: un nodo accoppiato può fare su questa macchina tutto quello che puoi fare tu.","authority-routed":"Non è accoppiato con questa macchina: la sua autorità vive presso l’hub che lo instrada.","authority-no-grants":"L’unico potere per-nodo che esiste è la scelta delle celle, qui sotto. Dentro quelle celle l’autorità resta piena.","authority-no-grants-elsewhere":"L’unico potere per-nodo che esiste è la scelta delle celle, e si imposta sull’installazione che le possiede — non da qui.","node-detail-network-view":"Cosa vede di questa rete","node-detail-command":"Comando","vl-no-commands":"Il device non dichiara comandi disponibili.","vl-events-title":"Sessione","vl-events-empty":"Nessun evento in memoria: la sessione non ha ancora parlato, oppure quello che ha detto è uscito dal buffer. La storia resta sul device.","vl-events-gap":"eventi non ricevuti:","vl-events-truncated":"contenuto troncato dal device","vl-events-turn-end":"— fine turno —","vl-events-done":"— fine risposta —","vl-events-writer-epoch":"— cambio scrittore —","vl-events-tool":"strumento","vl-events-tool-ok":"concluso","vl-events-tool-failed":"fallito","vl-events-usage":"consumo aggiornato","vl-events-stale":"Aggiornamento non riuscito: quello che vedi potrebbe non essere l’ultimo.","vl-cmd-phase-submitted":"inviato, in attesa di conferma","vl-cmd-phase-inflight":"in corso","vl-cmd-phase-done-ok":"completato","vl-cmd-phase-done-error":"fallito","vl-cmd-status":"stato","vl-cmd-health":"salute","vl-cmd-start":"avvia","vl-cmd-stop":"ferma","vl-cmd-restart":"riavvia","vl-cmd-version":"versione","vl-cmd-capabilities":"capacità","vl-cmd-logs":"log","vl-cmd-prompt":"prompt","vl-prompt-placeholder":"scrivi il prompt per la sessione del device…","vl-prompt-send":"invia prompt","vl-cmd-unpair":"disaccoppia","node-grant-none":"Nessun nodo scelto: condiviso, ma verso nessuno.","node-grant-unknown":"non più in inventario","node-grant-remove":"togli","node-grant-add":"Aggiungi un nodo","node-grant-search":"Cerca fra i nodi","node-grant-no-candidates":"Nessun nodo corrisponde.","cell-scope":"Celle visibili a questo nodo","cell-scope-help":"Vale su cio’ che questo nodo elenca e su cio’ che può toccare, terminale compreso. Dentro le celle concesse resta un nodo accoppiato a pieno titolo: non è una sandbox.","cell-scope-all":"tutte le celle","cell-scope-none":"nessuna cella","cell-scope-selected":"celle selezionate","cell-scope-none-granted":"Nessuna cella scelta: questo nodo non ne vede nessuna.","cell-scope-unknown":"cella non più esistente","cell-scope-add":"Aggiungi una cella","cell-scope-search":"Cerca fra le celle","cell-scope-no-candidates":"Nessuna cella corrisponde.","cell-scope-reset-warning":"Cambiando modo l’elenco viene azzerato: tornando a «celle selezionate» andrà rifatto.","cell-scope-list-unavailable":"Elenco delle celle non disponibile ora: le concessioni qui sotto restano valide, ma non si può dire se esistono ancora.","feed-owner":"da nodo federato","ask-remote-readonly":"Risposta non concessa per questo nodo: card in sola lettura.","ask-capability-loading":"Verifica del permesso di risposta…","ask-capability-unreachable":"Percorso di risposta non raggiungibile.","ask-capability-unsupported":"Questo nodo non supporta la verifica del permesso di risposta.","ask-remote-no-feed":"Non ricevi gli eventi di questo nodo: attiva la ricezione (nodes edit <peer> --events-receive true).","ask-feed-stale":"Feed di questo nodo non attivo (dati non aggiornati): la card potrebbe essere già chiusa altrove.","ask-dismiss-stale":"Scarta comunque: lo scarto parte via relay diretto, ma finché il feed è fermo la card può non riflettere lo stato reale.","ask-uncertain":"Esito incerto: la risposta potrebbe essere arrivata. Verifica lo stato prima di riprovare.","ask-reconcile":"Risposta bloccata da un invio precedente: riconcilia con il nodo che ha fatto la domanda. Nessun nuovo invio.","ask-verify":"Verifica stato","peer-access":"Ruolo del peer","peer-access-help":"Cosa questo peer può fare su questa installazione. Il nome è derivato dai permessi effettivi: applicare un preset riscrive l’intero vettore in una sola scrittura.","peer-access-current":"Adesso","peer-access-preset":"Preset da applicare","peer-access-preset-none":"scegli un preset","peer-access-matrix":"Cosa cambierebbe","peer-access-apply":"Applica il preset","peer-access-changed-hint":"Le righe evidenziate cambiano con la conferma.","peer-access-unchanged":"Il preset non cambierebbe nulla.","peer-access-conflict":"Questo peer è stato modificato altrove: stato ricaricato, riapplica il preset se serve.","access-label-admin":"amministratore","access-label-user":"utente","access-label-nexushost":"nexushost","access-label-custom":"personalizzato","access-label-unconfigured":"non configurato","access-grant-cellVisibility":"Celle visibili","access-grant-eventsAccess":"Eventi","access-grant-eventsReceive":"Ricezione eventi e notifiche","access-grant-nodeEventsAccess":"Eventi di nodo","access-grant-askReplyAccess":"Risposte alle domande","access-grant-filesReadAccess":"Lettura file","access-grant-liveHostAccess":"Host Live","access-grant-panelAccess":"Pannelli","access-grant-peerOperatorAccess":"Operatore dei peer","access-value-all":"tutte","access-value-selected":"selezionate","access-value-none":"nessuna","access-value-yes":"sì","access-value-no":"no","single-view":"vista singola",retract:"riduci","keybar-expand":"espandi la barra tasti","keybar-retract":"riduci la barra tasti","save-and-start":"salva e avvia",permissions:"Permessi","power-on-hint":"Spegni la cella; puoi anche toglierla dal boot.","launch-engine-help":"Provider, credenziali e nuovi engine si creano in Impostazioni → Flotta. Modello e permessi sono per questa cella.","launch-unavailable-hint":"Configurazione engine non disponibile su questo nodo.","import-as-cell":"Importa come cella","import-help":"Riconcilia una sessione tmux esistente in una cella gestita. Scegli un engine già dichiarato: nessun engine viene inventato.","import-engine-required":"scegli un engine (obbligatorio)","test-and-connect":"testa e collega","pairing-v2-hint":"Incolla o scansiona UN solo link: precompila nome, Host SSH ed etichetta quando il link li include (v2).","invite-v2-hint":"Crea un invito monouso. Serve l’indirizzo SSH di questo dispositivo, raggiungibile da chi lo userà.","invite-target-local":"Il nuovo dispositivo entrerà in","invite-target-this":"questo dispositivo","invite-endpoint-label":"Indirizzo SSH di questo hub visto dagli altri dispositivi","invite-endpoint-auto":"Endpoint già configurato","invite-endpoint-needed":"Inserisci user@host o un alias SSH condiviso. Non è 127.0.0.1 e non è l’URL HTTP NexusCrew.","invite-ssh-hint":"Il target SSH con cui L’ALTRO dispositivo raggiunge QUESTA installazione (user@host o alias). Obbligatorio: viene incluso nel link.","invite-next-steps":"copia questo link, apri NexusCrew sull’altro dispositivo e incollalo in Impostazioni → Nodi (o scansiona il QR): al resto pensa NexusCrew","pair-card-title":"collega con un solo link","pair-card-help":"Incolla il link di pairing generato sull’altro dispositivo (o scansiona il suo QR): NexusCrew decodifica, prova la connessione SSH e collega da solo.","pair-paste-ph":"incolla qui il link di pairing","pair-paste-btn":"incolla","pair-advanced":"avanzate / modifica","pair-progress":"collegamento in corso: SSH → invito → conferma → verifica…","pair-retry":"riprova","pair-invalid-link":"questo non è un link di pairing valido","pair-invalid-hint":"serve il link completo (http://…#pair=…) generato dall’altro NexusCrew: non aprirlo, incollalo qui","pair-missing-ssh":"il link non include il target SSH (formato v1): indica in “avanzate” come questo dispositivo raggiunge l’altro via SSH — non viene mai inventato","pair-missing-name":"manca il nome del nodo: completalo in “avanzate”","pair-clipboard-denied":"lettura degli appunti non consentita: incolla manualmente nel campo","pair-clipboard-empty":"appunti vuoti: copia prima il link di pairing","pair-stage-validation":"dati non validi","pair-stage-conflict":"nome già in uso","pair-stage-ssh-start":"avvio del tunnel SSH fallito","pair-stage-ssh-ready":"peer non raggiungibile via SSH","pair-stage-join":"scambio dell’invito fallito","pair-stage-tunnel-final":"tunnel negoziato fallito","pair-stage-confirm":"conferma del pairing fallita","pair-stage-health":"verifica finale della federazione fallita","pair-stage-internal":"errore interno","pair-stage-generic":"connessione fallita","qr-no-camera":"nessuna camera disponibile su questo dispositivo: usa una foto del QR","qr-permission":"permesso camera negato: consentilo nel browser o usa una foto del QR","qr-unsupported":"scanner live non supportato qui: carica una foto del QR","qr-upload":"usa una foto"},en:{"update-available":"new version {v} available","update-stale":"interface out of step: you are running v{browser}, the node is serving v{ui}. reload without cache; if it persists, restart the node","reload-no-cache":"reload without cache","update-installed-restart":"version {v} installed: restart the node","update-dismiss":"close","install-version-mismatch":"incomplete installation: frontend and server do not match (v{v})",reload:"reload","grid-empty":"drag a session here from the sidebar, or double-click for single view","grid-full":"a deck can show at most 9 sessions",pin:"pin to top",reorder:"reorder","host-lease-live":"live host: supervision active","host-lease-grace":"live host: supervision recovering (grace)","host-lease-expired":"live host: supervision expired","host-lease-none":"live host: never supervised","host-lease-unavailable":"live host: supervision guarantee not available on this node","reorder-help":"drag the handle; keyboard up/down arrows","rename-node":"rename node","rename-node-prompt":"New node name in NexusCrew","rename-node-invalid":"Invalid name: maximum 64 characters, no line breaks.","reorder-deck-help":"drag the deck; keyboard left/right arrows",sessions:"sessions","new-session":"new session",new:"new",fleet:"Fleet","fleet-tmux":"tmux fleet","other-sessions":"Other sessions","view-all":"all","view-pinned":"pinned","view-active":"active","view-off":"off","view-technical":"technical","mark-technical":"hide as technical session","mark-normal":"show as normal session","position-local":"Local",files:"files",refresh:"refresh","filter-placeholder":"filter sessions…","loading-fleet":"loading fleet…","no-sessions":"no live tmux sessions — the fleet starts at boot (systemd)","no-match":'no session matches "{q}"',"copy-url":"click to copy URL","ssh-only":"SSH/VPN tunnel only","new-files-outbox":"new files in outbox",terminate:"terminate","terminate-confirm":'Terminate session "{name}"?',"cell-on":"tmux alive","cell-off":"off","node-sessions-unverified":"sessions not verified","tile-unverified":"data not verified","cell-working":"working","cell-idle":"idle","cell-stopped":"stopped","cell-permission":"permission required","cell-unknown":"unverified","cell-degraded":"degraded: unit active, tmux dead","power-on":"power on","power-off":"power off","boot-enable":"enable at boot","boot-disable":"disable at boot","state-on":"running","state-off":"stopped","power-starting":"starting…","power-stopping":"stopping…","fleet-up-slow":"start still in progress: check the cell state","fleet-down-slow":"stop still in progress: check the cell state","fleet-up-duplicate":"already running",engine:"Engine",model:"Model","model-default":"Provider default model","model-remembered":"Last model used with this engine","boot-persist":"start at boot","remove-boot":"also remove from boot","power-config-in-settings":"Edit engine, provider, profile, model and permissions in Settings → Fleet.","no-remote-control":"⚠ non-native engine: no claude.ai app RC (you can still drive it from here)",cancel:"cancel",name:"name","name-invalid":"invalid name: a-zA-Z0-9._- max 64, no leading '-'",cwd:"folder",browse:"browse","fs-home":"home","fs-parent":".. up",preset:"preset","preset-2x2":"2×2 grid","preset-columns":"columns","preset-equalize":"equalize",collapse:"collapse",expand:"expand",create:"create","auth-prompt":"Paste the token (printed by the server):","auth-invalid":"The node no longer accepts this token (rotated or replaced). Enter the new one: your preferences are left untouched.","auth-not-remembered":"The browser did not allow remembering the token on this device: you will have to enter it again next time.","remember-device":"remember on this device","zoom-out":"smaller text","zoom-in":"bigger text","dual-swap":"swap the two cells","dual-go-to":"Go to {cell}","dual-close":"close the second cell","dual-focus":"focused cell","terminal-renderer-webgl":"WebGL","terminal-renderer-dom":"DOM","terminal-renderer-switch":"graphics renderer: requested {requested}, in use {effective} — tap to switch (reloads the terminal)",composer:"composer",panel:"panel","panel-none":"No panel configured for this cell.","panel-checking":"Opening panel…","panel-not-granted":"This node does not grant the panel to the requester: access must be granted on the node that owns the cell, not by retrying here.","panel-denied":"Panel entry refused: the ticket is no longer valid. Retry: a new ticket will be requested.","cell-peek":"Peek without switching cell","cell-tele-ctx":"context","cell-tele-free":"free","cell-tele-5h":"5h used","cell-tele-7d":"7d used","cell-activity":"activity","cell-activity-now":"now","cell-peek-preview":"Preview","cell-peek-stream":"Stream","cell-peek-panel":"Panel","cell-peek-vuoto":"No preview available for this cell.","panel-node-refused":"The node that owns the cell refuses the request: it is read-only, or its policy blocks this operation. Retrying here does not change the outcome.","panel-unauthorized":"Invalid credential for this node: fix it where it is configured, not by retrying from here.","panel-unreachable":"The panel is not reachable through this node: retry in a little while.","panel-frame-loading":"panel mounted: loading in progress","panel-frame-error":"The panel frame did not load: the ticket may have expired (30 s lifetime, single-use) or the destination is unreachable. Retry: a fresh ticket will be requested.","popup-drag-hint":"drag to move; double-click to recenter","popup-resize-hint":"drag to resize","panel-timeout":"The panel did not answer in time: service slow to start or overloaded. Retry in a little while.","panel-retry":"Retry","live-host-indicator":"Live host: {cell} · {mode} · {state}","live-host-indicator-none":"Live host: no cell designated","live-host-remote":"other node","live-host-mode-native":"native (thread)","live-host-mode-tmux":"tmux","live-host-mode-unknown":"unknown mode","live-host-state-none":"no designation","live-host-state-designated":"designated, no thread","live-host-state-thread-present":"thread present but idle","live-host-state-thread-active":"thread active","live-host-state-thread-unknown":"thread status unknown","live-badge":"Live","live-badge-native":"Live active (native thread)","live-badge-tmux":"Live active in tmux mode: it does not receive messages","live-host-designated":"Live host: {cell}","live-host-cleared":"Live host removed","live-host-action-use":"Use as Live host","live-host-action-remove":"Remove Live host","cell-actions-title":"Actions for {cell}","cell-actions-open":"Cell actions","cell-actions-live-assign":"Assign Live","cell-actions-live-remove":"Remove Live","cell-actions-pin":"Pin to top","cell-actions-unpin":"Unpin from top","cell-actions-boot":"Boot at startup","cell-actions-watch":"Watch live","bar-menu-open":"More actions","bar-menu-keyboard":"On-screen keyboard","bar-menu-keyboard-desc":"below the terminal","bar-menu-files":"Cell files","bar-menu-files-desc":"inbox · outbox","bar-menu-files-setting-desc":"show the button in the bar","bar-menu-panel":"Cell panel","bar-menu-panel-desc":"only if the cell has one","bar-menu-renderer":"GPU renderer","bar-menu-renderer-desc":"switching reloads the page","bar-keyboard-button":"Keyboard button in the bar","bar-keyboard-button-desc":"show the on-screen keyboard button","bar-panel-button":"AI Desktop button in the bar","bar-panel-button-desc":"show the button if the cell has a panel","cell-switcher-group":"Cells {node}","cell-switcher-group-local":"local","cell-switcher-tap-hint":"Tap a cell for the preview · tap again to open it","cell-switcher-two-taps":"2 taps = open","cell-switcher-side-add":"open side by side","cell-switcher-side-remove":"remove from side by side","cell-switcher-preview-word":"PREVIEW","cell-switcher-preview-readonly":"read only","cell-peek-expand":"Open window","ai-desktop-title":"Graphical desktop","ai-desktop":"Graphical desktop enabled","ai-desktop-help":"The desktop container starts with the switch and stops without it; the panel button appears only while the desktop is running.","ai-desktop-confirm-stop":"The desktop is running: stopping it closes the sessions open in the container. Continue?","panel-start-desktop":"Start the desktop","live-host-stale-revision":"designation not applied: the state changed meanwhile, try again","live-host-not-local":"that cell does not belong to this node","live-host-unavailable":"fleet not available on this node, try again shortly","live-host-not-granted":"This node does not grant the live host cell designation to the requester: it must be granted on the node that owns the cell (nodes live-host <node> on), not by retrying here.","live-host-error":"The live host cell designation failed: retry in a little while.","host-thread-designated":"cell designated; thread absent","host-thread-present":"thread present but idle","host-thread-active":"thread active","host-thread-unknown":"thread status unknown",windows:"{n} windows","empty-files":"empty","files-download":"download file","files-download-action":"Download","files-outbox":"Outbox · {n}","files-inbox":"Inbox · {n}","files-search":"search files","files-search-ph":"search by name…","files-no-match":'no file matches "{q}"',"files-actions":"file actions","files-sheet-title":"File actions","files-original-name":"original name","files-preview":"Preview","files-preview-failed":"preview failed","files-preview-blocked":"preview unavailable for this type: download it","files-copy-name":"Copy full name","files-copied-name":"full name copied","files-delete-ellipsis":"Delete…","files-delete-confirm":'Delete "{name}"?',"files-delete-confirm-help":"The file is permanently deleted from the cell folder.","files-today":"Today","files-dupes":"{n} copies","files-of":"Files of {session}","files-upload":"Upload file","files-upload-failed":"upload error: {e}","files-filter-all":"All","files-filter-docs":"Documents","files-filter-images":"Images","files-open":"Open","files-detail-none":"Select a file to see its details.","files-meta-date":"Date","files-meta-size":"Size","files-meta-folder":"Folder","files-meta-type":"Type","files-footer-count":"{n} files · {size}","files-kbd-enter":"Enter","files-kbd-hint":"↑↓ moves the selection · {enter} opens actions · / searches","no-sessions-short":"no sessions","composer-placeholder":"type or dictate…","composer-history-tools":"input history and size","composer-history":"cell history","composer-history-empty":"no submitted input","composer-history-clear":"clear this cell history","composer-expand":"expand input","composer-collapse":"collapse input","composer-clear-data":"clear drafts and history","composer-clear-data-help":"Removes every saved cell draft and input-history entry from this browser.","composer-clear-confirm":"Clear every saved draft and input-history entry from this browser?","composer-clear-done":"Drafts and history cleared.","composer-clear-failed":"Could not clear composer data in this browser.",attach:"attach","attach-file":"File","attach-camera":"Camera","attach-gallery":"Gallery","attach-inbox":"Add Inbox","attach-inbox-done":"{n} file added to the inbox","attach-uploading":"uploading…","attach-upload-progress":"attachment {n}/{total}…","attach-uploaded":"{n} attachments uploaded",voice:"voice",send:"send","composer-send-failed":"connection not ready — text kept, try again",close:"close","lang-label":"language",decks:"decks","new-deck":"new deck","deck-name":"deck name","open-deck-window":"open in a new window","detach-deck":"detach into a new window","deck-current":"this deck (current window)","deck-stale":"refresh running late","deck-stale-badge":"running late","deck-owner-unavailable":"owner node is not shared or reachable","deck-owner-reconnecting":"reconnecting…","deck-owner-stale":"stale owner (cached route)","rename-deck":"rename deck","delete-deck":"delete deck","delete-deck-confirm":'Delete deck "{name}"?',"send-to-deck":"send to deck…","deck-autosave":"autosave",saving:"saving…",saved:"saved","popup-blocked":"popup blocked: open here","expand-owner":"expand {owner} decks","collapse-owner":"collapse {owner} decks","owner-deck-count-one":"{count} deck","owner-deck-count-many":"{count} decks","dot-working":"in use (active window)","dot-on":"open in background","dot-neutral":"not open","dot-warn":"owner offline","select-drag":"drag to select","copy-manual":"select and copy manually","toggle-sidebar":"show/hide the sidebar",settings:"settings","tab-roles":"roles","tab-nodes":"nodes",local:"Local",location:"Location","pairing-link":"pairing link","pairing-required":"name, SSH alias and pairing link are required","pairing-connect-help":"Connecting a node requires a name, a working SSH Host, and a link/QR created by the other NexusCrew installation.","pairing-localhost-hint":"127.0.0.1 in the link is correct: do not open it here. NexusCrew carries the invite and port through the SSH Host.","scan-qr":"scan QR","pairing-qr-invalid":"invalid pairing QR","invite-node":"invite a node","create-pairing-link":"create link / QR","visibility-network":"whole network","tile-detach":"Detach and float","tile-reattach":"Put back in the grid","tile-minimize":"Minimize","tile-restore":"Restore","grid-resize-cols":"Drag to resize the two columns; double click: half and half. Alt: no snapping.","grid-resize-rows":"Drag to resize the two windows; double click: half and half. Alt: no snapping.","visibility-relay":"relay only","device-name-ask-title":"What is this device called?","device-name-ask-text":"The name cannot be derived from the host: it labels your Locale node and introduces you to new nodes.","device-name-save":"Save name","device-name-later":"Later","wizard-device-name":"Name this device (you will see it as your Locale node; new nodes will use it).","visibility-selected":"selected nodes","hydra-simple":"local + nodes, one network","local-ready":"This device is ready. Use it alone or connect it to a node.","local-only":"local only","add-node":"add node",connect:"connect","node-connected":"Node connected. The network will synchronize automatically.","pair-authkeys-title":"Line to replace in ~/.ssh/authorized_keys on the peer","pair-authkeys-hint":"Without this line the panel forward stays refused: the tunnel looks up while the panel does not answer.","pair-authkeys-copy":"Copy the line","pair-authkeys-copied":"Line copied","tab-system":"system","tab-fleet":"fleet","tab-audio":"audio","system-general":"general","system-diagnostics":"diagnostics","system-this-node":"this node","system-updates":"updates","system-security":"security","system-local-data":"local browser data","system-terminal":"terminal","alternate-screen":"alternate screen","alternate-screen-help":"Keeps standard tmux behaviour for new NexusCrew sessions. An application that tracks the mouse scrolls on its own; the others browse the tmux scrollback. It does not change cells already running.","tab-input":"input","tab-diagnostics":"diagnostics","input-settings-local":"Local preferences for this browser. They apply immediately to single view and decks without changing the remote node.","terminal-keyboard-gesture":"Open the virtual keyboard from the terminal","terminal-keyboard-double-tap":"Double tap (default)","terminal-keyboard-single-tap":"Single tap","terminal-keyboard-never":"Never from terminal","terminal-keyboard-gesture-help":"The keypad and STT use the separate controls below. Mouse and physical keyboard remain available.","keybar-ime-lock":"Keypad: keep the virtual keyboard closed","keybar-ime-lock-help":"ESC, arrows, PgUp/PgDn, Enter and menu send directly to the PTY without focusing a text field.","voice-ime-lock":"STT microphone: keep the virtual keyboard closed","voice-ime-lock-help":"Tapping the microphone starts or stops voice without focusing the composer.","keybar-enter-show":"Show the tall Enter keypad key","keybar-enter-show-help":"Enter stays to the right of PgUp/PgDn and spans both rows.","keybar-layout":"Keypad layout","keybar-layout-full":"Full (default)","keybar-layout-compact":"Compact","keybar-layout-help":"Compact: one row with an expand toggle that reaches the full key set without changing the preference.","input-settings-reset":"restore input defaults","diagnostics-local":"This node","diagnostics-target":"Node to diagnose","diagnostics-verbose":"Temporary verbose logs","diagnostics-duration":"Verbose duration","diagnostics-expires":"Verbose enabled until {time}","diagnostics-off":"Verbose is off; operational warnings and errors remain available.","diagnostics-level":"Level","diagnostics-all-levels":"all levels","diagnostics-component":"component","diagnostics-pause":"pause","diagnostics-autoscroll":"autoscroll","diagnostics-log":"Sanitized diagnostic log","diagnostics-empty":"No diagnostic events.","diagnostics-export":"export JSON","diagnostics-export-failed":"Export is not available in this browser.","diagnostics-clear":"clear","diagnostics-clear-confirm":"Clear this node diagnostic buffer?","diagnostics-unsupported":"This peer is offline or does not support structured diagnostics.","fleet-editor-loading":"Loading the Fleet editor…","fleet-editor-load-error":"Unable to load the Fleet editor.","fleet-editor-unavailable":"The Fleet editor is unavailable at this location.","fleet-stale":"Fleet read failed: the cell list may not be up to date.","reorder-blocked":"Reorder not applied: the list is incomplete right now, your order is safe.","prefs-journal":"Preferences journal (last 50 writes)","prefs-journal-empty":"No changes recorded yet.","prefs-journal-copy":"Copy journal","prefs-journal-clear":"Clear journal","prefs-persist":"Persistent storage","prefs-persist-unknown":"not checked yet","prefs-before":"before","prefs-after":"after","prefs-visible":"visible","prefs-backup":"Preferences backup","prefs-sync":"Copy on the node","prefs-conflict":"This device's preferences and the copy on the node differ. Which one do you keep?","prefs-keep-local":"Keep this device","prefs-use-server":"Use server copy","prefs-export":"Export preferences","prefs-import":"Import preferences","prefs-export-done":"Preferences file created (no token inside).","prefs-import-done":"Preferences imported.","prefs-import-confirm":"Replace this device's preferences with the ones in the file?","prefs-import-wrong":"The file is not a NexusCrew preferences file.","prefs-import-bad":"The preferences file is not valid: nothing was imported.","prefs-import-storage":"The browser refused the write: nothing was imported and this device's preferences are untouched.","fleet-off":"Fleet unavailable: no cells.","fleet-managed":"managed by NexusCrew","fleet-custom":"custom command","fleet-managed-help":"Client, provider and launch are managed internally; secrets are never displayed.","fleet-vl-binary":"absolute path of the vl binary (empty = PATH)","fleet-vl-config-file":"shared vl profile catalog (config.toml, absolute path)","fleet-vl-profile":"vl profile (-p)","fleet-vl-effort":"effort (VL_EFFORT)","fleet-vl-fields-help":"Every vl cell gets its own state and config. Binary and catalog are paths on the node that runs the cell; profile and effort are validated at launch. No secrets here.","fleet-shell-engine-help":"The local shell is resolved on the device at launch time; no executable path is stored in backups.","fleet-shell-command-placeholder":"optional command, e.g. npm test","fleet-shell-command-help":"Runs through an interactive login shell (-lic), with the user PATH and aliases. The cell stops when the command finishes; immediate failures are reported.","fleet-shell-command-metachar":"Pipes, redirects, variables, and other metacharacters are interpreted by the device shell.","fleet-shell-interactive":"Empty: opens a local interactive shell and keeps the cell active.","fleet-shell-launch-help":"Configure the Shell command on the cell in Settings → Fleet.","fleet-credential-title":"API key on this device","fleet-credential-help":"The key stays only on the selected node and is never displayed or exported. If the node is remote, the value travels to it over the paired channel.","fleet-credential-set":"set key","fleet-credential-change":"change key","fleet-credential-forget":"forget","fleet-credential-saved":"Key saved locally.","fleet-credential-removed":"Local key removed.","fleet-credential-remove-confirm":"Remove the local {key} key?","fleet-credential-source-environment":"environment","fleet-credential-source-local":"local store","fleet-credential-source-compatibility":"compatible config","fleet-credential-source-missing":"missing","fleet-credential-source-providers-shell":"user shell","fleet-credential-source-keys-file":"keys file","fleet-credential-source-secure-file":"secure file (wins)","fleet-credential-source-legacy":"legacy file","fleet-credential-source-nexuscrew-store":"NexusCrew store","fleet-credential-source-unreadable":"unreadable","fleet-credential-source-login":"client login","fleet-credential-source-none":"none","fleet-credential-source-policy":"credential source","fleet-credential-source-policy-auto":"auto (legacy precedence)","fleet-credential-source-policy-nexuscrew-store":"NexusCrew store only","fleet-credential-source-policy-environment":"environment only","fleet-key-section":"KEY","fleet-key-variable":"Variable","fleet-key-value":"Value for {key}","fleet-key-used-by":"Used by: {engines}","fleet-key-used-by-none":"Not yet used by configured engines on this node.","fleet-key-shared-impact":"Replacing or removing {key} affects every listed engine: {engines}.","fleet-key-enter":"enter the key","fleet-key-blank-keeps":"blank = keep the current source","fleet-key-reveal":"reveal","fleet-key-hide":"hide","fleet-key-local-help":"The value stays write-only on the selected node: it is never read back over the network and never enters engines or backups. If the selected node is remote, the value reaches it over the paired channel.","fleet-key-create-missing":"Explicitly create the engine without a key (it will remain “key required”).","fleet-key-partial-create":"Engine created; the key was not saved. Retry without creating a duplicate.","fleet-key-partial-edit":"Engine updated; the key was not saved. The engine changes remain applied.","fleet-provider-notice-claude-openrouter":"Claude Code is optimized for Anthropic models; other providers may not work correctly. Fast mode requires the first-party Anthropic provider.","fleet-provider-notice-codex-openrouter":"OpenRouter Responses is beta and stateless; Codex-VL has no Chat Completions fallback.","fleet-provider-notice-claude-kimi-code":"Kimi Code uses isolated Claude configuration with dedicated onboarding and fast-mode flags; native Claude configuration is not modified, but its MCP tools are inherited.","fleet-provider-notice-alibaba-token-plan":"Token Plan Personal uses only ALIBABA_CODE_API_KEY from the local credential layer; qwen3.8-max is the default and no OpenAI/PAYG fallback is used.","fleet-provider-notice-kimi-native":'Native Kimi Code CLI uses the CLI login (device code) and its own configuration: NexusCrew never reads or copies credentials. Distinct from the Claude Code "Kimi Code" provider, which remains the managed K3 path.',"fleet-provider-notice-opencode-native":"Native OpenCode client: auth is delegated to the local opencode login (gateway free models answer even without a login). NexusCrew never reads or copies credentials and never writes your opencode.jsonc; models and MCP stay in the client configuration.","fleet-model-default":"default model (optional)","fleet-model-required":"model (required)","fleet-models-title":"Models","fleet-models-usable":"You can use these","fleet-models-refresh":"Update models","fleet-models-refreshing":"Updating…","fleet-models-loading":"Looking up this engine’s models…","fleet-models-error":"Model update failed (network or node): the editor stays usable","fleet-models-stale":"Stale data: showing the last successful fetch","fleet-models-unsupported":"This engine does not expose a model listing","fleet-models-none":"No models found","fleet-models-not-in-api":"not available in the APIs","fleet-models-use":"Use model {model}","fleet-models-cap":"Enable the models you want, within the {cap}-model-per-engine cap","fleet-models-field-context":"context","fleet-models-field-output":"output","fleet-models-field-tools":"tools","fleet-models-field-vision":"vision","fleet-models-field-reasoning":"reasoning","fleet-models-source-of":"source: {source}","fleet-models-source-user":"user","fleet-models-source-api":"API","fleet-models-source-public":"catalog","fleet-models-source-backup":"backup","fleet-models-missing-title":"Missing data","fleet-models-missing-why":"The engine needs a datum for {model} that no source provided:","fleet-models-missing-backup":"proposed backup: {value}","fleet-models-missing-user":"What you confirm becomes your own value: top precedence, never rewritten by discovery.","fleet-models-missing-confirm":"Confirm","fleet-models-missing-empty":"Leave empty","fleet-models-missing-open":"Missing data for {model}","fleet-models-default-badge":"models.dev · default","fleet-models-make-mine":"Make it mine","fleet-models-make-mine-field":"Make it mine: {field} of {model}","fleet-models-make-mine-row":"Make it mine: {model}","fleet-models-make-mine-title":"Confirm the values of {model}","fleet-models-make-mine-why":"What you confirm becomes your own declaration: it stays above the catalog and does not change on the next refresh.","fleet-models-make-mine-confirm":"Confirm","fleet-models-write-failed":"The write did not succeed: the values are still here.","fleet-models-value-absent":"Leave empty","fleet-models-value-true":"Yes","fleet-models-value-false":"No","fleet-models-auth-missing-key":"This model listing requires authentication: the {key} key is not configured on this node","fleet-models-auth-missing-key-anonymous":"This model listing requires authentication, but this engine requests it anonymously: no key is configured.","fleet-models-auth-key-rejected":"The submitted key was not accepted for the model listing.","fleet-models-auth-access-denied":"Access to the model listing was denied: it may be permissions or policy, not necessarily the key.","fleet-models-auth-credential-unavailable":"The key cannot be read or verified on this node: it is not known to be missing — it is unavailable.","fleet-models-auth-endpoint-unreachable":"Endpoint unreachable (network or timeout): this is not a key problem.","fleet-models-auth-provider-error":"The provider answered with an error for the model listing.","fleet-models-auth-invalid-response":"The provider response for the model listing is not valid.","fleet-models-auth-anonymous-success":"Model listing obtained without a key.","fleet-standard-permissions":"standard permissions","fleet-unsafe-permissions":"unsafe · bypass approvals/sandbox","fleet-unsafe-warning":"Explicit unsafe mode: the worker can act without normal approval or sandbox gates.","fleet-provider-display":"provider display name","fleet-custom-provider-default":"Custom provider","fleet-api-key-env":"API_KEY_ENV_NAME","fleet-provider-id":"provider-id","fleet-custom-secret-help":"NexusCrew stores only the environment-variable name, never its value.","cell-prompt":"Cell start-up prompt","cell-prompt-help":"Sent to the cell when it starts: this is its standing brief. Empty means no prompt — the cell just starts.","fleet-boot":"start at boot","fleet-remote-control":"remote control","cell-mcp":"MCP tools","cell-mcp-all":"all","cell-mcp-none":"none","cell-mcp-some":"chosen","cell-mcp-inert":"For this client, MCP tools are registered by the client in its own config, not NexusCrew: the selection here has no effect.","cell-mcp-help":"“All” is the long-standing behaviour. “None” is the only CERTAIN exclusion: it removes every tool and does not depend on where the servers are defined — that is what you want for a cell you do not trust. “Chosen” grants by name, but the list only covers servers this node can enumerate: plugins and connectors do not appear and would stay available.","fleet-model-override":"model override","fleet-ready":"ready","fleet-not-ready":"not configured","fleet-engines":"Engines","fleet-cells":"Cells / cloud sessions","fleet-engine-group-standard":"Standard","fleet-engine-group-other":"Other","fleet-models":"Declared models","fleet-no-models":"No declared model: the built-in catalog is used.","model-editor-engine":"Profile","model-editor-id":"Model id","model-editor-id-help":"The exact id the provider expects. Profile and id cannot be changed later: withdraw and declare again.","model-editor-context":"Context window (tokens)","model-editor-max-tokens":"Max output tokens","model-editor-reasoning":"Supports extended reasoning","model-editor-tools":"Supports tools","model-editor-vision":"Reads images","model-editor-absent":"Leave empty","model-editor-true":"Yes","model-editor-false":"No","model-editor-limit-invalid":"The window must be between 1024 and 100000000.","model-editor-effort-levels":"Declared effort levels","model-editor-effort-invalid":"Invalid levels: short lowercase tokens, no repeats.","fleet-models-field-effort":"Effort levels","model-test":"Test against the API","model-test-running":"Testing…","model-test-ok":"responds","model-test-unknown-model":"the provider does not know this id","model-test-auth":"credential missing or refused","model-test-unreachable":"endpoint unreachable","model-test-unverified":"not verified","model-test-unverified-help":"This does not mean it fails: this provider does not expose a model list, so the test could say neither yes nor no.","model-remove":"Withdraw","model-in-use":"in use","fleet-backup":"backup / restore","fleet-backup-help":"Selectively export or restore engines, cells, declared models, and system prompts. Tokens, API keys, and provider secrets never enter the file.","fleet-backup-export":"export","fleet-backup-import":"import","fleet-backup-download":"download backup","fleet-backup-restore":"restore selected","fleet-backup-import-help":"Choose a JSON backup, review the cells and select a destination engine before restoring.","fleet-backup-overwrite":"overwrites existing cell","fleet-backup-new":"new cell","fleet-backup-engine-missing":"choose an available engine","fleet-backup-restore-unavailable":"The selected node supports export only; update it to restore backups.","fleet-backup-restored":"{n} cells restored","fleet-backup-confirm-overwrite":"Overwrite these cells? {cells}","fleet-backup-needs-restart":"restart required: {cells}","fleet-backup-empty":"no cells to export","fleet-backup-select-one":"select at least one cell","fleet-backup-too-large":"backup is too large (1 MB maximum)","fleet-backup-invalid-json":"the file does not contain valid JSON","fleet-backup-invalid-format":"unsupported backup format or version","fleet-backup-invalid-cell":"the backup contains an invalid cell","fleet-backup-duplicate-cell":"the backup contains duplicate cell IDs","fleet-backup-invalid-engine":"the backup contains an invalid engine","fleet-backup-duplicate-engine":"the backup contains duplicate engine IDs","fleet-backup-invalid-model":"the backup contains an invalid model","fleet-backup-duplicate-model":"the backup contains duplicate models","fleet-backup-confirm-engine-overwrite":"Overwrite these engines? Environment values already configured on the target stay unchanged. {engines}","fleet-backup-env-names":"environment names","fleet-backup-env-values-required":"environment values must be configured on this device","fleet-system-prompt":"system prompt",characters:"characters","select-all":"select all","select-none":"select none",edit:"edit",save:"save",label:"label","command-path":"absolute command path","args-lines":"arguments, one per line","env-write-only":"Environment values are write-only: blank keeps the existing value.","fleet-new-engine":"New engine","fleet-new-cell":"New cell","fleet-saved":"Definition saved.","fleet-restart-confirm":"Change saved. Restart now: {cells}?","fleet-remove-engine":'Delete engine "{id}"?',"fleet-remove-cell":'Delete cell "{id}"? If active it will be stopped first.',"fleet-cwd-needs-repair":"folder needs repair","fleet-cwd-repair":"repair","fleet-cwd-repair-title":"Repair cell folder {id}","fleet-cwd-repair-help":"The current folder is not portable on this device: it belongs to another device or does not exist under the home directory. Choose a home-relative (~) folder on the target device; the backend will recompute the absolute path.","fleet-cwd-repair-no-source-path":"The original path is not shown: it is specific to the source device.","fleet-cwd-repair-placeholder":"e.g. Alpha","fleet-cwd-repair-preview":"New folder: {path}","fleet-cwd-repair-browse":"browse under ~","fleet-cwd-repair-fs-empty":"no subfolders","fleet-cwd-repair-use-current":"use this folder","fleet-cwd-repair-invalid":'invalid path: no absolute path, "..", backslash or drive letter',"fleet-cwd-repair-confirm":"Set the folder of cell {id} to {path}? It will be recomputed on the target device.","fleet-cwd-repair-unportable":"The chosen path is not portable on this device: it must exist under the home directory.","fleet-cwd-repair-suggestion":"Suggestion from device:","fleet-cwd-repair-use-suggestion":"use {path}","fleet-cwd-repaired":"Cell folder repaired.","fleet-recovery-kimi-code-consent-yes":"Kimi Code: confirm the custom API key (Yes) in the cell terminal, then restart the cell.","fleet-recovery-kimi-code-config-custom-api-key":'Kimi Code: in the cell terminal open /config and enable "Use custom API key", then restart the cell. If the key changed, update the credential and retry.',"fleet-recovery-kimi-cli-login":"Kimi Code CLI: in the cell terminal run /login (Kimi device code) or /provider, then restart the cell.","fleet-readiness-degraded":"Started without readiness confirmation: it may not process right away. Check its terminal before assigning work.","fleet-mcp-degraded":"Started degraded, MCP servers not ready:","fleet-vl-prompt-degraded":"Started without its cell prompt: the vl version on this node does not support it (0.3.1+ required). The cell works without its identity: upgrade vl before assigning work.","fleet-recovery-client-terminal-dialog":"Complete the dialog shown in the cell terminal, then restart the cell.","settings-readonly":"READONLY active: changes are blocked by the server (NEXUSCREW_READONLY=1)","role-client":"client (hub)","role-client-desc":"this machine watches other nodes via SSH tunnels","role-node":"node (reachable)","published-port":"published port (optional)","no-nodes":"no remote nodes configured","node-add":"connect a NexusCrew installation","node-connect-help":"The SSH port reaches the SSH server. The NexusCrew port is the local port reported by `nexuscrew status` on the remote node.","node-name-label":"Node name","node-ssh-label":"SSH host","pair-ssh-local-label":"SSH host or alias on this device","node-ssh-local-help":"You may replace the link address with the same alias that works with ssh on this device. Aliases, agents and private keys stay local and are never carried in the link.","node-ssh-port-label":"SSH port","node-ssh-port-help":"Usually 22; use the SSH server public port.","node-app-port-label":"NexusCrew port on node","node-app-port-help":"The port reported by `nexuscrew status` on the remote node.","node-name-ph":"name (a-z 0-9 -)","node-ssh-ph":"ssh (user@host)","node-port-ph":"remote port (opt.)","node-remove-confirm":'Remove node "{name}"?',"node-remove-warning":"Deletes the pairing, credentials and local tunnel. It does not power off the remote device.","peer-inventory-title":"Nodes connected to the hub","peer-group-hubs":"Direct hubs","peer-group-clients":"Connected clients","peer-group-routed":"Nodes reachable through the network","peer-group-vl":"VL nodes","vl-owners-unavailable":"VL owners unreachable","peer-routed":"routed","peer-routed-stale":"routed, unreachable","peer-visibility":"Network visibility","node-test":"test","tunnel-start":"start tunnel","tunnel-stop":"stop tunnel","tunnel-restart":"restart tunnel","share-node":"Share this node","share-local-heading":"Share this device","share-local-hub":"Sharing hub","share-local-through":"Share {device} through {hub}","share-local-active":"Shared and reachable by the network connected to the hub.","share-local-pending":"Sharing is requested, but the tunnel is down: this device is not reachable yet.","share-local-private":"Private: only this device can use its hub connection.","share-local-private-down":"Private, but the hub connection is down. Reconnect to apply and verify private mode.","share-local-reconnect":"Reconnect and reconcile","share-off-hub-reconcile-pending":"Private state saved; hub revocation is still pending.","fleet-cell-label":"readable name (optional)","fleet-panel-url":"Panel URL (optional)","fleet-panel-url-help":"Graphical panel endpoint for the cell (e.g. a container's noVNC): http/https only, toward a loopback host — the proxy resolves the destination on the machine that hosts the cell.","fleet-panel-url-invalid":"The panel is not a port-forward: whoever opens it picks which cell, never where to connect. The address is resolved on the machine that hosts the cell, so it must be reachable there on loopback — 127.0.0.1, localhost, or [::1]. A container's address (e.g. 172.17.0.2) is not.","share-off-local-reconcile-pending":"Hub revocation confirmed; the local tunnel still needs reconciliation.","share-reverse-pool-pending":"The reverse channel was not demonstrably shut down: it is quarantined, not closed.","share-node-off-desc":"Private: it stays connected to the hub, but other clients cannot reach it.","share-node-on-desc":"Shared: the hub may advertise it and route authorized cells and decks.","peer-shared":"Client node shared on the Hydra network","peer-private":"Private client node: connected, not published on Hydra","peer-vl-federated":"VL node: federated","row-vl-federated":"federated","node-connected-client":"connected client","transport-used":"in use","tunnel-up":"tunnel up","tunnel-down":"tunnel down","vl-poll-online":"online (poll)","vl-poll-offline":"not responding","authorized-keys-hint":"paste this line into ~/.ssh/authorized_keys on the remote host:",copy:"copy",copied:"copied","token-rotate":"rotate token","token-rotate-explain":"The new token will NOT be shown: retrieve it with `nexuscrew show token`. The current session will be invalidated.","service-regenerate":"regenerate service","npm-auto-update":"automatic updates from npm","npm-auto-update-help":"Periodically checks latest and installs only newer versions. Never downgrades.","npm-update-current":"installed","npm-update-latest":"npm latest","npm-update-check":"check now","npm-update-install":"update now","npm-update-restarting":"Update started; NexusCrew will return after the service restarts.","npm-update-idle":"up to date","npm-update-never":"never checked","npm-update-checking":"checking","npm-update-available":"update available","npm-update-installing":"installing","npm-update-installed":"installed, restarting","npm-update-error":"check failed","npm-update-unsupported":"available only for global npm installations","service-installed":"service installed","service-missing":"service not installed","service-active":"active","service-inactive":"not active",confirm:"confirm",add:"add",enable:"enable","wizard-title":"welcome to NexusCrew","wizard-skip":"configure later from settings","wizard-step-roles":"roles of this install","wizard-step-node":"first remote node (optional)","wizard-done":"all set","wizard-done-desc":"setup complete — you can change everything from settings",next:"continue",back:"back",skip:"skip",finish:"finish","err-node-name":"invalid name (a-z, 0-9, -, max 32)","err-local-name":"invalid local name: use a unique slug, not “localhost”","err-ssh":"invalid ssh (expected user@host or alias)","err-port":"invalid port (1–65535)","err-ssh-port":"invalid SSH port (1–65535)","err-node-port":"invalid NexusCrew port (1–65535)","node-sessions":"{n} sessions","tunnel-down-since":"tunnel down for {t}","node-unreachable":"node unreachable","peer-cause-assente":"peer not responding — waiting for it to come back (polls spaced out)","peer-cause-nega":"peer denies access — grant permission on the remote node","peer-cause-rotta":"route no longer exists on the peer — update the node","node-passive":"client offline · expected","node-offline":"node offline","node-offline-seen":"offline · seen {t} ago","node-needs-repair":"legacy · pair again","asks-title":"questions from the cells","remote-notices-title":"Notifications from other nodes","remote-notices-clear":"Clear","remote-notices-dismiss":"dismiss this notice","remote-notices-dismiss-failed":"dismissal not confirmed: the notice stays","remote-notices-clear-failed":"clear not confirmed: the notices stay","ask-dismiss":"Dismiss question","ask-dismiss-local":"Dismiss on this node","ask-dismiss-local-pending":"Closure on the origin node is pending","ask-dismiss-local-blocked":"Local dismissal only: remote closure is not authorized","ask-dismiss-unconfirmed":"Local dismissal was not confirmed: the question remains visible.","ask-reply-ph":"type your answer…","push-enable":"enable push notifications","push-disable":"disable push notifications","push-on":"push active on this device","push-local-off":"silence on this browser","push-local-on":"re-enable on this browser","push-local-help":"this browser only: the UI and the owner’s own notifications stay on","push-local-off-note":"system alerts off on this browser; the UI stays live","push-local-disabled":"push alerts are off on this browser: re-enable them here","push-off":"push not active","push-denied":"notification permission denied by the browser","push-unsupported":"push not supported in this browser","notification-speech-enable":"read notifications aloud","notification-speech-help":"Uses the browser voice only for new notifications while this PWA is visible and in the foreground. When the app is closed, the system notification remains available.","notification-speech-test":"test voice","notification-speech-testing":"testing voice…","notification-speech-preview":"NexusCrew. Spoken notifications are active.","notification-speech-preview-ok":"Voice test completed.","notification-speech-preview-failed":"The browser did not start the voice test. Interact with the page and try again.","notification-speech-preview-voice-error":"The voice test failed: voice or audio unavailable. Check the selected voice and try again.","notification-speech-preview-timeout":"The voice test failed: no response from the speech engine. Check the selected voice and try again.","notification-speech-needs-test":"For this app session, select “test voice” before spoken alerts can play.","notification-speech-unsupported":"Speech synthesis is not supported in this browser.","audio-title":"Native node audio","audio-help":"Consent and controls apply only to this device. Share and visibility do not authorize sounds.","audio-consent":"allow TTS on this node","audio-consent-help":"Allows authorized local or remote cells to deliver a voice command. You can revoke it at any time.","audio-capability":"Local capability","audio-loading":"reading local audio state…","audio-adapter":"adapter","audio-adapter-none":"none","audio-installed":"installed","audio-installed-yes":"yes","audio-installed-no":"no","audio-liveness":"availability","audio-liveness-ready":"ready to accept","audio-liveness-unavailable":"unavailable","audio-languages":"declared languages","audio-limits":"limits","audio-test":"test local audio","audio-testing":"testing audio…","audio-stop":"stop local audio","audio-stopping":"stopping audio…","audio-test-needs-consent":"Enable local consent before testing the voice.","audio-unavailable":"No native TTS adapter is available on this node.","audio-test-accepted":"The node accepted the test. It does not prove that anyone heard it.","audio-test-refused":"The node refused the test.","audio-test-unknown":"Test outcome unknown: the node could not confirm startup.","audio-stop-stopped":"Local audio stopped.","audio-stop-idle":"No local utterance to stop.","audio-groups-title":"Shared audio groups","audio-groups-help":"Chooses which devices play the voice when a cell speaks. A group is a local delivery preference, not consent. Each node keeps its own consent, ACL, availability and local Stop.","audio-groups-empty":"No group: voice plays only on this node.","audio-group-name":"group name","audio-group-mode":"delivery mode","audio-group-primary":"first available (in order)","audio-group-fanout":"all listed nodes","audio-group-targets":"exact target nodes","audio-group-local":"this node","audio-group-unavailable-target":"not currently discovered","audio-group-no-targets":"No node with an available instanceId. A group cannot use names, wildcards, or “all”.","audio-group-new":"new group","audio-group-edit":"edit","audio-group-delete":"delete","audio-group-save":"save group","audio-group-cancel":"cancel","audio-group-invalid":"A group needs a valid name and at least one exact nodeId.","audio-group-save-failed":"Could not save audio group.","node-display-label":"Name (label)","routed-node-aliases":"Routed node aliases","routed-node-aliases-help":"Visible only on this device; the route and remote name do not change.","node-local-alias":"Alias on this device","alias-on-device":"Alias on this device","reset-alias":"Reset remote name","node-slug-hint":"routing on slug: {slug}","device-name-label":"Device name","device-name-hint":"how peers see you (editable)","local-route-name-label":"Local / route name","local-route-name-hint":"stable technical handle: readable label + nodeId suffix; editable before connecting","err-label":"invalid label (max 64 chars, no line breaks)","fleet-inventory":"Cells and sessions","fleet-inventory-help":"all positions (Local + Hydra routes)","fleet-manage-location":"Manage location","fleet-network-overview":"Network overview","fleet-manage-help":"create and configure cells at the selected location","fleet-overview-help":"operational state of every location, separate from the editor","fleet-inventory-empty":"no cells or sessions","cell-switcher-refreshing":"refreshing cells…","cell-switcher-empty-active":"no verified active cells","cell-switcher-not-confirmed":"status not confirmed","cell-switcher-not-active":"this cell is no longer active","cell-switcher-verify-failed":"Could not verify: try again shortly.","cell-switcher-select":"select a cell","cell-switcher-open":"open cell","cell-switcher-show-all":"all","cell-switcher-title":"Cells","cell-switcher-filter":"filter: active or all","cell-switcher-live-strip":"Live on {cell} · {mode}","cell-switcher-show-active":"active","cell-switcher-close":"close cell switcher","cell-switcher-here":"you are here","fleet-not-available":"fleet not available on this position",start:"start",stop:"stop",restart:"restart",delete:"delete","copy-manual":"copy failed — select and press Cmd+C, or copy manually","copy-empty":"nothing selected: drag with Shift to select","selection-held":"highlight gone, text still held","selection-changed":"text under the selection changed","invite-hub-only":"An invite is minted on the hub. Admitting a new node is the one thing a connected node cannot ask on another’s behalf: open NexusCrew on the hub and create the invite there.","row-private":"private","node-detail-open":"open details","node-detail-reach":"Reachability","node-detail-route":"path","node-detail-ssh":"SSH","node-detail-transport":"transport","node-detail-owner":"owner","node-detail-authority":"What this node can do","authority-owner-equivalent":"Authority equal to yours: a paired node can do on this machine everything you can do.","authority-routed":"Not paired with this machine: its authority lives on the hub that routes it.","authority-no-grants":"The only per-node power that exists is the choice of cells, below. Within those cells the authority stays full.","authority-no-grants-elsewhere":"The only per-node power that exists is the choice of cells, and it is set on the installation that owns them — not here.","node-detail-network-view":"What it sees of this network","node-detail-command":"Command","vl-no-commands":"The device declares no commands available.","vl-events-title":"Session","vl-events-empty":"No events in memory: the session has not spoken yet, or what it said has left the buffer. The history stays on the device.","vl-events-gap":"events not received:","vl-events-truncated":"content truncated by the device","vl-events-turn-end":"— end of turn —","vl-events-done":"— turn complete —","vl-events-writer-epoch":"— writer changed —","vl-events-tool":"tool","vl-events-tool-ok":"finished","vl-events-tool-failed":"failed","vl-events-usage":"usage updated","vl-events-stale":"Refresh failed: what you see may not be the latest.","vl-cmd-phase-submitted":"sent, awaiting confirmation","vl-cmd-phase-inflight":"in progress","vl-cmd-phase-done-ok":"completed","vl-cmd-phase-done-error":"failed","vl-cmd-status":"status","vl-cmd-health":"health","vl-cmd-start":"start","vl-cmd-stop":"stop","vl-cmd-restart":"restart","vl-cmd-version":"version","vl-cmd-capabilities":"capabilities","vl-cmd-logs":"logs","vl-cmd-prompt":"prompt","vl-prompt-placeholder":"write the prompt for the device session…","vl-prompt-send":"send prompt","vl-cmd-unpair":"unpair","node-grant-none":"No node chosen: shared, but towards nobody.","node-grant-unknown":"no longer in the inventory","node-grant-remove":"remove","node-grant-add":"Add a node","node-grant-search":"Search the nodes","node-grant-no-candidates":"No node matches.","cell-scope":"Cells this node can see","cell-scope-help":"Applies to what this node lists and to what it can act on, terminal included. Within the granted cells it remains a fully paired node: this is not a sandbox.","cell-scope-all":"every cell","cell-scope-none":"no cell","cell-scope-selected":"selected cells","cell-scope-none-granted":"No cell chosen: this node sees none of them.","cell-scope-unknown":"cell no longer exists","cell-scope-add":"Add a cell","cell-scope-search":"Search the cells","cell-scope-no-candidates":"No cell matches.","cell-scope-reset-warning":"Switching mode clears the list: coming back to “selected cells” means choosing them again.","cell-scope-list-unavailable":"Cell list unavailable right now: the grants below still hold, but we cannot tell whether they still exist.","feed-owner":"from federated node","ask-remote-readonly":"Reply not granted for this node: card is read-only.","ask-capability-loading":"Checking reply permission…","ask-capability-unreachable":"Reply route is unreachable.","ask-capability-unsupported":"This owner does not support reply capability.","ask-remote-no-feed":"You are not receiving this node’s events: enable receiving (nodes edit <peer> --events-receive true).","ask-feed-stale":"This node’s feed is inactive (stale data): the card may already be closed elsewhere.","ask-dismiss-stale":"Dismiss anyway: the dismissal is forwarded directly to the node, but while the feed is down the card may not reflect the live state.","ask-uncertain":"Uncertain outcome: the answer may have arrived. Verify the status before retrying.","ask-reconcile":"Answer blocked by a previous send: reconcile with the asking node. No blind resend.","ask-verify":"Verify status","peer-access":"Peer role","peer-access-help":"What this peer may do on this installation. The name is derived from the effective grants: applying a preset rewrites the whole vector in one write.","peer-access-current":"Now","peer-access-preset":"Preset to apply","peer-access-preset-none":"pick a preset","peer-access-matrix":"What would change","peer-access-apply":"Apply the preset","peer-access-changed-hint":"The highlighted rows change on confirmation.","peer-access-unchanged":"The preset would change nothing.","peer-access-conflict":"This peer was changed elsewhere: state reloaded, apply the preset again if needed.","access-label-admin":"administrator","access-label-user":"user","access-label-nexushost":"nexushost","access-label-custom":"custom","access-label-unconfigured":"not configured","access-grant-cellVisibility":"Visible cells","access-grant-eventsAccess":"Events","access-grant-eventsReceive":"Receive events and notifications","access-grant-nodeEventsAccess":"Node events","access-grant-askReplyAccess":"Ask replies","access-grant-filesReadAccess":"File reading","access-grant-liveHostAccess":"Live host","access-grant-panelAccess":"Panels","access-grant-peerOperatorAccess":"Peer operator","access-value-all":"all","access-value-selected":"selected","access-value-none":"none","access-value-yes":"yes","access-value-no":"no","single-view":"single view",retract:"retract","keybar-expand":"expand the key bar","keybar-retract":"retract the key bar","save-and-start":"save and start",permissions:"Permissions","power-on-hint":"Stop the cell; you can also remove it from boot.","launch-engine-help":"Providers, credentials and new engines are created in Settings → Fleet. Model and permissions are per cell.","launch-unavailable-hint":"Engine configuration is unavailable on this node.","import-as-cell":"Import as cell","import-help":"Reconcile an existing tmux session into a managed cell. Pick an already-declared engine: no engine is invented.","import-engine-required":"pick an engine (required)","test-and-connect":"test and connect","pairing-v2-hint":"Paste or scan ONE link: it prefills name, SSH host and label when the link carries them (v2).","invite-v2-hint":"Create one one-time invitation. It needs this device’s SSH address, reachable by whoever will use it.","invite-target-local":"The new device will join","invite-target-this":"this device","invite-endpoint-label":"This hub’s SSH address as seen by other devices","invite-endpoint-auto":"Configured endpoint","invite-endpoint-needed":"Enter user@host or a shared SSH alias. This is not 127.0.0.1 and not the NexusCrew HTTP URL.","invite-ssh-hint":"The SSH target the OTHER device uses to reach THIS installation (user@host or alias). Required: it is included in the link.","invite-next-steps":"copy this link, open NexusCrew on the other device and paste it in Settings → Nodes (or scan the QR): NexusCrew does the rest","pair-card-title":"connect with one link","pair-card-help":"Paste the pairing link generated on the other device (or scan its QR): NexusCrew decodes it, tests the SSH connection and connects on its own.","pair-paste-ph":"paste the pairing link here","pair-paste-btn":"paste","pair-advanced":"advanced / edit","pair-progress":"connecting: SSH → invite → confirm → verify…","pair-retry":"retry","pair-invalid-link":"this is not a valid pairing link","pair-invalid-hint":"you need the full link (http://…#pair=…) generated by the other NexusCrew: don’t open it, paste it here","pair-missing-ssh":"the link carries no SSH target (v1 format): set in “advanced” how this device reaches the other one over SSH — it is never invented","pair-missing-name":"the node name is missing: fill it in “advanced”","pair-clipboard-denied":"clipboard read not allowed: paste manually into the field","pair-clipboard-empty":"clipboard is empty: copy the pairing link first","pair-stage-validation":"invalid data","pair-stage-conflict":"name already in use","pair-stage-ssh-start":"SSH tunnel start failed","pair-stage-ssh-ready":"peer unreachable over SSH","pair-stage-join":"invite exchange failed","pair-stage-tunnel-final":"negotiated tunnel failed","pair-stage-confirm":"pairing confirmation failed","pair-stage-health":"final federation check failed","pair-stage-internal":"internal error","pair-stage-generic":"connection failed","qr-no-camera":"no camera available on this device: use a photo of the QR","qr-permission":"camera permission denied: allow it in the browser or use a photo of the QR","qr-unsupported":"live scanner not supported here: upload a photo of the QR","qr-upload":"use a photo"},es:{"update-available":"nueva versión {v} disponible","update-stale":"interfaz desalineada: ejecutas la v{browser}, el nodo sirve la v{ui}. recarga sin caché; si persiste, reinicia el nodo","reload-no-cache":"recargar sin caché","update-installed-restart":"versión {v} instalada: reinicia el nodo","update-dismiss":"cerrar","install-version-mismatch":"instalación incompleta: frontend y servidor no coinciden (v{v})",reload:"recargar","grid-empty":"arrastra aquí una sesión desde la barra lateral, o doble clic para vista única","grid-full":"un deck puede mostrar como máximo 9 sesiones",pin:"fijar arriba",reorder:"reordenar","host-lease-live":"host live: supervisión activa","host-lease-grace":"host live: supervisión en recuperación (grace)","host-lease-expired":"host live: supervisión caducada","host-lease-none":"host live: nunca supervisada","host-lease-unavailable":"host live: garantía de supervisión no disponible en este nodo","reorder-help":"arrastra el control; flechas arriba/abajo","rename-node":"renombrar nodo","rename-node-prompt":"Nuevo nombre del nodo en NexusCrew","rename-node-invalid":"Nombre no válido: máximo 64 caracteres, sin saltos de línea.","reorder-deck-help":"arrastra el deck; flechas izquierda/derecha",sessions:"sesiones","new-session":"nueva sesión",new:"nueva",fleet:"Flota","fleet-tmux":"flota tmux","other-sessions":"Otras sesiones","view-all":"todas","view-pinned":"fijadas","view-active":"activas","view-off":"apagadas","view-technical":"técnicas","mark-technical":"ocultar como sesión técnica","mark-normal":"mostrar como sesión normal","position-local":"Local",files:"archivos",refresh:"actualizar","filter-placeholder":"filtrar sesiones…","loading-fleet":"cargando flota…","no-sessions":"sin sesiones tmux vivas — la flota arranca en el boot (systemd)","no-match":"ninguna sesión coincide con «{q}»","copy-url":"clic para copiar la URL","ssh-only":"solo túnel SSH/VPN","new-files-outbox":"archivos nuevos en outbox",terminate:"terminar","terminate-confirm":"¿Terminar la sesión «{name}»?","cell-on":"tmux activo","cell-off":"apagada","node-sessions-unverified":"sesiones sin verificar","tile-unverified":"dato sin verificar","cell-working":"trabajando","cell-idle":"en espera","cell-stopped":"parada","cell-permission":"esperando permiso","cell-unknown":"sin verificar","cell-degraded":"degradada: unit activa, tmux muerto","power-on":"encender","power-off":"apagar","boot-enable":"activar al iniciar","boot-disable":"desactivar al iniciar","state-on":"encendida","state-off":"apagada","power-starting":"iniciando…","power-stopping":"deteniendo…","fleet-up-slow":"inicio en curso: comprueba el estado","fleet-down-slow":"parada en curso: comprueba el estado","fleet-up-duplicate":"ya en ejecución",engine:"Motor",model:"Modelo","model-default":"Modelo predeterminado del proveedor","model-remembered":"Último modelo usado con este motor","boot-persist":"iniciar en el boot","remove-boot":"quitar también del boot","power-config-in-settings":"Modifica motor, proveedor, perfil, modelo y permisos en Ajustes → Flota.","no-remote-control":"⚠ motor no nativo: sin RC de la app claude.ai (aquí puedes pilotarla igual)",cancel:"cancelar",name:"nombre","name-invalid":"nombre inválido: a-zA-Z0-9._- máx 64, sin '-' inicial",cwd:"carpeta",browse:"explorar","fs-home":"home","fs-parent":".. arriba",preset:"preset","preset-2x2":"cuadrícula 2×2","preset-columns":"columnas","preset-equalize":"igualar",collapse:"contraer",expand:"expandir",create:"crear","auth-prompt":"Pega el token (impreso por el servidor):","auth-invalid":"El nodo ya no acepta este token (rotado o reemplazado). Introduce el nuevo: tus preferencias no se tocan.","auth-not-remembered":"El navegador no permitió recordar el token en este dispositivo: tendrás que introducirlo de nuevo la próxima vez.","remember-device":"recordar en este dispositivo","zoom-out":"texto más pequeño","zoom-in":"texto más grande","dual-swap":"intercambiar las dos celdas","dual-go-to":"Ir a {cell}","dual-close":"cerrar la segunda celda","dual-focus":"celda con el foco","terminal-renderer-webgl":"WebGL","terminal-renderer-dom":"DOM","terminal-renderer-switch":"motor gráfico: solicitado {requested}, en uso {effective} — toca para cambiar (recarga el terminal)",composer:"composer",panel:"panel","panel-none":"Ningún panel configurado para esta celda.","panel-checking":"Abriendo el panel…","panel-not-granted":"Este nodo no concede el panel a quien lo pide: el acceso se concede en el nodo que posee la celda, no reintentando aquí.","panel-denied":"Entrada al panel rechazada: el billete ya no es válido. Reintenta: se pedirá un billete nuevo.","cell-peek":"Echa un vistazo sin cambiar de celda","cell-tele-ctx":"contexto","cell-tele-free":"libre","cell-tele-5h":"5h usados","cell-tele-7d":"7d usados","cell-activity":"actividad","cell-activity-now":"ahora","cell-peek-preview":"Vista previa","cell-peek-stream":"Flujo","cell-peek-panel":"Panel","cell-peek-vuoto":"No hay vista previa para esta celda.","panel-node-refused":"El nodo que posee la celda rechaza la petición: está en solo lectura, o su política bloquea esta operación. Reintentar aquí no cambia el resultado.","panel-unauthorized":"Credencial no válida para este nodo: se corrige donde está configurada, no reintentando desde aquí.","panel-unreachable":"El panel no es accesible a través de este nodo: reintenta en un momento.","panel-frame-loading":"panel montado: carga en curso","panel-frame-error":"El frame del panel no se ha cargado: el billete puede haber caducado (30 s de vida, monouso) o el destino es inaccesible. Reintenta: se pedirá un billete nuevo.","popup-drag-hint":"arrastra para mover; doble clic para volver al centro","popup-resize-hint":"arrastra para redimensionar","panel-timeout":"El panel no respondió a tiempo: servicio lento en arrancar o sobrecargado. Reintenta en un momento.","panel-retry":"Reintentar","live-host-indicator":"Live host: {cell} · {mode} · {state}","live-host-indicator-none":"Live host: ninguna celda designada","live-host-remote":"otro nodo","live-host-mode-native":"nativa (thread)","live-host-mode-tmux":"tmux","live-host-mode-unknown":"modo desconocido","live-host-state-none":"sin designación","live-host-state-designated":"designada, sin thread","live-host-state-thread-present":"thread presente pero inactivo","live-host-state-thread-active":"thread activo","live-host-state-thread-unknown":"estado del thread desconocido","live-badge":"Live","live-badge-native":"Live activa (thread nativo)","live-badge-tmux":"Live activa en modo tmux: no recibe mensajes","live-host-designated":"Live host: {cell}","live-host-cleared":"Live host quitado","live-host-action-use":"Usar como host Live","live-host-action-remove":"Quitar host Live","cell-actions-title":"Acciones de {cell}","cell-actions-open":"Acciones de celda","cell-actions-live-assign":"Asignar Live","cell-actions-live-remove":"Quitar Live","cell-actions-pin":"Fijar arriba","cell-actions-unpin":"Quitar de arriba","cell-actions-boot":"Arranque al inicio","cell-actions-watch":"Ver en vivo","bar-menu-open":"Más acciones","bar-menu-keyboard":"Teclado en pantalla","bar-menu-keyboard-desc":"bajo el terminal","bar-menu-files":"Archivos de la celda","bar-menu-files-desc":"inbox · outbox","bar-menu-files-setting-desc":"muestra el botón en la barra","bar-menu-panel":"Panel de la celda","bar-menu-panel-desc":"solo si la celda tiene uno","bar-menu-renderer":"Renderer GPU","bar-menu-renderer-desc":"cambiarlo recarga la página","bar-keyboard-button":"Botón de teclado en la barra","bar-keyboard-button-desc":"muestra el botón del teclado en pantalla","bar-panel-button":"Botón de AI Desktop en la barra","bar-panel-button-desc":"muestra el botón si la celda tiene panel","cell-switcher-group":"Celdas {node}","cell-switcher-group-local":"local","cell-switcher-tap-hint":"Toca una celda para la vista previa · toca de nuevo para abrirla","cell-switcher-two-taps":"2 toques = abrir","cell-switcher-side-add":"abrir en paralelo","cell-switcher-side-remove":"quitar de la vista en paralelo","cell-switcher-preview-word":"VISTA PREVIA","cell-switcher-preview-readonly":"solo lectura","cell-peek-expand":"Abrir ventana","ai-desktop-title":"Escritorio gráfico","ai-desktop":"Escritorio gráfico activo","ai-desktop-help":"El contenedor del escritorio arranca con la casilla y se detiene sin ella; el botón del panel aparece solo con el escritorio activo.","ai-desktop-confirm-stop":"El escritorio está en ejecución: detenerlo cierra las sesiones abiertas en el contenedor. ¿Continuar?","panel-start-desktop":"Iniciar el escritorio","live-host-stale-revision":"designación no aplicada: el estado cambió mientras tanto, reintenta","live-host-not-local":"esa celda no pertenece a este nodo","live-host-unavailable":"flota no disponible en este nodo, reintenta en un momento","live-host-not-granted":"Este nodo no concede la designación de celda anfitriona Live a quien la pide: se concede en el nodo que posee la celda (nodes live-host <nodo> on), no reintentando aquí.","live-host-error":"La designación de celda anfitriona Live no funcionó: reintenta en un momento.","host-thread-designated":"celda designada; thread ausente","host-thread-present":"thread presente pero inactivo","host-thread-active":"thread activo","host-thread-unknown":"estado del thread desconocido",windows:"{n} ventanas","empty-files":"vacía","files-download":"descargar archivo","files-download-action":"Descargar","files-outbox":"Outbox · {n}","files-inbox":"Inbox · {n}","files-search":"buscar archivos","files-search-ph":"buscar por nombre…","files-no-match":'ningún archivo contiene "{q}"',"files-actions":"acciones del archivo","files-sheet-title":"Acciones del archivo","files-original-name":"nombre original","files-preview":"Vista previa","files-preview-failed":"vista previa no lograda","files-preview-blocked":"vista previa no disponible para este tipo: descárgalo","files-copy-name":"Copiar nombre completo","files-copied-name":"nombre completo copiado","files-delete-ellipsis":"Eliminar…","files-delete-confirm":'¿Eliminar "{name}"?',"files-delete-confirm-help":"El archivo se elimina definitivamente de la carpeta de la celda.","files-today":"Hoy","files-dupes":"{n} copias","files-of":"Archivos de {session}","files-upload":"Subir archivo","files-upload-failed":"error de subida: {e}","files-filter-all":"Todos","files-filter-docs":"Documentos","files-filter-images":"Imágenes","files-open":"Abrir","files-detail-none":"Selecciona un archivo para ver sus detalles.","files-meta-date":"Fecha","files-meta-size":"Tamaño","files-meta-folder":"Carpeta","files-meta-type":"Tipo","files-footer-count":"{n} archivos · {size}","files-kbd-enter":"Enter","files-kbd-hint":"↑↓ mueve la selección · {enter} abre acciones · / busca","no-sessions-short":"sin sesiones","composer-placeholder":"escribe o dicta…","composer-history-tools":"historial y tamaño de entrada","composer-history":"historial de la celda","composer-history-empty":"ninguna entrada enviada","composer-history-clear":"borrar historial de esta celda","composer-expand":"ampliar entrada","composer-collapse":"reducir entrada","composer-clear-data":"borrar borradores e historial","composer-clear-data-help":"Elimina de este navegador todos los borradores y el historial de entrada de las celdas.","composer-clear-confirm":"¿Borrar todos los borradores y el historial de entrada guardados en este navegador?","composer-clear-done":"Borradores e historial eliminados.","composer-clear-failed":"No se pudieron borrar los datos del composer en este navegador.",attach:"adjuntar","attach-file":"Archivo","attach-camera":"Cámara","attach-gallery":"Galería","attach-inbox":"Inbox","attach-inbox-done":"{n} archivos añadidos a la bandeja","attach-uploading":"subiendo…","attach-upload-progress":"adjunto {n}/{total}…","attach-uploaded":"{n} adjuntos subidos",voice:"voz",send:"enviar","composer-send-failed":"conexión no disponible — texto conservado, inténtalo de nuevo",close:"cerrar","lang-label":"idioma",decks:"decks","new-deck":"nuevo deck","deck-name":"nombre del deck","open-deck-window":"abrir en una ventana nueva","detach-deck":"separar en una ventana nueva","deck-current":"este deck (ventana actual)","deck-stale":"actualización con retraso","deck-stale-badge":"con retraso","deck-owner-unavailable":"el nodo propietario no está compartido o accesible","deck-owner-reconnecting":"reconectando…","deck-owner-stale":"owner stale (ruta en caché)","rename-deck":"renombrar deck","delete-deck":"eliminar deck","delete-deck-confirm":"¿Eliminar el deck «{name}»?","send-to-deck":"enviar al deck…","deck-autosave":"guardado automático",saving:"guardando…",saved:"guardado","popup-blocked":"ventana bloqueada: abrir aquí","expand-owner":"expandir decks de {owner}","collapse-owner":"comprimir decks de {owner}","owner-deck-count-one":"{count} deck","owner-deck-count-many":"{count} decks","dot-working":"en uso (ventana activa)","dot-on":"abierta en segundo plano","dot-neutral":"no abierta","dot-warn":"nodo sin conexión","select-drag":"arrastra para seleccionar","copy-manual":"selecciona y copia manualmente","toggle-sidebar":"mostrar/ocultar la barra lateral",settings:"ajustes","tab-roles":"roles","tab-nodes":"nodos",local:"Local",location:"Ubicación","pairing-link":"enlace de emparejamiento","pairing-required":"nombre, alias SSH y enlace son obligatorios","pairing-connect-help":"Para conectar un nodo necesitas un nombre, un Host SSH funcional y el enlace/QR creado por la otra instalación NexusCrew.","pairing-localhost-hint":"127.0.0.1 en el enlace es correcto: no lo abras aquí. NexusCrew usa la invitación y el puerto mediante el Host SSH.","tile-detach":"Desprender y flotar","tile-reattach":"Volver a la cuadrícula","tile-minimize":"Minimizar","tile-restore":"Restaurar","grid-resize-cols":"Arrastra para redimensionar las dos columnas; doble clic: mitad y mitad. Alt: sin imán.","grid-resize-rows":"Arrastra para redimensionar las dos ventanas; doble clic: mitad y mitad. Alt: sin imán.","scan-qr":"escanear QR","pairing-qr-invalid":"QR de emparejamiento no válido","device-name-ask-title":"¿Cómo se llama este dispositivo?","device-name-ask-text":"El nombre no se puede deducir del host: identifica tu nodo Locale y te presenta a los nodos nuevos.","device-name-save":"Guardar nombre","device-name-later":"Más tarde","wizard-device-name":"Ponle nombre a este dispositivo (lo verás como nodo Locale; los nodos nuevos lo usarán).","invite-node":"invitar un nodo","create-pairing-link":"crear enlace / QR","visibility-network":"toda la red","visibility-relay":"solo relay","visibility-selected":"nodos seleccionados","hydra-simple":"local + nodos, una red","local-ready":"Este dispositivo está listo. Úsalo solo o conéctalo a un nodo.","local-only":"solo local","add-node":"añadir nodo",connect:"conectar","node-connected":"Nodo conectado. La red se sincronizará automáticamente.","pair-authkeys-title":"Línea que hay que sustituir en ~/.ssh/authorized_keys del peer","pair-authkeys-hint":"Sin esta línea el reenvío del panel sigue rechazado: el túnel parece activo y el panel no responde.","pair-authkeys-copy":"Copiar la línea","pair-authkeys-copied":"Línea copiada","tab-system":"sistema","tab-fleet":"flota","tab-audio":"audio","system-general":"general","system-diagnostics":"diagnóstico","system-this-node":"este nodo","system-updates":"actualizaciones","system-security":"seguridad","system-local-data":"datos locales del navegador","system-terminal":"terminal","alternate-screen":"pantalla alternativa","alternate-screen-help":"Mantiene el comportamiento estándar de tmux para las nuevas sesiones NexusCrew. Una aplicación que sigue el ratón se desplaza sola; las demás recorren el historial de tmux. No modifica las celdas ya activas.","tab-input":"entrada","tab-diagnostics":"diagnóstico","input-settings-local":"Preferencias locales de este navegador. Se aplican de inmediato a la vista única y a los decks sin cambiar el nodo remoto.","terminal-keyboard-gesture":"Abrir el teclado virtual desde el terminal","terminal-keyboard-double-tap":"Doble toque (predeterminado)","terminal-keyboard-single-tap":"Toque único","terminal-keyboard-never":"Nunca desde el terminal","terminal-keyboard-gesture-help":"El teclado auxiliar y STT usan los controles separados de abajo. El ratón y el teclado físico siguen disponibles.","keybar-ime-lock":"Teclado auxiliar: mantener cerrado el teclado virtual","keybar-ime-lock-help":"ESC, flechas, PgUp/PgDn, Enter y menú envían directamente al PTY sin enfocar un campo de texto.","voice-ime-lock":"Micrófono STT: mantener cerrado el teclado virtual","voice-ime-lock-help":"Tocar el micrófono inicia o detiene la voz sin enfocar el compositor.","keybar-enter-show":"Mostrar Enter vertical en el teclado auxiliar","keybar-enter-show-help":"Enter queda a la derecha de PgUp/PgDn y ocupa las dos filas.","keybar-layout":"Distribución del teclado auxiliar","keybar-layout-full":"Completo (predeterminado)","keybar-layout-compact":"Compacto","keybar-layout-help":"Compacto: una fila con un botón expandir que alcanza el conjunto completo sin cambiar la preferencia.","input-settings-reset":"restaurar valores de entrada","diagnostics-local":"Este nodo","diagnostics-target":"Nodo a diagnosticar","diagnostics-verbose":"Logs detallados temporales","diagnostics-duration":"Duración detallada","diagnostics-expires":"Log detallado activo hasta las {time}","diagnostics-off":"El log detallado está apagado; los avisos y errores operativos siguen disponibles.","diagnostics-level":"Nivel","diagnostics-all-levels":"todos los niveles","diagnostics-component":"componente","diagnostics-pause":"pausa","diagnostics-autoscroll":"desplazamiento automático","diagnostics-log":"Log de diagnóstico sanitizado","diagnostics-empty":"No hay eventos de diagnóstico.","diagnostics-export":"exportar JSON","diagnostics-export-failed":"La exportación no está disponible en este navegador.","diagnostics-clear":"vaciar","diagnostics-clear-confirm":"¿Vaciar el búfer de diagnóstico de este nodo?","diagnostics-unsupported":"Este par está desconectado o no admite diagnósticos estructurados.","fleet-editor-loading":"Cargando el editor de Fleet…","fleet-editor-load-error":"No se puede cargar el editor de Fleet.","fleet-editor-unavailable":"El editor de Fleet no está disponible en esta ubicación.","fleet-stale":"Fallo de lectura de la flota: la lista de celdas puede no estar actualizada.","reorder-blocked":"Reordenación no aplicada: la lista está incompleta ahora, tu orden está a salvo.","prefs-journal":"Diario de preferencias (últimas 50 escrituras)","prefs-journal-empty":"Aún no hay cambios registrados.","prefs-journal-copy":"Copiar diario","prefs-journal-clear":"Vaciar diario","prefs-persist":"Almacenamiento persistente","prefs-persist-unknown":"sin comprobar","prefs-before":"antes","prefs-after":"después","prefs-visible":"visibles","prefs-backup":"Copia de preferencias","prefs-sync":"Copia en el nodo","prefs-conflict":"Las preferencias de este dispositivo y la copia del nodo difieren. ¿Cuál conservas?","prefs-keep-local":"Conservar este dispositivo","prefs-use-server":"Usar la copia del nodo","prefs-export":"Exportar preferencias","prefs-import":"Importar preferencias","prefs-export-done":"Archivo de preferencias creado (sin token).","prefs-import-done":"Preferencias importadas.","prefs-import-confirm":"¿Reemplazar las preferencias de este dispositivo con las del archivo?","prefs-import-wrong":"El archivo no es un archivo de preferencias de NexusCrew.","prefs-import-bad":"El archivo de preferencias no es válido: no se importó nada.","prefs-import-storage":"El navegador rechazó la escritura: no se importó nada y las preferencias de este dispositivo están intactas.","fleet-off":"Flota no disponible: sin celdas.","fleet-managed":"gestionado por NexusCrew","fleet-custom":"comando personalizado","fleet-managed-help":"Cliente, proveedor e inicio se gestionan internamente; los secretos nunca se muestran.","fleet-vl-binary":"ruta absoluta del binario vl (vacío = PATH)","fleet-vl-config-file":"catálogo de perfiles vl compartido (config.toml, ruta absoluta)","fleet-vl-profile":"perfil vl (-p)","fleet-vl-effort":"effort (VL_EFFORT)","fleet-vl-fields-help":"Cada celda vl tiene su propio estado y config. Binario y catálogo son rutas del nodo que ejecuta la celda; perfil y effort se validan al iniciar. Aquí no hay secretos.","fleet-shell-engine-help":"La shell local se resuelve en el dispositivo al iniciar; no se guarda ninguna ruta ejecutable en las copias.","fleet-shell-command-placeholder":"comando opcional, p. ej. npm test","fleet-shell-command-help":"Se ejecuta mediante una shell de inicio interactiva (-lic), con PATH y alias del usuario. La celda se detiene al terminar; los fallos inmediatos se notifican.","fleet-shell-command-metachar":"Pipes, redirecciones, variables y otros metacaracteres son interpretados por la shell del dispositivo.","fleet-shell-interactive":"Vacío: abre una shell local interactiva y mantiene la celda activa.","fleet-shell-launch-help":"Configura el comando Shell de la celda en Ajustes → Flota.","fleet-credential-title":"Clave API en este dispositivo","fleet-credential-help":"La clave permanece solo en el nodo seleccionado y nunca se muestra ni se exporta. Si el nodo es remoto, el valor viaja hasta él por el canal emparejado.","fleet-credential-set":"poner clave","fleet-credential-change":"cambiar clave","fleet-credential-forget":"olvidar","fleet-credential-saved":"Clave guardada localmente.","fleet-credential-removed":"Clave local eliminada.","fleet-credential-remove-confirm":"¿Eliminar la clave local {key}?","fleet-credential-source-environment":"entorno","fleet-credential-source-local":"almacén local","fleet-credential-source-compatibility":"config compatible","fleet-credential-source-missing":"ausente","fleet-credential-source-providers-shell":"shell del usuario","fleet-credential-source-keys-file":"archivo de claves","fleet-credential-source-secure-file":"archivo secure (prevale)","fleet-credential-source-legacy":"archivo legacy","fleet-credential-source-nexuscrew-store":"almacén NexusCrew","fleet-credential-source-unreadable":"no verificable","fleet-credential-source-login":"login del cliente","fleet-credential-source-none":"ninguna","fleet-credential-source-policy":"origen de credencial","fleet-credential-source-policy-auto":"auto (precedencia legacy)","fleet-credential-source-policy-nexuscrew-store":"solo almacén NexusCrew","fleet-credential-source-policy-environment":"solo entorno","fleet-key-section":"KEY","fleet-key-variable":"Variable","fleet-key-value":"Valor para {key}","fleet-key-used-by":"Usada por: {engines}","fleet-key-used-by-none":"Aún no la usa ningún motor configurado en este nodo.","fleet-key-shared-impact":"Sustituir o eliminar {key} afecta a todos los motores listados: {engines}.","fleet-key-enter":"introduce la clave","fleet-key-blank-keeps":"vacío = mantener la fuente actual","fleet-key-reveal":"mostrar","fleet-key-hide":"ocultar","fleet-key-local-help":"El valor permanece write-only en el nodo seleccionado: nunca se vuelve a leer desde la red ni entra en motores o copias. Si el nodo seleccionado es remoto, el valor llega a él por el canal emparejado.","fleet-key-create-missing":"Crear explícitamente el motor sin clave (seguirá como “clave requerida”).","fleet-key-partial-create":"Motor creado; la clave no se guardó. Puedes reintentar sin crear un duplicado.","fleet-key-partial-edit":"Motor actualizado; la clave no se guardó. Los cambios del motor siguen aplicados.","fleet-provider-notice-claude-openrouter":"Claude Code está optimizado para modelos Anthropic; otros proveedores podrían no funcionar correctamente. Fast mode requiere el proveedor Anthropic first-party.","fleet-provider-notice-codex-openrouter":"OpenRouter Responses es beta y stateless; Codex-VL no usa fallback de Chat Completions.","fleet-provider-notice-claude-kimi-code":"Kimi Code usa una configuración Claude aislada con onboarding y fast mode dedicados; la configuración Claude nativa no se modifica, pero sus herramientas MCP se heredan.","fleet-provider-notice-alibaba-token-plan":"Token Plan Personal usa solo ALIBABA_CODE_API_KEY de la capa local de credenciales; qwen3.8-max es el modelo predeterminado y no se usa fallback OpenAI/PAYG.","fleet-provider-notice-kimi-native":'Kimi Code CLI nativo usa el login del CLI (device-code) y su propia configuración: NexusCrew no lee ni copia credenciales. Distinto del proveedor "Kimi Code" de Claude Code, que sigue siendo la ruta K3 gestionada.',"fleet-provider-notice-opencode-native":"Cliente OpenCode nativo: la autenticación se delega al login local de opencode (los modelos free del gateway responden incluso sin login). NexusCrew no lee ni copia credenciales y no escribe tu opencode.jsonc; modelos y MCP quedan en la configuración del cliente.","fleet-model-default":"modelo predeterminado (opcional)","fleet-model-required":"modelo (obligatorio)","fleet-models-title":"Modelos","fleet-models-usable":"Puedes usar estos","fleet-models-refresh":"Actualizar los modelos","fleet-models-refreshing":"Actualizando…","fleet-models-loading":"Buscando los modelos de este motor…","fleet-models-error":"No se pudieron actualizar los modelos (red o nodo): el editor sigue siendo utilizable","fleet-models-stale":"Datos no actualizados: muestro la última lectura correcta","fleet-models-unsupported":"Este motor no expone una lista de modelos","fleet-models-none":"No se ha encontrado ningún modelo","fleet-models-not-in-api":"no disponible en las API","fleet-models-use":"Usar el modelo {model}","fleet-models-cap":"Se activan los modelos que quieras, dentro del límite de {cap} por motor","fleet-models-field-context":"contexto","fleet-models-field-output":"salida","fleet-models-field-tools":"herramientas","fleet-models-field-vision":"visión","fleet-models-field-reasoning":"razonamiento","fleet-models-source-of":"procedencia: {source}","fleet-models-source-user":"usuario","fleet-models-source-api":"API","fleet-models-source-public":"catálogo","fleet-models-source-backup":"reserva","fleet-models-missing-title":"Falta un dato","fleet-models-missing-why":"A {model} le falta un dato que el motor necesita:","fleet-models-missing-backup":"copia de seguridad propuesta: {value}","fleet-models-missing-user":"Lo que confirmas se convierte en tu valor: prioridad máxima, el descubrimiento nunca lo reescribe.","fleet-models-missing-confirm":"Confirmar","fleet-models-missing-empty":"Dejar vacío","fleet-models-missing-open":"Falta un dato de {model}","fleet-models-default-badge":"models.dev · default","fleet-models-make-mine":"Hazlo mío","fleet-models-make-mine-field":"Hazlo mío: {field} de {model}","fleet-models-make-mine-row":"Hazlo mío: {model}","fleet-models-make-mine-title":"Confirma los valores de {model}","fleet-models-make-mine-why":"Lo que confirmas se convierte en una declaración tuya: queda por encima del catálogo y no cambia en la próxima actualización.","fleet-models-make-mine-confirm":"Confirmar","fleet-models-write-failed":"La escritura no se completó: los valores siguen aquí.","fleet-models-value-absent":"Dejar vacío","fleet-models-value-true":"Sí","fleet-models-value-false":"No","fleet-models-auth-missing-key":"Esta lista de modelos requiere autenticación: la clave {key} no está configurada en este nodo","fleet-models-auth-missing-key-anonymous":"Esta lista de modelos requiere autenticación, pero este motor la pide de forma anónima: no hay clave configurada.","fleet-models-auth-key-rejected":"La clave enviada no fue aceptada para la lista de modelos.","fleet-models-auth-access-denied":"Se denegó el acceso a la lista de modelos: pueden ser permisos o políticas, no necesariamente la clave.","fleet-models-auth-credential-unavailable":"La clave no se puede leer ni verificar en este nodo: no consta que falte, no está disponible.","fleet-models-auth-endpoint-unreachable":"Punto de acceso inalcanzable (red o tiempo de espera): no es un problema de clave.","fleet-models-auth-provider-error":"El proveedor respondió con un error para la lista de modelos.","fleet-models-auth-invalid-response":"La respuesta del proveedor para la lista de modelos no es válida.","fleet-models-auth-anonymous-success":"Lista de modelos obtenida sin clave.","fleet-standard-permissions":"permisos estándar","fleet-unsafe-permissions":"inseguro · omitir aprobaciones/sandbox","fleet-unsafe-warning":"Modo inseguro explícito: el worker puede actuar sin las aprobaciones normales ni las protecciones del sandbox.","fleet-provider-display":"nombre visible del proveedor","fleet-custom-provider-default":"Proveedor personalizado","fleet-api-key-env":"NOMBRE_VARIABLE_API_KEY","fleet-provider-id":"id-proveedor","fleet-custom-secret-help":"NexusCrew guarda solo el nombre de la variable de entorno, nunca su valor.","cell-prompt":"Prompt de arranque de la celda","cell-prompt-help":"Se envía a la celda al arrancar: es su encargo permanente. Vacío = sin prompt, la celda solo arranca.","fleet-boot":"inicio automático","fleet-remote-control":"control remoto","cell-mcp":"Herramientas MCP","cell-mcp-all":"todas","cell-mcp-none":"ninguna","cell-mcp-some":"elegidas","cell-mcp-inert":"Para este cliente, las herramientas MCP las registra el cliente en su propia config, no NexusCrew: la selección aquí no tiene efecto.","cell-mcp-help":"«Todas» es el comportamiento de siempre. «Ninguna» es la única exclusión CIERTA: quita toda herramienta y no depende de dónde estén definidos los servidores — es lo que hace falta para una celda en la que no se confía. Con «elegidas» se concede por nombre, pero la lista solo cubre los servidores que este nodo puede enumerar: los plugins y conectores no aparecen y seguirían disponibles.","fleet-model-override":"modelo alternativo","fleet-ready":"listo","fleet-not-ready":"no configurado","fleet-engines":"Motores","fleet-cells":"Celdas / sesiones cloud","fleet-engine-group-standard":"Estándar","fleet-engine-group-other":"Otros","fleet-models":"Modelos declarados","fleet-no-models":"Ningún modelo declarado: se usa el catálogo interno.","model-editor-engine":"Perfil","model-editor-id":"Id del modelo","model-editor-id-help":"El id exacto que espera el proveedor. Perfil e id no se cambian después: se retira y se vuelve a declarar.","model-editor-context":"Ventana de contexto (tokens)","model-editor-max-tokens":"Máximo de tokens de salida","model-editor-reasoning":"Admite razonamiento extendido","model-editor-tools":"Admite herramientas","model-editor-vision":"Lee imágenes","model-editor-absent":"Dejar vacío","model-editor-true":"Sí","model-editor-false":"No","model-editor-limit-invalid":"La ventana debe estar entre 1024 y 100000000.","model-editor-effort-levels":"Niveles de effort declarados","model-editor-effort-invalid":"Niveles no conformes: tokens cortos en minúsculas, sin repeticiones.","fleet-models-field-effort":"Niveles de effort","model-test":"Probar contra la API","model-test-running":"Probando…","model-test-ok":"responde","model-test-unknown-model":"el proveedor no conoce este id","model-test-auth":"credencial ausente o rechazada","model-test-unreachable":"endpoint inalcanzable","model-test-unverified":"no verificado","model-test-unverified-help":"No significa que falle: este proveedor no expone la lista de modelos, así que la prueba no pudo decir ni sí ni no.","model-remove":"Retirar","model-in-use":"en uso","fleet-backup":"copia / restauración","fleet-backup-help":"Exporta o restaura selectivamente motores, celdas, modelos declarados y system prompts. Tokens, claves API y secretos del proveedor nunca entran en el archivo.","fleet-backup-export":"exportar","fleet-backup-import":"importar","fleet-backup-download":"descargar copia","fleet-backup-restore":"restaurar seleccionadas","fleet-backup-import-help":"Elige una copia JSON, revisa las celdas y selecciona un motor de destino antes de restaurar.","fleet-backup-overwrite":"sobrescribe la celda existente","fleet-backup-new":"celda nueva","fleet-backup-engine-missing":"elige un motor disponible","fleet-backup-restore-unavailable":"El nodo seleccionado solo admite exportación; actualízalo para restaurar copias.","fleet-backup-restored":"{n} celdas restauradas","fleet-backup-confirm-overwrite":"¿Sobrescribir estas celdas? {cells}","fleet-backup-needs-restart":"reinicio necesario: {cells}","fleet-backup-empty":"no hay celdas para exportar","fleet-backup-select-one":"selecciona al menos una celda","fleet-backup-too-large":"copia demasiado grande (máximo 1 MB)","fleet-backup-invalid-json":"el archivo no contiene JSON válido","fleet-backup-invalid-format":"formato o versión de copia no compatible","fleet-backup-invalid-cell":"la copia contiene una celda no válida","fleet-backup-duplicate-cell":"la copia contiene IDs de celda duplicados","fleet-backup-invalid-engine":"la copia contiene un motor no válido","fleet-backup-duplicate-engine":"la copia contiene IDs de motor duplicados","fleet-backup-invalid-model":"la copia contiene un modelo no válido","fleet-backup-duplicate-model":"la copia contiene modelos duplicados","fleet-backup-confirm-engine-overwrite":"¿Sobrescribir estos motores? Los valores de entorno ya configurados en el destino no cambian. {engines}","fleet-backup-env-names":"nombres de entorno","fleet-backup-env-values-required":"los valores de entorno deben configurarse en este dispositivo","fleet-system-prompt":"system prompt",characters:"caracteres","select-all":"seleccionar todas","select-none":"ninguna",edit:"editar",save:"guardar",label:"etiqueta","command-path":"ruta absoluta del comando","args-lines":"argumentos, uno por línea","env-write-only":"Los valores env son de solo escritura: vacío conserva el valor existente.","fleet-new-engine":"Nuevo motor","fleet-new-cell":"Nueva celda","fleet-saved":"Definición guardada.","fleet-restart-confirm":"Cambio guardado. ¿Reiniciar ahora: {cells}?","fleet-remove-engine":'¿Eliminar el motor "{id}"?',"fleet-remove-cell":'¿Eliminar la celda "{id}"? Si está activa se detendrá primero.',"fleet-cwd-needs-repair":"carpeta a reparar","fleet-cwd-repair":"reparar","fleet-cwd-repair-title":"Reparar carpeta de celda {id}","fleet-cwd-repair-help":"La carpeta actual no es portátil en este dispositivo: pertenece a otro dispositivo o no existe bajo el directorio home. Elige una carpeta relativa a home (~) en el dispositivo destino; el backend recalculará la ruta absoluta.","fleet-cwd-repair-no-source-path":"La ruta original no se muestra: es específica del dispositivo de origen.","fleet-cwd-repair-placeholder":"p. ej. Dev","fleet-cwd-repair-preview":"Nueva carpeta: {path}","fleet-cwd-repair-browse":"examinar bajo ~","fleet-cwd-repair-fs-empty":"sin subcarpetas","fleet-cwd-repair-use-current":"usar esta carpeta","fleet-cwd-repair-invalid":'ruta no válida: nada de ruta absoluta, "..", barra invertida ni letra de unidad',"fleet-cwd-repair-confirm":"¿Establecer la carpeta de la celda {id} a {path}? Se recalculará en el dispositivo destino.","fleet-cwd-repair-unportable":"La ruta elegida no es portátil en este dispositivo: debe existir bajo el directorio home.","fleet-cwd-repair-suggestion":"Sugerencia del dispositivo:","fleet-cwd-repair-use-suggestion":"usar {path}","fleet-cwd-repaired":"Carpeta de la celda reparada.","fleet-recovery-kimi-code-consent-yes":"Kimi Code: confirma la clave API personalizada (Yes) en el terminal de la celda, luego reinicia la celda.","fleet-recovery-kimi-code-config-custom-api-key":'Kimi Code: en el terminal de la celda abre /config y activa "Use custom API key", luego reinicia la celda. Si la clave cambió, actualiza la credencial y reintenta.',"fleet-recovery-kimi-cli-login":"Kimi Code CLI: en el terminal de la celda ejecuta /login (código de dispositivo Kimi) o /provider, luego reinicia la celda.","fleet-readiness-degraded":"Iniciada sin confirmación de preparación: puede que no procese de inmediato. Revisa su terminal antes de asignarle trabajo.","fleet-mcp-degraded":"Iniciada en degradación, servidores MCP no listos:","fleet-vl-prompt-degraded":"Iniciada sin el prompt de celda: la versión de vl en este nodo no lo admite (se requiere 0.3.1+). La celda trabaja sin su identidad: actualiza vl antes de asignarle trabajo.","fleet-recovery-client-terminal-dialog":"Completa el diálogo mostrado en el terminal de la celda, luego reinicia la celda.","settings-readonly":"READONLY activo: los cambios están bloqueados por el servidor (NEXUSCREW_READONLY=1)","role-client":"client (hub)","role-client-desc":"esta máquina observa otros nodos vía túneles SSH","role-node":"nodo (alcanzable)","published-port":"puerto publicado (opcional)","no-nodes":"sin nodos remotos configurados","node-add":"conectar una instalación NexusCrew","node-connect-help":"El puerto SSH conecta con el servidor SSH. El puerto NexusCrew es el puerto local indicado por `nexuscrew status` en el nodo remoto.","node-name-label":"Nombre del nodo","node-ssh-label":"Host SSH","pair-ssh-local-label":"Host o alias SSH en este dispositivo","node-ssh-local-help":"Puedes sustituir la dirección del enlace por el mismo alias que funciona con ssh en este dispositivo. Los alias, agentes y claves permanecen locales y nunca viajan en el enlace.","node-ssh-port-label":"Puerto SSH","node-ssh-port-help":"Normalmente 22; usa el puerto público del servidor SSH.","node-app-port-label":"Puerto NexusCrew del nodo","node-app-port-help":"El puerto indicado por `nexuscrew status` en el nodo remoto.","node-name-ph":"nombre (a-z 0-9 -)","node-ssh-ph":"ssh (user@host)","node-port-ph":"puerto remoto (opc.)","node-remove-confirm":"¿Eliminar el nodo «{name}»?","node-remove-warning":"Elimina el emparejamiento, las credenciales y el túnel local. No apaga el dispositivo remoto.","peer-inventory-title":"Nodos conectados al hub","peer-group-hubs":"Hubs directos","peer-group-clients":"Clientes conectados","peer-group-routed":"Nodos accesibles a través de la red","peer-group-vl":"Nodos VL","vl-owners-unavailable":"Owners VL no alcanzados","peer-routed":"enrutado","peer-routed-stale":"enrutado, no accesible","peer-visibility":"Visibilidad en la red","node-test":"test","tunnel-start":"iniciar túnel","tunnel-stop":"detener túnel","tunnel-restart":"reiniciar túnel","share-node":"Compartir este nodo","share-local-heading":"Compartir este dispositivo","share-local-hub":"Hub para compartir","share-local-through":"Compartir {device} mediante {hub}","share-local-active":"Compartido y accesible para la red conectada al hub.","share-local-pending":"Se solicitó compartir, pero el túnel está caído: este dispositivo aún no es accesible.","share-local-private":"Privado: solo este dispositivo puede usar la conexión al hub.","share-local-private-down":"Privado, pero la conexión al hub está caída. Reconecta para aplicar y verificar el modo privado.","share-local-reconnect":"Reconectar y reconciliar","share-off-hub-reconcile-pending":"Estado privado guardado; la revocación en el hub sigue pendiente.","fleet-cell-label":"nombre legible (opcional)","fleet-panel-url":"URL del panel (opcional)","fleet-panel-url-help":"Endpoint del panel gráfico de la celda (p. ej. el noVNC de un contenedor): solo http/https hacia un host loopback — el proxy resuelve el destino en la máquina que aloja la celda.","fleet-panel-url-invalid":"El panel no es un port-forward: quien lo abre elige qué celda, nunca dónde conectarse. La dirección se resuelve en la máquina que aloja la celda, así que debe ser alcanzable allí en loopback — 127.0.0.1, localhost o [::1]. La dirección de un contenedor (p. ej. 172.17.0.2) no lo es.","share-off-local-reconcile-pending":"Revocación confirmada por el hub; el túnel local aún debe reconciliarse.","share-reverse-pool-pending":"El canal inverso no se apagó de forma demostrable: queda en cuarentena, no cerrado.","share-node-off-desc":"Privado: sigue conectado al hub, pero otros clientes no pueden alcanzarlo.","share-node-on-desc":"Compartido: el hub puede anunciarlo y enrutar celdas y decks autorizados.","peer-shared":"Nodo cliente compartido en la red Hydra","peer-private":"Nodo cliente privado: conectado, no publicado en Hydra","peer-vl-federated":"Nodo VL: federado","row-vl-federated":"federado","node-connected-client":"cliente conectado","transport-used":"en uso","tunnel-up":"túnel activo","tunnel-down":"túnel caído","vl-poll-online":"en línea (poll)","vl-poll-offline":"sin respuesta","authorized-keys-hint":"pega esta línea en ~/.ssh/authorized_keys del host remoto:",copy:"copiar",copied:"copiado","token-rotate":"rotar token","token-rotate-explain":"El nuevo token NO se mostrará: recupéralo con `nexuscrew show token`. La sesión actual quedará invalidada.","service-regenerate":"regenerar service","npm-auto-update":"actualizaciones automáticas desde npm","npm-auto-update-help":"Comprueba latest periódicamente e instala solo versiones más recientes. Nunca baja de versión.","npm-update-current":"instalada","npm-update-latest":"npm latest","npm-update-check":"comprobar ahora","npm-update-install":"actualizar ahora","npm-update-restarting":"Actualización iniciada; NexusCrew volverá después de reiniciar el servicio.","npm-update-idle":"actualizado","npm-update-never":"nunca comprobado","npm-update-checking":"comprobando","npm-update-available":"actualización disponible","npm-update-installing":"instalando","npm-update-installed":"instalada, reiniciando","npm-update-error":"comprobación fallida","npm-update-unsupported":"disponible solo con instalación npm global","service-installed":"service instalado","service-missing":"service no instalado","service-active":"activo","service-inactive":"no activo",confirm:"confirmar",add:"añadir",enable:"activar","wizard-title":"bienvenido a NexusCrew","wizard-skip":"configura después desde ajustes","wizard-step-roles":"roles de esta instalación","wizard-step-node":"primer nodo remoto (opcional)","wizard-done":"todo listo","wizard-done-desc":"configuración completa — puedes cambiarlo todo desde ajustes",next:"continuar",back:"atrás",skip:"omitir",finish:"terminar","err-node-name":"nombre inválido (a-z, 0-9, -, máx 32)","err-local-name":"nombre local inválido: usa un slug único, no “localhost”","err-ssh":"ssh inválido (se espera user@host o alias)","err-port":"puerto inválido (1–65535)","err-ssh-port":"puerto SSH inválido (1–65535)","err-node-port":"puerto NexusCrew inválido (1–65535)","node-sessions":"{n} sesiones","tunnel-down-since":"túnel caído desde hace {t}","node-unreachable":"nodo inalcanzable","peer-cause-assente":"el peer no responde — esperando a que vuelva (consultas espaciadas)","peer-cause-nega":"el peer deniega el acceso — concede el permiso en el nodo remoto","peer-cause-rotta":"la ruta ya no existe en el peer — actualiza el nodo","node-passive":"cliente desconectado · estado normal","node-offline":"nodo desconectado","node-offline-seen":"sin conexión · visto hace {t}","node-needs-repair":"legacy · vuelve a enlazar","asks-title":"preguntas de las celdas","remote-notices-title":"Notificaciones de otros nodos","remote-notices-clear":"Limpiar","remote-notices-dismiss":"descartar esta notificación","remote-notices-dismiss-failed":"descarte no confirmado: la notificación permanece","remote-notices-clear-failed":"limpieza no confirmada: las notificaciones permanecen","ask-dismiss":"Descartar la pregunta","ask-dismiss-local":"Descartar en este nodo","ask-dismiss-local-pending":"Cierre en el nodo de origen pendiente","ask-dismiss-local-blocked":"Descarte solo local: el cierre remoto no está autorizado","ask-dismiss-unconfirmed":"Descarte local no confirmado: la pregunta sigue visible.","ask-reply-ph":"escribe la respuesta…","push-enable":"activar notificaciones push","push-disable":"desactivar notificaciones push","push-on":"push activas en este dispositivo","push-local-off":"silenciar en este navegador","push-local-on":"reactivar en este navegador","push-local-help":"solo este navegador: la UI y las notificaciones del owner siguen activas","push-local-off-note":"avisos del sistema apagados en este navegador; la UI sigue activa","push-local-disabled":"los avisos push están apagados en este navegador: reactívalos aquí","push-off":"push no activas","push-denied":"permiso de notificaciones denegado por el navegador","push-unsupported":"push no soportadas en este navegador","notification-speech-enable":"leer las notificaciones en voz alta","notification-speech-help":"Usa la voz del navegador solo para notificaciones nuevas mientras esta PWA está visible y en primer plano. Con la aplicación cerrada permanece la notificación del sistema.","notification-speech-test":"probar voz","notification-speech-testing":"probando voz…","notification-speech-preview":"NexusCrew. Las notificaciones por voz están activas.","notification-speech-preview-ok":"Prueba de voz completada.","notification-speech-preview-failed":"El navegador no inició la prueba de voz. Interactúa con la página y vuelve a intentarlo.","notification-speech-preview-voice-error":"La prueba de voz falló: voz o audio no disponibles. Comprueba la voz seleccionada e inténtalo de nuevo.","notification-speech-preview-timeout":"La prueba de voz falló: sin respuesta del motor de voz. Comprueba la voz seleccionada e inténtalo de nuevo.","notification-speech-needs-test":"Para esta sesión de la aplicación, pulsa “probar voz” antes de recibir avisos hablados.","notification-speech-unsupported":"La síntesis de voz no está disponible en este navegador.","audio-title":"Audio nativo del nodo","audio-help":"El consentimiento y los controles valen solo para este dispositivo. Compartir y visibilidad no autorizan sonidos.","audio-consent":"permitir TTS en este nodo","audio-consent-help":"Permite que celdas autorizadas, locales o remotas, entreguen un comando de voz. Puedes revocarlo en cualquier momento.","audio-capability":"Capacidad local","audio-loading":"leyendo el estado de audio local…","audio-adapter":"adaptador","audio-adapter-none":"ninguno","audio-installed":"instalado","audio-installed-yes":"sí","audio-installed-no":"no","audio-liveness":"disponibilidad","audio-liveness-ready":"listo para aceptar","audio-liveness-unavailable":"no disponible","audio-languages":"idiomas declarados","audio-limits":"límites","audio-test":"probar audio local","audio-testing":"probando audio…","audio-stop":"detener audio local","audio-stopping":"deteniendo audio…","audio-test-needs-consent":"Activa el consentimiento local antes de probar la voz.","audio-unavailable":"No hay un adaptador TTS nativo disponible en este nodo.","audio-test-accepted":"El nodo aceptó la prueba. No demuestra que alguien la haya oído.","audio-test-refused":"El nodo rechazó la prueba.","audio-test-unknown":"Resultado de prueba desconocido: el nodo no pudo confirmar el inicio.","audio-stop-stopped":"Audio local detenido.","audio-stop-idle":"No hay enunciado local que detener.","audio-groups-title":"Grupos de audio compartido","audio-groups-help":"Decide en qué dispositivos se oye la voz cuando habla una celda. Un grupo es una preferencia local de entrega, no un consentimiento. Cada nodo conserva su consentimiento, ACL, disponibilidad y Stop local.","audio-groups-empty":"Sin grupos: la voz sale solo por este nodo.","audio-group-name":"nombre del grupo","audio-group-mode":"modo de entrega","audio-group-primary":"primero disponible (en orden)","audio-group-fanout":"todos los nodos enumerados","audio-group-targets":"nodos destino exactos","audio-group-local":"este nodo","audio-group-unavailable-target":"no detectado ahora","audio-group-no-targets":"No hay ningún nodo con instanceId disponible. Un grupo no puede usar nombres, comodines ni “todos”.","audio-group-new":"nuevo grupo","audio-group-edit":"editar","audio-group-delete":"eliminar","audio-group-save":"guardar grupo","audio-group-cancel":"cancelar","audio-group-invalid":"El grupo necesita un nombre válido y al menos un nodeId exacto.","audio-group-save-failed":"No se pudo guardar el grupo de audio.","node-display-label":"Nombre (etiqueta)","routed-node-aliases":"Alias de nodos enrutados","routed-node-aliases-help":"Visibles solo en este dispositivo; la ruta y el nombre remoto no cambian.","node-local-alias":"Alias en este dispositivo","alias-on-device":"Alias en este dispositivo","reset-alias":"Restablecer nombre remoto","node-slug-hint":"enrutado por slug: {slug}","device-name-label":"Nombre del dispositivo","device-name-hint":"cómo te ven los pares (editable)","local-route-name-label":"Nombre local / ruta","local-route-name-hint":"identificador técnico estable: etiqueta legible + sufijo del nodeId; editable antes de conectar","err-label":"etiqueta no válida (máx 64 caracteres, sin saltos de línea)","fleet-inventory":"Celdas y sesiones","fleet-inventory-help":"todas las posiciones (Local + rutas Hydra)","fleet-manage-location":"Gestionar ubicación","fleet-network-overview":"Vista de red","fleet-manage-help":"crea y configura celdas en la ubicación seleccionada","fleet-overview-help":"estado operativo de todas las ubicaciones, separado del editor","fleet-inventory-empty":"sin celdas ni sesiones","cell-switcher-refreshing":"actualizando celdas…","cell-switcher-empty-active":"no hay celdas activas verificadas","cell-switcher-not-confirmed":"estado sin confirmar","cell-switcher-not-active":"esta celda ya no está activa","cell-switcher-verify-failed":"No se pudo verificar: inténtalo de nuevo dentro de poco.","cell-switcher-select":"selecciona una celda","cell-switcher-open":"abrir celda","cell-switcher-show-all":"todas","cell-switcher-title":"Celdas","cell-switcher-filter":"filtro: activas o todas","cell-switcher-live-strip":"Live en {cell} · {mode}","cell-switcher-show-active":"activas","cell-switcher-close":"cerrar selector de celdas","cell-switcher-here":"estás aquí","fleet-not-available":"fleet no disponible en esta posición",start:"iniciar",stop:"detener",restart:"reiniciar",delete:"eliminar","copy-manual":"copia fallida — selecciona y pulsa Cmd+C, o copia a mano","copy-empty":"nada seleccionado: arrastra con Shift para seleccionar","selection-held":"resaltado perdido, texto aún retenido","selection-changed":"el texto bajo la selección cambió","invite-hub-only":"Una invitación se acuña en el hub. Admitir un nodo nuevo es lo único que un nodo conectado no puede pedir en nombre de otro: abre NexusCrew en el hub y créala allí.","row-private":"privado","node-detail-open":"abrir el detalle","node-detail-reach":"Alcanzabilidad","node-detail-route":"ruta","node-detail-ssh":"SSH","node-detail-transport":"transporte","node-detail-owner":"propietario","node-detail-authority":"Qué puede hacer este nodo","authority-owner-equivalent":"Autoridad igual a la tuya: un nodo emparejado puede hacer en esta máquina todo lo que puedes hacer tú.","authority-routed":"No está emparejado con esta máquina: su autoridad vive en el hub que lo enruta.","authority-no-grants":"El único poder por nodo que existe es la elección de celdas, más abajo. Dentro de esas celdas la autoridad sigue siendo plena.","authority-no-grants-elsewhere":"El único poder por nodo que existe es la elección de celdas, y se configura en la instalación que las posee — no aquí.","node-detail-network-view":"Qué ve de esta red","node-detail-command":"Comando","vl-no-commands":"El dispositivo no declara comandos disponibles.","vl-events-title":"Sesión","vl-events-empty":"Ningún evento en memoria: la sesión aún no ha hablado, o lo que dijo ha salido del búfer. El historial queda en el dispositivo.","vl-events-gap":"eventos no recibidos:","vl-events-truncated":"contenido truncado por el dispositivo","vl-events-turn-end":"— fin del turno —","vl-events-done":"— fin de la respuesta —","vl-events-writer-epoch":"— cambio de escritor —","vl-events-tool":"herramienta","vl-events-tool-ok":"terminada","vl-events-tool-failed":"fallida","vl-events-usage":"consumo actualizado","vl-events-stale":"Actualización fallida: puede que no estés viendo lo último.","vl-cmd-phase-submitted":"enviado, a la espera de confirmación","vl-cmd-phase-inflight":"en curso","vl-cmd-phase-done-ok":"completado","vl-cmd-phase-done-error":"fallido","vl-cmd-status":"estado","vl-cmd-health":"salud","vl-cmd-start":"iniciar","vl-cmd-stop":"detener","vl-cmd-restart":"reiniciar","vl-cmd-version":"versión","vl-cmd-capabilities":"capacidades","vl-cmd-logs":"logs","vl-cmd-prompt":"prompt","vl-prompt-placeholder":"escribe el prompt para la sesión del dispositivo…","vl-prompt-send":"enviar prompt","vl-cmd-unpair":"desemparejar","node-grant-none":"Ningún nodo elegido: compartido, pero hacia nadie.","node-grant-unknown":"ya no está en el inventario","node-grant-remove":"quitar","node-grant-add":"Añadir un nodo","node-grant-search":"Buscar entre los nodos","node-grant-no-candidates":"Ningún nodo coincide.","cell-scope":"Celdas visibles para este nodo","cell-scope-help":"Se aplica a lo que este nodo lista y a lo que puede tocar, incluido el terminal. Dentro de las celdas concedidas sigue siendo un nodo emparejado por completo: no es un sandbox.","cell-scope-all":"todas las celdas","cell-scope-none":"ninguna celda","cell-scope-selected":"celdas seleccionadas","cell-scope-none-granted":"Ninguna celda elegida: este nodo no ve ninguna.","cell-scope-unknown":"la celda ya no existe","cell-scope-add":"Añadir una celda","cell-scope-search":"Buscar entre las celdas","cell-scope-no-candidates":"Ninguna celda coincide.","cell-scope-reset-warning":"Al cambiar de modo la lista se borra: volver a «celdas seleccionadas» obliga a elegirlas de nuevo.","cell-scope-list-unavailable":"Lista de celdas no disponible ahora: las concesiones de abajo siguen vigentes, pero no se puede saber si aún existen.","feed-owner":"de nodo federado","ask-remote-readonly":"Respuesta no concedida para este nodo: tarjeta en solo lectura.","ask-capability-loading":"Comprobando el permiso de respuesta…","ask-capability-unreachable":"Ruta de respuesta no accesible.","ask-capability-unsupported":"Este nodo no admite la comprobación del permiso de respuesta.","ask-remote-no-feed":"No recibes los eventos de este nodo: activa la recepción (nodes edit <peer> --events-receive true).","ask-feed-stale":"El feed de este nodo está inactivo (datos no actualizados): la tarjeta puede estar ya cerrada en otro sitio.","ask-dismiss-stale":"Descartar igualmente: el descarto se reenvía directamente al nodo, pero con el feed caído la tarjeta puede no reflejar el estado real.","ask-uncertain":"Resultado incierto: la respuesta pudo llegar. Verifica el estado antes de reintentar.","ask-reconcile":"Respuesta bloqueada por un envío previo: reconcilia con el nodo que hizo la pregunta. Ningún reenvío a ciegas.","ask-verify":"Verificar estado","peer-access":"Rol del par","peer-access-help":"Lo que este par puede hacer en esta instalación. El nombre se deriva de los permisos efectivos: aplicar un preajuste reescribe todo el vector en una sola escritura.","peer-access-current":"Ahora","peer-access-preset":"Preajuste a aplicar","peer-access-preset-none":"elige un preajuste","peer-access-matrix":"Qué cambiaría","peer-access-apply":"Aplicar el preajuste","peer-access-changed-hint":"Las filas resaltadas cambian al confirmar.","peer-access-unchanged":"El preajuste no cambiaría nada.","peer-access-conflict":"Este par fue modificado en otro lugar: estado recargado, vuelve a aplicar el preajuste si hace falta.","access-label-admin":"administrador","access-label-user":"usuario","access-label-nexushost":"nexushost","access-label-custom":"personalizado","access-label-unconfigured":"no configurado","access-grant-cellVisibility":"Celdas visibles","access-grant-eventsAccess":"Eventos","access-grant-eventsReceive":"Recepción de eventos y notificaciones","access-grant-nodeEventsAccess":"Eventos de nodo","access-grant-askReplyAccess":"Respuestas a preguntas","access-grant-filesReadAccess":"Lectura de archivos","access-grant-liveHostAccess":"Host Live","access-grant-panelAccess":"Paneles","access-grant-peerOperatorAccess":"Operador de pares","access-value-all":"todas","access-value-selected":"seleccionadas","access-value-none":"ninguna","access-value-yes":"sí","access-value-no":"no","single-view":"vista única",retract:"reducir","keybar-expand":"ampliar la barra de teclas","keybar-retract":"reducir la barra de teclas","save-and-start":"guardar e iniciar",permissions:"Permisos","power-on-hint":"Detén la celda; también puedes quitarla del boot.","launch-engine-help":"Proveedores, credenciales y nuevos motores se crean en Ajustes → Flota. Modelo y permisos son por celda.","launch-unavailable-hint":"La configuración del motor no está disponible en este nodo.","import-as-cell":"Importar como celda","import-help":"Reconcilia una sesión tmux existente en una celda gestionada. Elige un motor ya declarado: no se inventa ninguno.","import-engine-required":"elige un motor (obligatorio)","test-and-connect":"probar y conectar","pairing-v2-hint":"Pega o escanea UN solo enlace: rellena nombre, Host SSH y etiqueta cuando los incluye (v2).","invite-v2-hint":"Crea una invitación de un solo uso. Hace falta la dirección SSH de este dispositivo, alcanzable por quien la use.","invite-target-local":"El nuevo dispositivo entrará en","invite-target-this":"este dispositivo","invite-endpoint-label":"Dirección SSH de este hub vista por los otros dispositivos","invite-endpoint-auto":"Endpoint ya configurado","invite-endpoint-needed":"Introduce usuario@host o un alias SSH compartido. No es 127.0.0.1 ni la URL HTTP de NexusCrew.","invite-ssh-hint":"El destino SSH con el que el OTRO dispositivo alcanza ESTA instalación (usuario@host o alias). Obligatorio: se incluye en el enlace.","invite-next-steps":"copia este enlace, abre NexusCrew en el otro dispositivo y pégalo en Ajustes → Nodos (o escanea el QR): NexusCrew hace el resto","pair-card-title":"conectar con un solo enlace","pair-card-help":"Pega el enlace de emparejamiento generado en el otro dispositivo (o escanea su QR): NexusCrew lo decodifica, prueba la conexión SSH y conecta solo.","pair-paste-ph":"pega aquí el enlace de emparejamiento","pair-paste-btn":"pegar","pair-advanced":"avanzado / editar","pair-progress":"conectando: SSH → invitación → confirmación → verificación…","pair-retry":"reintentar","pair-invalid-link":"esto no es un enlace de emparejamiento válido","pair-invalid-hint":"se necesita el enlace completo (http://…#pair=…) generado por el otro NexusCrew: no lo abras, pégalo aquí","pair-missing-ssh":"el enlace no incluye el destino SSH (formato v1): indica en “avanzado” cómo este dispositivo alcanza al otro por SSH — nunca se inventa","pair-missing-name":"falta el nombre del nodo: complétalo en “avanzado”","pair-clipboard-denied":"lectura del portapapeles no permitida: pega manualmente en el campo","pair-clipboard-empty":"portapapeles vacío: copia primero el enlace","pair-stage-validation":"datos no válidos","pair-stage-conflict":"nombre ya en uso","pair-stage-ssh-start":"fallo al iniciar el túnel SSH","pair-stage-ssh-ready":"peer inaccesible por SSH","pair-stage-join":"intercambio de invitación fallido","pair-stage-tunnel-final":"túnel negociado fallido","pair-stage-confirm":"confirmación de emparejamiento fallida","pair-stage-health":"verificación final de la federación fallida","pair-stage-internal":"error interno","pair-stage-generic":"conexión fallida","qr-no-camera":"no hay cámara disponible en este dispositivo: usa una foto del QR","qr-permission":"permiso de cámara denegado: permítelo en el navegador o usa una foto del QR","qr-unsupported":"escáner en vivo no soportado aquí: sube una foto del QR","qr-upload":"usar una foto"}};function Jo(){const e=x1(),t=e?e.getItem(S1):null;return xv.includes(t)?t:xd}function Rj(e){const t=x1();if(t)try{t.setItem(S1,e)}catch{}typeof window<"u"&&window.dispatchEvent(new Event(Tm))}function f(e){const t=Jo(),n=nd[t]||nd[xd];return Object.prototype.hasOwnProperty.call(n,e)?n[e]:Object.prototype.hasOwnProperty.call(nd[xd],e)?nd[xd][e]:e}function Aj(e){return typeof window>"u"?()=>{}:(window.addEventListener(Tm,e),()=>window.removeEventListener(Tm,e))}const k1=xv,Rc="none",C1="favorite",E1="designated",N1="thread-present",j1="thread-active",L1="thread-unknown",R1=new Set([E1,N1,j1,L1]);function A1(e){return e==="absent"?E1:e==="present"?N1:e==="active"?j1:L1}function Mj(e){return R1.has(e)?`host-thread-${e.replace("thread-","")}`:null}function $d({hostCell:e,threadStatus:t,pins:n=[],item:s}){const i=s&&s.value&&typeof s.value.cell=="string"?s.value.cell:null;return i!=null&&e===i?A1(t):Array.isArray(n)&&s&&n.includes(s.key)?C1:Rc}const Tj=Object.freeze(["live","grace","expired","none","unavailable"]);function Im(e,t){return!R1.has(e)||!Tj.includes(t)?null:`host-lease-${t}`}const Ij="local";function Rs(e){return Array.isArray(e)&&e.length?e.join("/"):Ij}function Pm(e){return(e&&e.data&&typeof e.data=="object"?e.data.reason:null)==="live-host-not-granted"?"live-host-not-granted":"live-host-error"}const M1="native",Dm="tmux";function Pj(e){return typeof e!="string"||!e?null:e.startsWith("codex-vl")?M1:Dm}function Ja({liveHost:e,cells:t=[],localNodeId:n="",ownerId:s=null}={}){const i=e&&typeof e.hostCell=="string"&&e.hostCell?e.hostCell:null,l=i&&(Array.isArray(t)?t:[]).find(u=>u&&u.cell===i)||null,c=l&&typeof l.engine=="string"&&l.engine?l.engine:null;return{hostCell:i,cell:i,known:!!l,engine:c,mode:Pj(c),state:i?A1(e&&e.threadStatus):Rc,hostActive:!!(l&&l.active===!0&&l.tmux!==!1),remote:!!(s&&n&&s!==n),lease:e&&(e.hostLease||(e.host&&typeof e.host.lease=="string"?e.host.lease:null))||null}}function Dj(e){const t=e&&e.state?e.state:Rc;return{modeKey:e&&e.mode?`live-host-mode-${e.mode}`:null,stateKey:`live-host-state-${t}`}}function kv(e){const t=e&&e.state?e.state:Rc;return t==="thread-active"?"active":t==="thread-present"?"present":t===Rc?"none":t==="thread-unknown"?"unknown":"designated"}function Oj(e){return!e||!e.cell||e.remote?null:e.state==="thread-present"||e.state==="thread-active"?M1:e.mode===Dm&&e.hostActive?Dm:null}function T1({view:e}){const t=Oj(e);return t?o.jsx("span",{className:"nc-live-badge","data-testid":"live-badge","data-mode":t,title:f(`live-badge-${t}`),children:f("live-badge")}):null}const Cv="nc_popup_assetto",Bj=320,$j=240,zj=1100,Fj=820,_w=48,Hj=44;function I1(){return{vw:window.innerWidth||1024,vh:window.innerHeight||768}}function fc(e){const{vw:t,vh:n}=I1(),s=Math.max(Bj,Math.min(e.w,t)),i=Math.max($j,Math.min(e.h,n)),l=Math.max(-(s-_w),Math.min(e.x,t-_w)),c=Math.max(0,Math.min(e.y,Math.max(0,n-Hj)));return{x:l,y:c,w:s,h:i}}function yw(){try{const e=window.localStorage.getItem(Cv);if(!e)return null;const t=JSON.parse(e);return!t||![t.x,t.y,t.w,t.h].every(n=>typeof n=="number"&&Number.isFinite(n))?null:fc(t)}catch{return null}}function Uj(e){try{window.localStorage.setItem(Cv,JSON.stringify(e))}catch{}}function Wj(){const[e,t]=y.useState(()=>typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 720px)").matches);return y.useEffect(()=>{if(typeof window.matchMedia!="function")return;const n=window.matchMedia("(max-width: 720px)"),s=i=>t(!!(i&&i.matches));if(typeof n.addEventListener=="function")return n.addEventListener("change",s),()=>n.removeEventListener("change",s)},[]),e}function P1({title:e,subtitle:t,onClose:n,children:s}){const i=y.useRef(null),l=y.useRef(null),c=Wj(),[u,h]=y.useState(()=>c?null:yw()),p=y.useRef(null),[v,_]=y.useState(!1),g=y.useCallback(()=>{n&&n()},[n]);y.useEffect(()=>{const j=E=>{E.key==="Escape"&&(E.stopPropagation(),g())};return document.addEventListener("keydown",j,!0),()=>document.removeEventListener("keydown",j,!0)},[g]),y.useEffect(()=>{const j=l.current;j&&typeof j.focus=="function"&&j.focus()},[]);const w=()=>{const{vw:j,vh:E}=I1(),R=Math.min(zj,Math.floor(j*.96)),x=Math.min(Fj,Math.floor(E*.92));return fc({x:Math.round((j-R)/2),y:Math.round((E-x)/2),w:R,h:x})},S=j=>E=>{if(c||E.button!==0||E.target&&typeof E.target.closest=="function"&&E.target.closest(".nc-popup-chiudi"))return;E.preventDefault();const R=u||w();p.current={mode:j,startX:E.clientX,startY:E.clientY,base:R},h(R),_(!0)};y.useEffect(()=>{if(!v)return;const j=R=>{const x=p.current;if(!x)return;const W=R.clientX-x.startX,$=R.clientY-x.startY;x.mode==="move"?h(fc({...x.base,x:x.base.x+W,y:x.base.y+$})):h(fc({...x.base,w:x.base.w+W,h:x.base.h+$}))},E=()=>{p.current=null,_(!1),h(R=>(R&&Uj(R),R))};return window.addEventListener("mousemove",j),window.addEventListener("mouseup",E),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",E)}},[v]);const N=()=>{if(!c){p.current=null,_(!1),h(null);try{window.localStorage.removeItem(Cv)}catch{}}};y.useEffect(()=>{if(c)return;const j=()=>h(E=>E&&fc(E));return window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[c]),y.useEffect(()=>{c||h(j=>j||yw())},[c]);const C=!!(u&&!c);return o.jsxs("div",{className:"nc-popup-velo",onMouseDown:j=>{j.target===j.currentTarget&&g()},role:"presentation",children:[o.jsxs("div",{className:C?"nc-popup nc-popup-libera":"nc-popup",style:C?{left:u.x,top:u.y,width:u.w,height:u.h}:void 0,ref:i,role:"dialog","aria-modal":"true","aria-label":e||f("panel"),children:[o.jsxs("header",{className:"nc-popup-testa",onMouseDown:S("move"),onDoubleClick:N,title:f("popup-drag-hint"),children:[o.jsxs("span",{className:"nc-popup-titolo",children:[e,t?o.jsx("small",{className:"nc-popup-sub",children:t}):null]}),o.jsx("button",{type:"button",ref:l,className:"nc-popup-chiudi",onClick:g,title:f("close"),"aria-label":f("close"),children:"✕"})]}),o.jsx("div",{className:"nc-popup-corpo",children:s}),!c&&o.jsx("div",{className:"nc-popup-angolo",onMouseDown:S("resize"),title:f("popup-resize-hint"),role:"presentation"})]}),v&&o.jsx("div",{className:"nc-popup-velo-drag",role:"presentation"})]})}function bw(e){const t=e&&e.status;return(e&&e.data&&typeof e.data=="object"?e.data.reason:null)==="live-host-not-granted"?"live-host-not-granted":t===409?"live-host-stale-revision":t===404?"live-host-not-local":t===503?"live-host-unavailable":Pm(e)}async function gh({action:e,cellId:t,route:n=[],token:s,api:i={}}={}){const l=i.getLiveHost||(v=>hh(s,v)),c=i.designateHostCell||((v,_,g)=>fh(s,v,_,g)),u=i.clearHostCell||((v,_)=>ph(s,v,_));let h;try{h=await l(n)}catch(v){return{ok:!1,messageKey:bw(v),error:v}}const p=Number.isInteger(h&&h.revision)?h.revision:0;try{if(e==="remove"){const _=await u(p,n);return{ok:!0,messageKey:"live-host-cleared",hostCell:_&&typeof _.hostCell=="string"?_.hostCell:null,revision:_&&_.revision}}const v=await c(t,p,n);return{ok:!0,messageKey:"live-host-designated",hostCell:v&&typeof v.hostCell=="string"?v.hostCell:t,revision:v&&v.revision}}catch(v){return{ok:!1,messageKey:bw(v),error:v}}}/**
41
+ * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
42
+ * @license MIT
43
+ *
44
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
45
+ * @license MIT
46
+ *
47
+ * Originally forked from (with the author's permission):
48
+ * Fabrice Bellard's javascript vt100 for jslinux:
49
+ * http://bellard.org/jslinux/
50
+ * Copyright (c) 2011 Fabrice Bellard
51
+ */var D1=Object.defineProperty,qj=Object.getOwnPropertyDescriptor,Kj=(e,t)=>{for(var n in t)D1(e,n,{get:t[n],enumerable:!0})},Mn=(e,t,n,s)=>{for(var i=s>1?void 0:s?qj(t,n):t,l=e.length-1,c;l>=0;l--)(c=e[l])&&(i=(s?c(t,n,i):c(i))||i);return s&&i&&D1(t,n,i),i},dt=(e,t)=>(n,s)=>t(n,s,e),ww="Terminal input",Om={get:()=>ww,set:e=>ww=e},Sw="Too much output to announce, navigate to rows manually to read",Bm={get:()=>Sw,set:e=>Sw=e};function Vj(e){return e.replace(/\r?\n/g,"\r")}function Gj(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function Yj(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Xj(e,t,n,s){if(e.stopPropagation(),e.clipboardData){let i=e.clipboardData.getData("text/plain");O1(i,t,n,s)}}function O1(e,t,n,s){e=Vj(e),e=Gj(e,n.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function B1(e,t,n){let s=n.getBoundingClientRect(),i=e.clientX-s.left-10,l=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${i}px`,t.style.top=`${l}px`,t.style.zIndex="1000",t.focus()}function xw(e,t,n,s,i){B1(e,t,n),i&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function oo(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function vh(e,t=0,n=e.length){let s="";for(let i=t;i<n;++i){let l=e[i];l>65535?(l-=65536,s+=String.fromCharCode((l>>10)+55296)+String.fromCharCode(l%1024+56320)):s+=String.fromCharCode(l)}return s}var Jj=class{constructor(){this._interim=0}clear(){this._interim=0}decode(t,n){let s=t.length;if(!s)return 0;let i=0,l=0;if(this._interim){let c=t.charCodeAt(l++);56320<=c&&c<=57343?n[i++]=(this._interim-55296)*1024+c-56320+65536:(n[i++]=this._interim,n[i++]=c),this._interim=0}for(let c=l;c<s;++c){let u=t.charCodeAt(c);if(55296<=u&&u<=56319){if(++c>=s)return this._interim=u,i;let h=t.charCodeAt(c);56320<=h&&h<=57343?n[i++]=(u-55296)*1024+h-56320+65536:(n[i++]=u,n[i++]=h);continue}u!==65279&&(n[i++]=u)}return i}},Qj=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(t,n){let s=t.length;if(!s)return 0;let i=0,l,c,u,h,p=0,v=0;if(this.interim[0]){let w=!1,S=this.interim[0];S&=(S&224)===192?31:(S&240)===224?15:7;let N=0,C;for(;(C=this.interim[++N]&63)&&N<4;)S<<=6,S|=C;let j=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=j-N;for(;v<E;){if(v>=s)return 0;if(C=t[v++],(C&192)!==128){v--,w=!0;break}else this.interim[N++]=C,S<<=6,S|=C&63}w||(j===2?S<128?v--:n[i++]=S:j===3?S<2048||S>=55296&&S<=57343||S===65279||(n[i++]=S):S<65536||S>1114111||(n[i++]=S)),this.interim.fill(0)}let _=s-4,g=v;for(;g<s;){for(;g<_&&!((l=t[g])&128)&&!((c=t[g+1])&128)&&!((u=t[g+2])&128)&&!((h=t[g+3])&128);)n[i++]=l,n[i++]=c,n[i++]=u,n[i++]=h,g+=4;if(l=t[g++],l<128)n[i++]=l;else if((l&224)===192){if(g>=s)return this.interim[0]=l,i;if(c=t[g++],(c&192)!==128){g--;continue}if(p=(l&31)<<6|c&63,p<128){g--;continue}n[i++]=p}else if((l&240)===224){if(g>=s)return this.interim[0]=l,i;if(c=t[g++],(c&192)!==128){g--;continue}if(g>=s)return this.interim[0]=l,this.interim[1]=c,i;if(u=t[g++],(u&192)!==128){g--;continue}if(p=(l&15)<<12|(c&63)<<6|u&63,p<2048||p>=55296&&p<=57343||p===65279)continue;n[i++]=p}else if((l&248)===240){if(g>=s)return this.interim[0]=l,i;if(c=t[g++],(c&192)!==128){g--;continue}if(g>=s)return this.interim[0]=l,this.interim[1]=c,i;if(u=t[g++],(u&192)!==128){g--;continue}if(g>=s)return this.interim[0]=l,this.interim[1]=c,this.interim[2]=u,i;if(h=t[g++],(h&192)!==128){g--;continue}if(p=(l&7)<<18|(c&63)<<12|(u&63)<<6|h&63,p<65536||p>1114111)continue;n[i++]=p}}return i}},$1="",lo=" ",Xc=class z1{constructor(){this.fg=0,this.bg=0,this.extended=new zd}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new z1;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},zd=class F1{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new F1(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Si=class H1 extends Xc{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new zd,this.combinedData=""}static fromCharData(t){let n=new H1;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?oo(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let i=t[1].charCodeAt(1);56320<=i&&i<=57343?this.content=(s-55296)*1024+i-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},kw="di$target",$m="di$dependencies",dp=new Map;function Zj(e){return e[$m]||[]}function us(e){if(dp.has(e))return dp.get(e);let t=function(n,s,i){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");eL(t,n,i)};return t._id=e,dp.set(e,t),t}function eL(e,t,n){t[kw]===t?t[$m].push({id:e,index:n}):(t[$m]=[{id:e,index:n}],t[kw]=t)}var zs=us("BufferService"),U1=us("CoreMouseService"),na=us("CoreService"),tL=us("CharsetService"),Ev=us("InstantiationService"),W1=us("LogService"),Fs=us("OptionsService"),q1=us("OscLinkService"),nL=us("UnicodeService"),Jc=us("DecorationService"),zm=class{constructor(t,n,s){this._bufferService=t,this._optionsService=n,this._oscLinkService=s}provideLinks(t,n){var _;let s=this._bufferService.buffer.lines.get(t-1);if(!s){n(void 0);return}let i=[],l=this._optionsService.rawOptions.linkHandler,c=new Si,u=s.getTrimmedLength(),h=-1,p=-1,v=!1;for(let g=0;g<u;g++)if(!(p===-1&&!s.hasContent(g))){if(s.loadCell(g,c),c.hasExtendedAttrs()&&c.extended.urlId)if(p===-1){p=g,h=c.extended.urlId;continue}else v=c.extended.urlId!==h;else p!==-1&&(v=!0);if(v||p!==-1&&g===u-1){let w=(_=this._oscLinkService.getLinkData(h))==null?void 0:_.uri;if(w){let S={start:{x:p+1,y:t},end:{x:g+(!v&&g===u-1?1:0),y:t}},N=!1;if(!(l!=null&&l.allowNonHttpProtocols))try{let C=new URL(w);["http:","https:"].includes(C.protocol)||(N=!0)}catch{N=!0}N||i.push({text:w,range:S,activate:(C,j)=>l?l.activate(C,j,S):sL(C,j),hover:(C,j)=>{var E;return(E=l==null?void 0:l.hover)==null?void 0:E.call(l,C,j,S)},leave:(C,j)=>{var E;return(E=l==null?void 0:l.leave)==null?void 0:E.call(l,C,j,S)}})}v=!1,c.hasExtendedAttrs()&&c.extended.urlId?(p=g,h=c.extended.urlId):(p=-1,h=-1)}}n(i)}};zm=Mn([dt(0,zs),dt(1,Fs),dt(2,q1)],zm);function sL(e,t){if(confirm(`Do you want to navigate to ${t}?
52
+
53
+ WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var _h=us("CharSizeService"),Mr=us("CoreBrowserService"),Nv=us("MouseService"),Tr=us("RenderService"),iL=us("SelectionService"),K1=us("CharacterJoinerService"),ol=us("ThemeService"),V1=us("LinkProviderService"),rL=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(t){setTimeout(()=>{throw t.stack?Cw.isErrorNoTelemetry(t)?new Cw(t.message+`
54
+
55
+ `+t.stack):new Error(t.message+`
56
+
57
+ `+t.stack):t},0)}}addListener(t){return this.listeners.push(t),()=>{this._removeListener(t)}}emit(t){this.listeners.forEach(n=>{n(t)})}_removeListener(t){this.listeners.splice(this.listeners.indexOf(t),1)}setUnexpectedErrorHandler(t){this.unexpectedErrorHandler=t}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(t){this.unexpectedErrorHandler(t),this.emit(t)}onUnexpectedExternalError(t){this.unexpectedErrorHandler(t)}},oL=new rL;function kd(e){aL(e)||oL.onUnexpectedError(e)}var Fm="Canceled";function aL(e){return e instanceof lL?!0:e instanceof Error&&e.name===Fm&&e.message===Fm}var lL=class extends Error{constructor(){super(Fm),this.name=this.message}};function cL(e){return new Error(`Illegal argument: ${e}`)}var Cw=class Hm extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Hm)return t;let n=new Hm;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Um=class G1 extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,G1.prototype)}};function si(e,t=0){return e[e.length-(1+t)]}var uL;(e=>{function t(l){return l<0}e.isLessThan=t;function n(l){return l<=0}e.isLessThanOrEqual=n;function s(l){return l>0}e.isGreaterThan=s;function i(l){return l===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(uL||(uL={}));function dL(e,t){let n=this,s=!1,i;return function(){return s||(s=!0,t||(i=e.apply(n,arguments))),i}}var Y1;(e=>{function t(x){return x&&typeof x=="object"&&typeof x[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function s(){return n}e.empty=s;function*i(x){yield x}e.single=i;function l(x){return t(x)?x:i(x)}e.wrap=l;function c(x){return x||n}e.from=c;function*u(x){for(let W=x.length-1;W>=0;W--)yield x[W]}e.reverse=u;function h(x){return!x||x[Symbol.iterator]().next().done===!0}e.isEmpty=h;function p(x){return x[Symbol.iterator]().next().value}e.first=p;function v(x,W){let $=0;for(let Y of x)if(W(Y,$++))return!0;return!1}e.some=v;function _(x,W){for(let $ of x)if(W($))return $}e.find=_;function*g(x,W){for(let $ of x)W($)&&(yield $)}e.filter=g;function*w(x,W){let $=0;for(let Y of x)yield W(Y,$++)}e.map=w;function*S(x,W){let $=0;for(let Y of x)yield*W(Y,$++)}e.flatMap=S;function*N(...x){for(let W of x)yield*W}e.concat=N;function C(x,W,$){let Y=$;for(let q of x)Y=W(Y,q);return Y}e.reduce=C;function*j(x,W,$=x.length){for(W<0&&(W+=x.length),$<0?$+=x.length:$>x.length&&($=x.length);W<$;W++)yield x[W]}e.slice=j;function E(x,W=Number.POSITIVE_INFINITY){let $=[];if(W===0)return[$,x];let Y=x[Symbol.iterator]();for(let q=0;q<W;q++){let K=Y.next();if(K.done)return[$,e.empty()];$.push(K.value)}return[$,{[Symbol.iterator](){return Y}}]}e.consume=E;async function R(x){let W=[];for await(let $ of x)W.push($);return Promise.resolve(W)}e.asyncToArray=R})(Y1||(Y1={}));function Qo(e){if(Y1.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(s){t.push(s)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function hL(...e){return yn(()=>Qo(e))}function yn(e){return{dispose:dL(()=>{e()})}}var X1=class J1{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Qo(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?J1.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};X1.DISABLE_DISPOSED_WARNING=!1;var ho=X1,qt=class{constructor(){this._store=new ho,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};qt.None=Object.freeze({dispose(){}});var Qa=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(t){var n;this._isDisposed||t===this._value||((n=this._value)==null||n.dispose(),this._value=t)}clear(){this.value=void 0}dispose(){var t;this._isDisposed=!0,(t=this._value)==null||t.dispose(),this._value=void 0}clearAndLeak(){let t=this._value;return this._value=void 0,t}},jr=typeof window=="object"?window:globalThis,Wm=class qm{constructor(t){this.element=t,this.next=qm.Undefined,this.prev=qm.Undefined}};Wm.Undefined=new Wm(void 0);var kn=Wm,Ew=class{constructor(){this._first=kn.Undefined,this._last=kn.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===kn.Undefined}clear(){let t=this._first;for(;t!==kn.Undefined;){let n=t.next;t.prev=kn.Undefined,t.next=kn.Undefined,t=n}this._first=kn.Undefined,this._last=kn.Undefined,this._size=0}unshift(t){return this._insert(t,!1)}push(t){return this._insert(t,!0)}_insert(t,n){let s=new kn(t);if(this._first===kn.Undefined)this._first=s,this._last=s;else if(n){let l=this._last;this._last=s,s.prev=l,l.next=s}else{let l=this._first;this._first=s,s.next=l,l.prev=s}this._size+=1;let i=!1;return()=>{i||(i=!0,this._remove(s))}}shift(){if(this._first!==kn.Undefined){let t=this._first.element;return this._remove(this._first),t}}pop(){if(this._last!==kn.Undefined){let t=this._last.element;return this._remove(this._last),t}}_remove(t){if(t.prev!==kn.Undefined&&t.next!==kn.Undefined){let n=t.prev;n.next=t.next,t.next.prev=n}else t.prev===kn.Undefined&&t.next===kn.Undefined?(this._first=kn.Undefined,this._last=kn.Undefined):t.next===kn.Undefined?(this._last=this._last.prev,this._last.next=kn.Undefined):t.prev===kn.Undefined&&(this._first=this._first.next,this._first.prev=kn.Undefined);this._size-=1}*[Symbol.iterator](){let t=this._first;for(;t!==kn.Undefined;)yield t.element,t=t.next}},fL=globalThis.performance&&typeof globalThis.performance.now=="function",pL=class Q1{static create(t){return new Q1(t)}constructor(t){this._now=fL&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},ys;(e=>{e.None=()=>qt.None;function t(B,D){return _(B,()=>{},0,void 0,!0,void 0,D)}e.defer=t;function n(B){return(D,O=null,P)=>{let z=!1,A;return A=B(T=>{if(!z)return A?A.dispose():z=!0,D.call(O,T)},null,P),z&&A.dispose(),A}}e.once=n;function s(B,D,O){return p((P,z=null,A)=>B(T=>P.call(z,D(T)),null,A),O)}e.map=s;function i(B,D,O){return p((P,z=null,A)=>B(T=>{D(T),P.call(z,T)},null,A),O)}e.forEach=i;function l(B,D,O){return p((P,z=null,A)=>B(T=>D(T)&&P.call(z,T),null,A),O)}e.filter=l;function c(B){return B}e.signal=c;function u(...B){return(D,O=null,P)=>{let z=hL(...B.map(A=>A(T=>D.call(O,T))));return v(z,P)}}e.any=u;function h(B,D,O,P){let z=O;return s(B,A=>(z=D(z,A),z),P)}e.reduce=h;function p(B,D){let O,P={onWillAddFirstListener(){O=B(z.fire,z)},onDidRemoveLastListener(){O==null||O.dispose()}},z=new st(P);return D==null||D.add(z),z.event}function v(B,D){return D instanceof Array?D.push(B):D&&D.add(B),B}function _(B,D,O=100,P=!1,z=!1,A,T){let L,H,M,U=0,ee,re={leakWarningThreshold:A,onWillAddFirstListener(){L=B(je=>{U++,H=D(H,je),P&&!M&&(oe.fire(H),H=void 0),ee=()=>{let te=H;H=void 0,M=void 0,(!P||U>1)&&oe.fire(te),U=0},typeof O=="number"?(clearTimeout(M),M=setTimeout(ee,O)):M===void 0&&(M=0,queueMicrotask(ee))})},onWillRemoveListener(){z&&U>0&&(ee==null||ee())},onDidRemoveLastListener(){ee=void 0,L.dispose()}},oe=new st(re);return T==null||T.add(oe),oe.event}e.debounce=_;function g(B,D=0,O){return e.debounce(B,(P,z)=>P?(P.push(z),P):[z],D,void 0,!0,void 0,O)}e.accumulate=g;function w(B,D=(P,z)=>P===z,O){let P=!0,z;return l(B,A=>{let T=P||!D(A,z);return P=!1,z=A,T},O)}e.latch=w;function S(B,D,O){return[e.filter(B,D,O),e.filter(B,P=>!D(P),O)]}e.split=S;function N(B,D=!1,O=[],P){let z=O.slice(),A=B(H=>{z?z.push(H):L.fire(H)});P&&P.add(A);let T=()=>{z==null||z.forEach(H=>L.fire(H)),z=null},L=new st({onWillAddFirstListener(){A||(A=B(H=>L.fire(H)),P&&P.add(A))},onDidAddFirstListener(){z&&(D?setTimeout(T):T())},onDidRemoveLastListener(){A&&A.dispose(),A=null}});return P&&P.add(L),L.event}e.buffer=N;function C(B,D){return(O,P,z)=>{let A=D(new E);return B(function(T){let L=A.evaluate(T);L!==j&&O.call(P,L)},void 0,z)}}e.chain=C;let j=Symbol("HaltChainable");class E{constructor(){this.steps=[]}map(D){return this.steps.push(D),this}forEach(D){return this.steps.push(O=>(D(O),O)),this}filter(D){return this.steps.push(O=>D(O)?O:j),this}reduce(D,O){let P=O;return this.steps.push(z=>(P=D(P,z),P)),this}latch(D=(O,P)=>O===P){let O=!0,P;return this.steps.push(z=>{let A=O||!D(z,P);return O=!1,P=z,A?z:j}),this}evaluate(D){for(let O of this.steps)if(D=O(D),D===j)break;return D}}function R(B,D,O=P=>P){let P=(...L)=>T.fire(O(...L)),z=()=>B.on(D,P),A=()=>B.removeListener(D,P),T=new st({onWillAddFirstListener:z,onDidRemoveLastListener:A});return T.event}e.fromNodeEventEmitter=R;function x(B,D,O=P=>P){let P=(...L)=>T.fire(O(...L)),z=()=>B.addEventListener(D,P),A=()=>B.removeEventListener(D,P),T=new st({onWillAddFirstListener:z,onDidRemoveLastListener:A});return T.event}e.fromDOMEventEmitter=x;function W(B){return new Promise(D=>n(B)(D))}e.toPromise=W;function $(B){let D=new st;return B.then(O=>{D.fire(O)},()=>{D.fire(void 0)}).finally(()=>{D.dispose()}),D.event}e.fromPromise=$;function Y(B,D){return B(O=>D.fire(O))}e.forward=Y;function q(B,D,O){return D(O),B(P=>D(P))}e.runAndSubscribe=q;class K{constructor(D,O){this._observable=D,this._counter=0,this._hasChanged=!1;let P={onWillAddFirstListener:()=>{D.addObserver(this)},onDidRemoveLastListener:()=>{D.removeObserver(this)}};this.emitter=new st(P),O&&O.add(this.emitter)}beginUpdate(D){this._counter++}handlePossibleChange(D){}handleChange(D,O){this._hasChanged=!0}endUpdate(D){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function se(B,D){return new K(B,D).emitter.event}e.fromObservable=se;function V(B){return(D,O,P)=>{let z=0,A=!1,T={beginUpdate(){z++},endUpdate(){z--,z===0&&(B.reportChanges(),A&&(A=!1,D.call(O)))},handlePossibleChange(){},handleChange(){A=!0}};B.addObserver(T),B.reportChanges();let L={dispose(){B.removeObserver(T)}};return P instanceof ho?P.add(L):Array.isArray(P)&&P.push(L),L}}e.fromObservableLight=V})(ys||(ys={}));var Km=class Vm{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Vm._idPool++}`,Vm.all.add(this)}start(t){this._stopWatch=new pL,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Km.all=new Set,Km._idPool=0;var mL=Km,gL=-1,Z1=class ek{constructor(t,n,s=(ek._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,n){let s=this.threshold;if(s<=0||n<s)return;this._stacks||(this._stacks=new Map);let i=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,i+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=s*.5;let[l,c]=this.getMostFrequentStack(),u=`[${this.name}] potential listener LEAK detected, having ${n} listeners already. MOST frequent listener (${c}):`;console.warn(u),console.warn(l);let h=new yL(u,l);this._errorHandler(h)}return()=>{let l=this._stacks.get(t.value)||0;this._stacks.set(t.value,l-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[s,i]of this._stacks)(!t||n<i)&&(t=[s,i],n=i);return t}};Z1._idPool=1;var vL=Z1,_L=class tk{constructor(t){this.value=t}static create(){let t=new Error;return new tk(t.stack??"")}print(){console.warn(this.value.split(`
58
+ `).slice(2).join(`
59
+ `))}},yL=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},bL=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},wL=0,hp=class{constructor(t){this.value=t,this.id=wL++}},SL=2,xL,st=class{constructor(e){var t,n,s,i;this._size=0,this._options=e,this._leakageMon=(t=this._options)!=null&&t.leakWarningThreshold?new vL((e==null?void 0:e.onListenerError)??kd,((n=this._options)==null?void 0:n.leakWarningThreshold)??gL):void 0,this._perfMon=(s=this._options)!=null&&s._profName?new mL(this._options._profName):void 0,this._deliveryQueue=(i=this._options)==null?void 0:i.deliveryQueue}dispose(){var e,t,n,s;this._disposed||(this._disposed=!0,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(n=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null||n.call(t),(s=this._leakageMon)==null||s.dispose())}get event(){return this._event??(this._event=(e,t,n)=>{var c,u,h,p,v;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let _=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(_);let g=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],w=new bL(`${_}. HINT: Stack shows most frequent listener (${g[1]}-times)`,g[0]);return(((c=this._options)==null?void 0:c.onListenerError)||kd)(w),qt.None}if(this._disposed)return qt.None;t&&(e=e.bind(t));let s=new hp(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(s.stack=_L.create(),i=this._leakageMon.check(s.stack,this._size+1)),this._listeners?this._listeners instanceof hp?(this._deliveryQueue??(this._deliveryQueue=new kL),this._listeners=[this._listeners,s]):this._listeners.push(s):((h=(u=this._options)==null?void 0:u.onWillAddFirstListener)==null||h.call(u,this),this._listeners=s,(v=(p=this._options)==null?void 0:p.onDidAddFirstListener)==null||v.call(p,this)),this._size++;let l=yn(()=>{i==null||i(),this._removeListener(s)});return n instanceof ho?n.add(l):Array.isArray(n)&&n.push(l),l}),this._event}_removeListener(e){var i,l,c,u;if((l=(i=this._options)==null?void 0:i.onWillRemoveListener)==null||l.call(i,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(u=(c=this._options)==null?void 0:c.onDidRemoveLastListener)==null||u.call(c,this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let s=this._deliveryQueue.current===this;if(this._size*SL<=t.length){let h=0;for(let p=0;p<t.length;p++)t[p]?t[h++]=t[p]:s&&(this._deliveryQueue.end--,h<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=h}}_deliver(e,t){var s;if(!e)return;let n=((s=this._options)==null?void 0:s.onListenerError)||kd;if(!n){e.value(t);return}try{e.value(t)}catch(i){n(i)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,n,s,i;if((t=this._deliveryQueue)!=null&&t.current&&(this._deliverQueue(this._deliveryQueue),(n=this._perfMon)==null||n.stop()),(s=this._perfMon)==null||s.start(this._size),this._listeners)if(this._listeners instanceof hp)this._deliver(this._listeners,e);else{let l=this._deliveryQueue;l.enqueue(this,e,this._listeners.length),this._deliverQueue(l)}(i=this._perfMon)==null||i.stop()}hasListeners(){return this._size>0}},kL=class{constructor(){this.i=-1,this.end=0}enqueue(t,n,s){this.i=0,this.end=s,this.current=t,this.value=n}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Gm=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new st,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new st,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let s=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let s=this.getWindowId(n);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Gm.INSTANCE=new Gm;var jv=Gm;function CL(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}jv.INSTANCE.onDidChangeZoomLevel;function EL(e){return jv.INSTANCE.getZoomFactor(e)}jv.INSTANCE.onDidChangeFullscreen;var al=typeof navigator=="object"?navigator.userAgent:"",Ym=al.indexOf("Firefox")>=0,NL=al.indexOf("AppleWebKit")>=0,Lv=al.indexOf("Chrome")>=0,jL=!Lv&&al.indexOf("Safari")>=0;al.indexOf("Electron/")>=0;al.indexOf("Android")>=0;var fp=!1;if(typeof jr.matchMedia=="function"){let e=jr.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=jr.matchMedia("(display-mode: fullscreen)");fp=e.matches,CL(jr,e,({matches:n})=>{fp&&t.matches||(fp=n)})}var Ua="en",Xm=!1,Jm=!1,Cd=!1,nk=!1,sd,Ed=Ua,Nw=Ua,LL,Ti,qo=globalThis,vs,e1;typeof qo.vscode<"u"&&typeof qo.vscode.process<"u"?vs=qo.vscode.process:typeof process<"u"&&typeof((e1=process==null?void 0:process.versions)==null?void 0:e1.node)=="string"&&(vs=process);var t1,RL=typeof((t1=vs==null?void 0:vs.versions)==null?void 0:t1.electron)=="string",AL=RL&&(vs==null?void 0:vs.type)==="renderer",n1;if(typeof vs=="object"){Xm=vs.platform==="win32",Jm=vs.platform==="darwin",Cd=vs.platform==="linux",Cd&&vs.env.SNAP&&vs.env.SNAP_REVISION,vs.env.CI||vs.env.BUILD_ARTIFACTSTAGINGDIRECTORY,sd=Ua,Ed=Ua;let e=vs.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);sd=t.userLocale,Nw=t.osLocale,Ed=t.resolvedLanguage||Ua,LL=(n1=t.languagePack)==null?void 0:n1.translationsConfigFile}catch{}nk=!0}else typeof navigator=="object"&&!AL?(Ti=navigator.userAgent,Xm=Ti.indexOf("Windows")>=0,Jm=Ti.indexOf("Macintosh")>=0,(Ti.indexOf("Macintosh")>=0||Ti.indexOf("iPad")>=0||Ti.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Cd=Ti.indexOf("Linux")>=0,(Ti==null?void 0:Ti.indexOf("Mobi"))>=0,Ed=globalThis._VSCODE_NLS_LANGUAGE||Ua,sd=navigator.language.toLowerCase(),Nw=sd):console.error("Unable to resolve platform.");var sk=Xm,sr=Jm,ML=Cd,jw=nk,rr=Ti,Xr=Ed,TL;(e=>{function t(){return Xr}e.value=t;function n(){return Xr.length===2?Xr==="en":Xr.length>=3?Xr[0]==="e"&&Xr[1]==="n"&&Xr[2]==="-":!1}e.isDefaultVariant=n;function s(){return Xr==="en"}e.isDefault=s})(TL||(TL={}));var IL=typeof qo.postMessage=="function"&&!qo.importScripts;(()=>{if(IL){let e=[];qo.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let s=0,i=e.length;s<i;s++){let l=e[s];if(l.id===n.data.vscodeScheduleAsyncWork){e.splice(s,1),l.callback();return}}});let t=0;return n=>{let s=++t;e.push({id:s,callback:n}),qo.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var PL=!!(rr&&rr.indexOf("Chrome")>=0);rr&&rr.indexOf("Firefox")>=0;!PL&&rr&&rr.indexOf("Safari")>=0;rr&&rr.indexOf("Edg/")>=0;rr&&rr.indexOf("Android")>=0;var Ma=typeof navigator=="object"?navigator:{};jw||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ma&&Ma.clipboard&&Ma.clipboard.writeText,jw||Ma&&Ma.clipboard&&Ma.clipboard.readText;var Rv=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(t,n){this._keyCodeToStr[t]=n,this._strToKeyCode[n.toLowerCase()]=t}keyCodeToStr(t){return this._keyCodeToStr[t]}strToKeyCode(t){return this._strToKeyCode[t.toLowerCase()]||0}},pp=new Rv,Lw=new Rv,Rw=new Rv,DL=new Array(230),ik;(e=>{function t(u){return pp.keyCodeToStr(u)}e.toString=t;function n(u){return pp.strToKeyCode(u)}e.fromString=n;function s(u){return Lw.keyCodeToStr(u)}e.toUserSettingsUS=s;function i(u){return Rw.keyCodeToStr(u)}e.toUserSettingsGeneral=i;function l(u){return Lw.strToKeyCode(u)||Rw.strToKeyCode(u)}e.fromUserSettings=l;function c(u){if(u>=98&&u<=113)return null;switch(u){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return pp.keyCodeToStr(u)}e.toElectronAccelerator=c})(ik||(ik={}));var OL=class rk{constructor(t,n,s,i,l){this.ctrlKey=t,this.shiftKey=n,this.altKey=s,this.metaKey=i,this.keyCode=l}equals(t){return t instanceof rk&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",n=this.shiftKey?"1":"0",s=this.altKey?"1":"0",i=this.metaKey?"1":"0";return`K${t}${n}${s}${i}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new BL([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},BL=class{constructor(e){if(e.length===0)throw cL("chords");this.chords=e}getHashCode(){let e="";for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=";"),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function $L(e){if(e.charCode){let n=String.fromCharCode(e.charCode).toUpperCase();return ik.fromString(n)}let t=e.keyCode;if(t===3)return 7;if(Ym)switch(t){case 59:return 85;case 60:if(ML)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(sr)return 57;break}else if(NL&&(sr&&t===93||!sr&&t===92))return 57;return DL[t]||0}var zL=sr?256:2048,FL=512,HL=1024,UL=sr?2048:256,Aw=class{constructor(e){var n;this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=(n=t.getModifierState)==null?void 0:n.call(t,"AltGraph"),this.keyCode=$L(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=zL),this.altKey&&(t|=FL),this.shiftKey&&(t|=HL),this.metaKey&&(t|=UL),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new OL(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Mw=new WeakMap;function WL(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!=="null"&&n.origin!=="null"&&t.origin!==n.origin)return null}catch{return null}return e.parent}var qL=class{static getSameOriginWindowChain(e){let t=Mw.get(e);if(!t){t=[],Mw.set(e,t);let n=e,s;do s=WL(n),s?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=s;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,s=0,i=this.getSameOriginWindowChain(e);for(let l of i){let c=l.window.deref();if(n+=(c==null?void 0:c.scrollY)??0,s+=(c==null?void 0:c.scrollX)??0,c===t||!l.iframeElement)break;let u=l.iframeElement.getBoundingClientRect();n+=u.top,s+=u.left}return{top:n,left:s}}},id=class{constructor(t,n){this.timestamp=Date.now(),this.browserEvent=n,this.leftButton=n.button===0,this.middleButton=n.button===1,this.rightButton=n.button===2,this.buttons=n.buttons,this.target=n.target,this.detail=n.detail||1,n.type==="dblclick"&&(this.detail=2),this.ctrlKey=n.ctrlKey,this.shiftKey=n.shiftKey,this.altKey=n.altKey,this.metaKey=n.metaKey,typeof n.pageX=="number"?(this.posx=n.pageX,this.posy=n.pageY):(this.posx=n.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=n.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let s=qL.getPositionOfChildWindowRelativeToAncestorWindow(t,n.view);this.posx-=s.left,this.posy-=s.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Tw=class{constructor(t,n=0,s=0){var l;this.browserEvent=t||null,this.target=t?t.target||t.targetNode||t.srcElement:null,this.deltaY=s,this.deltaX=n;let i=!1;if(Lv){let c=navigator.userAgent.match(/Chrome\/(\d+)/);i=(c?parseInt(c[1]):123)<=122}if(t){let c=t,u=t,h=((l=t.view)==null?void 0:l.devicePixelRatio)||1;if(typeof c.wheelDeltaY<"u")i?this.deltaY=c.wheelDeltaY/(120*h):this.deltaY=c.wheelDeltaY/120;else if(typeof u.VERTICAL_AXIS<"u"&&u.axis===u.VERTICAL_AXIS)this.deltaY=-u.detail/3;else if(t.type==="wheel"){let p=t;p.deltaMode===p.DOM_DELTA_LINE?Ym&&!sr?this.deltaY=-t.deltaY/3:this.deltaY=-t.deltaY:this.deltaY=-t.deltaY/40}if(typeof c.wheelDeltaX<"u")jL&&sk?this.deltaX=-(c.wheelDeltaX/120):i?this.deltaX=c.wheelDeltaX/(120*h):this.deltaX=c.wheelDeltaX/120;else if(typeof u.HORIZONTAL_AXIS<"u"&&u.axis===u.HORIZONTAL_AXIS)this.deltaX=-t.detail/3;else if(t.type==="wheel"){let p=t;p.deltaMode===p.DOM_DELTA_LINE?Ym&&!sr?this.deltaX=-t.deltaX/3:this.deltaX=-t.deltaX:this.deltaX=-t.deltaX/40}this.deltaY===0&&this.deltaX===0&&t.wheelDelta&&(i?this.deltaY=t.wheelDelta/(120*h):this.deltaY=t.wheelDelta/120)}}preventDefault(){var t;(t=this.browserEvent)==null||t.preventDefault()}stopPropagation(){var t;(t=this.browserEvent)==null||t.stopPropagation()}},ok=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),KL;(e=>{function t(n){return n===e.None||n===e.Cancelled||n instanceof VL?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ys.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ok})})(KL||(KL={}));var VL=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?ok:(this._emitter||(this._emitter=new st),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Av=class{constructor(t,n){this._isDisposed=!1,this._token=-1,typeof t=="function"&&typeof n=="number"&&this.setIfNotSet(t,n)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(t,n){if(this._isDisposed)throw new Um("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,t()},n)}setIfNotSet(t,n){if(this._isDisposed)throw new Um("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,t()},n))}},GL=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var t;(t=this.disposable)==null||t.dispose(),this.disposable=void 0}cancelAndSet(t,n,s=globalThis){if(this.isDisposed)throw new Um("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let i=s.setInterval(()=>{t()},n);this.disposable=yn(()=>{s.clearInterval(i),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},YL;(e=>{async function t(s){let i,l=await Promise.all(s.map(c=>c.then(u=>u,u=>{i||(i=u)})));if(typeof i<"u")throw i;return l}e.settled=t;function n(s){return new Promise(async(i,l)=>{try{await s(i,l)}catch(c){l(c)}})}e.withAsyncBody=n})(YL||(YL={}));var Iw=class mi{static fromArray(t){return new mi(n=>{n.emitMany(t)})}static fromPromise(t){return new mi(async n=>{n.emitMany(await t)})}static fromPromises(t){return new mi(async n=>{await Promise.all(t.map(async s=>n.emitOne(await s)))})}static merge(t){return new mi(async n=>{await Promise.all(t.map(async s=>{for await(let i of s)n.emitOne(i)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new st,queueMicrotask(async()=>{let s={emitOne:i=>this.emitOne(i),emitMany:i=>this.emitMany(i),reject:i=>this.reject(i)};try{await Promise.resolve(t(s)),this.resolve()}catch(i){this.reject(i)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await ys.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>{var n;return(n=this._onReturn)==null||n.call(this),{done:!0,value:void 0}}}}static map(t,n){return new mi(async s=>{for await(let i of t)s.emitOne(n(i))})}map(t){return mi.map(this,t)}static filter(t,n){return new mi(async s=>{for await(let i of t)n(i)&&s.emitOne(i)})}filter(t){return mi.filter(this,t)}static coalesce(t){return mi.filter(t,n=>!!n)}coalesce(){return mi.coalesce(this)}static async toPromise(t){let n=[];for await(let s of t)n.push(s);return n}toPromise(){return mi.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};Iw.EMPTY=Iw.fromArray([]);var{getWindow:nr,getWindowId:XL,onDidRegisterWindow:JL}=(function(){let e=new Map,t={window:jr,disposables:new ho};e.set(jr.vscodeWindowId,t);let n=new st,s=new st,i=new st;function l(c,u){return(typeof c=="number"?e.get(c):void 0)??(u?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return qt.None;let u=new ho,h={window:c,disposables:u.add(new ho)};return e.set(c.vscodeWindowId,h),u.add(yn(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),u.add(Ot(c,ss.BEFORE_UNLOAD,()=>{i.fire(c)})),n.fire(h),u},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:l,getWindow(c){var p;let u=c;if((p=u==null?void 0:u.ownerDocument)!=null&&p.defaultView)return u.ownerDocument.defaultView.window;let h=c;return h!=null&&h.view?h.view.window:jr},getDocument(c){return nr(c).document}}})(),QL=class{constructor(t,n,s,i){this._node=t,this._type=n,this._handler=s,this._options=i||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Ot(e,t,n,s){return new QL(e,t,n,s)}var Pw=function(e,t,n,s){return Ot(e,t,n,s)},Mv,ZL=class extends GL{constructor(e){super(),this.defaultTarget=e&&nr(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Dw=class{constructor(t,n=0){this._runner=t,this.priority=n,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(t){kd(t)}}static sort(t,n){return n.priority-t.priority}};(function(){let e=new Map,t=new Map,n=new Map,s=new Map,i=l=>{n.set(l,!1);let c=e.get(l)??[];for(t.set(l,c),e.set(l,[]),s.set(l,!0);c.length>0;)c.sort(Dw.sort),c.shift().execute();s.set(l,!1)};Mv=(l,c,u=0)=>{let h=XL(l),p=new Dw(c,u),v=e.get(h);return v||(v=[],e.set(h,v)),v.push(p),n.get(h)||(n.set(h,!0),l.requestAnimationFrame(()=>i(h))),p}})();function eR(e){let t=e.getBoundingClientRect(),n=nr(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}var ss={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},tR=class{constructor(t){this.domNode=t,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(t){let n=Gs(t);this._maxWidth!==n&&(this._maxWidth=n,this.domNode.style.maxWidth=this._maxWidth)}setWidth(t){let n=Gs(t);this._width!==n&&(this._width=n,this.domNode.style.width=this._width)}setHeight(t){let n=Gs(t);this._height!==n&&(this._height=n,this.domNode.style.height=this._height)}setTop(t){let n=Gs(t);this._top!==n&&(this._top=n,this.domNode.style.top=this._top)}setLeft(t){let n=Gs(t);this._left!==n&&(this._left=n,this.domNode.style.left=this._left)}setBottom(t){let n=Gs(t);this._bottom!==n&&(this._bottom=n,this.domNode.style.bottom=this._bottom)}setRight(t){let n=Gs(t);this._right!==n&&(this._right=n,this.domNode.style.right=this._right)}setPaddingTop(t){let n=Gs(t);this._paddingTop!==n&&(this._paddingTop=n,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(t){let n=Gs(t);this._paddingLeft!==n&&(this._paddingLeft=n,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(t){let n=Gs(t);this._paddingBottom!==n&&(this._paddingBottom=n,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(t){let n=Gs(t);this._paddingRight!==n&&(this._paddingRight=n,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(t){let n=Gs(t);this._fontSize!==n&&(this._fontSize=n,this.domNode.style.fontSize=this._fontSize)}setFontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(t){this._fontFeatureSettings!==t&&(this._fontFeatureSettings=t,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(t){this._fontVariationSettings!==t&&(this._fontVariationSettings=t,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(t){this._textDecoration!==t&&(this._textDecoration=t,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(t){let n=Gs(t);this._lineHeight!==n&&(this._lineHeight=n,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(t){let n=Gs(t);this._letterSpacing!==n&&(this._letterSpacing=n,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(t){this._className!==t&&(this._className=t,this.domNode.className=this._className)}toggleClassName(t,n){this.domNode.classList.toggle(t,n),this._className=this.domNode.className}setDisplay(t){this._display!==t&&(this._display=t,this.domNode.style.display=this._display)}setPosition(t){this._position!==t&&(this._position=t,this.domNode.style.position=this._position)}setVisibility(t){this._visibility!==t&&(this._visibility=t,this.domNode.style.visibility=this._visibility)}setColor(t){this._color!==t&&(this._color=t,this.domNode.style.color=this._color)}setBackgroundColor(t){this._backgroundColor!==t&&(this._backgroundColor=t,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(t){this._layerHint!==t&&(this._layerHint=t,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(t){this._boxShadow!==t&&(this._boxShadow=t,this.domNode.style.boxShadow=t)}setContain(t){this._contain!==t&&(this._contain=t,this.domNode.style.contain=this._contain)}setAttribute(t,n){this.domNode.setAttribute(t,n)}removeAttribute(t){this.domNode.removeAttribute(t)}appendChild(t){this.domNode.appendChild(t.domNode)}removeChild(t){this.domNode.removeChild(t.domNode)}};function Gs(e){return typeof e=="number"?`${e}px`:e}function xc(e){return new tR(e)}var ak=class{constructor(){this._hooks=new ho,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(t,n){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let s=this._onStopCallback;this._onStopCallback=null,t&&s&&s(n)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(t,n,s,i,l){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=i,this._onStopCallback=l;let c=t;try{t.setPointerCapture(n),this._hooks.add(yn(()=>{try{t.releasePointerCapture(n)}catch{}}))}catch{c=nr(t)}this._hooks.add(Ot(c,ss.POINTER_MOVE,u=>{if(u.buttons!==s){this.stopMonitoring(!0);return}u.preventDefault(),this._pointerMoveCallback(u)})),this._hooks.add(Ot(c,ss.POINTER_UP,u=>this.stopMonitoring(!0)))}};function nR(e,t,n){let s=null,i=null;if(typeof n.value=="function"?(s="value",i=n.value,i.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(s="get",i=n.get),!i)throw new Error("not supported");let l=`$memoize$${t}`;n[s]=function(...c){return this.hasOwnProperty(l)||Object.defineProperty(this,l,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,c)}),this[l]}}var Yi;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Yi||(Yi={}));var pc=class Ls extends qt{constructor(){super(),this.dispatched=!1,this.targets=new Ew,this.ignoreTargets=new Ew,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(ys.runAndSubscribe(JL,({window:t,disposables:n})=>{n.add(Ot(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),n.add(Ot(t.document,"touchend",s=>this.onTouchEnd(t,s))),n.add(Ot(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:jr,disposables:this._store}))}static addTarget(t){if(!Ls.isTouchDevice())return qt.None;Ls.INSTANCE||(Ls.INSTANCE=new Ls);let n=Ls.INSTANCE.targets.push(t);return yn(n)}static ignoreTarget(t){if(!Ls.isTouchDevice())return qt.None;Ls.INSTANCE||(Ls.INSTANCE=new Ls);let n=Ls.INSTANCE.ignoreTargets.push(t);return yn(n)}static isTouchDevice(){return"ontouchstart"in jr||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let n=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,i=t.targetTouches.length;s<i;s++){let l=t.targetTouches.item(s);this.activeTouches[l.identifier]={id:l.identifier,initialTarget:l.target,initialTimeStamp:n,initialPageX:l.pageX,initialPageY:l.pageY,rollingTimestamps:[n],rollingPageX:[l.pageX],rollingPageY:[l.pageY]};let c=this.newGestureEvent(Yi.Start,l.target);c.pageX=l.pageX,c.pageY=l.pageY,this.dispatchEvent(c)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,n){let s=Date.now(),i=Object.keys(this.activeTouches).length;for(let l=0,c=n.changedTouches.length;l<c;l++){let u=n.changedTouches.item(l);if(!this.activeTouches.hasOwnProperty(String(u.identifier))){console.warn("move of an UNKNOWN touch",u);continue}let h=this.activeTouches[u.identifier],p=Date.now()-h.initialTimeStamp;if(p<Ls.HOLD_DELAY&&Math.abs(h.initialPageX-si(h.rollingPageX))<30&&Math.abs(h.initialPageY-si(h.rollingPageY))<30){let v=this.newGestureEvent(Yi.Tap,h.initialTarget);v.pageX=si(h.rollingPageX),v.pageY=si(h.rollingPageY),this.dispatchEvent(v)}else if(p>=Ls.HOLD_DELAY&&Math.abs(h.initialPageX-si(h.rollingPageX))<30&&Math.abs(h.initialPageY-si(h.rollingPageY))<30){let v=this.newGestureEvent(Yi.Contextmenu,h.initialTarget);v.pageX=si(h.rollingPageX),v.pageY=si(h.rollingPageY),this.dispatchEvent(v)}else if(i===1){let v=si(h.rollingPageX),_=si(h.rollingPageY),g=si(h.rollingTimestamps)-h.rollingTimestamps[0],w=v-h.rollingPageX[0],S=_-h.rollingPageY[0],N=[...this.targets].filter(C=>h.initialTarget instanceof Node&&C.contains(h.initialTarget));this.inertia(t,N,s,Math.abs(w)/g,w>0?1:-1,v,Math.abs(S)/g,S>0?1:-1,_)}this.dispatchEvent(this.newGestureEvent(Yi.End,h.initialTarget)),delete this.activeTouches[u.identifier]}this.dispatched&&(n.preventDefault(),n.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,n){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=n,s.tapCount=0,s}dispatchEvent(t){if(t.type===Yi.Tap){let n=new Date().getTime(),s=0;n-this._lastSetTapCountTime>Ls.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=n,t.tapCount=s}else(t.type===Yi.Change||t.type===Yi.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let n=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let i=0,l=t.initialTarget;for(;l&&l!==s;)i++,l=l.parentElement;n.push([i,s])}n.sort((s,i)=>s[0]-i[0]);for(let[s,i]of n)i.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,s,i,l,c,u,h,p){this.handle=Mv(t,()=>{let v=Date.now(),_=v-s,g=0,w=0,S=!0;i+=Ls.SCROLL_FRICTION*_,u+=Ls.SCROLL_FRICTION*_,i>0&&(S=!1,g=l*i*_),u>0&&(S=!1,w=h*u*_);let N=this.newGestureEvent(Yi.Change);N.translationX=g,N.translationY=w,n.forEach(C=>C.dispatchEvent(N)),S||this.inertia(t,n,v,i,l,c+g,u,h,p+w)})}onTouchMove(t){let n=Date.now();for(let s=0,i=t.changedTouches.length;s<i;s++){let l=t.changedTouches.item(s);if(!this.activeTouches.hasOwnProperty(String(l.identifier))){console.warn("end of an UNKNOWN touch",l);continue}let c=this.activeTouches[l.identifier],u=this.newGestureEvent(Yi.Change,c.initialTarget);u.translationX=l.pageX-si(c.rollingPageX),u.translationY=l.pageY-si(c.rollingPageY),u.pageX=l.pageX,u.pageY=l.pageY,this.dispatchEvent(u),c.rollingPageX.length>3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(l.pageX),c.rollingPageY.push(l.pageY),c.rollingTimestamps.push(n)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};pc.SCROLL_FRICTION=-.005,pc.HOLD_DELAY=700,pc.CLEAR_TAP_COUNT_TIME=400,Mn([nR],pc,"isTouchDevice",1);var sR=pc,Tv=class extends qt{onclick(t,n){this._register(Ot(t,ss.CLICK,s=>n(new id(nr(t),s))))}onmousedown(t,n){this._register(Ot(t,ss.MOUSE_DOWN,s=>n(new id(nr(t),s))))}onmouseover(t,n){this._register(Ot(t,ss.MOUSE_OVER,s=>n(new id(nr(t),s))))}onmouseleave(t,n){this._register(Ot(t,ss.MOUSE_LEAVE,s=>n(new id(nr(t),s))))}onkeydown(t,n){this._register(Ot(t,ss.KEY_DOWN,s=>n(new Aw(s))))}onkeyup(t,n){this._register(Ot(t,ss.KEY_UP,s=>n(new Aw(s))))}oninput(t,n){this._register(Ot(t,ss.INPUT,n))}onblur(t,n){this._register(Ot(t,ss.BLUR,n))}onfocus(t,n){this._register(Ot(t,ss.FOCUS,n))}onchange(t,n){this._register(Ot(t,ss.CHANGE,n))}ignoreGesture(t){return sR.ignoreTarget(t)}},Ow=11,iR=class extends Tv{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=Ow+"px",this.domNode.style.height=Ow+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new ak),this._register(Pw(this.bgDomNode,ss.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Pw(this.domNode,ss.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new ZL),this._pointerdownScheduleRepeatTimer=this._register(new Av)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,nr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},rR=class Qm{constructor(t,n,s,i,l,c,u){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(n=n|0,s=s|0,i=i|0,l=l|0,c=c|0,u=u|0),this.rawScrollLeft=i,this.rawScrollTop=u,n<0&&(n=0),i+n>s&&(i=s-n),i<0&&(i=0),l<0&&(l=0),u+l>c&&(u=c-l),u<0&&(u=0),this.width=n,this.scrollWidth=s,this.scrollLeft=i,this.height=l,this.scrollHeight=c,this.scrollTop=u}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,n){return new Qm(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Qm(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,n){let s=this.width!==t.width,i=this.scrollWidth!==t.scrollWidth,l=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,u=this.scrollHeight!==t.scrollHeight,h=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:n,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:i,scrollLeftChanged:l,heightChanged:c,scrollHeightChanged:u,scrollTopChanged:h}}},oR=class extends qt{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new st),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new rR(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let s;t?s=new $w(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let n=this._state.withScrollPosition(e);this._smoothScrolling=$w.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Bw=class{constructor(t,n,s){this.scrollLeft=t,this.scrollTop=n,this.isDone=s}};function mp(e,t){let n=t-e;return function(s){return e+n*cR(s)}}function aR(e,t,n){return function(s){return s<n?e(s/n):t((s-n)/(1-n))}}var $w=class Zm{constructor(t,n,s,i){this.from=t,this.to=n,this.duration=i,this.startTime=s,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,n,s){if(Math.abs(t-n)>2.5*s){let i,l;return t<n?(i=t+.75*s,l=n-.75*s):(i=t-.75*s,l=n+.75*s),aR(mp(t,i),mp(l,n),.33)}return mp(t,n)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(t){this.to=t.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(t){let n=(t-this.startTime)/this.duration;if(n<1){let s=this.scrollLeft(n),i=this.scrollTop(n);return new Bw(s,i,!1)}return new Bw(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,s){return Zm.start(t,n,s)}static start(t,n,s){s=s+10;let i=Date.now()-10;return new Zm(t,n,i,s)}};function lR(e){return Math.pow(e,3)}function cR(e){return 1-lR(1-e)}var uR=class extends qt{constructor(t,n,s){super(),this._visibility=t,this._visibleClassName=n,this._invisibleClassName=s,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Av)}setVisibility(t){this._visibility!==t&&(this._visibility=t,this._updateShouldBeVisible())}setShouldBeVisible(t){this._rawShouldBeVisible=t,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let t=this._applyVisibilitySetting();this._shouldBeVisible!==t&&(this._shouldBeVisible=t,this.ensureVisibility())}setIsNeeded(t){this._isNeeded!==t&&(this._isNeeded=t,this.ensureVisibility())}setDomNode(t){this._domNode=t,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{var t;(t=this._domNode)==null||t.setClassName(this._visibleClassName)},0))}_hide(t){var n;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(n=this._domNode)==null||n.setClassName(this._invisibleClassName+(t?" fade":"")))}},dR=140,lk=class extends Tv{constructor(t){super(),this._lazyRender=t.lazyRender,this._host=t.host,this._scrollable=t.scrollable,this._scrollByPage=t.scrollByPage,this._scrollbarState=t.scrollbarState,this._visibilityController=this._register(new uR(t.visibility,"visible scrollbar "+t.extraScrollbarClassName,"invisible scrollbar "+t.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new ak),this._shouldRender=!0,this.domNode=xc(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ot(this.domNode.domNode,ss.POINTER_DOWN,n=>this._domNodePointerDown(n)))}_createArrow(t){let n=this._register(new iR(t));this.domNode.domNode.appendChild(n.bgDomNode),this.domNode.domNode.appendChild(n.domNode)}_createSlider(t,n,s,i){this.slider=xc(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(t),this.slider.setLeft(n),typeof s=="number"&&this.slider.setWidth(s),typeof i=="number"&&this.slider.setHeight(i),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ot(this.slider.domNode,ss.POINTER_DOWN,l=>{l.button===0&&(l.preventDefault(),this._sliderPointerDown(l))})),this.onclick(this.slider.domNode,l=>{l.leftButton&&l.stopPropagation()})}_onElementSize(t){return this._scrollbarState.setVisibleSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(t){return this._scrollbarState.setScrollSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(t){return this._scrollbarState.setScrollPosition(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(t){t.target===this.domNode.domNode&&this._onPointerDown(t)}delegatePointerDown(t){let n=this.domNode.domNode.getClientRects()[0].top,s=n+this._scrollbarState.getSliderPosition(),i=n+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),l=this._sliderPointerPosition(t);s<=l&&l<=i?t.button===0&&(t.preventDefault(),this._sliderPointerDown(t)):this._onPointerDown(t)}_onPointerDown(t){let n,s;if(t.target===this.domNode.domNode&&typeof t.offsetX=="number"&&typeof t.offsetY=="number")n=t.offsetX,s=t.offsetY;else{let l=eR(this.domNode.domNode);n=t.pageX-l.left,s=t.pageY-l.top}let i=this._pointerDownRelativePosition(n,s);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(i):this._scrollbarState.getDesiredScrollPositionFromOffset(i)),t.button===0&&(t.preventDefault(),this._sliderPointerDown(t))}_sliderPointerDown(t){if(!t.target||!(t.target instanceof Element))return;let n=this._sliderPointerPosition(t),s=this._sliderOrthogonalPointerPosition(t),i=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(t.target,t.pointerId,t.buttons,l=>{let c=this._sliderOrthogonalPointerPosition(l),u=Math.abs(c-s);if(sk&&u>dR){this._setDesiredScrollPositionNow(i.getScrollPosition());return}let h=this._sliderPointerPosition(l)-n;this._setDesiredScrollPositionNow(i.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(t){let n={};this.writeScrollPosition(n,t),this._scrollable.setScrollPositionNow(n)}updateScrollbarSize(t){this._updateScrollbarSize(t),this._scrollbarState.setScrollbarSize(t),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},ck=class eg{constructor(t,n,s,i,l,c){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=i,this._scrollSize=l,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new eg(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let n=Math.round(t);return this._visibleSize!==n?(this._visibleSize=n,this._refreshComputedValues(),!0):!1}setScrollSize(t){let n=Math.round(t);return this._scrollSize!==n?(this._scrollSize=n,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let n=Math.round(t);return this._scrollPosition!==n?(this._scrollPosition=n,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,n,s,i,l){let c=Math.max(0,s-t),u=Math.max(0,c-2*n),h=i>0&&i>s;if(!h)return{computedAvailableSize:Math.round(c),computedIsNeeded:h,computedSliderSize:Math.round(u),computedSliderRatio:0,computedSliderPosition:0};let p=Math.round(Math.max(20,Math.floor(s*u/i))),v=(u-p)/(i-s),_=l*v;return{computedAvailableSize:Math.round(c),computedIsNeeded:h,computedSliderSize:Math.round(p),computedSliderRatio:v,computedSliderPosition:Math.round(_)}}_refreshComputedValues(){let t=eg._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize,s=this._scrollPosition;return n<this._computedSliderPosition?s-=this._visibleSize:s+=this._visibleSize,s}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let n=this._computedSliderPosition+t;return Math.round(n/this._computedSliderRatio)}},hR=class extends lk{constructor(t,n,s){let i=t.getScrollDimensions(),l=t.getCurrentScrollPosition();if(super({lazyRender:n.lazyRender,host:s,scrollbarState:new ck(n.horizontalHasArrows?n.arrowSize:0,n.horizontal===2?0:n.horizontalScrollbarSize,n.vertical===2?0:n.verticalScrollbarSize,i.width,i.scrollWidth,l.scrollLeft),visibility:n.horizontal,extraScrollbarClassName:"horizontal",scrollable:t,scrollByPage:n.scrollByPage}),n.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((n.horizontalScrollbarSize-n.horizontalSliderSize)/2),0,void 0,n.horizontalSliderSize)}_updateSlider(t,n){this.slider.setWidth(t),this.slider.setLeft(n)}_renderDomNode(t,n){this.domNode.setWidth(t),this.domNode.setHeight(n),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(t){return this._shouldRender=this._onElementScrollSize(t.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(t.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(t.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(t,n){return t}_sliderPointerPosition(t){return t.pageX}_sliderOrthogonalPointerPosition(t){return t.pageY}_updateScrollbarSize(t){this.slider.setHeight(t)}writeScrollPosition(t,n){t.scrollLeft=n}updateOptions(t){this.updateScrollbarSize(t.horizontal===2?0:t.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(t.vertical===2?0:t.verticalScrollbarSize),this._visibilityController.setVisibility(t.horizontal),this._scrollByPage=t.scrollByPage}},fR=class extends lk{constructor(e,t,n){let s=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new ck(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},pR=500,zw=50,mR=class{constructor(t,n,s){this.timestamp=t,this.deltaX=n,this.deltaY=s,this.score=0}},tg=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let t=1,n=0,s=1,i=this._rear;do{let l=i===this._front?t:Math.pow(2,-s);if(t-=l,n+=this._memory[i].score*l,i===this._front)break;i=(this._capacity+i-1)%this._capacity,s++}while(!0);return n<=.5}acceptStandardWheelEvent(t){if(Lv){let n=nr(t.browserEvent),s=EL(n);this.accept(Date.now(),t.deltaX*s,t.deltaY*s)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,n,s){let i=null,l=new mR(t,n,s);this._front===-1&&this._rear===-1?(this._memory[0]=l,this._front=0,this._rear=0):(i=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=l),l.score=this._computeScore(l,i)}_computeScore(t,n){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),n){let i=Math.abs(t.deltaX),l=Math.abs(t.deltaY),c=Math.abs(n.deltaX),u=Math.abs(n.deltaY),h=Math.max(Math.min(i,c),1),p=Math.max(Math.min(l,u),1),v=Math.max(i,c),_=Math.max(l,u);v%h===0&&_%p===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};tg.INSTANCE=new tg;var gR=tg,vR=class extends Tv{constructor(e,t,n){super(),this._onScroll=this._register(new st),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new st),this.onWillScroll=this._onWillScroll.event,this._options=yR(t),this._scrollable=n,this._register(this._scrollable.onScroll(i=>{this._onWillScroll.fire(i),this._onDidScroll(i),this._onScroll.fire(i)}));let s={onMouseWheel:i=>this._onMouseWheel(i),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new fR(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new hR(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=xc(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=xc(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=xc(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,i=>this._onMouseOver(i)),this.onmouseleave(this._listenOnDomNode,i=>this._onMouseLeave(i)),this._hideTimeout=this._register(new Av),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Qo(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,sr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Tw(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Qo(this._mouseWheelToDispose),e)){let t=n=>{this._onMouseWheel(new Tw(n))};this._mouseWheelToDispose.push(Ot(this._listenOnDomNode,ss.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var i;if((i=e.browserEvent)!=null&&i.defaultPrevented)return;let t=gR.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let l=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+l===0?c=l=0:Math.abs(l)>=Math.abs(c)?c=0:l=0),this._options.flipAxes&&([l,c]=[c,l]);let u=!sr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||u)&&!c&&(c=l,l=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,l=l*this._options.fastScrollSensitivity);let h=this._scrollable.getFutureScrollPosition(),p={};if(l){let v=zw*l,_=h.scrollTop-(v<0?Math.floor(v):Math.ceil(v));this._verticalScrollbar.writeScrollPosition(p,_)}if(c){let v=zw*c,_=h.scrollLeft-(v<0?Math.floor(v):Math.ceil(v));this._horizontalScrollbar.writeScrollPosition(p,_)}p=this._scrollable.validateScrollPosition(p),(h.scrollLeft!==p.scrollLeft||h.scrollTop!==p.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(p):this._scrollable.setScrollPositionNow(p),n=!0)}let s=n;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,s=n?" left":"",i=t?" top":"",l=n||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${l}${i}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),pR)}},_R=class extends vR{constructor(t,n,s){super(t,n,s)}setScrollPosition(t){t.reuseAnimation?this._scrollable.setScrollPositionSmooth(t,t.reuseAnimation):this._scrollable.setScrollPositionNow(t)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function yR(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,sr&&(t.className+=" mac"),t}var ng=class extends qt{constructor(t,n,s,i,l,c,u,h){super(),this._bufferService=s,this._optionsService=u,this._renderService=h,this._onRequestScrollLines=this._register(new st),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new oR({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:v=>Mv(i.window,v)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new _R(n,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(l.onProtocolChange(v=>{this._scrollableElement.updateOptions({handleMouseWheel:!(v&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(ys.runAndSubscribe(c.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=c.colors.background.css})),t.appendChild(this._scrollableElement.getDomNode()),this._register(yn(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=i.mainDocument.createElement("style"),n.appendChild(this._styleElement),this._register(yn(()=>this._styleElement.remove())),this._register(ys.runAndSubscribe(c.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${c.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${c.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${c.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
60
+ `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(v=>this._handleScroll(v)))}scrollLines(t){let n=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:n.scrollTop+t*this._renderService.dimensions.css.cell.height})}scrollToLine(t,n){n&&(this._latestYDisp=t),this._scrollableElement.setScrollPosition({reuseAnimation:!n,scrollTop:t*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var t;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((t=this._optionsService.rawOptions.overviewRuler)==null?void 0:t.width)||14}}queueSync(t){t!==void 0&&(this._latestYDisp=t),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(t=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,t!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:t*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(t){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let n=Math.round(t.scrollTop/this._renderService.dimensions.css.cell.height),s=n-this._bufferService.buffer.ydisp;s!==0&&(this._latestYDisp=n,this._onRequestScrollLines.fire(s)),this._isHandlingScroll=!1}};ng=Mn([dt(2,zs),dt(3,Mr),dt(4,U1),dt(5,ol),dt(6,Fs),dt(7,Tr)],ng);var sg=class extends qt{constructor(t,n,s,i,l){super(),this._screenElement=t,this._bufferService=n,this._coreBrowserService=s,this._decorationService=i,this._renderService=l,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(c=>this._removeDecoration(c))),this._register(yn(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let t of this._decorationService.decorations)this._renderDecoration(t);this._dimensionsChanged=!1}_renderDecoration(t){this._refreshStyle(t),this._dimensionsChanged&&this._refreshXPosition(t)}_createElement(t){var i;let n=this._coreBrowserService.mainDocument.createElement("div");n.classList.add("xterm-decoration"),n.classList.toggle("xterm-decoration-top-layer",((i=t==null?void 0:t.options)==null?void 0:i.layer)==="top"),n.style.width=`${Math.round((t.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(t.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${(t.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let s=t.options.x??0;return s&&s>this._bufferService.cols&&(n.style.display="none"),this._refreshXPosition(t,n),n}_refreshStyle(t){let n=t.marker.line-this._bufferService.buffers.active.ydisp;if(n<0||n>=this._bufferService.rows)t.element&&(t.element.style.display="none",t.onRenderEmitter.fire(t.element));else{let s=this._decorationElements.get(t);s||(s=this._createElement(t),t.element=s,this._decorationElements.set(t,s),this._container.appendChild(s),t.onDispose(()=>{this._decorationElements.delete(t),s.remove()})),s.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(s.style.width=`${Math.round((t.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,s.style.height=`${(t.options.height||1)*this._renderService.dimensions.css.cell.height}px`,s.style.top=`${n*this._renderService.dimensions.css.cell.height}px`,s.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),t.onRenderEmitter.fire(s)}}_refreshXPosition(t,n=t.element){if(!n)return;let s=t.options.x??0;(t.options.anchor||"left")==="right"?n.style.right=s?`${s*this._renderService.dimensions.css.cell.width}px`:"":n.style.left=s?`${s*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(t){var n;(n=this._decorationElements.get(t))==null||n.remove(),this._decorationElements.delete(t),t.dispose()}};sg=Mn([dt(1,zs),dt(2,Mr),dt(3,Jc),dt(4,Tr)],sg);var bR=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(t){if(t.options.overviewRulerOptions){for(let n of this._zones)if(n.color===t.options.overviewRulerOptions.color&&n.position===t.options.overviewRulerOptions.position){if(this._lineIntersectsZone(n,t.marker.line))return;if(this._lineAdjacentToZone(n,t.marker.line,t.options.overviewRulerOptions.position)){this._addLineToZone(n,t.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=t.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=t.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=t.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=t.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:t.options.overviewRulerOptions.color,position:t.options.overviewRulerOptions.position,startBufferLine:t.marker.line,endBufferLine:t.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(t){this._linePadding=t}_lineIntersectsZone(t,n){return n>=t.startBufferLine&&n<=t.endBufferLine}_lineAdjacentToZone(t,n,s){return n>=t.startBufferLine-this._linePadding[s||"full"]&&n<=t.endBufferLine+this._linePadding[s||"full"]}_addLineToZone(t,n){t.startBufferLine=Math.min(t.startBufferLine,n),t.endBufferLine=Math.max(t.endBufferLine,n)}},qi={full:0,left:0,center:0,right:0},Jr={full:0,left:0,center:0,right:0},Kl={full:0,left:0,center:0,right:0},Fd=class extends qt{constructor(t,n,s,i,l,c,u,h){var v;super(),this._viewportElement=t,this._screenElement=n,this._bufferService=s,this._decorationService=i,this._renderService=l,this._optionsService=c,this._themeService=u,this._coreBrowserService=h,this._colorZoneStore=new bR,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(v=this._viewportElement.parentElement)==null||v.insertBefore(this._canvas,this._viewportElement),this._register(yn(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var t;return((t=this._optionsService.options.overviewRuler)==null?void 0:t.width)||0}_refreshDrawConstants(){let t=Math.floor((this._canvas.width-1)/3),n=Math.ceil((this._canvas.width-1)/3);Jr.full=this._canvas.width,Jr.left=t,Jr.center=n,Jr.right=t,this._refreshDrawHeightConstants(),Kl.full=1,Kl.left=1,Kl.center=1+Jr.left,Kl.right=1+Jr.left+Jr.center}_refreshDrawHeightConstants(){qi.full=Math.round(2*this._coreBrowserService.dpr);let t=this._canvas.height/this._bufferService.buffer.lines.length,n=Math.round(Math.max(Math.min(t,12),6)*this._coreBrowserService.dpr);qi.left=n,qi.center=n,qi.right=n}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*qi.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*qi.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*qi.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*qi.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let n of this._decorationService.decorations)this._colorZoneStore.addDecoration(n);this._ctx.lineWidth=1,this._renderRulerOutline();let t=this._colorZoneStore.zones;for(let n of t)n.position!=="full"&&this._renderColorZone(n);for(let n of t)n.position==="full"&&this._renderColorZone(n);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(t){this._ctx.fillStyle=t.color,this._ctx.fillRect(Kl[t.position||"full"],Math.round((this._canvas.height-1)*(t.startBufferLine/this._bufferService.buffers.active.lines.length)-qi[t.position||"full"]/2),Jr[t.position||"full"],Math.round((this._canvas.height-1)*((t.endBufferLine-t.startBufferLine)/this._bufferService.buffers.active.lines.length)+qi[t.position||"full"]))}_queueRefresh(t,n){this._shouldUpdateDimensions=t||this._shouldUpdateDimensions,this._shouldUpdateAnchor=n||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Fd=Mn([dt(2,zs),dt(3,Jc),dt(4,Tr),dt(5,Fs),dt(6,ol),dt(7,Mr)],Fd);var Fe;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=`
61
+ `,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(Fe||(Fe={}));var Nd;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(Nd||(Nd={}));var uk;(e=>e.ST=`${Fe.ESC}\\`)(uk||(uk={}));var ig=class{constructor(t,n,s,i,l,c){this._textarea=t,this._compositionView=n,this._bufferService=s,this._optionsService=i,this._coreService=l,this._renderService=c,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(t){this._compositionView.textContent=t.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(t){if(this._isComposing||this._isSendingComposition){if(t.keyCode===20||t.keyCode===229||t.keyCode===16||t.keyCode===17||t.keyCode===18)return!1;this._finalizeComposition(!1)}return t.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(t){if(this._compositionView.classList.remove("active"),this._isComposing=!1,t){let n={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let s;n.start+=this._dataAlreadySent.length,this._isComposing?s=this._textarea.value.substring(n.start,this._compositionPosition.start):s=this._textarea.value.substring(n.start),s.length>0&&this._coreService.triggerDataEvent(s,!0)}},0)}else{this._isSendingComposition=!1;let n=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(n,!0)}}_handleAnyTextareaChanges(){let t=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let n=this._textarea.value,s=n.replace(t,"");this._dataAlreadySent=s,n.length>t.length?this._coreService.triggerDataEvent(s,!0):n.length<t.length?this._coreService.triggerDataEvent(`${Fe.DEL}`,!0):n.length===t.length&&n!==t&&this._coreService.triggerDataEvent(n,!0)}},0)}updateCompositionElements(t){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let n=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),s=this._renderService.dimensions.css.cell.height,i=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,l=n*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=l+"px",this._compositionView.style.top=i+"px",this._compositionView.style.height=s+"px",this._compositionView.style.lineHeight=s+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let c=this._compositionView.getBoundingClientRect();this._textarea.style.left=l+"px",this._textarea.style.top=i+"px",this._textarea.style.width=Math.max(c.width,1)+"px",this._textarea.style.height=Math.max(c.height,1)+"px",this._textarea.style.lineHeight=c.height+"px"}t||setTimeout(()=>this.updateCompositionElements(!0),0)}}};ig=Mn([dt(2,zs),dt(3,Fs),dt(4,na),dt(5,Tr)],ig);var is=0,rs=0,os=0,Rn=0,Fw={css:"#00000000",rgba:0},zn;(e=>{function t(i,l,c,u){return u!==void 0?`#${To(i)}${To(l)}${To(c)}${To(u)}`:`#${To(i)}${To(l)}${To(c)}`}e.toCss=t;function n(i,l,c,u=255){return(i<<24|l<<16|c<<8|u)>>>0}e.toRgba=n;function s(i,l,c,u){return{css:e.toCss(i,l,c,u),rgba:e.toRgba(i,l,c,u)}}e.toColor=s})(zn||(zn={}));var gn;(e=>{function t(h,p){if(Rn=(p.rgba&255)/255,Rn===1)return{css:p.css,rgba:p.rgba};let v=p.rgba>>24&255,_=p.rgba>>16&255,g=p.rgba>>8&255,w=h.rgba>>24&255,S=h.rgba>>16&255,N=h.rgba>>8&255;is=w+Math.round((v-w)*Rn),rs=S+Math.round((_-S)*Rn),os=N+Math.round((g-N)*Rn);let C=zn.toCss(is,rs,os),j=zn.toRgba(is,rs,os);return{css:C,rgba:j}}e.blend=t;function n(h){return(h.rgba&255)===255}e.isOpaque=n;function s(h,p,v){let _=jd.ensureContrastRatio(h.rgba,p.rgba,v);if(_)return zn.toColor(_>>24&255,_>>16&255,_>>8&255)}e.ensureContrastRatio=s;function i(h){let p=(h.rgba|255)>>>0;return[is,rs,os]=jd.toChannels(p),{css:zn.toCss(is,rs,os),rgba:p}}e.opaque=i;function l(h,p){return Rn=Math.round(p*255),[is,rs,os]=jd.toChannels(h.rgba),{css:zn.toCss(is,rs,os,Rn),rgba:zn.toRgba(is,rs,os,Rn)}}e.opacity=l;function c(h,p){return Rn=h.rgba&255,l(h,Rn*p/255)}e.multiplyOpacity=c;function u(h){return[h.rgba>>24&255,h.rgba>>16&255,h.rgba>>8&255]}e.toColorRGB=u})(gn||(gn={}));var Cn;(e=>{let t,n;try{let i=document.createElement("canvas");i.width=1,i.height=1;let l=i.getContext("2d",{willReadFrequently:!0});l&&(t=l,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function s(i){if(i.match(/#[\da-f]{3,8}/i))switch(i.length){case 4:return is=parseInt(i.slice(1,2).repeat(2),16),rs=parseInt(i.slice(2,3).repeat(2),16),os=parseInt(i.slice(3,4).repeat(2),16),zn.toColor(is,rs,os);case 5:return is=parseInt(i.slice(1,2).repeat(2),16),rs=parseInt(i.slice(2,3).repeat(2),16),os=parseInt(i.slice(3,4).repeat(2),16),Rn=parseInt(i.slice(4,5).repeat(2),16),zn.toColor(is,rs,os,Rn);case 7:return{css:i,rgba:(parseInt(i.slice(1),16)<<8|255)>>>0};case 9:return{css:i,rgba:parseInt(i.slice(1),16)>>>0}}let l=i.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return is=parseInt(l[1]),rs=parseInt(l[2]),os=parseInt(l[3]),Rn=Math.round((l[5]===void 0?1:parseFloat(l[5]))*255),zn.toColor(is,rs,os,Rn);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=i,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[is,rs,os,Rn]=t.getImageData(0,0,1,1).data,Rn!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:zn.toRgba(is,rs,os,Rn),css:i}}e.toColor=s})(Cn||(Cn={}));var Os;(e=>{function t(s){return n(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function n(s,i,l){let c=s/255,u=i/255,h=l/255,p=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),v=u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4);return p*.2126+v*.7152+_*.0722}e.relativeLuminance2=n})(Os||(Os={}));var jd;(e=>{function t(c,u){if(Rn=(u&255)/255,Rn===1)return u;let h=u>>24&255,p=u>>16&255,v=u>>8&255,_=c>>24&255,g=c>>16&255,w=c>>8&255;return is=_+Math.round((h-_)*Rn),rs=g+Math.round((p-g)*Rn),os=w+Math.round((v-w)*Rn),zn.toRgba(is,rs,os)}e.blend=t;function n(c,u,h){let p=Os.relativeLuminance(c>>8),v=Os.relativeLuminance(u>>8);if(wr(p,v)<h){if(v<p){let w=s(c,u,h),S=wr(p,Os.relativeLuminance(w>>8));if(S<h){let N=i(c,u,h),C=wr(p,Os.relativeLuminance(N>>8));return S>C?w:N}return w}let _=i(c,u,h),g=wr(p,Os.relativeLuminance(_>>8));if(g<h){let w=s(c,u,h),S=wr(p,Os.relativeLuminance(w>>8));return g>S?_:w}return _}}e.ensureContrastRatio=n;function s(c,u,h){let p=c>>24&255,v=c>>16&255,_=c>>8&255,g=u>>24&255,w=u>>16&255,S=u>>8&255,N=wr(Os.relativeLuminance2(g,w,S),Os.relativeLuminance2(p,v,_));for(;N<h&&(g>0||w>0||S>0);)g-=Math.max(0,Math.ceil(g*.1)),w-=Math.max(0,Math.ceil(w*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=wr(Os.relativeLuminance2(g,w,S),Os.relativeLuminance2(p,v,_));return(g<<24|w<<16|S<<8|255)>>>0}e.reduceLuminance=s;function i(c,u,h){let p=c>>24&255,v=c>>16&255,_=c>>8&255,g=u>>24&255,w=u>>16&255,S=u>>8&255,N=wr(Os.relativeLuminance2(g,w,S),Os.relativeLuminance2(p,v,_));for(;N<h&&(g<255||w<255||S<255);)g=Math.min(255,g+Math.ceil((255-g)*.1)),w=Math.min(255,w+Math.ceil((255-w)*.1)),S=Math.min(255,S+Math.ceil((255-S)*.1)),N=wr(Os.relativeLuminance2(g,w,S),Os.relativeLuminance2(p,v,_));return(g<<24|w<<16|S<<8|255)>>>0}e.increaseLuminance=i;function l(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=l})(jd||(jd={}));function To(e){let t=e.toString(16);return t.length<2?"0"+t:t}function wr(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var wR=class extends Xc{constructor(t,n,s){super(),this.content=0,this.combinedData="",this.fg=t.fg,this.bg=t.bg,this.combinedData=n,this._width=s}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(t){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Hd=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Si}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],s=t.translateToString(!0),i=0,l=0,c=0,u=t.getFg(0),h=t.getBg(0);for(let p=0;p<t.getTrimmedLength();p++)if(t.loadCell(p,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==u||this._workCell.bg!==h){if(p-i>1){let v=this._getJoinedRanges(s,c,l,t,i);for(let _=0;_<v.length;_++)n.push(v[_])}i=p,c=l,u=this._workCell.fg,h=this._workCell.bg}l+=this._workCell.getChars().length||lo.length}if(this._bufferService.cols-i>1){let p=this._getJoinedRanges(s,c,l,t,i);for(let v=0;v<p.length;v++)n.push(p[v])}return n}_getJoinedRanges(e,t,n,s,i){let l=e.substring(t,n),c=[];try{c=this._characterJoiners[0].handler(l)}catch(u){console.error(u)}for(let u=1;u<this._characterJoiners.length;u++)try{let h=this._characterJoiners[u].handler(l);for(let p=0;p<h.length;p++)Hd._mergeRanges(c,h[p])}catch(h){console.error(h)}return this._stringRangesToCellRanges(c,s,i),c}_stringRangesToCellRanges(e,t,n){let s=0,i=!1,l=0,c=e[s];if(c){for(let u=n;u<this._bufferService.cols;u++){let h=t.getWidth(u),p=t.getString(u).length||lo.length;if(h!==0){if(!i&&c[0]<=l&&(c[0]=u,i=!0),c[1]<=l){if(c[1]=u,c=e[++s],!c)break;c[0]<=l?(c[0]=u,i=!0):i=!1}l+=p}}c&&(c[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(n){if(t[1]<=i[0])return e[s-1][1]=t[1],e;if(t[1]<=i[1])return e[s-1][1]=Math.max(t[1],i[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=i[0])return e.splice(s,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};Hd=Mn([dt(0,zs)],Hd);function SR(e){return 57508<=e&&e<=57558}function xR(e){return 9472<=e&&e<=9631}function kR(e){return SR(e)||xR(e)}function CR(){return{css:{canvas:rd(),cell:rd()},device:{canvas:rd(),cell:rd(),char:{width:0,height:0,left:0,top:0}}}}function rd(){return{width:0,height:0}}var rg=class{constructor(t,n,s,i,l,c,u){this._document=t,this._characterJoinerService=n,this._optionsService=s,this._coreBrowserService=i,this._coreService=l,this._decorationService=c,this._themeService=u,this._workCell=new Si,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(t,n,s){this._selectionStart=t,this._selectionEnd=n,this._columnSelectMode=s}createRow(t,n,s,i,l,c,u,h,p,v,_){let g=[],w=this._characterJoinerService.getJoinedCharacters(n),S=this._themeService.colors,N=t.getNoBgTrimmedLength();s&&N<c+1&&(N=c+1);let C,j=0,E="",R=0,x=0,W=0,$=0,Y=!1,q=0,K=!1,se=0,V=0,B=[],D=v!==-1&&_!==-1;for(let O=0;O<N;O++){t.loadCell(O,this._workCell);let P=this._workCell.getWidth();if(P===0)continue;let z=!1,A=O>=V,T=O,L=this._workCell;if(w.length>0&&O===w[0][0]&&A){let J=w.shift(),le=this._isCellInSelection(J[0],n);for(R=J[0]+1;R<J[1];R++)A&&(A=le===this._isCellInSelection(R,n));A&&(A=!s||c<J[0]||c>=J[1]),A?(z=!0,L=new wR(this._workCell,t.translateToString(!0,J[0],J[1]),J[1]-J[0]),T=J[1]-1,P=L.getWidth()):V=J[1]}let H=this._isCellInSelection(O,n),M=s&&O===c,U=D&&O>=v&&O<=_,ee=!1;this._decorationService.forEachDecorationAtCell(O,n,void 0,J=>{ee=!0});let re=L.getChars()||lo;if(re===" "&&(L.isUnderline()||L.isOverline())&&(re=" "),se=P*h-p.get(re,L.isBold(),L.isItalic()),!C)C=this._document.createElement("span");else if(j&&(H&&K||!H&&!K&&L.bg===x)&&(H&&K&&S.selectionForeground||L.fg===W)&&L.extended.ext===$&&U===Y&&se===q&&!M&&!z&&!ee&&A){L.isInvisible()?E+=lo:E+=re,j++;continue}else j&&(C.textContent=E),C=this._document.createElement("span"),j=0,E="";if(x=L.bg,W=L.fg,$=L.extended.ext,Y=U,q=se,K=H,z&&c>=O&&c<=T&&(c=O),!this._coreService.isCursorHidden&&M&&this._coreService.isCursorInitialized){if(B.push("xterm-cursor"),this._coreBrowserService.isFocused)u&&B.push("xterm-cursor-blink"),B.push(i==="bar"?"xterm-cursor-bar":i==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(l)switch(l){case"outline":B.push("xterm-cursor-outline");break;case"block":B.push("xterm-cursor-block");break;case"bar":B.push("xterm-cursor-bar");break;case"underline":B.push("xterm-cursor-underline");break}}if(L.isBold()&&B.push("xterm-bold"),L.isItalic()&&B.push("xterm-italic"),L.isDim()&&B.push("xterm-dim"),L.isInvisible()?E=lo:E=L.getChars()||lo,L.isUnderline()&&(B.push(`xterm-underline-${L.extended.underlineStyle}`),E===" "&&(E=" "),!L.isUnderlineColorDefault()))if(L.isUnderlineColorRGB())C.style.textDecorationColor=`rgb(${Xc.toColorRGB(L.getUnderlineColor()).join(",")})`;else{let J=L.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&L.isBold()&&J<8&&(J+=8),C.style.textDecorationColor=S.ansi[J].css}L.isOverline()&&(B.push("xterm-overline"),E===" "&&(E=" ")),L.isStrikethrough()&&B.push("xterm-strikethrough"),U&&(C.style.textDecoration="underline");let oe=L.getFgColor(),je=L.getFgColorMode(),te=L.getBgColor(),ie=L.getBgColorMode(),pe=!!L.isInverse();if(pe){let J=oe;oe=te,te=J;let le=je;je=ie,ie=le}let xe,Be,Te=!1;this._decorationService.forEachDecorationAtCell(O,n,void 0,J=>{J.options.layer!=="top"&&Te||(J.backgroundColorRGB&&(ie=50331648,te=J.backgroundColorRGB.rgba>>8&16777215,xe=J.backgroundColorRGB),J.foregroundColorRGB&&(je=50331648,oe=J.foregroundColorRGB.rgba>>8&16777215,Be=J.foregroundColorRGB),Te=J.options.layer==="top")}),!Te&&H&&(xe=this._coreBrowserService.isFocused?S.selectionBackgroundOpaque:S.selectionInactiveBackgroundOpaque,te=xe.rgba>>8&16777215,ie=50331648,Te=!0,S.selectionForeground&&(je=50331648,oe=S.selectionForeground.rgba>>8&16777215,Be=S.selectionForeground)),Te&&B.push("xterm-decoration-top");let Me;switch(ie){case 16777216:case 33554432:Me=S.ansi[te],B.push(`xterm-bg-${te}`);break;case 50331648:Me=zn.toColor(te>>16,te>>8&255,te&255),this._addStyle(C,`background-color:#${Hw((te>>>0).toString(16),"0",6)}`);break;case 0:default:pe?(Me=S.foreground,B.push("xterm-bg-257")):Me=S.background}switch(xe||L.isDim()&&(xe=gn.multiplyOpacity(Me,.5)),je){case 16777216:case 33554432:L.isBold()&&oe<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(oe+=8),this._applyMinimumContrast(C,Me,S.ansi[oe],L,xe,void 0)||B.push(`xterm-fg-${oe}`);break;case 50331648:let J=zn.toColor(oe>>16&255,oe>>8&255,oe&255);this._applyMinimumContrast(C,Me,J,L,xe,Be)||this._addStyle(C,`color:#${Hw(oe.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(C,Me,S.foreground,L,xe,Be)||pe&&B.push("xterm-fg-257")}B.length&&(C.className=B.join(" "),B.length=0),!M&&!z&&!ee&&A?j++:C.textContent=E,se!==this.defaultSpacing&&(C.style.letterSpacing=`${se}px`),g.push(C),O=T}return C&&j&&(C.textContent=E),g}_applyMinimumContrast(t,n,s,i,l,c){if(this._optionsService.rawOptions.minimumContrastRatio===1||kR(i.getCode()))return!1;let u=this._getContrastCache(i),h;if(!l&&!c&&(h=u.getColor(n.rgba,s.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(i.isDim()?2:1);h=gn.ensureContrastRatio(l||n,c||s,p),u.setColor((l||n).rgba,(c||s).rgba,h??null)}return h?(this._addStyle(t,`color:${h.css}`),!0):!1}_getContrastCache(t){return t.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(t,n){t.setAttribute("style",`${t.getAttribute("style")||""}${n};`)}_isCellInSelection(t,n){let s=this._selectionStart,i=this._selectionEnd;return!s||!i?!1:this._columnSelectMode?s[0]<=i[0]?t>=s[0]&&n>=s[1]&&t<i[0]&&n<=i[1]:t<s[0]&&n>=s[1]&&t>=i[0]&&n<=i[1]:n>s[1]&&n<i[1]||s[1]===i[1]&&n===s[1]&&t>=s[0]&&t<i[0]||s[1]<i[1]&&n===i[1]&&t<i[0]||s[1]<i[1]&&n===s[1]&&t>=s[0]}};rg=Mn([dt(1,K1),dt(2,Fs),dt(3,Mr),dt(4,na),dt(5,Jc),dt(6,ol)],rg);function Hw(e,t,n){for(;e.length<n;)e=t+e;return e}var ER=class{constructor(t,n){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=t.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let s=t.createElement("span");s.classList.add("xterm-char-measure-element");let i=t.createElement("span");i.classList.add("xterm-char-measure-element"),i.style.fontWeight="bold";let l=t.createElement("span");l.classList.add("xterm-char-measure-element"),l.style.fontStyle="italic";let c=t.createElement("span");c.classList.add("xterm-char-measure-element"),c.style.fontWeight="bold",c.style.fontStyle="italic",this._measureElements=[s,i,l,c],this._container.appendChild(s),this._container.appendChild(i),this._container.appendChild(l),this._container.appendChild(c),n.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(t,n,s,i){t===this._font&&n===this._fontSize&&s===this._weight&&i===this._weightBold||(this._font=t,this._fontSize=n,this._weight=s,this._weightBold=i,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${s}`,this._measureElements[1].style.fontWeight=`${i}`,this._measureElements[2].style.fontWeight=`${s}`,this._measureElements[3].style.fontWeight=`${i}`,this.clear())}get(t,n,s){let i=0;if(!n&&!s&&t.length===1&&(i=t.charCodeAt(0))<256){if(this._flat[i]!==-9999)return this._flat[i];let u=this._measure(t,0);return u>0&&(this._flat[i]=u),u}let l=t;n&&(l+="B"),s&&(l+="I");let c=this._holey.get(l);if(c===void 0){let u=0;n&&(u|=1),s&&(u|=2),c=this._measure(t,u),c>0&&this._holey.set(l,c)}return c}_measure(t,n){let s=this._measureElements[n];return s.textContent=t.repeat(32),s.offsetWidth/32}},NR=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(t,n,s,i=!1){if(this.selectionStart=n,this.selectionEnd=s,!n||!s||n[0]===s[0]&&n[1]===s[1]){this.clear();return}let l=t.buffers.active.ydisp,c=n[1]-l,u=s[1]-l,h=Math.max(c,0),p=Math.min(u,t.rows-1);if(h>=t.rows||p<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=i,this.viewportStartRow=c,this.viewportEndRow=u,this.viewportCappedStartRow=h,this.viewportCappedEndRow=p,this.startCol=n[0],this.endCol=s[0]}isCellSelected(t,n,s){return this.hasSelection?(s-=t.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?n>=this.startCol&&s>=this.viewportCappedStartRow&&n<this.endCol&&s<=this.viewportCappedEndRow:n<this.startCol&&s>=this.viewportCappedStartRow&&n>=this.endCol&&s<=this.viewportCappedEndRow:s>this.viewportStartRow&&s<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&s===this.viewportStartRow&&n>=this.startCol&&n<this.endCol||this.viewportStartRow<this.viewportEndRow&&s===this.viewportEndRow&&n<this.endCol||this.viewportStartRow<this.viewportEndRow&&s===this.viewportStartRow&&n>=this.startCol):!1}};function jR(){return new NR}var gp="xterm-dom-renderer-owner-",pi="xterm-rows",od="xterm-fg-",Uw="xterm-bg-",Vl="xterm-focus",ad="xterm-selection",LR=1,og=class extends qt{constructor(t,n,s,i,l,c,u,h,p,v,_,g,w,S){super(),this._terminal=t,this._document=n,this._element=s,this._screenElement=i,this._viewportElement=l,this._helperContainer=c,this._linkifier2=u,this._charSizeService=p,this._optionsService=v,this._bufferService=_,this._coreService=g,this._coreBrowserService=w,this._themeService=S,this._terminalClass=LR++,this._rowElements=[],this._selectionRenderModel=jR(),this.onRequestRedraw=this._register(new st).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(pi),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(ad),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=CR(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(N=>this._injectCss(N))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(rg,document),this._element.classList.add(gp+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(N=>this._handleLinkHover(N))),this._register(this._linkifier2.onHideLinkUnderline(N=>this._handleLinkLeave(N))),this._register(yn(()=>{this._element.classList.remove(gp+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new ER(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let t=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*t,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*t),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/t),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/t),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let s of this._rowElements)s.style.width=`${this.dimensions.css.canvas.width}px`,s.style.height=`${this.dimensions.css.cell.height}px`,s.style.lineHeight=`${this.dimensions.css.cell.height}px`,s.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let n=`${this._terminalSelector} .${pi} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=n,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(t){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let n=`${this._terminalSelector} .${pi} { pointer-events: none; color: ${t.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;n+=`${this._terminalSelector} .${pi} .xterm-dim { color: ${gn.multiplyOpacity(t.foreground,.5).css};}`,n+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let s=`blink_underline_${this._terminalClass}`,i=`blink_bar_${this._terminalClass}`,l=`blink_block_${this._terminalClass}`;n+=`@keyframes ${s} { 50% { border-bottom-style: hidden; }}`,n+=`@keyframes ${i} { 50% { box-shadow: none; }}`,n+=`@keyframes ${l} { 0% { background-color: ${t.cursor.css}; color: ${t.cursorAccent.css}; } 50% { background-color: inherit; color: ${t.cursor.css}; }}`,n+=`${this._terminalSelector} .${pi}.${Vl} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${pi}.${Vl} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${pi}.${Vl} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${l} 1s step-end infinite;}${this._terminalSelector} .${pi} .xterm-cursor.xterm-cursor-block { background-color: ${t.cursor.css}; color: ${t.cursorAccent.css};}${this._terminalSelector} .${pi} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${t.cursor.css} !important; color: ${t.cursorAccent.css} !important;}${this._terminalSelector} .${pi} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${t.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${pi} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${t.cursor.css} inset;}${this._terminalSelector} .${pi} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${t.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,n+=`${this._terminalSelector} .${ad} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${ad} div { position: absolute; background-color: ${t.selectionBackgroundOpaque.css};}${this._terminalSelector} .${ad} div { position: absolute; background-color: ${t.selectionInactiveBackgroundOpaque.css};}`;for(let[c,u]of t.ansi.entries())n+=`${this._terminalSelector} .${od}${c} { color: ${u.css}; }${this._terminalSelector} .${od}${c}.xterm-dim { color: ${gn.multiplyOpacity(u,.5).css}; }${this._terminalSelector} .${Uw}${c} { background-color: ${u.css}; }`;n+=`${this._terminalSelector} .${od}257 { color: ${gn.opaque(t.background).css}; }${this._terminalSelector} .${od}257.xterm-dim { color: ${gn.multiplyOpacity(gn.opaque(t.background),.5).css}; }${this._terminalSelector} .${Uw}257 { background-color: ${t.foreground.css}; }`,this._themeStyleElement.textContent=n}_setDefaultSpacing(){let t=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${t}px`,this._rowFactory.defaultSpacing=t}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(t,n){for(let s=this._rowElements.length;s<=n;s++){let i=this._document.createElement("div");this._rowContainer.appendChild(i),this._rowElements.push(i)}for(;this._rowElements.length>n;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(t,n){this._refreshRowElements(t,n),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Vl),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Vl),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(t,n,s){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(t,n,s),this.renderRows(0,this._bufferService.rows-1),!t||!n||(this._selectionRenderModel.update(this._terminal,t,n,s),!this._selectionRenderModel.hasSelection))return;let i=this._selectionRenderModel.viewportStartRow,l=this._selectionRenderModel.viewportEndRow,c=this._selectionRenderModel.viewportCappedStartRow,u=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(s){let p=t[0]>n[0];h.appendChild(this._createSelectionElement(c,p?n[0]:t[0],p?t[0]:n[0],u-c+1))}else{let p=i===c?t[0]:0,v=c===l?n[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,p,v));let _=u-c-1;if(h.appendChild(this._createSelectionElement(c+1,0,this._bufferService.cols,_)),c!==u){let g=l===u?n[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(u,0,g))}}this._selectionContainer.appendChild(h)}_createSelectionElement(t,n,s,i=1){let l=this._document.createElement("div"),c=n*this.dimensions.css.cell.width,u=this.dimensions.css.cell.width*(s-n);return c+u>this.dimensions.css.canvas.width&&(u=this.dimensions.css.canvas.width-c),l.style.height=`${i*this.dimensions.css.cell.height}px`,l.style.top=`${t*this.dimensions.css.cell.height}px`,l.style.left=`${c}px`,l.style.width=`${u}px`,l}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let t of this._rowElements)t.replaceChildren()}renderRows(t,n){let s=this._bufferService.buffer,i=s.ybase+s.y,l=Math.min(s.x,this._bufferService.cols-1),c=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,u=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=t;p<=n;p++){let v=p+s.ydisp,_=this._rowElements[p],g=s.lines.get(v);if(!_||!g)break;_.replaceChildren(...this._rowFactory.createRow(g,v,v===i,u,h,l,c,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${gp}${this._terminalClass}`}_handleLinkHover(t){this._setCellUnderline(t.x1,t.x2,t.y1,t.y2,t.cols,!0)}_handleLinkLeave(t){this._setCellUnderline(t.x1,t.x2,t.y1,t.y2,t.cols,!1)}_setCellUnderline(t,n,s,i,l,c){s<0&&(t=0),i<0&&(n=0);let u=this._bufferService.rows-1;s=Math.max(Math.min(s,u),0),i=Math.max(Math.min(i,u),0),l=Math.min(l,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,v=Math.min(h.x,l-1),_=this._optionsService.rawOptions.cursorBlink,g=this._optionsService.rawOptions.cursorStyle,w=this._optionsService.rawOptions.cursorInactiveStyle;for(let S=s;S<=i;++S){let N=S+h.ydisp,C=this._rowElements[S],j=h.lines.get(N);if(!C||!j)break;C.replaceChildren(...this._rowFactory.createRow(j,N,N===p,g,w,v,_,this.dimensions.css.cell.width,this._widthCache,c?S===s?t:0:-1,c?(S===i?n:l)-1:-1))}}};og=Mn([dt(7,Ev),dt(8,_h),dt(9,Fs),dt(10,zs),dt(11,na),dt(12,Mr),dt(13,ol)],og);var ag=class extends qt{constructor(t,n,s){super(),this._optionsService=s,this.width=0,this.height=0,this._onCharSizeChange=this._register(new st),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new AR(this._optionsService))}catch{this._measureStrategy=this._register(new RR(t,n,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let t=this._measureStrategy.measure();(t.width!==this.width||t.height!==this.height)&&(this.width=t.width,this.height=t.height,this._onCharSizeChange.fire())}};ag=Mn([dt(2,Fs)],ag);var dk=class extends qt{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},RR=class extends dk{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},AR=class extends dk{constructor(t){super(),this._optionsService=t,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let n=this._ctx.measureText("W");if(!("width"in n&&"fontBoundingBoxAscent"in n&&"fontBoundingBoxDescent"in n))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let t=this._ctx.measureText("W");return this._validateAndSet(t.width,t.fontBoundingBoxAscent+t.fontBoundingBoxDescent),this._result}},MR=class extends qt{constructor(t,n,s){super(),this._textarea=t,this._window=n,this.mainDocument=s,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new TR(this._window)),this._onDprChange=this._register(new st),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new st),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(i=>this._screenDprMonitor.setWindow(i))),this._register(ys.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ot(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ot(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(t){this._window!==t&&(this._window=t,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},TR=class extends qt{constructor(t){super(),this._parentWindow=t,this._windowResizeListener=this._register(new Qa),this._onDprChange=this._register(new st),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(yn(()=>this.clearListener()))}setWindow(t){this._parentWindow=t,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ot(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var t;this._outerListener&&((t=this._resolutionMediaMatchList)==null||t.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},IR=class extends qt{constructor(){super(),this.linkProviders=[],this._register(yn(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Iv(e,t,n){let s=n.getBoundingClientRect(),i=e.getComputedStyle(n),l=parseInt(i.getPropertyValue("padding-left")),c=parseInt(i.getPropertyValue("padding-top"));return[t.clientX-s.left-l,t.clientY-s.top-c]}function PR(e,t,n,s,i,l,c,u,h){if(!l)return;let p=Iv(e,t,n);if(p)return p[0]=Math.ceil((p[0]+(h?c/2:0))/c),p[1]=Math.ceil(p[1]/u),p[0]=Math.min(Math.max(p[0],1),s+(h?1:0)),p[1]=Math.min(Math.max(p[1],1),i),p}var lg=class{constructor(t,n){this._renderService=t,this._charSizeService=n}getCoords(t,n,s,i,l){return PR(window,t,n,s,i,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,l)}getMouseReportCoords(t,n){let s=Iv(window,t,n);if(this._charSizeService.hasValidSize)return s[0]=Math.min(Math.max(s[0],0),this._renderService.dimensions.css.canvas.width-1),s[1]=Math.min(Math.max(s[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(s[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(s[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(s[0]),y:Math.floor(s[1])}}};lg=Mn([dt(0,Tr),dt(1,_h)],lg);var DR=class{constructor(t,n){this._renderCallback=t,this._coreBrowserService=n,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(t){return this._refreshCallbacks.push(t),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(t,n,s){this._rowCount=s,t=t!==void 0?t:0,n=n!==void 0?n:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,t):t,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,n):n,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let t=Math.max(this._rowStart,0),n=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(t,n),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let t of this._refreshCallbacks)t(0);this._refreshCallbacks=[]}},hk={};Kj(hk,{getSafariVersion:()=>BR,isChromeOS:()=>gk,isFirefox:()=>fk,isIpad:()=>$R,isIphone:()=>zR,isLegacyEdge:()=>OR,isLinux:()=>Pv,isMac:()=>Ud,isNode:()=>yh,isSafari:()=>pk,isWindows:()=>mk});var yh=typeof process<"u"&&"title"in process,Qc=yh?"node":navigator.userAgent,Zc=yh?"node":navigator.platform,fk=Qc.includes("Firefox"),OR=Qc.includes("Edge"),pk=/^((?!chrome|android).)*safari/i.test(Qc);function BR(){if(!pk)return 0;let e=Qc.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Ud=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Zc),$R=Zc==="iPad",zR=Zc==="iPhone",mk=["Windows","Win16","Win32","WinCE"].includes(Zc),Pv=Zc.indexOf("Linux")>=0,gk=/\bCrOS\b/.test(Qc),vk=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,n=0,s=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=i}this.clear()}},FR=class extends vk{_requestCallback(t){return setTimeout(()=>t(this._createDeadline(16)))}_cancelCallback(t){clearTimeout(t)}_createDeadline(t){let n=performance.now()+t;return{timeRemaining:()=>Math.max(0,n-performance.now())}}},HR=class extends vk{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Wd=!yh&&"requestIdleCallback"in window?HR:FR,UR=class{constructor(){this._queue=new Wd}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},cg=class extends qt{constructor(t,n,s,i,l,c,u,h,p){super(),this._rowCount=t,this._optionsService=s,this._charSizeService=i,this._coreService=l,this._coreBrowserService=h,this._renderer=this._register(new Qa),this._pausedResizeTask=new UR,this._observerDisposable=this._register(new Qa),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new st),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new st),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new st),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new st),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new DR((v,_)=>this._renderRows(v,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new WR(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(yn(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(u.onResize(()=>this._fullRefresh())),this._register(u.buffers.onBufferActivate(()=>{var v;return(v=this._renderer.value)==null?void 0:v.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(c.onDecorationRegistered(()=>this._fullRefresh())),this._register(c.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(u.cols,u.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(u.buffer.y,u.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,n),this._register(this._coreBrowserService.onWindowChange(v=>this._registerIntersectionObserver(v,n)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(t,n){if("IntersectionObserver"in t){let s=new t.IntersectionObserver(i=>this._handleIntersectionChange(i[i.length-1]),{threshold:0});s.observe(n),this._observerDisposable.value=yn(()=>s.disconnect())}}_handleIntersectionChange(t){this._isPaused=t.isIntersecting===void 0?t.intersectionRatio===0:!t.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(t,n,s=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(t,n);return}let i=this._syncOutputHandler.flush();i&&(t=Math.min(t,i.start),n=Math.max(n,i.end)),s||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(t,n,this._rowCount)}_renderRows(t,n){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(t,n);return}t=Math.min(t,this._rowCount-1),n=Math.min(n,this._rowCount-1),this._renderer.value.renderRows(t,n),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:t,end:n}),this._onRender.fire({start:t,end:n}),this._isNextRenderRedrawOnly=!0}}resize(t,n){this._rowCount=n,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(t){this._renderer.value=t,this._renderer.value&&(this._renderer.value.onRequestRedraw(n=>this.refreshRows(n.start,n.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(t){return this._renderDebouncer.addRefreshCallback(t)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var t,n;this._renderer.value&&((n=(t=this._renderer.value).clearTextureAtlas)==null||n.call(t),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(t,n){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var s;return(s=this._renderer.value)==null?void 0:s.handleResize(t,n)}):this._renderer.value.handleResize(t,n),this._fullRefresh())}handleCharSizeChanged(){var t;(t=this._renderer.value)==null||t.handleCharSizeChanged()}handleBlur(){var t;(t=this._renderer.value)==null||t.handleBlur()}handleFocus(){var t;(t=this._renderer.value)==null||t.handleFocus()}handleSelectionChanged(t,n,s){var i;this._selectionState.start=t,this._selectionState.end=n,this._selectionState.columnSelectMode=s,(i=this._renderer.value)==null||i.handleSelectionChanged(t,n,s)}handleCursorMove(){var t;(t=this._renderer.value)==null||t.handleCursorMove()}clear(){var t;(t=this._renderer.value)==null||t.clear()}};cg=Mn([dt(2,Fs),dt(3,_h),dt(4,na),dt(5,Jc),dt(6,zs),dt(7,Mr),dt(8,ol)],cg);var WR=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function qR(e,t,n,s){let i=n.buffer.x,l=n.buffer.y;if(!n.buffer.hasScrollback)return GR(i,l,e,t,n,s)+bh(l,t,n,s)+YR(i,l,e,t,n,s);let c;if(l===t)return c=i>e?"D":"C",Mc(Math.abs(i-e),Ac(c,s));c=l>t?"D":"C";let u=Math.abs(l-t),h=VR(l>t?e:i,n)+(u-1)*n.cols+1+KR(l>t?i:e);return Mc(h,Ac(c,s))}function KR(e,t){return e-1}function VR(e,t){return t.cols-e}function GR(e,t,n,s,i,l){return bh(t,s,i,l).length===0?"":Mc(yk(e,t,e,t-Zo(t,i),!1,i).length,Ac("D",l))}function bh(e,t,n,s){let i=e-Zo(e,n),l=t-Zo(t,n),c=Math.abs(i-l)-XR(e,t,n);return Mc(c,Ac(_k(e,t),s))}function YR(e,t,n,s,i,l){let c;bh(t,s,i,l).length>0?c=s-Zo(s,i):c=t;let u=s,h=JR(e,t,n,s,i,l);return Mc(yk(e,c,n,u,h==="C",i).length,Ac(h,l))}function XR(e,t,n){var c;let s=0,i=e-Zo(e,n),l=t-Zo(t,n);for(let u=0;u<Math.abs(i-l);u++){let h=_k(e,t)==="A"?-1:1;(c=n.buffer.lines.get(i+h*u))!=null&&c.isWrapped&&s++}return s}function Zo(e,t){let n=0,s=t.buffer.lines.get(e),i=s==null?void 0:s.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,s=t.buffer.lines.get(--e),i=s==null?void 0:s.isWrapped;return n}function JR(e,t,n,s,i,l){let c;return bh(n,s,i,l).length>0?c=s-Zo(s,i):c=t,e<n&&c<=s||e>=n&&c<s?"C":"D"}function _k(e,t){return e>t?"A":"B"}function yk(e,t,n,s,i,l){let c=e,u=t,h="";for(;(c!==n||u!==s)&&u>=0&&u<l.buffer.lines.length;)c+=i?1:-1,i&&c>l.cols-1?(h+=l.buffer.translateBufferLineToString(u,!1,e,c),c=0,e=0,u++):!i&&c<0&&(h+=l.buffer.translateBufferLineToString(u,!1,0,e+1),c=l.cols-1,e=c,u--);return h+l.buffer.translateBufferLineToString(u,!1,e,c)}function Ac(e,t){let n=t?"O":"[";return Fe.ESC+n+e}function Mc(e,t){e=Math.floor(e);let n="";for(let s=0;s<e;s++)n+=t;return n}var QR=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Ww(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var vp=50,ZR=15,eA=50,tA=500,nA=" ",sA=new RegExp(nA,"g"),ug=class extends qt{constructor(t,n,s,i,l,c,u,h,p){super(),this._element=t,this._screenElement=n,this._linkifier=s,this._bufferService=i,this._coreService=l,this._mouseService=c,this._optionsService=u,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Si,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new st),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new st),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new st),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new st),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=v=>this._handleMouseMove(v),this._mouseUpListener=v=>this._handleMouseUp(v),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(v=>this._handleTrim(v)),this._register(this._bufferService.buffers.onBufferActivate(v=>this._handleBufferActivate(v))),this.enable(),this._model=new QR(this._bufferService),this._activeSelectionMode=0,this._register(yn(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(v=>{v.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let t=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!t||!n?!1:t[0]!==n[0]||t[1]!==n[1]}get selectionText(){let t=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;if(!t||!n)return"";let s=this._bufferService.buffer,i=[];if(this._activeSelectionMode===3){if(t[0]===n[0])return"";let l=t[0]<n[0]?t[0]:n[0],c=t[0]<n[0]?n[0]:t[0];for(let u=t[1];u<=n[1];u++){let h=s.translateBufferLineToString(u,!0,l,c);i.push(h)}}else{let l=t[1]===n[1]?n[0]:void 0;i.push(s.translateBufferLineToString(t[1],!0,t[0],l));for(let c=t[1]+1;c<=n[1]-1;c++){let u=s.lines.get(c),h=s.translateBufferLineToString(c,!0);u!=null&&u.isWrapped?i[i.length-1]+=h:i.push(h)}if(t[1]!==n[1]){let c=s.lines.get(n[1]),u=s.translateBufferLineToString(n[1],!0,0,n[0]);c&&c.isWrapped?i[i.length-1]+=u:i.push(u)}}return i.map(l=>l.replace(sA," ")).join(mk?`\r
62
+ `:`
63
+ `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(t){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Pv&&t&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(t){let n=this._getMouseBufferCoords(t),s=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;return!s||!i||!n?!1:this._areCoordsInSelection(n,s,i)}isCellInSelection(t,n){let s=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;return!s||!i?!1:this._areCoordsInSelection([t,n],s,i)}_areCoordsInSelection(t,n,s){return t[1]>n[1]&&t[1]<s[1]||n[1]===s[1]&&t[1]===n[1]&&t[0]>=n[0]&&t[0]<s[0]||n[1]<s[1]&&t[1]===s[1]&&t[0]<s[0]||n[1]<s[1]&&t[1]===n[1]&&t[0]>=n[0]}_selectWordAtCursor(t,n){var l,c;let s=(c=(l=this._linkifier.currentLink)==null?void 0:l.link)==null?void 0:c.range;if(s)return this._model.selectionStart=[s.start.x-1,s.start.y-1],this._model.selectionStartLength=Ww(s,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let i=this._getMouseBufferCoords(t);return i?(this._selectWordAt(i,n),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(t,n){this._model.clearSelection(),t=Math.max(t,0),n=Math.min(n,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,t],this._model.selectionEnd=[this._bufferService.cols,n],this.refresh(),this._onSelectionChange.fire()}_handleTrim(t){this._model.handleTrim(t)&&this.refresh()}_getMouseBufferCoords(t){let n=this._mouseService.getCoords(t,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(n)return n[0]--,n[1]--,n[1]+=this._bufferService.buffer.ydisp,n}_getMouseEventScrollAmount(t){let n=Iv(this._coreBrowserService.window,t,this._screenElement)[1],s=this._renderService.dimensions.css.canvas.height;return n>=0&&n<=s?0:(n>s&&(n-=s),n=Math.min(Math.max(n,-vp),vp),n/=vp,n/Math.abs(n)+Math.round(n*(ZR-1)))}shouldForceSelection(t){return Ud?t.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:t.shiftKey}handleMouseDown(t){if(this._mouseDownTimeStamp=t.timeStamp,!(t.button===2&&this.hasSelection)&&t.button===0){if(!this._enabled){if(!this.shouldForceSelection(t))return;t.stopPropagation()}t.preventDefault(),this._dragScrollAmount=0,this._enabled&&t.shiftKey?this._handleIncrementalClick(t):t.detail===1?this._handleSingleClick(t):t.detail===2?this._handleDoubleClick(t):t.detail===3&&this._handleTripleClick(t),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),eA)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(t){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(t))}_handleSingleClick(t){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(t)?3:0,this._model.selectionStart=this._getMouseBufferCoords(t),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let n=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);n&&n.length!==this._model.selectionStart[0]&&n.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(t){this._selectWordAtCursor(t,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(t){let n=this._getMouseBufferCoords(t);n&&(this._activeSelectionMode=2,this._selectLineAt(n[1]))}shouldColumnSelect(t){return t.altKey&&!(Ud&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(t){if(t.stopImmediatePropagation(),!this._model.selectionStart)return;let n=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(t),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(t),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let s=this._bufferService.buffer;if(this._model.selectionEnd[1]<s.lines.length){let i=s.lines.get(this._model.selectionEnd[1]);i&&i.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!n||n[0]!==this._model.selectionEnd[0]||n[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let t=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(t.ydisp+this._bufferService.rows,t.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=t.ydisp),this.refresh()}}_handleMouseUp(t){let n=t.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&n<tA&&t.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let s=this._mouseService.getCoords(t,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(s&&s[0]!==void 0&&s[1]!==void 0){let i=qR(s[0]-1,s[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(i,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let t=this._model.finalSelectionStart,n=this._model.finalSelectionEnd,s=!!t&&!!n&&(t[0]!==n[0]||t[1]!==n[1]);if(!s){this._oldHasSelection&&this._fireOnSelectionChange(t,n,s);return}!t||!n||(!this._oldSelectionStart||!this._oldSelectionEnd||t[0]!==this._oldSelectionStart[0]||t[1]!==this._oldSelectionStart[1]||n[0]!==this._oldSelectionEnd[0]||n[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(t,n,s)}_fireOnSelectionChange(t,n,s){this._oldSelectionStart=t,this._oldSelectionEnd=n,this._oldHasSelection=s,this._onSelectionChange.fire()}_handleBufferActivate(t){this.clearSelection(),this._trimListener.dispose(),this._trimListener=t.activeBuffer.lines.onTrim(n=>this._handleTrim(n))}_convertViewportColToCharacterIndex(t,n){let s=n;for(let i=0;n>=i;i++){let l=t.loadCell(i,this._workCell).getChars().length;this._workCell.getWidth()===0?s--:l>1&&n!==i&&(s+=l-1)}return s}setSelection(t,n,s){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[t,n],this._model.selectionStartLength=s,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(t){this._isClickInSelection(t)||(this._selectWordAtCursor(t,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(t,n,s=!0,i=!0){if(t[0]>=this._bufferService.cols)return;let l=this._bufferService.buffer,c=l.lines.get(t[1]);if(!c)return;let u=l.translateBufferLineToString(t[1],!1),h=this._convertViewportColToCharacterIndex(c,t[0]),p=h,v=t[0]-h,_=0,g=0,w=0,S=0;if(u.charAt(h)===" "){for(;h>0&&u.charAt(h-1)===" ";)h--;for(;p<u.length&&u.charAt(p+1)===" ";)p++}else{let j=t[0],E=t[0];c.getWidth(j)===0&&(_++,j--),c.getWidth(E)===2&&(g++,E++);let R=c.getString(E).length;for(R>1&&(S+=R-1,p+=R-1);j>0&&h>0&&!this._isCharWordSeparator(c.loadCell(j-1,this._workCell));){c.loadCell(j-1,this._workCell);let x=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,j--):x>1&&(w+=x-1,h-=x-1),h--,j--}for(;E<c.length&&p+1<u.length&&!this._isCharWordSeparator(c.loadCell(E+1,this._workCell));){c.loadCell(E+1,this._workCell);let x=this._workCell.getChars().length;this._workCell.getWidth()===2?(g++,E++):x>1&&(S+=x-1,p+=x-1),p++,E++}}p++;let N=h+v-_+w,C=Math.min(this._bufferService.cols,p-h+_+g-w-S);if(!(!n&&u.slice(h,p).trim()==="")){if(s&&N===0&&c.getCodePoint(0)!==32){let j=l.lines.get(t[1]-1);if(j&&c.isWrapped&&j.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,t[1]-1],!1,!0,!1);if(E){let R=this._bufferService.cols-E.start;N-=R,C+=R}}}if(i&&N+C===this._bufferService.cols&&c.getCodePoint(this._bufferService.cols-1)!==32){let j=l.lines.get(t[1]+1);if(j!=null&&j.isWrapped&&j.getCodePoint(0)!==32){let E=this._getWordAt([0,t[1]+1],!1,!1,!0);E&&(C+=E.length)}}return{start:N,length:C}}}_selectWordAt(t,n){let s=this._getWordAt(t,n);if(s){for(;s.start<0;)s.start+=this._bufferService.cols,t[1]--;this._model.selectionStart=[s.start,t[1]],this._model.selectionStartLength=s.length}}_selectToWordAt(t){let n=this._getWordAt(t,!0);if(n){let s=t[1];for(;n.start<0;)n.start+=this._bufferService.cols,s--;if(!this._model.areSelectionValuesReversed())for(;n.start+n.length>this._bufferService.cols;)n.length-=this._bufferService.cols,s++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?n.start:n.start+n.length,s]}}_isCharWordSeparator(t){return t.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(t.getChars())>=0}_selectLineAt(t){let n=this._bufferService.buffer.getWrappedRangeForLine(t),s={start:{x:0,y:n.first},end:{x:this._bufferService.cols-1,y:n.last}};this._model.selectionStart=[0,n.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Ww(s,this._bufferService.cols)}};ug=Mn([dt(3,zs),dt(4,na),dt(5,Nv),dt(6,Fs),dt(7,Tr),dt(8,Mr)],ug);var qw=class{constructor(){this._data={}}set(t,n,s){this._data[t]||(this._data[t]={}),this._data[t][n]=s}get(t,n){return this._data[t]?this._data[t][n]:void 0}clear(){this._data={}}},Kw=class{constructor(){this._color=new qw,this._css=new qw}setCss(t,n,s){this._css.set(t,n,s)}getCss(t,n){return this._css.get(t,n)}setColor(t,n,s){this._color.set(t,n,s)}getColor(t,n){return this._color.get(t,n)}clear(){this._color.clear(),this._css.clear()}},qn=Object.freeze((()=>{let e=[Cn.toColor("#2e3436"),Cn.toColor("#cc0000"),Cn.toColor("#4e9a06"),Cn.toColor("#c4a000"),Cn.toColor("#3465a4"),Cn.toColor("#75507b"),Cn.toColor("#06989a"),Cn.toColor("#d3d7cf"),Cn.toColor("#555753"),Cn.toColor("#ef2929"),Cn.toColor("#8ae234"),Cn.toColor("#fce94f"),Cn.toColor("#729fcf"),Cn.toColor("#ad7fa8"),Cn.toColor("#34e2e2"),Cn.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let s=t[n/36%6|0],i=t[n/6%6|0],l=t[n%6];e.push({css:zn.toCss(s,i,l),rgba:zn.toRgba(s,i,l)})}for(let n=0;n<24;n++){let s=8+n*10;e.push({css:zn.toCss(s,s,s),rgba:zn.toRgba(s,s,s)})}return e})()),Oo=Cn.toColor("#ffffff"),mc=Cn.toColor("#000000"),Vw=Cn.toColor("#ffffff"),Gw=mc,Gl={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},iA=Oo,dg=class extends qt{constructor(t){super(),this._optionsService=t,this._contrastCache=new Kw,this._halfContrastCache=new Kw,this._onChangeColors=this._register(new st),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Oo,background:mc,cursor:Vw,cursorAccent:Gw,selectionForeground:void 0,selectionBackgroundTransparent:Gl,selectionBackgroundOpaque:gn.blend(mc,Gl),selectionInactiveBackgroundTransparent:Gl,selectionInactiveBackgroundOpaque:gn.blend(mc,Gl),scrollbarSliderBackground:gn.opacity(Oo,.2),scrollbarSliderHoverBackground:gn.opacity(Oo,.4),scrollbarSliderActiveBackground:gn.opacity(Oo,.5),overviewRulerBorder:Oo,ansi:qn.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(t={}){let n=this._colors;if(n.foreground=an(t.foreground,Oo),n.background=an(t.background,mc),n.cursor=gn.blend(n.background,an(t.cursor,Vw)),n.cursorAccent=gn.blend(n.background,an(t.cursorAccent,Gw)),n.selectionBackgroundTransparent=an(t.selectionBackground,Gl),n.selectionBackgroundOpaque=gn.blend(n.background,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundTransparent=an(t.selectionInactiveBackground,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundOpaque=gn.blend(n.background,n.selectionInactiveBackgroundTransparent),n.selectionForeground=t.selectionForeground?an(t.selectionForeground,Fw):void 0,n.selectionForeground===Fw&&(n.selectionForeground=void 0),gn.isOpaque(n.selectionBackgroundTransparent)&&(n.selectionBackgroundTransparent=gn.opacity(n.selectionBackgroundTransparent,.3)),gn.isOpaque(n.selectionInactiveBackgroundTransparent)&&(n.selectionInactiveBackgroundTransparent=gn.opacity(n.selectionInactiveBackgroundTransparent,.3)),n.scrollbarSliderBackground=an(t.scrollbarSliderBackground,gn.opacity(n.foreground,.2)),n.scrollbarSliderHoverBackground=an(t.scrollbarSliderHoverBackground,gn.opacity(n.foreground,.4)),n.scrollbarSliderActiveBackground=an(t.scrollbarSliderActiveBackground,gn.opacity(n.foreground,.5)),n.overviewRulerBorder=an(t.overviewRulerBorder,iA),n.ansi=qn.slice(),n.ansi[0]=an(t.black,qn[0]),n.ansi[1]=an(t.red,qn[1]),n.ansi[2]=an(t.green,qn[2]),n.ansi[3]=an(t.yellow,qn[3]),n.ansi[4]=an(t.blue,qn[4]),n.ansi[5]=an(t.magenta,qn[5]),n.ansi[6]=an(t.cyan,qn[6]),n.ansi[7]=an(t.white,qn[7]),n.ansi[8]=an(t.brightBlack,qn[8]),n.ansi[9]=an(t.brightRed,qn[9]),n.ansi[10]=an(t.brightGreen,qn[10]),n.ansi[11]=an(t.brightYellow,qn[11]),n.ansi[12]=an(t.brightBlue,qn[12]),n.ansi[13]=an(t.brightMagenta,qn[13]),n.ansi[14]=an(t.brightCyan,qn[14]),n.ansi[15]=an(t.brightWhite,qn[15]),t.extendedAnsi){let s=Math.min(n.ansi.length-16,t.extendedAnsi.length);for(let i=0;i<s;i++)n.ansi[i+16]=an(t.extendedAnsi[i],qn[i+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(t){this._restoreColor(t),this._onChangeColors.fire(this.colors)}_restoreColor(t){if(t===void 0){for(let n=0;n<this._restoreColors.ansi.length;++n)this._colors.ansi[n]=this._restoreColors.ansi[n];return}switch(t){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[t]=this._restoreColors.ansi[t]}}modifyColors(t){t(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};dg=Mn([dt(0,Fs)],dg);function an(e,t){if(e!==void 0)try{return Cn.toColor(e)}catch{}return t}var rA=class{constructor(...t){this._entries=new Map;for(let[n,s]of t)this.set(n,s)}set(t,n){let s=this._entries.get(t);return this._entries.set(t,n),s}forEach(t){for(let[n,s]of this._entries.entries())t(n,s)}has(t){return this._entries.has(t)}get(t){return this._entries.get(t)}},oA=class{constructor(){this._services=new rA,this._services.set(Ev,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Zj(e).sort((l,c)=>l.index-c.index),s=[];for(let l of n){let c=this._services.get(l.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${l.id._id}.`);s.push(c)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},aA={trace:0,debug:1,info:2,warn:3,error:4,off:5},lA="xterm.js: ",hg=class extends qt{constructor(t){super(),this._optionsService=t,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=aA[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(t){for(let n=0;n<t.length;n++)typeof t[n]=="function"&&(t[n]=t[n]())}_log(t,n,s){this._evalLazyOptionalParams(s),t.call(console,(this._optionsService.options.logger?"":lA)+n,...s)}trace(t,...n){var s;this._logLevel<=0&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.trace.bind(this._optionsService.options.logger))??console.log,t,n)}debug(t,...n){var s;this._logLevel<=1&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.debug.bind(this._optionsService.options.logger))??console.log,t,n)}info(t,...n){var s;this._logLevel<=2&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.info.bind(this._optionsService.options.logger))??console.info,t,n)}warn(t,...n){var s;this._logLevel<=3&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.warn.bind(this._optionsService.options.logger))??console.warn,t,n)}error(t,...n){var s;this._logLevel<=4&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.error.bind(this._optionsService.options.logger))??console.error,t,n)}};hg=Mn([dt(0,Fs)],hg);var Yw=class extends qt{constructor(t){super(),this._maxLength=t,this.onDeleteEmitter=this._register(new st),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new st),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new st),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(t){if(this._maxLength===t)return;let n=new Array(t);for(let s=0;s<Math.min(t,this.length);s++)n[s]=this._array[this._getCyclicIndex(s)];this._array=n,this._maxLength=t,this._startIndex=0}get length(){return this._length}set length(t){if(t>this._length)for(let n=this._length;n<t;n++)this._array[n]=void 0;this._length=t}get(t){return this._array[this._getCyclicIndex(t)]}set(t,n){this._array[this._getCyclicIndex(t)]=n}push(t){this._array[this._getCyclicIndex(this._length)]=t,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(t,n,...s){if(n){for(let i=t;i<this._length-n;i++)this._array[this._getCyclicIndex(i)]=this._array[this._getCyclicIndex(i+n)];this._length-=n,this.onDeleteEmitter.fire({index:t,amount:n})}for(let i=this._length-1;i>=t;i--)this._array[this._getCyclicIndex(i+s.length)]=this._array[this._getCyclicIndex(i)];for(let i=0;i<s.length;i++)this._array[this._getCyclicIndex(t+i)]=s[i];if(s.length&&this.onInsertEmitter.fire({index:t,amount:s.length}),this._length+s.length>this._maxLength){let i=this._length+s.length-this._maxLength;this._startIndex+=i,this._length=this._maxLength,this.onTrimEmitter.fire(i)}else this._length+=s.length}trimStart(t){t>this._length&&(t=this._length),this._startIndex+=t,this._length-=t,this.onTrimEmitter.fire(t)}shiftElements(t,n,s){if(!(n<=0)){if(t<0||t>=this._length)throw new Error("start argument out of range");if(t+s<0)throw new Error("Cannot shift elements in list beyond index 0");if(s>0){for(let l=n-1;l>=0;l--)this.set(t+l+s,this.get(t+l));let i=t+n+s-this._length;if(i>0)for(this._length+=i;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let i=0;i<n;i++)this.set(t+i+s,this.get(t+i))}}_getCyclicIndex(t){return(this._startIndex+t)%this._maxLength}},Ut=3,Bn=Object.freeze(new Xc),ld=0,_p=2,gc=class bk{constructor(t,n,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*Ut);let i=n||Si.fromCharData([0,$1,1,0]);for(let l=0;l<t;++l)this.setCell(l,i);this.length=t}get(t){let n=this._data[t*Ut+0],s=n&2097151;return[this._data[t*Ut+1],n&2097152?this._combined[t]:s?oo(s):"",n>>22,n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,n){this._data[t*Ut+1]=n[0],n[1].length>1?(this._combined[t]=n[1],this._data[t*Ut+0]=t|2097152|n[2]<<22):this._data[t*Ut+0]=n[1].charCodeAt(0)|n[2]<<22}getWidth(t){return this._data[t*Ut+0]>>22}hasWidth(t){return this._data[t*Ut+0]&12582912}getFg(t){return this._data[t*Ut+1]}getBg(t){return this._data[t*Ut+2]}hasContent(t){return this._data[t*Ut+0]&4194303}getCodePoint(t){let n=this._data[t*Ut+0];return n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n&2097151}isCombined(t){return this._data[t*Ut+0]&2097152}getString(t){let n=this._data[t*Ut+0];return n&2097152?this._combined[t]:n&2097151?oo(n&2097151):""}isProtected(t){return this._data[t*Ut+2]&536870912}loadCell(t,n){return ld=t*Ut,n.content=this._data[ld+0],n.fg=this._data[ld+1],n.bg=this._data[ld+2],n.content&2097152&&(n.combinedData=this._combined[t]),n.bg&268435456&&(n.extended=this._extendedAttrs[t]),n}setCell(t,n){n.content&2097152&&(this._combined[t]=n.combinedData),n.bg&268435456&&(this._extendedAttrs[t]=n.extended),this._data[t*Ut+0]=n.content,this._data[t*Ut+1]=n.fg,this._data[t*Ut+2]=n.bg}setCellFromCodepoint(t,n,s,i){i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*Ut+0]=n|s<<22,this._data[t*Ut+1]=i.fg,this._data[t*Ut+2]=i.bg}addCodepointToCell(t,n,s){let i=this._data[t*Ut+0];i&2097152?this._combined[t]+=oo(n):i&2097151?(this._combined[t]=oo(i&2097151)+oo(n),i&=-2097152,i|=2097152):i=n|1<<22,s&&(i&=-12582913,i|=s<<22),this._data[t*Ut+0]=i}insertCells(t,n,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),n<this.length-t){let i=new Si;for(let l=this.length-t-n-1;l>=0;--l)this.setCell(t+n+l,this.loadCell(t+l,i));for(let l=0;l<n;++l)this.setCell(t+l,s)}else for(let i=t;i<this.length;++i)this.setCell(i,s);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(t,n,s){if(t%=this.length,n<this.length-t){let i=new Si;for(let l=0;l<this.length-t-n;++l)this.setCell(t+l,this.loadCell(t+n+l,i));for(let l=this.length-n;l<this.length;++l)this.setCell(l,s)}else for(let i=t;i<this.length;++i)this.setCell(i,s);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,s)}replaceCells(t,n,s,i=!1){if(i){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,s),n<this.length&&this.getWidth(n-1)===2&&!this.isProtected(n)&&this.setCellFromCodepoint(n,0,1,s);t<n&&t<this.length;)this.isProtected(t)||this.setCell(t,s),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),n<this.length&&this.getWidth(n-1)===2&&this.setCellFromCodepoint(n,0,1,s);t<n&&t<this.length;)this.setCell(t++,s)}resize(t,n){if(t===this.length)return this._data.length*4*_p<this._data.buffer.byteLength;let s=t*Ut;if(t>this.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let i=new Uint32Array(s);i.set(this._data),this._data=i}for(let i=this.length;i<t;++i)this.setCell(i,n)}else{this._data=this._data.subarray(0,s);let i=Object.keys(this._combined);for(let c=0;c<i.length;c++){let u=parseInt(i[c],10);u>=t&&delete this._combined[u]}let l=Object.keys(this._extendedAttrs);for(let c=0;c<l.length;c++){let u=parseInt(l[c],10);u>=t&&delete this._extendedAttrs[u]}}return this.length=t,s*4*_p<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*_p<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,n=!1){if(n){for(let s=0;s<this.length;++s)this.isProtected(s)||this.setCell(s,t);return}this._combined={},this._extendedAttrs={};for(let s=0;s<this.length;++s)this.setCell(s,t)}copyFrom(t){this.length!==t.length?this._data=new Uint32Array(t._data):this._data.set(t._data),this.length=t.length,this._combined={};for(let n in t._combined)this._combined[n]=t._combined[n];this._extendedAttrs={};for(let n in t._extendedAttrs)this._extendedAttrs[n]=t._extendedAttrs[n];this.isWrapped=t.isWrapped}clone(){let t=new bk(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let n in this._combined)t._combined[n]=this._combined[n];for(let n in this._extendedAttrs)t._extendedAttrs[n]=this._extendedAttrs[n];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Ut+0]&4194303)return t+(this._data[t*Ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Ut+0]&4194303||this._data[t*Ut+2]&50331648)return t+(this._data[t*Ut+0]>>22);return 0}copyCellsFrom(t,n,s,i,l){let c=t._data;if(l)for(let h=i-1;h>=0;h--){for(let p=0;p<Ut;p++)this._data[(s+h)*Ut+p]=c[(n+h)*Ut+p];c[(n+h)*Ut+2]&268435456&&(this._extendedAttrs[s+h]=t._extendedAttrs[n+h])}else for(let h=0;h<i;h++){for(let p=0;p<Ut;p++)this._data[(s+h)*Ut+p]=c[(n+h)*Ut+p];c[(n+h)*Ut+2]&268435456&&(this._extendedAttrs[s+h]=t._extendedAttrs[n+h])}let u=Object.keys(t._combined);for(let h=0;h<u.length;h++){let p=parseInt(u[h],10);p>=n&&(this._combined[p-n+s]=t._combined[p])}}translateToString(t,n,s,i){n=n??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),i&&(i.length=0);let l="";for(;n<s;){let c=this._data[n*Ut+0],u=c&2097151,h=c&2097152?this._combined[n]:u?oo(u):lo;if(l+=h,i)for(let p=0;p<h.length;++p)i.push(n);n+=c>>22||1}return i&&i.push(n),l}};function cA(e,t,n,s,i,l){let c=[];for(let u=0;u<e.length-1;u++){let h=u,p=e.get(++h);if(!p.isWrapped)continue;let v=[e.get(u)];for(;h<e.length&&p.isWrapped;)v.push(p),p=e.get(++h);if(!l&&s>=u&&s<h){u+=v.length-1;continue}let _=0,g=Tc(v,_,t),w=1,S=0;for(;w<v.length;){let C=Tc(v,w,t),j=C-S,E=n-g,R=Math.min(j,E);v[_].copyCellsFrom(v[w],S,g,R,!1),g+=R,g===n&&(_++,g=0),S+=R,S===C&&(w++,S=0),g===0&&_!==0&&v[_-1].getWidth(n-1)===2&&(v[_].copyCellsFrom(v[_-1],n-1,g++,1,!1),v[_-1].setCell(n-1,i))}v[_].replaceCells(g,n,i);let N=0;for(let C=v.length-1;C>0&&(C>_||v[C].getTrimmedLength()===0);C--)N++;N>0&&(c.push(u+v.length-N),c.push(N)),u+=v.length-1}return c}function uA(e,t){let n=[],s=0,i=t[s],l=0;for(let c=0;c<e.length;c++)if(i===c){let u=t[++s];e.onDeleteEmitter.fire({index:c-l,amount:u}),c+=u-1,l+=u,i=t[++s]}else n.push(c);return{layout:n,countRemoved:l}}function dA(e,t){let n=[];for(let s=0;s<t.length;s++)n.push(e.get(t[s]));for(let s=0;s<n.length;s++)e.set(s,n[s]);e.length=t.length}function hA(e,t,n){let s=[],i=e.map((h,p)=>Tc(e,p,t)).reduce((h,p)=>h+p),l=0,c=0,u=0;for(;u<i;){if(i-u<n){s.push(i-u);break}l+=n;let h=Tc(e,c,t);l>h&&(l-=h,c++);let p=e[c].getWidth(l-1)===2;p&&l--;let v=p?n-1:n;s.push(v),u+=v}return s}function Tc(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return s&&i?n-1:n}var wk=class Sk{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Sk._nextId++,this._onDispose=this.register(new st),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Qo(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};wk._nextId=1;var fA=wk,Gn={},Bo=Gn.B;Gn[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Gn.A={"#":"£"};Gn.B=void 0;Gn[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Gn.C=Gn[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Gn.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Gn.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Gn.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Gn.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Gn.E=Gn[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Gn.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Gn.H=Gn[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Gn["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Xw=4294967295,Jw=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Bn.clone(),this.savedCharset=Bo,this.markers=[],this._nullCell=Si.fromCharData([0,$1,1,0]),this._whitespaceCell=Si.fromCharData([0,lo,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Wd,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Yw(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new zd),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new zd),this._whitespaceCell}getBlankLine(e,t){return new gc(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Xw?Xw:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Bn);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Yw(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(Bn),s=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let c=0;c<this.lines.length;c++)s+=+this.lines.get(c).resize(e,n);let l=0;if(this._rows<t)for(let c=this._rows;c<t;c++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new gc(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+l+1?(this.ybase--,l++,this.ydisp>0&&this.ydisp--):this.lines.push(new gc(e,n)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let c=this.lines.length-i;c>0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),l&&(this.y+=l),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let l=0;l<this.lines.length;l++)s+=+this.lines.get(l).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,s=cA(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Bn),n);if(s.length>0){let i=uA(this.lines,s);dA(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let s=this.getNullCell(Bn),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new gc(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(Bn),i=[],l=0;for(let c=this.lines.length-1;c>=0;c--){let u=this.lines.get(c);if(!u||!u.isWrapped&&u.getTrimmedLength()<=e)continue;let h=[u];for(;u.isWrapped&&c>0;)u=this.lines.get(--c),h.unshift(u);if(!n){let R=this.ybase+this.y;if(R>=c&&R<c+h.length)continue}let p=h[h.length-1].getTrimmedLength(),v=hA(h,this._cols,e),_=v.length-h.length,g;this.ybase===0&&this.y!==this.lines.length-1?g=Math.max(0,this.y-this.lines.maxLength+_):g=Math.max(0,this.lines.length-this.lines.maxLength+_);let w=[];for(let R=0;R<_;R++){let x=this.getBlankLine(Bn,!0);w.push(x)}w.length>0&&(i.push({start:c+h.length+l,newLines:w}),l+=w.length),h.push(...w);let S=v.length-1,N=v[S];N===0&&(S--,N=v[S]);let C=h.length-_-1,j=p;for(;C>=0;){let R=Math.min(j,N);if(h[S]===void 0)break;if(h[S].copyCellsFrom(h[C],j-R,N-R,R,!0),N-=R,N===0&&(S--,N=v[S]),j-=R,j===0){C--;let x=Math.max(C,0);j=Tc(h,x,this._cols)}}for(let R=0;R<h.length;R++)v[R]<e&&h[R].setCell(v[R],s);let E=_-g;for(;E-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+l)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+_,this.ybase+t-1)}if(i.length>0){let c=[],u=[];for(let N=0;N<this.lines.length;N++)u.push(this.lines.get(N));let h=this.lines.length,p=h-1,v=0,_=i[v];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+l);let g=0;for(let N=Math.min(this.lines.maxLength-1,h+l-1);N>=0;N--)if(_&&_.start>p+g){for(let C=_.newLines.length-1;C>=0;C--)this.lines.set(N--,_.newLines[C]);N++,c.push({index:p+1,amount:_.newLines.length}),g+=_.newLines.length,_=i[++v]}else this.lines.set(N,u[p--]);let w=0;for(let N=c.length-1;N>=0;N--)c[N].index+=w,this.lines.onInsertEmitter.fire(c[N]),w+=c[N].amount;let S=Math.max(0,h+l-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}translateBufferLineToString(e,t,n=0,s){let i=this.lines.get(e);return i?i.translateToString(t,n,s):""}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e!=null?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e==null&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new fA(e);return this.markers.push(t),t.register(this.lines.onTrim(n=>{t.line-=n,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(n=>{t.line>=n.index&&(t.line+=n.amount)})),t.register(this.lines.onDelete(n=>{t.line>=n.index&&t.line<n.index+n.amount&&t.dispose(),t.line>n.index&&(t.line-=n.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},pA=class extends qt{constructor(t,n){super(),this._optionsService=t,this._bufferService=n,this._onBufferActivate=this._register(new st),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Jw(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Jw(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(t){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(t),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(t,n){this._normal.resize(t,n),this._alt.resize(t,n),this.setupTabStops(t)}setupTabStops(t){this._normal.setupTabStops(t),this._alt.setupTabStops(t)}},xk=2,kk=1,fg=class extends qt{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new st),this.onResize=this._onResize.event,this._onScroll=this._register(new st),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,xk),this.rows=Math.max(e.rawOptions.rows||0,kk),this.buffers=this._register(new pA(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=n.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let i=n.ybase+n.scrollTop,l=n.ybase+n.scrollBottom;if(n.scrollTop===0){let c=n.lines.isFull;l===n.lines.length-1?c?n.lines.recycle().copyFrom(s):n.lines.push(s.clone()):n.lines.splice(l+1,0,s.clone()),c?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let c=l-i+1;n.lines.shiftElements(i+1,c-1,-1),n.lines.set(l,s.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let s=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),s!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};fg=Mn([dt(0,Fs)],fg);var Ta={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Ud,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},mA=["normal","bold","100","200","300","400","500","600","700","800","900"],gA=class extends qt{constructor(t){super(),this._onOptionChange=this._register(new st),this.onOptionChange=this._onOptionChange.event;let n={...Ta};for(let s in t)if(s in n)try{let i=t[s];n[s]=this._sanitizeAndValidateOption(s,i)}catch(i){console.error(i)}this.rawOptions=n,this.options={...n},this._setupOptions(),this._register(yn(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(t,n){return this.onOptionChange(s=>{s===t&&n(this.rawOptions[t])})}onMultipleOptionChange(t,n){return this.onOptionChange(s=>{t.indexOf(s)!==-1&&n()})}_setupOptions(){let t=s=>{if(!(s in Ta))throw new Error(`No option with key "${s}"`);return this.rawOptions[s]},n=(s,i)=>{if(!(s in Ta))throw new Error(`No option with key "${s}"`);i=this._sanitizeAndValidateOption(s,i),this.rawOptions[s]!==i&&(this.rawOptions[s]=i,this._onOptionChange.fire(s))};for(let s in this.rawOptions){let i={get:t.bind(this,s),set:n.bind(this,s)};Object.defineProperty(this.options,s,i)}}_sanitizeAndValidateOption(t,n){switch(t){case"cursorStyle":if(n||(n=Ta[t]),!vA(n))throw new Error(`"${n}" is not a valid value for ${t}`);break;case"wordSeparator":n||(n=Ta[t]);break;case"fontWeight":case"fontWeightBold":if(typeof n=="number"&&1<=n&&n<=1e3)break;n=mA.includes(n)?n:Ta[t];break;case"cursorWidth":n=Math.floor(n);case"lineHeight":case"tabStopWidth":if(n<1)throw new Error(`${t} cannot be less than 1, value: ${n}`);break;case"minimumContrastRatio":n=Math.max(1,Math.min(21,Math.round(n*10)/10));break;case"scrollback":if(n=Math.min(n,4294967295),n<0)throw new Error(`${t} cannot be less than 0, value: ${n}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(n<=0)throw new Error(`${t} cannot be less than or equal to 0, value: ${n}`);break;case"rows":case"cols":if(!n&&n!==0)throw new Error(`${t} must be numeric, value: ${n}`);break;case"windowsPty":n=n??{};break}return n}};function vA(e){return e==="block"||e==="underline"||e==="bar"}function vc(e,t=5){if(typeof e!="object")return e;let n=Array.isArray(e)?[]:{};for(let s in e)n[s]=t<=1?e[s]:e[s]&&vc(e[s],t-1);return n}var Qw=Object.freeze({insertMode:!1}),Zw=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),pg=class extends qt{constructor(t,n,s){super(),this._bufferService=t,this._logService=n,this._optionsService=s,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new st),this.onData=this._onData.event,this._onUserInput=this._register(new st),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new st),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new st),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=vc(Qw),this.decPrivateModes=vc(Zw)}reset(){this.modes=vc(Qw),this.decPrivateModes=vc(Zw)}triggerDataEvent(t,n=!1){if(this._optionsService.rawOptions.disableStdin)return;let s=this._bufferService.buffer;n&&this._optionsService.rawOptions.scrollOnUserInput&&s.ybase!==s.ydisp&&this._onRequestScrollToBottom.fire(),n&&this._onUserInput.fire(),this._logService.debug(`sending data "${t}"`),this._logService.trace("sending data (codes)",()=>t.split("").map(i=>i.charCodeAt(0))),this._onData.fire(t)}triggerBinaryEvent(t){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${t}"`),this._logService.trace("sending binary (codes)",()=>t.split("").map(n=>n.charCodeAt(0))),this._onBinary.fire(t))}};pg=Mn([dt(0,zs),dt(1,W1),dt(2,Fs)],pg);var e0={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function yp(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var bp=String.fromCharCode,t0={DEFAULT:e=>{let t=[yp(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${bp(t[0])}${bp(t[1])}${bp(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${yp(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${yp(e,!0)};${e.x};${e.y}${t}`}},mg=class extends qt{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new st),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(e0))this.addProtocol(s,e0[s]);for(let s of Object.keys(t0))this.addEncoding(s,t0[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let s=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=s+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};mg=Mn([dt(0,zs),dt(1,na),dt(2,Fs)],mg);var wp=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],_A=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Kn;function yA(e,t){let n=0,s=t.length-1,i;if(e<t[0][0]||e>t[s][1])return!1;for(;s>=n;)if(i=n+s>>1,e>t[i][1])n=i+1;else if(e<t[i][0])s=i-1;else return!0;return!1}var bA=class{constructor(){if(this.version="6",!Kn){Kn=new Uint8Array(65536),Kn.fill(1),Kn[0]=0,Kn.fill(0,1,32),Kn.fill(0,127,160),Kn.fill(2,4352,4448),Kn[9001]=2,Kn[9002]=2,Kn.fill(2,11904,42192),Kn[12351]=1,Kn.fill(2,44032,55204),Kn.fill(2,63744,64256),Kn.fill(2,65040,65050),Kn.fill(2,65072,65136),Kn.fill(2,65280,65377),Kn.fill(2,65504,65511);for(let t=0;t<wp.length;++t)Kn.fill(0,wp[t][0],wp[t][1]+1)}}wcwidth(t){return t<32?0:t<127?1:t<65536?Kn[t]:yA(t,_A)?0:t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}charProperties(t,n){let s=this.wcwidth(t),i=s===0&&n!==0;if(i){let l=Fo.extractWidth(n);l===0?i=!1:l>s&&(s=l)}return Fo.createPropertyValue(0,s,i)}},Fo=class Ld{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new st,this.onChange=this._onChange.event;let t=new bA;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,n,s=!1){return(t&16777215)<<3|(n&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let n=0,s=0,i=t.length;for(let l=0;l<i;++l){let c=t.charCodeAt(l);if(55296<=c&&c<=56319){if(++l>=i)return n+this.wcwidth(c);let p=t.charCodeAt(l);56320<=p&&p<=57343?c=(c-55296)*1024+p-56320+65536:n+=this.wcwidth(p)}let u=this.charProperties(c,s),h=Ld.extractWidth(u);Ld.extractShouldJoin(u)&&(h-=Ld.extractWidth(s)),n+=h,s=u}return n}charProperties(t,n){return this._activeProvider.charProperties(t,n)}},wA=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(t){this.glevel=t,this.charset=this._charsets[t]}setgCharset(t,n){this._charsets[t]=n,this.glevel===t&&(this.charset=n)}};function n0(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Yl=2147483647,SA=256,Ck=class gg{constructor(t=32,n=32){if(this.maxLength=t,this.maxSubParamsLength=n,n>SA)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(n),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new gg;if(!t.length)return n;for(let s=Array.isArray(t[0])?1:0;s<t.length;++s){let i=t[s];if(Array.isArray(i))for(let l=0;l<i.length;++l)n.addSubParam(i[l]);else n.addParam(i)}return n}clone(){let t=new gg(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let t=[];for(let n=0;n<this.length;++n){t.push(this.params[n]);let s=this._subParamsIdx[n]>>8,i=this._subParamsIdx[n]&255;i-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,i))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Yl?Yl:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Yl?Yl:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let n=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-n>0?this._subParams.subarray(n,s):null}getSubParamsAll(){let t={};for(let n=0;n<this.length;++n){let s=this._subParamsIdx[n]>>8,i=this._subParamsIdx[n]&255;i-s>0&&(t[n]=this._subParams.slice(s,i))}return t}addDigit(t){let n;if(this._rejectDigits||!(n=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,i=s[n-1];s[n-1]=~i?Math.min(i*10+t,Yl):t}},Xl=[],xA=class{constructor(){this._state=0,this._active=Xl,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(t,n){this._handlers[t]===void 0&&(this._handlers[t]=[]);let s=this._handlers[t];return s.push(n),{dispose:()=>{let i=s.indexOf(n);i!==-1&&s.splice(i,1)}}}clearHandler(t){this._handlers[t]&&delete this._handlers[t]}setHandlerFallback(t){this._handlerFb=t}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Xl}reset(){if(this._state===2)for(let t=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;t>=0;--t)this._active[t].end(!1);this._stack.paused=!1,this._active=Xl,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Xl,!this._active.length)this._handlerFb(this._id,"START");else for(let t=this._active.length-1;t>=0;t--)this._active[t].start()}_put(t,n,s){if(!this._active.length)this._handlerFb(this._id,"PUT",vh(t,n,s));else for(let i=this._active.length-1;i>=0;i--)this._active[i].put(t,n,s)}start(){this.reset(),this._state=1}put(t,n,s){if(this._state!==3){if(this._state===1)for(;n<s;){let i=t[n++];if(i===59){this._state=2,this._start();break}if(i<48||57<i){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+i-48}this._state===2&&s-n>0&&this._put(t,n,s)}}end(t,n=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",t);else{let s=!1,i=this._active.length-1,l=!1;if(this._stack.paused&&(i=this._stack.loopPosition-1,s=n,l=this._stack.fallThrough,this._stack.paused=!1),!l&&s===!1){for(;i>=0&&(s=this._active[i].end(t),s!==!0);i--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!1,s;i--}for(;i>=0;i--)if(s=this._active[i].end(!1),s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!0,s}this._active=Xl,this._id=-1,this._state=0}}},ii=class{constructor(t){this._handler=t,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(t,n,s){this._hitLimit||(this._data+=vh(t,n,s),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(t){let n=!1;if(this._hitLimit)n=!1;else if(t&&(n=this._handler(this._data),n instanceof Promise))return n.then(s=>(this._data="",this._hitLimit=!1,s));return this._data="",this._hitLimit=!1,n}},Jl=[],kA=class{constructor(){this._handlers=Object.create(null),this._active=Jl,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Jl}registerHandler(t,n){this._handlers[t]===void 0&&(this._handlers[t]=[]);let s=this._handlers[t];return s.push(n),{dispose:()=>{let i=s.indexOf(n);i!==-1&&s.splice(i,1)}}}clearHandler(t){this._handlers[t]&&delete this._handlers[t]}setHandlerFallback(t){this._handlerFb=t}reset(){if(this._active.length)for(let t=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;t>=0;--t)this._active[t].unhook(!1);this._stack.paused=!1,this._active=Jl,this._ident=0}hook(t,n){if(this.reset(),this._ident=t,this._active=this._handlers[t]||Jl,!this._active.length)this._handlerFb(this._ident,"HOOK",n);else for(let s=this._active.length-1;s>=0;s--)this._active[s].hook(n)}put(t,n,s){if(!this._active.length)this._handlerFb(this._ident,"PUT",vh(t,n,s));else for(let i=this._active.length-1;i>=0;i--)this._active[i].put(t,n,s)}unhook(t,n=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",t);else{let s=!1,i=this._active.length-1,l=!1;if(this._stack.paused&&(i=this._stack.loopPosition-1,s=n,l=this._stack.fallThrough,this._stack.paused=!1),!l&&s===!1){for(;i>=0&&(s=this._active[i].unhook(t),s!==!0);i--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!1,s;i--}for(;i>=0;i--)if(s=this._active[i].unhook(!1),s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!0,s}this._active=Jl,this._ident=0}},_c=new Ck;_c.addParam(0);var s0=class{constructor(e){this._handler=e,this._data="",this._params=_c,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():_c,this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=vh(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(n=>(this._params=_c,this._data="",this._hitLimit=!1,n));return this._params=_c,this._data="",this._hitLimit=!1,t}},CA=class{constructor(t){this.table=new Uint8Array(t)}setDefault(t,n){this.table.fill(t<<4|n)}add(t,n,s,i){this.table[n<<8|t]=s<<4|i}addMany(t,n,s,i){for(let l=0;l<t.length;l++)this.table[n<<8|t[l]]=s<<4|i}},_i=160,EA=(function(){let e=new CA(4095),t=Array.apply(null,Array(256)).map((u,h)=>h),n=(u,h)=>t.slice(u,h),s=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let l=n(0,14),c;e.setDefault(1,0),e.addMany(s,0,2,0);for(c in l)e.addMany([24,26,153,154],c,3,0),e.addMany(n(128,144),c,3,0),e.addMany(n(144,152),c,3,0),e.add(156,c,0,0),e.add(27,c,11,1),e.add(157,c,4,8),e.addMany([152,158,159],c,0,7),e.add(155,c,11,3),e.add(144,c,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(_i,0,2,0),e.add(_i,8,5,8),e.add(_i,6,0,6),e.add(_i,11,0,11),e.add(_i,13,13,13),e})(),NA=class extends qt{constructor(t=EA){super(),this._transitions=t,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Ck,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(n,s,i)=>{},this._executeHandlerFb=n=>{},this._csiHandlerFb=(n,s)=>{},this._escHandlerFb=n=>{},this._errorHandlerFb=n=>n,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(yn(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new xA),this._dcsParser=this._register(new kA),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(t,n=[64,126]){let s=0;if(t.prefix){if(t.prefix.length>1)throw new Error("only one byte as prefix supported");if(s=t.prefix.charCodeAt(0),s&&60>s||s>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(t.intermediates){if(t.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let l=0;l<t.intermediates.length;++l){let c=t.intermediates.charCodeAt(l);if(32>c||c>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");s<<=8,s|=c}}if(t.final.length!==1)throw new Error("final must be a single byte");let i=t.final.charCodeAt(0);if(n[0]>i||i>n[1])throw new Error(`final must be in range ${n[0]} .. ${n[1]}`);return s<<=8,s|=i,s}identToString(t){let n=[];for(;t;)n.push(String.fromCharCode(t&255)),t>>=8;return n.reverse().join("")}setPrintHandler(t){this._printHandler=t}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(t,n){let s=this._identifier(t,[48,126]);this._escHandlers[s]===void 0&&(this._escHandlers[s]=[]);let i=this._escHandlers[s];return i.push(n),{dispose:()=>{let l=i.indexOf(n);l!==-1&&i.splice(l,1)}}}clearEscHandler(t){this._escHandlers[this._identifier(t,[48,126])]&&delete this._escHandlers[this._identifier(t,[48,126])]}setEscHandlerFallback(t){this._escHandlerFb=t}setExecuteHandler(t,n){this._executeHandlers[t.charCodeAt(0)]=n}clearExecuteHandler(t){this._executeHandlers[t.charCodeAt(0)]&&delete this._executeHandlers[t.charCodeAt(0)]}setExecuteHandlerFallback(t){this._executeHandlerFb=t}registerCsiHandler(t,n){let s=this._identifier(t);this._csiHandlers[s]===void 0&&(this._csiHandlers[s]=[]);let i=this._csiHandlers[s];return i.push(n),{dispose:()=>{let l=i.indexOf(n);l!==-1&&i.splice(l,1)}}}clearCsiHandler(t){this._csiHandlers[this._identifier(t)]&&delete this._csiHandlers[this._identifier(t)]}setCsiHandlerFallback(t){this._csiHandlerFb=t}registerDcsHandler(t,n){return this._dcsParser.registerHandler(this._identifier(t),n)}clearDcsHandler(t){this._dcsParser.clearHandler(this._identifier(t))}setDcsHandlerFallback(t){this._dcsParser.setHandlerFallback(t)}registerOscHandler(t,n){return this._oscParser.registerHandler(t,n)}clearOscHandler(t){this._oscParser.clearHandler(t)}setOscHandlerFallback(t){this._oscParser.setHandlerFallback(t)}setErrorHandler(t){this._errorHandler=t}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(t,n,s,i,l){this._parseStack.state=t,this._parseStack.handlers=n,this._parseStack.handlerPos=s,this._parseStack.transition=i,this._parseStack.chunkPos=l}parse(t,n,s){let i=0,l=0,c=0,u;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,c=this._parseStack.chunkPos+1;else{if(s===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(s===!1&&p>-1){for(;p>=0&&(u=h[p](this._params),u!==!0);p--)if(u instanceof Promise)return this._parseStack.handlerPos=p,u}this._parseStack.handlers=[];break;case 4:if(s===!1&&p>-1){for(;p>=0&&(u=h[p](),u!==!0);p--)if(u instanceof Promise)return this._parseStack.handlerPos=p,u}this._parseStack.handlers=[];break;case 6:if(i=t[this._parseStack.chunkPos],u=this._dcsParser.unhook(i!==24&&i!==26,s),u)return u;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(i=t[this._parseStack.chunkPos],u=this._oscParser.end(i!==24&&i!==26,s),u)return u;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,c=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=c;h<n;++h){switch(i=t[h],l=this._transitions.table[this.currentState<<8|(i<160?i:_i)],l>>4){case 2:for(let w=h+1;;++w){if(w>=n||(i=t[w])<32||i>126&&i<_i){this._printHandler(t,h,w),h=w-1;break}if(++w>=n||(i=t[w])<32||i>126&&i<_i){this._printHandler(t,h,w),h=w-1;break}if(++w>=n||(i=t[w])<32||i>126&&i<_i){this._printHandler(t,h,w),h=w-1;break}if(++w>=n||(i=t[w])<32||i>126&&i<_i){this._printHandler(t,h,w),h=w-1;break}}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:h,code:i,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let p=this._csiHandlers[this._collect<<8|i],v=p?p.length-1:-1;for(;v>=0&&(u=p[v](this._params),u!==!0);v--)if(u instanceof Promise)return this._preserveStack(3,p,v,l,h),u;v<0&&this._csiHandlerFb(this._collect<<8|i,this._params),this.precedingJoinState=0;break;case 8:do switch(i){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(i-48)}while(++h<n&&(i=t[h])>47&&i<60);h--;break;case 9:this._collect<<=8,this._collect|=i;break;case 10:let _=this._escHandlers[this._collect<<8|i],g=_?_.length-1:-1;for(;g>=0&&(u=_[g](),u!==!0);g--)if(u instanceof Promise)return this._preserveStack(4,_,g,l,h),u;g<0&&this._escHandlerFb(this._collect<<8|i),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|i,this._params);break;case 13:for(let w=h+1;;++w)if(w>=n||(i=t[w])===24||i===26||i===27||i>127&&i<_i){this._dcsParser.put(t,h,w),h=w-1;break}break;case 14:if(u=this._dcsParser.unhook(i!==24&&i!==26),u)return this._preserveStack(6,[],0,l,h),u;i===27&&(l|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let w=h+1;;w++)if(w>=n||(i=t[w])<32||i>127&&i<_i){this._oscParser.put(t,h,w),h=w-1;break}break;case 6:if(u=this._oscParser.end(i!==24&&i!==26),u)return this._preserveStack(5,[],0,l,h),u;i===27&&(l|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=l&15}}},jA=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,LA=/^[\da-f]+$/;function i0(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let n=jA.exec(t);if(n){let s=n[1]?15:n[4]?255:n[7]?4095:65535;return[Math.round(parseInt(n[1]||n[4]||n[7]||n[10],16)/s*255),Math.round(parseInt(n[2]||n[5]||n[8]||n[11],16)/s*255),Math.round(parseInt(n[3]||n[6]||n[9]||n[12],16)/s*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),LA.exec(t)&&[3,6,9,12].includes(t.length))){let n=t.length/3,s=[0,0,0];for(let i=0;i<3;++i){let l=parseInt(t.slice(n*i,n*i+n),16);s[i]=n===1?l<<4:n===2?l:n===3?l>>4:l>>8}return s}}function Sp(e,t){let n=e.toString(16),s=n.length<2?"0"+n:n;switch(t){case 4:return n[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function RA(e,t=16){let[n,s,i]=e;return`rgb:${Sp(n,t)}/${Sp(s,t)}/${Sp(i,t)}`}var AA={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Qr=131072,r0=10;function o0(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var a0=5e3,l0=0,MA=class extends qt{constructor(e,t,n,s,i,l,c,u,h=new NA){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=s,this._optionsService=i,this._oscLinkService=l,this._coreMouseService=c,this._unicodeService=u,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Jj,this._utf8Decoder=new Qj,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Bn.clone(),this._eraseAttrDataInternal=Bn.clone(),this._onRequestBell=this._register(new st),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new st),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new st),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new st),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new st),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new st),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new st),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new st),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new st),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new st),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new st),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new st),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new st),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new vg(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(p=>this._activeBuffer=p.activeBuffer)),this._parser.setCsiHandlerFallback((p,v)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(p),params:v.toArray()})}),this._parser.setEscHandlerFallback(p=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(p)})}),this._parser.setExecuteHandlerFallback(p=>{this._logService.debug("Unknown EXECUTE code: ",{code:p})}),this._parser.setOscHandlerFallback((p,v,_)=>{this._logService.debug("Unknown OSC code: ",{identifier:p,action:v,data:_})}),this._parser.setDcsHandlerFallback((p,v,_)=>{v==="HOOK"&&(_=_.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(p),action:v,payload:_})}),this._parser.setPrintHandler((p,v,_)=>this.print(p,v,_)),this._parser.registerCsiHandler({final:"@"},p=>this.insertChars(p)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},p=>this.scrollLeft(p)),this._parser.registerCsiHandler({final:"A"},p=>this.cursorUp(p)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},p=>this.scrollRight(p)),this._parser.registerCsiHandler({final:"B"},p=>this.cursorDown(p)),this._parser.registerCsiHandler({final:"C"},p=>this.cursorForward(p)),this._parser.registerCsiHandler({final:"D"},p=>this.cursorBackward(p)),this._parser.registerCsiHandler({final:"E"},p=>this.cursorNextLine(p)),this._parser.registerCsiHandler({final:"F"},p=>this.cursorPrecedingLine(p)),this._parser.registerCsiHandler({final:"G"},p=>this.cursorCharAbsolute(p)),this._parser.registerCsiHandler({final:"H"},p=>this.cursorPosition(p)),this._parser.registerCsiHandler({final:"I"},p=>this.cursorForwardTab(p)),this._parser.registerCsiHandler({final:"J"},p=>this.eraseInDisplay(p,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},p=>this.eraseInDisplay(p,!0)),this._parser.registerCsiHandler({final:"K"},p=>this.eraseInLine(p,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},p=>this.eraseInLine(p,!0)),this._parser.registerCsiHandler({final:"L"},p=>this.insertLines(p)),this._parser.registerCsiHandler({final:"M"},p=>this.deleteLines(p)),this._parser.registerCsiHandler({final:"P"},p=>this.deleteChars(p)),this._parser.registerCsiHandler({final:"S"},p=>this.scrollUp(p)),this._parser.registerCsiHandler({final:"T"},p=>this.scrollDown(p)),this._parser.registerCsiHandler({final:"X"},p=>this.eraseChars(p)),this._parser.registerCsiHandler({final:"Z"},p=>this.cursorBackwardTab(p)),this._parser.registerCsiHandler({final:"`"},p=>this.charPosAbsolute(p)),this._parser.registerCsiHandler({final:"a"},p=>this.hPositionRelative(p)),this._parser.registerCsiHandler({final:"b"},p=>this.repeatPrecedingCharacter(p)),this._parser.registerCsiHandler({final:"c"},p=>this.sendDeviceAttributesPrimary(p)),this._parser.registerCsiHandler({prefix:">",final:"c"},p=>this.sendDeviceAttributesSecondary(p)),this._parser.registerCsiHandler({final:"d"},p=>this.linePosAbsolute(p)),this._parser.registerCsiHandler({final:"e"},p=>this.vPositionRelative(p)),this._parser.registerCsiHandler({final:"f"},p=>this.hVPosition(p)),this._parser.registerCsiHandler({final:"g"},p=>this.tabClear(p)),this._parser.registerCsiHandler({final:"h"},p=>this.setMode(p)),this._parser.registerCsiHandler({prefix:"?",final:"h"},p=>this.setModePrivate(p)),this._parser.registerCsiHandler({final:"l"},p=>this.resetMode(p)),this._parser.registerCsiHandler({prefix:"?",final:"l"},p=>this.resetModePrivate(p)),this._parser.registerCsiHandler({final:"m"},p=>this.charAttributes(p)),this._parser.registerCsiHandler({final:"n"},p=>this.deviceStatus(p)),this._parser.registerCsiHandler({prefix:"?",final:"n"},p=>this.deviceStatusPrivate(p)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},p=>this.softReset(p)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},p=>this.setCursorStyle(p)),this._parser.registerCsiHandler({final:"r"},p=>this.setScrollRegion(p)),this._parser.registerCsiHandler({final:"s"},p=>this.saveCursor(p)),this._parser.registerCsiHandler({final:"t"},p=>this.windowOptions(p)),this._parser.registerCsiHandler({final:"u"},p=>this.restoreCursor(p)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},p=>this.insertColumns(p)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},p=>this.deleteColumns(p)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},p=>this.selectProtected(p)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},p=>this.requestMode(p,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},p=>this.requestMode(p,!1)),this._parser.setExecuteHandler(Fe.BEL,()=>this.bell()),this._parser.setExecuteHandler(Fe.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(Fe.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(Fe.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(Fe.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(Fe.BS,()=>this.backspace()),this._parser.setExecuteHandler(Fe.HT,()=>this.tab()),this._parser.setExecuteHandler(Fe.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(Fe.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Nd.IND,()=>this.index()),this._parser.setExecuteHandler(Nd.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Nd.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new ii(p=>(this.setTitle(p),this.setIconName(p),!0))),this._parser.registerOscHandler(1,new ii(p=>this.setIconName(p))),this._parser.registerOscHandler(2,new ii(p=>this.setTitle(p))),this._parser.registerOscHandler(4,new ii(p=>this.setOrReportIndexedColor(p))),this._parser.registerOscHandler(8,new ii(p=>this.setHyperlink(p))),this._parser.registerOscHandler(10,new ii(p=>this.setOrReportFgColor(p))),this._parser.registerOscHandler(11,new ii(p=>this.setOrReportBgColor(p))),this._parser.registerOscHandler(12,new ii(p=>this.setOrReportCursorColor(p))),this._parser.registerOscHandler(104,new ii(p=>this.restoreIndexedColor(p))),this._parser.registerOscHandler(110,new ii(p=>this.restoreFgColor(p))),this._parser.registerOscHandler(111,new ii(p=>this.restoreBgColor(p))),this._parser.registerOscHandler(112,new ii(p=>this.restoreCursorColor(p))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let p in Gn)this._parser.registerEscHandler({intermediates:"(",final:p},()=>this.selectCharset("("+p)),this._parser.registerEscHandler({intermediates:")",final:p},()=>this.selectCharset(")"+p)),this._parser.registerEscHandler({intermediates:"*",final:p},()=>this.selectCharset("*"+p)),this._parser.registerEscHandler({intermediates:"+",final:p},()=>this.selectCharset("+"+p)),this._parser.registerEscHandler({intermediates:"-",final:p},()=>this.selectCharset("-"+p)),this._parser.registerEscHandler({intermediates:".",final:p},()=>this.selectCharset("."+p)),this._parser.registerEscHandler({intermediates:"/",final:p},()=>this.selectCharset("/"+p));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(p=>(this._logService.error("Parsing error: ",p),p)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new s0((p,v)=>this.requestStatusString(p,v)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,n)=>setTimeout(()=>n("#SLOW_TIMEOUT"),a0))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${a0} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,s=this._activeBuffer.x,i=this._activeBuffer.y,l=0,c=this._parseStack.paused;if(c){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;s=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Qr&&(l=this._parseStack.position+Qr)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,p=>String.fromCharCode(p)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(p=>p.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Qr&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Qr))),c||this._dirtyRowTracker.clearRange(),e.length>Qr)for(let p=l;p<e.length;p+=Qr){let v=p+Qr<e.length?p+Qr:e.length,_=typeof e=="string"?this._stringDecoder.decode(e.substring(p,v),this._parseBuffer):this._utf8Decoder.decode(e.subarray(p,v),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,_))return this._preserveStack(s,i,_,p),this._logSlowResolvingAsync(n),n}else if(!c){let p=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,p))return this._preserveStack(s,i,p,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==s||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let u=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),h=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);h<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(h,this._bufferService.rows-1),end:Math.min(u,this._bufferService.rows-1)})}print(e,t,n){let s,i,l=this._charsetService.charset,c=this._optionsService.rawOptions.screenReaderMode,u=this._bufferService.cols,h=this._coreService.decPrivateModes.wraparound,p=this._coreService.modes.insertMode,v=this._curAttrData,_=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&_.getWidth(this._activeBuffer.x-1)===2&&_.setCellFromCodepoint(this._activeBuffer.x-1,0,1,v);let g=this._parser.precedingJoinState;for(let w=t;w<n;++w){if(s=e[w],s<127&&l){let j=l[String.fromCharCode(s)];j&&(s=j.charCodeAt(0))}let S=this._unicodeService.charProperties(s,g);i=Fo.extractWidth(S);let N=Fo.extractShouldJoin(S),C=N?Fo.extractWidth(g):0;if(g=S,c&&this._onA11yChar.fire(oo(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-C>u){if(h){let j=_,E=this._activeBuffer.x-C;for(this._activeBuffer.x=C,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),_=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),C>0&&_ instanceof gc&&_.copyCellsFrom(j,E,0,C,!1);E<u;)j.setCellFromCodepoint(E++,0,1,v)}else if(this._activeBuffer.x=u-1,i===2)continue}if(N&&this._activeBuffer.x){let j=_.getWidth(this._activeBuffer.x-1)?1:2;_.addCodepointToCell(this._activeBuffer.x-j,s,i);for(let E=i-C;--E>=0;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,v);continue}if(p&&(_.insertCells(this._activeBuffer.x,i-C,this._activeBuffer.getNullCell(v)),_.getWidth(u-1)===2&&_.setCellFromCodepoint(u-1,0,1,v)),_.setCellFromCodepoint(this._activeBuffer.x++,s,i,v),i>0)for(;--i;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,v)}this._parser.precedingJoinState=g,this._activeBuffer.x<u&&n-t>0&&_.getWidth(this._activeBuffer.x)===0&&!_.hasContent(this._activeBuffer.x)&&_.setCellFromCodepoint(this._activeBuffer.x,0,1,v),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,n=>o0(n.params[0],this._optionsService.rawOptions.windowOptions)?t(n):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new s0(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new ii(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,s=!1,i=!1){let l=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);l.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),s&&(l.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n))!=null&&s.getTrimmedLength()););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let i=this._activeBuffer.lines.length-this._bufferService.rows;i>0&&(this._activeBuffer.lines.trimStart(i),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-i,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-i,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(Bn));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,s=Fo.extractWidth(t),i=this._activeBuffer.x-s,l=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),c=new Uint32Array(l.length*n),u=0;for(let p=0;p<l.length;){let v=l.codePointAt(p)||0;c[u++]=v,p+=v>65535?2:1}let h=u;for(let p=1;p<n;++p)c.copyWithin(h,0,u),h+=u;return this.print(c,0,h),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(Fe.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(Fe.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(Fe.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(Fe.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(Fe.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Bo),this._charsetService.setgCharset(1,Bo),this._charsetService.setgCharset(2,Bo),this._charsetService.setgCharset(3,Bo);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){(N=>(N[N.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",N[N.SET=1]="SET",N[N.RESET=2]="RESET",N[N.PERMANENTLY_SET=3]="PERMANENTLY_SET",N[N.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(n={}));let s=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:l}=this._coreMouseService,c=this._coreService,{buffers:u,cols:h}=this._bufferService,{active:p,alt:v}=u,_=this._optionsService.rawOptions,g=(N,C)=>(c.triggerDataEvent(`${Fe.ESC}[${t?"":"?"}${N};${C}$y`),!0),w=N=>N?1:2,S=e.params[0];return t?S===2?g(S,4):S===4?g(S,w(c.modes.insertMode)):S===12?g(S,3):S===20?g(S,w(_.convertEol)):g(S,0):S===1?g(S,w(s.applicationCursorKeys)):S===3?g(S,_.windowOptions.setWinLines?h===80?2:h===132?1:0:0):S===6?g(S,w(s.origin)):S===7?g(S,w(s.wraparound)):S===8?g(S,3):S===9?g(S,w(i==="X10")):S===12?g(S,w(_.cursorBlink)):S===25?g(S,w(!c.isCursorHidden)):S===45?g(S,w(s.reverseWraparound)):S===66?g(S,w(s.applicationKeypad)):S===67?g(S,4):S===1e3?g(S,w(i==="VT200")):S===1002?g(S,w(i==="DRAG")):S===1003?g(S,w(i==="ANY")):S===1004?g(S,w(s.sendFocus)):S===1005?g(S,4):S===1006?g(S,w(l==="SGR")):S===1015?g(S,4):S===1016?g(S,w(l==="SGR_PIXELS")):S===1048?g(S,1):S===47||S===1047||S===1049?g(S,w(p===v)):S===2004?g(S,w(s.bracketedPasteMode)):S===2026?g(S,w(s.synchronizedOutput)):g(S,0)}_updateAttrColor(e,t,n,s,i){return t===2?(e|=50331648,e&=-16777216,e|=Xc.fromColorRGB([n,s,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let s=[0,0,-1,0,0,0],i=0,l=0;do{if(s[l+i]=e.params[t+l],e.hasSubParams(t+l)){let c=e.getSubParams(t+l),u=0;do s[1]===5&&(i=1),s[l+u+1+i]=c[u];while(++u<c.length&&u+l+1+i<s.length);break}if(s[1]===5&&l+i>=2||s[1]===2&&l+i>=5)break;s[1]&&(i=1)}while(++l+t<e.length&&l+i<s.length);for(let c=2;c<s.length;++c)s[c]===-1&&(s[c]=0);switch(s[0]){case 38:n.fg=this._updateAttrColor(n.fg,s[1],s[3],s[4],s[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,s[1],s[3],s[4],s[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,s[1],s[3],s[4],s[5])}return l}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Bn.fg,e.bg=Bn.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,s=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(s.fg&=-50331904,s.fg|=16777216|n-30):n>=40&&n<=47?(s.bg&=-50331904,s.bg|=16777216|n-40):n>=90&&n<=97?(s.fg&=-50331904,s.fg|=16777216|n-90|8):n>=100&&n<=107?(s.bg&=-50331904,s.bg|=16777216|n-100|8):n===0?this._processSGR0(s):n===1?s.fg|=134217728:n===3?s.bg|=67108864:n===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,s)):n===5?s.fg|=536870912:n===7?s.fg|=67108864:n===8?s.fg|=1073741824:n===9?s.fg|=2147483648:n===2?s.bg|=134217728:n===21?this._processUnderline(2,s):n===22?(s.fg&=-134217729,s.bg&=-134217729):n===23?s.bg&=-67108865:n===24?(s.fg&=-268435457,this._processUnderline(0,s)):n===25?s.fg&=-536870913:n===27?s.fg&=-67108865:n===28?s.fg&=-1073741825:n===29?s.fg&=2147483647:n===39?(s.fg&=-67108864,s.fg|=Bn.fg&16777215):n===49?(s.bg&=-67108864,s.bg|=Bn.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,s):n===53?s.bg|=1073741824:n===55?s.bg&=-1073741825:n===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):n===100?(s.fg&=-67108864,s.fg|=Bn.fg&16777215,s.bg&=-67108864,s.bg|=Bn.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${Fe.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Fe.ESC}[${t};${n}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Fe.ESC}[?${t};${n}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Bn.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let n=t%2===1;this._coreService.decPrivateModes.cursorBlink=n}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!o0(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${Fe.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>r0&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>r0&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(";");for(;n.length>1;){let s=n.shift(),i=n.shift();if(/^\d+$/.exec(s)){let l=parseInt(s);if(c0(l))if(i==="?")t.push({type:0,index:l});else{let c=i0(i);c&&t.push({type:1,index:l,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let n=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(n,s):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(":"),s,i=n.findIndex(l=>l.startsWith("id="));return i!==-1&&(s=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(";");for(let s=0;s<n.length&&!(t>=this._specialColors.length);++s,++t)if(n[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let i=i0(n[s]);i&&this._onColor.fire([{type:1,index:this._specialColors[t],color:i}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(";");for(let s=0;s<n.length;++s)if(/^\d+$/.exec(n[s])){let i=parseInt(n[s]);c0(i)&&t.push({type:2,index:i})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Bo),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(AA[e[0]],Gn[e[1]]||Bo),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Bn.clone(),this._eraseAttrDataInternal=Bn.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Si;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(n);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=c=>(this._coreService.triggerDataEvent(`${Fe.ESC}${c}${Fe.ESC}\\`),!0),s=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-(i.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},vg=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(l0=e,e=t,t=l0),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vg=Mn([dt(0,zs)],vg);function c0(e){return 0<=e&&e<256}var TA=5e7,u0=12,IA=50,PA=class extends qt{constructor(t){super(),this._action=t,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new st),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(t,n){if(n!==void 0&&this._syncCalls>n){this._syncCalls=0;return}if(this._pendingData+=t.length,this._writeBuffer.push(t),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let s;for(;s=this._writeBuffer.shift();){this._action(s);let i=this._callbacks.shift();i&&i()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(t,n){if(this._pendingData>TA)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=t.length,this._writeBuffer.push(t),this._callbacks.push(n),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=t.length,this._writeBuffer.push(t),this._callbacks.push(n)}_innerWrite(t=0,n=!0){let s=t||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let i=this._writeBuffer[this._bufferOffset],l=this._action(i,n);if(l){let u=h=>performance.now()-s>=u0?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(s,h);l.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(u);return}let c=this._callbacks[this._bufferOffset];if(c&&c(),this._bufferOffset++,this._pendingData-=i.length,performance.now()-s>=u0)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>IA&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},_g=class{constructor(t){this._bufferService=t,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(t){let n=this._bufferService.buffer;if(t.id===void 0){let h=n.addMarker(n.ybase+n.y),p={data:t,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let s=t,i=this._getEntryIdKey(s),l=this._entriesWithId.get(i);if(l)return this.addLineToLink(l.id,n.ybase+n.y),l.id;let c=n.addMarker(n.ybase+n.y),u={id:this._nextId++,key:this._getEntryIdKey(s),data:s,lines:[c]};return c.onDispose(()=>this._removeMarkerFromLink(u,c)),this._entriesWithId.set(u.key,u),this._dataByLinkId.set(u.id,u),u.id}addLineToLink(t,n){let s=this._dataByLinkId.get(t);if(s&&s.lines.every(i=>i.line!==n)){let i=this._bufferService.buffer.addMarker(n);s.lines.push(i),i.onDispose(()=>this._removeMarkerFromLink(s,i))}}getLinkData(t){var n;return(n=this._dataByLinkId.get(t))==null?void 0:n.data}_getEntryIdKey(t){return`${t.id};;${t.uri}`}_removeMarkerFromLink(t,n){let s=t.lines.indexOf(n);s!==-1&&(t.lines.splice(s,1),t.lines.length===0&&(t.data.id!==void 0&&this._entriesWithId.delete(t.key),this._dataByLinkId.delete(t.id)))}};_g=Mn([dt(0,zs)],_g);var d0=!1,DA=class extends qt{constructor(t){super(),this._windowsWrappingHeuristics=this._register(new Qa),this._onBinary=this._register(new st),this.onBinary=this._onBinary.event,this._onData=this._register(new st),this.onData=this._onData.event,this._onLineFeed=this._register(new st),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new st),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new st),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new st),this._instantiationService=new oA,this.optionsService=this._register(new gA(t)),this._instantiationService.setService(Fs,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(fg)),this._instantiationService.setService(zs,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(hg)),this._instantiationService.setService(W1,this._logService),this.coreService=this._register(this._instantiationService.createInstance(pg)),this._instantiationService.setService(na,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(mg)),this._instantiationService.setService(U1,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Fo)),this._instantiationService.setService(nL,this.unicodeService),this._charsetService=this._instantiationService.createInstance(wA),this._instantiationService.setService(tL,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_g),this._instantiationService.setService(q1,this._oscLinkService),this._inputHandler=this._register(new MA(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(ys.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(ys.forward(this._bufferService.onResize,this._onResize)),this._register(ys.forward(this.coreService.onData,this._onData)),this._register(ys.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new PA((n,s)=>this._inputHandler.parse(n,s))),this._register(ys.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new st),this._onScroll.event(t=>{var n;(n=this._onScrollApi)==null||n.fire(t.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(t){for(let n in t)this.optionsService.options[n]=t[n]}write(t,n){this._writeBuffer.write(t,n)}writeSync(t,n){this._logService.logLevel<=3&&!d0&&(this._logService.warn("writeSync is unreliable and will be removed soon."),d0=!0),this._writeBuffer.writeSync(t,n)}input(t,n=!0){this.coreService.triggerDataEvent(t,n)}resize(t,n){isNaN(t)||isNaN(n)||(t=Math.max(t,xk),n=Math.max(n,kk),this._bufferService.resize(t,n))}scroll(t,n=!1){this._bufferService.scroll(t,n)}scrollLines(t,n){this._bufferService.scrollLines(t,n)}scrollPages(t){this.scrollLines(t*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(t){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(t){let n=t-this._bufferService.buffer.ydisp;n!==0&&this.scrollLines(n)}registerEscHandler(t,n){return this._inputHandler.registerEscHandler(t,n)}registerDcsHandler(t,n){return this._inputHandler.registerDcsHandler(t,n)}registerCsiHandler(t,n){return this._inputHandler.registerCsiHandler(t,n)}registerOscHandler(t,n){return this._inputHandler.registerOscHandler(t,n)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let t=!1,n=this.optionsService.rawOptions.windowsPty;n&&n.buildNumber!==void 0&&n.buildNumber!==void 0?t=n.backend==="conpty"&&n.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(t=!0),t?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let t=[];t.push(this.onLineFeed(n0.bind(null,this._bufferService))),t.push(this.registerCsiHandler({final:"H"},()=>(n0(this._bufferService),!1))),this._windowsWrappingHeuristics.value=yn(()=>{for(let n of t)n.dispose()})}}},OA={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function BA(e,t,n,s){var c;let i={type:0,cancel:!1,key:void 0},l=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?i.key=Fe.ESC+"OA":i.key=Fe.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?i.key=Fe.ESC+"OD":i.key=Fe.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?i.key=Fe.ESC+"OC":i.key=Fe.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?i.key=Fe.ESC+"OB":i.key=Fe.ESC+"[B");break;case 8:i.key=e.ctrlKey?"\b":Fe.DEL,e.altKey&&(i.key=Fe.ESC+i.key);break;case 9:if(e.shiftKey){i.key=Fe.ESC+"[Z";break}i.key=Fe.HT,i.cancel=!0;break;case 13:i.key=e.altKey?Fe.ESC+Fe.CR:Fe.CR,i.cancel=!0;break;case 27:i.key=Fe.ESC,e.altKey&&(i.key=Fe.ESC+Fe.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;l?i.key=Fe.ESC+"[1;"+(l+1)+"D":t?i.key=Fe.ESC+"OD":i.key=Fe.ESC+"[D";break;case 39:if(e.metaKey)break;l?i.key=Fe.ESC+"[1;"+(l+1)+"C":t?i.key=Fe.ESC+"OC":i.key=Fe.ESC+"[C";break;case 38:if(e.metaKey)break;l?i.key=Fe.ESC+"[1;"+(l+1)+"A":t?i.key=Fe.ESC+"OA":i.key=Fe.ESC+"[A";break;case 40:if(e.metaKey)break;l?i.key=Fe.ESC+"[1;"+(l+1)+"B":t?i.key=Fe.ESC+"OB":i.key=Fe.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=Fe.ESC+"[2~");break;case 46:l?i.key=Fe.ESC+"[3;"+(l+1)+"~":i.key=Fe.ESC+"[3~";break;case 36:l?i.key=Fe.ESC+"[1;"+(l+1)+"H":t?i.key=Fe.ESC+"OH":i.key=Fe.ESC+"[H";break;case 35:l?i.key=Fe.ESC+"[1;"+(l+1)+"F":t?i.key=Fe.ESC+"OF":i.key=Fe.ESC+"[F";break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=Fe.ESC+"[5;"+(l+1)+"~":i.key=Fe.ESC+"[5~";break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=Fe.ESC+"[6;"+(l+1)+"~":i.key=Fe.ESC+"[6~";break;case 112:l?i.key=Fe.ESC+"[1;"+(l+1)+"P":i.key=Fe.ESC+"OP";break;case 113:l?i.key=Fe.ESC+"[1;"+(l+1)+"Q":i.key=Fe.ESC+"OQ";break;case 114:l?i.key=Fe.ESC+"[1;"+(l+1)+"R":i.key=Fe.ESC+"OR";break;case 115:l?i.key=Fe.ESC+"[1;"+(l+1)+"S":i.key=Fe.ESC+"OS";break;case 116:l?i.key=Fe.ESC+"[15;"+(l+1)+"~":i.key=Fe.ESC+"[15~";break;case 117:l?i.key=Fe.ESC+"[17;"+(l+1)+"~":i.key=Fe.ESC+"[17~";break;case 118:l?i.key=Fe.ESC+"[18;"+(l+1)+"~":i.key=Fe.ESC+"[18~";break;case 119:l?i.key=Fe.ESC+"[19;"+(l+1)+"~":i.key=Fe.ESC+"[19~";break;case 120:l?i.key=Fe.ESC+"[20;"+(l+1)+"~":i.key=Fe.ESC+"[20~";break;case 121:l?i.key=Fe.ESC+"[21;"+(l+1)+"~":i.key=Fe.ESC+"[21~";break;case 122:l?i.key=Fe.ESC+"[23;"+(l+1)+"~":i.key=Fe.ESC+"[23~";break;case 123:l?i.key=Fe.ESC+"[24;"+(l+1)+"~":i.key=Fe.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=Fe.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=Fe.DEL:e.keyCode===219?i.key=Fe.ESC:e.keyCode===220?i.key=Fe.FS:e.keyCode===221&&(i.key=Fe.GS);else if((!n||s)&&e.altKey&&!e.metaKey){let u=(c=OA[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(u)i.key=Fe.ESC+u;else if(e.keyCode>=65&&e.keyCode<=90){let h=e.ctrlKey?e.keyCode-64:e.keyCode+32,p=String.fromCharCode(h);e.shiftKey&&(p=p.toUpperCase()),i.key=Fe.ESC+p}else if(e.keyCode===32)i.key=Fe.ESC+(e.ctrlKey?Fe.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let h=e.code.slice(3,4);e.shiftKey||(h=h.toLowerCase()),i.key=Fe.ESC+h,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(i.key=Fe.US),e.key==="@"&&(i.key=Fe.NUL));break}return i}var Pn=0,$A=class{constructor(t){this._getKey=t,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Wd,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Wd,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(t){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(t)}_flushInserted(){let t=this._insertedValues.sort((l,c)=>this._getKey(l)-this._getKey(c)),n=0,s=0,i=new Array(this._array.length+this._insertedValues.length);for(let l=0;l<i.length;l++)s>=this._array.length||this._getKey(t[n])<=this._getKey(this._array[s])?(i[l]=t[n],n++):i[l]=this._array[s++];this._array=i,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(t){if(this._flushCleanupInserted(),this._array.length===0)return!1;let n=this._getKey(t);if(n===void 0||(Pn=this._search(n),Pn===-1)||this._getKey(this._array[Pn])!==n)return!1;do if(this._array[Pn]===t)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Pn),!0;while(++Pn<this._array.length&&this._getKey(this._array[Pn])===n);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let t=this._deletedIndices.sort((l,c)=>l-c),n=0,s=new Array(this._array.length-t.length),i=0;for(let l=0;l<this._array.length;l++)t[n]===l?n++:s[i++]=this._array[l];this._array=s,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Pn=this._search(t),!(Pn<0||Pn>=this._array.length)&&this._getKey(this._array[Pn])===t))do yield this._array[Pn];while(++Pn<this._array.length&&this._getKey(this._array[Pn])===t)}forEachByKey(t,n){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Pn=this._search(t),!(Pn<0||Pn>=this._array.length)&&this._getKey(this._array[Pn])===t))do n(this._array[Pn]);while(++Pn<this._array.length&&this._getKey(this._array[Pn])===t)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(t){let n=0,s=this._array.length-1;for(;s>=n;){let i=n+s>>1,l=this._getKey(this._array[i]);if(l>t)s=i-1;else if(l<t)n=i+1;else{for(;i>0&&this._getKey(this._array[i-1])===t;)i--;return i}}return n}},xp=0,h0=0,zA=class extends qt{constructor(){super(),this._decorations=new $A(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new st),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new st),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(yn(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new FA(e);if(t){let n=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),n.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let s=0,i=0;for(let l of this._decorations.getKeyIterator(t))s=l.options.x??0,i=s+(l.options.width??1),e>=s&&e<i&&(!n||(l.options.layer??"bottom")===n)&&(yield l)}forEachDecorationAtCell(e,t,n,s){this._decorations.forEachByKey(t,i=>{xp=i.options.x??0,h0=xp+(i.options.width??1),e>=xp&&e<h0&&(!n||(i.options.layer??"bottom")===n)&&s(i)})}},FA=class extends ho{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new st),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new st),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=Cn.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Cn.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},HA=1e3,UA=class{constructor(t,n=HA){this._renderCallback=t,this._debounceThresholdMS=n,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(t,n,s){this._rowCount=s,t=t!==void 0?t:0,n=n!==void 0?n:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,t):t,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,n):n;let i=performance.now();if(i-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=i,this._innerRefresh();else if(!this._additionalRefreshRequested){let l=i-this._lastRefreshMs,c=this._debounceThresholdMS-l;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},c)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let t=Math.max(this._rowStart,0),n=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(t,n)}},f0=20,qd=class extends qt{constructor(e,t,n,s){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=i.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let l=0;l<this._terminal.rows;l++)this._rowElements[l]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[l]);if(this._topBoundaryFocusListener=l=>this._handleBoundaryFocus(l,0),this._bottomBoundaryFocusListener=l=>this._handleBoundaryFocus(l,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new UA(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(l=>this._handleResize(l.rows))),this._register(this._terminal.onRender(l=>this._refreshRows(l.start,l.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(l=>this._handleChar(l))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
64
+ `))),this._register(this._terminal.onA11yTab(l=>this._handleTab(l))),this._register(this._terminal.onKey(l=>this._handleKey(l.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Ot(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(yn(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<f0+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
65
+ `&&(this._liveRegionLineCount++,this._liveRegionLineCount===f0+1&&(this._liveRegion.textContent+=Bm.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,s=n.lines.length.toString();for(let i=e;i<=t;i++){let l=n.lines.get(n.ydisp+i),c=[],u=(l==null?void 0:l.translateToString(!0,void 0,void 0,c))||"",h=(n.ydisp+i+1).toString(),p=this._rowElements[i];p&&(u.length===0?(p.textContent=" ",this._rowColumns.set(p,[0,1])):(p.textContent=u,this._rowColumns.set(p,c)),p.setAttribute("aria-posinset",h),p.setAttribute("aria-setsize",s),this._alignRowWidth(p))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],i=n.getAttribute("aria-posinset"),l=t===0?"1":`${this._terminal.buffer.lines.length}`;if(i===l||e.relatedTarget!==s)return;let c,u;if(t===0?(c=n,u=this._rowElements.pop(),this._rowContainer.removeChild(u)):(c=this._rowElements.shift(),u=n,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),u.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let h=this._createAccessibilityTreeNode();this._rowElements.unshift(h),this._rowContainer.insertAdjacentElement("afterbegin",h)}else{let h=this._createAccessibilityTreeNode();this._rowElements.push(h),this._rowContainer.appendChild(h)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var u;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:s,offset:((u=s.textContent)==null?void 0:u.length)??0}),!this._rowContainer.contains(n.node))return;let i=({node:h,offset:p})=>{let v=h instanceof Text?h.parentNode:h,_=parseInt(v==null?void 0:v.getAttribute("aria-posinset"),10)-1;if(isNaN(_))return console.warn("row is invalid. Race condition?"),null;let g=this._rowColumns.get(v);if(!g)return console.warn("columns is null. Race condition?"),null;let w=p<g.length?g[p]:g.slice(-1)[0]+1;return w>=this._terminal.cols&&(++_,w=0),{row:_,column:w}},l=i(t),c=i(n);if(!(!l||!c)){if(l.row>c.row||l.row===c.row&&l.column>=c.column)throw new Error("invalid range");this._terminal.select(l.column,l.row,(c.row-l.row)*this._terminal.cols-l.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){var i,l;e.style.transform="";let t=e.getBoundingClientRect().width,n=(l=(i=this._rowColumns.get(e))==null?void 0:i.slice(-1))==null?void 0:l[0];if(!n)return;let s=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${s/t})`}};qd=Mn([dt(1,Ev),dt(2,Mr),dt(3,Tr)],qd);var yg=class extends qt{constructor(e,t,n,s,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=s,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new st),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new st),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(yn(()=>{var l;Qo(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(l=this._activeProviderReplies)==null||l.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ot(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ot(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ot(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ot(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let s=0;s<n.length;s++){let i=n[s];if(i.classList.contains("xterm"))break;if(i.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){var s,i;(!this._activeProviderReplies||!t)&&((s=this._activeProviderReplies)==null||s.forEach(l=>{l==null||l.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[l,c]of this._linkProviderService.linkProviders.entries())t?(i=this._activeProviderReplies)!=null&&i.get(l)&&(n=this._checkLinkProviderResult(l,e,n)):c.provideLinks(e.y,u=>{var p,v;if(this._isMouseOut)return;let h=u==null?void 0:u.map(_=>({link:_}));(p=this._activeProviderReplies)==null||p.set(l,h),n=this._checkLinkProviderResult(l,e,n),((v=this._activeProviderReplies)==null?void 0:v.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let s=0;s<t.size;s++){let i=t.get(s);if(i)for(let l=0;l<i.length;l++){let c=i[l],u=c.link.range.start.y<e?0:c.link.range.start.x,h=c.link.range.end.y>e?this._bufferService.cols:c.link.range.end.x;for(let p=u;p<=h;p++){if(n.has(p)){i.splice(l--,1);break}n.add(p)}}}}_checkLinkProviderResult(e,t,n){var l;if(!this._activeProviderReplies)return n;let s=this._activeProviderReplies.get(e),i=!1;for(let c=0;c<e;c++)(!this._activeProviderReplies.has(c)||this._activeProviderReplies.get(c))&&(i=!0);if(!i&&s){let c=s.find(u=>this._linkAtPosition(u.link,t));c&&(n=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let c=0;c<this._activeProviderReplies.size;c++){let u=(l=this._activeProviderReplies.get(c))==null?void 0:l.find(h=>this._linkAtPosition(h.link,t));if(u){n=!0,this._handleNewLink(u);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&WA(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Qo(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var n,s;return(s=(n=this._currentLink)==null?void 0:n.state)==null?void 0:s.decorations.pointerCursor},set:n=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>{var n,s;return(s=(n=this._currentLink)==null?void 0:n.state)==null?void 0:s.decorations.underline},set:n=>{var s,i,l;(s=this._currentLink)!=null&&s.state&&((l=(i=this._currentLink)==null?void 0:i.state)==null?void 0:l.decorations.underline)!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let s=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(s,i),this._lastMouseEvent)){let l=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);l&&this._askForLink(l,!1)}})))}_linkHover(e,t,n){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,s=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-s-1,n.end.x,n.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=s}_positionFromMouseEvent(e,t,n){let s=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,s,i){return{x1:e,y1:t,x2:n,y2:s,cols:this._bufferService.cols,fg:i}}};yg=Mn([dt(1,Nv),dt(2,Tr),dt(3,zs),dt(4,V1)],yg);function WA(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var qA=class extends DA{constructor(t={}){super(t),this._linkifier=this._register(new Qa),this.browser=hk,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Qa),this._onCursorMove=this._register(new st),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new st),this.onKey=this._onKey.event,this._onRender=this._register(new st),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new st),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new st),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new st),this.onBell=this._onBell.event,this._onFocus=this._register(new st),this._onBlur=this._register(new st),this._onA11yCharEmitter=this._register(new st),this._onA11yTabEmitter=this._register(new st),this._onWillOpen=this._register(new st),this._setup(),this._decorationService=this._instantiationService.createInstance(zA),this._instantiationService.setService(Jc,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(IR),this._instantiationService.setService(V1,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(zm)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(n=>this.refresh((n==null?void 0:n.start)??0,(n==null?void 0:n.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(n=>this._reportWindowsOptions(n))),this._register(this._inputHandler.onColor(n=>this._handleColorEvent(n))),this._register(ys.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(ys.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(ys.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(ys.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(n=>this._afterResize(n.cols,n.rows))),this._register(yn(()=>{var n,s;this._customKeyEventHandler=void 0,(s=(n=this.element)==null?void 0:n.parentNode)==null||s.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(t){if(this._themeService)for(let n of t){let s,i="";switch(n.index){case 256:s="foreground",i="10";break;case 257:s="background",i="11";break;case 258:s="cursor",i="12";break;default:s="ansi",i="4;"+n.index}switch(n.type){case 0:let l=gn.toColorRGB(s==="ansi"?this._themeService.colors.ansi[n.index]:this._themeService.colors[s]);this.coreService.triggerDataEvent(`${Fe.ESC}]${i};${RA(l)}${uk.ST}`);break;case 1:if(s==="ansi")this._themeService.modifyColors(c=>c.ansi[n.index]=zn.toColor(...n.color));else{let c=s;this._themeService.modifyColors(u=>u[c]=zn.toColor(...n.color))}break;case 2:this._themeService.restoreColor(n.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(t){t?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(qd,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(t){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Fe.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var t;return(t=this.textarea)==null?void 0:t.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Fe.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let t=this.buffer.ybase+this.buffer.y,n=this.buffer.lines.get(t);if(!n)return;let s=Math.min(this.buffer.x,this.cols-1),i=this._renderService.dimensions.css.cell.height,l=n.getWidth(s),c=this._renderService.dimensions.css.cell.width*l,u=this.buffer.y*this._renderService.dimensions.css.cell.height,h=s*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=u+"px",this.textarea.style.width=c+"px",this.textarea.style.height=i+"px",this.textarea.style.lineHeight=i+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Ot(this.element,"copy",n=>{this.hasSelection()&&Yj(n,this._selectionService)}));let t=n=>Xj(n,this.textarea,this.coreService,this.optionsService);this._register(Ot(this.textarea,"paste",t)),this._register(Ot(this.element,"paste",t)),fk?this._register(Ot(this.element,"mousedown",n=>{n.button===2&&xw(n,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ot(this.element,"contextmenu",n=>{xw(n,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Pv&&this._register(Ot(this.element,"auxclick",n=>{n.button===1&&B1(n,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ot(this.textarea,"keyup",t=>this._keyUp(t),!0)),this._register(Ot(this.textarea,"keydown",t=>this._keyDown(t),!0)),this._register(Ot(this.textarea,"keypress",t=>this._keyPress(t),!0)),this._register(Ot(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ot(this.textarea,"compositionupdate",t=>this._compositionHelper.compositionupdate(t))),this._register(Ot(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ot(this.textarea,"input",t=>this._inputEvent(t),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(t){var l;if(!t)throw new Error("Terminal requires a parent element.");if(t.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((l=this.element)==null?void 0:l.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=t.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),t.appendChild(this.element);let n=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),n.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Ot(this.screenElement,"mousemove",c=>this.updateCursorStyle(c))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),n.appendChild(this.screenElement);let s=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Om.get()),gk||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>s.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(MR,this.textarea,t.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Mr,this._coreBrowserService),this._register(Ot(this.textarea,"focus",c=>this._handleTextAreaFocus(c))),this._register(Ot(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(ag,this._document,this._helperContainer),this._instantiationService.setService(_h,this._charSizeService),this._themeService=this._instantiationService.createInstance(dg),this._instantiationService.setService(ol,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Hd),this._instantiationService.setService(K1,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(cg,this.rows,this.screenElement)),this._instantiationService.setService(Tr,this._renderService),this._register(this._renderService.onRenderedViewportChange(c=>this._onRender.fire(c))),this.onResize(c=>this._renderService.resize(c.cols,c.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(ig,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(lg),this._instantiationService.setService(Nv,this._mouseService);let i=this._linkifier.value=this._register(this._instantiationService.createInstance(yg,this.screenElement));this.element.appendChild(n);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ng,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(c=>{super.scrollLines(c,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(ug,this.element,this.screenElement,i)),this._instantiationService.setService(iL,this._selectionService),this._register(this._selectionService.onRequestScrollLines(c=>this.scrollLines(c.amount,c.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(c=>this._renderService.handleSelectionChanged(c.start,c.end,c.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(c=>{this.textarea.value=c,this.textarea.focus(),this.textarea.select()})),this._register(ys.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var c;this._selectionService.refresh(),(c=this._viewport)==null||c.queueSync()})),this._register(this._instantiationService.createInstance(sg,this.screenElement)),this._register(Ot(this.element,"mousedown",c=>this._selectionService.handleMouseDown(c))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(qd,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",c=>this._handleScreenReaderModeOptionChange(c))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Fd,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",c=>{!this._overviewRulerRenderer&&c&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Fd,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(og,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let t=this,n=this.element;function s(c){var v,_,g,w,S;let u=t._mouseService.getMouseReportCoords(c,t.screenElement);if(!u)return!1;let h,p;switch(c.overrideType||c.type){case"mousemove":p=32,c.buttons===void 0?(h=3,c.button!==void 0&&(h=c.button<3?c.button:3)):h=c.buttons&1?0:c.buttons&4?1:c.buttons&2?2:3;break;case"mouseup":p=0,h=c.button<3?c.button:3;break;case"mousedown":p=1,h=c.button<3?c.button:3;break;case"wheel":if(t._customWheelEventHandler&&t._customWheelEventHandler(c)===!1)return!1;let N=c.deltaY;if(N===0||t.coreMouseService.consumeWheelEvent(c,(w=(g=(_=(v=t._renderService)==null?void 0:v.dimensions)==null?void 0:_.device)==null?void 0:g.cell)==null?void 0:w.height,(S=t._coreBrowserService)==null?void 0:S.dpr)===0)return!1;p=N<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:t.coreMouseService.triggerMouseEvent({col:u.col,row:u.row,x:u.x,y:u.y,button:h,action:p,ctrl:c.ctrlKey,alt:c.altKey,shift:c.shiftKey})}let i={mouseup:null,wheel:null,mousedrag:null,mousemove:null},l={mouseup:c=>(s(c),c.buttons||(this._document.removeEventListener("mouseup",i.mouseup),i.mousedrag&&this._document.removeEventListener("mousemove",i.mousedrag)),this.cancel(c)),wheel:c=>(s(c),this.cancel(c,!0)),mousedrag:c=>{c.buttons&&s(c)},mousemove:c=>{c.buttons||s(c)}};this._register(this.coreMouseService.onProtocolChange(c=>{c?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(c)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),c&8?i.mousemove||(n.addEventListener("mousemove",l.mousemove),i.mousemove=l.mousemove):(n.removeEventListener("mousemove",i.mousemove),i.mousemove=null),c&16?i.wheel||(n.addEventListener("wheel",l.wheel,{passive:!1}),i.wheel=l.wheel):(n.removeEventListener("wheel",i.wheel),i.wheel=null),c&2?i.mouseup||(i.mouseup=l.mouseup):(this._document.removeEventListener("mouseup",i.mouseup),i.mouseup=null),c&4?i.mousedrag||(i.mousedrag=l.mousedrag):(this._document.removeEventListener("mousemove",i.mousedrag),i.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ot(n,"mousedown",c=>{if(c.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(c)))return s(c),i.mouseup&&this._document.addEventListener("mouseup",i.mouseup),i.mousedrag&&this._document.addEventListener("mousemove",i.mousedrag),this.cancel(c)})),this._register(Ot(n,"wheel",c=>{var u,h,p,v,_;if(!i.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(c)===!1)return!1;if(!this.buffer.hasScrollback){if(c.deltaY===0)return!1;if(t.coreMouseService.consumeWheelEvent(c,(v=(p=(h=(u=t._renderService)==null?void 0:u.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:v.height,(_=t._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(c,!0);let g=Fe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(c.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(g,!0),this.cancel(c,!0)}}},{passive:!1}))}refresh(t,n){var s;(s=this._renderService)==null||s.refreshRows(t,n)}updateCursorStyle(t){var n;(n=this._selectionService)!=null&&n.shouldColumnSelect(t)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(t,n){this._viewport?this._viewport.scrollLines(t):super.scrollLines(t,n),this.refresh(0,this.rows-1)}scrollPages(t){this.scrollLines(t*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(t){t&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(t){let n=t-this._bufferService.buffer.ydisp;n!==0&&this.scrollLines(n)}paste(t){O1(t,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(t){this._customKeyEventHandler=t}attachCustomWheelEventHandler(t){this._customWheelEventHandler=t}registerLinkProvider(t){return this._linkProviderService.registerLinkProvider(t)}registerCharacterJoiner(t){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let n=this._characterJoinerService.register(t);return this.refresh(0,this.rows-1),n}deregisterCharacterJoiner(t){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(t)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(t){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+t)}registerDecoration(t){return this._decorationService.registerDecoration(t)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(t,n,s){this._selectionService.setSelection(t,n,s)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var t;(t=this._selectionService)==null||t.clearSelection()}selectAll(){var t;(t=this._selectionService)==null||t.selectAll()}selectLines(t,n){var s;(s=this._selectionService)==null||s.selectLines(t,n)}_keyDown(t){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(t)===!1)return!1;let n=this.browser.isMac&&this.options.macOptionIsMeta&&t.altKey;if(!n&&!this._compositionHelper.keydown(t))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!n&&(t.key==="Dead"||t.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let s=BA(t,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(t),s.type===3||s.type===2){let i=this.rows-1;return this.scrollLines(s.type===2?-i:i),this.cancel(t,!0)}if(s.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,t)||(s.cancel&&this.cancel(t,!0),!s.key)||t.key&&!t.ctrlKey&&!t.altKey&&!t.metaKey&&t.key.length===1&&t.key.charCodeAt(0)>=65&&t.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((s.key===Fe.ETX||s.key===Fe.CR)&&(this.textarea.value=""),this._onKey.fire({key:s.key,domEvent:t}),this._showCursor(),this.coreService.triggerDataEvent(s.key,!0),!this.optionsService.rawOptions.screenReaderMode||t.altKey||t.ctrlKey)return this.cancel(t,!0);this._keyDownHandled=!0}_isThirdLevelShift(t,n){let s=t.isMac&&!this.options.macOptionIsMeta&&n.altKey&&!n.ctrlKey&&!n.metaKey||t.isWindows&&n.altKey&&n.ctrlKey&&!n.metaKey||t.isWindows&&n.getModifierState("AltGraph");return n.type==="keypress"?s:s&&(!n.keyCode||n.keyCode>47)}_keyUp(t){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(t)===!1)&&(KA(t)||this.focus(),this.updateCursorStyle(t),this._keyPressHandled=!1)}_keyPress(t){let n;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(t)===!1)return!1;if(this.cancel(t),t.charCode)n=t.charCode;else if(t.which===null||t.which===void 0)n=t.keyCode;else if(t.which!==0&&t.charCode!==0)n=t.which;else return!1;return!n||(t.altKey||t.ctrlKey||t.metaKey)&&!this._isThirdLevelShift(this.browser,t)?!1:(n=String.fromCharCode(n),this._onKey.fire({key:n,domEvent:t}),this._showCursor(),this.coreService.triggerDataEvent(n,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(t){if(t.data&&t.inputType==="insertText"&&(!t.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let n=t.data;return this.coreService.triggerDataEvent(n,!0),this.cancel(t),!0}return!1}resize(t,n){if(t===this.cols&&n===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(t,n)}_afterResize(t,n){var s;(s=this._charSizeService)==null||s.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let t=1;t<this.rows;t++)this.buffer.lines.push(this.buffer.getBlankLine(Bn));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){var n;this.options.rows=this.rows,this.options.cols=this.cols;let t=this._customKeyEventHandler;this._setup(),super.reset(),(n=this._selectionService)==null||n.reset(),this._decorationService.reset(),this._customKeyEventHandler=t,this.refresh(0,this.rows-1)}clearTextureAtlas(){var t;(t=this._renderService)==null||t.clearTextureAtlas()}_reportFocus(){var t;(t=this.element)!=null&&t.classList.contains("focus")?this.coreService.triggerDataEvent(Fe.ESC+"[I"):this.coreService.triggerDataEvent(Fe.ESC+"[O")}_reportWindowsOptions(t){if(this._renderService)switch(t){case 0:let n=this._renderService.dimensions.css.canvas.width.toFixed(0),s=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${Fe.ESC}[4;${s};${n}t`);break;case 1:let i=this._renderService.dimensions.css.cell.width.toFixed(0),l=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${Fe.ESC}[6;${l};${i}t`);break}}cancel(t,n){if(!(!this.options.cancelEvents&&!n))return t.preventDefault(),t.stopPropagation(),!1}};function KA(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var VA=class{constructor(){this._addons=[]}dispose(){for(let t=this._addons.length-1;t>=0;t--)this._addons[t].instance.dispose()}loadAddon(t,n){let s={instance:n,dispose:n.dispose,isDisposed:!1};this._addons.push(s),n.dispose=()=>this._wrappedAddonDispose(s),n.activate(t)}_wrappedAddonDispose(t){if(t.isDisposed)return;let n=-1;for(let s=0;s<this._addons.length;s++)if(this._addons[s]===t){n=s;break}if(n===-1)throw new Error("Could not dispose an addon that has not been loaded");t.isDisposed=!0,t.dispose.apply(t.instance),this._addons.splice(n,1)}},GA=class{constructor(t){this._line=t}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(t,n){if(!(t<0||t>=this._line.length))return n?(this._line.loadCell(t,n),n):this._line.loadCell(t,new Si)}translateToString(t,n,s){return this._line.translateToString(t,n,s)}},p0=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new GA(t)}getNullCell(){return new Si}},YA=class extends qt{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new st),this.onBufferChange=this._onBufferChange.event,this._normal=new p0(this._core.buffers.normal,"normal"),this._alternate=new p0(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},XA=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,s)=>t(n,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},JA=class{constructor(t){this._core=t}register(t){this._core.unicodeService.register(t)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(t){this._core.unicodeService.activeVersion=t}},QA=["cols","rows"],Ki=0,ZA=class extends qt{constructor(e){super(),this._core=this._register(new qA(e)),this._addonManager=this._register(new VA),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],n=(s,i)=>{this._checkReadonlyOptions(s),this._core.options[s]=i};for(let s in this._core.options){let i={get:t.bind(this,s),set:n.bind(this,s)};Object.defineProperty(this._publicOptions,s,i)}}_checkReadonlyOptions(e){if(QA.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new XA(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new JA(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new YA(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
66
+ `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Om.get()},set promptLabel(e){Om.set(e)},get tooMuchOutput(){return Bm.get()},set tooMuchOutput(e){Bm.set(e)}}}_verifyIntegers(...e){for(Ki of e)if(Ki===1/0||isNaN(Ki)||Ki%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Ki of e)if(Ki&&(Ki===1/0||isNaN(Ki)||Ki%1!==0||Ki<0))throw new Error("This API only accepts positive integers")}};/**
67
+ * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
68
+ * @license MIT
69
+ *
70
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
71
+ * @license MIT
72
+ *
73
+ * Originally forked from (with the author's permission):
74
+ * Fabrice Bellard's javascript vt100 for jslinux:
75
+ * http://bellard.org/jslinux/
76
+ * Copyright (c) 2011 Fabrice Bellard
77
+ */var eM=2,tM=1,nM=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var _;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((_=this._terminal.options.overviewRuler)==null?void 0:_.width)||14,n=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(n.getPropertyValue("height")),i=Math.max(0,parseInt(n.getPropertyValue("width"))),l=window.getComputedStyle(this._terminal.element),c={top:parseInt(l.getPropertyValue("padding-top")),bottom:parseInt(l.getPropertyValue("padding-bottom")),right:parseInt(l.getPropertyValue("padding-right")),left:parseInt(l.getPropertyValue("padding-left"))},u=c.top+c.bottom,h=c.right+c.left,p=s-u,v=i-h-t;return{cols:Math.max(eM,Math.floor(v/e.css.cell.width)),rows:Math.max(tM,Math.floor(p/e.css.cell.height))}}};const sM=Object.freeze([[4352,4447],[8986,8987],[9001,9002],[9193,9196],[9200,9200],[9203,9203],[9725,9726],[9748,9749],[9800,9811],[9855,9855],[9875,9875],[9889,9889],[9898,9899],[9917,9918],[9924,9925],[9934,9934],[9940,9940],[9962,9962],[9970,9971],[9973,9973],[9978,9978],[9981,9981],[9989,9989],[9994,9995],[10024,10024],[10060,10060],[10062,10062],[10067,10069],[10071,10071],[10133,10135],[10160,10160],[10175,10175],[11035,11036],[11088,11088],[11093,11093],[11904,12350],[12352,12871],[12880,19903],[19968,42182],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65131],[65281,65376],[65504,65510],[126976,127461],[127488,129791]]),iM=Object.freeze([[768,879],[1155,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1552,1562],[1611,1631],[1648,1648],[1750,1756],[1759,1764],[1767,1768],[1770,1773],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2070,2073],[2075,2083],[2085,2087],[2089,2093],[2137,2139],[2275,2307],[2362,2364],[2369,2376],[2381,2381],[2385,2391],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2817,2817],[2876,2876],[2879,2879],[2881,2884],[2893,2893],[3134,3136],[3142,3144],[3146,3149],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3772],[3784,3790],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[4038,4038],[4448,4607],[4957,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6155,6157],[6832,6911],[7616,7679],[8203,8207],[8232,8238],[8288,8292],[8294,8303],[8400,8432],[11503,11505],[11647,11647],[11744,11775],[12330,12335],[12441,12442],[42607,42610],[42612,42621],[42654,42655],[42736,42737],[43010,43010],[43014,43014],[43019,43019],[43045,43046],[43204,43205],[64286,64286],[65024,65039],[65056,65071],[65279,65279],[66045,66045],[66272,66272],[113824,113827],[119141,119145],[119149,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]]),rM="nc-15.1";function m0(e,t){let n=0,s=e.length-1;for(;n<=s;){const i=n+s>>1,[l,c]=e[i];if(t<l)s=i-1;else if(t>c)n=i+1;else return!0}return!1}function oM(e,t,n){return(e&16777215)<<3|(t&3)<<1|(n?1:0)}function g0(e){const t=Number(e);return!Number.isFinite(t)||t<0||t<32||t>=127&&t<160||m0(iM,t)?0:m0(sM,t)?2:1}function aM(){return{version:rM,wcwidth:g0,charProperties(e,t){let n=g0(e),s=n===0&&t!==0;if(s){const i=t>>1&3;i===0?s=!1:i>n&&(n=i)}return oM(e,n,s)}}}function lM(e){try{const t=e&&e.unicode;if(!t||typeof t.register!="function")return null;const n=aM();return t.versions.includes(n.version)||t.register(n),t.activeVersion=n.version,n}catch{return null}}/**
78
+ * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
79
+ * @license MIT
80
+ *
81
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
82
+ * @license MIT
83
+ *
84
+ * Originally forked from (with the author's permission):
85
+ * Fabrice Bellard's javascript vt100 for jslinux:
86
+ * http://bellard.org/jslinux/
87
+ * Copyright (c) 2011 Fabrice Bellard
88
+ */var cM=(e,t,n,s)=>{for(var i=t,l=e.length-1,c;l>=0;l--)(c=e[l])&&(i=c(i)||i);return i},uM=(e,t)=>(n,s)=>t(n,s,e),dM=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?v0.isErrorNoTelemetry(e)?new v0(e.message+`
89
+
90
+ `+e.stack):new Error(e.message+`
91
+
92
+ `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},hM=new dM;function kp(e){fM(e)||hM.onUnexpectedError(e)}var bg="Canceled";function fM(e){return e instanceof pM?!0:e instanceof Error&&e.name===bg&&e.message===bg}var pM=class extends Error{constructor(){super(bg),this.name=this.message}},v0=class wg extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof wg)return t;let n=new wg;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},mM;(e=>{function t(l){return l<0}e.isLessThan=t;function n(l){return l<=0}e.isLessThanOrEqual=n;function s(l){return l>0}e.isGreaterThan=s;function i(l){return l===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(mM||(mM={}));function gM(e,t){let n=this,s=!1,i;return function(){return s||(s=!0,t||(i=e.apply(n,arguments))),i}}var Ek;(e=>{function t(x){return x&&typeof x=="object"&&typeof x[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function s(){return n}e.empty=s;function*i(x){yield x}e.single=i;function l(x){return t(x)?x:i(x)}e.wrap=l;function c(x){return x||n}e.from=c;function*u(x){for(let W=x.length-1;W>=0;W--)yield x[W]}e.reverse=u;function h(x){return!x||x[Symbol.iterator]().next().done===!0}e.isEmpty=h;function p(x){return x[Symbol.iterator]().next().value}e.first=p;function v(x,W){let $=0;for(let Y of x)if(W(Y,$++))return!0;return!1}e.some=v;function _(x,W){for(let $ of x)if(W($))return $}e.find=_;function*g(x,W){for(let $ of x)W($)&&(yield $)}e.filter=g;function*w(x,W){let $=0;for(let Y of x)yield W(Y,$++)}e.map=w;function*S(x,W){let $=0;for(let Y of x)yield*W(Y,$++)}e.flatMap=S;function*N(...x){for(let W of x)yield*W}e.concat=N;function C(x,W,$){let Y=$;for(let q of x)Y=W(Y,q);return Y}e.reduce=C;function*j(x,W,$=x.length){for(W<0&&(W+=x.length),$<0?$+=x.length:$>x.length&&($=x.length);W<$;W++)yield x[W]}e.slice=j;function E(x,W=Number.POSITIVE_INFINITY){let $=[];if(W===0)return[$,x];let Y=x[Symbol.iterator]();for(let q=0;q<W;q++){let K=Y.next();if(K.done)return[$,e.empty()];$.push(K.value)}return[$,{[Symbol.iterator](){return Y}}]}e.consume=E;async function R(x){let W=[];for await(let $ of x)W.push($);return Promise.resolve(W)}e.asyncToArray=R})(Ek||(Ek={}));function Nk(e){if(Ek.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(s){t.push(s)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function jk(...e){return As(()=>Nk(e))}function As(e){return{dispose:gM(()=>{e()})}}var Lk=class Rk{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Nk(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Rk.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Lk.DISABLE_DISPOSED_WARNING=!1;var Ga=Lk,Oi=class{constructor(){this._store=new Ga,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Oi.None=Object.freeze({dispose(){}});var Ql=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Dv=typeof process<"u"&&"title"in process,wh=Dv?"node":navigator.userAgent,vM=Dv?"node":navigator.platform,_M=wh.includes("Firefox"),yM=wh.includes("Edge"),Ak=/^((?!chrome|android).)*safari/i.test(wh);function bM(){if(!Ak)return 0;let e=wh.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}vM.indexOf("Linux")>=0;var wM="",as=0,ls=0,cs=0,An=0,gi={css:"#00000000",rgba:0},$s;(e=>{function t(i,l,c,u){return u!==void 0?`#${Io(i)}${Io(l)}${Io(c)}${Io(u)}`:`#${Io(i)}${Io(l)}${Io(c)}`}e.toCss=t;function n(i,l,c,u=255){return(i<<24|l<<16|c<<8|u)>>>0}e.toRgba=n;function s(i,l,c,u){return{css:e.toCss(i,l,c,u),rgba:e.toRgba(i,l,c,u)}}e.toColor=s})($s||($s={}));var yc;(e=>{function t(h,p){if(An=(p.rgba&255)/255,An===1)return{css:p.css,rgba:p.rgba};let v=p.rgba>>24&255,_=p.rgba>>16&255,g=p.rgba>>8&255,w=h.rgba>>24&255,S=h.rgba>>16&255,N=h.rgba>>8&255;as=w+Math.round((v-w)*An),ls=S+Math.round((_-S)*An),cs=N+Math.round((g-N)*An);let C=$s.toCss(as,ls,cs),j=$s.toRgba(as,ls,cs);return{css:C,rgba:j}}e.blend=t;function n(h){return(h.rgba&255)===255}e.isOpaque=n;function s(h,p,v){let _=Ko.ensureContrastRatio(h.rgba,p.rgba,v);if(_)return $s.toColor(_>>24&255,_>>16&255,_>>8&255)}e.ensureContrastRatio=s;function i(h){let p=(h.rgba|255)>>>0;return[as,ls,cs]=Ko.toChannels(p),{css:$s.toCss(as,ls,cs),rgba:p}}e.opaque=i;function l(h,p){return An=Math.round(p*255),[as,ls,cs]=Ko.toChannels(h.rgba),{css:$s.toCss(as,ls,cs,An),rgba:$s.toRgba(as,ls,cs,An)}}e.opacity=l;function c(h,p){return An=h.rgba&255,l(h,An*p/255)}e.multiplyOpacity=c;function u(h){return[h.rgba>>24&255,h.rgba>>16&255,h.rgba>>8&255]}e.toColorRGB=u})(yc||(yc={}));var SM;(e=>{let t,n;try{let i=document.createElement("canvas");i.width=1,i.height=1;let l=i.getContext("2d",{willReadFrequently:!0});l&&(t=l,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function s(i){if(i.match(/#[\da-f]{3,8}/i))switch(i.length){case 4:return as=parseInt(i.slice(1,2).repeat(2),16),ls=parseInt(i.slice(2,3).repeat(2),16),cs=parseInt(i.slice(3,4).repeat(2),16),$s.toColor(as,ls,cs);case 5:return as=parseInt(i.slice(1,2).repeat(2),16),ls=parseInt(i.slice(2,3).repeat(2),16),cs=parseInt(i.slice(3,4).repeat(2),16),An=parseInt(i.slice(4,5).repeat(2),16),$s.toColor(as,ls,cs,An);case 7:return{css:i,rgba:(parseInt(i.slice(1),16)<<8|255)>>>0};case 9:return{css:i,rgba:parseInt(i.slice(1),16)>>>0}}let l=i.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return as=parseInt(l[1]),ls=parseInt(l[2]),cs=parseInt(l[3]),An=Math.round((l[5]===void 0?1:parseFloat(l[5]))*255),$s.toColor(as,ls,cs,An);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=i,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[as,ls,cs,An]=t.getImageData(0,0,1,1).data,An!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:$s.toRgba(as,ls,cs,An),css:i}}e.toColor=s})(SM||(SM={}));var Bs;(e=>{function t(s){return n(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function n(s,i,l){let c=s/255,u=i/255,h=l/255,p=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),v=u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4);return p*.2126+v*.7152+_*.0722}e.relativeLuminance2=n})(Bs||(Bs={}));var Ko;(e=>{function t(c,u){if(An=(u&255)/255,An===1)return u;let h=u>>24&255,p=u>>16&255,v=u>>8&255,_=c>>24&255,g=c>>16&255,w=c>>8&255;return as=_+Math.round((h-_)*An),ls=g+Math.round((p-g)*An),cs=w+Math.round((v-w)*An),$s.toRgba(as,ls,cs)}e.blend=t;function n(c,u,h){let p=Bs.relativeLuminance(c>>8),v=Bs.relativeLuminance(u>>8);if(Sr(p,v)<h){if(v<p){let w=s(c,u,h),S=Sr(p,Bs.relativeLuminance(w>>8));if(S<h){let N=i(c,u,h),C=Sr(p,Bs.relativeLuminance(N>>8));return S>C?w:N}return w}let _=i(c,u,h),g=Sr(p,Bs.relativeLuminance(_>>8));if(g<h){let w=s(c,u,h),S=Sr(p,Bs.relativeLuminance(w>>8));return g>S?_:w}return _}}e.ensureContrastRatio=n;function s(c,u,h){let p=c>>24&255,v=c>>16&255,_=c>>8&255,g=u>>24&255,w=u>>16&255,S=u>>8&255,N=Sr(Bs.relativeLuminance2(g,w,S),Bs.relativeLuminance2(p,v,_));for(;N<h&&(g>0||w>0||S>0);)g-=Math.max(0,Math.ceil(g*.1)),w-=Math.max(0,Math.ceil(w*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=Sr(Bs.relativeLuminance2(g,w,S),Bs.relativeLuminance2(p,v,_));return(g<<24|w<<16|S<<8|255)>>>0}e.reduceLuminance=s;function i(c,u,h){let p=c>>24&255,v=c>>16&255,_=c>>8&255,g=u>>24&255,w=u>>16&255,S=u>>8&255,N=Sr(Bs.relativeLuminance2(g,w,S),Bs.relativeLuminance2(p,v,_));for(;N<h&&(g<255||w<255||S<255);)g=Math.min(255,g+Math.ceil((255-g)*.1)),w=Math.min(255,w+Math.ceil((255-w)*.1)),S=Math.min(255,S+Math.ceil((255-S)*.1)),N=Sr(Bs.relativeLuminance2(g,w,S),Bs.relativeLuminance2(p,v,_));return(g<<24|w<<16|S<<8|255)>>>0}e.increaseLuminance=i;function l(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=l})(Ko||(Ko={}));function Io(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Sr(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}function $n(e){if(!e)throw new Error("value must not be falsy");return e}function Ov(e){return 57508<=e&&e<=57558}function xM(e){return 57520<=e&&e<=57527}function kM(e){return 57344<=e&&e<=63743}function CM(e){return 9472<=e&&e<=9631}function EM(e){return e>=128512&&e<=128591||e>=127744&&e<=128511||e>=128640&&e<=128767||e>=9728&&e<=9983||e>=9984&&e<=10175||e>=65024&&e<=65039||e>=129280&&e<=129535||e>=127462&&e<=127487}function NM(e,t,n,s){return t===1&&n>Math.ceil(s*1.5)&&e!==void 0&&e>255&&!EM(e)&&!Ov(e)&&!kM(e)}function Mk(e){return Ov(e)||CM(e)}function jM(){return{css:{canvas:cd(),cell:cd()},device:{canvas:cd(),cell:cd(),char:{width:0,height:0,left:0,top:0}}}}function cd(){return{width:0,height:0}}function LM(e,t,n=0){return(e-(Math.round(t)*2-n))%(Math.round(t)*2)}var ms=0,ts=0,Vi=!1,xr=!1,ud=!1,Ys,Cp=0,RM=class{constructor(e,t,n,s,i,l){this._terminal=e,this._optionService=t,this._selectionRenderModel=n,this._decorationService=s,this._coreBrowserService=i,this._themeService=l,this.result={fg:0,bg:0,ext:0}}resolve(e,t,n,s){if(this.result.bg=e.bg,this.result.fg=e.fg,this.result.ext=e.bg&268435456?e.extended.ext:0,ts=0,ms=0,xr=!1,Vi=!1,ud=!1,Ys=this._themeService.colors,Cp=0,e.getCode()!==0&&e.extended.underlineStyle===4){let i=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));Cp=t*s%(Math.round(i)*2)}if(this._decorationService.forEachDecorationAtCell(t,n,"bottom",i=>{i.backgroundColorRGB&&(ts=i.backgroundColorRGB.rgba>>8&16777215,xr=!0),i.foregroundColorRGB&&(ms=i.foregroundColorRGB.rgba>>8&16777215,Vi=!0)}),ud=this._selectionRenderModel.isCellSelected(this._terminal,t,n),ud){if(this.result.fg&67108864||(this.result.bg&50331648)!==0){if(this.result.fg&67108864)switch(this.result.fg&50331648){case 16777216:case 33554432:ts=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:ts=(this.result.fg&16777215)<<8|255;break;case 0:default:ts=this._themeService.colors.foreground.rgba}else switch(this.result.bg&50331648){case 16777216:case 33554432:ts=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:ts=(this.result.bg&16777215)<<8|255;break}ts=Ko.blend(ts,(this._coreBrowserService.isFocused?Ys.selectionBackgroundOpaque:Ys.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}else ts=(this._coreBrowserService.isFocused?Ys.selectionBackgroundOpaque:Ys.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(xr=!0,Ys.selectionForeground&&(ms=Ys.selectionForeground.rgba>>8&16777215,Vi=!0),Mk(e.getCode())){if(this.result.fg&67108864&&(this.result.bg&50331648)===0)ms=(this._coreBrowserService.isFocused?Ys.selectionBackgroundOpaque:Ys.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(this.result.fg&67108864)switch(this.result.bg&50331648){case 16777216:case 33554432:ms=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:ms=(this.result.bg&16777215)<<8|255;break}else switch(this.result.fg&50331648){case 16777216:case 33554432:ms=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:ms=(this.result.fg&16777215)<<8|255;break;case 0:default:ms=this._themeService.colors.foreground.rgba}ms=Ko.blend(ms,(this._coreBrowserService.isFocused?Ys.selectionBackgroundOpaque:Ys.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}Vi=!0}}this._decorationService.forEachDecorationAtCell(t,n,"top",i=>{i.backgroundColorRGB&&(ts=i.backgroundColorRGB.rgba>>8&16777215,xr=!0),i.foregroundColorRGB&&(ms=i.foregroundColorRGB.rgba>>8&16777215,Vi=!0)}),xr&&(ud?ts=e.bg&-16777216&-134217729|ts|50331648:ts=e.bg&-16777216|ts|50331648),Vi&&(ms=e.fg&-16777216&-67108865|ms|50331648),this.result.fg&67108864&&(xr&&!Vi&&((this.result.bg&50331648)===0?ms=this.result.fg&-134217728|Ys.background.rgba>>8&16777215&16777215|50331648:ms=this.result.fg&-134217728|this.result.bg&67108863,Vi=!0),!xr&&Vi&&((this.result.fg&50331648)===0?ts=this.result.bg&-67108864|Ys.foreground.rgba>>8&16777215&16777215|50331648:ts=this.result.bg&-67108864|this.result.fg&67108863,xr=!0)),Ys=void 0,this.result.bg=xr?ts:this.result.bg,this.result.fg=Vi?ms:this.result.fg,this.result.ext&=536870911,this.result.ext|=Cp<<29&3758096384}},AM=.5,Tk=_M||yM?"bottom":"ideographic",MM={"▀":[{x:0,y:0,w:8,h:4}],"▁":[{x:0,y:7,w:8,h:1}],"▂":[{x:0,y:6,w:8,h:2}],"▃":[{x:0,y:5,w:8,h:3}],"▄":[{x:0,y:4,w:8,h:4}],"▅":[{x:0,y:3,w:8,h:5}],"▆":[{x:0,y:2,w:8,h:6}],"▇":[{x:0,y:1,w:8,h:7}],"█":[{x:0,y:0,w:8,h:8}],"▉":[{x:0,y:0,w:7,h:8}],"▊":[{x:0,y:0,w:6,h:8}],"▋":[{x:0,y:0,w:5,h:8}],"▌":[{x:0,y:0,w:4,h:8}],"▍":[{x:0,y:0,w:3,h:8}],"▎":[{x:0,y:0,w:2,h:8}],"▏":[{x:0,y:0,w:1,h:8}],"▐":[{x:4,y:0,w:4,h:8}],"▔":[{x:0,y:0,w:8,h:1}],"▕":[{x:7,y:0,w:1,h:8}],"▖":[{x:0,y:4,w:4,h:4}],"▗":[{x:4,y:4,w:4,h:4}],"▘":[{x:0,y:0,w:4,h:4}],"▙":[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}],"▚":[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}],"▛":[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}],"▜":[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}],"▝":[{x:4,y:0,w:4,h:4}],"▞":[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}],"▟":[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}],"🭰":[{x:1,y:0,w:1,h:8}],"🭱":[{x:2,y:0,w:1,h:8}],"🭲":[{x:3,y:0,w:1,h:8}],"🭳":[{x:4,y:0,w:1,h:8}],"🭴":[{x:5,y:0,w:1,h:8}],"🭵":[{x:6,y:0,w:1,h:8}],"🭶":[{x:0,y:1,w:8,h:1}],"🭷":[{x:0,y:2,w:8,h:1}],"🭸":[{x:0,y:3,w:8,h:1}],"🭹":[{x:0,y:4,w:8,h:1}],"🭺":[{x:0,y:5,w:8,h:1}],"🭻":[{x:0,y:6,w:8,h:1}],"🭼":[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}],"🭽":[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}],"🭾":[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}],"🭿":[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}],"🮀":[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}],"🮁":[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}],"🮂":[{x:0,y:0,w:8,h:2}],"🮃":[{x:0,y:0,w:8,h:3}],"🮄":[{x:0,y:0,w:8,h:5}],"🮅":[{x:0,y:0,w:8,h:6}],"🮆":[{x:0,y:0,w:8,h:7}],"🮇":[{x:6,y:0,w:2,h:8}],"🮈":[{x:5,y:0,w:3,h:8}],"🮉":[{x:3,y:0,w:5,h:8}],"🮊":[{x:2,y:0,w:6,h:8}],"🮋":[{x:1,y:0,w:7,h:8}],"🮕":[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}],"🮖":[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}],"🮗":[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},TM={"░":[[1,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]],"▒":[[1,0],[0,0],[0,1],[0,0]],"▓":[[0,1],[1,1],[1,0],[1,1]]},IM={"─":{1:"M0,.5 L1,.5"},"━":{3:"M0,.5 L1,.5"},"│":{1:"M.5,0 L.5,1"},"┃":{3:"M.5,0 L.5,1"},"┌":{1:"M0.5,1 L.5,.5 L1,.5"},"┏":{3:"M0.5,1 L.5,.5 L1,.5"},"┐":{1:"M0,.5 L.5,.5 L.5,1"},"┓":{3:"M0,.5 L.5,.5 L.5,1"},"└":{1:"M.5,0 L.5,.5 L1,.5"},"┗":{3:"M.5,0 L.5,.5 L1,.5"},"┘":{1:"M.5,0 L.5,.5 L0,.5"},"┛":{3:"M.5,0 L.5,.5 L0,.5"},"├":{1:"M.5,0 L.5,1 M.5,.5 L1,.5"},"┣":{3:"M.5,0 L.5,1 M.5,.5 L1,.5"},"┤":{1:"M.5,0 L.5,1 M.5,.5 L0,.5"},"┫":{3:"M.5,0 L.5,1 M.5,.5 L0,.5"},"┬":{1:"M0,.5 L1,.5 M.5,.5 L.5,1"},"┳":{3:"M0,.5 L1,.5 M.5,.5 L.5,1"},"┴":{1:"M0,.5 L1,.5 M.5,.5 L.5,0"},"┻":{3:"M0,.5 L1,.5 M.5,.5 L.5,0"},"┼":{1:"M0,.5 L1,.5 M.5,0 L.5,1"},"╋":{3:"M0,.5 L1,.5 M.5,0 L.5,1"},"╴":{1:"M.5,.5 L0,.5"},"╸":{3:"M.5,.5 L0,.5"},"╵":{1:"M.5,.5 L.5,0"},"╹":{3:"M.5,.5 L.5,0"},"╶":{1:"M.5,.5 L1,.5"},"╺":{3:"M.5,.5 L1,.5"},"╷":{1:"M.5,.5 L.5,1"},"╻":{3:"M.5,.5 L.5,1"},"═":{1:(e,t)=>`M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t}`},"║":{1:(e,t)=>`M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1`},"╒":{1:(e,t)=>`M.5,1 L.5,${.5-t} L1,${.5-t} M.5,${.5+t} L1,${.5+t}`},"╓":{1:(e,t)=>`M${.5-e},1 L${.5-e},.5 L1,.5 M${.5+e},.5 L${.5+e},1`},"╔":{1:(e,t)=>`M1,${.5-t} L${.5-e},${.5-t} L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1`},"╕":{1:(e,t)=>`M0,${.5-t} L.5,${.5-t} L.5,1 M0,${.5+t} L.5,${.5+t}`},"╖":{1:(e,t)=>`M${.5+e},1 L${.5+e},.5 L0,.5 M${.5-e},.5 L${.5-e},1`},"╗":{1:(e,t)=>`M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M0,${.5-t} L${.5+e},${.5-t} L${.5+e},1`},"╘":{1:(e,t)=>`M.5,0 L.5,${.5+t} L1,${.5+t} M.5,${.5-t} L1,${.5-t}`},"╙":{1:(e,t)=>`M1,.5 L${.5-e},.5 L${.5-e},0 M${.5+e},.5 L${.5+e},0`},"╚":{1:(e,t)=>`M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0 M1,${.5+t} L${.5-e},${.5+t} L${.5-e},0`},"╛":{1:(e,t)=>`M0,${.5+t} L.5,${.5+t} L.5,0 M0,${.5-t} L.5,${.5-t}`},"╜":{1:(e,t)=>`M0,.5 L${.5+e},.5 L${.5+e},0 M${.5-e},.5 L${.5-e},0`},"╝":{1:(e,t)=>`M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0 M0,${.5+t} L${.5+e},${.5+t} L${.5+e},0`},"╞":{1:(e,t)=>`M.5,0 L.5,1 M.5,${.5-t} L1,${.5-t} M.5,${.5+t} L1,${.5+t}`},"╟":{1:(e,t)=>`M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1 M${.5+e},.5 L1,.5`},"╠":{1:(e,t)=>`M${.5-e},0 L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1 M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0`},"╡":{1:(e,t)=>`M.5,0 L.5,1 M0,${.5-t} L.5,${.5-t} M0,${.5+t} L.5,${.5+t}`},"╢":{1:(e,t)=>`M0,.5 L${.5-e},.5 M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1`},"╣":{1:(e,t)=>`M${.5+e},0 L${.5+e},1 M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0`},"╤":{1:(e,t)=>`M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t} M.5,${.5+t} L.5,1`},"╥":{1:(e,t)=>`M0,.5 L1,.5 M${.5-e},.5 L${.5-e},1 M${.5+e},.5 L${.5+e},1`},"╦":{1:(e,t)=>`M0,${.5-t} L1,${.5-t} M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1`},"╧":{1:(e,t)=>`M.5,0 L.5,${.5-t} M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t}`},"╨":{1:(e,t)=>`M0,.5 L1,.5 M${.5-e},.5 L${.5-e},0 M${.5+e},.5 L${.5+e},0`},"╩":{1:(e,t)=>`M0,${.5+t} L1,${.5+t} M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0 M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0`},"╪":{1:(e,t)=>`M.5,0 L.5,1 M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t}`},"╫":{1:(e,t)=>`M0,.5 L1,.5 M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1`},"╬":{1:(e,t)=>`M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1 M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0 M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0`},"╱":{1:"M1,0 L0,1"},"╲":{1:"M0,0 L1,1"},"╳":{1:"M1,0 L0,1 M0,0 L1,1"},"╼":{1:"M.5,.5 L0,.5",3:"M.5,.5 L1,.5"},"╽":{1:"M.5,.5 L.5,0",3:"M.5,.5 L.5,1"},"╾":{1:"M.5,.5 L1,.5",3:"M.5,.5 L0,.5"},"╿":{1:"M.5,.5 L.5,1",3:"M.5,.5 L.5,0"},"┍":{1:"M.5,.5 L.5,1",3:"M.5,.5 L1,.5"},"┎":{1:"M.5,.5 L1,.5",3:"M.5,.5 L.5,1"},"┑":{1:"M.5,.5 L.5,1",3:"M.5,.5 L0,.5"},"┒":{1:"M.5,.5 L0,.5",3:"M.5,.5 L.5,1"},"┕":{1:"M.5,.5 L.5,0",3:"M.5,.5 L1,.5"},"┖":{1:"M.5,.5 L1,.5",3:"M.5,.5 L.5,0"},"┙":{1:"M.5,.5 L.5,0",3:"M.5,.5 L0,.5"},"┚":{1:"M.5,.5 L0,.5",3:"M.5,.5 L.5,0"},"┝":{1:"M.5,0 L.5,1",3:"M.5,.5 L1,.5"},"┞":{1:"M0.5,1 L.5,.5 L1,.5",3:"M.5,.5 L.5,0"},"┟":{1:"M.5,0 L.5,.5 L1,.5",3:"M.5,.5 L.5,1"},"┠":{1:"M.5,.5 L1,.5",3:"M.5,0 L.5,1"},"┡":{1:"M.5,.5 L.5,1",3:"M.5,0 L.5,.5 L1,.5"},"┢":{1:"M.5,.5 L.5,0",3:"M0.5,1 L.5,.5 L1,.5"},"┥":{1:"M.5,0 L.5,1",3:"M.5,.5 L0,.5"},"┦":{1:"M0,.5 L.5,.5 L.5,1",3:"M.5,.5 L.5,0"},"┧":{1:"M.5,0 L.5,.5 L0,.5",3:"M.5,.5 L.5,1"},"┨":{1:"M.5,.5 L0,.5",3:"M.5,0 L.5,1"},"┩":{1:"M.5,.5 L.5,1",3:"M.5,0 L.5,.5 L0,.5"},"┪":{1:"M.5,.5 L.5,0",3:"M0,.5 L.5,.5 L.5,1"},"┭":{1:"M0.5,1 L.5,.5 L1,.5",3:"M.5,.5 L0,.5"},"┮":{1:"M0,.5 L.5,.5 L.5,1",3:"M.5,.5 L1,.5"},"┯":{1:"M.5,.5 L.5,1",3:"M0,.5 L1,.5"},"┰":{1:"M0,.5 L1,.5",3:"M.5,.5 L.5,1"},"┱":{1:"M.5,.5 L1,.5",3:"M0,.5 L.5,.5 L.5,1"},"┲":{1:"M.5,.5 L0,.5",3:"M0.5,1 L.5,.5 L1,.5"},"┵":{1:"M.5,0 L.5,.5 L1,.5",3:"M.5,.5 L0,.5"},"┶":{1:"M.5,0 L.5,.5 L0,.5",3:"M.5,.5 L1,.5"},"┷":{1:"M.5,.5 L.5,0",3:"M0,.5 L1,.5"},"┸":{1:"M0,.5 L1,.5",3:"M.5,.5 L.5,0"},"┹":{1:"M.5,.5 L1,.5",3:"M.5,0 L.5,.5 L0,.5"},"┺":{1:"M.5,.5 L0,.5",3:"M.5,0 L.5,.5 L1,.5"},"┽":{1:"M.5,0 L.5,1 M.5,.5 L1,.5",3:"M.5,.5 L0,.5"},"┾":{1:"M.5,0 L.5,1 M.5,.5 L0,.5",3:"M.5,.5 L1,.5"},"┿":{1:"M.5,0 L.5,1",3:"M0,.5 L1,.5"},"╀":{1:"M0,.5 L1,.5 M.5,.5 L.5,1",3:"M.5,.5 L.5,0"},"╁":{1:"M.5,.5 L.5,0 M0,.5 L1,.5",3:"M.5,.5 L.5,1"},"╂":{1:"M0,.5 L1,.5",3:"M.5,0 L.5,1"},"╃":{1:"M0.5,1 L.5,.5 L1,.5",3:"M.5,0 L.5,.5 L0,.5"},"╄":{1:"M0,.5 L.5,.5 L.5,1",3:"M.5,0 L.5,.5 L1,.5"},"╅":{1:"M.5,0 L.5,.5 L1,.5",3:"M0,.5 L.5,.5 L.5,1"},"╆":{1:"M.5,0 L.5,.5 L0,.5",3:"M0.5,1 L.5,.5 L1,.5"},"╇":{1:"M.5,.5 L.5,1",3:"M.5,.5 L.5,0 M0,.5 L1,.5"},"╈":{1:"M.5,.5 L.5,0",3:"M0,.5 L1,.5 M.5,.5 L.5,1"},"╉":{1:"M.5,.5 L1,.5",3:"M.5,0 L.5,1 M.5,.5 L0,.5"},"╊":{1:"M.5,.5 L0,.5",3:"M.5,0 L.5,1 M.5,.5 L1,.5"},"╌":{1:"M.1,.5 L.4,.5 M.6,.5 L.9,.5"},"╍":{3:"M.1,.5 L.4,.5 M.6,.5 L.9,.5"},"┄":{1:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5"},"┅":{3:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5"},"┈":{1:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5"},"┉":{3:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5"},"╎":{1:"M.5,.1 L.5,.4 M.5,.6 L.5,.9"},"╏":{3:"M.5,.1 L.5,.4 M.5,.6 L.5,.9"},"┆":{1:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333"},"┇":{3:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333"},"┊":{1:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95"},"┋":{3:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95"},"╭":{1:(e,t)=>`M.5,1 L.5,${.5+t/.15*.5} C.5,${.5+t/.15*.5},.5,.5,1,.5`},"╮":{1:(e,t)=>`M.5,1 L.5,${.5+t/.15*.5} C.5,${.5+t/.15*.5},.5,.5,0,.5`},"╯":{1:(e,t)=>`M.5,0 L.5,${.5-t/.15*.5} C.5,${.5-t/.15*.5},.5,.5,0,.5`},"╰":{1:(e,t)=>`M.5,0 L.5,${.5-t/.15*.5} C.5,${.5-t/.15*.5},.5,.5,1,.5`}},Ic={"":{d:"M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655",type:0},"":{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0},"":{d:"M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82",type:0},"":{d:"M0,0 L1,.5 L0,1",type:0,rightPadding:2},"":{d:"M-1,-.5 L1,.5 L-1,1.5",type:1,leftPadding:1,rightPadding:1},"":{d:"M1,0 L0,.5 L1,1",type:0,leftPadding:2},"":{d:"M2,-.5 L0,.5 L2,1.5",type:1,leftPadding:1,rightPadding:1},"":{d:"M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0",type:0,rightPadding:1},"":{d:"M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0",type:1,rightPadding:1},"":{d:"M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0",type:0,leftPadding:1},"":{d:"M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0",type:1,leftPadding:1},"":{d:"M-.5,-.5 L1.5,1.5 L-.5,1.5",type:0},"":{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1},"":{d:"M1.5,-.5 L-.5,1.5 L1.5,1.5",type:0},"":{d:"M1.5,-.5 L-.5,1.5 L-.5,-.5",type:0},"":{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1},"":{d:"M-.5,-.5 L1.5,1.5 L1.5,-.5",type:0}};Ic[""]=Ic[""];Ic[""]=Ic[""];function PM(e,t,n,s,i,l,c,u){let h=MM[t];if(h)return DM(e,h,n,s,i,l),!0;let p=TM[t];if(p)return OM(e,p,n,s,i,l),!0;let v=IM[t];if(v)return BM(e,v,n,s,i,l,u),!0;let _=Ic[t];return _?($M(e,_,n,s,i,l,c,u),!0):!1}function DM(e,t,n,s,i,l){for(let c=0;c<t.length;c++){let u=t[c],h=i/8,p=l/8;e.fillRect(n+u.x*h,s+u.y*p,u.w*h,u.h*p)}}var _0=new Map;function OM(e,t,n,s,i,l){let c=_0.get(t);c||(c=new Map,_0.set(t,c));let u=e.fillStyle;if(typeof u!="string")throw new Error(`Unexpected fillStyle type "${u}"`);let h=c.get(u);if(!h){let p=t[0].length,v=t.length,_=e.canvas.ownerDocument.createElement("canvas");_.width=p,_.height=v;let g=$n(_.getContext("2d")),w=new ImageData(p,v),S,N,C,j;if(u.startsWith("#"))S=parseInt(u.slice(1,3),16),N=parseInt(u.slice(3,5),16),C=parseInt(u.slice(5,7),16),j=u.length>7&&parseInt(u.slice(7,9),16)||1;else if(u.startsWith("rgba"))[S,N,C,j]=u.substring(5,u.length-1).split(",").map(E=>parseFloat(E));else throw new Error(`Unexpected fillStyle color format "${u}" when drawing pattern glyph`);for(let E=0;E<v;E++)for(let R=0;R<p;R++)w.data[(E*p+R)*4]=S,w.data[(E*p+R)*4+1]=N,w.data[(E*p+R)*4+2]=C,w.data[(E*p+R)*4+3]=t[E][R]*(j*255);g.putImageData(w,0,0),h=$n(e.createPattern(_,null)),c.set(u,h)}e.fillStyle=h,e.fillRect(n,s,i,l)}function BM(e,t,n,s,i,l,c){e.strokeStyle=e.fillStyle;for(let[u,h]of Object.entries(t)){e.beginPath(),e.lineWidth=c*Number.parseInt(u);let p;if(typeof h=="function"){let v=.15/l*i;p=h(.15,v)}else p=h;for(let v of p.split(" ")){let _=v[0],g=Ik[_];if(!g){console.error(`Could not find drawing instructions for "${_}"`);continue}let w=v.substring(1).split(",");!w[0]||!w[1]||g(e,Pk(w,i,l,n,s,!0,c))}e.stroke(),e.closePath()}}function $M(e,t,n,s,i,l,c,u){let h=new Path2D;h.rect(n,s,i,l),e.clip(h),e.beginPath();let p=c/12;e.lineWidth=u*p;for(let v of t.d.split(" ")){let _=v[0],g=Ik[_];if(!g){console.error(`Could not find drawing instructions for "${_}"`);continue}let w=v.substring(1).split(",");!w[0]||!w[1]||g(e,Pk(w,i,l,n,s,!1,u,(t.leftPadding??0)*(p/2),(t.rightPadding??0)*(p/2)))}t.type===1?(e.strokeStyle=e.fillStyle,e.stroke()):e.fill(),e.closePath()}function y0(e,t,n=0){return Math.max(Math.min(e,t),n)}var Ik={C:(e,t)=>e.bezierCurveTo(t[0],t[1],t[2],t[3],t[4],t[5]),L:(e,t)=>e.lineTo(t[0],t[1]),M:(e,t)=>e.moveTo(t[0],t[1])};function Pk(e,t,n,s,i,l,c,u=0,h=0){let p=e.map(v=>parseFloat(v)||parseInt(v));if(p.length<2)throw new Error("Too few arguments for instruction");for(let v=0;v<p.length;v+=2)p[v]*=t-u*c-h*c,l&&p[v]!==0&&(p[v]=y0(Math.round(p[v]+.5)-.5,t,0)),p[v]+=s+u*c;for(let v=1;v<p.length;v+=2)p[v]*=n,l&&p[v]!==0&&(p[v]=y0(Math.round(p[v]+.5)-.5,n,0)),p[v]+=i;return p}var b0=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},w0=class{constructor(){this._data=new b0}set(e,t,n,s,i){this._data.get(e,t)||this._data.set(e,t,new b0),this._data.get(e,t).set(n,s,i)}get(e,t,n,s){var i;return(i=this._data.get(e,t))==null?void 0:i.get(n,s)}clear(){this._data.clear()}},Dk=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,n=0,s=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=i}this.clear()}},zM=class extends Dk{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},FM=class extends Dk{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},HM=!Dv&&"requestIdleCallback"in window?FM:zM,Wa=class Ok{constructor(){this.fg=0,this.bg=0,this.extended=new Bk}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Ok;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Bk=class $k{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new $k(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},UM=globalThis.performance&&typeof globalThis.performance.now=="function",WM=class zk{static create(t){return new zk(t)}constructor(t){this._now=UM&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Lr;(e=>{e.None=()=>Oi.None;function t(B,D){return _(B,()=>{},0,void 0,!0,void 0,D)}e.defer=t;function n(B){return(D,O=null,P)=>{let z=!1,A;return A=B(T=>{if(!z)return A?A.dispose():z=!0,D.call(O,T)},null,P),z&&A.dispose(),A}}e.once=n;function s(B,D,O){return p((P,z=null,A)=>B(T=>P.call(z,D(T)),null,A),O)}e.map=s;function i(B,D,O){return p((P,z=null,A)=>B(T=>{D(T),P.call(z,T)},null,A),O)}e.forEach=i;function l(B,D,O){return p((P,z=null,A)=>B(T=>D(T)&&P.call(z,T),null,A),O)}e.filter=l;function c(B){return B}e.signal=c;function u(...B){return(D,O=null,P)=>{let z=jk(...B.map(A=>A(T=>D.call(O,T))));return v(z,P)}}e.any=u;function h(B,D,O,P){let z=O;return s(B,A=>(z=D(z,A),z),P)}e.reduce=h;function p(B,D){let O,P={onWillAddFirstListener(){O=B(z.fire,z)},onDidRemoveLastListener(){O==null||O.dispose()}},z=new vn(P);return D==null||D.add(z),z.event}function v(B,D){return D instanceof Array?D.push(B):D&&D.add(B),B}function _(B,D,O=100,P=!1,z=!1,A,T){let L,H,M,U=0,ee,re={leakWarningThreshold:A,onWillAddFirstListener(){L=B(je=>{U++,H=D(H,je),P&&!M&&(oe.fire(H),H=void 0),ee=()=>{let te=H;H=void 0,M=void 0,(!P||U>1)&&oe.fire(te),U=0},typeof O=="number"?(clearTimeout(M),M=setTimeout(ee,O)):M===void 0&&(M=0,queueMicrotask(ee))})},onWillRemoveListener(){z&&U>0&&(ee==null||ee())},onDidRemoveLastListener(){ee=void 0,L.dispose()}},oe=new vn(re);return T==null||T.add(oe),oe.event}e.debounce=_;function g(B,D=0,O){return e.debounce(B,(P,z)=>P?(P.push(z),P):[z],D,void 0,!0,void 0,O)}e.accumulate=g;function w(B,D=(P,z)=>P===z,O){let P=!0,z;return l(B,A=>{let T=P||!D(A,z);return P=!1,z=A,T},O)}e.latch=w;function S(B,D,O){return[e.filter(B,D,O),e.filter(B,P=>!D(P),O)]}e.split=S;function N(B,D=!1,O=[],P){let z=O.slice(),A=B(H=>{z?z.push(H):L.fire(H)});P&&P.add(A);let T=()=>{z==null||z.forEach(H=>L.fire(H)),z=null},L=new vn({onWillAddFirstListener(){A||(A=B(H=>L.fire(H)),P&&P.add(A))},onDidAddFirstListener(){z&&(D?setTimeout(T):T())},onDidRemoveLastListener(){A&&A.dispose(),A=null}});return P&&P.add(L),L.event}e.buffer=N;function C(B,D){return(O,P,z)=>{let A=D(new E);return B(function(T){let L=A.evaluate(T);L!==j&&O.call(P,L)},void 0,z)}}e.chain=C;let j=Symbol("HaltChainable");class E{constructor(){this.steps=[]}map(D){return this.steps.push(D),this}forEach(D){return this.steps.push(O=>(D(O),O)),this}filter(D){return this.steps.push(O=>D(O)?O:j),this}reduce(D,O){let P=O;return this.steps.push(z=>(P=D(P,z),P)),this}latch(D=(O,P)=>O===P){let O=!0,P;return this.steps.push(z=>{let A=O||!D(z,P);return O=!1,P=z,A?z:j}),this}evaluate(D){for(let O of this.steps)if(D=O(D),D===j)break;return D}}function R(B,D,O=P=>P){let P=(...L)=>T.fire(O(...L)),z=()=>B.on(D,P),A=()=>B.removeListener(D,P),T=new vn({onWillAddFirstListener:z,onDidRemoveLastListener:A});return T.event}e.fromNodeEventEmitter=R;function x(B,D,O=P=>P){let P=(...L)=>T.fire(O(...L)),z=()=>B.addEventListener(D,P),A=()=>B.removeEventListener(D,P),T=new vn({onWillAddFirstListener:z,onDidRemoveLastListener:A});return T.event}e.fromDOMEventEmitter=x;function W(B){return new Promise(D=>n(B)(D))}e.toPromise=W;function $(B){let D=new vn;return B.then(O=>{D.fire(O)},()=>{D.fire(void 0)}).finally(()=>{D.dispose()}),D.event}e.fromPromise=$;function Y(B,D){return B(O=>D.fire(O))}e.forward=Y;function q(B,D,O){return D(O),B(P=>D(P))}e.runAndSubscribe=q;class K{constructor(D,O){this._observable=D,this._counter=0,this._hasChanged=!1;let P={onWillAddFirstListener:()=>{D.addObserver(this)},onDidRemoveLastListener:()=>{D.removeObserver(this)}};this.emitter=new vn(P),O&&O.add(this.emitter)}beginUpdate(D){this._counter++}handlePossibleChange(D){}handleChange(D,O){this._hasChanged=!0}endUpdate(D){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function se(B,D){return new K(B,D).emitter.event}e.fromObservable=se;function V(B){return(D,O,P)=>{let z=0,A=!1,T={beginUpdate(){z++},endUpdate(){z--,z===0&&(B.reportChanges(),A&&(A=!1,D.call(O)))},handlePossibleChange(){},handleChange(){A=!0}};B.addObserver(T),B.reportChanges();let L={dispose(){B.removeObserver(T)}};return P instanceof Ga?P.add(L):Array.isArray(P)&&P.push(L),L}}e.fromObservableLight=V})(Lr||(Lr={}));var Sg=class xg{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${xg._idPool++}`,xg.all.add(this)}start(t){this._stopWatch=new WM,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Sg.all=new Set,Sg._idPool=0;var qM=Sg,KM=-1,Fk=class Hk{constructor(t,n,s=(Hk._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,n){let s=this.threshold;if(s<=0||n<s)return;this._stacks||(this._stacks=new Map);let i=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,i+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=s*.5;let[l,c]=this.getMostFrequentStack(),u=`[${this.name}] potential listener LEAK detected, having ${n} listeners already. MOST frequent listener (${c}):`;console.warn(u),console.warn(l);let h=new YM(u,l);this._errorHandler(h)}return()=>{let l=this._stacks.get(t.value)||0;this._stacks.set(t.value,l-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[s,i]of this._stacks)(!t||n<i)&&(t=[s,i],n=i);return t}};Fk._idPool=1;var VM=Fk,GM=class Uk{constructor(t){this.value=t}static create(){let t=new Error;return new Uk(t.stack??"")}print(){console.warn(this.value.split(`
93
+ `).slice(2).join(`
94
+ `))}},YM=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},XM=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},JM=0,Ep=class{constructor(e){this.value=e,this.id=JM++}},QM=2,ZM,vn=class{constructor(e){var t,n,s,i;this._size=0,this._options=e,this._leakageMon=(t=this._options)!=null&&t.leakWarningThreshold?new VM((e==null?void 0:e.onListenerError)??kp,((n=this._options)==null?void 0:n.leakWarningThreshold)??KM):void 0,this._perfMon=(s=this._options)!=null&&s._profName?new qM(this._options._profName):void 0,this._deliveryQueue=(i=this._options)==null?void 0:i.deliveryQueue}dispose(){var e,t,n,s;this._disposed||(this._disposed=!0,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(n=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null||n.call(t),(s=this._leakageMon)==null||s.dispose())}get event(){return this._event??(this._event=(e,t,n)=>{var c,u,h,p,v;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let _=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(_);let g=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],w=new XM(`${_}. HINT: Stack shows most frequent listener (${g[1]}-times)`,g[0]);return(((c=this._options)==null?void 0:c.onListenerError)||kp)(w),Oi.None}if(this._disposed)return Oi.None;t&&(e=e.bind(t));let s=new Ep(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(s.stack=GM.create(),i=this._leakageMon.check(s.stack,this._size+1)),this._listeners?this._listeners instanceof Ep?(this._deliveryQueue??(this._deliveryQueue=new eT),this._listeners=[this._listeners,s]):this._listeners.push(s):((h=(u=this._options)==null?void 0:u.onWillAddFirstListener)==null||h.call(u,this),this._listeners=s,(v=(p=this._options)==null?void 0:p.onDidAddFirstListener)==null||v.call(p,this)),this._size++;let l=As(()=>{i==null||i(),this._removeListener(s)});return n instanceof Ga?n.add(l):Array.isArray(n)&&n.push(l),l}),this._event}_removeListener(e){var i,l,c,u;if((l=(i=this._options)==null?void 0:i.onWillRemoveListener)==null||l.call(i,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(u=(c=this._options)==null?void 0:c.onDidRemoveLastListener)==null||u.call(c,this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let s=this._deliveryQueue.current===this;if(this._size*QM<=t.length){let h=0;for(let p=0;p<t.length;p++)t[p]?t[h++]=t[p]:s&&(this._deliveryQueue.end--,h<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=h}}_deliver(e,t){var s;if(!e)return;let n=((s=this._options)==null?void 0:s.onListenerError)||kp;if(!n){e.value(t);return}try{e.value(t)}catch(i){n(i)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,n,s,i;if((t=this._deliveryQueue)!=null&&t.current&&(this._deliverQueue(this._deliveryQueue),(n=this._perfMon)==null||n.stop()),(s=this._perfMon)==null||s.start(this._size),this._listeners)if(this._listeners instanceof Ep)this._deliver(this._listeners,e);else{let l=this._deliveryQueue;l.enqueue(this,e,this._listeners.length),this._deliverQueue(l)}(i=this._perfMon)==null||i.stop()}hasListeners(){return this._size>0}},eT=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},S0={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}},Zl=2,ec,no=class Fa{constructor(t,n,s){this._document=t,this._config=n,this._unicodeService=s,this._didWarmUp=!1,this._cacheMap=new w0,this._cacheMapCombined=new w0,this._pages=[],this._activePages=[],this._workBoundingBox={top:0,left:0,bottom:0,right:0},this._workAttributeData=new Wa,this._textureSize=512,this._onAddTextureAtlasCanvas=new vn,this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=new vn,this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._requestClearModel=!1,this._createNewPage(),this._tmpCanvas=Wk(t,this._config.deviceCellWidth*4+Zl*2,this._config.deviceCellHeight+Zl*2),this._tmpCtx=$n(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let t of this.pages)t.canvas.remove();this._onAddTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){let t=new HM;for(let n=33;n<126;n++)t.enqueue(()=>{if(!this._cacheMap.get(n,0,0,0)){let s=this._drawToCache(n,0,0,0,!1,void 0);this._cacheMap.set(n,0,0,0,s)}})}beginFrame(){return this._requestClearModel}clearTexture(){if(!(this._pages[0].currentRow.x===0&&this._pages[0].currentRow.y===0)){for(let t of this._pages)t.clear();this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1}}_createNewPage(){if(Fa.maxAtlasPages&&this._pages.length>=Math.max(4,Fa.maxAtlasPages)){let n=this._pages.filter(p=>p.canvas.width*2<=(Fa.maxTextureSize||4096)).sort((p,v)=>v.canvas.width!==p.canvas.width?v.canvas.width-p.canvas.width:v.percentageUsed-p.percentageUsed),s=-1,i=0;for(let p=0;p<n.length;p++)if(n[p].canvas.width!==i)s=p,i=n[p].canvas.width;else if(p-s===3)break;let l=n.slice(s,s+4),c=l.map(p=>p.glyphs[0].texturePage).sort((p,v)=>p>v?1:-1),u=this.pages.length-l.length,h=this._mergePages(l,u);h.version++;for(let p=c.length-1;p>=0;p--)this._deletePage(c[p]);this.pages.push(h),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(h.canvas)}let t=new Np(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}_mergePages(t,n){let s=t[0].canvas.width*2,i=new Np(this._document,s,t);for(let[l,c]of t.entries()){let u=l*c.canvas.width%s,h=Math.floor(l/2)*c.canvas.height;i.ctx.drawImage(c.canvas,u,h);for(let v of c.glyphs)v.texturePage=n,v.sizeClipSpace.x=v.size.x/s,v.sizeClipSpace.y=v.size.y/s,v.texturePosition.x+=u,v.texturePosition.y+=h,v.texturePositionClipSpace.x=v.texturePosition.x/s,v.texturePositionClipSpace.y=v.texturePosition.y/s;this._onRemoveTextureAtlasCanvas.fire(c.canvas);let p=this._activePages.indexOf(c);p!==-1&&this._activePages.splice(p,1)}return i}_deletePage(t){this._pages.splice(t,1);for(let n=t;n<this._pages.length;n++){let s=this._pages[n];for(let i of s.glyphs)i.texturePage--;s.version++}}getRasterizedGlyphCombinedChar(t,n,s,i,l,c){return this._getFromCacheMap(this._cacheMapCombined,t,n,s,i,l,c)}getRasterizedGlyph(t,n,s,i,l,c){return this._getFromCacheMap(this._cacheMap,t,n,s,i,l,c)}_getFromCacheMap(t,n,s,i,l,c,u){return ec=t.get(n,s,i,l),ec||(ec=this._drawToCache(n,s,i,l,c,u),t.set(n,s,i,l,ec)),ec}_getColorFromAnsiIndex(t){if(t>=this._config.colors.ansi.length)throw new Error("No color found for idx "+t);return this._config.colors.ansi[t]}_getBackgroundColor(t,n,s,i){if(this._config.allowTransparency)return gi;let l;switch(t){case 16777216:case 33554432:l=this._getColorFromAnsiIndex(n);break;case 50331648:let c=Wa.toColorRGB(n);l=$s.toColor(c[0],c[1],c[2]);break;case 0:default:s?l=yc.opaque(this._config.colors.foreground):l=this._config.colors.background;break}return this._config.allowTransparency||(l=yc.opaque(l)),l}_getForegroundColor(t,n,s,i,l,c,u,h,p,v){let _=this._getMinimumContrastColor(t,n,s,i,l,c,u,p,h,v);if(_)return _;let g;switch(l){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&p&&c<8&&(c+=8),g=this._getColorFromAnsiIndex(c);break;case 50331648:let w=Wa.toColorRGB(c);g=$s.toColor(w[0],w[1],w[2]);break;case 0:default:u?g=this._config.colors.background:g=this._config.colors.foreground}return this._config.allowTransparency&&(g=yc.opaque(g)),h&&(g=yc.multiplyOpacity(g,AM)),g}_resolveBackgroundRgba(t,n,s){switch(t){case 16777216:case 33554432:return this._getColorFromAnsiIndex(n).rgba;case 50331648:return n<<8;case 0:default:return s?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(t,n,s,i){switch(t){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&i&&n<8&&(n+=8),this._getColorFromAnsiIndex(n).rgba;case 50331648:return n<<8;case 0:default:return s?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(t,n,s,i,l,c,u,h,p,v){if(this._config.minimumContrastRatio===1||v)return;let _=this._getContrastCache(p),g=_.getColor(t,i);if(g!==void 0)return g||void 0;let w=this._resolveBackgroundRgba(n,s,u),S=this._resolveForegroundRgba(l,c,u,h),N=Ko.ensureContrastRatio(w,S,this._config.minimumContrastRatio/(p?2:1));if(!N){_.setColor(t,i,null);return}let C=$s.toColor(N>>24&255,N>>16&255,N>>8&255);return _.setColor(t,i,C),C}_getContrastCache(t){return t?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(t,n,s,i,l,c){let u=typeof t=="number"?String.fromCharCode(t):t;c&&this._tmpCanvas.parentElement!==c&&(this._tmpCanvas.style.display="none",c.append(this._tmpCanvas));let h=Math.min(this._config.deviceCellWidth*Math.max(u.length,2)+Zl*2,this._config.deviceMaxTextureSize);this._tmpCanvas.width<h&&(this._tmpCanvas.width=h);let p=Math.min(this._config.deviceCellHeight+Zl*4,this._textureSize);if(this._tmpCanvas.height<p&&(this._tmpCanvas.height=p),this._tmpCtx.save(),this._workAttributeData.fg=s,this._workAttributeData.bg=n,this._workAttributeData.extended.ext=i,!!this._workAttributeData.isInvisible())return S0;let v=!!this._workAttributeData.isBold(),_=!!this._workAttributeData.isInverse(),g=!!this._workAttributeData.isDim(),w=!!this._workAttributeData.isItalic(),S=!!this._workAttributeData.isUnderline(),N=!!this._workAttributeData.isStrikethrough(),C=!!this._workAttributeData.isOverline(),j=this._workAttributeData.getFgColor(),E=this._workAttributeData.getFgColorMode(),R=this._workAttributeData.getBgColor(),x=this._workAttributeData.getBgColorMode();if(_){let H=j;j=R,R=H;let M=E;E=x,x=M}let W=this._getBackgroundColor(x,R,_,g);this._tmpCtx.globalCompositeOperation="copy",this._tmpCtx.fillStyle=W.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.globalCompositeOperation="source-over";let $=v?this._config.fontWeightBold:this._config.fontWeight,Y=w?"italic":"";this._tmpCtx.font=`${Y} ${$} ${this._config.fontSize*this._config.devicePixelRatio}px ${this._config.fontFamily}`,this._tmpCtx.textBaseline=Tk;let q=u.length===1&&Ov(u.charCodeAt(0)),K=u.length===1&&xM(u.charCodeAt(0)),se=this._getForegroundColor(n,x,R,s,E,j,_,g,v,Mk(u.charCodeAt(0)));this._tmpCtx.fillStyle=se.css;let V=K?0:Zl*2,B=!1;this._config.customGlyphs!==!1&&(B=PM(this._tmpCtx,u,V,V,this._config.deviceCellWidth,this._config.deviceCellHeight,this._config.fontSize,this._config.devicePixelRatio));let D=!q,O;if(typeof t=="number"?O=this._unicodeService.wcwidth(t):O=this._unicodeService.getStringCellWidth(t),S){this._tmpCtx.save();let H=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),M=H%2===1?.5:0;if(this._tmpCtx.lineWidth=H,this._workAttributeData.isUnderlineColorDefault())this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle;else if(this._workAttributeData.isUnderlineColorRGB())D=!1,this._tmpCtx.strokeStyle=`rgb(${Wa.toColorRGB(this._workAttributeData.getUnderlineColor()).join(",")})`;else{D=!1;let te=this._workAttributeData.getUnderlineColor();this._config.drawBoldTextInBrightColors&&this._workAttributeData.isBold()&&te<8&&(te+=8),this._tmpCtx.strokeStyle=this._getColorFromAnsiIndex(te).css}this._tmpCtx.beginPath();let U=V,ee=Math.ceil(V+this._config.deviceCharHeight)-M-(l?H*2:0),re=ee+H,oe=ee+H*2,je=this._workAttributeData.getUnderlineVariantOffset();for(let te=0;te<O;te++){this._tmpCtx.save();let ie=U+te*this._config.deviceCellWidth,pe=U+(te+1)*this._config.deviceCellWidth,xe=ie+this._config.deviceCellWidth/2;switch(this._workAttributeData.extended.underlineStyle){case 2:this._tmpCtx.moveTo(ie,ee),this._tmpCtx.lineTo(pe,ee),this._tmpCtx.moveTo(ie,oe),this._tmpCtx.lineTo(pe,oe);break;case 3:let Be=H<=1?oe:Math.ceil(V+this._config.deviceCharHeight-H/2)-M,Te=H<=1?ee:Math.ceil(V+this._config.deviceCharHeight+H/2)-M,Me=new Path2D;Me.rect(ie,ee,this._config.deviceCellWidth,oe-ee),this._tmpCtx.clip(Me),this._tmpCtx.moveTo(ie-this._config.deviceCellWidth/2,re),this._tmpCtx.bezierCurveTo(ie-this._config.deviceCellWidth/2,Te,ie,Te,ie,re),this._tmpCtx.bezierCurveTo(ie,Be,xe,Be,xe,re),this._tmpCtx.bezierCurveTo(xe,Te,pe,Te,pe,re),this._tmpCtx.bezierCurveTo(pe,Be,pe+this._config.deviceCellWidth/2,Be,pe+this._config.deviceCellWidth/2,re);break;case 4:let J=je===0?0:je>=H?H*2-je:H-je;je>=H||J===0?(this._tmpCtx.setLineDash([Math.round(H),Math.round(H)]),this._tmpCtx.moveTo(ie+J,ee),this._tmpCtx.lineTo(pe,ee)):(this._tmpCtx.setLineDash([Math.round(H),Math.round(H)]),this._tmpCtx.moveTo(ie,ee),this._tmpCtx.lineTo(ie+J,ee),this._tmpCtx.moveTo(ie+J+H,ee),this._tmpCtx.lineTo(pe,ee)),je=LM(pe-ie,H,je);break;case 5:let le=.6,Q=.3,ge=pe-ie,Z=Math.floor(le*ge),fe=Math.floor(Q*ge),ve=ge-Z-fe;this._tmpCtx.setLineDash([Z,fe,ve]),this._tmpCtx.moveTo(ie,ee),this._tmpCtx.lineTo(pe,ee);break;case 1:default:this._tmpCtx.moveTo(ie,ee),this._tmpCtx.lineTo(pe,ee);break}this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!B&&this._config.fontSize>=12&&!this._config.allowTransparency&&u!==" "){this._tmpCtx.save(),this._tmpCtx.textBaseline="alphabetic";let te=this._tmpCtx.measureText(u);if(this._tmpCtx.restore(),"actualBoundingBoxDescent"in te&&te.actualBoundingBoxDescent>0){this._tmpCtx.save();let ie=new Path2D;ie.rect(U,ee-Math.ceil(H/2),this._config.deviceCellWidth*O,oe-ee+Math.ceil(H/2)),this._tmpCtx.clip(ie),this._tmpCtx.lineWidth=this._config.devicePixelRatio*3,this._tmpCtx.strokeStyle=W.css,this._tmpCtx.strokeText(u,V,V+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(C){let H=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),M=H%2===1?.5:0;this._tmpCtx.lineWidth=H,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(V,V+M),this._tmpCtx.lineTo(V+this._config.deviceCharWidth*O,V+M),this._tmpCtx.stroke()}if(B||this._tmpCtx.fillText(u,V,V+this._config.deviceCharHeight),u==="_"&&!this._config.allowTransparency){let H=jp(this._tmpCtx.getImageData(V,V,this._config.deviceCellWidth,this._config.deviceCellHeight),W,se,D);if(H)for(let M=1;M<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=W.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(u,V,V+this._config.deviceCharHeight-M),H=jp(this._tmpCtx.getImageData(V,V,this._config.deviceCellWidth,this._config.deviceCellHeight),W,se,D),!!H);M++);}if(N){let H=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),M=this._tmpCtx.lineWidth%2===1?.5:0;this._tmpCtx.lineWidth=H,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(V,V+Math.floor(this._config.deviceCharHeight/2)-M),this._tmpCtx.lineTo(V+this._config.deviceCharWidth*O,V+Math.floor(this._config.deviceCharHeight/2)-M),this._tmpCtx.stroke()}this._tmpCtx.restore();let P=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height),z;if(this._config.allowTransparency?z=tT(P):z=jp(P,W,se,D),z)return S0;let A=this._findGlyphBoundingBox(P,this._workBoundingBox,h,K,B,V),T,L;for(;;){if(this._activePages.length===0){let H=this._createNewPage();T=H,L=H.currentRow,L.height=A.size.y;break}T=this._activePages[this._activePages.length-1],L=T.currentRow;for(let H of this._activePages)A.size.y<=H.currentRow.height&&(T=H,L=H.currentRow);for(let H=this._activePages.length-1;H>=0;H--)for(let M of this._activePages[H].fixedRows)M.height<=L.height&&A.size.y<=M.height&&(T=this._activePages[H],L=M);if(A.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new Np(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),T=this._overflowSizePage,L=this._overflowSizePage.currentRow,L.x+A.size.x>=T.canvas.width&&(L.x=0,L.y+=L.height,L.height=0);break}if(L.y+A.size.y>=T.canvas.height||L.height>A.size.y+2){let H=!1;if(T.currentRow.y+T.currentRow.height+A.size.y>=T.canvas.height){let M;for(let U of this._activePages)if(U.currentRow.y+U.currentRow.height+A.size.y<U.canvas.height){M=U;break}if(M)T=M;else if(Fa.maxAtlasPages&&this._pages.length>=Fa.maxAtlasPages&&L.y+A.size.y<=T.canvas.height&&L.height>=A.size.y&&L.x+A.size.x<=T.canvas.width)H=!0;else{let U=this._createNewPage();T=U,L=U.currentRow,L.height=A.size.y,H=!0}}H||(T.currentRow.height>0&&T.fixedRows.push(T.currentRow),L={x:0,y:T.currentRow.y+T.currentRow.height,height:A.size.y},T.fixedRows.push(L),T.currentRow={x:0,y:L.y+L.height,height:0})}if(L.x+A.size.x<=T.canvas.width)break;L===T.currentRow?(L.x=0,L.y+=L.height,L.height=0):T.fixedRows.splice(T.fixedRows.indexOf(L),1)}return A.texturePage=this._pages.indexOf(T),A.texturePosition.x=L.x,A.texturePosition.y=L.y,A.texturePositionClipSpace.x=L.x/T.canvas.width,A.texturePositionClipSpace.y=L.y/T.canvas.height,A.sizeClipSpace.x/=T.canvas.width,A.sizeClipSpace.y/=T.canvas.height,L.height=Math.max(L.height,A.size.y),L.x+=A.size.x,T.ctx.putImageData(P,A.texturePosition.x-this._workBoundingBox.left,A.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,A.size.x,A.size.y),T.addGlyph(A),T.version++,A}_findGlyphBoundingBox(t,n,s,i,l,c){n.top=0;let u=i?this._config.deviceCellHeight:this._tmpCanvas.height,h=i?this._config.deviceCellWidth:s,p=!1;for(let v=0;v<u;v++){for(let _=0;_<h;_++){let g=v*this._tmpCanvas.width*4+_*4+3;if(t.data[g]!==0){n.top=v,p=!0;break}}if(p)break}n.left=0,p=!1;for(let v=0;v<c+h;v++){for(let _=0;_<u;_++){let g=_*this._tmpCanvas.width*4+v*4+3;if(t.data[g]!==0){n.left=v,p=!0;break}}if(p)break}n.right=h,p=!1;for(let v=c+h-1;v>=c;v--){for(let _=0;_<u;_++){let g=_*this._tmpCanvas.width*4+v*4+3;if(t.data[g]!==0){n.right=v,p=!0;break}}if(p)break}n.bottom=u,p=!1;for(let v=u-1;v>=0;v--){for(let _=0;_<h;_++){let g=v*this._tmpCanvas.width*4+_*4+3;if(t.data[g]!==0){n.bottom=v,p=!0;break}}if(p)break}return{texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},size:{x:n.right-n.left+1,y:n.bottom-n.top+1},sizeClipSpace:{x:n.right-n.left+1,y:n.bottom-n.top+1},offset:{x:-n.left+c+(i||l?Math.floor((this._config.deviceCellWidth-this._config.deviceCharWidth)/2):0),y:-n.top+c+(i||l?this._config.lineHeight===1?0:Math.round((this._config.deviceCellHeight-this._config.deviceCharHeight)/2):0)}}}},Np=class{constructor(e,t,n){if(this._usedPixels=0,this._glyphs=[],this.version=0,this.currentRow={x:0,y:0,height:0},this.fixedRows=[],n)for(let s of n)this._glyphs.push(...s.glyphs),this._usedPixels+=s._usedPixels;this.canvas=Wk(e,t,t),this.ctx=$n(this.canvas.getContext("2d",{alpha:!0}))}get percentageUsed(){return this._usedPixels/(this.canvas.width*this.canvas.height)}get glyphs(){return this._glyphs}addGlyph(e){this._glyphs.push(e),this._usedPixels+=e.size.x*e.size.y}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.currentRow.x=0,this.currentRow.y=0,this.currentRow.height=0,this.fixedRows.length=0,this.version++}};function jp(e,t,n,s){let i=t.rgba>>>24,l=t.rgba>>>16&255,c=t.rgba>>>8&255,u=n.rgba>>>24,h=n.rgba>>>16&255,p=n.rgba>>>8&255,v=Math.floor((Math.abs(i-u)+Math.abs(l-h)+Math.abs(c-p))/12),_=!0;for(let g=0;g<e.data.length;g+=4)e.data[g]===i&&e.data[g+1]===l&&e.data[g+2]===c||s&&Math.abs(e.data[g]-i)+Math.abs(e.data[g+1]-l)+Math.abs(e.data[g+2]-c)<v?e.data[g+3]=0:_=!1;return _}function tT(e){for(let t=0;t<e.data.length;t+=4)if(e.data[t+3]>0)return!1;return!0}function Wk(e,t,n){let s=e.createElement("canvas");return s.width=t,s.height=n,s}function nT(e,t,n,s,i,l,c,u){let h={foreground:l.foreground,background:l.background,cursor:gi,cursorAccent:gi,selectionForeground:gi,selectionBackgroundTransparent:gi,selectionBackgroundOpaque:gi,selectionInactiveBackgroundTransparent:gi,selectionInactiveBackgroundOpaque:gi,overviewRulerBorder:gi,scrollbarSliderBackground:gi,scrollbarSliderHoverBackground:gi,scrollbarSliderActiveBackground:gi,ansi:l.ansi.slice(),contrastCache:l.contrastCache,halfContrastCache:l.halfContrastCache};return{customGlyphs:i.customGlyphs,devicePixelRatio:c,deviceMaxTextureSize:u,letterSpacing:i.letterSpacing,lineHeight:i.lineHeight,deviceCellWidth:e,deviceCellHeight:t,deviceCharWidth:n,deviceCharHeight:s,fontFamily:i.fontFamily,fontSize:i.fontSize,fontWeight:i.fontWeight,fontWeightBold:i.fontWeightBold,allowTransparency:i.allowTransparency,drawBoldTextInBrightColors:i.drawBoldTextInBrightColors,minimumContrastRatio:i.minimumContrastRatio,colors:h}}function x0(e,t){for(let n=0;n<e.colors.ansi.length;n++)if(e.colors.ansi[n].rgba!==t.colors.ansi[n].rgba)return!1;return e.devicePixelRatio===t.devicePixelRatio&&e.customGlyphs===t.customGlyphs&&e.lineHeight===t.lineHeight&&e.letterSpacing===t.letterSpacing&&e.fontFamily===t.fontFamily&&e.fontSize===t.fontSize&&e.fontWeight===t.fontWeight&&e.fontWeightBold===t.fontWeightBold&&e.allowTransparency===t.allowTransparency&&e.deviceCharWidth===t.deviceCharWidth&&e.deviceCharHeight===t.deviceCharHeight&&e.drawBoldTextInBrightColors===t.drawBoldTextInBrightColors&&e.minimumContrastRatio===t.minimumContrastRatio&&e.colors.foreground.rgba===t.colors.foreground.rgba&&e.colors.background.rgba===t.colors.background.rgba}function sT(e){return(e&50331648)===16777216||(e&50331648)===33554432}var yi=[];function qk(e,t,n,s,i,l,c,u,h){let p=nT(s,i,l,c,t,n,u,h);for(let g=0;g<yi.length;g++){let w=yi[g],S=w.ownedBy.indexOf(e);if(S>=0){if(x0(w.config,p))return w.atlas;w.ownedBy.length===1?(w.atlas.dispose(),yi.splice(g,1)):w.ownedBy.splice(S,1);break}}for(let g=0;g<yi.length;g++){let w=yi[g];if(x0(w.config,p))return w.ownedBy.push(e),w.atlas}let v=e._core,_={atlas:new no(document,p,v.unicodeService),config:p,ownedBy:[e]};return yi.push(_),_.atlas}function k0(e){for(let t=0;t<yi.length;t++){let n=yi[t].ownedBy.indexOf(e);if(n!==-1){yi[t].ownedBy.length===1?(yi[t].atlas.dispose(),yi.splice(t,1)):yi[t].ownedBy.splice(n,1);break}}}var dd=600,iT=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this.isCursorVisible=!0,this._coreBrowserService.isFocused&&this._restartInterval()}get isPaused(){return!(this._blinkStartTimeout||this._blinkInterval)}dispose(){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}restartBlinkAnimation(){this.isPaused||(this._animationTimeRestarted=Date.now(),this.isCursorVisible=!0,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})))}_restartInterval(e=dd){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){let t=dd-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,t>0){this._restartInterval(t);return}}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){let t=dd-(Date.now()-this._animationTimeRestarted);this._animationTimeRestarted=void 0,this._restartInterval(t);return}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},dd)},e)}pause(){this.isCursorVisible=!0,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this.restartBlinkAnimation()}};function C0(e,t,n){let s=new t.ResizeObserver(i=>{let l=i.find(h=>h.target===e);if(!l)return;if(!("devicePixelContentBoxSize"in l)){s==null||s.disconnect(),s=void 0;return}let c=l.devicePixelContentBoxSize[0].inlineSize,u=l.devicePixelContentBoxSize[0].blockSize;c>0&&u>0&&n(c,u)});try{s.observe(e,{box:["device-pixel-content-box"]})}catch{s.disconnect(),s=void 0}return As(()=>s==null?void 0:s.disconnect())}function rT(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}var E0=class Kk extends Wa{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Bk,this.combinedData=""}static fromCharData(t){let n=new Kk;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?rT(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let i=t[1].charCodeAt(1);56320<=i&&i<=57343?this.content=(s-55296)*1024+i-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Vk=new Float32Array([2,0,0,0,0,-2,0,0,0,0,1,0,-1,1,0,1]);function Gk(e,t,n){let s=$n(e.createProgram());if(e.attachShader(s,$n(N0(e,e.VERTEX_SHADER,t))),e.attachShader(s,$n(N0(e,e.FRAGMENT_SHADER,n))),e.linkProgram(s),e.getProgramParameter(s,e.LINK_STATUS))return s;console.error(e.getProgramInfoLog(s)),e.deleteProgram(s)}function N0(e,t,n){let s=$n(e.createShader(t));if(e.shaderSource(s,n),e.compileShader(s),e.getShaderParameter(s,e.COMPILE_STATUS))return s;console.error(e.getShaderInfoLog(s)),e.deleteShader(s)}function oT(e,t){let n=Math.min(e.length*2,t),s=new Float32Array(n);for(let i=0;i<e.length;i++)s[i]=e[i];return s}var aT=class{constructor(e){this.texture=e,this.version=-1}},lT=`#version 300 es
95
+ layout (location = 0) in vec2 a_unitquad;
96
+ layout (location = 1) in vec2 a_cellpos;
97
+ layout (location = 2) in vec2 a_offset;
98
+ layout (location = 3) in vec2 a_size;
99
+ layout (location = 4) in float a_texpage;
100
+ layout (location = 5) in vec2 a_texcoord;
101
+ layout (location = 6) in vec2 a_texsize;
102
+
103
+ uniform mat4 u_projection;
104
+ uniform vec2 u_resolution;
105
+
106
+ out vec2 v_texcoord;
107
+ flat out int v_texpage;
108
+
109
+ void main() {
110
+ vec2 zeroToOne = (a_offset / u_resolution) + a_cellpos + (a_unitquad * a_size);
111
+ gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);
112
+ v_texpage = int(a_texpage);
113
+ v_texcoord = a_texcoord + a_unitquad * a_texsize;
114
+ }`;function cT(e){let t="";for(let n=1;n<e;n++)t+=` else if (v_texpage == ${n}) { outColor = texture(u_texture[${n}], v_texcoord); }`;return`#version 300 es
115
+ precision lowp float;
116
+
117
+ in vec2 v_texcoord;
118
+ flat in int v_texpage;
119
+
120
+ uniform sampler2D u_texture[${e}];
121
+
122
+ out vec4 outColor;
123
+
124
+ void main() {
125
+ if (v_texpage == 0) {
126
+ outColor = texture(u_texture[0], v_texcoord);
127
+ } ${t}
128
+ }`}var so=11,Ia=so*Float32Array.BYTES_PER_ELEMENT,uT=2,Ln=0,mn,Lp=0,tc=0,dT=class extends Oi{constructor(e,t,n,s){super(),this._terminal=e,this._gl=t,this._dimensions=n,this._optionsService=s,this._activeBuffer=0,this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};let i=this._gl;no.maxAtlasPages===void 0&&(no.maxAtlasPages=Math.min(32,$n(i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS))),no.maxTextureSize=$n(i.getParameter(i.MAX_TEXTURE_SIZE))),this._program=$n(Gk(i,lT,cT(no.maxAtlasPages))),this._register(As(()=>i.deleteProgram(this._program))),this._projectionLocation=$n(i.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=$n(i.getUniformLocation(this._program,"u_resolution")),this._textureLocation=$n(i.getUniformLocation(this._program,"u_texture")),this._vertexArrayObject=i.createVertexArray(),i.bindVertexArray(this._vertexArrayObject);let l=new Float32Array([0,0,1,0,0,1,1,1]),c=i.createBuffer();this._register(As(()=>i.deleteBuffer(c))),i.bindBuffer(i.ARRAY_BUFFER,c),i.bufferData(i.ARRAY_BUFFER,l,i.STATIC_DRAW),i.enableVertexAttribArray(0),i.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);let u=new Uint8Array([0,1,2,3]),h=i.createBuffer();this._register(As(()=>i.deleteBuffer(h))),i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,h),i.bufferData(i.ELEMENT_ARRAY_BUFFER,u,i.STATIC_DRAW),this._attributesBuffer=$n(i.createBuffer()),this._register(As(()=>i.deleteBuffer(this._attributesBuffer))),i.bindBuffer(i.ARRAY_BUFFER,this._attributesBuffer),i.enableVertexAttribArray(2),i.vertexAttribPointer(2,2,i.FLOAT,!1,Ia,0),i.vertexAttribDivisor(2,1),i.enableVertexAttribArray(3),i.vertexAttribPointer(3,2,i.FLOAT,!1,Ia,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(3,1),i.enableVertexAttribArray(4),i.vertexAttribPointer(4,1,i.FLOAT,!1,Ia,4*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(4,1),i.enableVertexAttribArray(5),i.vertexAttribPointer(5,2,i.FLOAT,!1,Ia,5*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(5,1),i.enableVertexAttribArray(6),i.vertexAttribPointer(6,2,i.FLOAT,!1,Ia,7*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(6,1),i.enableVertexAttribArray(1),i.vertexAttribPointer(1,2,i.FLOAT,!1,Ia,9*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(1,1),i.useProgram(this._program);let p=new Int32Array(no.maxAtlasPages);for(let v=0;v<no.maxAtlasPages;v++)p[v]=v;i.uniform1iv(this._textureLocation,p),i.uniformMatrix4fv(this._projectionLocation,!1,Vk),this._atlasTextures=[];for(let v=0;v<no.maxAtlasPages;v++){let _=new aT($n(i.createTexture()));this._register(As(()=>i.deleteTexture(_.texture))),i.activeTexture(i.TEXTURE0+v),i.bindTexture(i.TEXTURE_2D,_.texture),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[v]=_}i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return this._atlas?this._atlas.beginFrame():!0}updateCell(e,t,n,s,i,l,c,u,h){this._updateCell(this._vertices.attributes,e,t,n,s,i,l,c,u,h)}_updateCell(e,t,n,s,i,l,c,u,h,p){if(Ln=(n*this._terminal.cols+t)*so,s===0||s===void 0){e.fill(0,Ln,Ln+so-1-uT);return}this._atlas&&(u&&u.length>1?mn=this._atlas.getRasterizedGlyphCombinedChar(u,i,l,c,!1,this._terminal.element):mn=this._atlas.getRasterizedGlyph(s,i,l,c,!1,this._terminal.element),Lp=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),i!==p&&mn.offset.x>Lp?(tc=mn.offset.x-Lp,e[Ln]=-(mn.offset.x-tc)+this._dimensions.device.char.left,e[Ln+1]=-mn.offset.y+this._dimensions.device.char.top,e[Ln+2]=(mn.size.x-tc)/this._dimensions.device.canvas.width,e[Ln+3]=mn.size.y/this._dimensions.device.canvas.height,e[Ln+4]=mn.texturePage,e[Ln+5]=mn.texturePositionClipSpace.x+tc/this._atlas.pages[mn.texturePage].canvas.width,e[Ln+6]=mn.texturePositionClipSpace.y,e[Ln+7]=mn.sizeClipSpace.x-tc/this._atlas.pages[mn.texturePage].canvas.width,e[Ln+8]=mn.sizeClipSpace.y):(e[Ln]=-mn.offset.x+this._dimensions.device.char.left,e[Ln+1]=-mn.offset.y+this._dimensions.device.char.top,e[Ln+2]=mn.size.x/this._dimensions.device.canvas.width,e[Ln+3]=mn.size.y/this._dimensions.device.canvas.height,e[Ln+4]=mn.texturePage,e[Ln+5]=mn.texturePositionClipSpace.x,e[Ln+6]=mn.texturePositionClipSpace.y,e[Ln+7]=mn.sizeClipSpace.x,e[Ln+8]=mn.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&NM(s,h,mn.size.x,this._dimensions.device.cell.width)&&(e[Ln+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let e=this._terminal,t=e.cols*e.rows*so;this._vertices.count!==t?this._vertices.attributes=new Float32Array(t):this._vertices.attributes.fill(0);let n=0;for(;n<this._vertices.attributesBuffers.length;n++)this._vertices.count!==t?this._vertices.attributesBuffers[n]=new Float32Array(t):this._vertices.attributesBuffers[n].fill(0);this._vertices.count=t,n=0;for(let s=0;s<e.rows;s++)for(let i=0;i<e.cols;i++)this._vertices.attributes[n+9]=i/e.cols,this._vertices.attributes[n+10]=s/e.rows,n+=so}handleResize(){let e=this._gl;e.useProgram(this._program),e.viewport(0,0,e.canvas.width,e.canvas.height),e.uniform2f(this._resolutionLocation,e.canvas.width,e.canvas.height),this.clear()}render(e){if(!this._atlas)return;let t=this._gl;t.useProgram(this._program),t.bindVertexArray(this._vertexArrayObject),this._activeBuffer=(this._activeBuffer+1)%2;let n=this._vertices.attributesBuffers[this._activeBuffer],s=0;for(let i=0;i<e.lineLengths.length;i++){let l=i*this._terminal.cols*so,c=this._vertices.attributes.subarray(l,l+e.lineLengths[i]*so);n.set(c,s),s+=c.length}t.bindBuffer(t.ARRAY_BUFFER,this._attributesBuffer),t.bufferData(t.ARRAY_BUFFER,n.subarray(0,s),t.STREAM_DRAW);for(let i=0;i<this._atlas.pages.length;i++)this._atlas.pages[i].version!==this._atlasTextures[i].version&&this._bindAtlasPageTexture(t,this._atlas,i);t.drawElementsInstanced(t.TRIANGLE_STRIP,4,t.UNSIGNED_BYTE,0,s/so)}setAtlas(e){this._atlas=e;for(let t of this._atlasTextures)t.version=-1}_bindAtlasPageTexture(e,t,n){e.activeTexture(e.TEXTURE0+n),e.bindTexture(e.TEXTURE_2D,this._atlasTextures[n].texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.pages[n].canvas),e.generateMipmap(e.TEXTURE_2D),this._atlasTextures[n].version=t.pages[n].version}setDimensions(e){this._dimensions=e}},hT=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,s=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,l=t[1]-i,c=n[1]-i,u=Math.max(l,0),h=Math.min(c,e.rows-1);if(u>=e.rows||h<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=l,this.viewportEndRow=c,this.viewportCappedStartRow=u,this.viewportCappedEndRow=h,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function fT(){return new hT}var Kd=4,Rd=1,Ad=2,Rp=3,pT=2147483648,mT=class{constructor(){this.cells=new Uint32Array(0),this.lineLengths=new Uint32Array(0),this.selection=fT()}resize(e,t){let n=e*t*Kd;n!==this.cells.length&&(this.cells=new Uint32Array(n),this.lineLengths=new Uint32Array(t))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}},gT=`#version 300 es
129
+ layout (location = 0) in vec2 a_position;
130
+ layout (location = 1) in vec2 a_size;
131
+ layout (location = 2) in vec4 a_color;
132
+ layout (location = 3) in vec2 a_unitquad;
133
+
134
+ uniform mat4 u_projection;
135
+
136
+ out vec4 v_color;
137
+
138
+ void main() {
139
+ vec2 zeroToOne = a_position + (a_unitquad * a_size);
140
+ gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);
141
+ v_color = a_color;
142
+ }`,vT=`#version 300 es
143
+ precision lowp float;
144
+
145
+ in vec4 v_color;
146
+
147
+ out vec4 outColor;
148
+
149
+ void main() {
150
+ outColor = v_color;
151
+ }`,Cr=8,Ap=Cr*Float32Array.BYTES_PER_ELEMENT,_T=20*Cr,j0=class{constructor(){this.attributes=new Float32Array(_T),this.count=0}},kr=0,L0=0,R0=0,A0=0,M0=0,T0=0,I0=0,yT=class extends Oi{constructor(e,t,n,s){super(),this._terminal=e,this._gl=t,this._dimensions=n,this._themeService=s,this._vertices=new j0,this._verticesCursor=new j0;let i=this._gl;this._program=$n(Gk(i,gT,vT)),this._register(As(()=>i.deleteProgram(this._program))),this._projectionLocation=$n(i.getUniformLocation(this._program,"u_projection")),this._vertexArrayObject=i.createVertexArray(),i.bindVertexArray(this._vertexArrayObject);let l=new Float32Array([0,0,1,0,0,1,1,1]),c=i.createBuffer();this._register(As(()=>i.deleteBuffer(c))),i.bindBuffer(i.ARRAY_BUFFER,c),i.bufferData(i.ARRAY_BUFFER,l,i.STATIC_DRAW),i.enableVertexAttribArray(3),i.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);let u=new Uint8Array([0,1,2,3]),h=i.createBuffer();this._register(As(()=>i.deleteBuffer(h))),i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,h),i.bufferData(i.ELEMENT_ARRAY_BUFFER,u,i.STATIC_DRAW),this._attributesBuffer=$n(i.createBuffer()),this._register(As(()=>i.deleteBuffer(this._attributesBuffer))),i.bindBuffer(i.ARRAY_BUFFER,this._attributesBuffer),i.enableVertexAttribArray(0),i.vertexAttribPointer(0,2,i.FLOAT,!1,Ap,0),i.vertexAttribDivisor(0,1),i.enableVertexAttribArray(1),i.vertexAttribPointer(1,2,i.FLOAT,!1,Ap,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(1,1),i.enableVertexAttribArray(2),i.vertexAttribPointer(2,4,i.FLOAT,!1,Ap,4*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(2,1),this._updateCachedColors(s.colors),this._register(this._themeService.onChangeColors(p=>{this._updateCachedColors(p),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(e){let t=this._gl;t.useProgram(this._program),t.bindVertexArray(this._vertexArrayObject),t.uniformMatrix4fv(this._projectionLocation,!1,Vk),t.bindBuffer(t.ARRAY_BUFFER,this._attributesBuffer),t.bufferData(t.ARRAY_BUFFER,e.attributes,t.DYNAMIC_DRAW),t.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,t.UNSIGNED_BYTE,0,e.count)}handleResize(){this._updateViewportRectangle()}setDimensions(e){this._dimensions=e}_updateCachedColors(e){this._bgFloat=this._colorToFloat32Array(e.background),this._cursorFloat=this._colorToFloat32Array(e.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(e){let t=this._terminal,n=this._vertices,s=1,i,l,c,u,h,p,v,_,g,w,S;for(i=0;i<t.rows;i++){for(c=-1,u=0,h=0,p=!1,l=0;l<t.cols;l++)v=(i*t.cols+l)*Kd,_=e.cells[v+Rd],g=e.cells[v+Ad],w=!!(g&67108864),(_!==u||g!==h&&(p||w))&&((u!==0||p&&h!==0)&&(S=s++*Cr,this._updateRectangle(n,S,h,u,c,l,i)),c=l,u=_,h=g,p=w);(u!==0||p&&h!==0)&&(S=s++*Cr,this._updateRectangle(n,S,h,u,c,t.cols,i))}n.count=s}updateCursor(e){let t=this._verticesCursor,n=e.cursor;if(!n||n.style==="block"){t.count=0;return}let s,i=0;(n.style==="bar"||n.style==="outline")&&(s=i++*Cr,this._addRectangleFloat(t.attributes,s,n.x*this._dimensions.device.cell.width,n.y*this._dimensions.device.cell.height,n.style==="bar"?n.dpr*n.cursorWidth:n.dpr,this._dimensions.device.cell.height,this._cursorFloat)),(n.style==="underline"||n.style==="outline")&&(s=i++*Cr,this._addRectangleFloat(t.attributes,s,n.x*this._dimensions.device.cell.width,(n.y+1)*this._dimensions.device.cell.height-n.dpr,n.width*this._dimensions.device.cell.width,n.dpr,this._cursorFloat)),n.style==="outline"&&(s=i++*Cr,this._addRectangleFloat(t.attributes,s,n.x*this._dimensions.device.cell.width,n.y*this._dimensions.device.cell.height,n.width*this._dimensions.device.cell.width,n.dpr,this._cursorFloat),s=i++*Cr,this._addRectangleFloat(t.attributes,s,(n.x+n.width)*this._dimensions.device.cell.width-n.dpr,n.y*this._dimensions.device.cell.height,n.dpr,this._dimensions.device.cell.height,this._cursorFloat)),t.count=i}_updateRectangle(e,t,n,s,i,l,c){if(n&67108864)switch(n&50331648){case 16777216:case 33554432:kr=this._themeService.colors.ansi[n&255].rgba;break;case 50331648:kr=(n&16777215)<<8;break;case 0:default:kr=this._themeService.colors.foreground.rgba}else switch(s&50331648){case 16777216:case 33554432:kr=this._themeService.colors.ansi[s&255].rgba;break;case 50331648:kr=(s&16777215)<<8;break;case 0:default:kr=this._themeService.colors.background.rgba}e.attributes.length<t+4&&(e.attributes=oT(e.attributes,this._terminal.rows*this._terminal.cols*Cr)),L0=i*this._dimensions.device.cell.width,R0=c*this._dimensions.device.cell.height,A0=(kr>>24&255)/255,M0=(kr>>16&255)/255,T0=(kr>>8&255)/255,I0=1,this._addRectangle(e.attributes,t,L0,R0,(l-i)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,A0,M0,T0,I0)}_addRectangle(e,t,n,s,i,l,c,u,h,p){e[t]=n/this._dimensions.device.canvas.width,e[t+1]=s/this._dimensions.device.canvas.height,e[t+2]=i/this._dimensions.device.canvas.width,e[t+3]=l/this._dimensions.device.canvas.height,e[t+4]=c,e[t+5]=u,e[t+6]=h,e[t+7]=p}_addRectangleFloat(e,t,n,s,i,l,c){e[t]=n/this._dimensions.device.canvas.width,e[t+1]=s/this._dimensions.device.canvas.height,e[t+2]=i/this._dimensions.device.canvas.width,e[t+3]=l/this._dimensions.device.canvas.height,e[t+4]=c[0],e[t+5]=c[1],e[t+6]=c[2],e[t+7]=c[3]}_colorToFloat32Array(e){return new Float32Array([(e.rgba>>24&255)/255,(e.rgba>>16&255)/255,(e.rgba>>8&255)/255,(e.rgba&255)/255])}},bT=class extends Oi{constructor(e,t,n,s,i,l,c,u){super(),this._container=t,this._alpha=i,this._coreBrowserService=l,this._optionsService=c,this._themeService=u,this._deviceCharWidth=0,this._deviceCharHeight=0,this._deviceCellWidth=0,this._deviceCellHeight=0,this._deviceCharLeft=0,this._deviceCharTop=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add(`xterm-${n}-layer`),this._canvas.style.zIndex=s.toString(),this._initCanvas(),this._container.appendChild(this._canvas),this._register(this._themeService.onChangeColors(h=>{this._refreshCharAtlas(e,h),this.reset(e)})),this._register(As(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=$n(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(e){}handleFocus(e){}handleCursorMove(e){}handleGridChanged(e,t,n){}handleSelectionChanged(e,t,n,s=!1){}_setTransparency(e,t){if(t===this._alpha)return;let n=this._canvas;this._alpha=t,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,n),this._refreshCharAtlas(e,this._themeService.colors),this.handleGridChanged(e,0,e.rows-1)}_refreshCharAtlas(e,t){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=qk(e,this._optionsService.rawOptions,t,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(e,t){this._deviceCellWidth=t.device.cell.width,this._deviceCellHeight=t.device.cell.height,this._deviceCharWidth=t.device.char.width,this._deviceCharHeight=t.device.char.height,this._deviceCharLeft=t.device.char.left,this._deviceCharTop=t.device.char.top,this._canvas.width=t.device.canvas.width,this._canvas.height=t.device.canvas.height,this._canvas.style.width=`${t.css.canvas.width}px`,this._canvas.style.height=`${t.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(e,this._themeService.colors)}_fillBottomLineAtCells(e,t,n=1){this._ctx.fillRect(e*this._deviceCellWidth,(t+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,n*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(e,t,n,s){this._alpha?this._ctx.clearRect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,s*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,s*this._deviceCellHeight))}_fillCharTrueColor(e,t,n,s){this._ctx.font=this._getFont(e,!1,!1),this._ctx.textBaseline=Tk,this._clipCell(n,s,t.getWidth()),this._ctx.fillText(t.getChars(),n*this._deviceCellWidth+this._deviceCharLeft,s*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(e,t,n){this._ctx.beginPath(),this._ctx.rect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(e,t,n){let s=t?e.options.fontWeightBold:e.options.fontWeight;return`${n?"italic":""} ${s} ${e.options.fontSize*this._coreBrowserService.dpr}px ${e.options.fontFamily}`}},wT=class extends bT{constructor(e,t,n,s,i,l,c){super(n,e,"link",t,!0,i,l,c),this._register(s.onShowLinkUnderline(u=>this._handleShowLinkUnderline(u))),this._register(s.onHideLinkUnderline(u=>this._handleHideLinkUnderline(u)))}resize(e,t){super.resize(e,t),this._state=void 0}reset(e){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);let e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(e){if(e.fg===257?this._ctx.fillStyle=this._themeService.colors.background.css:e.fg!==void 0&&sT(e.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[e.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(let t=e.y1+1;t<e.y2;t++)this._fillBottomLineAtCells(0,t,e.cols);this._fillBottomLineAtCells(0,e.y2,e.x2)}this._state=e}_handleHideLinkUnderline(e){this._clearCurrentLink()}},Ho=typeof window=="object"?window:globalThis,kg=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new vn,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new vn,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let s=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let s=this.getWindowId(n);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};kg.INSTANCE=new kg;var Yk=kg;function ST(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}Yk.INSTANCE.onDidChangeZoomLevel;Yk.INSTANCE.onDidChangeFullscreen;var ll=typeof navigator=="object"?navigator.userAgent:"";ll.indexOf("Firefox")>=0;ll.indexOf("AppleWebKit")>=0;var xT=ll.indexOf("Chrome")>=0;!xT&&ll.indexOf("Safari")>=0;ll.indexOf("Electron/")>=0;ll.indexOf("Android")>=0;var Mp=!1;if(typeof Ho.matchMedia=="function"){let e=Ho.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Ho.matchMedia("(display-mode: fullscreen)");Mp=e.matches,ST(Ho,e,({matches:n})=>{Mp&&t.matches||(Mp=n)})}var qa="en",Tp=!1,Xk=!1,hd,Md=qa,P0=qa,kT,Ii,Vo=globalThis,_s,s1;typeof Vo.vscode<"u"&&typeof Vo.vscode.process<"u"?_s=Vo.vscode.process:typeof process<"u"&&typeof((s1=process==null?void 0:process.versions)==null?void 0:s1.node)=="string"&&(_s=process);var i1,CT=typeof((i1=_s==null?void 0:_s.versions)==null?void 0:i1.electron)=="string",ET=CT&&(_s==null?void 0:_s.type)==="renderer",r1;if(typeof _s=="object"){_s.platform,_s.platform,Tp=_s.platform==="linux",Tp&&_s.env.SNAP&&_s.env.SNAP_REVISION,_s.env.CI||_s.env.BUILD_ARTIFACTSTAGINGDIRECTORY,hd=qa,Md=qa;let e=_s.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);hd=t.userLocale,P0=t.osLocale,Md=t.resolvedLanguage||qa,kT=(r1=t.languagePack)==null?void 0:r1.translationsConfigFile}catch{}Xk=!0}else typeof navigator=="object"&&!ET?(Ii=navigator.userAgent,Ii.indexOf("Windows")>=0,Ii.indexOf("Macintosh")>=0,(Ii.indexOf("Macintosh")>=0||Ii.indexOf("iPad")>=0||Ii.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Tp=Ii.indexOf("Linux")>=0,(Ii==null?void 0:Ii.indexOf("Mobi"))>=0,Md=globalThis._VSCODE_NLS_LANGUAGE||qa,hd=navigator.language.toLowerCase(),P0=hd):console.error("Unable to resolve platform.");var D0=Xk,or=Ii,Zr=Md,NT;(e=>{function t(){return Zr}e.value=t;function n(){return Zr.length===2?Zr==="en":Zr.length>=3?Zr[0]==="e"&&Zr[1]==="n"&&Zr[2]==="-":!1}e.isDefaultVariant=n;function s(){return Zr==="en"}e.isDefault=s})(NT||(NT={}));var jT=typeof Vo.postMessage=="function"&&!Vo.importScripts;(()=>{if(jT){let e=[];Vo.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let s=0,i=e.length;s<i;s++){let l=e[s];if(l.id===n.data.vscodeScheduleAsyncWork){e.splice(s,1),l.callback();return}}});let t=0;return n=>{let s=++t;e.push({id:s,callback:n}),Vo.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var LT=!!(or&&or.indexOf("Chrome")>=0);or&&or.indexOf("Firefox")>=0;!LT&&or&&or.indexOf("Safari")>=0;or&&or.indexOf("Edg/")>=0;or&&or.indexOf("Android")>=0;var Pa=typeof navigator=="object"?navigator:{};D0||document.queryCommandSupported&&document.queryCommandSupported("copy")||Pa&&Pa.clipboard&&Pa.clipboard.writeText,D0||Pa&&Pa.clipboard&&Pa.clipboard.readText;var Bv=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Ip=new Bv,O0=new Bv,B0=new Bv;new Array(230);var RT;(e=>{function t(u){return Ip.keyCodeToStr(u)}e.toString=t;function n(u){return Ip.strToKeyCode(u)}e.fromString=n;function s(u){return O0.keyCodeToStr(u)}e.toUserSettingsUS=s;function i(u){return B0.keyCodeToStr(u)}e.toUserSettingsGeneral=i;function l(u){return O0.strToKeyCode(u)||B0.strToKeyCode(u)}e.fromUserSettings=l;function c(u){if(u>=98&&u<=113)return null;switch(u){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Ip.keyCodeToStr(u)}e.toElectronAccelerator=c})(RT||(RT={}));var Jk=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),AT;(e=>{function t(n){return n===e.None||n===e.Cancelled||n instanceof MT?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Lr.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Jk})})(AT||(AT={}));var MT=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Jk:(this._emitter||(this._emitter=new vn),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},TT;(e=>{async function t(s){let i,l=await Promise.all(s.map(c=>c.then(u=>u,u=>{i||(i=u)})));if(typeof i<"u")throw i;return l}e.settled=t;function n(s){return new Promise(async(i,l)=>{try{await s(i,l)}catch(c){l(c)}})}e.withAsyncBody=n})(TT||(TT={}));var $0=class vi{static fromArray(t){return new vi(n=>{n.emitMany(t)})}static fromPromise(t){return new vi(async n=>{n.emitMany(await t)})}static fromPromises(t){return new vi(async n=>{await Promise.all(t.map(async s=>n.emitOne(await s)))})}static merge(t){return new vi(async n=>{await Promise.all(t.map(async s=>{for await(let i of s)n.emitOne(i)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new vn,queueMicrotask(async()=>{let s={emitOne:i=>this.emitOne(i),emitMany:i=>this.emitMany(i),reject:i=>this.reject(i)};try{await Promise.resolve(t(s)),this.resolve()}catch(i){this.reject(i)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await Lr.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>{var n;return(n=this._onReturn)==null||n.call(this),{done:!0,value:void 0}}}}static map(t,n){return new vi(async s=>{for await(let i of t)s.emitOne(n(i))})}map(t){return vi.map(this,t)}static filter(t,n){return new vi(async s=>{for await(let i of t)n(i)&&s.emitOne(i)})}filter(t){return vi.filter(this,t)}static coalesce(t){return vi.filter(t,n=>!!n)}coalesce(){return vi.coalesce(this)}static async toPromise(t){let n=[];for await(let s of t)n.push(s);return n}toPromise(){return vi.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};$0.EMPTY=$0.fromArray([]);var{getWindow:IT}=(function(){let e=new Map,t={window:Ho,disposables:new Ga};e.set(Ho.vscodeWindowId,t);let n=new vn,s=new vn,i=new vn;function l(c,u){return(typeof c=="number"?e.get(c):void 0)??(u?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return Oi.None;let u=new Ga,h={window:c,disposables:u.add(new Ga)};return e.set(c.vscodeWindowId,h),u.add(As(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),u.add(Cg(c,DT.BEFORE_UNLOAD,()=>{i.fire(c)})),n.fire(h),u},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:l,getWindow(c){var p;let u=c;if((p=u==null?void 0:u.ownerDocument)!=null&&p.defaultView)return u.ownerDocument.defaultView.window;let h=c;return h!=null&&h.view?h.view.window:Ho},getDocument(c){return IT(c).document}}})(),PT=class{constructor(e,t,n,s){this._node=e,this._type=t,this._handler=n,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Cg(e,t,n,s){return new PT(e,t,n,s)}var DT={BEFORE_UNLOAD:"beforeunload"},OT=class extends Oi{constructor(e,t,n,s,i,l,c,u,h){super(),this._terminal=e,this._characterJoinerService=t,this._charSizeService=n,this._coreBrowserService=s,this._coreService=i,this._decorationService=l,this._optionsService=c,this._themeService=u,this._cursorBlinkStateManager=new Ql,this._charAtlasDisposable=this._register(new Ql),this._observerDisposable=this._register(new Ql),this._model=new mT,this._workCell=new E0,this._workCell2=new E0,this._rectangleRenderer=this._register(new Ql),this._glyphRenderer=this._register(new Ql),this._onChangeTextureAtlas=this._register(new vn),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new vn),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new vn),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onRequestRedraw=this._register(new vn),this.onRequestRedraw=this._onRequestRedraw.event,this._onContextLoss=this._register(new vn),this.onContextLoss=this._onContextLoss.event,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas");let p={antialias:!1,depth:!1,preserveDrawingBuffer:h};if(this._gl=this._canvas.getContext("webgl2",p),!this._gl)throw new Error("WebGL2 not supported "+this._gl);this._register(this._themeService.onChangeColors(()=>this._handleColorChange())),this._cellColorResolver=new RM(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new wT(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,c,this._themeService)],this.dimensions=jM(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(c.onOptionChange(()=>this._handleOptionsChanged())),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register(Cg(this._canvas,"webglcontextlost",v=>{console.log("webglcontextlost event received"),v.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,console.warn("webgl context not restored; firing onContextLoss"),this._onContextLoss.fire(v)},3e3)})),this._register(Cg(this._canvas,"webglcontextrestored",v=>{console.warn("webglcontextrestored event received"),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,k0(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=C0(this._canvas,this._coreBrowserService.window,(v,_)=>this._setCanvasDevicePixelDimensions(v,_)),this._register(this._coreBrowserService.onWindowChange(v=>{this._observerDisposable.value=C0(this._canvas,v,(_,g)=>this._setCanvasDevicePixelDimensions(_,g))})),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register(As(()=>{var v;for(let _ of this._renderLayers)_.dispose();(v=this._canvas.parentElement)==null||v.removeChild(this._canvas),k0(this._terminal)}))}get textureAtlas(){var e;return(e=this._charAtlas)==null?void 0:e.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(e,t){var n,s,i,l;this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows);for(let c of this._renderLayers)c.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,(n=this._rectangleRenderer.value)==null||n.setDimensions(this.dimensions),(s=this._rectangleRenderer.value)==null||s.handleResize(),(i=this._glyphRenderer.value)==null||i.setDimensions(this.dimensions),(l=this._glyphRenderer.value)==null||l.handleResize(),this._refreshCharAtlas(),this._clearModel(!1)}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){var e;for(let t of this._renderLayers)t.handleBlur(this._terminal);(e=this._cursorBlinkStateManager.value)==null||e.pause(),this._requestRedrawViewport()}handleFocus(){var e;for(let t of this._renderLayers)t.handleFocus(this._terminal);(e=this._cursorBlinkStateManager.value)==null||e.resume(),this._requestRedrawViewport()}handleSelectionChanged(e,t,n){for(let s of this._renderLayers)s.handleSelectionChanged(this._terminal,e,t,n);this._model.selection.update(this._core,e,t,n),this._requestRedrawViewport()}handleCursorMove(){var e;for(let t of this._renderLayers)t.handleCursorMove(this._terminal);(e=this._cursorBlinkStateManager.value)==null||e.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new yT(this._terminal,this._gl,this.dimensions,this._themeService),this._glyphRenderer.value=new dT(this._terminal,this._gl,this.dimensions,this._optionsService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){var t;if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0){this._isAttached=!1;return}let e=qk(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize);this._charAtlas!==e&&(this._onChangeTextureAtlas.fire(e.pages[0].canvas),this._charAtlasDisposable.value=jk(Lr.forward(e.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),Lr.forward(e.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=e,this._charAtlas.warmUp(),(t=this._glyphRenderer.value)==null||t.setAtlas(this._charAtlas)}_clearModel(e){var t;this._model.clear(),e&&((t=this._glyphRenderer.value)==null||t.clear())}clearTextureAtlas(){var e;(e=this._charAtlas)==null||e.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){var e;this._clearModel(!0);for(let t of this._renderLayers)t.reset(this._terminal);(e=this._cursorBlinkStateManager.value)==null||e.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(e,t){var n;if(!this._isAttached)if((n=this._core.screenElement)!=null&&n.isConnected&&this._charSizeService.width&&this._charSizeService.height)this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0;else return;for(let s of this._renderLayers)s.handleGridChanged(this._terminal,e,t);!this._glyphRenderer.value||!this._rectangleRenderer.value||(this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(e,t),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible)&&this._rectangleRenderer.value.renderCursor())}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new iT(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(e,t){let n=this._core,s=this._workCell,i,l,c,u,h,p,v=0,_=!0,g,w,S,N,C,j,E,R,x;e=z0(e,n.rows-1,0),t=z0(t,n.rows-1,0);let W=this._coreService.decPrivateModes.cursorStyle??n.options.cursorStyle??"block",$=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,Y=$-n.buffer.ydisp,q=Math.min(this._terminal.buffer.active.cursorX,n.cols-1),K=-1,se=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let V=!1;for(l=e;l<=t;l++)for(c=l+n.buffer.ydisp,u=n.buffer.lines.get(c),this._model.lineLengths[l]=0,S=$===c,v=0,h=this._characterJoinerService.getJoinedCharacters(c),R=0;R<n.cols;R++){if(i=this._cellColorResolver.result.bg,u.loadCell(R,s),R===0&&(i=this._cellColorResolver.result.bg),p=!1,_=R>=v,g=R,h.length>0&&R===h[0][0]&&_){w=h.shift();let B=this._model.selection.isCellSelected(this._terminal,w[0],c);for(E=w[0]+1;E<w[1];E++)_&&(_=B===this._model.selection.isCellSelected(this._terminal,E,c));_&&(_=!S||q<w[0]||q>=w[1]),_?(p=!0,s=new BT(s,u.translateToString(!0,w[0],w[1]),w[1]-w[0]),g=w[1]-1):v=w[1]}if(N=s.getChars(),C=s.getCode(),E=(l*n.cols+R)*Kd,this._cellColorResolver.resolve(s,R,c,this.dimensions.device.cell.width),se&&c===$&&(R===q&&(this._model.cursor={x:q,y:Y,width:s.getWidth(),style:this._coreBrowserService.isFocused?W:n.options.cursorInactiveStyle,cursorWidth:n.options.cursorWidth,dpr:this._devicePixelRatio},K=q+s.getWidth()-1),R>=q&&R<=K&&(this._coreBrowserService.isFocused&&W==="block"||this._coreBrowserService.isFocused===!1&&n.options.cursorInactiveStyle==="block")&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),C!==0&&(this._model.lineLengths[l]=R+1),!(this._model.cells[E]===C&&this._model.cells[E+Rd]===this._cellColorResolver.result.bg&&this._model.cells[E+Ad]===this._cellColorResolver.result.fg&&this._model.cells[E+Rp]===this._cellColorResolver.result.ext)&&(V=!0,N.length>1&&(C|=pT),this._model.cells[E]=C,this._model.cells[E+Rd]=this._cellColorResolver.result.bg,this._model.cells[E+Ad]=this._cellColorResolver.result.fg,this._model.cells[E+Rp]=this._cellColorResolver.result.ext,j=s.getWidth(),this._glyphRenderer.value.updateCell(R,l,C,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,N,j,i),p)){for(s=this._workCell,R++;R<=g;R++)x=(l*n.cols+R)*Kd,this._glyphRenderer.value.updateCell(R,l,0,0,0,0,wM,0,0),this._model.cells[x]=0,this._model.cells[x+Rd]=this._cellColorResolver.result.bg,this._model.cells[x+Ad]=this._cellColorResolver.result.fg,this._model.cells[x+Rp]=this._cellColorResolver.result.ext;R--}}V&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model)}_updateDimensions(){!this._charSizeService.width||!this._charSizeService.height||(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=this._optionsService.rawOptions.lineHeight===1?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(e,t){this._canvas.width===e&&this._canvas.height===t||(this._canvas.width=e,this._canvas.height=t,this._requestRedrawViewport())}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){let e=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:e,end:e})}},BT=class extends Wa{constructor(e,t,n){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}};function z0(e,t,n=0){return Math.max(Math.min(e,t),n)}var F0="di$target",H0="di$dependencies",Pp=new Map;function ar(e){if(Pp.has(e))return Pp.get(e);let t=function(n,s,i){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");$T(t,n,i)};return t._id=e,Pp.set(e,t),t}function $T(e,t,n){t[F0]===t?t[H0].push({id:e,index:n}):(t[H0]=[{id:e,index:n}],t[F0]=t)}ar("BufferService");ar("CoreMouseService");ar("CoreService");ar("CharsetService");ar("InstantiationService");ar("LogService");var zT=ar("OptionsService");ar("OscLinkService");ar("UnicodeService");ar("DecorationService");var FT={trace:0,debug:1,info:2,warn:3,error:4,off:5},HT="xterm.js: ",U0=class extends Oi{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=FT[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]=="function"&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?"":HT)+t,...n)}trace(e,...t){var n;this._logLevel<=0&&this._log(((n=this._optionsService.options.logger)==null?void 0:n.trace.bind(this._optionsService.options.logger))??console.log,e,t)}debug(e,...t){var n;this._logLevel<=1&&this._log(((n=this._optionsService.options.logger)==null?void 0:n.debug.bind(this._optionsService.options.logger))??console.log,e,t)}info(e,...t){var n;this._logLevel<=2&&this._log(((n=this._optionsService.options.logger)==null?void 0:n.info.bind(this._optionsService.options.logger))??console.info,e,t)}warn(e,...t){var n;this._logLevel<=3&&this._log(((n=this._optionsService.options.logger)==null?void 0:n.warn.bind(this._optionsService.options.logger))??console.warn,e,t)}error(e,...t){var n;this._logLevel<=4&&this._log(((n=this._optionsService.options.logger)==null?void 0:n.error.bind(this._optionsService.options.logger))??console.error,e,t)}};U0=cM([uM(0,zT)],U0);var UT=class extends Oi{constructor(e){if(Ak&&bM()<16){let t={antialias:!1,depth:!1,preserveDrawingBuffer:!0};if(!document.createElement("canvas").getContext("webgl2",t))throw new Error("Webgl2 is only supported on Safari 16 and above")}super(),this._preserveDrawingBuffer=e,this._onChangeTextureAtlas=this._register(new vn),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new vn),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new vn),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onContextLoss=this._register(new vn),this.onContextLoss=this._onContextLoss.event}activate(e){let t=e._core;if(!e.element){this._register(t.onWillOpen(()=>this.activate(e)));return}this._terminal=e;let n=t.coreService,s=t.optionsService,i=t,l=i._renderService,c=i._characterJoinerService,u=i._charSizeService,h=i._coreBrowserService,p=i._decorationService;i._logService;let v=i._themeService;this._renderer=this._register(new OT(e,c,u,h,n,p,s,v,this._preserveDrawingBuffer)),this._register(Lr.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(Lr.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(Lr.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(Lr.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),l.setRenderer(this._renderer),this._register(As(()=>{if(this._terminal._core._store._isDisposed)return;let _=this._terminal._core._renderService;_.setRenderer(this._terminal._core._createRenderer()),_.handleResize(e.cols,e.rows)}))}get textureAtlas(){var e;return(e=this._renderer)==null?void 0:e.textureAtlas}clearTextureAtlas(){var e;(e=this._renderer)==null||e.clearTextureAtlas()}};const Qk="nc-terminal-renderer",vo="webgl",_o="dom";function Zk(e){if(e!==void 0)return e;try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function Pc(e){const t=Zk(e);try{return t&&t.getItem(Qk)===_o?_o:vo}catch{return vo}}function eC(e,t){const n=e===_o?_o:vo,s=Zk(t);try{s&&s.setItem(Qk,n)}catch{}return n}function WT(e){return e===_o?vo:_o}function qT(e,{preference:t,createAddon:n,onFallback:s}={}){const i=t||Pc(),l={kind:_o,dispose:()=>{}};if(i!==vo||!e||typeof e.loadAddon!="function"||typeof n!="function")return l;let c;try{if(c=n(),!c)return l;e.loadAddon(c)}catch{try{c&&c.dispose()}catch{}return s&&s("unavailable"),l}let u=!1;const h=()=>{if(!u){u=!0;try{c.dispose()}catch{}}};return typeof c.onContextLoss=="function"&&c.onContextLoss(()=>{h(),s&&s("context-loss")}),{kind:vo,dispose:h}}const KT=Object.freeze({retryBaseMs:250,retryMaxMs:5e3,pingMs:5e3,deadMs:1e4,queuedInputBytes:4096,overlayDelayMs:1e3}),VT=(e,t)=>{const n=Number(e);return Number.isFinite(n)&&n>0?n:t};function tC(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n={};for(const[s,i]of Object.entries(KT))n[s]=VT(t[s],i);return n}let Eg=tC(null);function GT(e){return Eg=tC(e),{...Eg}}function nC(){return{...Eg}}function YT(e,t,n=null,s=null){if(!e)return"/ws";let l=`/api/route/${String(e).split("/").map(encodeURIComponent).join("/")}/_/ws?token=${encodeURIComponent(t||"")}`;return n&&(l+=`&attachId=${encodeURIComponent(n)}`,s&&(l+=`&attachSession=${encodeURIComponent(s)}`)),l}function XT(e,t,n=null){const s=n===null?typeof sessionStorage<"u"?sessionStorage:null:n;if(!s)return null;const i=`nc-attach:${t||"local"}:${String(e||"")}`;try{const l=s.getItem(i);if(typeof l=="string"&&/^[0-9a-f]{32}$/.test(l))return l;const c=new Uint8Array(16),u=globalThis.crypto;if(!u||typeof u.getRandomValues!="function")return null;u.getRandomValues(c);const h=Array.from(c).map(p=>p.toString(16).padStart(2,"0")).join("");return s.setItem(i,h),h}catch{return null}}function JT({session:e,node:t,token:n,cols:s,rows:i,readonly:l=!1,takeSize:c,focused:u,onData:h,onExit:p,onFiles:v,onSnapshot:_,onLink:g,retryBaseMs:w,retryMaxMs:S,retryStableMs:N=5e3,onRetryScheduled:C,pingMs:j,deadMs:E,queuedInputBytes:R,onQueued:x}){const W=nC(),$=w===void 0?W.retryBaseMs:w,Y=S===void 0?W.retryMaxMs:S,q=j===void 0?W.pingMs:j,K=E===void 0?W.deadMs:E,se=R===void 0?W.queuedInputBytes:R,V=["localhost","127.0.0.1","::1","[::1]"].includes(location.hostname);if(location.protocol!=="https:"&&!V)throw new Error("nexuscrew: ws:// rifiutato su origine non-locale e non-TLS (apri via tunnel su localhost o servi in HTTPS)");const B=location.protocol==="https:"?"wss":"ws",D=XT(e,t),O=`${B}://${location.host}${YT(t,n,D,e)}`;let P=null,z=!1,A=!1,T=null,L=null,H=0,M=null,U=!1,ee=null,re=0,oe=null;const je=Math.max(1,Number(se)||4096);let te=[],ie=0;const pe=()=>{if(typeof x=="function")try{x(ie)}catch{}},xe=()=>{if(!P||P.readyState!==1||!te.length)return;const Q=te;te=[],ie=0;for(const ge of Q)try{P.send(ge)}catch{}pe()},Be=()=>{ee&&(clearInterval(ee),ee=null)},Te=Q=>{Be(),re=Date.now();const ge=Math.max(1,Number(q)||5e3),Z=Math.max(1,Number(K)||1e4);ee=setInterval(()=>{if(P!==Q||z||A){Be();return}if(Date.now()-re>Z){Be();try{Q.close(4e3,"liveness timeout")}catch{}return}if(Q.readyState===1)try{Q.send(JSON.stringify({type:"ping",t:Date.now()}))}catch{}},ge),typeof ee.unref=="function"&&ee.unref()};let Me=u;const J=()=>{if(z||A||T)return;const Q=Math.min(Y,Math.max(0,$)*2**Math.min(H++,5));typeof C=="function"&&C(Q),T=setTimeout(()=>{T=null,le()},Q)},le=()=>{if(z||A)return;const Q=new WebSocket(O);P=Q,Q.binaryType="arraybuffer",Q.onopen=()=>{if(P!==Q||z)return;L&&clearTimeout(L);const ge=Number(N),Z=Number.isFinite(ge)?Math.max(0,ge):5e3;L=setTimeout(()=>{L=null,P===Q&&Q.readyState===1&&(H=0)},Z),typeof L.unref=="function"&&L.unref();const fe={type:"attach",session:e,token:n,cols:s,rows:i,readonly:l};M&&(fe.reconnectToken=M),c!==void 0&&(fe.takeSize=c),Q.send(JSON.stringify(fe)),Me!==void 0&&Q.send(JSON.stringify({type:"focus",on:!!Me})),U&&Q.send(JSON.stringify(oe===null?{type:"resync"}:{type:"resume",seq:oe})),xe(),Te(Q)},Q.onmessage=ge=>{if(!(P!==Q||z))if(re=Date.now(),typeof ge.data=="string"){let Z;try{Z=JSON.parse(ge.data)}catch{return}if(Z.type==="attached"&&typeof Z.reconnectToken=="string"&&Z.reconnectToken&&(M=Z.reconnectToken),Z.type==="exit"&&(A=!0,p&&p(Z.code)),Z.type==="files"&&v&&v(Z),Z.type==="snapshot"&&_&&_(typeof Z.data=="string"?Z.data:""),Z.type==="link"&&g&&g(Z.state==="live"?"live":"reconnecting"),Z.type==="resync-needed")try{Q.send(JSON.stringify({type:"resync"}))}catch{}}else{let Z=new Uint8Array(ge.data);try{ge.data&&ge.data.byteLength>=4&&(oe=new DataView(ge.data).getUint32(0),Z=new Uint8Array(ge.data,4))}catch{}h&&h(Z)}},Q.onerror=()=>{if(P===Q)try{Q.close()}catch{}},Q.onclose=ge=>{Be(),!(P!==Q||z||A)&&(L&&(clearTimeout(L),L=null),![4401,4403,4404].includes(ge==null?void 0:ge.code)&&(U=!0,g&&g("reconnecting"),J()))}};return le(),{sendInput:Q=>{const ge=typeof Q=="string"?new TextEncoder().encode(Q):Q;if(P&&P.readyState===1)try{return P.send(ge),!0}catch{try{P.close()}catch{}}return ie+ge.length>je?!1:(te.push(ge),ie+=ge.length,pe(),!0)},isReady:()=>!!P&&P.readyState===1,resize:(Q,ge)=>{s=Q,i=ge,(P==null?void 0:P.readyState)===1&&P.send(JSON.stringify({type:"resize",cols:Q,rows:ge}))},action:Q=>{(P==null?void 0:P.readyState)===1&&P.send(JSON.stringify({type:"action",name:Q}))},focus:Q=>{Me=Q,(P==null?void 0:P.readyState)===1&&P.send(JSON.stringify({type:"focus",on:!!Q}))},close:()=>{if(z=!0,Be(),T&&clearTimeout(T),L&&clearTimeout(L),T=null,L=null,P)try{P.close()}catch{}},get raw(){return P}}}const sC=1e3;function QT(e,t,n=sC){if(e==null)return!1;const s=Number(t)-Number(e);return Number.isFinite(s)?s>=Math.max(0,Number(n)||0):!1}function ZT(e={},t={}){const n=Number(e.viewportY)||0,s=Number(e.baseY)||0,i=Math.max(0,Number(t.baseY)||0);return n>=s?{atBottom:!0,line:null}:{atBottom:!1,line:Math.min(n,i)}}function eI(e){return e?`\r
152
+ \x1B[2m── riconnesso ──\x1B[0m\r
153
+ `:""}function tI(e,t){var s;if(!e||typeof((s=e.parser)==null?void 0:s.registerCsiHandler)!="function")return;const n=i=>l=>{const c=l&&l[0],u=Array.isArray(c)?c[0]:c,h=Number.isFinite(u)&&u>0?u:0;if(typeof t=="function")try{t(`\x1B[${i}${h};0$y`)}catch{}return!0};e.parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},n("?")),e.parser.registerCsiHandler({intermediates:"$",final:"p"},n(""))}function W0(e,t){try{return e.write(t),!0}catch(n){return console.error("[terminal] output scartato: eccezione del parser",n),!1}}function nI(e,{ctrl:t=!1,alt:n=!1}={}){if(!e||!t&&!n)return e;const s=e.charCodeAt(0);let i=s;return t&&(s>=97&&s<=122?i=s-96:s>=64&&s<=95?i=s-64:s===32&&(i=0)),(n?"\x1B":"")+String.fromCharCode(i)+e.slice(1)}async function Dc(e){const t=String(e||"");if(!t)return!1;try{if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function")return await navigator.clipboard.writeText(t),!0}catch{}try{const n=document.createElement("textarea");n.value=t,n.readOnly=!0,n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n),n.select();const s=document.execCommand&&document.execCommand("copy");if(n.remove(),s)return!0}catch{}return!1}const sI="\r";function iI(e){const t=String(e||"");let n=t.length;for(;n>0;){const s=t.charCodeAt(n-1);if(s===10||s===13)n-=1;else break}return t.slice(0,n)}function rI({isReady:e,paste:t,send:n}){return s=>{if(!s||!e())return!1;try{return t(s)===!1||!e()?!1:n(sI)!==!1}catch{return!1}}}function oI(e){return!e||typeof e!="object"?!1:!!e.shiftKey}function aI(e){return!e||typeof e!="object"||String(e.key||"").toLowerCase()!=="c"?!1:!!(e.metaKey||e.ctrlKey&&e.shiftKey)}function lI(e){return/mac|iphone|ipad/i.test(String(e||""))?"⌘C":"Ctrl+Shift+C"}const cI=450,q0=8;function K0(e,t,n,s){return Math.abs(Number(n)-Number(e))>q0||Math.abs(Number(s)-Number(t))>q0}function uI({range:e,cell:t,cols:n}){const s=Number(n),i=Number(e.start.row)*s+Number(e.start.col),l=Number(e.end.row)*s+Number(e.end.col),c=Number(t.row)*s+Number(t.col),u={start:{row:e.start.row,col:e.start.col},end:{row:e.end.row,col:e.end.col},moved:null};if(c<i)u.start={row:Number(t.row),col:Number(t.col)},u.moved="start";else if(c>l)u.end={row:Number(t.row),col:Number(t.col)},u.moved="end";else{if(c===i||c===l)return u;c-i<=l-c?(u.start={row:Number(t.row),col:Number(t.col)},u.moved="start"):(u.end={row:Number(t.row),col:Number(t.col)},u.moved="end")}return u}function dI(e){const t=e!=="mouse";return{handles:t,magnifier:t}}function hI(e,t){if(!e||!e.start||!e.end)return null;const n=Number(t);if(!Number.isFinite(n)||n<=0)return null;const s=Number(e.start.y)*n+Number(e.start.x),i=Number(e.end.y)*n+Number(e.end.x),l=Math.min(s,i),c=Math.max(l,Math.max(s,i)-1);return{start:{row:Math.floor(l/n),col:l%n},end:{row:Math.floor(c/n),col:c%n}}}function V0(e,t,n){const s=Number(e.row)*Number(n)+Number(e.col),i=Number(t.row)*Number(n)+Number(t.col);return s<=i?{start:{row:e.row,col:e.col},end:{row:t.row,col:t.col}}:{start:{row:t.row,col:t.col},end:{row:e.row,col:e.col}}}function fI({moving:e,fixed:t,which:n,cols:s,maxRow:i}){const l=Number(s);let c=Math.max(0,Math.min(Number(i),Number(e.row))),u=Math.max(0,Math.min(l-1,Number(e.col)));const h=c*l+u,p=Number(t.row)*l+Number(t.col);return n==="start"&&h>p&&(c=Number(t.row),u=Number(t.col)),n==="end"&&h<p&&(c=Number(t.row),u=Number(t.col)),{row:c,col:u}}function Da({line:e,col:t,side:n,cols:s}){const i=Math.max(0,Math.min(Number(s)-1,Number(t))),l=e&&typeof e.getCell=="function"?e.getCell(i):null;return(l&&typeof l.getWidth=="function"?Number(l.getWidth()):1)!==0?i:n==="end"?Math.min(Number(s)-1,i+1):Math.max(0,i-1)}function G0({line:e,col:t,cols:n}){const s=Math.max(0,Math.min(Number(n)-1,Number(t))),i=u=>{const h=e&&typeof e.getCell=="function"?e.getCell(u):null;return h&&typeof h.getChars=="function"?h.getChars():""};if(i(s)===""||i(s)===" ")return{start:s,end:s};let l=s;for(;l>0;){const u=i(l-1);if(u===""||u===" ")break;l-=1}let c=s;for(;c<Number(n)-1;){const u=i(c+1);if(u===""||u===" ")break;c+=1}return{start:l,end:c}}function pI({startLeft:e,endLeft:t,targetWidth:n=46}){return Math.abs(Number(t)-Number(e))<Number(n)}function mI({anchorLeft:e,anchorTop:t,hostWidth:n,hostHeight:s,bubbleWidth:i,bubbleHeight:l,pinHeight:c=30,margin:u=4,gap:h=8}){const p=Number(i),v=Number(l),_=Number(u),g=Math.max(_,Number(n)-_-p),w=Math.max(_,Math.min(g,Number(e)-Math.round(p/2)));let S=Number(t)-Number(h)-v,N=!1;S<_&&(S=Number(t)+Number(c)+Number(h),N=!0);const C=Math.max(_,Number(s)-_-v);return S>C&&(S=C),{left:w,top:S,flipped:N}}function Y0(e,t){const n=Number(t),s=Number(e.start.row)*n+Number(e.start.col),i=Number(e.end.row)*n+Number(e.end.col);return{col:e.start.col,row:e.start.row,length:i-s+1}}const X0=28,gI=50;function vI({range:e,viewportY:t,rows:n,cols:s=0,cellWidth:i,cellHeight:l,screenLeft:c=0,screenTop:u=0}){const h={},p=Number(s)*Number(i);for(const v of["start","end"]){const _=e[v],g=Number(_.row)-Number(t),w=g>=0&&g<Number(n),S=(v==="start"?Number(_.col):Number(_.col)+1)*Number(i),N=v==="start"?S-X0<0:S+X0>p;h[v]={left:Number(c)+S,top:Number(u)+(g+1)*Number(l),visible:w,flip:N}}return h}function _I({visibleRow:e,rows:t}){const n=Number(e);return n<=0?-1:n>=Number(t)-1?1:0}function yI({range:e,side:t,line:n,cols:s}){if(!e||!e.start||!e.end||!n)return null;const i=Math.max(0,Number(s)-1),l=t==="end"?e.end:e.start,c=Number(l.row);let u,h;Number(e.start.row)===Number(e.end.row)?(u=Number(e.start.col),h=Number(e.end.col)):c===Number(e.start.row)?(u=Number(e.start.col),h=i):c===Number(e.end.row)?(u=0,h=Number(e.end.col)):(u=0,h=i),u=Math.max(0,Math.min(i,u)),h=Math.max(u,Math.min(i,h));const p=n.translateToString(!0,0,u);let v=n.translateToString(!1,u,h+1);v.replace(/\s+$/,"")===""&&(v="");const _=n.translateToString(!0,Math.min(i+1,h+1),i+1);return{row:c,before:p,sel:v,after:_}}const $v="(min-width:1024px) and (pointer:fine)";function bI(){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia($v).matches}catch{return!1}}function zv(){const[e,t]=y.useState(bI);return y.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia($v),s=i=>t(i.matches);return n.addEventListener("change",s),()=>n.removeEventListener("change",s)},[]),e}const wI=new Map([["image/png","png"],["image/jpeg","jpg"],["image/gif","gif"],["image/webp","webp"],["application/pdf","pdf"],["text/plain","txt"]]);function Dp(e){return e?e.files&&e.files.length>0||Array.from(e.items||[]).some(t=>t&&t.kind==="file")?!0:Array.from(e.types||[]).includes("Files"):!1}function J0(e){if(!e)return[];const t=Array.from(e.files||[]).filter(Boolean);return t.length?t:Array.from(e.items||[]).filter(n=>n&&n.kind==="file"&&typeof n.getAsFile=="function").map(n=>n.getAsFile()).filter(Boolean)}function SI(e,t=0,n=Date.now()){const s=String((e==null?void 0:e.name)||"").trim();if(s)return s;const i=wI.get(String((e==null?void 0:e.type)||"").toLowerCase())||"bin";return`clipboard-${n}-${t+1}.${i}`}async function Vd({files:e,token:t,session:n,node:s="",paste:i=!0,fetchImpl:l=Vn,onProgress:c=()=>{},now:u=Date.now()}={}){const h=Array.from(e||[]).filter(Boolean),p=[],v=[];if(!n||!h.length)return{paths:p,errors:v};const _=bn(s?String(s).split("/"):[]);for(let g=0;g<h.length;g+=1){const w=h[g],S=SI(w,g,u);c({index:g,total:h.length,name:S,state:"uploading"});try{const N=new FormData;N.append("session",n),N.append("paste",i?"true":"false"),N.append("file",w,S);const C=await l(`${_}/files/upload`,t,{method:"POST",body:N}),j=await C.json().catch(()=>({}));if(!C.ok||j.error)throw new Error(j.error||`HTTP ${C.status}`);p.push(j.path),c({index:g,total:h.length,name:S,state:"done",path:j.path})}catch(N){const C=String((N==null?void 0:N.message)||N);v.push({name:S,message:C}),c({index:g,total:h.length,name:S,state:"error",error:C})}}return{paths:p,errors:v}}const xI=420,kI=32;function CI(e){if(!e||typeof e!="object")return!1;const t=String(e.tagName||"").toLowerCase();return t==="textarea"||t==="input"||e.isContentEditable===!0}function Ng({documentRef:e,navigatorRef:t}={}){const n=e||(typeof document<"u"?document:null),s=t||(typeof navigator<"u"?navigator:null);let i=!1;try{s!=null&&s.virtualKeyboard&&typeof s.virtualKeyboard.hide=="function"&&(s.virtualKeyboard.hide(),i=!0)}catch{}const l=n&&n.activeElement;let c=!1;if(CI(l)&&typeof l.blur=="function")try{l.blur(),c=!0}catch{}return{blurred:c,apiRequested:i}}function iC(e,t,n=!1){const s=e&&e.textarea;if(!s)return null;const l=t==="single-tap"||t==="double-tap"&&n?"text":"none";return s.inputMode=l,s.setAttribute("inputmode",l),l}function EI(e,t){if(!e||!e.textarea)return!1;iC(e,"double-tap",!0);try{e.focus()}catch{return!1}const n=typeof navigator<"u"?navigator:null;try{n!=null&&n.virtualKeyboard&&typeof n.virtualKeyboard.show=="function"&&n.virtualKeyboard.show()}catch{}return!0}function NI(e,t,n){return e==="never"?{open:!1,next:null}:e==="single-tap"?{open:!0,next:null}:!n||!Number.isFinite(n.at)||!Number.isFinite(n.x)||!Number.isFinite(n.y)?{open:!1,next:null}:t&&n.at>=t.at&&n.at-t.at<=xI&&Math.hypot(n.x-t.x,n.y-t.y)<=kI?{open:!0,next:null}:{open:!1,next:n}}const jI=24,Q0=80,rC=8,LI="\x1B[5~",RI="\x1B[6~",AI=64,MI=65;function TI(e,t,n){const s=e==="up"?AI:MI,i=l=>Math.max(1,Math.min(9999,Number.isFinite(l)?Math.round(l):1));return`\x1B[<${s};${i(t)};${i(n)}M`}function II({alternateScreen:e=!1,readonly:t=!1,mouseTracking:n=!1}={}){return t?"scroll":n?"mouse":e?"page":"scroll"}function PI(e,t){return e==="page"?Number.isFinite(t)&&t>0?Math.max(Q0,t):Q0:Number.isFinite(t)&&t>0?t:jI}function DI({mode:e="scroll",accumulated:t=0,threshold:n=0}={}){const s=PI(e,n);if(!Number.isFinite(t))return{mode:e,up:0,down:0,remainder:0};const i=Math.abs(t);if(i<s)return{mode:e,up:0,down:0,remainder:t};const l=Math.floor(i/s),c=Math.min(l,rC),u=(t>=0?1:-1)*(i%s);return{mode:e,up:t>0?c:0,down:t<0?c:0,remainder:u}}function OI(e,t=null){const n=[],s=t&&Number.isFinite(t.col)?t.col:1,i=t&&Number.isFinite(t.row)?t.row:1,l=u=>Math.min(rC,Number.isFinite(u)?Math.max(0,Math.floor(u)):0),c=u=>e.mode==="mouse"?{kind:"input",seq:TI(u,s,i)}:e.mode==="page"?{kind:"input",seq:u==="up"?LI:RI}:{kind:"action",name:u==="up"?"scroll-up":"scroll-down"};for(let u=0;u<l(e.up);u+=1)n.push(c("up"));for(let u=0;u<l(e.down);u+=1)n.push(c("down"));return n}function kc({session:e,node:t,token:n,readonly:s,takeSize:i,focused:l,sendRef:c,composerRef:u,actionRef:h,ctrlRef:p,setCtrlArmed:v,altRef:_,setAltArmed:g,keyboardRef:w,onFiles:S,fontSize:N=13,selectionMode:C=!1,onSelectionModeChange:j,keyboardGesture:E="double-tap",onRendererChange:R}){const x=y.useRef(null),W=y.useRef(null),$=y.useRef(null),Y=y.useRef(N);Y.current=N;const q=y.useRef(l);q.current=l;const K=y.useRef(C);K.current=C;const se=y.useRef(E);se.current=E;const[V,B]=y.useState(""),[D,O]=y.useState(""),[P,z]=y.useState(null),[A,T]=y.useState(null),[L,H]=y.useState(!1),[M,U]=y.useState(0),ee=y.useRef(null),re=y.useRef(null),[oe,je]=y.useState(!1),[te,ie]=y.useState(null),pe=y.useRef(null),[xe,Be]=y.useState(null),[Te,Me]=y.useState(0),[J,le]=y.useState(null),[Q,ge]=y.useState("start"),[Z,fe]=y.useState(null),[ve,ke]=y.useState(!1),[Ve,ot]=y.useState(null),[rt,$e]=y.useState(null),_e=y.useRef(null),ze=y.useRef(null),[Je,He]=y.useState(!1),nt=async()=>{var gt,At,Lt,Rt;const ae=((At=(gt=W.current)==null?void 0:gt.term)==null?void 0:At.getSelection())||V;if(!ae){O(f("copy-empty")),setTimeout(()=>O(""),1500);return}const Oe=await Dc(ae);O(f(Oe?"copied":"copy-manual")),Oe&&((Rt=(Lt=W.current)==null?void 0:Lt.term)==null||Rt.clearSelection(),B(""),je(!1),j==null||j(!1)),setTimeout(()=>O(""),1800)},lt=y.useRef(nt);lt.current=nt;const X=y.useRef({startHandleDrag:()=>{}}),I=y.useRef(null);I.current=xe,y.useEffect(()=>{const ae=x.current;ae&&(ae.dataset.selectionOrigin=rt||"")},[rt]),y.useEffect(()=>{const ae=W.current;ae&&ae.sock&&ae.sock.focus&&ae.sock.focus(!!l)},[l]),y.useEffect(()=>{const ae=W.current;ae&&(ae.term.options.fontSize=N,ae.fit.fit(),ae.sock.resize(ae.term.cols,ae.term.rows))},[N]),y.useEffect(()=>{var ae,Oe;(Oe=(ae=W.current)==null?void 0:ae.setKeyboardGesture)==null||Oe.call(ae,E)},[E]),y.useEffect(()=>{var zi,dr,hr,ou,la,ca,yo,ua,yl,Ei,da;const ae=new ZA({cursorBlink:!0,fontSize:Y.current,scrollback:1e3,allowProposedApi:!0,theme:{background:"#0a0e0a"}}),Oe=new nM;ae.loadAddon(Oe),ae.open(x.current),Oe.fit(),lM(ae);const gt=qT(ae,{preference:Pc(),createAddon:()=>new UT,onFallback:()=>{R&&R("dom")}});$.current=gt,R&&R(gt.kind);let At=!1,Lt=!1;const Rt=be=>Ye=>{for(const tt of Ye){const pt=Array.isArray(tt)?tt[0]:tt;pt===1006&&(At=be),pt===1016&&(Lt=be)}return!1};(dr=(zi=ae.parser)==null?void 0:zi.registerCsiHandler)==null||dr.call(zi,{prefix:"?",final:"h"},Rt(!0)),(ou=(hr=ae.parser)==null?void 0:hr.registerCsiHandler)==null||ou.call(hr,{prefix:"?",final:"l"},Rt(!1)),(ca=(la=ae.parser)==null?void 0:la.registerEscHandler)==null||ca.call(la,{final:"c"},()=>(At=!1,Lt=!1,!1));let zt=null;tI(ae,s?null:be=>zt&&zt(be));const ft=()=>{const be=At&&!Lt&&(ae.modes&&ae.modes.mouseTrackingMode||"none")!=="none",Ye=x.current;return Ye&&(Ye.dataset.mouseTracking=be?"on":"off"),be},Yt=new TextDecoder;let $t=se.current==="single-tap",Zt=null;const Bt=()=>{$t=se.current==="single-tap",iC(ae,se.current,$t)},Yn=be=>{se.current=be,Zt=null,Bt()},nn=()=>se.current==="never"?!1:($t=!0,EI(ae));w&&(w.current=nn),Bt();const rn=ae.textarea,sn=()=>{se.current==="double-tap"&&Bt()};rn==null||rn.addEventListener("blur",sn);let wn=!1,Ft=0;const on=()=>{wn=!0,Ft=Date.now()+2e3},un=()=>{wn=!1};(yo=x.current)==null||yo.addEventListener("paste",on,!0),(ua=x.current)==null||ua.addEventListener("keydown",un,!0);let Xt;try{Xt=JT({session:e,node:t,token:n,readonly:s,takeSize:i,focused:q.current,onFiles:S,cols:ae.cols,rows:ae.rows,onData:be=>W0(ae,Yt.decode(be)),onExit:()=>W0(ae,`\r
154
+ \x1B[33m[sessione finita]\x1B[0m\r
155
+ `),onSnapshot:be=>{try{const Ye=ae.buffer&&ae.buffer.active,tt=ZT({viewportY:Ye?Ye.viewportY:0,baseY:Ye?Ye.baseY:0},{baseY:Ye?Ye.baseY:0});ae.reset(),ae.write(be),!tt.atBottom&&tt.line!==null&&typeof ae.scrollToLine=="function"&&ae.scrollToLine(tt.line)}catch{}},onQueued:be=>U(be),onLink:be=>{if(re.current&&(clearTimeout(re.current),re.current=null),be==="live"){const Ye=ee.current!==null&&QT(ee.current,Date.now());if(ee.current=null,H(!1),Ye)try{ae.write(eI(!0))}catch{}return}ee.current===null&&(ee.current=Date.now()),re.current=setTimeout(()=>{re.current=null,H(!0)},nC().overlayDelayMs||sC)}}),zt=be=>Xt.sendInput(be)}catch(be){return ae.write(`\r
156
+ \x1B[31m${be.message}\x1B[0m\r
157
+ `),w&&(w.current=null),rn==null||rn.removeEventListener("blur",sn),(yl=x.current)==null||yl.removeEventListener("paste",on,!0),(Ei=x.current)==null||Ei.removeEventListener("keydown",un,!0),()=>{var Ye,tt;try{(tt=(Ye=$.current)==null?void 0:Ye.dispose)==null||tt.call(Ye)}catch{}$.current=null,ae.dispose()}}W.current={term:ae,fit:Oe,sock:Xt,setKeyboardGesture:Yn};let dn=null;const Js=ae.onData(be=>{if(s){dn&&(dn.ok=!1);return}const Ye=wn&&Date.now()<Ft;un(),!dn&&!Ye&&be.length>=1&&(p&&p.current||_&&_.current)&&(be=nI(be,{ctrl:!!(p&&p.current),alt:!!(_&&_.current)}),p&&(p.current=!1),_&&(_.current=!1),v&&v(!1),g&&g(!1));const tt=Xt.sendInput(be);dn&&(dn.seen=!0,dn.ok=dn.ok&&tt)});c&&(c.current=be=>Xt.sendInput(be)),h&&(h.current=be=>Xt.action(be)),u&&(u.current=rI({isReady:()=>!s&&Xt.isReady(),paste:be=>{const Ye={seen:!1,ok:!0};dn=Ye;try{ae.paste(be)}catch{Ye.ok=!1}finally{dn=null}return Ye.seen&&Ye.ok},send:be=>Xt.sendInput(be)}));const ds=be=>{_e.current=be,$e(be)};let Vt=null;const Ms=ae.onSelectionChange(()=>{const be=ae.getSelection();be?(B(be),je(!1)):je(!0);const Ye=hI(ae.getSelectionPosition(),ae.cols),tt=Ye?V0(Ye.start,Ye.end,ae.cols):null;ie(tt),pe.current=tt,tt||ds(null),!tt&&Vt&&Pr();let pt=null;if(tt&&typeof ae.buffer.active.getLine=="function"){const Mt=[];for(let xt=tt.start.row;xt<=tt.end.row;xt++){const Qt=ae.buffer.active.getLine(xt);Mt.push(Qt?Qt.translateToString():"")}pt={startRow:tt.start.row,endRow:tt.end.row,lines:Mt}}ze.current=pt,He(!1)}),Xn=ae.onRender(be=>{var Ye;if((Ye=ae.hasSelection)!=null&&Ye.call(ae)){const tt=ze.current,pt=be&&be.start,Mt=be&&be.end;if(tt&&Number.isInteger(pt)&&Number.isInteger(Mt)&&typeof ae.buffer.active.getLine=="function"){const xt=Number(ae.buffer.active.viewportY)||0,Qt=Math.max(xt+pt,tt.startRow),hn=Math.min(xt+Mt,tt.endRow);for(let Dn=Qt;Dn<=hn;Dn++){const Tn=ae.buffer.active.getLine(Dn);if((Tn?Tn.translateToString():"")!==tt.lines[Dn-tt.startRow]){He(!0);break}}}Me(xt=>xt+1)}}),Ts=ae.onScroll(()=>{var be;(be=ae.hasSelection)!=null&&be.call(ae)&&Me(Ye=>Ye+1)});ae.attachCustomKeyEventHandler(be=>(be.ctrlKey||be.metaKey)&&be.key.toLowerCase()==="c"&&ae.getSelection()?(be.type==="keydown"&&Dc(ae.getSelection()),!1):!0);const kt=x.current;let ue=!1;const De=async be=>{if(!be.length||ue)return;if(s){z({error:f("settings-readonly")});return}ue=!0,z({current:0,total:be.length,name:""});const Ye=await Vd({files:be,token:n,session:e,node:t,paste:!0,onProgress:({index:tt,total:pt,name:Mt,state:xt,error:Qt})=>z({current:tt+1,total:pt,name:Mt,...xt==="error"?{error:Qt}:{}})});ue=!1,Ye.errors.length?z({error:Ye.errors.map(tt=>`${tt.name}: ${tt.message}`).join(" · ")}):(z({done:!0,total:Ye.paths.length}),setTimeout(()=>z(null),1600))},Xe=be=>{const Ye=be.clipboardData;if(!Dp(Ye))return;const tt=J0(Ye);tt.length&&(be.preventDefault(),be.stopPropagation(),De(tt))},ct=be=>{Dp(be.dataTransfer)&&(be.preventDefault(),be.stopPropagation())},It=be=>{Dp(be.dataTransfer)&&(be.preventDefault(),be.stopPropagation(),De(J0(be.dataTransfer)))};kt.addEventListener("paste",Xe,!0),kt.addEventListener("dragenter",ct,!0),kt.addEventListener("dragover",ct,!0),kt.addEventListener("drop",It,!0);const G=24,he=(be,Ye)=>{const pt=(kt.querySelector(".xterm-screen")||kt).getBoundingClientRect(),Mt=Math.floor((be-pt.left)/Math.max(1,pt.width)*ae.cols)+1,xt=Math.floor((Ye-pt.top)/Math.max(1,pt.height)*ae.rows)+1;return{col:Math.max(1,Math.min(ae.cols,Mt)),row:Math.max(1,Math.min(ae.rows,xt))}},Ie=(be,Ye={mode:null,remainder:0},tt=null,pt=null)=>{const Mt=x.current,xt=Mt?Mt.getBoundingClientRect().height:G,Qt=II({alternateScreen:ae.buffer.active.type==="alternate",readonly:s,mouseTracking:ft()}),hn=Qt==="mouse"?"mouse":tt||Qt,Dn=Ye.mode===hn?Ye.remainder+be:be,Tn=DI({mode:hn,accumulated:Dn,threshold:hn==="page"?xt:G});for(const ks of OI(Tn,pt))ks.kind==="input"?Xt.sendInput(ks.seq):Xt.action(ks.name);return{mode:hn,remainder:Tn.remainder}};let Qe=null,Ae=null,Et=null,Ct=null,Ze=!1,Ee=!1,ut={mode:null,remainder:0},Pe=null,We=null,vt=null,we=!1;const Le=750;let Ke=0;const at=()=>{vt&&clearTimeout(vt),vt=null},wt=(be,Ye)=>{const pt=(kt.querySelector(".xterm-screen")||kt).getBoundingClientRect(),Mt=Math.max(0,Math.min(ae.cols-1,Math.floor((be-pt.left)/Math.max(1,pt.width)*ae.cols))),xt=Math.max(0,Math.min(ae.rows-1,Math.floor((Ye-pt.top)/Math.max(1,pt.height)*ae.rows)));return{col:Mt,row:ae.buffer.active.viewportY+xt}},Nn=()=>{const tt=(kt.querySelector(".xterm-screen")||kt).getBoundingClientRect().height/Math.max(1,ae.rows),pt=kt.querySelector(".nc-sel-handle"),Mt=pt?pt.getBoundingClientRect().height:0;return-.3*(Mt>0?Mt:tt)},hs=(be,Ye)=>wt(be.clientX,be.clientY+Ye),Gt=be=>{const tt=(kt.querySelector(".xterm-screen")||kt).getBoundingClientRect(),pt=kt.getBoundingClientRect(),Mt=tt.width/Math.max(1,ae.cols),xt=tt.height/Math.max(1,ae.rows),Qt=Number(ae.buffer.active.viewportY)||0,hn=Math.max(0,Math.min(ae.rows-1,be.row-Qt));T({left:`${tt.left-pt.left+be.col*Mt}px`,top:`${tt.top-pt.top+hn*xt}px`,width:`${Mt}px`,height:`${xt}px`})},Hn=be=>{if(Ke=Date.now(),ds("touch"),at(),we=!1,Ze=!1,Ee||be.touches.length!==1){Ee=!0,Ze=!0,Zt=null,T(null),Qe=null,Ae=null,Et=null,Ct=null;return}if(K.current){be.preventDefault(),be.stopPropagation();const tt=wt(be.touches[0].clientX,be.touches[0].clientY),pt=ae.buffer.active.getLine(tt.row),Mt=Da({line:pt,col:tt.col,side:"start",cols:ae.cols}),xt=G0({line:pt,col:Mt,cols:ae.cols});We={row:tt.row,col:xt.start};const Qt={row:tt.row,col:xt.end};ae.clearSelection(),ds("touch"),ke(!0),ge("end"),ae.select(xt.start,tt.row,xt.end-xt.start+1),Gt(Qt);return}Qe=be.touches[0].clientY,Ae=be.touches[0].clientX,Et=Ae,Ct=Qe,ut={mode:null,remainder:0},Pe=null;const Ye={x:Ae,y:Qe};vt=setTimeout(()=>{var hn;vt=null,we=!0,Ze=!0,Zt=null,K.current=!0,j==null||j(!0);const tt=wt(Ye.x,Ye.y),pt=ae.buffer.active.getLine(tt.row),Mt=Da({line:pt,col:tt.col,side:"start",cols:ae.cols}),xt=G0({line:pt,col:Mt,cols:ae.cols});We={row:tt.row,col:xt.start};const Qt={row:tt.row,col:xt.end};ae.clearSelection(),ds("touch"),ke(!0),ge("end"),ae.select(xt.start,tt.row,xt.end-xt.start+1),Gt(Qt);try{(hn=navigator.vibrate)==null||hn.call(navigator,10)}catch{}Qe=null,Ae=null,Pe=null,ut={mode:null,remainder:0}},cI)},Pt=be=>{if(we&&We&&be.touches.length===1){be.preventDefault(),be.stopPropagation();const pt=wt(be.touches[0].clientX,be.touches[0].clientY),Mt=We.row*ae.cols+We.col,xt=pt.row*ae.cols+pt.col,Qt=Mt<=xt?"end":"start",hn=ae.buffer.active.getLine(pt.row),Dn=Da({line:hn,col:pt.col,side:Qt,cols:ae.cols}),Tn={row:pt.row,col:Dn},ks=Tn.row*ae.cols+Tn.col,ai=Mt<=ks?We:Tn;ge(Qt),ae.select(ai.col,ai.row,Math.abs(ks-Mt)+1),Gt(Tn);return}if(K.current&&We&&be.touches.length===1){be.preventDefault(),be.stopPropagation();const pt=wt(be.touches[0].clientX,be.touches[0].clientY),Mt=We.row*ae.cols+We.col,xt=pt.row*ae.cols+pt.col,Qt=Mt<=xt?"end":"start",hn=ae.buffer.active.getLine(pt.row),Dn=Da({line:hn,col:pt.col,side:Qt,cols:ae.cols}),Tn={row:pt.row,col:Dn},ks=Tn.row*ae.cols+Tn.col,ai=Mt<=ks?We:Tn;ge(Qt),ae.select(ai.col,ai.row,Math.abs(ks-Mt)+1),Gt(Tn);return}if(Qe===null||be.touches.length!==1)return;be.preventDefault(),be.stopPropagation();const Ye=be.touches[0];if(K0(Et,Ct,Ye.clientX,Ye.clientY)&&(Ze=!0,Zt=null,vt&&at()),Pe===null&&(Math.abs(Ye.clientY-Qe)>8||Math.abs(Ye.clientX-Ae)>8)&&(Pe=Math.abs(Ye.clientY-Qe)>Math.abs(Ye.clientX-Ae)),!Pe)return;const tt=Ye.clientY-Qe;Qe=Ye.clientY,ut=Ie(tt,ut,"scroll",he(Ye.clientX,Ye.clientY))},ws=()=>{at(),Qe=null,Ae=null,Et=null,Ct=null,We=null,we=!1,Ze=!1,Ee=!1,T(null),ke(!1),ut={mode:null,remainder:0},Ke=Date.now()},$i=be=>{if(Ee){Zt=null,at(),(!be.touches||be.touches.length===0)&&ws();return}const Ye=be.changedTouches&&be.changedTouches[0];if(!Ze&&!we&&!K.current&&Ye){const tt={at:Date.now(),x:Ye.clientX,y:Ye.clientY},pt=NI(se.current,Zt,tt);Zt=pt.next,pt.open&&nn()}ws()},xi=()=>{Zt=null,ws()};let Jt={mode:null,remainder:0};const hl=be=>{be.preventDefault(),be.stopPropagation(),Jt=Ie(-be.deltaY,Jt,"scroll",he(be.clientX,be.clientY))};kt.addEventListener("touchstart",Hn,{passive:!1}),kt.addEventListener("touchmove",Pt,{passive:!1,capture:!0}),kt.addEventListener("touchend",$i,{passive:!0}),kt.addEventListener("touchcancel",xi,{passive:!0});const fl=()=>{typeof window.matchMedia=="function"&&window.matchMedia($v).matches||!K.current&&se.current==="double-tap"&&nn()};kt.addEventListener("dblclick",fl);const ra=be=>{(K.current||we)&&(be.preventDefault(),be.stopPropagation())};kt.addEventListener("contextmenu",ra,!0),kt.addEventListener("wheel",hl,{passive:!1,capture:!0});let Qs=null;const pl=be=>{Date.now()-Ke>=Le&&ds("mouse"),oI(be)&&(be.preventDefault(),be.stopPropagation(),Qs={cell:wt(be.clientX,be.clientY),clientX:be.clientX,clientY:be.clientY,extendFrom:pe.current,dragged:!1})},ml=be=>{var Qt;if(!Qs){(Qt=ae.hasSelection)!=null&&Qt.call(ae)&&ft()&&(be.preventDefault(),be.stopPropagation());return}if(be.preventDefault(),be.stopPropagation(),!Qs.dragged&&!K0(Qs.clientX,Qs.clientY,be.clientX,be.clientY))return;Qs.dragged=!0;const Ye=Qs.cell,tt=wt(be.clientX,be.clientY),pt=Ye.row*ae.cols+Ye.col,Mt=tt.row*ae.cols+tt.col,xt=pt<=Mt?Ye:tt;ae.select(xt.col,xt.row,Math.abs(Mt-pt)+1)},oa=be=>{if(!Qs)return;be.stopPropagation();const{cell:Ye,extendFrom:tt,dragged:pt}=Qs;if(Qs=null,pt||!tt)return;const Mt=uI({range:tt,cell:Ye,cols:ae.cols});if(!Mt.moved)return;const xt=Mt[Mt.moved],Qt=ae.buffer.active.getLine(xt.row);xt.col=Da({line:Qt,col:xt.col,side:Mt.moved,cols:ae.cols});const hn=Y0({start:Mt.start,end:Mt.end},ae.cols);ae.select(hn.col,hn.row,hn.length)};kt.addEventListener("mousedown",pl,!0),kt.addEventListener("mousemove",ml,!0),kt.addEventListener("mouseup",oa,!0);let lr=null,Ss={x:0,y:0,type:"touch"};const Zs=()=>{lr&&(clearInterval(lr),lr=null)},ki=(be,Ye,tt)=>{if(!Vt||!Vt.fixed)return;const pt=Vt.fixed,Mt=tt==="mouse"?wt(be,Ye):hs({clientX:be,clientY:Ye},Nn()),xt=ae.buffer.active.getLine(Mt.row),Qt={row:Mt.row,col:Da({line:xt,col:Mt.col,side:Vt.which,cols:ae.cols})},hn=Math.max(0,Number(ae.buffer.active.baseY||0)+ae.rows-1),Dn=fI({moving:Qt,fixed:pt,which:Vt.which,cols:ae.cols,maxRow:hn}),Tn=Y0(V0(Dn,pt,ae.cols),ae.cols);ae.select(Tn.col,Tn.row,Tn.length);const ks=Number(ae.buffer.active.viewportY)||0,ai=_I({visibleRow:Dn.row-ks,rows:ae.rows});Zs(),!(ai===0||ae.buffer.active.type==="alternate")&&(lr=setInterval(()=>{const bo=Number(ae.buffer.active.viewportY)||0;if(ae.scrollLines(ai),(Number(ae.buffer.active.viewportY)||0)===bo){Zs();return}ki(Ss.x-Vt.offsetX,Ss.y-Vt.offsetY,Ss.type)},130))},cr=be=>{Vt&&(be.preventDefault(),Ss={x:be.clientX,y:be.clientY,type:be.pointerType||Ss.type},ki(be.clientX-Vt.offsetX,be.clientY-Vt.offsetY,Ss.type))},Pr=()=>{Vt=null,Zs(),le(null),window.removeEventListener("pointermove",cr),window.removeEventListener("pointerup",Is),window.removeEventListener("pointercancel",Is)},Is=()=>Pr();X.current={startHandleDrag:(be,Ye)=>{if(!ae.getSelectionPosition())return;Ye.preventDefault(),Ye.stopPropagation();const tt=I.current&&I.current[be],pt=kt.getBoundingClientRect();Vt={which:be,offsetX:tt?Ye.clientX-(pt.left+tt.left):0,offsetY:tt?Ye.clientY-(pt.top+tt.top):0,fixed:pe.current?be==="start"?pe.current.end:pe.current.start:null},Ss={x:Ye.clientX,y:Ye.clientY,type:Ye.pointerType||"touch"},le(be),ge(be),window.addEventListener("pointermove",cr),window.addEventListener("pointerup",Is),window.addEventListener("pointercancel",Is)}};const ru=be=>{!aI(be)||!(W.current&&W.current.term&&W.current.term.getSelection())||(be.preventDefault(),be.stopPropagation(),lt.current&&lt.current())};kt.addEventListener("keydown",ru,!0);const ur=()=>{Oe.fit(),Xt.resize(ae.cols,ae.rows)};window.addEventListener("resize",ur);const xs=window.visualViewport;let gl=xs&&Number(xs.height);const vl=()=>{const be=xs&&Number(xs.height);$t&&se.current==="double-tap"&&Number.isFinite(gl)&&Number.isFinite(be)&&be>gl+80&&Bt(),gl=be,ur()};xs&&(xs.addEventListener("resize",vl),xs.addEventListener("scroll",ur));const Jn=typeof navigator<"u"?navigator.virtualKeyboard:null,_l=()=>{var be;$t&&se.current==="double-tap"&&Number(((be=Jn==null?void 0:Jn.boundingRect)==null?void 0:be.height)||0)===0&&Bt()};(da=Jn==null?void 0:Jn.addEventListener)==null||da.call(Jn,"geometrychange",_l);let aa=null,Ci=0;return typeof ResizeObserver<"u"&&(aa=new ResizeObserver(()=>{Ci&&cancelAnimationFrame(Ci),Ci=requestAnimationFrame(ur)}),aa.observe(kt)),()=>{var be,Ye,tt;W.current=null,w&&(w.current=null),re.current&&(clearTimeout(re.current),re.current=null),c&&(c.current=()=>!1),u&&(u.current=()=>!1),h&&(h.current=()=>!1),Js.dispose(),Ms.dispose(),Xn.dispose(),Ts.dispose(),Zs(),window.removeEventListener("pointermove",cr),window.removeEventListener("pointerup",Is),window.removeEventListener("pointercancel",Is),X.current={startHandleDrag:()=>{}},kt.removeEventListener("touchstart",Hn),kt.removeEventListener("touchmove",Pt,{capture:!0}),kt.removeEventListener("touchend",$i),kt.removeEventListener("touchcancel",xi),kt.removeEventListener("dblclick",fl),kt.removeEventListener("contextmenu",ra,!0),at(),kt.removeEventListener("wheel",hl,{capture:!0}),kt.removeEventListener("mousedown",pl,!0),kt.removeEventListener("mousemove",ml,!0),kt.removeEventListener("mouseup",oa,!0),kt.removeEventListener("keydown",ru,!0),kt.removeEventListener("paste",Xe,!0),kt.removeEventListener("dragenter",ct,!0),kt.removeEventListener("dragover",ct,!0),kt.removeEventListener("drop",It,!0),window.removeEventListener("resize",ur),xs&&(xs.removeEventListener("resize",vl),xs.removeEventListener("scroll",ur)),(be=Jn==null?void 0:Jn.removeEventListener)==null||be.call(Jn,"geometrychange",_l),rn==null||rn.removeEventListener("blur",sn),(Ye=x.current)==null||Ye.removeEventListener("paste",on,!0),(tt=x.current)==null||tt.removeEventListener("keydown",un,!0),aa&&aa.disconnect(),Ci&&cancelAnimationFrame(Ci),Xt.close(),ae.dispose()}},[e,t,n,s,i,c,u,h,p,v,S]),y.useEffect(()=>{const ae=x.current,Oe=W.current?W.current.term:null;if(!ae||!Oe||!te){Be(null),fe(null),ot(null);return}const At=(ae.querySelector(".xterm-screen")||ae).getBoundingClientRect(),Lt=ae.getBoundingClientRect(),Rt=At.width/Math.max(1,Oe.cols),zt=At.height/Math.max(1,Oe.rows),ft=vI({range:te,viewportY:Number(Oe.buffer.active.viewportY)||0,rows:Oe.rows,cols:Oe.cols,cellWidth:Rt,cellHeight:zt,screenLeft:At.left-Lt.left,screenTop:At.top-Lt.top});Be(ft);let Yt=null;const $t=te[Q==="end"?"end":"start"].row;typeof Oe.buffer.active.getLine=="function"&&(Yt=Oe.buffer.active.getLine(Number($t)));const Zt=Math.max(16,Math.round(zt*2)),Bt=Yt?{...yI({range:te,side:Q,line:Yt,cols:Oe.cols}),fontSize:Zt}:null;fe(Bt);const Yn=J!==null||ve,nn=ft[Q==="end"?"end":"start"];if(!Yn||!Bt||!nn||!nn.visible){ot(null);return}const rn=(Bt.before+Bt.sel+Bt.after).length,sn=Rt*(Zt/Math.max(1,zt)),wn=Math.min(Lt.width-8,Math.round(rn*sn)+16),Ft=Math.round(Zt*1.25)+12;ot(mI({anchorLeft:nn.left,anchorTop:nn.top,hostWidth:Lt.width,hostHeight:Lt.height,bubbleWidth:wn,bubbleHeight:Ft}))},[te,Te,Q,J,ve]);const ce=dI(rt),ye=y.useRef({}),Re=(ae,Oe)=>{if(J!==ae)return ye.current[ae]={flip:Oe,ts:0},Oe;const gt=ye.current[ae]||{flip:Oe,ts:0};if(gt.flip===Oe)return ye.current[ae]=gt,Oe;const At=Date.now();return At-gt.ts<gI?gt.flip:(ye.current[ae]={flip:Oe,ts:At},Oe)};return o.jsxs("div",{className:`nc-terminal${C?" selecting":""}`,children:[o.jsx("div",{className:"nc-terminal-host",ref:x}),L&&o.jsxs("div",{className:"nc-terminal-link-overlay",children:["riconnessione…",M>0?` (${M} byte in coda)`:""]}),A&&o.jsx("div",{className:"nc-touch-selection-caret",style:A,"aria-hidden":"true"}),te&&xe&&ce.handles&&["start","end"].map(ae=>xe[ae].visible&&o.jsx("div",{className:`nc-sel-handle ${ae}${J===ae?" dragging":""}${Re(ae,xe[ae].flip)?" flip":""}${pI({startLeft:xe.start.left,endLeft:xe.end.left})?" tight":""}`,style:{left:`${xe[ae].left}px`,top:`${xe[ae].top}px`},onPointerDown:Oe=>X.current.startHandleDrag(ae,Oe),"aria-hidden":"true"},`nc-sel-handle-${ae}`)),te&&Z&&ce.magnifier&&Ve&&o.jsx("div",{className:`nc-zoom-bubble${Ve.flipped?" flipped":""}`,style:{left:`${Ve.left}px`,top:`${Ve.top}px`},"aria-hidden":"true",children:o.jsxs("pre",{className:"nc-zoom-line",style:{fontSize:`${Z.fontSize}px`},children:[o.jsx("span",{children:Z.before}),o.jsx("span",{className:"nc-zoom-sel",children:Z.sel}),o.jsx("span",{children:Z.after})]})}),P&&o.jsx("div",{className:`nc-upload-state${P.error?" error":""}`,role:"status",children:P.error?P.error:P.done?f("attach-uploaded").replace("{n}",String(P.total||0)):f("attach-upload-progress").replace("{n}",String(P.current||0)).replace("{total}",String(P.total||0))}),(V||C)&&o.jsxs("div",{className:"nc-selection-tools",children:[V?o.jsx("button",{type:"button",onClick:nt,children:D||`${f("copy")} · ${lI(typeof navigator<"u"?navigator.userAgent:"")}`}):o.jsx("span",{children:f("select-drag")}),V&&oe&&o.jsx("span",{className:"nc-selection-held",children:f("selection-held")}),V&&!oe&&Je&&o.jsx("span",{className:"nc-selection-changed",children:f("selection-changed")}),o.jsx("button",{type:"button",onClick:()=>{var ae,Oe;(Oe=(ae=W.current)==null?void 0:ae.term)==null||Oe.clearSelection(),B(""),je(!1),j==null||j(!1)},children:f("cancel")}),D===f("copy-manual")&&o.jsx("textarea",{readOnly:!0,value:V,onFocus:ae=>ae.target.select()})]})]})}let oC=new Set;function BI(e){oC=new Set(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}function $I(e){return Array.isArray(e)&&e.some(t=>oC.has(t))}function Oc(e,t,n){const s=c=>Number.isInteger(c)&&c>0&&c<65536?c:0;if(e==null)return s(n);if(!Array.isArray(e))return 0;if(e.length===0)return s(n);const i=typeof e[0]=="string"?e[0]:null;return i?s((t&&typeof t=="object"?t:{})[i]):0}const zI=6901,FI="allow-scripts allow-forms allow-popups allow-modals allow-downloads allow-pointer-lock";function Fv({cellId:e,panelUrl:t,route:n=[],panelPort:s=0,token:i,title:l,requestTimeoutMs:c=4e3}){const[u,h]=y.useState(e&&i?"requesting":"none"),[p,v]=y.useState(""),_=Array.isArray(n)?n.join("\0"):"",g=y.useMemo(()=>Array.isArray(n)?n:[],[_]),w=$I(g)?FI:null,S=y.useRef(0),N=y.useCallback(async()=>{if(!e||!i||!t){h("none");return}const D=S.current+=1;h("requesting");const O=new AbortController,P=setTimeout(()=>O.abort(),c);try{const z=await C5(i,g,e,{signal:O.signal});if(clearTimeout(P),D!==S.current)return;if(z.ok){let A="/";try{A=new URL(t).pathname||"/"}catch{}const T=s?`http://127.0.0.1:${s}`:bn(g);v(`${T}/panel/${encodeURIComponent(e)}${A}?ticket=${encodeURIComponent(z.ticket)}`),h("ready")}else h(z.cause)}catch(z){if(clearTimeout(P),D!==S.current)return;h(z&&z.name==="AbortError"?"timeout":"unreachable")}},[e,t,g,s,i,c]),C=y.useCallback(()=>{h(D=>D==="ready"?"loaded":D)},[]),j=y.useCallback(()=>{h(D=>D==="ready"||D==="loaded"?"frame-error":D)},[]),E=y.useRef(null),R=y.useCallback(D=>{D&&(E.current=D,D.onload=C,D.onerror=j)},[C,j]);y.useEffect(()=>{N()},[N]);const W=y.useMemo(()=>{try{return Number(new URL(t).port)===zI}catch{return!1}},[t])&&g.length===0,[$,Y]=y.useState(!1),[q,K]=y.useState("");y.useEffect(()=>{const D=O=>{const P=E.current;if(!P||!P.contentWindow||O.source!==P.contentWindow)return;let z=null;try{z=new URL(p,window.location.href).origin}catch{return}!z||O.origin!==z||!O.data||O.data.type!=="nc-panel-unreachable"||h(A=>A==="ready"||A==="loaded"?"unreachable":A)};return window.addEventListener("message",D),()=>window.removeEventListener("message",D)},[p]);const se=y.useCallback(async()=>{if(!i||$)return;Y(!0),K("");let D=!1;try{const O=await _1(i,!0);O&&O.ok===!1&&(K(O.error||"comando fallito"),D=!0)}catch(O){K(String(O&&O.message||O)),D=!0}Y(!1),D||N()},[i,$,N]),V=(D,O=!0,P=null)=>o.jsxs("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:[o.jsx("span",{children:f(D)}),O&&o.jsxs("span",{className:"nc-cellpanel-actions",children:[P,o.jsx("button",{type:"button",title:f("panel-retry"),onClick:()=>N(),children:f("panel-retry")})]})]}),B=W?o.jsx("button",{type:"button",disabled:$,onClick:se,children:f("panel-start-desktop")}):null;return u==="none"||u==="no-panel"?V("panel-none",!1):u==="requesting"?o.jsx("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:o.jsx("span",{children:f("panel-checking")})}):u==="not-granted"?V("panel-not-granted",!1):u==="node-refused"?V("panel-node-refused",!1):u==="unauthorized"?V("panel-unauthorized",!1):u==="denied"?V("panel-denied"):u==="timeout"?V("panel-timeout"):u==="unreachable"?o.jsxs("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:[o.jsxs("span",{children:[f("panel-unreachable"),q?` — ${q}`:""]}),o.jsxs("span",{className:"nc-cellpanel-actions",children:[B,o.jsx("button",{type:"button",title:f("panel-retry"),onClick:()=>N(),children:f("panel-retry")})]})]}):u==="frame-error"?V("panel-frame-error",!0,B):o.jsxs(o.Fragment,{children:[u==="ready"&&o.jsx("div",{className:"nc-cellpanel-loading",role:"status",children:f("panel-frame-loading")}),o.jsx("iframe",{ref:R,className:"nc-cellpanel nc-cellpanel-frame","data-frame-state":u,src:p,title:l||f("panel"),allowFullScreen:!0,...w?{sandbox:w}:{}})]})}const HI=1800*1e3;function jg(e,t,n=Date.now()){const s=Number(t);if(!Number.isFinite(s)||s<=0)return"";const i=n-s;if(i<0||i>HI)return"";if(i<60*1e3)return`${e("cell-activity")} ${e("cell-activity-now")}`;const l=Math.floor(i/6e4);return l<60?`${e("cell-activity")} ${l}m`:`${e("cell-activity")} ${Math.floor(l/60)}h`}function Lg(e,t){if(!t||typeof t!="object")return"";const n=[];return Number.isInteger(t.contextFreePct)&&n.push(`${e("cell-tele-ctx")} ${t.contextFreePct}% ${e("cell-tele-free")}`),Number.isInteger(t.tier5hUsedPct)&&n.push(`${e("cell-tele-5h")} ${t.tier5hUsedPct}%`),Number.isInteger(t.tier7dUsedPct)&&n.push(`${e("cell-tele-7d")} ${t.tier7dUsedPct}%`),n.join(" · ")}function Hv({row:e,token:t,panelPort:n=0,liveHost:s=null,onLiveHostApplied:i,source:l,onSourceChange:c,fontSize:u,readOnly:h=!1,chrome:p=!0}){const v=q=>c&&c(q),_=y.useRef(()=>{}),g=y.useRef(()=>!1),w=y.useRef(()=>{}),S=y.useRef(!1),[N,C]=y.useState(!1),[j,E]=y.useState(""),[R,x]=y.useState(!1),W=!!(s&&s.cell&&s.cell===e.cellName),$=async()=>{x(!0);const q=await gh({action:W?"remove":"use",cellId:e.cellName,route:e.route||[],token:t,api:{getLiveHost:K=>hh(t,K),designateHostCell:(K,se,V)=>fh(t,K,se,V),clearHostCell:(K,se)=>ph(t,K,se)}});x(!1),E(f(q.messageKey).replace("{cell}",q.hostCell||e.cellName)),q.ok&&i&&i({route:e.route||[],hostCell:q.hostCell,revision:q.revision})},Y=[["preview",f("cell-peek-preview")],["stream",f("cell-peek-stream")],...e.panelUrl?[["panel",f("cell-peek-panel")]]:[]];return o.jsxs(o.Fragment,{children:[p&&o.jsx("div",{className:"nc-peek-sorgenti",role:"tablist",children:Y.map(([q,K])=>o.jsx("button",{type:"button",role:"tab","aria-selected":l===q,className:`nc-peek-sorgente${l===q?" attiva":""}`,onClick:()=>v(q),children:K},q))}),p&&o.jsxs("div",{className:"nc-peek-host",children:[o.jsx("button",{type:"button",className:"nc-peek-host-btn",disabled:R,onClick:$,children:f(W?"live-host-action-remove":"live-host-action-use")}),j&&o.jsx("div",{className:"nc-peek-notice",role:"status",children:j})]}),l==="stream"?o.jsx("div",{className:"nc-peek-stream",children:o.jsx(kc,{session:e.session,node:e.node||void 0,token:t,readonly:h,takeSize:!1,focused:!0,sendRef:_,composerRef:g,actionRef:w,ctrlRef:S,setCtrlArmed:C,fontSize:u},`peek:${e.key}`)}):l==="panel"?o.jsx(Fv,{cellId:e.cellName,panelUrl:e.panelUrl,route:e.route||[],panelPort:n,token:t,title:e.cellName}):o.jsxs(o.Fragment,{children:[o.jsx("pre",{className:"nc-peek-testo",children:e.preview||f("cell-peek-vuoto")}),[jg(f,e.activity),Lg(f,e.telemetry)].filter(Boolean).join(" · ")&&o.jsx("small",{className:"nc-cell-switcher-telemetry",children:[jg(f,e.activity),Lg(f,e.telemetry)].filter(Boolean).join(" · ")})]})]})}function aC({row:e,token:t,initialSource:n="preview",panelPort:s=0,onClose:i,liveHost:l=null,onLiveHostApplied:c}){const[u,h]=y.useState(n==="panel"&&!e.panelUrl?"preview":n);return o.jsx(P1,{title:e.cellName,subtitle:[e.nodeLabel,e.subtitle].filter(Boolean).join(" · "),onClose:i,children:o.jsx(Hv,{row:e,token:t,panelPort:s,liveHost:l,onLiveHostApplied:c,source:u,onSourceChange:h})})}const Bc="nc_order_journal_v1",UI=50,Op="__corrupt",WI=200,qI=200,KI=["reason","key","position","source","target","note"],VI=["before","after","visible"],lC=e=>String(e).slice(0,qI),GI=e=>Array.isArray(e)?e.slice(0,WI).map(lC):void 0,Sh=e=>{try{return e||globalThis.localStorage}catch{return null}};function YI(e){const t={t:Date.now()};for(const n of KI)e[n]!==void 0&&e[n]!==null&&(t[n]=lC(e[n]));for(const n of VI){const s=GI(e[n]);s&&(t[n]=s)}return t}function Uv(e,t,n){const s=Sh(n);if(!s||t===null||t===void 0)return!1;try{if(s.getItem(e+Op)===t)return!1;s.setItem(e+Op,t)}catch{return!1}return e!==Bc&&er({reason:"corrupt-preserved",key:e,note:`${String(t).length} caratteri conservati in ${e}${Op}`},s),!0}function Rg(e){const t=Sh(e);if(!t)return[];let n=null;try{n=t.getItem(Bc)}catch{return[]}if(n===null)return[];try{const s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return Uv(Bc,n,t),[]}function er(e,t){const n=Sh(t);if(!(!n||!e))try{const s=[...Rg(n),YI(e)].slice(-UI);n.setItem(Bc,JSON.stringify(s))}catch{}}function XI(e){const t=Sh(e);if(t)try{t.removeItem(Bc)}catch{}}function Ir(e,{parse:t,fallback:n,storage:s}={}){let i=s;try{i=i||globalThis.localStorage}catch{return n()}let l=null;try{l=i.getItem(e)}catch{return n()}if(l==null)return n();try{const c=t(JSON.parse(l));if(c!==void 0)return c}catch{}return Uv(e,l,i),n()}function wi(e,t,{storage:n}={}){let s=n;try{s=s||globalThis.localStorage}catch(i){return i}try{const i=s.getItem(e);if(i!=null)try{JSON.parse(i)}catch{Uv(e,i,s)}return s.setItem(e,JSON.stringify(t)),null}catch(i){return i instanceof Error?i:new Error(String(i))}}const JI=["all","pinned","active","off","technical"],ea="nc_sidebar_views_v1",ta="nc_sidebar_order_v1";function cC(e){return JI.includes(e)?e:"all"}function QI(e,t=[],n="all"){const s=cC(n);return s==="technical"?e.technical===!0:e.technical===!0?!1:s==="pinned"?t.includes(e.key):s==="active"?!!e.live:s==="off"?!e.live:!0}function ZI(e,t,n=[],s=[]){const i=n.indexOf(e.key),l=n.indexOf(t.key),c=i===-1?Number.MAX_SAFE_INTEGER:i,u=l===-1?Number.MAX_SAFE_INTEGER:l,h=s.indexOf(e.key),p=s.indexOf(t.key),v=h===-1?Number.MAX_SAFE_INTEGER:h,_=p===-1?Number.MAX_SAFE_INTEGER:p;return c-u||v-_||+!!t.live-+!!e.live||+!!t.fresh-+!!e.fresh||Number(t.activity||0)-Number(e.activity||0)||String(e.label||"").localeCompare(String(t.label||""))||String(e.key||"").localeCompare(String(t.key||""))}function bc(e=globalThis.localStorage){return Ir(ta,{storage:e,fallback:()=>({}),parse:t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const n={};for(const[s,i]of Object.entries(t).slice(0,64)){if(typeof s!="string"||!s||s.length>160||!Array.isArray(i))continue;const l=[...new Set(i.filter(c=>typeof c=="string"&&c&&c.length<=256))].slice(0,128);l.length&&(n[s]=l)}return n}})}function Di(e,t){return Array.isArray(e==null?void 0:e[t])?e[t]:[]}function eP(e,t=globalThis.localStorage){return wi(ta,e,{storage:t}),e}function tP(e,t,n,s,i=[]){if(typeof t!="string"||!t||n===s)return e;const l=[...new Set(i.filter(g=>typeof g=="string"&&g))];if(!l.includes(n)||!l.includes(s))return e;const c=Di(e,t),u=[...c,...l.filter(g=>!c.includes(g))],h=u.indexOf(n),p=u.indexOf(s);u.splice(h,1);const v=u.indexOf(s),_=h<p?v+1:v;return u.splice(_,0,n),{...e,[t]:u}}function Td(e=globalThis.localStorage){return Ir(ea,{storage:e,fallback:()=>({}),parse:t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0})}function Ag(e,t){var n,s;return{open:((n=e==null?void 0:e[t])==null?void 0:n.open)!==!1,filter:cC((s=e==null?void 0:e[t])==null?void 0:s.filter)}}function nP(e,t=globalThis.localStorage){return wi(ea,e,{storage:t}),e}function Z0(e,t=""){const n=String(t||"").trim().toLocaleLowerCase();return n?[e.label,e.key,e.searchText].filter(Boolean).join(" ").toLocaleLowerCase().includes(n):!0}function fo(e=[],t=[],n="all",s=[]){return[...e].filter(i=>QI(i,t,n)).sort((i,l)=>ZI(i,l,t,s))}function Fn(){return[y.useSyncExternalStore(Aj,Jo,Jo),Rj]}function sP(e){const t=Array.isArray(e)?e:[],n=t.filter(i=>i&&i.standard===!0),s=t.filter(i=>!(i&&i.standard===!0));return{standard:n,others:s}}function xh({engines:e}){const{standard:t,others:n}=sP(e);return o.jsxs(o.Fragment,{children:[t.length>0&&o.jsx("optgroup",{label:f("fleet-engine-group-standard"),children:t.map(s=>o.jsx("option",{value:s.id,children:s.label||s.id},s.id))}),n.length>0&&o.jsx("optgroup",{label:f("fleet-engine-group-other"),children:n.map(s=>o.jsx("option",{value:s.id,children:s.label||s.id},s.id))})]})}function Gd({cell:e,token:t,route:n=[],onConfirm:s,onClose:i}){var z,A;Fn();const l=!!(e&&e.active),c=Array.isArray(n)?n.join("/"):"",[u,h]=y.useState([]),[p,v]=y.useState(!1);y.useEffect(()=>{let T=!0;return(async()=>{if(t)try{const L=await rl(t,c?c.split("/"):[]);if(!T)return;if(v(L.provider==="builtin"&&(L.capabilities||[]).includes("edit")),L.provider==="builtin"&&(L.capabilities||[]).includes("definitions")){const H=await uh(t,c?c.split("/"):[]);if(!T)return;const M=new Map((L.engines||[]).map(U=>[U.id,U]));h((H.engines||[]).map(U=>{var ee,re,oe,je,te,ie,pe;return{id:U.id,label:U.label||U.id,client:((ee=U.managed)==null?void 0:ee.client)||"",models:[...new Set([...((re=M.get(U.id))==null?void 0:re.models)||[],...((oe=U.managedInfo)==null?void 0:oe.models)||[]])].filter(Boolean),defaultModel:((je=U.managed)==null?void 0:je.model)||((te=U.managedInfo)==null?void 0:te.defaultModel)||"",policyDefault:((ie=U.managed)==null?void 0:ie.permissionPolicy)||((pe=U.managed)!=null&&pe.client&&U.managed.client==="claude"?"unsafe":"standard")}}))}}catch{}})(),()=>{T=!1}},[t,c]);const _=(e==null?void 0:e.engine)||((z=u[0])==null?void 0:z.id)||"",g=T=>(e==null?void 0:e.models)&&e.models[T]||"",w=T=>{const L=(e==null?void 0:e.permissionPolicies)&&e.permissionPolicies[T];if(L==="standard"||L==="unsafe")return L;const H=u.find(M=>M.id===T);return H?H.policyDefault:"standard"},[S,N]=y.useState(_),[C,j]=y.useState((e==null?void 0:e.model)||""),E=(e==null?void 0:e.permissionPolicy)==="standard"||(e==null?void 0:e.permissionPolicy)==="unsafe"?e.permissionPolicy:((A=e==null?void 0:e.permissionPolicies)==null?void 0:A[e==null?void 0:e.engine])||"",[R,x]=y.useState(E),[W,$]=y.useState((e==null?void 0:e.boot)??!0),[Y,q]=y.useState(!1),[K,se]=y.useState(null);y.useEffect(()=>{u.length&&(N(T=>T||_),j(T=>T||g((e==null?void 0:e.engine)||_)||""),x(T=>T==="standard"||T==="unsafe"?T:w((e==null?void 0:e.engine)||_)))},[u.length]);const V=y.useMemo(()=>u.find(T=>T.id===S)||null,[u,S]),B=!!(V&&["claude","codex","codex-vl","agy","kimi"].includes(V.client)),D=(V==null?void 0:V.client)==="shell";function O(T){N(T);const L=u.find(H=>H.id===T);j(g(T)||(L==null?void 0:L.defaultModel)||""),x(w(T))}async function P(T){T.preventDefault(),q(!0),se(null);try{if(l)await s({action:"down",boot:W});else{const L=R==="standard"||R==="unsafe"?R:(V==null?void 0:V.policyDefault)||"standard";await s({action:"up",...p?{engine:S,model:C||"",...B?{permissionPolicy:L}:(V==null?void 0:V.client)==="pi"?{permissionPolicy:"standard"}:{}}:{},boot:W})}i()}catch(L){se(String(L&&L.message||L)),q(!1)}}return o.jsx("div",{className:"nc-sheet-overlay nc-launch-overlay",onClick:i,children:o.jsxs("form",{className:"nc-sheet nc-power-sheet nc-launch-sheet",onClick:T=>T.stopPropagation(),onSubmit:P,children:[o.jsxs("div",{className:"nc-sheet-head",children:[o.jsx("b",{children:e==null?void 0:e.cell}),o.jsx("span",{className:"nc-sheet-state",children:f(l?"state-on":"state-off")})]}),l?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"nc-power-config",children:[o.jsx("span",{children:f("engine")}),o.jsx("b",{children:(e==null?void 0:e.engine)||"—"}),(e==null?void 0:e.model)&&o.jsxs("small",{children:[f("model"),": ",e.model]}),o.jsx("small",{children:f("power-on-hint")})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:W,onChange:T=>$(T.target.checked)}),f("remove-boot")]})]}):o.jsxs(o.Fragment,{children:[p&&u.length>0?o.jsxs("div",{className:"nc-launch-fields",children:[o.jsxs("label",{className:"nc-field",children:[f("engine"),o.jsx("select",{value:S,onChange:T=>O(T.target.value),children:o.jsx(xh,{engines:u})})]}),!D&&o.jsxs("label",{className:"nc-field",children:[f("model"),o.jsx("input",{value:C,list:"nc-launch-models",placeholder:f("model-default"),onChange:T=>j(T.target.value)}),o.jsx("datalist",{id:"nc-launch-models",children:((V==null?void 0:V.models)||[]).map(T=>o.jsx("option",{value:T},T))})]}),B?o.jsxs("label",{className:"nc-field",children:[f("permissions"),o.jsxs("select",{value:R,onChange:T=>x(T.target.value),children:[o.jsx("option",{value:"standard",children:f("fleet-standard-permissions")}),o.jsx("option",{value:"unsafe",children:f("fleet-unsafe-permissions")})]})]}):o.jsx("small",{className:"nc-note",children:f("fleet-standard-permissions")}),B&&R==="unsafe"&&o.jsx("small",{className:"nc-err",children:f("fleet-unsafe-warning")}),o.jsx("small",{className:"nc-note",children:f(D?"fleet-shell-launch-help":"launch-engine-help")})]}):o.jsxs("div",{className:"nc-power-config",children:[o.jsx("span",{children:f("engine")}),o.jsx("b",{children:(e==null?void 0:e.engine)||"—"}),(e==null?void 0:e.model)&&o.jsxs("small",{children:[f("model"),": ",e.model]}),o.jsx("small",{children:f("launch-unavailable-hint")})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:W,onChange:T=>$(T.target.checked)}),f("boot-persist")]})]}),K&&o.jsx("div",{className:"nc-err",children:K}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:i,children:f("cancel")}),o.jsx("button",{type:"submit",className:"nc-btn primary",disabled:Y,children:f(Y?l?"power-stopping":"power-starting":l?"power-off":"save-and-start")})]})]})})}const eS=/^[a-z0-9-]{1,32}$/;function $c(e,t){const n=Array.isArray(e)?e:[];return n.length?`${n.map(encodeURIComponent).join("/")}:${t}`:String(t)}function iP(e,t,n){const s={};for(const i of Array.isArray(t)?t:[]){const l=Array.isArray(i==null?void 0:i.route)?i.route:typeof(i==null?void 0:i.name)=="string"?[i.name]:[];if(!l.length)continue;const c=l.join("/"),u=i.status==="up"||i.tunnel&&i.tunnel.status==="up",h=i.status==="passive"||i.tunnel&&i.tunnel.status==="passive";!u&&!h&&i.status!=="pending"&&!i.checking&&(s[c]=e&&e[c]||n)}return s}function Mg(e,t,n,s=!1){return!e||!Array.isArray(e.cells)?[]:e.cells.map(i=>({...i,route:t,key:`${n}:${i.tmuxSession||i.cell}`,...s?{preserved:!0}:{}}))}function nc(e,t,n){if(!e)return{};const s=Tg(e);return!wc(e,s)||s!=="stale"?{}:{cells:Mg(e,t,n,!0),fleetState:"stale",fleetAvailable:!1,cellsPreserved:!0}}function Tg(e){return(e==null?void 0:e.fleetState)==="stale"?"stale":(e==null?void 0:e.fleetState)==="disabled"?"disabled":(e==null?void 0:e.available)===!0&&Array.isArray(e.cells)?"available":(e==null?void 0:e.available)===!1?"disabled":"stale"}function wc(e,t){return(t==="available"||t==="stale")&&Array.isArray(e==null?void 0:e.cells)}function tS(e,t){const n=e?t&&t.at:t&&t.lastGoodAt;return Number.isFinite(n)?n:null}function nS({nodes:e,topology:t,remote:n,down:s,fleet:i,aliases:l,pendingReads:c,previousGroups:u}={}){var S,N,C,j;const h=[],p=new Set,v=new Set,_=(E,R)=>!!(c&&(c.has(E)||c.has(`${E}#${R}`))),g=(E,R,x)=>Array.isArray(u)?u.find(W=>W.name===R&&W.instanceId===x&&(Array.isArray(W.route)?W.route.join("/"):"")===E):null;function w(E,R){const x=g(E,R.name,R.instanceId),W=_(E,"sessions"),$=_(E,"fleet"),Y=(n==null?void 0:n[E])||(W&&x?{sessions:x.sessionsAvailable?x.sessions:void 0,at:x.verifiedAt,lastGoodAt:x.verifiedAt,...x.sessionsAvailable===!1&&x.cause?{cause:x.cause}:{}}:null),q=(i==null?void 0:i[E])||($&&x?{available:x.fleetAvailable,cells:x.cells,fleetState:x.fleetState,capabilities:x.capabilities,engines:x.engines,provider:x.fleetProvider,cellsPreserved:x.cellsPreserved,...x.fleetState==="stale"&&x.cause?{cause:x.cause}:{}}:null);return(W||$)&&(R.checking=!0,R.sessionsPending=W,R.fleetPending=$),{r:Y,f:q,previous:x,pending:W||$,rereading:x&&(W||$)&&!(n!=null&&n[E])&&!(i!=null&&i[E])}}for(const E of Array.isArray(e)?e:[]){if(!E||typeof E.name!="string"||!eS.test(E.name)||E.direction==="inbound"&&E.shared!==!0)continue;const R=[E.name],x=E.name;p.add(x);const W=((S=E.tunnel)==null?void 0:S.status)||"unknown",$=W==="up",Y={name:E.name,label:E.label||E.name,originalLabel:E.label||E.name,alias:null,route:R,direct:!0,instanceId:E.nodeId||null,shared:E.shared===!0,stale:E.stale===!0,tunnelStatus:W,sessions:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:E.health||null,direction:E.direction||"outbound",roles:E.roles||null,rolesKnown:E.rolesKnown===!0};if(E.nodeId&&v.add(E.nodeId),!E.nodeId&&E.paired===!1){h.push({...Y,status:"needs-repair",downSince:s&&s[x]||null,...nc(i&&(i[x]||i[E.name]),R,x)});continue}if(((N=E.health)==null?void 0:N.auth)==="failed"||W==="degraded"&&((C=E.health)==null?void 0:C.status)==="degraded"){h.push({...Y,status:"needs-repair",downSince:s&&s[x]||null,...nc(i&&(i[x]||i[E.name]),R,x)});continue}if(W==="passive"||((j=E.health)==null?void 0:j.status)==="passive"){h.push({...Y,status:"passive",downSince:null,...nc(i&&(i[x]||i[E.name]),R,x)});continue}if(!$){h.push({...Y,status:"down",downSince:s&&s[x]||null,...nc(i&&(i[x]||i[E.name]),R,x)});continue}const{r:q,f:K,previous:se,pending:V,rereading:B}=w(x,Y);if(B){h.push({...se,checking:!0,sessionsPending:Y.sessionsPending,fleetPending:Y.fleetPending});continue}const D=!!(q&&!q.error&&Array.isArray(q.sessions)),O=Tg(K),P=O==="available"&&wc(K,O),z=wc(K,O);if(V&&!q&&!K){h.push({...Y,status:(se==null?void 0:se.status)||"pending",pendingRead:!0,verifiedAt:(se==null?void 0:se.verifiedAt)??null});continue}if(!D&&!z){h.push({...Y,status:V?(se==null?void 0:se.status)||"pending":"unreachable",cause:q&&q.cause||null});continue}const A=(D?q.sessions:[]).filter(H=>H&&typeof H.name=="string"&&H.name).map(H=>({...H,node:x,route:R,key:`${x}:${H.name}`})),T=Mg(K,R,x),L=new Set(T.map(H=>H.tmuxSession).filter(Boolean));h.push({...Y,status:"up",sessions:A,cells:T,unmanaged:A.filter(H=>!L.has(H.name)),fleetAvailable:P,fleetState:O,...K!=null&&K.cellsPreserved?{cellsPreserved:!0}:{},...q!=null&&q.cause||K!=null&&K.cause?{cause:(q==null?void 0:q.cause)||(K==null?void 0:K.cause)}:{},capabilities:K&&K.capabilities||[],engines:K&&K.engines||[],fleetProvider:K&&K.provider||null,sessionsAvailable:D,inventoryPartial:!D,verifiedAt:tS(D,q)})}for(const E of Array.isArray(t)?t:[]){if(!E||!Array.isArray(E.route)||E.route.length<1||E.route.some(L=>!eS.test(L)))continue;const R=E.route.join("/");if(p.has(R)||E.instanceId&&v.has(E.instanceId))continue;E.instanceId&&v.add(E.instanceId);const x=E.label||E.route.join(" › "),W=E.instanceId&&l&&typeof l[E.instanceId]=="string"?l[E.instanceId]:null,$={name:E.name,label:W||x,originalLabel:x,alias:W,route:[...E.route],direct:!1,instanceId:E.instanceId||null,shared:!0,stale:E.stale===!0,tunnelStatus:null,sessions:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:E.health||null,lastSeen:E.lastSeen||null};if(E.stale){h.push({...$,status:"offline",downSince:s&&s[R]||E.lastSeen||null,...nc(i&&i[R],E.route,R)});continue}const{r:Y,f:q,previous:K,pending:se,rereading:V}=w(R,$);if(V){h.push({...K,checking:!0,sessionsPending:$.sessionsPending,fleetPending:$.fleetPending});continue}const B=!!(Y&&!Y.error&&Array.isArray(Y.sessions)),D=Tg(q),O=D==="available"&&wc(q,D),P=wc(q,D);if(se&&!Y&&!q){h.push({...$,status:(K==null?void 0:K.status)||"pending",pendingRead:!0,verifiedAt:(K==null?void 0:K.verifiedAt)??null});continue}if(!B&&!P){h.push({...$,status:se?(K==null?void 0:K.status)||"pending":"unreachable",downSince:s&&s[R]||null,cause:Y&&Y.cause||null});continue}const z=(B?Y.sessions:[]).filter(L=>L&&typeof L.name=="string"&&L.name).map(L=>({...L,node:R,route:E.route,key:`${R}:${L.name}`})),A=Mg(q,E.route,R),T=new Set(A.map(L=>L.tmuxSession).filter(Boolean));h.push({...$,status:"up",sessions:z,cells:A,unmanaged:z.filter(L=>!T.has(L.name)),fleetAvailable:O,fleetState:D,...q!=null&&q.cellsPreserved?{cellsPreserved:!0}:{},...Y!=null&&Y.cause||q!=null&&q.cause?{cause:(Y==null?void 0:Y.cause)||(q==null?void 0:q.cause)}:{},capabilities:q&&q.capabilities||[],engines:q&&q.engines||[],fleetProvider:q&&q.provider||null,lastSeen:E.lastSeen||null,sessionsAvailable:B,inventoryPartial:!B,verifiedAt:tS(B,Y)})}return h.sort((E,R)=>E.label.localeCompare(R.label))}const Ig="nc_route_alias_v1",rP="nexuscrew-roster-preferences",sS="nc_pins",oP=/^[a-f0-9]{16,64}$/;let Wv=new Map;const aP=e=>Array.isArray(e==null?void 0:e.route)&&e.route.length?e.route.join("/"):String((e==null?void 0:e.name)||"");function Bp(e,t=Wv){if(e==="local"||typeof e!="string")return e;const n=t.get(e);return n?`id:${n}`:e}const iS=(e,t,n)=>typeof e=="string"&&e.startsWith(`${t}:`)?`${n}:${e.slice(t.length+1)}`:e,rS=e=>[...new Set(e)];function $p(e,t){return Ir(e,{storage:t,fallback:()=>({}),parse:n=>n&&typeof n=="object"&&!Array.isArray(n)?n:void 0})}function Oa(e,t=Wv){const n={...e||{}};for(const[s,i]of t)e&&e[`id:${i}`]!==void 0&&(n[s]=e[`id:${i}`]);return n}function lP(e,{storage:t=globalThis.localStorage}={}){const n=new Map,s=new Map;for(const N of Array.isArray(e)?e:[]){const C=String((N==null?void 0:N.instanceId)||""),j=aP(N);if(!(oP.test(C)&&j)||n.has(j))continue;n.set(j,C);const E=N.status==="up"&&N.stale!==!0;(!s.has(C)||E&&!s.get(C).up)&&s.set(C,{name:j,up:E})}if(Wv=n,!n.size)return!1;const i=$p(Ig,t);let l=$p(ta,t),c=$p(ea,t),u=Ir(sS,{storage:t,fallback:()=>[],parse:N=>Array.isArray(N)?N:void 0});const h={...i},p={...l},v={...c};let _=[...u];const g={aliases:!1,orders:!1,views:!1,pins:!1};for(const[N,{name:C}]of s){const j=`id:${N}`,E=typeof i[N]=="string"?i[N]:"",R=E&&E!==C&&(!n.has(E)||n.get(E)===N)?E:"";R&&(_=rS([..._,...u.filter(x=>x.startsWith(`${R}:`)).map(x=>iS(x,R,C))]),g.pins=g.pins||_.length!==u.length);for(const[x,W,$]of[[l,p,"orders"],[c,v,"views"]]){const Y=x[j]!==void 0?x[j]:R&&x[R]!==void 0?x[R]:x[C];if(Y===void 0)continue;let q=Y;$==="orders"&&Array.isArray(q)&&(q=rS(q.map(K=>R?iS(K,R,C):K))),JSON.stringify(W[j])!==JSON.stringify(q)&&(W[j]=q,g[$]=!0)}i[N]!==C&&(h[N]=C,g.aliases=!0),R&&er({reason:"route-renamed",key:N,note:`${R} -> ${C}`})}const w=[];g.pins&&w.push(wi(sS,_,{storage:t})),g.orders&&w.push(wi(ta,p,{storage:t})),g.views&&w.push(wi(ea,v,{storage:t})),g.aliases&&w.push(wi(Ig,h,{storage:t}));const S=Object.values(g).some(Boolean);if(S)try{window.dispatchEvent(new Event(rP))}catch{}return S&&w.every(N=>!N)}const uC="nc_last_roster_v1",cP=64,uP=["cell","tmuxSession","engine","model","label","boot"],dC=e=>Ir(uC,{storage:e,fallback:()=>({}),parse:t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0});function Za(e,t,n=globalThis.localStorage){if(!e)return;const s={...dC(n)};!Array.isArray(t)||!t.length?delete s[e]:s[e]={at:Date.now(),cells:t.slice(0,cP).filter(i=>i&&typeof i.cell=="string").map(i=>Object.fromEntries(uP.filter(l=>i[l]!==void 0&&i[l]!==null).map(l=>[l,i[l]])))},wi(uC,s,{storage:n})}function qv(e,t=globalThis.localStorage){const n=e?dC(t)[e]:null;return!n||!Array.isArray(n.cells)?[]:n.cells.map(s=>({...s,tmux:!1,active:!1,preserved:!0,degraded:!1}))}function hC(e,t={}){if(!e||typeof e!="object")return null;const n=typeof e.nodeId=="string"?e.nodeId:"";if(!n)return null;const s=typeof e.label=="string"&&e.label.trim()||typeof e.cell=="string"&&e.cell.trim()||n,i=Array.isArray(t.route)?[...t.route]:[];return{kind:"vl",nodeId:n,name:n,label:s,cell:e.cell??null,paired:!!e.pairedAt,online:!!e.online,lastSeen:e.lastSeen??null,generation:e.generation??null,version:e.version??null,health:e.health??null,session:e.session??null,capabilities:Array.isArray(e.capabilities)?e.capabilities:[],inflight:e.inflight??null,lastAck:e.lastAck??null,canManage:!!e.canManage,route:i,isLocal:i.length===0,ownerInstanceId:typeof t.instanceId=="string"?t.instanceId:null,ownerLabel:typeof t.label=="string"&&t.label?t.label:null}}function dP(e){var n;const t=[];for(const s of Array.isArray(e)?e:[]){if(!s||s.kind!=="vl"||!s.nodeId)continue;const i=s.online===!0,l=i&&((n=s.session)==null?void 0:n.attached)===!0,c=s.ownerInstanceId||"local";t.push({kind:"vl",name:`vl-${s.nodeId.slice(0,8)}`,label:s.label,route:Array.isArray(s.route)?[...s.route]:[],instanceId:null,direct:!1,status:i?"up":"offline",downSince:i?null:s.lastSeen??null,sessions:l?[{key:`vl:${c}:${s.nodeId}`,name:s.session.profile,attached:!0}]:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:s.health??null,stale:s.stale===!0,fleetState:s.stale===!0?"stale":null,peer:s})}return t}function fC(e,t){const n=e&&Array.isArray(e.nodes)?e.nodes:[],s=new Set([t]),i=[];for(const l of n){const c=l&&typeof l.instanceId=="string"?l.instanceId:"";if(!c||s.has(c)||l.stale===!0||!Array.isArray(l.route)||l.route.length===0)continue;s.add(c);const u=typeof l.label=="string"&&l.label||typeof l.name=="string"&&l.name||l.route.join(" › ");i.push({instanceId:c,route:[...l.route],label:u})}return i}const hP=/fleet\.json/;function kh({fs:e=null,error:t=null}={}){if(t)return{kind:"stale"};if(!e)return{kind:"stale"};if(e.available===!0)return{kind:"data",cells:e.cells||[],capabilities:e.capabilities||[]};const n=typeof e.reason=="string"?e.reason:"";return typeof e.migrationCode=="string"&&e.migrationCode?{kind:"disabled",reason:n||null}:hP.test(n)?{kind:"stale"}:{kind:"disabled",reason:n||null}}const pC={baseMs:4e3,capMs:6e4},mC="peer-assente",gC="peer-nega",vC="rotta-inesistente";function zp(e){const t=e&&e.status;return t===403?gC:t===404?vC:mC}function fP(e,{baseMs:t,capMs:n}=pC){return!Number.isFinite(e)||e<1?0:Math.min(t*2**(e-1),n)}function oS(e,t,n){const s=e&&e[t];return!s||!(s.failures>=1)?!0:n>=s.nextAtMs}function aS(e,t,n,s,i=pC){const c=(e&&e[t]||{failures:0}).failures+1;return{...e,[t]:{failures:c,cause:n,nextAtMs:s+fP(c,i)}}}function lS(e,t){if(!e||!(t in e))return e;const n={...e};return delete n[t],n}const pP=4e3,Kv=600*1e3,_C="nc-sticky-owners-v1";function mP(){try{const e=localStorage.getItem(_C);if(!e)return null;const t=JSON.parse(e);return!t||!Array.isArray(t.nodes)||!Array.isArray(t.topology)?null:t}catch{return null}}function gP(e){try{localStorage.setItem(_C,JSON.stringify(e))}catch{}}function fd(e,t,n,s,i){if(!t){for(const c of e.values())c.data={...c.data,stale:!0};return e}const l=new Map(n.map(c=>[s(c),c]));for(const[c,u]of e)l.has(c)?(u.data=l.get(c),u.missingSince=null,l.delete(c)):(u.missingSince??(u.missingSince=i),i-u.missingSince>Kv?e.delete(c):u.data={...u.data,stale:!0});for(const[c,u]of l)e.set(c,{data:u,missingSince:null});return e}function yC(e,t=!0,n=0){const[s,i]=y.useState([]),[l,c]=y.useState(null),u=y.useRef([]),h=y.useRef({}),p=y.useRef({}),v=y.useRef({remote:{},fleet:{}}),_=y.useRef(null),g=y.useRef(null),w=y.useRef(new Map),S=y.useRef(new Map),N=y.useRef(new Set),C=y.useRef(mh()),j=y.useRef(null);return y.useEffect(()=>{if(!t||!e){i([]),c(null);return}let E=!0;const R=_.current!==null&&_.current!==e;_.current!==e&&(_.current=e,p.current={},v.current={remote:{},fleet:{}},w.current.clear(),S.current.clear(),N.current.clear(),h.current={},u.current=[],i([]));const x={instanceId:"",nodes:new Map,topology:new Map},W=R?null:mP();if(W){x.instanceId=W.instanceId||"";for(const q of W.nodes)x.nodes.set(q.name,{data:q,missingSince:null});for(const q of W.topology)x.topology.set(q.route.join("/"),{data:q,missingSince:null})}async function $(){const q=C.current,K=Date.now(),se=q.begin();if(se===null)return;const V=new AbortController;j.current=V;const B={timeoutMs:l1,signal:V.signal},D=()=>E&&q.isCurrent(se);let O=[],P=[],z={},A="",T=!1,L=!1,H="pending",M="pending";const U={},ee={},re=new Set,oe=new Set,je=new Set;let te=new Map;const ie=[],pe=()=>{te=new Map([...P.filter($e=>Array.isArray($e.route)).map($e=>[$e.route.join("/"),$e.instanceId]),...O.map($e=>[$e.name,$e.nodeId])].filter(([,$e])=>typeof $e=="string"&&$e))},xe=$e=>{const _e=te.get($e),ze=_e?qv(`id:${_e}`):[];return ze.length?{available:!1,cells:ze,fleetState:"stale"}:null},Be=()=>{if(!D()||!A)return!1;const $e=[],_e=Date.now();for(const[nt,lt]of S.current){if(_e-lt.at>Kv){S.current.delete(nt);continue}const X=nt.slice(3),I=w.current.get(X);if(lt.ownerInstanceId!=null&&I!==void 0&&I!==lt.ownerInstanceId){S.current.delete(nt);continue}const ce=N.current.has(nt.slice(3)),ye=lt.round!==se||lt.identityUnknown===!0||ce;for(const Re of lt.peers)$e.push({...Re,stale:ye})}const ze=u.current,Je=nS({nodes:O,topology:P,remote:U,fleet:ee,aliases:z,down:h.current,pendingReads:re,previousGroups:ze});h.current=iP(h.current,Je,Math.floor(Date.now()/1e3));const He=[...nS({nodes:O,topology:P,remote:U,fleet:ee,aliases:z,down:h.current,pendingReads:re,previousGroups:u.current}),...dP($e)];return lP(He),u.current=He,c(e),i(He),!0};let Te=[],Me=[];const J=()=>{var $e;if(D()&&A){T?fd(x.nodes,!0,Te,_e=>_e&&_e.name,K):H==="error"&&fd(x.nodes,!1,Te,_e=>_e&&_e.name,K),L?fd(x.topology,!0,Me,_e=>Array.isArray(_e&&_e.route)?_e.route.join("/"):"",K):M==="error"&&fd(x.topology,!1,Me,_e=>Array.isArray(_e&&_e.route)?_e.route.join("/"):"",K),O=[...x.nodes.values()].map(_e=>_e.data),P=[...x.topology.values()].map(_e=>_e.data),pe();for(const[_e,ze]of te){const Je=w.current.get(_e);Je&&Je!==ze&&(delete v.current.remote[_e],delete v.current.fleet[_e],delete p.current[_e],delete p.current[`vl:${_e}`],delete h.current[_e],S.current.delete(`vl:${_e}`)),w.current.set(_e,ze)}for(const _e of w.current.keys())if(!te.has(_e)){const ze=S.current.get(`vl:${_e}`);ze&&(ze.identityUnknown=!0)}N.current=new Set(P.filter(_e=>!_e.stale&&Array.isArray(_e.route)&&_e.route.length>0&&!te.has(_e.route.join("/"))).map(_e=>_e.route.join("/")));for(const _e of O){if((($e=_e.tunnel)==null?void 0:$e.status)==="up")continue;const ze=v.current.fleet[_e.name];ze&&!ee[_e.name]&&(ee[_e.name]={...ze,available:!1,fleetState:"stale"})}for(const _e of P){if(!_e.stale||!Array.isArray(_e.route)||!_e.route.length)continue;const ze=_e.route.join("/"),Je=v.current.fleet[ze];Je&&!ee[ze]&&(ee[ze]={...Je,available:!1,fleetState:"stale"})}(T||L)&&gP({instanceId:x.instanceId,savedAt:K,nodes:[...x.nodes.values()].map(_e=>_e.data),topology:[...x.topology.values()].map(_e=>_e.data)}),ve(),Be()}},le=($e,_e)=>{D()&&(H=$e?"success":"error",T=$e,Te=$e?_e:[],J())},Q=($e,_e)=>{D()&&(M=$e?"success":"error",L=$e,Me=$e?_e:[],J())},ge=$e=>{D()&&(A=$e&&typeof $e.instanceId=="string"?$e.instanceId:"",A&&(x.instanceId!==A||g.current!==A)?(x.instanceId!==A&&(x.nodes.clear(),x.topology.clear()),u.current=[],h.current={},p.current={},v.current={remote:{},fleet:{}},w.current.clear(),S.current.clear(),N.current.clear()):A&&(x.instanceId=A),g.current=A||null,x.instanceId=A,J())};function Z(){const $e=[{instanceId:A||null,route:[],label:null},...fC({nodes:P},A)];for(const _e of $e){const ze=`${_e.instanceId}:${_e.route.join("/")}`;if(je.has(ze))continue;je.add(ze);const Je=`vl:${_e.route.join("/")}`;ie.push((async()=>{if(oS(p.current,Je,K))try{const He=await g1(e,_e.route,{signal:V.signal});if(!D())return;const nt=w.current.get(_e.route.join("/"));if(nt!==void 0&&nt!==_e.instanceId||N.current.has(_e.route.join("/")))return;p.current=lS(p.current,Je);const lt=[];for(const X of He.nodes||[]){const I=hC(X,_e);I&&lt.push(I)}S.current.set(Je,{peers:lt,ownerInstanceId:_e.instanceId??null,at:K,round:se}),Be()}catch(He){if(!D())return;const nt=w.current.get(_e.route.join("/"));if(nt!==void 0&&nt!==_e.instanceId||N.current.has(_e.route.join("/")))return;p.current=aS(p.current,Je,zp(He),K)}})())}}async function fe($e){const _e=$e.join("/"),ze=v.current.remote[_e]||null;if(!oS(p.current,_e,K)){re.delete(`${_e}#sessions`),re.delete(`${_e}#fleet`);const nt=p.current[_e];U[_e]={error:"unreachable",cause:nt&&nt.cause||null,lastGoodAt:ze?ze.at:null};const lt=v.current.fleet[_e]||xe(_e);lt&&(ee[_e]={...lt,available:!1,fleetState:"stale"});return}re.add(`${_e}#sessions`),re.add(`${_e}#fleet`);const Je=(async()=>{let nt=!1;try{const lt=await bv(e,$e,B);if(!D())return;nt=!0,U[_e]={...lt,at:K},v.current.remote[_e]={payload:lt,at:K}}catch(lt){if(!D())return;U[_e]={error:"unreachable",cause:zp(lt),lastGoodAt:ze?ze.at:null}}finally{re.delete(`${_e}#sessions`)}p.current=nt?lS(p.current,_e):aS(p.current,_e,U[_e].cause,K),Be()})(),He=(async()=>{const nt=v.current.fleet[_e]||xe(_e);try{const lt=await rl(e,$e,B);if(!D())return;const X=kh({fs:lt});X.kind==="data"?(ee[_e]={...lt,available:!0,cells:X.cells,fleetState:"available"},te.get(_e)&&Za(`id:${te.get(_e)}`,X.cells)):X.kind==="disabled"?(ee[_e]={...lt,available:!1,cells:[],fleetState:"disabled"},te.get(_e)&&Za(`id:${te.get(_e)}`,[])):ee[_e]={...nt||{},available:!1,cells:Array.isArray(nt==null?void 0:nt.cells)?nt.cells:[],fleetState:"stale",...lt!=null&&lt.reason?{reason:lt.reason}:{}},v.current.fleet[_e]=ee[_e]}catch(lt){if(!D())return;ee[_e]={...nt||{},available:!1,cells:Array.isArray(nt==null?void 0:nt.cells)?nt.cells:[],fleetState:"stale",cause:zp(lt)},v.current.fleet[_e]=ee[_e]}re.delete(`${_e}#fleet`),Be()})();await Promise.allSettled([Je,He])}function ve(){var ze,Je;if(!D()||!A)return;Z();const $e=new Set(O.map(He=>He.name)),_e=He=>{const nt=He.join("/");oe.has(nt)||(oe.add(nt),ie.push(fe(He)))};for(const He of O)T&&!He.stale&&((ze=He.tunnel)==null?void 0:ze.status)==="up"&&(He.nodeId||He.paired!==!1)&&(He.direction!=="inbound"||He.shared===!0)?_e([He.name]):H==="pending"&&!He.stale&&((Je=He.tunnel)==null?void 0:Je.status)==="up"&&(re.add(`${He.name}#sessions`),re.add(`${He.name}#fleet`));for(const He of P)if(!He.stale&&Array.isArray(He.route)&&He.route.length>0&&!(He.route.length===1&&$e.has(He.route[0]))){const nt=He.route.join("/");L?_e(He.route):M==="pending"&&(re.add(`${nt}#sessions`),re.add(`${nt}#fleet`))}}const ke=$5(e,B).then($e=>{le(!0,Array.isArray($e.nodes)?$e.nodes:[])},()=>{le(!1,[])}),Ve=v1(e,B).then($e=>{Q(!0,Array.isArray($e.nodes)?$e.nodes:[])},()=>{Q(!1,[])}),ot=K5(e,B).then($e=>{D()&&(z=$e&&typeof $e.aliasesByInstanceId=="object"?$e.aliasesByInstanceId:{},Be())},()=>{}),rt=Yc(e,[],B).then($e=>{ge($e)},()=>{});try{await Promise.allSettled([ke,Ve,ot,rt]),await Promise.allSettled(ie)}finally{q.isCurrent(se)&&q.end(se)}}$();const Y=setInterval($,pP);return()=>{E=!1,clearInterval(Y),C.current.reset(),j.current&&j.current.abort()}},[e,t,n]),{groups:s,hasLoaded:t&&!!e&&l===e}}function Vv(e,t=!0,n=0){return yC(e,t,n).groups}const cS=52,uS=14;function Qi({position:e,itemKey:t,label:n,onMove:s,onStep:i,canMove:l=()=>!0,scope:c="roster"}){const u=y.useRef(null),h=y.useRef(0),[p,v]=y.useState(!1),_=()=>{var j,E,R,x;const C=u.current;(E=(j=C==null?void 0:C.over)==null?void 0:j.classList)==null||E.remove("nc-roster-over"),(x=(R=C==null?void 0:C.source)==null?void 0:R.classList)==null||x.remove("nc-roster-dragging"),h.current&&cancelAnimationFrame(h.current),h.current=0},g=(C=!1)=>{const j=u.current;if(!j)return;const E=j.target;_(),u.current=null,v(!1);try{j.handle.releasePointerCapture(j.pointerId)}catch{}C&&E&&E!==t&&l(t,E)&&s(t,E)},w=(C,j)=>{var q,K,se,V,B,D,O,P,z;const E=u.current;if(!E)return;E.x=C,E.y=j;const R=c==="node"?"[data-node-order-key]":"[data-roster-key][data-position]",x=(K=(q=document.elementFromPoint(C,j))==null?void 0:q.closest)==null?void 0:K.call(q,R),W=c==="node"?(se=x==null?void 0:x.dataset)==null?void 0:se.nodeOrderKey:(V=x==null?void 0:x.dataset)==null?void 0:V.rosterKey,Y=(c==="node"||((B=x==null?void 0:x.dataset)==null?void 0:B.position)===e)&&W&&W!==t&&l(t,W);E.over!==(Y?x:null)&&((O=(D=E.over)==null?void 0:D.classList)==null||O.remove("nc-roster-over"),E.over=Y?x:null,(z=(P=E.over)==null?void 0:P.classList)==null||z.add("nc-roster-over")),E.target=Y?W:null},S=()=>{const C=u.current;if(!C){h.current=0;return}const j=C.container;if(j){const E=j.getBoundingClientRect(),R=C.y<E.top+cS?-uS:C.y>E.bottom-cS?uS:0;R&&(j.scrollTop+=R,w(C.x,C.y))}h.current=requestAnimationFrame(S)};y.useEffect(()=>{const C=E=>{E.key==="Escape"&&u.current&&(E.preventDefault(),g(!1))},j=()=>g(!1);return window.addEventListener("keydown",C),window.addEventListener("blur",j),()=>{window.removeEventListener("keydown",C),window.removeEventListener("blur",j),_(),u.current=null}},[t,e,c]);const N=C=>{var x;if(C.pointerType==="mouse"&&C.button!==0)return;C.preventDefault(),C.stopPropagation(),C.currentTarget.focus({preventScroll:!0});const j=c==="node"?"[data-node-order-key]":"[data-roster-key][data-position]",E=C.currentTarget.closest(j),R=C.currentTarget.closest(".nc-side-scroll, .nc-home-scroll, .nc-cell-switcher-list");u.current={pointerId:C.pointerId,handle:C.currentTarget,source:E,container:R,target:null,over:null,x:C.clientX,y:C.clientY},(x=E==null?void 0:E.classList)==null||x.add("nc-roster-dragging");try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}v(!0),h.current=requestAnimationFrame(S)};return o.jsx("button",{type:"button",className:`nc-roster-handle${p?" active":""}`,"aria-label":`${f("reorder")} ${n}`,"aria-keyshortcuts":"ArrowUp ArrowDown",title:f("reorder-help"),onClick:C=>{C.preventDefault(),C.stopPropagation()},onDragStart:C=>C.preventDefault(),onKeyDown:C=>{C.key!=="ArrowUp"&&C.key!=="ArrowDown"||(C.preventDefault(),C.stopPropagation(),i(C.key==="ArrowUp"?-1:1))},onPointerDown:N,onPointerMove:C=>{!u.current||C.pointerId!==u.current.pointerId||(C.preventDefault(),C.stopPropagation(),w(C.clientX,C.clientY))},onPointerUp:C=>{!u.current||C.pointerId!==u.current.pointerId||(C.preventDefault(),C.stopPropagation(),g(!0))},onPointerCancel:()=>g(!1),onLostPointerCapture:()=>{u.current&&g(!1)},children:"↕"})}const bC="nc_pins";function io(){return Ir(bC,{fallback:()=>[],parse:e=>Array.isArray(e)?e:void 0})}function Gv(e){return wi(bC,e)}function vP(e,t){const n=e.includes(t)?e.filter(s=>s!==t):[...e,t];return{next:n,error:Gv(n)}}function dS(e,t){if(!Array.isArray(e)||!e.includes(t))return{next:Array.isArray(e)?e:[],error:null};const n=e.filter(s=>s!==t);return{next:n,error:Gv(n)}}function _P(e,t,n){if(!e.includes(t)||!e.includes(n)||t===n)return e;const s=[...e],i=s.indexOf(t),l=s.indexOf(n);s.splice(i,1);const c=s.indexOf(n);return s.splice(i<l?c+1:c,0,t),Gv(s),s}function yP(e,t,n){const s=e.indexOf(t);return[s===-1?1e9:s,-(n||0)]}function bP(e,t){return e[0]-t[0]||e[1]-t[1]}const Pg="nexuscrew-roster-preferences",wP=new Set(["nc_pins",ta,ea,Ig]),Ba=()=>{try{window.dispatchEvent(new Event(Pg))}catch{}},SP=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Fp=e=>t=>SP(t,e)?t:e;function Yv(){const[e,t]=y.useState(io),[n,s]=y.useState(Td),[i,l]=y.useState(bc),[c,u]=y.useState(null),[h,p]=y.useState(null);y.useEffect(()=>{if(!h)return;const R=setTimeout(()=>p(null),8e3);return()=>clearTimeout(R)},[h]),y.useEffect(()=>{const R=x=>{x&&x.type==="storage"&&x.key&&!wP.has(x.key)||(t(Fp(io())),l(Fp(bc())),s(Fp(Td())))};return window.addEventListener("storage",R),window.addEventListener(Pg,R),()=>{window.removeEventListener("storage",R),window.removeEventListener(Pg,R)}},[]);const v=R=>{const x=io(),W=vP(x,R);t(W.next),er({reason:W.error?"pin-write-failed":"pin",key:R,before:x,after:W.next,note:W.error?String(W.error.message||W.error):void 0}),Ba()},_=R=>{const x=io(),W=dS(x,R);return t(W.next),u(W.error?{key:R,message:W.error.message||String(W.error)}:null),er({reason:W.error?"unpin-write-failed":"unpin",key:R,before:x,after:W.next}),Ba(),W.error},g=()=>{if(!c)return;const R=dS(io(),c.key);t(R.next),u(R.error?{...c,message:R.error.message||String(R.error)}:null),Ba()},w=()=>u(null),S=R=>Ag(Oa(n),R),N=(R,x)=>{const W=Td(),$=Bp(R),Y=nP({...W,[$]:{...Ag(Oa(W),R),...x}});s(Y),Ba()},C=(R,x)=>e.includes(R)===e.includes(x);function j(R,x,W,$){var T,L;const Y=(T=$.find(H=>H.partial))==null?void 0:T.partial;if(Y){p({reason:Y,position:R,at:Date.now()}),er({reason:"reorder-blocked",position:Bp(R),source:x,target:W,note:Y});return}p(null);const q=io(),K=q.includes(x),se=q.includes(W);if(K!==se)return;if(K){const H=_P(q,x,W);t(H),er({reason:"move-pin",source:x,target:W,before:q,after:H}),Ba();return}const V=bc(),B=Bp(R),D=Oa(V),O=((L=$.find(H=>H.key===x))==null?void 0:L.technical)===!0,P=fo($,q,O?"technical":"all",Di(D,R)).map(H=>H.key),z=tP({...V,[B]:Di(D,R)},B,x,W,P),A={...V,[B]:z[B]};eP(A),er({reason:"move",position:B,source:x,target:W,before:Di(D,R),after:z[B],visible:P}),l(A),Ba()}function E(R,x,W,$){var O;if($.some(P=>P.partial)){j(R,x,x,$);return}const Y=io(),q=Oa(bc()),K=((O=$.find(P=>P.key===x))==null?void 0:O.technical)===!0,se=Y.includes(x),V=fo($,Y,K?"technical":"all",Di(q,R)).map(P=>P.key).filter(P=>Y.includes(P)===se),B=V.indexOf(x),D=V[B+W];B>=0&&D&&j(R,x,D,$)}return{pins:e,views:Oa(n),orders:Oa(i),togglePin:v,removePin:_,pinError:c,retryPinPersist:g,clearPinError:w,reorderBlocked:h,viewFor:S,updateView:N,canMoveRoster:C,moveRoster:j,stepRoster:E}}const Ch="nc_node_order_v1",xP=/^[a-f0-9]{16,64}$/;function Uo(e){if(xP.test(String((e==null?void 0:e.instanceId)||"")))return`id:${e.instanceId}`;const t=Array.isArray(e==null?void 0:e.route)?e.route.filter(n=>typeof n=="string"&&n):[];return t.length?`route:${t.map(encodeURIComponent).join("/")}`:typeof(e==null?void 0:e.name)=="string"&&e.name?`name:${encodeURIComponent(e.name)}`:""}function Dg(e=globalThis.localStorage){return Ir(Ch,{storage:e,fallback:()=>[],parse:t=>Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"&&n&&n.length<=192))].slice(0,128):void 0})}function kP(e,t=globalThis.localStorage){return wi(Ch,e,{storage:t}),e}function hS(e=[],t=[]){const n=new Map(t.map((s,i)=>[s,i]));return e.map((s,i)=>({group:s,index:i})).sort((s,i)=>{const l=n.has(Uo(s.group))?n.get(Uo(s.group)):Number.MAX_SAFE_INTEGER,c=n.has(Uo(i.group))?n.get(Uo(i.group)):Number.MAX_SAFE_INTEGER;return l-c||s.index-i.index}).map(({group:s})=>s)}function CP(e,t,n,s=[]){if(!t||!n||t===n)return e;const i=s.map(Uo).filter(Boolean);if(!i.includes(t)||!i.includes(n))return e;const l=[...e,...i.filter(p=>!e.includes(p))],c=l.indexOf(t),u=l.indexOf(n);l.splice(c,1);const h=l.indexOf(n);return l.splice(c<u?h+1:h,0,t),l}const Og="nexuscrew-node-preferences";function EP(){try{window.dispatchEvent(new Event(Og))}catch{}}function Eh(){const[e,t]=y.useState(Dg);y.useEffect(()=>{const l=()=>t(Dg());return window.addEventListener("storage",l),window.addEventListener(Og,l),()=>{window.removeEventListener("storage",l),window.removeEventListener(Og,l)}},[]);const n=l=>hS(l,e),s=(l,c,u)=>t(h=>{const p=CP(h,l,c,u);return kP(p),EP(),p});return{order:e,groupsFor:n,moveNode:s,stepNode:(l,c,u)=>{const h=hS(u,e).map(Uo),p=h.indexOf(l),v=h[p+c];p>=0&&v&&s(l,v,u)},nodeKey:Uo}}function wC({pinError:e,onRetry:t,onDismiss:n}){return e?o.jsxs("div",{className:"nc-pin-error",role:"alert",children:[o.jsx("span",{className:"nc-pin-error-text",children:"★ preferenza non salvata"}),o.jsx("button",{type:"button",className:"nc-pin-error-retry",onClick:t,children:"riprova"}),o.jsx("button",{type:"button",className:"nc-pin-error-close",onClick:n,"aria-label":"chiudi avviso",children:"×"})]}):null}function Nh({item:e,pins:t,hostByRoute:n,route:s}){const i=(n||{})[Rs(s)]||{},l=$d({hostCell:i.hostCell??null,threadStatus:i.threadStatus,pins:t,item:e}),c=Mj(l);return{state:l,live:!!c,favorite:l==="favorite",filled:l!=="none",titleKey:c||"pin",action:l===C1?"removePin":"addPin"}}async function Xv({view:e,itemKey:t,togglePin:n,removePin:s}){return e.action==="removePin"?(s(t),{ok:!0}):(n(t),{ok:!0})}function co({item:e,cellName:t,route:n=[],pins:s=[],hostByRoute:i={}}={}){const l=Nh({item:e,pins:s,hostByRoute:i,route:n}),c=(i||{})[Rs(n)]||{};return{pinned:l.favorite,isLive:!!c.hostCell&&c.hostCell===t}}function Jv({isLive:e,pinned:t,canBoot:n,boot:s,alive:i,handlers:l={}}={}){const c=[];return typeof l.onToggleLive=="function"&&c.push({id:"live",kind:"action",on:!!e,labelKey:e?"cell-actions-live-remove":"cell-actions-live-assign",run:l.onToggleLive}),typeof l.onTogglePin=="function"&&c.push({id:"pin",kind:"action",on:!!t,labelKey:t?"cell-actions-unpin":"cell-actions-pin",run:l.onTogglePin}),n&&typeof l.onToggleBoot=="function"&&c.push({id:"boot",kind:"switch",on:!!s,labelKey:"cell-actions-boot",run:()=>l.onToggleBoot(!s)}),i&&typeof l.onWatchLive=="function"&&c.push({id:"watch",kind:"action",on:!1,labelKey:"cell-actions-watch",run:l.onWatchLive}),c}function SC({items:e=[],busy:t=!1,onRun:n}){return o.jsx("div",{className:"nc-cellactions",role:"menu","aria-busy":t||void 0,children:e.map(s=>{const i=s.descKey?f(s.descKey):s.descText;return o.jsxs("button",{type:"button",role:s.kind==="switch"?"menuitemcheckbox":"menuitem","aria-checked":s.kind==="switch"?s.on?"true":"false":void 0,className:`nc-cellactions-voce${s.on?" on":""}`,disabled:t,"data-cellaction":s.id,onClick:l=>{l.stopPropagation(),n?n(s):s.run()},children:[s.kind==="switch"?o.jsx("span",{className:`nc-cellactions-toggle${s.on?" on":""}`,"aria-hidden":"true"}):null,o.jsxs("span",{className:"nc-cellactions-testo",children:[f(s.labelKey),i?o.jsx("small",{className:"nc-cellactions-desc",children:i}):null]})]},s.id)})})}function xC({aperto:e,refGuscio:t,onClose:n}){y.useEffect(()=>{const s=l=>{t.current&&!t.current.contains(l.target)&&n()},i=l=>{l.key==="Escape"&&n()};return document.addEventListener("pointerdown",s),document.addEventListener("keydown",i),()=>{document.removeEventListener("pointerdown",s),document.removeEventListener("keydown",i)}},[e,t,n])}function kC({anchorRect:e,items:t,busy:n,onClose:s}){const i=y.useRef(null);xC({aperto:!0,refGuscio:i,onClose:s});const l=e?{top:Math.min(e.bottom+6,window.innerHeight-8),left:Math.max(8,Math.min(e.right-210,window.innerWidth-218))}:void 0;return o.jsx("div",{className:"nc-cellactions-popover",style:l,ref:i,"data-testid":"cell-actions-popover",children:o.jsx(SC,{items:t,busy:n,onRun:c=>{c.run(),s()}})})}function Qv({cellName:e,items:t,busy:n,onClose:s}){const i=y.useRef(null);return xC({aperto:!0,refGuscio:i,onClose:s}),o.jsx("div",{className:"nc-cellactions-velo","data-testid":"cell-actions-sheet",children:o.jsxs("div",{className:"nc-cellactions-foglio",role:"dialog","aria-modal":"true","aria-label":f("cell-actions-title").replace("{cell}",e||""),ref:i,children:[o.jsxs("div",{className:"nc-cellactions-testa",children:[o.jsx("span",{className:"nc-cellactions-titolo",children:f("cell-actions-title").replace("{cell}",e||"")}),o.jsx("button",{type:"button",className:"nc-cellactions-chiudi",onClick:s,title:f("close"),"aria-label":f("close"),children:"✕"})]}),o.jsx(SC,{items:t,busy:n,onRun:l=>{l.run(),s()}})]})})}function uo(e,t=Math.floor(Date.now()/1e3)){if(!e)return"";const n=t-e;return n<0||n<60?"ora":n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}g`}function CC(e){const t=e||{};return!(t.sessionsAvailable===!1||typeof t.status=="string"&&t.status!=="up")}function tr(e){return e.status==="up"&&!CC(e)?f("node-sessions-unverified"):e.status==="passive"?f("node-passive"):e.status==="down"?e.downSince?f("tunnel-down-since").replace("{t}",uo(e.downSince)):f("tunnel-down"):e.status==="unreachable"?e.cause===gC?f("peer-cause-nega"):e.cause===vC?f("peer-cause-rotta"):e.cause===mC?f("peer-cause-assente"):f("node-unreachable"):e.status==="offline"?e.lastSeen?f("node-offline-seen").replace("{t}",uo(e.lastSeen)):f("node-offline"):e.status==="needs-repair"?f("node-needs-repair"):""}function EC(e,{passive:t=null}={}){return e?e.status==="passive"?t:e.status==="healthy"?"on":"warn":null}function Yd(e){return e&&(e.detail||e.status)||""}const NP="restrict,port-forwarding,permitopen=";function jP(e){const t=e&&typeof e.hint=="string"&&e.hint.trim()||"",n=e&&typeof e.authorizedKeys=="string"&&e.authorizedKeys.trim()||"";if(n){const i=t.indexOf(n);return{note:i>=0?t.slice(0,i).replace(/[:\s]+$/,""):t,line:n}}if(!t)return null;const s=t.indexOf(NP);return s<0?{note:t,line:""}:{note:t.slice(0,s).replace(/[:\s]+$/,""),line:t.slice(s).trim()}}function Xd(e,t,n=globalThis.localStorage){if(!(e!=null&&e.outbox)||e.outbox.count<1)return!1;const s=Number(n.getItem(c1(t))||0);return e.outbox.latest>s}function Zv(e,t={},{autorevole:n=!0}={}){const s=e||{},i=`${s.engine||""}${s.key?`·${s.key}`:""}`,l=[i,s.model&&s.model!==i?s.model:""].filter(Boolean).join(" · ");if(!s.tmux)return{working:!1,subtitle:String(l||f("cell-off")).trim()};const c=t.attivita&&typeof t.attivita=="object"?t.attivita.stato:null;if(c==="lavora"||c==="attesa"){const u=f(c==="attesa"?"cell-permission":"cell-working"),h=String(t.status||"").trim(),p=!h||/^working(?:\.{3}|…)?$/i.test(h);return{working:!0,stato:c,subtitle:c==="lavora"&&!p?`${u} · ${h}`:u}}if(c==="ferma")return{working:!1,stato:"ferma",subtitle:f("cell-stopped")};if(!n)return{working:!1,stato:"ignoto",subtitle:[f("cell-unknown"),l].filter(Boolean).join(" · ")};if(t.working===!0){const u=String(t.status||"").trim();return{working:!0,stato:"ignoto",subtitle:!u||/^working(?:\.{3}|…)?$/i.test(u)?f("cell-unknown"):`${f("cell-unknown")} · ${u}`}}return t.working===!1?{working:!1,stato:"ignoto",subtitle:f("cell-unknown")}:{working:!1,stato:"ignoto",subtitle:String(t.preview||s.preview||f("cell-on")).trim()}}function NC(e,t){return[...new Set([e.engine,e.model,e.key,t.preview,e.preview,t.status].filter(Boolean).map(String))].join(" ")}function jC({sessionsOk:e=!0,fleetStale:t=!1,cellCount:n=0}={}){return e?t&&!n?"fleet":null:"sessions"}function e_(e,t,n,s=globalThis.localStorage,{autorevole:i=!0,fleetStale:l=!1}={}){const c=jC({sessionsOk:i,fleetStale:l,cellCount:Array.isArray(e)?e.length:0});return LC([...(Array.isArray(e)?e:[]).map(u=>{const h=n.get(u.tmuxSession)||{},p=$c([],u.tmuxSession),v=Zv(u,h,{autorevole:i});return{type:"cell",value:u,key:p,label:u.cell,live:!!u.tmux,fresh:Xd(h,p,s),activity:h.activity||0,working:v.working,stato:v.stato,subtitle:v.subtitle,searchText:NC(u,h)}}),...(Array.isArray(t)?t:[]).map(u=>{const h=$c([],u.name);return{type:"session",value:u,key:h,label:u.name,live:!0,technical:u.technical===!0,fresh:Xd(u,h,s),activity:u.activity||0,searchText:`${u.preview||""} ${u.cmd||""}`}})],c)}const LC=(e,t)=>t?e.map(n=>({...n,partial:t})):e;function Cc(e,t=globalThis.localStorage){const n=e||{},s=Array.isArray(n.route)?n.route:[],i=CC(n),l=new Map((n.sessions||[]).map(h=>[h.name,h])),c=[...(n.cells||[]).map(h=>{const p=l.get(h.tmuxSession)||{},v=$c(s,h.tmuxSession||h.cell),_=Zv(h,p,{autorevole:i});return{type:"cell",value:h,key:v,label:h.cell,live:!!h.tmux&&!h.preserved,fresh:Xd(p,v,t),activity:p.activity||h.activity||0,working:_.working,stato:_.stato,subtitle:_.subtitle,searchText:NC(h,p)}}),...(n.unmanaged||[]).map(h=>{const p=$c(s,h.name);return{type:"session",value:h,key:p,label:h.name,live:!0,technical:h.technical===!0,fresh:Xd(h,p,t),activity:h.activity||0,searchText:`${h.preview||""} ${h.cmd||""}`}})],u=jC({sessionsOk:n.sessionsAvailable!==!1,fleetStale:n.fleetState==="stale",cellCount:(n.cells||[]).length});return{route:s,rawItems:LC(c,u)}}const jh=9,Bg=.2,LP=/^[a-z0-9-]{1,32}(?:\/[a-z0-9-]{1,32}){0,3}$/,el=/^[a-f0-9]{16,64}$/,$g=e=>LP.test(e)&&new Set(e.split("/")).size===e.split("/").length;function Ar(e){if(typeof e=="string"&&e){const t=e.indexOf(":");if(t<0)return{session:e};const n=e.slice(0,t),s=e.slice(t+1);return!$g(n)||!s?null:{session:s,node:n}}if(e&&typeof e=="object"&&typeof e.session=="string"&&e.session){const t=e.ownerId===void 0?void 0:typeof e.ownerId=="string"&&el.test(e.ownerId)?e.ownerId:null;return t===null?null:e.node===void 0||e.node===null||e.node===""?{session:e.session,...t?{ownerId:t}:{}}:typeof e.node=="string"&&$g(e.node)?{session:e.session,node:e.node,...t?{ownerId:t}:{}}:null}return null}function Wt(e){const t=Ar(e);return t?t.node?`${t.node}:${t.session}`:t.session:""}const RC=9,AC=24,bi=11,MC=e=>{const t=Number(e);return t>=RC&&t<=AC?t:bi};function po(){return{columns:[]}}function bs(e){return e.columns.flatMap(t=>t.tiles.map(n=>Wt(n)))}function RP(e){const t=[],n=Math.max(0,...e.columns.map(s=>s.tiles.length));for(let s=0;s<n;s+=1)for(const i of e.columns)i.tiles[s]&&t.push(Wt(i.tiles[s]));return t}const Bi=e=>({columns:e.columns.map(t=>({width:t.width,tiles:t.tiles.map(n=>({...n}))}))});function zc(e,t,n,s){const i=Ar(t);if(!i||bs(e).includes(Wt(i))||bs(e).length>=jh)return e;const l=Bi(e),c={session:i.session,height:1,fontSize:bi,...s||{}};if(i.node&&(c.node=i.node),i.ownerId&&(c.ownerId=i.ownerId),n==="end")return l.columns.push({width:1,tiles:[c]}),l;if(n&&typeof n.col=="number"&&typeof n.row=="number"&&l.columns[n.col])return l.columns[n.col].tiles.splice(n.row,0,c),l;if(n&&typeof n.col=="number"){const u=Math.max(0,Math.min(l.columns.length,n.col));return l.columns.splice(u,0,{width:1,tiles:[c]}),l}return l.columns.push({width:1,tiles:[c]}),l}function TC(e,t){const n=Wt(t);if(!n||bs(e).includes(n)||bs(e).length>=jh)return e;const s=bs(e).length+1,i=Math.ceil(Math.sqrt(s));if(e.columns.length>=i){let v=0;for(let _=1;_<e.columns.length;_+=1)e.columns[_].tiles.length<e.columns[v].tiles.length&&(v=_);return zc(e,t,{col:v,row:e.columns[v].tiles.length})}const l=[...RP(e),n],c=new Map(e.columns.flatMap(v=>v.tiles.map(_=>[Wt(_),_]))),u=Ar(t),h=e.columns.length?e.columns.reduce((v,_)=>v+(Number(_.width)||1),0)/e.columns.length:1,p=Array.from({length:i},(v,_)=>{var g;return{width:((g=e.columns[_])==null?void 0:g.width)||h,tiles:[]}});return l.forEach((v,_)=>{const g=Ar(v);if(!g)return;const w=c.get(v)||(v===n?u:{})||{},S={session:g.session,height:w.height||1,fontSize:w.fontSize||bi};g.node&&(S.node=g.node),w.ownerId&&(S.ownerId=w.ownerId),w.unavailable===!0&&(S.unavailable=!0),w.stale===!0&&(S.stale=!0),p[_%i].tiles.push(S)}),{columns:p.filter(v=>v.tiles.length)}}function IC(e,t){const n=Ar(t);if(!n)return e;const s=Wt(n);if(!s||bs(e).includes(s)||bs(e).length>=jh)return e;const i=t&&typeof t=="object"?t:{},l={height:Math.max(Bg,Number(i.height)||1),fontSize:MC(i.fontSize),...n.ownerId?{ownerId:n.ownerId}:{}};if(!e.columns.length)return zc(e,n,null,l);let c=0;for(let u=1;u<e.columns.length;u+=1)e.columns[u].tiles.length<e.columns[c].tiles.length&&(c=u);return zc(e,n,{col:c,row:e.columns[c].tiles.length},l)}function Fc(e,t){const n=Wt(t),s=Bi(e);for(const i of s.columns)i.tiles=i.tiles.filter(l=>Wt(l)!==n);return s.columns=s.columns.filter(i=>i.tiles.length>0),s}function AP(e,t,n){const s=Wt(t);if(!bs(e).includes(s))return e;const i=e.columns.flatMap(l=>l.tiles).find(l=>Wt(l)===s);return zc(Fc(e,s),s,n,{fontSize:i.fontSize,height:i.height,...i.ownerId?{ownerId:i.ownerId}:{},...i.unavailable===!0?{unavailable:!0}:{},...i.stale===!0?{stale:!0}:{}})}function MP(e,t){if(!(t instanceof Map)||t.size===0)return e;let n=!1;const s=Bi(e);for(const i of s.columns)for(const l of i.tiles){const c=t.get(Wt(l));if(!c)continue;const u=Ar(c);u&&(l.session=u.session,u.node?l.node=u.node:delete l.node,u.ownerId&&(l.ownerId=u.ownerId),n=!0)}return n?Pi(s):e}const PC=120,DC=60,Sc=[1/3,.5,2/3],zg=16;function OC(e,t,n,s){if(!(t>0))return .5;const i=Math.max(0,Math.min(.5,n/t));let l=e/t;if(l=Math.max(i,Math.min(1-i,l)),s){for(const c of Sc)if(Math.abs(l-c)*t<=zg){l=c;break}}return l}function fS(e,t,n,s,i={}){const l=Bi(e),c=l.columns[t],u=l.columns[t+1];if(!c||!u)return e;const h=l.columns.reduce((g,w)=>g+(Number(w.width)||1),0),p=(Number(c.width)||1)+(Number(u.width)||1),v=(Number(n)||0)*(p/(h||1)),_=i.half===!0?.5:OC(s,v,i.minPx??PC,i.snap!==!1);return c.width=p*_,u.width=p*(1-_),l}function pS(e,t,n,s,i,l={}){const c=Bi(e),u=c.columns[t],h=u&&u.tiles[n],p=u&&u.tiles[n+1];if(!h||!p)return e;const v=u.tiles.reduce((S,N)=>S+(Number(N.height)||1),0),_=(Number(h.height)||1)+(Number(p.height)||1),g=(Number(s)||0)*(_/(v||1)),w=l.half===!0?.5:OC(i,g,l.minPx??DC,l.snap!==!1);return h.height=_*w,p.height=_*(1-w),c}function TP(e,t,n){if(!t||!n||t===n)return e;const s=Bi(e);let i=null,l=null;for(const p of s.columns)for(let v=0;v<p.tiles.length;v+=1){const _=Wt(p.tiles[v]);_===t&&!i?i={col:p,i:v}:_===n&&!l&&(l={col:p,i:v})}if(!i||!l)return e;const c=i.col.tiles[i.i],u=l.col.tiles[l.i],h=p=>{const v={...p};return delete v.height,v};return i.col.tiles[i.i]={...h(u),height:c.height},l.col.tiles[l.i]={...h(c),height:u.height},s}const eu=6,tu=e=>{let{x:t,y:n,w:s,h:i}=e;return s=Math.max(.05,Math.min(1,Number(s)||.3)),i=Math.max(.05,Math.min(1,Number(i)||.3)),t=Math.max(0,Math.min(1-s,Number(t)||0)),n=Math.max(0,Math.min(1-i,Number(n)||0)),{x:t,y:n,w:s,h:i}};function t_(e,t){for(const n of e.columns)for(let s=0;s<n.tiles.length;s+=1)if(Wt(n.tiles[s])===t)return{tile:n.tiles[s]};return null}function IP(e,t,n){const s=Bi(e),i=Wt(t);if(DP(s).length>=eu)return e;const l=t_(s,i);return!l||l.tile.float?e:(l.tile.float=tu(n||{}),s)}function PP(e,t){const n=Bi(e),s=t_(n,Wt(t));return!s||!s.tile.float?e:(delete s.tile.float,n)}function mS(e,t,n){const s=Bi(e),i=t_(s,Wt(t));return!i||!i.tile.float?e:(i.tile.float=tu(n),s)}function DP(e){return e.columns.flatMap(t=>t.tiles).filter(t=>t.float).map(t=>Wt(t))}function Jd(e){const t=[],n=[];for(const s of e.columns){const i=[];for(const l of s.tiles)if(l.float){const c={session:l.session,...l.float,fontSize:l.fontSize};l.node&&(c.node=l.node),l.ownerId&&(c.ownerId=l.ownerId),t.push(c)}else i.push(l);i.length&&n.push({width:s.width,tiles:i})}return{grid:{columns:n},floating:t}}const BC=["x","y","w","h","fontSize"],Fg=(e,t)=>Math.abs((Number(e)||0)-(Number(t)||0))<1e-9,$C=(e,t)=>BC.every(n=>Fg(e[n],t[n]));function OP(e,t,n){if(!e)return n;const s={...n};for(const i of BC)Fg(n[i],e[i])&&!Fg(t[i],e[i])&&(s[i]=t[i]);return{...s,...tu(s)}}function BP(e,t,n){const s=h=>new Map((Array.isArray(h)?h:[]).map(p=>[Wt(p),p]).filter(([p])=>p)),i=s(e),l=s(t),c=s(n),u=[];for(const[h,p]of c)!l.has(h)&&i.has(h)&&$C(p,i.get(h))||u.push(l.has(h)?OP(i.get(h),l.get(h),p):p);for(const[h,p]of l)c.has(h)||i.has(h)||u.push(p);return u.slice(0,eu)}function $P(e,t,n,s,i){const l=g=>Array.isArray(g.floating)?g.floating:[],c=(g,w)=>l(g).some(S=>Wt(S)===w)?"float":bs(g.grid).includes(w)?"grid":"",u=(g,w)=>g.columns.flatMap(S=>S.tiles).find(S=>Wt(S)===w),h=new Set([...l(n),...l(s),...l(i)].map(g=>Wt(g)).filter(Boolean));let p=e,v=Array.isArray(t)?t:[];const _=(g,w)=>l(g).find(S=>Wt(S)===w);for(const g of h){const w=c(i,g),S=c(n,g),C=w!==S||w==="float"&&!$C(_(i,g),_(n,g))?w:c(s,g);if(C!=="grid"&&bs(p).includes(g)&&(p=Fc(p,g)),C!=="float"&&(v=v.filter(j=>Wt(j)!==g)),C==="grid"&&!bs(p).includes(g)){const j=u(s.grid,g)||u(i.grid,g)||u(n.grid,g);j&&(p=IC(p,j))}if(C==="float"&&!v.some(j=>Wt(j)===g)){const j=[s,i,n].map(E=>l(E).find(R=>Wt(R)===g)).find(Boolean);j&&(v=[...v,j])}}return{grid:p,floating:v.slice(0,eu)}}function zP(e,t){const n=s=>{const{grid:i,floating:l}=Jd(s||po());return JSON.stringify({g:i.columns.map(c=>[c.width,c.tiles.map(u=>[Wt(u),u.ownerId||"",u.height,u.fontSize])]),f:l.map(c=>[Wt(c),c.ownerId||"",c.x,c.y,c.w,c.h,c.fontSize])})};return n(e)===n(t)}function Hg(e,t){let n=e;for(const s of Array.isArray(t)?t:[]){const i={session:s.session};s.node&&(i.node=s.node),s.ownerId&&(i.ownerId=s.ownerId);const l=Wt(i);if(!l||bs(n).includes(l))continue;const c=Bi(n);c.columns.length||c.columns.push({width:1,tiles:[]});let u=0;for(let p=1;p<c.columns.length;p+=1)c.columns[p].tiles.length<c.columns[u].tiles.length&&(u=p);const h={session:i.session,height:1,fontSize:s.fontSize||bi,float:tu(s)};i.node&&(h.node=i.node),i.ownerId&&(h.ownerId=i.ownerId),c.columns[u].tiles.push(h),n=c}return n}function FP(e,t,n,s){if(!(e.columns[t]&&e.columns[t].tiles[n]))return e;const l=Bi(e),c=l.columns[t].tiles[n],u=Number(c.fontSize)||bi;return c.fontSize=Math.max(RC,Math.min(AC,u+(Number(s)||0))),l}function HP(e,t,n,s){const i=e.columns[t];if(!i||!i.tiles[n])return null;switch(s){case"left":return{col:t};case"right":return{col:t+1};case"top":return{col:t,row:n};case"bottom":return{col:t,row:n+1};default:return null}}function Pi(e){if(!e||!Array.isArray(e.columns))return po();const t=e.columns.map(l=>({width:Math.max(Bg,Number(l&&l.width)||1),tiles:(Array.isArray(l&&l.tiles)?l.tiles:[]).filter(c=>c&&typeof c.session=="string"&&c.session).filter(c=>c.node==null||typeof c.node=="string"&&$g(c.node)).filter(c=>c.ownerId==null||typeof c.ownerId=="string"&&el.test(c.ownerId)).map(c=>{const u={session:c.session,height:Math.max(Bg,Number(c.height)||1),fontSize:MC(c.fontSize)};return c.node!=null&&(u.node=c.node),c.ownerId!=null&&(u.ownerId=c.ownerId),c.float&&(u.float=tu(c.float)),u})})).filter(l=>l.tiles.length>0),n=new Set;let s=0,i=0;for(const l of t)l.tiles=l.tiles.filter(c=>{const u=Wt(c);return n.has(u)||(c.float?i>=eu:s>=jh)?!1:(n.add(u),c.float?i+=1:s+=1,!0)});return{columns:t.filter(l=>l.tiles.length>0)}}function UP(e,t){let n=Pi(e);const s=Pi(t),i=new Map;for(const c of s.columns)for(const u of c.tiles)i.set(Wt(u),u);for(const c of n.columns)for(let u=0;u<c.tiles.length;u+=1){const h=Wt(c.tiles[u]);i.has(h)&&(c.tiles[u]=i.get(h))}const l=new Map;for(const c of s.columns){const u=c.tiles.map(h=>Wt(h)).sort().join("|");l.has(u)||l.set(u,c.width)}for(const c of n.columns){const u=c.tiles.map(p=>Wt(p)).sort().join("|"),h=l.get(u);h!=null&&(c.width=h)}for(const[c,u]of i)bs(n).includes(c)||(n=IC(n,u));return n}const zC=/^[a-z0-9-]{1,32}$/,WP=/^[A-Za-z0-9._-]{1,32}$/,qP=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/,KP=320;function Ug(e){return typeof e=="string"&&zC.test(e)}const VP=64;function tl(e){if(typeof e!="string")return!1;const t=e.trim();return t.length>0&&t.length<=VP&&!/[\x00-\x1f\x7f]/.test(t)}function mo(e){return String(e??"").normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32).replace(/-+$/g,"")||"node"}function FC(e){if(typeof e!="string"||!e||e.length>KP||e.startsWith("-")||/[\0-\x20\x7f]/.test(e))return!1;if(!e.includes("@"))return/^[A-Za-z0-9][A-Za-z0-9._:-]{0,254}$/.test(e);const t=e.indexOf("@");return t<=0||t!==e.lastIndexOf("@")?!1:WP.test(e.slice(0,t))&&qP.test(e.slice(t+1))}function gS(e){if(e===""||e===null||e===void 0)return null;const t=String(e).trim();if(!/^[0-9]{1,5}$/.test(t))return;const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=65535?n:void 0}function GP({name:e,ssh:t,sshPort:n,remotePort:s}={}){const i=typeof e=="string"?e.trim():e,l=typeof t=="string"?t.trim():t;if(!Ug(i))return{ok:!1,error:"err-node-name"};if(!FC(l))return{ok:!1,error:"err-ssh"};const c=gS(n);if(c===void 0)return{ok:!1,error:"err-ssh-port"};const u=gS(s);if(u===void 0)return{ok:!1,error:"err-node-port"};const h={name:i,ssh:l};return c!==null&&(h.sshPort=c),u!==null&&(h.remotePort=u),{ok:!0,value:h}}function YP(e,t){if(!e||!t||t<e)return null;const n=Math.floor((t-e)/1e3);return n<60?"ora":n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}g`}function Wg(e,t){const n=!!(e&&e.status==="up"),s=!!(e&&e.status==="passive");return{up:n,...s?{passive:!0}:{},label:n?"tunnel-up":s?"node-passive":"tunnel-down",since:n?YP(e.since,t):null}}const XP=new Set(["v","instanceId","port","label","invite"]),JP=new Set(["v","instanceId","port","label","invite","name","ssh","sshPort"]);function QP(e){const t=String(e).replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4),s=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("binary"),i=Uint8Array.from(s,l=>l.charCodeAt(0));return typeof TextDecoder<"u"?new TextDecoder().decode(i):Buffer.from(i).toString("utf8")}function ZP(e){let t="";try{const c=new URL(String(e));t=new URLSearchParams(c.hash.replace(/^#/,"")).get("pair")||""}catch{return{ok:!1}}if(!t)return{ok:!1};let n;try{n=JSON.parse(QP(t))}catch{return{ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1};const s=n.v===1?XP:n.v===2?JP:null;if(!s)return{ok:!1};for(const c of Object.keys(n))if(!s.has(c))return{ok:!1};if(!/^[a-f0-9]{16,64}$/.test(String(n.instanceId)))return{ok:!1};const i=Number(n.port);if(!Number.isInteger(i)||i<1||i>65535)return{ok:!1};if(typeof n.label!="string")return{ok:!1};if(typeof n.invite!="string"||!n.invite)return{ok:!1};const l={ok:!0,version:n.v,label:n.label,invite:n.invite,instanceId:n.instanceId,port:i};if(n.v===2){if(n.name!==void 0){if(typeof n.name!="string"||!zC.test(n.name))return{ok:!1};l.name=n.name}if(n.ssh!==void 0){if(!FC(n.ssh))return{ok:!1};l.ssh=String(n.ssh).trim()}if(n.sshPort!==void 0){const c=Number(n.sshPort);if(!Number.isInteger(c)||c<1||c>65535)return{ok:!1};l.sshPort=c}}return l}function eD(e,t,n=new Set){if(!t||!t.ok)return e;const s={...e},i=(l,c)=>{c==null||c===""||n.has(l)||(s[l]=c)};return i("label",t.label),t.version===2&&(i("name",t.name||(t.ssh?mo(t.label):"")),i("ssh",t.ssh),t.sshPort!==void 0&&i("sshPort",String(t.sshPort))),s}const tD=["KIMI_AUTH_ACTION_REQUIRED","CLIENT_INTERACTION_REQUIRED"],nD=["kimi-code-consent-yes","kimi-code-config-custom-api-key","kimi-cli-login","client-terminal-dialog"];function sD(e){const t=e&&typeof e=="object"?e.actionRequired:null;if(t&&typeof t=="object"&&tD.includes(t.code)&&nD.includes(t.recovery))return{code:t.code,recovery:t.recovery,text:f(`fleet-recovery-${t.recovery}`)};if(e&&typeof e=="object"&&e.vlPromptDegraded===!0)return{code:"VL_PROMPT_DEGRADED",recovery:null,text:f("fleet-vl-prompt-degraded")};if(e&&typeof e=="object"&&e.readinessDegraded===!0){if(e.mcpDegraded&&typeof e.mcpDegraded=="object"){const n=[...Array.isArray(e.mcpDegraded.failed)?e.mcpDegraded.failed:[],...Array.isArray(e.mcpDegraded.pending)?e.mcpDegraded.pending:[]].filter(s=>typeof s=="string"&&s).slice(0,16);if(n.length)return{code:"READINESS_DEGRADED",recovery:null,text:f("fleet-mcp-degraded")+" "+n.join(", ")}}return{code:"READINESS_DEGRADED",recovery:null,text:f("fleet-readiness-degraded")}}return null}function iD(e,t){if(!e)return null;const n=e.status===502&&e.data&&e.data.cause==="upstream-timeout";return e.name==="TimeoutError"||n?{code:"FLEET_ACTION_TIMEOUT",recovery:null,text:f(t==="down"?"fleet-down-slow":"fleet-up-slow")}:e.status===409&&t==="up"&&e.data&&e.data.code==="SESSION_DUPLICATE"?{code:"FLEET_SESSION_DUPLICATE",recovery:null,text:f("fleet-up-duplicate")}:null}async function n_({token:e,powerCell:t,payload:n,onNotice:s,fleetApi:i}){const l=i||{fleetUp:E5,fleetDown:u1},{cell:c}=t,u=Array.isArray(t.route)?t.route:[];try{if(n.action==="up"){const h=await l.fleetUp(e,{cell:c,boot:!!n.boot,...n.engine?{engine:n.engine}:{},...n.model!==void 0?{model:n.model}:{},...n.permissionPolicy?{permissionPolicy:n.permissionPolicy}:{}},u),p=sD(h);p&&s(p.text)}else await l.fleetDown(e,{cell:c,boot:!!n.boot},u);return}catch(h){const p=iD(h,n.action);if(p)return s(p.text),{benign:p.code};throw h}}const rD=1e4;function HC(){const[e,t]=y.useState(null),n=y.useRef(null),s=y.useCallback(i=>{typeof i!="string"||!i||(n.current&&clearTimeout(n.current),t(i),n.current=setTimeout(()=>t(null),rD))},[]);return y.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]),{notice:e,showActionNotice:s}}let qg={sessions:[],cells:[],nodeGroups:[],localNodeId:"",localFresh:!1,refreshedAt:0};function oD(){return qg}function aD(e={}){return qg={sessions:Array.isArray(e.sessions)?e.sessions:[],cells:Array.isArray(e.cells)?e.cells:[],nodeGroups:Array.isArray(e.nodeGroups)?e.nodeGroups:[],localNodeId:typeof e.localNodeId=="string"?e.localNodeId:"",localFresh:e.localFresh===!0,refreshedAt:Number.isFinite(e.refreshedAt)?e.refreshedAt:0},qg}const $a=(e,t=[])=>`${t.length?t.join("/"):"local"}:${e}`;function lD({onPick:e,token:t,onSettings:n,onOpenVlSession:s,hostByRoute:i={},onDesignateCell:l,onClearHostCell:c,panelPort:u=0,nodePanelPorts:h=null}){const[p,v]=Fn(),_=Vv(t),[g,w]=y.useState(null),[S,N]=y.useState(null),[C,j]=y.useState(!0),[E,R]=y.useState(""),[x,W]=y.useState(""),[$,Y]=y.useState({bind:"127.0.0.1",port:""}),[q,K]=y.useState(""),[se,V]=y.useState([]),[B,D]=y.useState([]),[O,P]=y.useState(!1),[z,A]=y.useState(null),[T,L]=y.useState({}),[H,M]=y.useState(new Set),[U,ee]=y.useState(null),{notice:re,showActionNotice:oe}=HC(),[je,te]=y.useState(null),[ie,pe]=y.useState(null),[xe,Be]=y.useState(!1),[Te,Me]=y.useState(null),[J,le]=y.useState(null),[Q,ge]=y.useState("preview"),[Z,fe]=y.useState(!1),{pins:ve,orders:ke,togglePin:Ve,removePin:ot,pinError:rt,reorderBlocked:$e,retryPinPersist:_e,clearPinError:ze,viewFor:Je,updateView:He,canMoveRoster:nt,moveRoster:lt,stepRoster:X}=Yv(),I=ue=>i[Rs(ue)]||{},{groupsFor:ce,moveNode:ye,stepNode:Re,nodeKey:ae}=Eh(),Oe=ce(_);y.useEffect(()=>{aD({sessions:g||[],cells:se,nodeGroups:_,localNodeId:q})},[g,se,_,q]),y.useEffect(()=>{const ue=new Map;for(const De of se)ue.set($a(De.cell),!!De.boot);for(const De of _){const Xe=De.route||[De.name];for(const ct of De.cells||[])ue.set($a(ct.cell,Xe),!!ct.boot)}L(De=>{let Xe=!1;const ct={...De};for(const[It,G]of Object.entries(De))ue.has(It)&&ue.get(It)===G&&(delete ct[It],Xe=!0);return Xe?ct:De})},[se,_]);function gt(){hc([],t)}y.useEffect(()=>{const De=Lc(t,[],Xe=>{if(!Xe)return;const ct=Xe.sessionsError?null:Xe.sessionsJson;ct&&!ct.error?(N(null),w(ct.sessions||[]),j(!0)):ct?(N(ct.error),w([]),j(!1)):(N(String(Xe.sessionsError)),w([]),j(!1));const It=kh({fs:Xe.fs,error:Xe.fleetError});It.kind==="data"?(Za("local",It.cells),V(It.cells),D(It.capabilities),P(!1),A(null)):It.kind==="stale"?(V(G=>G.length?G:qv("local")),P(!0),A(null)):(V([]),Za("local",[]),D([]),P(!1),A(It.reason||""))});return Vn("/api/config",t).then(Xe=>Xe.json()).then(Xe=>{W(Xe.version||""),Y({bind:Xe.bind||"127.0.0.1",port:Xe.port||""}),K(el.test(String(Xe.instanceId||""))?Xe.instanceId:"")}).catch(()=>{}),De},[t]);async function At(){if(!$.port)return;const ue=`http://${$.bind}:${$.port}/#token=${t}`;try{await navigator.clipboard.writeText(ue)}catch{}}function Lt(ue,De,Xe){const ct=$a(ue,De);L(It=>({...It,[ct]:!!Xe}))}function Rt(ue,De=[]){const Xe=$a(ue.cell,De);return Object.prototype.hasOwnProperty.call(T,Xe)?T[Xe]:!!ue.boot}async function zt(ue,De,Xe=[],ct){const It=$a(De.cell,Xe),G=typeof ct=="boolean"?ct:!Rt(De,Xe);Lt(De.cell,Xe,G),M(he=>new Set(he).add(It));try{await d1(t,{cell:De.cell,enabled:G},Xe),Xe.length||V(he=>he.map(Ie=>Ie.cell===De.cell?{...Ie,boot:G}:Ie))}catch(he){L(Ie=>{const Qe={...Ie};return delete Qe[It],Qe}),N(String((he==null?void 0:he.message)||he))}finally{M(he=>{const Ie=new Set(he);return Ie.delete(It),Ie})}}const ft=(ue,De,Xe)=>({onToggleLive:async()=>{const ct=co({item:ue,cellName:De.cell,route:Xe,pins:ve,hostByRoute:i});Be(!0);const It=await gh({action:ct.isLive?"remove":"use",cellId:De.cell,route:Xe,token:t});Be(!1),Me({messageKey:It.messageKey,ok:It.ok,cell:It.hostCell||De.cell})},onTogglePin:()=>Xv({view:Nh({item:ue,pins:ve,hostByRoute:i,route:Xe}),itemKey:ue.key,togglePin:Ve,removePin:ot}),onToggleBoot:ct=>zt(null,De,Xe,ct),onWatchLive:()=>{ge("stream"),le(ue.key)}});async function Yt(ue){if(!U)return;let De=null;try{De=await n_({token:t,powerCell:U,payload:ue,onNotice:oe})}catch(Xe){throw oe(String(Xe&&Xe.message||Xe)),Xe}if(!De){const{cell:Xe}=U,ct=Array.isArray(U.route)?U.route:[];ue.action==="up"?Lt(Xe,ct,!!ue.boot):ue.boot&&Lt(Xe,ct,!1)}gt()}const $t=y.useMemo(()=>{if(!U)return null;const ue=(Array.isArray(U.route)?U.route:[]).join("/"),Xe=[...se,..._.flatMap(ct=>(ct.cells||[]).map(It=>({...It,route:ct.route||[ct.name]})))].find(ct=>ct.cell===U.cell&&(Array.isArray(ct.route)?ct.route.join("/"):"")===ue);return Xe?{...U,active:!!Xe.active}:U},[U,se,_]);async function Zt(ue,De=[]){try{await _v(t,ue,De)}catch{return}gt()}async function Bt(ue,De,Xe=[]){try{await p1(t,ue,De,Xe)}catch{return}gt()}async function Yn(ue){if(!(!(ue!=null&&ue.direct)||je)){te(ue.name);try{await wv(t,ue.name,ue.tunnelStatus==="up"?"down":"up")}catch{}te(null)}}async function nn(ue){if(!(ue!=null&&ue.direct))return;const De=window.prompt(f("rename-node-prompt"),ue.label||ue.name);if(De===null)return;const Xe=String(De).trim();if(!tl(Xe)){window.alert(f("rename-node-invalid"));return}try{await y1(t,ue.name,Xe)}catch(ct){window.alert(String((ct==null?void 0:ct.message)||ct))}}const rn=y.useMemo(()=>new Map((g||[]).map(ue=>[ue.name,ue])),[g]),sn=y.useMemo(()=>new Set(se.map(ue=>ue.tmuxSession)),[se]),wn=y.useMemo(()=>(g||[]).filter(ue=>!sn.has(ue.name)),[g,sn]),Ft=y.useMemo(()=>e_(se,wn,rn,void 0,{autorevole:C,fleetStale:O}),[se,wn,rn,C,O]),on=y.useMemo(()=>{const ue=new Map;for(const De of Ft)De.type==="cell"&&ue.set(De.key,{item:De,route:[],nodeLabel:"",sessions:g||[],cells:se});for(const De of Oe){const Xe=Array.isArray(De.route)?De.route:[];if(!Xe.length||De.kind==="vl")continue;const{rawItems:ct}=Cc(De);for(const It of ct)It.type==="cell"&&ue.set(It.key,{item:It,route:Xe,nodeLabel:De.label||De.name||"",sessions:De.sessions||[],cells:De.cells||[]})}return ue},[Ft,Oe,g,se]),un=y.useMemo(()=>{if(!J)return null;const ue=on.get(J);if(!ue)return null;const De=ue.item.value,Xe=(ue.sessions||[]).find(ct=>ct.name===De.tmuxSession)||{};return{row:{key:ue.item.key,cellName:De.cell,subtitle:ue.item.subtitle||"",nodeLabel:ue.nodeLabel,node:ue.route.length?ue.route.join("/"):"",session:De.tmuxSession,route:ue.route,panelUrl:De.panelUrl||"",telemetry:Xe.telemetry||null,preview:Xe.preview||De.preview||"",activity:Xe.activity||De.activity||0},cells:ue.cells||[]}},[J,on]),Xt=Je("local"),dn=y.useMemo(()=>fo(Ft,ve,Xt.filter,Di(ke,"local")).filter(ue=>Z0(ue,E)),[Ft,ve,Xt.filter,E,ke]),Js=Oe.reduce((ue,De)=>ue+(De.cells||[]).length+(De.unmanaged||[]).filter(Xe=>!Xe.technical).length,0),ds=fo(Ft,ve,"all",Di(ke,"local")).length+Js,Vt=Ft.filter(ue=>ue.live).length+Oe.reduce((ue,De)=>ue+Cc(De).rawItems.filter(Xe=>Xe.live).length,0),Ms=(g||[]).filter(ue=>ue.attached).length+Oe.reduce((ue,De)=>ue+(De.sessions||[]).filter(Xe=>Xe.attached).length,0),Xn=Math.min(Ms,Vt),Ts=$.port?`${$.bind}:${$.port}`:$.bind;function kt(ue,De=null,Xe=Ft){var Et,Ct;const ct=Array.isArray(De==null?void 0:De.route)?De.route:[],It=ct.join("/"),G=It||"local",he=ct.length?De==null?void 0:De.instanceId:q,Ie=(Ze,Ee)=>e({session:Ze,...It?{node:It}:{},...el.test(String(he||""))?{ownerId:he}:{},...typeof Ee=="string"&&Ee?{cellName:Ee}:{}}),Qe=nt;if(ue.type==="cell"){const Ze=ue.value,Ee=I(ct),ut=$d({hostCell:Ee.hostCell??null,threadStatus:Ee.threadStatus,pins:ve,item:ue}),Pe=ct.length?((De==null?void 0:De.sessions)||[]).find(Gt=>Gt.name===Ze.tmuxSession):rn.get(Ze.tmuxSession),We=Im(ut,Ee.hostLease??null),vt=Ze.degraded?f("cell-degraded"):ue.subtitle||(Ze.tmux?f("cell-idle"):f("cell-off")),we=We?`${vt} · ${f(We)}`:vt,Le=ct.length===0||((De==null?void 0:De.capabilities)||[]).includes(Ze.active?"down":"up"),Ke=ct.length===0?B.includes("boot"):((De==null?void 0:De.capabilities)||[]).includes("boot"),at=Rt(Ze,ct),wt=co({item:ue,cellName:Ze.cell,route:ct,pins:ve,hostByRoute:i}),Nn=!!ie&&ie.itemKey===ue.key,hs=`${f("cell-actions-open")}: ${Ze.cell}`;return o.jsxs("div",{className:"nc-mcard","data-roster-key":ue.key,"data-position":G,children:[Z&&o.jsx(Qi,{position:G,itemKey:ue.key,label:Ze.cell,canMove:Qe,onMove:(Gt,Hn)=>lt(G,Gt,Hn,Xe),onStep:Gt=>X(G,ue.key,Gt,Xe)}),o.jsxs("button",{className:"nc-mcard-main",onClick:()=>Ze.tmux&&Ie(Ze.tmuxSession,Ze.cell),title:we,"aria-label":`${Ze.cell}, ${we}`,children:[o.jsx("span",{className:`dot ${Ze.degraded?"warn":Ze.tmux?`on${ue.working?" working":""}`:""}`}),o.jsxs("span",{className:"nc-mcard-text",children:[o.jsxs("span",{className:"nc-mcard-nome",children:[o.jsx("b",{children:Ze.cell}),wt.isLive&&o.jsx("span",{className:"nc-m-live",children:"LIVE"})]}),o.jsx("small",{title:ue.subtitle,children:ue.subtitle})]})]}),ue.activity?o.jsx("span",{className:"nc-rel",children:uo(ue.activity)}):null,ue.fresh&&((Et=Pe==null?void 0:Pe.outbox)==null?void 0:Et.count)>0&&o.jsx("span",{className:"nc-badge",title:f("new-files-outbox"),children:Pe.outbox.count}),o.jsx("button",{type:"button",className:`nc-act cellmenu${Nn?" on":""}`,title:hs,"aria-label":hs,"aria-haspopup":"menu","aria-expanded":Nn?"true":"false",onClick:()=>pe({itemKey:ue.key,item:ue,cell:Ze,route:ct,canBoot:Ke}),children:"⋯"}),Le&&o.jsx("button",{className:`nc-act power${Ze.tmux?" on":""}${Ze.degraded?" warn":""}`,onClick:()=>ee(ct.length?{...Ze,boot:at,route:ct,availableEngines:(De==null?void 0:De.engines)||[]}:{...Ze,boot:at}),title:Ze.active?f("power-off"):f("power-on"),"aria-label":`${Ze.active?f("power-off"):f("power-on")} ${Ze.cell}`,children:o.jsx(yt,{name:"power",size:16})})]},ue.key)}const Ae=ue.value;return o.jsxs("div",{className:"nc-mcard","data-roster-key":ue.key,"data-position":G,children:[o.jsx(Qi,{position:G,itemKey:ue.key,label:Ae.name,canMove:Qe,onMove:(Ze,Ee)=>lt(G,Ze,Ee,Xe),onStep:Ze=>X(G,ue.key,Ze,Xe)}),o.jsxs("button",{className:"nc-mcard-main",onClick:()=>Ie(Ae.name),children:[o.jsx("span",{className:Ae.attached?"dot on":"dot"}),o.jsxs("span",{className:"nc-mcard-text",children:[o.jsx("b",{children:Ae.name}),o.jsx("small",{children:Ae.preview?Ae.preview:Ae.cmd?Ae.cmd:f("windows").replace("{n}",String(Ae.windows||0))})]})]}),ue.activity?o.jsx("span",{className:"nc-rel",children:uo(ue.activity)}):null,ue.fresh&&((Ct=Ae.outbox)==null?void 0:Ct.count)>0&&o.jsx("span",{className:"nc-badge",title:f("new-files-outbox"),children:Ae.outbox.count}),o.jsx("button",{className:`nc-act pin${ve.includes(ue.key)?" on":""}`,"aria-label":`${f("pin")} ${Ae.name}`,title:f("pin"),onClick:()=>Ve(ue.key),children:ve.includes(ue.key)?"★":"☆"}),o.jsx("button",{className:`nc-act technical${Ae.technical?" on":""}`,title:Ae.technical?f("mark-normal"):f("mark-technical"),"aria-label":`${Ae.technical?f("mark-normal"):f("mark-technical")} ${Ae.name}`,onClick:()=>Bt(Ae.name,!Ae.technical,ct),children:"T"}),o.jsx("button",{className:"nc-menu",title:f("terminate"),"aria-label":`${f("terminate")} ${Ae.name}`,onClick:()=>{window.confirm(f("terminate-confirm").replace("{name}",Ae.name))&&Zt(Ae.name,ct)},children:"⋯"})]},ue.key)}return o.jsxs("div",{className:"nc-home",children:[o.jsxs("header",{className:"nc-home-head",children:[o.jsxs("div",{className:"nc-wordmark",children:["NexusCrew",o.jsx("span",{className:"nc-cursor"})]}),o.jsxs("div",{className:"nc-home-sub",children:[f("fleet-tmux")," · ",Vt," ",f("sessions"),Xn>0&&` · ${Xn} attached`]}),o.jsxs("span",{className:"nc-head-actions",children:[o.jsx("button",{className:`nc-refresh${Z?" on":""}`,onClick:()=>fe(ue=>!ue),"aria-pressed":Z,title:f("reorder-help"),"aria-label":f("reorder"),children:"↕"}),o.jsx("button",{className:"nc-refresh",onClick:()=>n("nodes",!1),title:f("settings"),children:o.jsx(yt,{name:"gear",size:18})}),o.jsx("button",{className:"nc-refresh",onClick:gt,title:f("refresh"),children:o.jsx(yt,{name:"refresh",size:18})})]})]}),o.jsxs("main",{className:"nc-home-scroll",children:[o.jsx(cD,{view:Ja({liveHost:i[Rs([])],cells:se}),notice:Te}),o.jsx(wC,{pinError:rt,onRetry:_e,onDismiss:ze}),ds>8&&o.jsx("input",{className:"nc-filter",type:"search",placeholder:f("filter-placeholder"),"aria-label":f("filter-placeholder"),value:E,onChange:ue=>R(ue.target.value)}),S&&o.jsx("div",{className:"nc-err",children:S}),re&&o.jsx("div",{className:"nc-notice",role:"status",children:re}),O&&o.jsx("div",{className:"nc-set-hint nc-fleet-stale",role:"status",children:f("fleet-stale")}),$e&&o.jsxs("div",{className:"nc-set-hint nc-reorder-blocked",role:"status",children:[f("reorder-blocked")," (",$e.reason,")"]}),z!==null&&o.jsxs("div",{className:"nc-set-hint nc-fleet-off",role:"status",children:[f("fleet-off"),z?` (${z})`:""]}),o.jsxs("section",{className:"nc-group","data-position":"local",children:[o.jsx(Hp,{label:f("position-local"),count:dn.length,state:Xt,dotClass:"on",onToggle:()=>He("local",{open:!Xt.open}),onFilter:ue=>He("local",{filter:ue})}),Xt.open&&dn.map(ue=>kt(ue,null,Ft)),Xt.open&&g===null&&o.jsx("div",{className:"nc-empty",children:f("loading-fleet")}),Xt.open&&g!==null&&dn.length===0&&!S&&o.jsx("div",{className:"nc-empty",children:E?f("no-match").replace("{q}",E):f("no-sessions-short")})]}),Oe.map(ue=>{const De=EC(ue.health,{passive:"warn"}),Xe=ue.fleetState==="stale"?f("fleet-stale"):ue.fleetState==="disabled"?f("fleet-off"):"",ct=ue.fleetState==="stale"?"warn":De||(ue.status==="up"?"on":ue.status==="passive"?"":"warn"),It=[ue.health?Yd(ue.health):tr(ue),Xe].filter(Boolean).join(" · "),he=(ue.route&&ue.route.length?ue.route:[ue.name]).join("/"),Ie=Je(he);if(ue.kind==="vl")return o.jsxs("section",{className:"nc-group nc-node-order-wrap","data-position":he,"data-node-order-key":ae(ue),children:[o.jsx(Hp,{label:ue.label||ue.name,count:ue.sessions.length,state:Ie,dotClass:ct,dotTitle:It,detail:tr(ue),onToggle:()=>He(he,{open:!Ie.open}),onFilter:Ze=>He(he,{filter:Ze})}),ue.status==="up"&&Ie.open&&ue.sessions.map(Ze=>o.jsx("div",{className:"nc-mcard nc-vl-session-row",children:o.jsxs("button",{className:"nc-mcard-main",onClick:()=>s&&s(ue.peer),"aria-label":`${ue.label||ue.name}: ${Ze.name}`,children:[o.jsx("span",{className:"dot on"}),o.jsxs("span",{className:"nc-mcard-text",children:[o.jsx("b",{children:Ze.name}),o.jsx("small",{children:f("vl-events-title")})]})]})},Ze.key)),ue.status==="up"&&Ie.open&&ue.sessions.length===0&&o.jsx("div",{className:"nc-empty",children:f("no-sessions-short")})]},`nodo-vl-${he}-${ue.name}`);const{rawItems:Qe}=Cc(ue),Ae=fo(Qe,ve,Ie.filter,Di(ke,he)).filter(Ze=>Z0(Ze,E)),Et=ue.direct&&ue.health&&ue.health.managed!==!1?o.jsx("button",{type:"button",className:`nc-act power${ue.tunnelStatus==="up"?" on":""}`,disabled:je===ue.name,title:ue.tunnelStatus==="up"?f("power-off"):f("power-on"),"aria-label":`${ue.tunnelStatus==="up"?f("power-off"):f("power-on")} ${ue.label||ue.name}`,onClick:()=>Yn(ue),children:o.jsx(yt,{name:"power",size:15})}):null,Ct=o.jsxs("span",{className:"nc-node-actions",children:[o.jsx(Qi,{scope:"node",position:"nodes",itemKey:ae(ue),label:ue.label||ue.name,onMove:(Ze,Ee)=>ye(Ze,Ee,_),onStep:Ze=>Re(ae(ue),Ze,_)}),ue.direct&&o.jsx("button",{type:"button",className:"nc-node-rename",title:f("rename-node"),"aria-label":`${f("rename-node")} ${ue.label||ue.name}`,onClick:()=>nn(ue),children:"✎"}),Et]});return o.jsxs("section",{className:"nc-group nc-node-order-wrap","data-position":he,"data-node-order-key":ae(ue),children:[o.jsx(Hp,{label:ue.label||ue.name,count:Ae.length,state:Ie,dotClass:ct,dotTitle:It,detail:ue.status==="up"?[tr(ue),Xe].filter(Boolean).join(" · "):ue.health&&Yd(ue.health)||tr(ue),onToggle:()=>He(he,{open:!Ie.open}),onFilter:Ze=>He(he,{filter:Ze}),onRename:ue.direct?()=>nn(ue):null,action:Ct}),ue.status==="up"&&Ie.open&&Ae.map(Ze=>kt(Ze,ue,Qe)),ue.status==="up"&&Ie.open&&Ae.length===0&&o.jsx("div",{className:"nc-empty",children:E?f("no-match").replace("{q}",E):f("no-sessions-short")})]},`nodo-${he}`)}),o.jsxs("footer",{className:"nc-home-foot",onClick:At,title:f("copy-url"),children:[o.jsxs("span",{className:"nc-home-meta",children:[x&&o.jsxs("span",{className:"nc-home-version",children:["v",x]}),o.jsxs("span",{className:"nc-home-endpoint",children:[Ts," · ",f("ssh-only")]})]}),o.jsx("span",{className:"nc-lang",onClick:ue=>ue.stopPropagation(),children:k1.map((ue,De)=>o.jsxs("span",{children:[De>0&&" · ",o.jsx("button",{className:`nc-lang-btn${p===ue?" on":""}`,onClick:()=>v(ue),title:ue,children:ue.toUpperCase()})]},ue))})]})]}),$t&&o.jsx(Gd,{cell:$t,token:t,route:Array.isArray($t.route)?$t.route:[],onConfirm:Yt,onClose:()=>ee(null)}),un&&o.jsx(aC,{row:un.row,token:t,initialSource:Q,panelPort:Oc(un.row.route||[],h,u),liveHost:Ja({liveHost:i[Rs(un.row.route||[])],cells:un.cells}),onClose:()=>{le(null),ge("preview")}}),ie&&(()=>{const{item:ue,cell:De,route:Xe=[],canBoot:ct}=ie,It=co({item:ue,cellName:De.cell,route:Xe,pins:ve,hostByRoute:i}),G=Jv({...It,canBoot:ct,boot:Rt(De,Xe),alive:!!De.tmux,handlers:ft(ue,De,Xe)});return o.jsx(Qv,{cellName:De.cell,items:G,busy:xe||H.has($a(De.cell,Xe)),onClose:()=>pe(null)})})()]})}function cD({view:e,notice:t}){const n=!!(e&&e.cell),s=n?f("live-host-indicator").replace("{cell}",e.cell).replace("{mode}",f(e.mode?`live-host-mode-${e.mode}`:"live-host-mode-unknown")).replace("{state}",f(`live-host-state-${e.state||"none"}`)):f("live-host-indicator-none");return o.jsxs("div",{className:"nc-m-live-strip","data-state":e&&e.state?e.state:"none",title:t?`${s} · ${f(t.messageKey)}`:s,children:[o.jsx("span",{className:`nc-m-live-dot ${kv(e||{})}`,"aria-hidden":"true"}),o.jsx("span",{className:"nc-m-live-testo",children:n?e.cell:s}),o.jsx(T1,{view:e}),t&&o.jsx("span",{className:`nc-m-live-notice${t.ok?" ok":" ko"}`,role:"status",children:f(t.messageKey).replace("{cell}",t.cell||e.cell||"")})]})}function Hp({label:e,count:t,state:n,dotClass:s="",dotTitle:i="",detail:l="",onToggle:c,onFilter:u,onRename:h=null,action:p=null}){return o.jsxs("div",{className:"nc-mobile-position-head",onContextMenu:h?v=>{v.preventDefault(),h()}:void 0,children:[o.jsxs("button",{type:"button",className:"nc-mobile-position-toggle",onClick:c,"aria-expanded":n.open,"aria-label":`${e} · ${f("node-sessions").replace("{n}",String(t))}`,children:[o.jsx("span",{className:"nc-mobile-chevron","aria-hidden":"true",children:n.open?"⌄":"›"}),o.jsx("span",{className:`dot ${s}`,title:i}),o.jsxs("span",{className:"nc-mobile-position-copy",children:[o.jsx("b",{children:e}),o.jsx("small",{children:l||f("node-sessions").replace("{n}",String(t))})]})]}),o.jsxs("select",{className:"nc-mobile-position-filter",value:n.filter,"aria-label":`${e} · ${f("filter-placeholder")}`,title:f(`view-${n.filter}`),onChange:v=>u(v.target.value),children:[o.jsx("option",{value:"all",children:f("view-all")}),o.jsx("option",{value:"pinned",children:f("view-pinned")}),o.jsx("option",{value:"active",children:f("view-active")}),o.jsx("option",{value:"off",children:f("view-off")}),o.jsx("option",{value:"technical",children:f("view-technical")})]}),p]})}const vS="",cn="\x1B",uD=[{label:"↑",seq:cn+"[A"},{label:"↓",seq:cn+"[B"},{label:"PGUP",seq:cn+"[5~"},{label:"PGDN",seq:cn+"[6~"}],dD=new Set([cn+"[A",cn+"[B",cn+"[C",cn+"[D",cn+"[5~",cn+"[6~"]),hD=350,fD=55;function pD({send:e,action:t,ctrlArmed:n=!1,onCtrl:s,altArmed:i=!1,onAlt:l,onAltConsume:c,onKeyboard:u,selectionMode:h=!1,onSelectionMode:p,onCellSwitcher:v,cellSwitcherOpen:_=!1,keepKeyboardClosed:g=!0,showEnter:w=!0,keybarLayout:S="full",onKeyboardKeep:N}){const[C,j]=y.useState(!1),[E,R]=y.useState(!1),[x,W]=y.useState(!1),$=S==="compact"&&!x,Y=y.useRef({delay:null,interval:null}),q=y.useRef(()=>{}),K=()=>{const M=Y.current;M.delay!==null&&clearTimeout(M.delay),M.interval!==null&&clearInterval(M.interval),M.delay=null,M.interval=null};q.current=K,y.useEffect(()=>{const M=()=>{document.visibilityState==="hidden"&&q.current()},U=()=>q.current();return window.addEventListener("blur",U),document.addEventListener("visibilitychange",M),()=>{window.removeEventListener("blur",U),document.removeEventListener("visibilitychange",M),q.current()}},[]),y.useEffect(()=>{S!=="compact"&&W(!1)},[S]);const se=M=>{i?(e(cn+M),c&&c()):e(M)},V=(M,{keepOpen:U}={})=>{g&&!U&&Ng(),U&&N&&N(),M()},B=(M,U={})=>({onPointerDown:ee=>{ee.preventDefault(),V(M,U)},onClick:ee=>{ee.detail===0&&V(M,U)}}),D=(M,U={})=>({onPointerDown:ee=>{ee.preventDefault(),K(),V(M,U),!i&&(Y.current.delay=setTimeout(()=>{Y.current.delay=null,M(),Y.current.interval=setInterval(M,fD)},hD))},onPointerUp:K,onPointerLeave:K,onPointerCancel:K,onLostPointerCapture:K,onTouchCancel:K,onClick:ee=>{ee.detail===0&&V(M,U)}}),O=(M,U,ee)=>o.jsx("button",{type:"button",...dD.has(U)&&!ee?D(()=>se(U)):B(()=>{se(U),ee&&ee()}),children:M},M),P=(M,U)=>o.jsx("button",{type:"button",...B(()=>{t(U),R(!1)}),children:M},M),z=v?o.jsx("button",{type:"button","aria-label":f("fleet-cells"),title:f("fleet-cells"),"aria-expanded":_,...B(v),children:"◫"},"cells"):o.jsx("button",{type:"button",...B(()=>{u&&u()}),children:"⌨"},"kbd"),A=w&&o.jsx("button",{type:"button",className:"nc-enter-key","aria-label":"ENTER",title:"ENTER",...B(()=>se("\r")),children:o.jsx(yt,{name:"enter",size:24})}),T=E&&o.jsxs("div",{className:"nc-keymenu",children:[P("←WIN","prev-window"),P("WIN→","next-window"),P("⬅PANE","pane-left"),P("PANE➡","pane-right"),O("SCROLL",vS+"[",()=>{j(!0),R(!1)}),o.jsx("button",{type:"button",className:h?"armed":"",...B(()=>{p==null||p(!h),R(!1)}),children:"SELECT"}),O("⌃C","",()=>R(!1)),O("DETACH",vS+"d",()=>R(!1))]});if(C)return o.jsxs("div",{className:"nc-keybar copy",children:[o.jsx("span",{className:"tag",children:"copy-mode"}),uD.map(M=>O(M.label,M.seq)),O("ESCI (q)","q",()=>j(!1))]});if($)return o.jsxs("div",{className:"nc-keybar termux",children:[T,o.jsxs("div",{className:`nc-keygrid compact${w?"":" no-enter"}`,children:[o.jsx("div",{className:"nc-keyrows",children:o.jsxs("div",{className:"row",children:[o.jsx("button",{type:"button","aria-label":f("keybar-expand"),title:f("expand"),...B(()=>W(!0)),children:o.jsx(yt,{name:"chevronUp",size:20})},"expand"),z,o.jsx("button",{type:"button",className:E?"armed":"",...B(()=>R(M=>!M)),children:"☰"},"menu"),O("↑",cn+"[A"),O("↓",cn+"[B"),O("←",cn+"[D"),O("→",cn+"[C"),O("PGUP",cn+"[5~"),O("PGDN",cn+"[6~")]})}),A]})]});const L=S==="compact"&&x,H=L&&o.jsx("button",{type:"button",className:"nc-retract-key","aria-label":f("keybar-retract"),title:f("retract"),...B(()=>W(!1)),children:o.jsx(yt,{name:"chevronDown",size:20})});return o.jsxs("div",{className:`nc-keybar termux${L?" expanded":""}`,children:[T,o.jsxs("div",{className:`nc-keygrid${w?"":" no-enter"}${L?" expanded":""}`,children:[H,o.jsxs("div",{className:"nc-keyrows",children:[o.jsxs("div",{className:"row",children:[O("ESC",cn),o.jsx("button",{type:"button",className:E?"armed":"",...B(()=>R(M=>!M)),children:"☰"},"menu"),O("/","/"),O("—","-"),O("HOME",cn+"[H"),O("↑",cn+"[A"),O("END",cn+"[F"),O("PGUP",cn+"[5~")]}),o.jsxs("div",{className:"row",children:[O("⇥"," "),z,o.jsx("button",{type:"button",className:n?"armed":"",...B(()=>{s&&s()},{keepOpen:!0}),children:"CTRL"},"ctrl"),o.jsx("button",{type:"button",className:i?"armed":"",...B(()=>{l&&l()},{keepOpen:!0}),children:"ALT"},"alt"),O("←",cn+"[D"),O("↓",cn+"[B"),O("→",cn+"[C"),O("PGDN",cn+"[6~")]})]}),A]})]})}const UC=/^(\d+-)?(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})_/;function mD(e){return String(e||"").replace(UC,"$1")}const gD=/^\d{4}-\d{2}-\d{2}_/;function nl(e){const t=String(e||"");let n=mD(t);return n=n.replace(gD,""),n||t}function vD(e){const t=UC.exec(String(e||""));if(!t)return null;const[n,s,i,l,c]=[Number(t[2]),Number(t[3]),Number(t[4]),Number(t[5]),Number(t[6])],u=new Date(n,s-1,i,l,c);return u.getFullYear()!==n||u.getMonth()!==s-1||u.getDate()!==i||u.getHours()!==l||u.getMinutes()!==c?null:u}function Hc(e,t){const n=vD(e);if(n)return n;const s=Number(t);return Number.isFinite(s)&&s>0?new Date(s):new Date(0)}function Ec(e){const t=Number(e)||0;return t>=1048576?`${(t/1048576).toFixed(1)} MB`:t>=1024?`${Math.max(1,Math.round(t/1024))} KB`:`${t} B`}function Qd(e){return String(e).padStart(2,"0")}function WC(e){return`${Qd(e.getHours())}:${Qd(e.getMinutes())}`}function qC(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function Go(e){const t=nl(e),n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n+1).toUpperCase().slice(0,4)}function KC(e,t,n){const s=WC(e);return qC(e,t)?s:`${new Intl.DateTimeFormat(n||"en",{day:"numeric",month:"short"}).format(e)} ${s}`}function _D(e,t,n,s=""){const i=new Intl.DateTimeFormat(n||"en",{day:"numeric",month:"long"}).format(e);return qC(e,t)&&s?`${s} · ${i}`:i}function VC(e,t){return`${new Intl.DateTimeFormat(t||"en",{day:"numeric",month:"long",year:"numeric"}).format(e)}, ${WC(e)}`}function yD(e){return`${e.getFullYear()}-${Qd(e.getMonth()+1)}-${Qd(e.getDate())}`}const bD=new Set(["PNG","JPG","JPEG","GIF","WEBP","SVG","PDF","TXT","MD","JSON"]);function wD(e){return bD.has(Go(e))}const SD=new Set(["PNG","JPG","JPEG","GIF","WEBP","PDF","TXT","MD","JSON"]);function GC(e){return SD.has(Go(e))}const xD=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","text/markdown","application/json"]);function kD(e){const t=String(e||"").split(";")[0].trim().toLowerCase();return xD.has(t)}const CD=new Set(["PNG","JPG","JPEG","GIF","WEBP","SVG","BMP","ICO","AVIF","HEIC"]),ED=new Set(["TXT","MD","JSON","PDF","CSV","LOG","HTML","HTM","XML","YML","YAML","DOC","DOCX","ODT","RTF","XLS","XLSX","PPT","PPTX"]);function ND(e){const t=Go(e);return CD.has(t)?"image":ED.has(t)?"document":"other"}function YC(e){const t=new Map;for(const n of e||[]){const s=nl(n&&n.name);t.set(s,(t.get(s)||0)+1)}return t}function XC(e,t,n,s=""){const i=(e||[]).map(u=>({...u,when:Hc(u.name,u.mtime)}));i.sort((u,h)=>h.when-u.when||String(u.name).localeCompare(String(h.name)));const l=[],c=new Map;for(const u of i){const h=yD(u.when);let p=c.get(h);p||(p={key:h,when:u.when,label:_D(u.when,t,n,s),files:[]},c.set(h,p),l.push(p)),p.files.push(u)}return l}function jD({file:e,box:t,session:n,previewable:s=!1,notice:i="",busy:l=!1,onClose:c,onActionStart:u,onDownload:h,onPreview:p,onDelete:v}){const[_,g]=y.useState(!1),[w,S]=y.useState(!1),N=e&&e.name;y.useEffect(()=>{g(!1),S(!1)},[N]),y.useEffect(()=>{const x=W=>{W.key==="Escape"&&c()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[c]);async function C(){u&&u(),S(await Dc(e?e.name:""))}const j=nl(N),E=Hc(N,e?e.mtime:0),R=Jo();return o.jsx("div",{className:"nc-filesheet-velo","data-testid":"file-actions-sheet",onClick:c,children:o.jsxs("div",{className:"nc-filesheet",role:"dialog","aria-modal":"true","aria-label":f("files-sheet-title"),onClick:x=>x.stopPropagation(),children:[o.jsxs("div",{className:"nc-filesheet-testa",children:[o.jsx("span",{className:"nc-filesheet-titolo",children:f("files-sheet-title")}),o.jsx("button",{type:"button",className:"nc-filesheet-chiudi",onClick:c,title:f("close"),"aria-label":f("close"),children:o.jsx(yt,{name:"x",size:18})})]}),o.jsxs("div",{className:"nc-filesheet-file",children:[o.jsx("span",{className:"nc-filesheet-nome",children:j}),o.jsxs("div",{className:"nc-filesheet-originale",children:[o.jsx("span",{className:"nc-filesheet-label",children:f("files-original-name")}),o.jsx("code",{className:"nc-filesheet-mono",children:N})]}),o.jsxs("small",{className:"nc-filesheet-meta",children:[VC(E,R)," · ",Ec(e?e.size:0)," · ",t==="outbox"?"Outbox":"Inbox"," · ",n]})]}),i&&o.jsx("div",{className:"nc-filesheet-notice",role:"status",children:i}),_?o.jsxs("div",{className:"nc-filesheet-conferma","data-testid":"file-delete-confirm",children:[o.jsx("b",{className:"nc-filesheet-conferma-titolo",children:f("files-delete-confirm").replace("{name}",j)}),o.jsx("small",{className:"nc-filesheet-conferma-aiuto",children:f("files-delete-confirm-help")}),o.jsxs("div",{className:"nc-filesheet-conferma-azioni",children:[o.jsx("button",{type:"button",onClick:()=>g(!1),disabled:l,children:f("cancel")}),o.jsx("button",{type:"button",className:"danger",disabled:l,"data-fileaction":"delete-confirm",onClick:()=>v(e),children:f("delete")})]})]}):o.jsxs("div",{className:"nc-filesheet-azioni",role:"menu",children:[s&&o.jsxs("button",{type:"button",role:"menuitem",disabled:l,"data-fileaction":"preview",onClick:()=>{u&&u(),p(e)},children:[o.jsx(yt,{name:"eye",size:20}),o.jsx("span",{children:f("files-preview")})]}),o.jsxs("button",{type:"button",role:"menuitem",disabled:l,"data-fileaction":"download",onClick:()=>{u&&u(),h(e)},children:[o.jsx(yt,{name:"download",size:20}),o.jsx("span",{children:f("files-download-action")})]}),o.jsxs("button",{type:"button",role:"menuitem",disabled:l,"data-fileaction":"copy",onClick:C,"aria-live":"polite",children:[o.jsx(yt,{name:"copy",size:20}),o.jsx("span",{children:f(w?"files-copied-name":"files-copy-name")})]}),o.jsxs("button",{type:"button",role:"menuitem",className:"danger",disabled:l,"data-fileaction":"delete",onClick:()=>g(!0),children:[o.jsx(yt,{name:"trash",size:20}),o.jsx("span",{children:f("files-delete-ellipsis")})]})]})]})})}const LD=new Set(["TXT","MD","JSON"]),RD=new Set(["PNG","JPG","JPEG","GIF","WEBP","SVG","BMP","ICO","AVIF"]),AD=8e3;function MD({session:e,node:t,token:n,box:s,onBox:i,counts:l,rows:c,visible:u,busy:h,notice:p="",error:v="",onNotice:_,sheetFile:g,onSheet:w,onClose:S,onRefresh:N,fetchBlob:C,onDownload:j,onPreview:E,onDelete:R,query:x,onQuery:W}){const[$,Y]=y.useState("all"),[q,K]=y.useState(""),[se,V]=y.useState(!1),[B,D]=y.useState(!1),[O,P]=y.useState(null),z=y.useRef(null),A=y.useRef(null),T=y.useRef(null),L=Jo(),H=new Date,M=$==="all"?u:u.filter(J=>ND(J.name)===$),U=XC(M,H,L,f("files-today")),ee=YC(M),re=U.flatMap(J=>J.files),oe=q?c.find(J=>J.name===q):null,je=oe?oe.name:"";y.useEffect(()=>{q&&!c.some(J=>J.name===q)&&K("")},[c,q]),y.useEffect(()=>{V(!1),D(!1)},[je]),y.useEffect(()=>{if(P(null),!je||!wD(je))return;let J=!0,le="";return(async()=>{const Q=await C(je);if(!J||!Q)return;const ge=Go(je);if(LD.has(ge)){const Z=await Q.text();J&&P({kind:"text",text:Z.slice(0,AD)})}else RD.has(ge)&&(le=URL.createObjectURL(Q),J&&P({kind:"img",url:le}))})(),()=>{J=!1,le&&URL.revokeObjectURL(le)}},[je,s,e,t]),y.useEffect(()=>{if(!q)return;const J=A.current?A.current.querySelector('[data-sel="1"]'):null;J&&typeof J.scrollIntoView=="function"&&J.scrollIntoView({block:"nearest"})},[q]),y.useEffect(()=>{const J=le=>{if(g)return;const Q=le.target;if(!(Q&&(Q.tagName==="INPUT"||Q.tagName==="TEXTAREA"||Q.tagName==="SELECT"||Q.tagName==="BUTTON"||Q.tagName==="A"||Q.isContentEditable))){if(le.key==="/"){le.preventDefault(),z.current&&z.current.focus();return}if(le.key==="ArrowDown"||le.key==="ArrowUp"){if(le.preventDefault(),!re.length)return;const ge=re.map(ve=>ve.name),Z=q?ge.indexOf(q):-1,fe=Z<0?le.key==="ArrowDown"?0:ge.length-1:Math.min(ge.length-1,Math.max(0,Z+(le.key==="ArrowDown"?1:-1)));K(ge[fe]);return}le.key==="Enter"&&oe&&(le.preventDefault(),w(oe.name))}};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)});async function te(J){const le=Array.from(J.target.files||[]);if(J.target.value="",!le.length)return;const{errors:Q}=await Vd({files:le,token:n,session:e,node:t,paste:!1});if(Q&&Q.length){const ge=Q[0]||{};_(f("files-upload-failed").replace("{e}",String(ge.message||ge.error||"")))}N()}async function ie(){D(await Dc(oe?oe.name:""))}const pe=oe?nl(oe.name):"",xe=oe?Hc(oe.name,oe.mtime):null,Be=x.trim()||f($==="image"?"files-filter-images":"files-filter-docs"),Te=M.reduce((J,le)=>J+(Number(le.size)||0),0),Me=t?`${t}:${e}`:e;return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"nc-filesd-head",children:[o.jsxs("div",{className:"nc-filesd-titolo",children:[o.jsx("b",{children:f("files-of").replace("{session}",Me)}),o.jsxs("span",{className:"nc-filesd-percorso",children:[t?`${t} · `:"","~/NexusFiles/",e,"/",s]})]}),o.jsxs("button",{type:"button",className:"nc-filesd-upload",onClick:()=>T.current&&T.current.click(),children:[o.jsx(yt,{name:"upload",size:16}),o.jsx("span",{children:f("files-upload")})]}),o.jsx("input",{ref:T,type:"file",multiple:!0,className:"nc-filesd-upload-input",tabIndex:-1,"aria-hidden":"true",onChange:te}),o.jsx("button",{type:"button",className:"nc-ntf-x",onClick:S,title:f("close"),"aria-label":f("close"),children:o.jsx(yt,{name:"x",size:16})})]}),o.jsxs("div",{className:"nc-filesd-bar",children:[o.jsxs("nav",{className:"nc-filesd-seg",children:[o.jsx("button",{type:"button",className:s==="outbox"?"on":"",onClick:()=>i("outbox"),children:f("files-outbox").replace("{n}",String(l.outbox))}),o.jsx("button",{type:"button",className:s==="inbox"?"on":"",onClick:()=>i("inbox"),children:f("files-inbox").replace("{n}",String(l.inbox))})]}),o.jsxs("div",{className:"nc-filesd-search",children:[o.jsx(yt,{name:"search",size:16}),o.jsx("input",{ref:z,type:"search",value:x,onChange:J=>W(J.target.value),placeholder:f("files-search-ph"),"aria-label":f("files-search"),enterKeyHint:"search","data-testid":"files-search-input"}),o.jsx("kbd",{className:"nc-filesd-kbd","aria-hidden":"true",children:"/"})]}),o.jsxs("div",{className:"nc-filesd-filtri",children:[o.jsx("button",{type:"button",className:$==="all"?"on":"","aria-pressed":$==="all",onClick:()=>Y("all"),children:f("files-filter-all")}),o.jsx("button",{type:"button",className:$==="document"?"on":"","aria-pressed":$==="document",onClick:()=>Y("document"),children:f("files-filter-docs")}),o.jsx("button",{type:"button",className:$==="image"?"on":"","aria-pressed":$==="image",onClick:()=>Y("image"),children:f("files-filter-images")})]})]}),o.jsxs("div",{className:"nc-filesd-main",children:[o.jsxs("div",{className:"nc-filesd-list",ref:A,children:[U.map(J=>o.jsxs("section",{className:"nc-filesd-daygroup",children:[o.jsx("h3",{className:"nc-filesd-day",children:J.label}),o.jsx("div",{className:"nc-filesd-rows",role:"grid","aria-label":J.label,children:J.files.map(le=>{const Q=nl(le.name),ge=ee.get(Q)||1,Z=le.name===q;return o.jsxs("div",{role:"row","aria-selected":Z,"data-sel":Z?"1":void 0,className:Z?"nc-filesd-row sel":"nc-filesd-row",onClick:()=>K(le.name),children:[o.jsx("span",{className:"nc-files-type","aria-hidden":"true",children:Go(le.name)||o.jsx(yt,{name:"file",size:18})}),o.jsxs("span",{className:"nc-filesd-name",children:[Q,ge>1&&o.jsxs("span",{className:"nc-files-dup",children:[o.jsx("span",{"aria-hidden":"true",children:`×${ge}`}),o.jsx("span",{className:"nc-sr-only",children:f("files-dupes").replace("{n}",String(ge))})]})]}),o.jsx("span",{className:"nc-filesd-quando",children:KC(Hc(le.name,le.mtime),H,L)}),o.jsx("span",{className:"nc-filesd-dim",children:Ec(le.size)}),o.jsx("span",{className:"nc-filesd-cella",children:o.jsx("button",{type:"button",className:"nc-filesd-dl",onClick:()=>j(le.name),title:f("files-download"),"aria-label":`${f("files-download")} ${Q}`,children:o.jsx(yt,{name:"download",size:18})})}),o.jsx("span",{className:"nc-filesd-cella",children:o.jsx("button",{type:"button",className:"nc-filesd-more",onClick:()=>w(le.name),title:f("files-actions"),"aria-label":`${f("files-actions")} ${Q}`,children:o.jsx(yt,{name:"more",size:18})})})]},le.name)})})]},J.key)),c.length===0&&o.jsx("div",{className:"nc-files-empty",children:f("empty-files")}),c.length>0&&M.length===0&&o.jsx("div",{className:"nc-files-empty",children:f("files-no-match").replace("{q}",Be)})]}),o.jsx("aside",{className:"nc-filesd-detail",children:oe?o.jsxs(o.Fragment,{children:[O&&O.kind==="text"&&o.jsx("pre",{className:"nc-filesd-prev-text","data-testid":"files-detail-text",children:O.text}),O&&O.kind==="img"&&o.jsx("img",{className:"nc-filesd-prev-img","data-testid":"files-detail-img",src:O.url,alt:pe}),o.jsx("b",{className:"nc-filesd-nome",children:pe}),o.jsxs("div",{className:"nc-filesd-originale",children:[o.jsx("span",{className:"nc-filesd-label",children:f("files-original-name")}),o.jsx("code",{className:"nc-filesd-mono",children:oe.name})]}),o.jsxs("dl",{className:"nc-filesd-meta",children:[o.jsxs("div",{children:[o.jsx("dt",{children:f("files-meta-date")}),o.jsx("dd",{children:VC(xe,L)})]}),o.jsxs("div",{children:[o.jsx("dt",{children:f("files-meta-size")}),o.jsx("dd",{children:Ec(oe.size)})]}),o.jsxs("div",{children:[o.jsx("dt",{children:f("files-meta-folder")}),o.jsxs("dd",{children:[s==="outbox"?"Outbox":"Inbox"," · ",Me]})]}),o.jsxs("div",{children:[o.jsx("dt",{children:f("files-meta-type")}),o.jsx("dd",{children:Go(oe.name)||"—"})]})]}),o.jsxs("div",{className:"nc-filesd-azioni",children:[o.jsxs("button",{type:"button",className:"primario",onClick:()=>j(oe.name),children:[o.jsx(yt,{name:"download",size:16}),o.jsx("span",{children:f("files-download-action")})]}),GC(oe.name)&&o.jsxs("button",{type:"button",onClick:()=>E(oe.name),children:[o.jsx(yt,{name:"eye",size:16}),o.jsx("span",{children:f("files-open")})]}),o.jsxs("button",{type:"button",onClick:ie,"aria-live":"polite",children:[o.jsx(yt,{name:"copy",size:16}),o.jsx("span",{children:f(B?"files-copied-name":"files-copy-name")})]}),o.jsxs("button",{type:"button",className:"danger",onClick:()=>V(!0),children:[o.jsx(yt,{name:"trash",size:16}),o.jsx("span",{children:f("files-delete-ellipsis")})]})]}),se&&o.jsxs("div",{className:"nc-filesd-conferma","data-testid":"files-detail-confirm",children:[o.jsx("b",{className:"nc-filesd-conferma-titolo",children:f("files-delete-confirm").replace("{name}",pe)}),o.jsx("small",{className:"nc-filesd-conferma-aiuto",children:f("files-delete-confirm-help")}),o.jsxs("div",{className:"nc-filesd-conferma-azioni",children:[o.jsx("button",{type:"button",onClick:()=>V(!1),disabled:!!h,children:f("cancel")}),o.jsx("button",{type:"button",className:"danger",disabled:!!h,"data-fileaction":"delete-confirm",onClick:()=>R(oe.name),children:f("delete")})]})]})]}):o.jsx("div",{className:"nc-filesd-detail-none",children:f("files-detail-none")})})]}),(v||p)&&!g&&o.jsx("div",{className:"nc-busy",role:"status",children:v||p}),o.jsxs("footer",{className:"nc-filesd-foot",children:[o.jsx("span",{children:f("files-footer-count").replace("{n}",String(M.length)).replace("{size}",Ec(Te))}),o.jsxs("span",{className:"nc-filesd-tasti",title:f("files-kbd-hint").replace("{enter}",f("files-kbd-enter")),children:[o.jsx("kbd",{children:"↑↓"}),o.jsx("kbd",{children:f("files-kbd-enter")}),o.jsx("kbd",{children:"/"})]})]})]})}const TD=6e4;function JC(e,t){const n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(n),TD)}const ID=6e4;function Kg({session:e,node:t,token:n,filesEvent:s,onClose:i}){Fn();const l=t?`/api/route/${String(t).split("/").map(encodeURIComponent).join("/")}/_`:"/api",c=t?`${t}:${e}`:e,[u,h]=y.useState("outbox"),[p,v]=y.useState({inbox:[],outbox:[]}),[_,g]=y.useState(!1),[w,S]=y.useState(""),[N,C]=y.useState(""),[j,E]=y.useState(""),[R,x]=y.useState(""),W=zv();async function $(){try{const M=await(await Vn(`${l}/files?session=${encodeURIComponent(e)}`,n)).json();if(M.error){S(M.error);return}S(""),C(""),v(M);const U=M.outbox[0]?M.outbox[0].mtime:0;localStorage.setItem(c1(c),String(U))}catch(H){S(String(H))}}y.useEffect(()=>{$()},[e,t]),y.useEffect(()=>{s&&s.session===e&&$()},[s]);async function Y(H){try{const M=await Vn(`${l}/files/download?session=${encodeURIComponent(e)}&box=${u}&name=${encodeURIComponent(H)}`,n);if(!M.ok){const U=await M.json().catch(()=>({}));return S(U.error?`errore: ${U.error}`:"errore download"),null}return await M.blob()}catch{return S("errore download"),null}}async function q(H){S(""),C(""),g(!0);try{const M=await Y(H);if(!M)return;JC(M,H)}catch{S("errore download")}finally{g(!1)}}async function K(H){S(""),C(""),g(!0);try{const M=await Y(H);if(!M)return;if(!kD(M.type)){C(f("files-preview-blocked"));return}const U=URL.createObjectURL(M);try{window.open(U,"_blank","noopener")}catch{URL.revokeObjectURL(U),S(f("files-preview-failed"));return}setTimeout(()=>URL.revokeObjectURL(U),ID)}finally{g(!1)}}async function se(H){S(""),C(""),g(!0);try{const M=await Vn(`${l}/files?session=${encodeURIComponent(e)}&box=${u}&name=${encodeURIComponent(H)}`,n,{method:"DELETE"});if(!M.ok){const U=await M.json().catch(()=>({}));S(U.error?`errore: ${U.error}`:"errore delete");return}R===H&&x(""),$()}catch{S("errore delete")}finally{g(!1)}}const V=Jo(),B=new Date,D=p[u]||[],O=j.trim().toLowerCase(),P=O?D.filter(H=>String(H.name||"").toLowerCase().includes(O)):D,z=XC(P,B,V,f("files-today")),A=YC(P),T=R?D.find(H=>H.name===R):null,L=T?o.jsx(jD,{file:T,box:u,session:t?`${t}:${e}`:e,previewable:GC(T.name),notice:w||N,busy:_,onClose:()=>x(""),onActionStart:()=>{S(""),C("")},onDownload:H=>{x(""),q(H.name)},onPreview:H=>K(H.name),onDelete:H=>se(H.name)}):null;return W?o.jsxs("div",{className:"nc-files nc-files-d",children:[o.jsx(MD,{session:e,node:t,token:n,box:u,onBox:h,counts:{outbox:(p.outbox||[]).length,inbox:(p.inbox||[]).length},rows:D,visible:P,busy:_,notice:N,error:w,onNotice:S,sheetFile:T,onSheet:x,onClose:i,onRefresh:$,fetchBlob:Y,onDownload:q,onPreview:K,onDelete:se,query:j,onQuery:E}),L]}):o.jsxs("div",{className:"nc-files",children:[o.jsxs("header",{children:[o.jsx("b",{children:t?`${t}:${e}`:e}),o.jsx("button",{type:"button",className:"nc-ntf-x",onClick:i,title:f("close"),"aria-label":f("close"),children:o.jsx(yt,{name:"x",size:16})})]}),o.jsxs("nav",{children:[o.jsx("button",{className:u==="outbox"?"on":"",onClick:()=>h("outbox"),children:f("files-outbox").replace("{n}",String((p.outbox||[]).length))}),o.jsx("button",{className:u==="inbox"?"on":"",onClick:()=>h("inbox"),children:f("files-inbox").replace("{n}",String((p.inbox||[]).length))})]}),o.jsxs("div",{className:"nc-files-search",children:[o.jsx(yt,{name:"search",size:16}),o.jsx("input",{type:"search",value:j,onChange:H=>E(H.target.value),placeholder:f("files-search-ph"),"aria-label":f("files-search"),enterKeyHint:"search"})]}),(w||N)&&!T&&o.jsx("div",{className:"nc-busy",role:"status",children:w||N}),o.jsxs("div",{className:"nc-files-list",children:[z.map(H=>o.jsxs("section",{className:"nc-files-daygroup",children:[o.jsx("h3",{className:"nc-files-day",children:H.label}),o.jsx("ul",{children:H.files.map(M=>{const U=nl(M.name),ee=A.get(U)||1;return o.jsxs("li",{children:[o.jsx("span",{className:"nc-files-type","aria-hidden":"true",children:Go(M.name)||o.jsx(yt,{name:"file",size:18})}),o.jsxs("span",{className:"nc-files-info",children:[o.jsxs("span",{className:"nc-files-name",children:[U,ee>1&&o.jsxs("span",{className:"nc-files-dup",children:[o.jsx("span",{"aria-hidden":"true",children:`×${ee}`}),o.jsx("span",{className:"nc-sr-only",children:f("files-dupes").replace("{n}",String(ee))})]})]}),o.jsxs("small",{className:"nc-files-meta",children:[KC(Hc(M.name,M.mtime),B,V)," · ",Ec(M.size)]})]}),o.jsx("button",{type:"button",className:"nc-files-dl",onClick:()=>q(M.name),title:f("files-download"),"aria-label":`${f("files-download")} ${U}`,children:o.jsx(yt,{name:"download",size:20})}),o.jsx("button",{type:"button",className:"nc-files-more",onClick:()=>x(M.name),title:f("files-actions"),"aria-label":`${f("files-actions")} ${U}`,children:o.jsx(yt,{name:"more",size:20})})]},M.name)})})]},H.key)),D.length===0&&o.jsx("div",{className:"nc-files-empty",children:f("empty-files")}),D.length>0&&P.length===0&&o.jsx("div",{className:"nc-files-empty",children:f("files-no-match").replace("{q}",j.trim())})]}),L]})}const Lh="nc_composer_v1",Vg="nc-composer-reset",PD=50,QC=256*1024,ZC=512*1024,DD=768*1024,_S=2*1024*1024,eE=720*60*60*1e3,Gg=1;function tE(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:0}function s_(e){if(e!==void 0)return e;try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function Zd(){return{version:Gg,cells:{}}}function nE(e){const t=[];for(const s of Array.isArray(e)?e:[]){const i=typeof s=="string"?s:s&&s.text,l=tE(typeof s=="string"?0:s&&s.at);if(!(typeof i!="string"||!i||i.length>QC)&&!(t.length&&t[t.length-1].text===i)&&(t.push({text:i,at:l}),t.length>=PD))break}let n=0;return t.filter(s=>n+s.text.length>DD?!1:(n+=s.text.length,!0))}function eh(e){if(!e||typeof e!="object")return null;const t=typeof e.draft=="string"&&e.draft.length<=ZC?e.draft:"",n=nE(e.history),s=tE(e.updatedAt),i=e.expanded===!0;return!t&&!n.length&&!i?null:{draft:t,history:n,expanded:i,updatedAt:s}}function OD(e){let t;try{t=typeof e=="string"?JSON.parse(e):e}catch{return Zd()}if(!t||typeof t!="object"||t.version!==Gg||!t.cells||typeof t.cells!="object")return Zd();const n=Object.create(null);for(const[s,i]of Object.entries(t.cells)){if(!s||typeof s!="string"||s.length>512||s==="__proto__"||s==="constructor"||s==="prototype")continue;const l=eh(i);l&&(n[s]=l)}return{version:Gg,cells:n}}function sE(e){const t=s_(e);if(!t)return Zd();try{return OD(t.getItem(Lh))}catch{return Zd()}}function yS(e){try{return JSON.stringify(e).length}catch{return 1/0}}function BD(e,t,n){for(const[s,i]of Object.entries(e.cells))s!==n&&i.updatedAt>0&&t-i.updatedAt>eE&&delete e.cells[s]}function iE(e,t){return Object.entries(e.cells).filter(([n])=>n!==t).sort((n,s)=>n[1].updatedAt-s[1].updatedAt).map(([n])=>n)}function $D(e,t){for(;yS(e)>_S;){const n=Object.entries(e.cells).filter(([,s])=>s.history.length).sort((s,i)=>s[1].updatedAt-i[1].updatedAt);if(!n.length)break;n[0][1].history.pop()}for(const n of iE(e,t)){if(yS(e)<=_S)break;delete e.cells[n]}}function rE(e,t,n){const s=s_(e);if(!s)return!1;$D(t,n);const i=()=>(s.setItem(Lh,JSON.stringify(t)),!0);try{return i()}catch{for(const c of iE(t,n)){delete t.cells[c];try{return i()}catch{}}return!1}}function nu(e,t,n,s){const i=sE(t);BD(i,n,e);const l=eh(i.cells[e])||{draft:"",history:[],expanded:!1,updatedAt:0},c=s({...l,history:[...l.history]}),u=eh(c);return u?i.cells[e]={...u,updatedAt:n}:delete i.cells[e],{ok:rE(t,i,e),cell:i.cells[e]||{draft:"",history:[],expanded:!1,updatedAt:n}}}function zD({ownerId:e,node:t,session:n}){const s=String(n||"");if(!s)return"";const i=el.test(String(e||""))?String(e):t?`route:${String(t)}`:"local";return`${encodeURIComponent(i)}:${encodeURIComponent(s)}`}function sc(e,t,n=Date.now()){if(!e)return{draft:"",history:[],expanded:!1,updatedAt:0};const s=sE(t),i=eh(s.cells[e]);return!i||i.updatedAt>0&&n-i.updatedAt>eE?(s.cells[e]&&(delete s.cells[e],rE(t,s,"")),{draft:"",history:[],expanded:!1,updatedAt:0}):{...i,history:[...i.history]}}function bS(e,t,n,s=Date.now()){const i=String(t||"");return!e||i.length>ZC?!1:nu(e,n,s,l=>({...l,draft:i})).ok}function wS(e,t,n=Date.now()){return e?nu(e,t,n,s=>({...s,draft:""})).ok:!1}function FD(e,t,n,s=Date.now()){return e?nu(e,n,s,i=>({...i,expanded:!!t})).ok:!1}function HD(e,t,n,s=Date.now()){const i=String(t||"");return!e||!i||i.length>QC?!1:nu(e,n,s,l=>{const c=l.history.filter(u=>u.text!==i);return c.unshift({text:i,at:s}),{...l,history:nE(c)}}).ok}function UD(e,t,n=Date.now()){return e?nu(e,t,n,s=>({...s,history:[]})).ok:!1}function WD(e){const t=s_(e);if(!t)return!1;try{return t.removeItem(Lh),!0}catch{return!1}}const qD=300;function KD(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function VD({ownerId:e,node:t,session:n,storage:s=KD()}){const i=y.useMemo(()=>zD({ownerId:e,node:t,session:n}),[e,t,n]),l=y.useMemo(()=>sc(i,s),[]),[c,u]=y.useState(l.draft),[h,p]=y.useState(l.expanded),[v,_]=y.useState(l.history),[g,w]=y.useState(-1),S=y.useRef(i),N=y.useRef(l.draft),C=y.useRef(null),j=y.useRef(l.updatedAt||0),E=y.useRef(l.draft),R=y.useCallback(()=>{C.current&&clearTimeout(C.current),C.current=null},[]),x=y.useCallback(()=>{R(),bS(S.current,N.current,s)},[R,s]),W=y.useCallback(()=>{R(),C.current=setTimeout(()=>{C.current=null,bS(S.current,N.current,s)},qD)},[R,s]),$=y.useCallback(O=>{const P=String(typeof O=="function"?O(N.current):O||"");N.current=P,j.current=Date.now(),E.current=P,w(-1),u(P),W()},[W]),Y=y.useCallback((O,P)=>{R(),N.current=O,j.current=Date.now(),u(O),w(P),W()},[R,W]),q=y.useCallback(()=>{if(!v.length)return!1;const O=Math.min(g+1,v.length-1);return g<0&&(E.current=N.current),Y(v[O].text,O),!0},[Y,v,g]),K=y.useCallback(()=>{if(g<0)return!1;const O=g-1;return Y(O<0?E.current:v[O].text,O),!0},[Y,v,g]),se=y.useCallback(O=>{E.current=N.current;const P=v.findIndex(z=>z.text===O);Y(String(O||""),P)},[Y,v]),V=y.useCallback(()=>{p(O=>{const P=!O;return FD(S.current,P,s),P})},[s]),B=y.useCallback((O,P,z)=>{if(!O)return;if(HD(O,z,s),!(S.current===O)){sc(O,s).draft===P&&wS(O,s);return}_(sc(O,s).history),E.current="",w(-1),N.current===P?(R(),N.current="",j.current=Date.now(),u(""),wS(O,s)):W()},[R,W,s]),D=y.useCallback(()=>{UD(S.current,s),_([]),w(-1),E.current=N.current},[s]);return y.useEffect(()=>{if(S.current===i)return;x(),S.current=i;const O=sc(i,s);N.current=O.draft,j.current=O.updatedAt||0,E.current=O.draft,u(O.draft),p(O.expanded),_(O.history),w(-1)},[i,x,s]),y.useEffect(()=>{const O=()=>x(),P=()=>{document.visibilityState==="hidden"&&x()};return window.addEventListener("pagehide",O),document.addEventListener("visibilitychange",P),()=>{window.removeEventListener("pagehide",O),document.removeEventListener("visibilitychange",P),x()}},[x]),y.useEffect(()=>{const O=()=>{R(),N.current="",j.current=0,E.current="",u(""),p(!1),_([]),w(-1)},P=A=>{if(A.key!==Lh)return;if(A.newValue==null){O();return}const T=sc(S.current,s);T.updatedAt<j.current||(R(),N.current=T.draft,j.current=T.updatedAt,E.current=T.draft,u(T.draft),p(T.expanded),_(T.history),w(-1))},z=()=>O();return window.addEventListener("storage",P),window.addEventListener(Vg,z),()=>{window.removeEventListener("storage",P),window.removeEventListener(Vg,z)}},[R,s]),{cellKey:i,text:c,setText:$,expanded:h,toggleExpanded:V,history:v,historyCursor:g,recallPrevious:q,recallNext:K,selectHistory:se,confirmSubmitted:B,clearHistory:D,flush:x}}function oE({submitText:e,token:t,session:n,node:s,ownerId:i,readonly:l=!1,keepKeyboardClosedOnVoice:c=!0}){Fn();const u=s?`/api/route/${String(s).split("/").map(encodeURIComponent).join("/")}/_`:"/api",{cellKey:h,text:p,setText:v,expanded:_,toggleExpanded:g,history:w,historyCursor:S,recallPrevious:N,recallNext:C,selectHistory:j,confirmSubmitted:E,clearHistory:R,flush:x}=VD({ownerId:i,node:s,session:n}),[W,$]=y.useState(!1),[Y,q]=y.useState(""),[K,se]=y.useState(""),[V,B]=y.useState(!1),D=y.useRef(null),O=y.useRef(null),P=y.useRef(null),[z,A]=y.useState(!1),[T,L]=y.useState({left:0,bottom:0}),[H,M]=y.useState(!1),[U,ee]=y.useState(!1),re=y.useRef(null),oe=y.useRef(null),je=y.useRef(null),te=y.useRef(null),ie=y.useRef(null),pe=y.useRef(null),xe=y.useRef(null),Be=y.useRef(null),Te=y.useRef(!1),[Me,J]=y.useState(!1),[le,Q]=y.useState({left:0,bottom:0,width:320}),ge=y.useRef(`nc-attach-${Math.random().toString(36).slice(2,8)}`);y.useEffect(()=>{let X=!1;if(s){B(!1);return}return Vn(`${u}/voice/status`,t).then(I=>I.json()).then(I=>{X||B(!!I.serverSttConfigured)}).catch(()=>{X||B(!1)}),()=>{X=!0}},[t,u]);const fe=!!(typeof window<"u"&&(window.SpeechRecognition||window.webkitSpeechRecognition)||V);async function ve(){const X=P.current&&typeof P.current.value=="string"?P.current.value:p;Ng(),X!==p&&v(X);const I=X,ce=iI(I);if(!ce||U)return;if(l){q(f("settings-readonly"));return}ee(!0),q("");let ye=!1;try{ye=!!await e(ce)}catch{ye=!1}ye?E(h,I,ce):q(f("composer-send-failed")),ee(!1)}function ke(){const X=re.current&&re.current.getBoundingClientRect();X&&L({left:Math.max(6,Math.min(X.left,window.innerWidth-186)),bottom:window.innerHeight-X.top+6}),A(!0)}function Ve(X){A(!1),X&&re.current&&re.current.focus()}function ot(){const X=je.current&&je.current.getBoundingClientRect();if(X){const I=Math.max(220,Math.min(360,window.innerWidth-12));Q({left:Math.max(6,Math.min(X.right-I,window.innerWidth-I-6)),bottom:window.innerHeight-X.top+6,width:I})}J(!0)}function rt(X){J(!1),X&&je.current&&je.current.focus()}y.useEffect(()=>{if(!z)return;const X=ce=>{ce.key==="Escape"&&Ve(!0)},I=ce=>{const ye=oe.current&&oe.current.contains(ce.target),Re=re.current&&re.current.contains(ce.target);!ye&&!Re&&Ve(!1)};return document.addEventListener("keydown",X),document.addEventListener("pointerdown",I),()=>{document.removeEventListener("keydown",X),document.removeEventListener("pointerdown",I)}},[z]),y.useEffect(()=>{if(!Me)return;const X=ce=>{ce.key==="Escape"&&rt(!0)},I=ce=>{const ye=te.current&&te.current.contains(ce.target),Re=je.current&&je.current.contains(ce.target);!ye&&!Re&&rt(!1)};return document.addEventListener("keydown",X),document.addEventListener("pointerdown",I),()=>{document.removeEventListener("keydown",X),document.removeEventListener("pointerdown",I)}},[Me]);function $e(X){if(!(X.isComposing||Te.current||X.altKey||X.ctrlKey||X.metaKey)){if(X.key==="ArrowUp"&&X.currentTarget.selectionStart===0&&X.currentTarget.selectionEnd===0){N()&&X.preventDefault();return}X.key==="ArrowDown"&&S>=0&&X.currentTarget.selectionStart===p.length&&X.currentTarget.selectionEnd===p.length&&C()&&X.preventDefault()}}function _e(X){Ve(!1),X.current&&X.current.click()}async function ze(X){if(!X.length||!n)return;M(!0),q("");const{paths:I,errors:ce}=await Vd({files:X,token:t,session:n,node:s,paste:!1});ce.length&&q(ce.map(ye=>`${ye.name}: ${ye.message}`).join(" · ")),I.length&&v(ye=>ye+(ye&&!ye.endsWith(" ")?" ":"")+I.join(" ")),M(!1)}async function Je(X){var ye;if(!X.length||!n)return;M(!0),q(""),se("");const{paths:I,errors:ce}=await Vd({files:X,token:t,session:n,node:s,paste:!1});if(ce.length&&q(ce.map(Re=>`${Re.name}: ${Re.message}`).join(" · ")),I.length){se(f("attach-inbox-done").replace("{n}",String(I.length)));try{(ye=navigator.vibrate)==null||ye.call(navigator,10)}catch{}setTimeout(()=>se(""),2500)}M(!1)}function He(){D.current&&D.current.stop(),O.current&&O.current.stop(),$(!1)}async function nt(){q("");const X=window.SpeechRecognition||window.webkitSpeechRecognition;if(X){const I=new X;I.lang="it-IT",I.continuous=!1,I.interimResults=!0;const ce=p?`${p} `:"";I.onresult=ye=>{const Re=Array.from(ye.results).map(ae=>ae[0].transcript).join("");v(ce+Re)},I.onend=()=>$(!1),I.onerror=ye=>{q(`voice: ${ye.error||"errore"}`),$(!1)},D.current=I,I.start(),$(!0);return}try{const I=await navigator.mediaDevices.getUserMedia({audio:!0}),ce=new MediaRecorder(I),ye=[];ce.ondataavailable=Re=>ye.push(Re.data),ce.onstop=async()=>{I.getTracks().forEach(Re=>Re.stop()),$(!1),q("trascrivo…");try{const Re=new Blob(ye,{type:ce.mimeType||"audio/webm"}),Oe=await(await Vn(`${u}/voice/transcribe`,t,{method:"POST",headers:{"content-type":"application/octet-stream"},body:Re})).json();Oe.error?q(Oe.error):(q(""),v(gt=>gt+(gt?" ":"")+(Oe.text||"")))}catch(Re){q(String(Re))}},O.current={stop:()=>ce.state!=="inactive"&&ce.stop()},ce.start(),$(!0)}catch{q("microfono non disponibile"),$(!1)}}function lt(){c&&Ng(),W?He():nt()}return o.jsxs("div",{className:"nc-composer",children:[Y&&o.jsx("div",{className:"nc-composer-err",children:Y}),K&&o.jsx("div",{className:"nc-composer-info",children:K}),o.jsxs("div",{className:"nc-composer-row",children:[n&&o.jsx("button",{ref:re,className:H?"attach busy":"attach",disabled:H,onClick:()=>z?Ve(!1):ke(),title:f(H?"attach-uploading":"attach"),"aria-label":f("attach"),"aria-haspopup":"menu","aria-expanded":z,"aria-controls":ge.current,children:o.jsx(yt,{name:"attach",size:22})}),z&&o.jsxs("div",{ref:oe,id:ge.current,role:"menu",className:"nc-attach-menu",style:{left:T.left,bottom:T.bottom},children:[o.jsxs("button",{role:"menuitem",onClick:()=>_e(ie),children:[o.jsx(yt,{name:"file",size:18})," ",f("attach-file")]}),o.jsxs("button",{role:"menuitem",onClick:()=>_e(pe),children:[o.jsx(yt,{name:"camera",size:18})," ",f("attach-camera")]}),o.jsxs("button",{role:"menuitem",onClick:()=>_e(xe),children:[o.jsx(yt,{name:"image",size:18})," ",f("attach-gallery")]}),o.jsxs("button",{role:"menuitem",onClick:()=>_e(Be),children:[o.jsx(yt,{name:"folder",size:18})," ",f("attach-inbox")]})]}),o.jsx("button",{ref:je,type:"button",className:"history",onPointerDown:X=>X.preventDefault(),onClick:()=>Me?rt(!1):ot(),title:f("composer-history-tools"),"aria-label":f("composer-history-tools"),"aria-haspopup":"menu","aria-expanded":Me,children:o.jsx(yt,{name:"history",size:21})}),Me&&o.jsxs("div",{ref:te,role:"menu",className:"nc-composer-history-menu",style:{left:le.left,bottom:le.bottom,width:le.width},children:[o.jsxs("button",{role:"menuitem",className:"nc-composer-history-action",onPointerDown:X=>X.preventDefault(),onClick:()=>{g(),rt(!1)},children:[o.jsx(yt,{name:_?"chevronDown":"chevronUp",size:18}),f(_?"composer-collapse":"composer-expand")]}),o.jsx("div",{className:"nc-composer-history-title",children:f("composer-history")}),w.length===0&&o.jsx("div",{className:"nc-composer-history-empty",children:f("composer-history-empty")}),w.map((X,I)=>o.jsxs("button",{type:"button",role:"menuitem",className:"nc-composer-history-entry",onPointerDown:ce=>ce.preventDefault(),onClick:()=>{j(X.text),rt(!1)},children:[o.jsx("span",{children:X.text.replace(/\s+/g," ").slice(0,180)}),X.at>0&&o.jsx("small",{children:new Date(X.at).toLocaleString()})]},`${X.at}:${I}`)),w.length>0&&o.jsx("button",{type:"button",role:"menuitem",className:"nc-composer-history-clear",onPointerDown:X=>X.preventDefault(),onClick:()=>{R(),rt(!1)},children:f("composer-history-clear")})]}),o.jsx("input",{ref:ie,type:"file",multiple:!0,hidden:!0,onChange:X=>{ze(Array.from(X.target.files||[])),X.target.value=""}}),o.jsx("input",{ref:pe,type:"file",accept:"image/*",capture:"environment",hidden:!0,onChange:X=>{ze(Array.from(X.target.files||[])),X.target.value=""}}),o.jsx("input",{ref:xe,type:"file",accept:"image/*,video/*",multiple:!0,hidden:!0,onChange:X=>{ze(Array.from(X.target.files||[])),X.target.value=""}}),o.jsx("input",{ref:Be,type:"file",multiple:!0,hidden:!0,onChange:X=>{Je(Array.from(X.target.files||[])),X.target.value=""}}),o.jsx("textarea",{ref:P,className:_?"expanded":"",rows:_?8:2,value:p,placeholder:f("composer-placeholder"),onChange:X=>v(X.target.value),onKeyDown:$e,onCompositionStart:()=>{Te.current=!0},onCompositionEnd:()=>{Te.current=!1},onBlur:x}),fe&&o.jsx("button",{type:"button",className:W?"mic on":"mic",title:f("voice"),"aria-label":f("voice"),onPointerDown:X=>{X.preventDefault(),lt()},onClick:X=>{X.detail===0&&lt()},children:o.jsx(yt,{name:"mic",size:22})}),o.jsx("button",{type:"button",className:"go",disabled:U,onPointerDown:X=>X.preventDefault(),onClick:ve,title:f("send"),children:o.jsx(yt,{name:"enter",size:22})})]})]})}const SS=460,GD=320;function YD({row:e,token:t,panelPort:n=0,anchorRect:s,liveHost:i=null,onLiveHostApplied:l,source:c,onSourceChange:u,onExpand:h,onClose:p,onMouseEnter:v,onMouseLeave:_}){y.useEffect(()=>{const S=N=>{N.key==="Escape"&&p()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[p]);const g=s?Math.max(8,Math.min(s.right+10,window.innerWidth-SS-8)):void 0,w=s?Math.max(8,Math.min(s.top-6,window.innerHeight-GD-8)):void 0;return o.jsxs("div",{className:"nc-peekcloud",style:{left:g,top:w,width:SS},"data-testid":"peek-cloud",onMouseEnter:v,onMouseLeave:_,children:[o.jsxs("div",{className:"nc-peekcloud-testa",children:[o.jsx("b",{className:"nc-peekcloud-nome",children:e.cellName}),[e.nodeLabel,e.subtitle].filter(Boolean).length>0&&o.jsx("span",{className:"nc-peekcloud-sub",children:[e.nodeLabel,e.subtitle].filter(Boolean).join(" · ")}),o.jsx("button",{type:"button",className:"nc-peekcloud-espandi",title:f("cell-peek-expand"),"aria-label":`${f("cell-peek-expand")}: ${e.cellName}`,onClick:()=>h(c),children:"⤢"})]}),o.jsx(Hv,{row:e,token:t,panelPort:n,liveHost:i,onLiveHostApplied:l,source:c,onSourceChange:u})]})}function Up(e){return String(e||"?").replace(/^[^a-zA-Z0-9]+/,"").charAt(0).toUpperCase()||"?"}const XD=180,JD=480,ic=(e,t=[])=>`${t.length?t.join("/"):"local"}:${e}`;function QD({sessions:e=[],cells:t=[],activeSessions:n=[],nodeGroups:s=[],onPick:i,onAddTile:l,onPower:c,onBoot:u,onNodePower:h,onKill:p,onVisibility:v,onNew:_,onNodeRename:g,onSettings:w,onBootError:S,localNodeId:N,fleetCapabilities:C=[],fleetStale:j=!1,fleetOff:E=null,bootSettlement:R=null,localVerified:x=!0,hostByRoute:W={},onDesignateCell:$,onClearHostCell:Y,onBootSettlementApplied:q,onOpenVlSession:K,token:se="",onPeekOpen:V,overlayOpen:B=!1,width:D=240,collapsed:O=!1,onResize:P,onToggleCollapse:z}){const[A,T]=Fn(),{pins:L,orders:H,togglePin:M,removePin:U,pinError:ee,reorderBlocked:re,retryPinPersist:oe,clearPinError:je,viewFor:te,updateView:ie,canMoveRoster:pe,moveRoster:xe,stepRoster:Be}=Yv(),{groupsFor:Te,moveNode:Me,stepNode:J,nodeKey:le}=Eh(),Q=G=>W[Rs(G)]||{},ge=new Set((t||[]).map(G=>G.tmuxSession)),Z=new Map((e||[]).map(G=>[G.name,G])),fe=(G,he)=>yP(L,G,he),ve=bP,ke=[...t||[]].sort((G,he)=>ve(fe(G.tmuxSession,(Z.get(G.tmuxSession)||{}).activity),fe(he.tmuxSession,(Z.get(he.tmuxSession)||{}).activity))),Ve=(e||[]).filter(G=>!ge.has(G.name)).sort((G,he)=>ve(fe(G.name,G.activity),fe(he.name,he.activity))||G.name.localeCompare(he.name)),ot=new Set(n||[]),[rt,$e]=y.useState(null),[_e,ze]=y.useState("preview"),[Je,He]=y.useState(null),nt=y.useRef(null),lt=y.useRef(null),X=y.useRef(null);y.useEffect(()=>{X.current=rt},[rt]),y.useEffect(()=>()=>{clearTimeout(nt.current),clearTimeout(lt.current)},[]);const[I,ce]=y.useState(null),[ye,Re]=y.useState(null),[ae,Oe]=y.useState(!1),[gt,At]=y.useState(null),Lt=(G,he,Ie=[],Qe="",Ae=null)=>{const Ct=(Ie.length===0?Z.get(he.tmuxSession):(Ae||[]).find(Ze=>Ze&&Ze.name===he.tmuxSession))||{};return{key:G.key,cellName:he.cell,subtitle:G.subtitle||"",nodeLabel:Qe,node:Ie.length?Ie.join("/"):"",session:he.tmuxSession,route:Ie,panelUrl:he.panelUrl||"",telemetry:Ct.telemetry||null,preview:Ct.preview||he.preview||"",activity:Ct.activity||he.activity||0}},Rt=(G,he,Ie=[],Qe="",Ae="preview")=>Et=>{Et&&Et.stopPropagation(),He(null),ze(Ae),$e(G.key),typeof V=="function"&&V()},zt=(G,he,Ie)=>{Ie&&(clearTimeout(lt.current),clearTimeout(nt.current),nt.current=setTimeout(()=>{X.current||He({itemKey:G.key,routeKey:he||"",anchorRect:Ie.getBoundingClientRect(),source:"stream"})},300))},ft=()=>{clearTimeout(nt.current),clearTimeout(lt.current),lt.current=setTimeout(()=>He(null),150)},Yt=()=>clearTimeout(lt.current),$t=()=>He(null),Zt=(G,he,Ie,Qe,Ae)=>{if(I&&I.itemKey===G){ce(null);return}ce({itemKey:G,routeKey:he||"",canBoot:!!Qe,preserved:!!Ae}),Re(Ie?Ie.getBoundingClientRect():null)};y.useEffect(()=>{B&&($e(null),ze("preview"))},[B]);const Bt=e_(ke,Ve,Z,void 0,{autorevole:x,fleetStale:j}),Yn=fo(Bt,L,te("local").filter,Di(H,"local")),rn=Te(s||[]).map(G=>{const he=(G.route&&G.route.length?G.route:[G.name]).join("/"),Ie=te(he);if(G.kind==="vl")return{g:G,nodeRoute:he,groupView:Ie,rawItems:[],items:[]};const{rawItems:Qe}=Cc(G),Ae=fo(Qe,L,Ie.filter,Di(H,he));return{g:G,nodeRoute:he,groupView:Ie,rawItems:Qe,items:Ae}}),sn=[...Yn,...rn.flatMap(({items:G,nodeRoute:he,g:Ie})=>(G||[]).map(Qe=>({...Qe,nodeRoute:he,nodeLabel:Ie.label||Ie.name})))].filter(G=>G.type==="cell"),wn=rt?sn.find(G=>G.key===rt):null,Ft=()=>{if(!Je)return null;const G=sn.find(Ae=>Ae.key===Je.itemKey);if(!G)return null;const he=G.value,Ie=G.nodeRoute?s.find(Ae=>(Ae.route||[Ae.name]).join("/")===G.nodeRoute)||{}:null,Qe=G.nodeRoute?Ie.route||[G.nodeRoute]:[];return o.jsx(YD,{row:Lt(G,he,Qe,G.nodeLabel||"",Ie&&Ie.sessions),token:se,anchorRect:Je.anchorRect,source:Je.source,onSourceChange:Ae=>He(Et=>Et&&{...Et,source:Ae}),onExpand:Ae=>{He(null),ze(Ae),$e(G.key),typeof V=="function"&&V()},onClose:$t,onMouseEnter:Yt,onMouseLeave:ft})},on=(G,he,Ie)=>i&&i({session:G,...he?{node:he}:{},...el.test(String(Ie||""))?{ownerId:Ie}:{}}),un=async G=>{if(!(G!=null&&G.direct)||!g)return;const he=window.prompt(f("rename-node-prompt"),G.label||G.name);if(he!==null)try{await g(G,he)||window.alert(f("rename-node-invalid"))}catch(Ie){window.alert(String((Ie==null?void 0:Ie.message)||Ie))}},[Xt,dn]=y.useState({}),[Js,ds]=y.useState(new Set);y.useEffect(()=>{const G=new Map;for(const he of t||[])G.set(ic(he.cell),!!he.boot);for(const he of s||[]){const Ie=he.route||[he.name];for(const Qe of he.cells||[])G.set(ic(Qe.cell,Ie),!!Qe.boot)}dn(he=>{let Ie=!1;const Qe={...he};for(const[Ae,Et]of Object.entries(he))G.has(Ae)&&G.get(Ae)===Et&&(delete Qe[Ae],Ie=!0);return Ie?Qe:he})},[t,s]),y.useEffect(()=>{if(!(R!=null&&R.cell))return;const G=Array.isArray(R.route)?R.route:[],he=ic(R.cell,G);dn(Ie=>({...Ie,[he]:!!R.enabled})),q&&q(R.id)},[R,q]);const Vt=(G,he=[])=>{const Ie=ic(G.cell,he);return Object.prototype.hasOwnProperty.call(Xt,Ie)?Xt[Ie]:!!G.boot},Ms=async(G,he,Ie=[],Qe)=>{if(!u)return;const Ae=ic(he.cell,Ie),Et=typeof Qe=="boolean"?Qe:!Vt(he,Ie);dn(Ct=>({...Ct,[Ae]:Et})),ds(Ct=>new Set(Ct).add(Ae));try{await u(he.cell,Et,Ie)}catch(Ct){dn(Ze=>{const Ee={...Ze};return delete Ee[Ae],Ee}),S&&S(Ct)}finally{ds(Ct=>{const Ze=new Set(Ct);return Ze.delete(Ae),Ze})}},Xn=(G,he,Ie)=>({onToggleLive:async()=>{const Qe=co({item:G,cellName:he.cell,route:Ie,pins:L,hostByRoute:W});Oe(!0);const Ae=await gh({action:Qe.isLive?"remove":"use",cellId:he.cell,route:Ie,token:se});Oe(!1),At({messageKey:Ae.messageKey,ok:Ae.ok,cell:Ae.hostCell||he.cell})},onTogglePin:()=>Xv({view:Nh({item:G,pins:L,hostByRoute:W,route:Ie}),itemKey:G.key,togglePin:M,removePin:U}),onToggleBoot:Qe=>Ms(null,he,Ie,Qe),onWatchLive:()=>{He(null),ze("stream"),$e(G.key),typeof V=="function"&&V()}}),[Ts,kt]=y.useState(null),ue=(G,he)=>{const Ie=G.currentTarget.getBoundingClientRect();kt({text:he,y:Ie.top+Ie.height/2})},De=()=>kt(null),Xe=y.useRef(null);y.useEffect(()=>()=>{Xe.current&&Xe.current()},[]);function ct(G){G.preventDefault(),G.stopPropagation();const he=G.clientX,Ie=D,Qe=Et=>{const Ct=Math.max(XD,Math.min(JD,Ie+(Et.clientX-he)));P&&P(Ct)},Ae=()=>{window.removeEventListener("pointermove",Qe),window.removeEventListener("pointerup",Ae),window.removeEventListener("pointercancel",Ae),window.removeEventListener("blur",Ae),Xe.current=null};window.addEventListener("pointermove",Qe),window.addEventListener("pointerup",Ae),window.addEventListener("pointercancel",Ae),window.addEventListener("blur",Ae),Xe.current=Ae}const It=O?{width:48,flex:"0 0 48px"}:{width:D,flex:`0 0 ${D}px`};return O?o.jsxs("aside",{className:"nc-sidebar mini",style:It,children:[o.jsx("div",{className:"nc-side-head mini",children:o.jsx("button",{className:"nc-collapse-btn",onClick:z,title:f("expand"),children:"⟩"})}),o.jsx("button",{className:"nc-side-gear mini",onClick:()=>w&&w("nodes",!1),title:f("settings"),onMouseEnter:G=>ue(G,f("settings")),onMouseLeave:De,children:o.jsx(yt,{name:"gear",size:16})}),o.jsx("div",{className:"nc-side-scroll mini",children:o.jsxs("div",{className:"nc-side-group mini",children:[te("local").open&&Yn.map(G=>G.type==="cell"?(()=>{const he=G.value,Ie=he.degraded?"warn":he.tmux?"on":"",Qe=!!he.tmux;return o.jsx("button",{type:"button",className:`nc-mini-dot${ot.has(he.tmuxSession)?" active":""}`,onMouseEnter:Ae=>{Qe?zt(G,"",Ae.currentTarget):ue(Ae,`${he.cell}: ${G.subtitle}`)},onMouseLeave:()=>{Qe?ft():De()},draggable:Qe,onDragStart:Qe?Ae=>Ae.dataTransfer.setData("text/nc-session",he.tmuxSession):void 0,onClick:Qe?()=>{He(null),l&&l(he.tmuxSession)}:()=>c&&c(he),onDoubleClick:Qe?()=>on(he.tmuxSession,"",N):void 0,children:o.jsx("span",{className:`nc-dot ${Ie}${G.working?" working":""}`})},G.key)})():(()=>{const he=G.value;return o.jsx("button",{type:"button",className:`nc-mini-init${ot.has(he.name)?" active":""}`,onMouseEnter:Ie=>ue(Ie,he.name),onMouseLeave:De,draggable:!0,onDragStart:Ie=>Ie.dataTransfer.setData("text/nc-session",he.name),onClick:()=>l&&l(he.name),onDoubleClick:()=>on(he.name,"",N),children:Up(he.name)},G.key)})()),rn.flatMap(({g:G,nodeRoute:he,groupView:Ie,items:Qe})=>G.kind==="vl"?G.status==="up"&&G.sessions.length?G.sessions.map(Ae=>o.jsx("button",{type:"button",className:"nc-mini-init",onMouseEnter:Et=>ue(Et,`${G.label||he}: ${Ae.name}`),onMouseLeave:De,onClick:()=>K&&K(G.peer),children:Up(Ae.name)},Ae.key)):[o.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:Ae=>ue(Ae,`${G.label||G.name}: ${tr(G)||f("no-sessions-short")}`),onMouseLeave:De,children:o.jsx("span",{className:`nc-dot${G.status==="up"?" on":" warn"}`})},`nodo-vl-${he}-${G.name}`)]:G.status==="up"?Ie.open?Qe.map(Ae=>Ae.type==="cell"?(()=>{const Et=Ae.value,Ct=!!Et.tmux;return o.jsx("button",{type:"button",className:`nc-mini-dot${ot.has(Ae.key)?" active":""}`,onMouseEnter:Ze=>{Ct?zt(Ae,he,Ze.currentTarget):ue(Ze,`${G.label||he}: ${Et.cell} · ${Ae.subtitle}`)},onMouseLeave:()=>{Ct?ft():De()},draggable:Ct,onDragStart:Ct?Ze=>Ze.dataTransfer.setData("text/nc-session",Ae.key):void 0,onClick:Ct?()=>{He(null),l&&l(Ae.key)}:()=>c&&c({...Et,route:G.route,availableEngines:G.engines||[]}),onDoubleClick:Ct?()=>on(Et.tmuxSession,he,G.instanceId):void 0,children:o.jsx("span",{className:`nc-dot ${Et.degraded?"warn":Ct?`on${Ae.working?" working":""}`:""}`})},Ae.key)})():(()=>{const Et=Ae.value;return o.jsx("button",{type:"button",className:`nc-mini-init${ot.has(Ae.key)?" active":""}`,onMouseEnter:Ct=>ue(Ct,`${G.label||he}: ${Et.name}`),onMouseLeave:De,draggable:!0,onDragStart:Ct=>Ct.dataTransfer.setData("text/nc-session",Ae.key),onClick:()=>l&&l(Ae.key),onDoubleClick:()=>on(Et.name,he,G.instanceId),children:Up(Et.name)},Ae.key)})()):[]:[o.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:Ae=>ue(Ae,`${G.label||(G.route||[G.name]).join(" › ")}: ${tr(G)}`),onMouseLeave:De,children:o.jsx("span",{className:`nc-dot${G.status==="passive"?"":" warn"}`})},`nodo-${(G.route||[G.name]).join("/")}`)])]})}),Ft(),Ts&&o.jsx("div",{className:"nc-mini-tip",style:{top:Ts.y},children:Ts.text})]}):o.jsxs("aside",{className:"nc-sidebar",style:It,children:[o.jsx("div",{className:"nc-side-live-host",children:o.jsx(ZD,{view:Ja({liveHost:W[Rs([])],cells:t}),notice:gt})}),o.jsxs("div",{className:"nc-side-head",children:[o.jsx("button",{className:"nc-collapse-btn",onClick:z,title:f("collapse"),children:"⟨"}),o.jsx("span",{className:"nc-side-title",children:f("fleet")}),re&&o.jsx("span",{className:"nc-side-fleet-stale",role:"status",title:f("reorder-blocked"),"aria-label":f("reorder-blocked"),children:"⇅"}),j&&o.jsx("span",{className:"nc-side-fleet-stale",role:"status",title:f("fleet-stale"),"aria-label":f("fleet-stale"),children:"●"}),E!==null&&o.jsx("span",{className:"nc-side-fleet-off",role:"status",title:`${f("fleet-off")}${E?` (${E})`:""}`,"aria-label":`${f("fleet-off")}${E?` (${E})`:""}`,children:"○"}),o.jsxs("button",{className:"nc-new-btn",onClick:_,title:f("fleet-new-cell"),children:["+ ",f("new")]})]}),o.jsxs("button",{className:"nc-side-gear",onClick:()=>w&&w("nodes",!1),title:f("settings"),children:[o.jsx(yt,{name:"gear",size:15})," ",f("settings")]}),o.jsx(wC,{pinError:ee,onRetry:oe,onDismiss:je}),o.jsxs("div",{className:"nc-side-scroll",children:[o.jsx(e3,{label:f("position-local"),count:Yn.length,state:te("local"),onToggle:()=>ie("local",{open:!te("local").open}),onFilter:G=>ie("local",{filter:G})}),te("local").open&&o.jsxs("div",{className:"nc-side-group",children:[Yn.map(G=>G.type==="cell"?(()=>{var ut;const he=G.value,Ie=Q([]),Qe=$d({hostCell:Ie.hostCell??null,threadStatus:Ie.threadStatus,pins:L,item:G}),Ae=he.degraded?"warn":he.tmux?"on":"",Et=Im(Qe,Ie.hostLease??null),Ct=he.degraded?f("cell-degraded"):G.subtitle||(he.tmux?f("cell-idle"):f("cell-off")),Ze=Et?`${Ct} · ${f(Et)}`:Ct,Ee=!!he.tmux;return o.jsxs("div",{"data-roster-key":G.key,"data-position":"local",className:`nc-cell${Ee?" live":""}${ot.has(he.tmuxSession)?" active":""}`,title:`${he.cell} · ${G.subtitle}${Ze===G.subtitle?"":` · ${Ze}`}`,"aria-label":`${he.cell}, ${G.subtitle}${Ze===G.subtitle?"":`, ${Ze}`}`,draggable:Ee,onDragStart:Ee?Pe=>Pe.dataTransfer.setData("text/nc-session",he.tmuxSession):void 0,onClick:Ee?()=>l&&l(he.tmuxSession):void 0,onDoubleClick:Ee?()=>on(he.tmuxSession,"",N):void 0,children:[o.jsx(Qi,{position:"local",itemKey:G.key,label:he.cell,canMove:pe,onMove:(Pe,We)=>xe("local",Pe,We,Bt),onStep:Pe=>Be("local",G.key,Pe,Bt)}),Ee?o.jsx("button",{type:"button",className:"nc-side-peek",title:f("cell-peek"),"aria-label":`${f("cell-peek")}: ${he.cell}`,onClick:Rt(G,he,[],""),onMouseEnter:Pe=>zt(G,"",Pe.currentTarget),onMouseLeave:ft,children:o.jsx("span",{className:`nc-dot ${Ae}${G.working?" working":""}`})}):o.jsx("span",{className:`nc-dot ${Ae}${G.working?" working":""}`}),o.jsxs("span",{className:"nc-cell-main",children:[o.jsxs("b",{title:he.cell,children:[he.cell,co({item:G,cellName:he.cell,route:[],pins:L,hostByRoute:W}).isLive&&o.jsx("span",{className:"nc-live-bollino",children:"LIVE"})]}),o.jsx("small",{title:G.subtitle,children:G.subtitle})]}),G.activity?o.jsx("span",{className:"nc-rel",children:uo(G.activity)}):null,G.fresh&&((ut=(Z.get(he.tmuxSession)||{}).outbox)==null?void 0:ut.count)>0?o.jsx("span",{className:"nc-badge",title:f("new-files-outbox"),children:Z.get(he.tmuxSession).outbox.count}):null,o.jsx("button",{type:"button",className:"nc-cellmenu",title:`${f("cell-actions-open")}: ${he.cell}`,"aria-label":`${f("cell-actions-open")}: ${he.cell}`,"aria-haspopup":"menu","aria-expanded":I&&I.itemKey===G.key?"true":"false",onClick:Pe=>{Pe.stopPropagation(),Zt(G.key,"",Pe.currentTarget,C.includes("boot")&&!!u,!1)},children:o.jsx("span",{"aria-hidden":"true",children:"⋯"})}),o.jsx("button",{className:`nc-power${he.tmux?" on":""}${he.degraded?" warn":""}`,onClick:Pe=>{Pe.stopPropagation(),c&&c({...he,boot:Vt(he)})},title:he.active?f("power-off"):f("power-on"),children:o.jsx(yt,{name:"power",size:14})})]},G.key)})():(()=>{var Ie;const he=G.value;return o.jsxs("div",{"data-roster-key":G.key,"data-position":"local",className:`nc-side-card${ot.has(he.name)?" active":""}`,draggable:!0,onDragStart:Qe=>Qe.dataTransfer.setData("text/nc-session",he.name),onClick:()=>l&&l(he.name),onDoubleClick:()=>on(he.name,"",N),children:[o.jsx(Qi,{position:"local",itemKey:G.key,label:he.name,canMove:pe,onMove:(Qe,Ae)=>xe("local",Qe,Ae,Bt),onStep:Qe=>Be("local",G.key,Qe,Bt)}),o.jsx("span",{className:he.attached?"nc-dot on":"nc-dot"}),o.jsxs("span",{className:"nc-card-main",children:[o.jsx("b",{children:he.name}),o.jsxs("small",{children:[he.preview||he.cmd||f("windows").replace("{n}",String(he.windows||0)),((Ie=he.outbox)==null?void 0:Ie.count)>0?` · 📦${he.outbox.count}`:""]})]}),he.activity?o.jsx("span",{className:"nc-rel",children:uo(he.activity)}):null,o.jsx("button",{className:`nc-pin${L.includes(G.key)?" on":""}`,title:f("pin"),onClick:Qe=>{Qe.stopPropagation(),M(G.key)},children:L.includes(G.key)?"★":"☆"}),o.jsx("button",{className:`nc-technical${he.technical?" on":""}`,title:he.technical?f("mark-normal"):f("mark-technical"),"aria-label":`${he.technical?f("mark-normal"):f("mark-technical")} ${he.name}`,onClick:Qe=>{Qe.stopPropagation(),v&&v(he.name,!he.technical,[])},children:"T"}),o.jsx("button",{className:"nc-menu",title:f("terminate"),onClick:Qe=>{Qe.stopPropagation(),window.confirm(f("terminate-confirm").replace("{name}",he.name))&&p&&p(he.name)},children:"⋯"})]},G.key)})()),Yn.length===0&&o.jsx("div",{className:"nc-empty",children:f("no-sessions-short")})]}),rn.map(({g:G,nodeRoute:he,groupView:Ie,rawItems:Qe,items:Ae})=>{const Et=EC(G.health),Ct=G.fleetState==="stale"?f("fleet-stale"):G.fleetState==="disabled"?f("fleet-off"):"",Ze=G.fleetState==="stale"?"warn":Et||(G.status==="up"?"on":G.status==="passive"?"":"warn"),Ee=[G.health?Yd(G.health):"",Ct].filter(Boolean).join(" · "),ut=G.status==="up"?[f("node-sessions").replace("{n}",String(Ae.length)),Ct].filter(Boolean).join(" · "):G.health&&Yd(G.health)||tr(G);if(G.kind==="vl"){const Pe=tr(G)||[f("node-sessions").replace("{n}",String(G.sessions.length)),Ct].filter(Boolean).join(" · ");return o.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":le(G),children:[o.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:()=>ie(he,{open:!Ie.open}),onKeyDown:We=>{(We.key==="Enter"||We.key===" ")&&(We.preventDefault(),ie(he,{open:!Ie.open}))},children:[o.jsx(Qi,{scope:"node",position:"nodes",itemKey:le(G),label:G.label||G.name,onMove:(We,vt)=>Me(We,vt,s||[]),onStep:We=>J(le(G),We,s||[])}),o.jsx("span",{className:"nc-node-chevron",children:Ie.open?"⌄":"›"}),o.jsx("span",{className:`nc-dot ${Ze}`,title:Ee}),o.jsxs("span",{className:"nc-node-main",children:[o.jsx("b",{children:G.label||G.name}),o.jsx("small",{title:Pe,children:Pe})]})]}),G.status==="up"&&Ie.open&&o.jsxs("div",{className:"nc-side-group",children:[G.sessions.map(We=>o.jsxs("div",{className:"nc-side-card nc-vl-session-row",role:"button",tabIndex:0,onClick:()=>K&&K(G.peer),onKeyDown:vt=>{(vt.key==="Enter"||vt.key===" ")&&(vt.preventDefault(),K&&K(G.peer))},children:[o.jsx("span",{className:"nc-dot on"}),o.jsxs("span",{className:"nc-card-main",children:[o.jsx("b",{children:We.name}),o.jsx("small",{children:f("vl-events-title")})]})]},We.key)),G.sessions.length===0&&o.jsx("div",{className:"nc-empty",children:f("no-sessions-short")})]})]},`nodo-vl-${he}-${G.name}`)}return o.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":le(G),children:[o.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onContextMenu:G.direct&&g?Pe=>{Pe.preventDefault(),un(G)}:void 0,onClick:()=>ie(he,{open:!Ie.open}),onKeyDown:Pe=>{(Pe.key==="Enter"||Pe.key===" ")&&(Pe.preventDefault(),ie(he,{open:!Ie.open}))},children:[o.jsx(Qi,{scope:"node",position:"nodes",itemKey:le(G),label:G.label||G.name,onMove:(Pe,We)=>Me(Pe,We,s||[]),onStep:Pe=>J(le(G),Pe,s||[])}),o.jsx("span",{className:"nc-node-chevron",children:Ie.open?"⌄":"›"}),o.jsx("span",{className:`nc-dot ${Ze}`,title:Ee}),o.jsxs("span",{className:"nc-node-main",children:[o.jsx("b",{children:G.label||G.name}),o.jsx("small",{title:ut,children:ut})]}),G.direct&&g&&o.jsx("button",{type:"button",className:"nc-node-rename",title:f("rename-node"),"aria-label":`${f("rename-node")} ${G.label||G.name}`,onClick:Pe=>{Pe.stopPropagation(),un(G)},children:"✎"}),G.direct&&G.health&&G.health.managed!==!1&&o.jsx("button",{type:"button",className:`nc-power${G.tunnelStatus==="up"?" on":""}`,title:G.tunnelStatus==="up"?f("power-off"):f("power-on"),onClick:Pe=>{Pe.stopPropagation(),h&&h(G)},children:o.jsx(yt,{name:"power",size:14})}),o.jsxs("select",{className:"nc-node-filter",value:Ie.filter,title:f(`view-${Ie.filter}`),onClick:Pe=>Pe.stopPropagation(),onChange:Pe=>ie(he,{filter:Pe.target.value}),children:[o.jsx("option",{value:"all",children:f("view-all")}),o.jsx("option",{value:"pinned",children:f("view-pinned")}),o.jsx("option",{value:"active",children:f("view-active")}),o.jsx("option",{value:"off",children:f("view-off")}),o.jsx("option",{value:"technical",children:f("view-technical")})]})]}),(G.status==="up"||G.cellsPreserved)&&Ie.open&&o.jsxs("div",{className:"nc-side-group",children:[Ae.map(Pe=>Pe.type==="cell"?(()=>{var Hn;const We=Pe.value,vt=G.route||[G.name],we=Q(vt),Le=$d({hostCell:we.hostCell??null,threadStatus:we.threadStatus,pins:L,item:Pe}),Ke=Im(Le,we.hostLease??null),at=!!We.tmux&&!G.cellsPreserved,wt=We.degraded?"warn":We.tmux&&!G.cellsPreserved?"on":"",Nn=(G.sessions||[]).find(Pt=>Pt&&Pt.name===We.tmuxSession)||null,hs=G.cellsPreserved?`${f("fleet-stale")}`:Pe.subtitle||(We.tmux?f("cell-idle"):f("cell-off")),Gt=Ke?`${hs} · ${f(Ke)}`:hs;return o.jsxs("div",{"data-roster-key":Pe.key,"data-position":he,className:`nc-side-card nc-cell${at?" live":""}${G.cellsPreserved?" preserved":""}${ot.has(We.key)?" active":""}`,title:Gt,draggable:at,onDragStart:at?Pt=>Pt.dataTransfer.setData("text/nc-session",We.key):void 0,onClick:at?()=>l&&l(We.key):void 0,onDoubleClick:at?()=>on(We.tmuxSession,he,G.instanceId):void 0,children:[o.jsx(Qi,{position:he,itemKey:Pe.key,label:We.cell,canMove:pe,onMove:(Pt,ws)=>xe(he,Pt,ws,Qe),onStep:Pt=>Be(he,Pe.key,Pt,Qe)}),at?o.jsx("button",{type:"button",className:"nc-side-peek",title:f("cell-peek"),"aria-label":`${f("cell-peek")}: ${We.cell}`,onClick:Rt(Pe,We,G.route||[G.name],G.label||G.name),onMouseEnter:Pt=>zt(Pe,he,Pt.currentTarget),onMouseLeave:ft,children:o.jsx("span",{className:`nc-dot ${wt}${Pe.working?" working":""}`})}):o.jsx("span",{className:`nc-dot ${wt}${Pe.working?" working":""}`}),o.jsxs("span",{className:"nc-card-main",children:[o.jsxs("b",{children:[We.cell,co({item:Pe,cellName:We.cell,route:vt,pins:L,hostByRoute:W}).isLive&&o.jsx("span",{className:"nc-live-bollino",children:"LIVE"})]}),o.jsx("small",{title:Pe.subtitle,children:Pe.subtitle})]}),Pe.activity?o.jsx("span",{className:"nc-rel",children:uo(Pe.activity)}):null,Pe.fresh&&((Hn=(Nn||{}).outbox)==null?void 0:Hn.count)>0?o.jsx("span",{className:"nc-badge",title:f("new-files-outbox"),children:Nn.outbox.count}):null,o.jsx("button",{type:"button",className:"nc-cellmenu",title:`${f("cell-actions-open")}: ${We.cell}`,"aria-label":`${f("cell-actions-open")}: ${We.cell}`,"aria-haspopup":"menu","aria-expanded":I&&I.itemKey===Pe.key?"true":"false",onClick:Pt=>{Pt.stopPropagation(),Zt(Pe.key,he,Pt.currentTarget,u&&(G.capabilities||[]).includes("boot"),!!G.cellsPreserved)},children:o.jsx("span",{"aria-hidden":"true",children:"⋯"})}),(G.capabilities||[]).includes(We.active?"down":"up")&&o.jsx("button",{className:`nc-power${We.active?" on":""}${We.degraded?" warn":""}`,onClick:Pt=>{Pt.stopPropagation(),c&&c({...We,boot:Vt(We,G.route||[]),route:G.route,availableEngines:G.engines||[]})},title:We.active?f("power-off"):f("power-on"),children:o.jsx(yt,{name:"power",size:14})})]},Pe.key)})():(()=>{const We=Pe.value;return o.jsxs("div",{"data-roster-key":Pe.key,"data-position":he,className:`nc-side-card${ot.has(We.key)?" active":""}`,draggable:!0,onDragStart:vt=>vt.dataTransfer.setData("text/nc-session",We.key),onClick:()=>l&&l(We.key),onDoubleClick:()=>on(We.name,We.node||he,G.instanceId),children:[o.jsx(Qi,{position:he,itemKey:Pe.key,label:We.name,canMove:pe,onMove:(vt,we)=>xe(he,vt,we,Qe),onStep:vt=>Be(he,Pe.key,vt,Qe)}),o.jsx("span",{className:We.attached?"nc-dot on":"nc-dot"}),o.jsxs("span",{className:"nc-card-main",children:[o.jsx("b",{children:We.name}),o.jsx("small",{children:We.preview?We.preview:We.cmd?We.cmd:f("windows").replace("{n}",String(We.windows||0))})]}),We.activity?o.jsx("span",{className:"nc-rel",children:uo(We.activity)}):null,o.jsx("button",{className:`nc-pin${L.includes(Pe.key)?" on":""}`,title:f("pin"),onClick:vt=>{vt.stopPropagation(),M(Pe.key)},children:L.includes(Pe.key)?"★":"☆"}),o.jsx("button",{className:`nc-technical${We.technical?" on":""}`,title:We.technical?f("mark-normal"):f("mark-technical"),"aria-label":`${We.technical?f("mark-normal"):f("mark-technical")} ${We.name}`,onClick:vt=>{vt.stopPropagation(),v&&v(We.name,!We.technical,G.route||[])},children:"T"}),o.jsx("button",{className:"nc-menu",title:f("terminate"),onClick:vt=>{vt.stopPropagation(),window.confirm(f("terminate-confirm").replace("{name}",We.name))&&p&&p(We.name,G.route)},children:"⋯"})]},Pe.key)})()),Ae.length===0&&o.jsx("div",{className:"nc-empty",children:f("no-sessions-short")})]})]},`nodo-${(G.route||[G.name]).join("/")}`)})]}),o.jsx("div",{className:"nc-side-lang",children:k1.map((G,he)=>o.jsxs("span",{children:[he>0&&" · ",o.jsx("button",{className:`nc-lang-btn${A===G?" on":""}`,onClick:()=>T(G),title:G,children:G.toUpperCase()})]},G))}),o.jsx("div",{className:"nc-side-resize",onPointerDown:ct,title:""}),wn&&(()=>{const G=wn.value,he=wn.nodeRoute?s.find(Qe=>(Qe.route||[Qe.name]).join("/")===wn.nodeRoute)||{}:null,Ie=wn.nodeRoute?he.route||[wn.nodeRoute]:[];return o.jsx(aC,{row:Lt(wn,G,Ie,wn.nodeLabel||"",he&&he.sessions),token:se,initialSource:_e,onClose:()=>{$e(null),ze("preview")}})})(),Ft(),I&&(()=>{const G=sn.find(Ze=>Ze.key===I.itemKey);if(!G)return null;const he=G.value,Ie=I.routeKey?s.find(Ze=>(Ze.route||[Ze.name]).join("/")===I.routeKey)||{}:null,Qe=I.routeKey?Ie.route||[I.routeKey]:[],Ae=I.preserved?!1:!!he.tmux,Et=co({item:G,cellName:he.cell,route:Qe,pins:L,hostByRoute:W}),Ct=Jv({...Et,canBoot:I.canBoot,boot:Vt(he,Qe),alive:Ae,handlers:Xn(G,he,Qe)});return o.jsx(kC,{anchorRect:ye,items:Ct,busy:ae,onClose:()=>ce(null)})})()]})}function ZD({view:e,notice:t}){const n=!!(e&&e.cell),s=n?f("live-host-indicator").replace("{cell}",e.cell).replace("{mode}",f(e.mode?`live-host-mode-${e.mode}`:"live-host-mode-unknown")).replace("{state}",f(`live-host-state-${e.state||"none"}`)):f("live-host-indicator-none");return o.jsxs("div",{className:"nc-live-strip","data-state":e&&e.state?e.state:"none",title:t?`${s} · ${f(t.messageKey)}`:s,children:[o.jsx("span",{className:`nc-live-strip-dot ${kv(e||{})}`,"aria-hidden":"true"}),o.jsx("span",{className:"nc-live-strip-testo",children:n?e.cell:s}),o.jsx(T1,{view:e}),t&&o.jsx("span",{className:`nc-live-strip-notice${t.ok?" ok":" ko"}`,role:"status",children:f(t.messageKey).replace("{cell}",t.cell||e.cell||"")})]})}function e3({label:e,count:t,state:n,onToggle:s,onFilter:i}){return o.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:s,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),s())},children:[o.jsx("span",{className:"nc-node-chevron",children:n.open?"⌄":"›"}),o.jsx("span",{className:"nc-dot on"}),o.jsxs("span",{className:"nc-node-main",children:[o.jsx("b",{children:e}),o.jsx("small",{children:f("node-sessions").replace("{n}",String(t))})]}),o.jsxs("select",{className:"nc-node-filter",value:n.filter,title:f(`view-${n.filter}`),onClick:l=>l.stopPropagation(),onChange:l=>i(l.target.value),children:[o.jsx("option",{value:"all",children:f("view-all")}),o.jsx("option",{value:"pinned",children:f("view-pinned")}),o.jsx("option",{value:"active",children:f("view-active")}),o.jsx("option",{value:"off",children:f("view-off")}),o.jsx("option",{value:"technical",children:f("view-technical")})]})]})}const gs={PRESENTE:"presente-verificata",ASSENTE:"assente-verificata",IGNOTA:"ignota"},Wp={OK:"ok",NON_DISPONIBILE:"non-disponibile",RIMOSSO:"rimosso"},pd={LETTURA_NON_VERIFICABILE:"lettura-non-verificabile",OWNER_NON_DISPONIBILE:"owner-non-disponibile",OWNER_RIMOSSO:"owner-rimosso",LOCALE_NON_VERIFICATO:"lettura-locale-non-verificata"},xS={RITORNO:"ritorno-dopo-assenza",IDENTITA:"identita-cambiata"},t3=6e4;function n3(e,t){return!e||!Array.isArray(t)?null:t.find(n=>Array.isArray(n==null?void 0:n.route)&&n.route.join("/")===e)||null}function kS(e){const t=e&&e.created;return Number.isFinite(t)&&t>0?t:null}function s3({tileKey:e,node:t,nodeGroups:n,sessionsAlive:s,localVerified:i=!0,localIdentita:l=null,lastVerifiedAt:c=null,nowMs:u=0}={}){const h=n3(t,n);let p,v=Wp.OK,_=null,g=null;if(!t)i?!s||s.has(e)?(p=gs.PRESENTE,g=kS({created:l})):p=gs.ASSENTE:(p=gs.IGNOTA,_=pd.LOCALE_NON_VERIFICATO);else if(!h)p=gs.IGNOTA,v=Wp.RIMOSSO,_=pd.OWNER_RIMOSSO;else if(h.status!=="up")p=gs.IGNOTA,v=Wp.NON_DISPONIBILE,_=h.cause||pd.OWNER_NON_DISPONIBILE;else if(h.inventoryPartial===!0)p=gs.IGNOTA,_=pd.LETTURA_NON_VERIFICABILE;else if(!s||s.has(e)){p=gs.PRESENTE;const S=Array.isArray(h.sessions)?h.sessions.find(N=>N&&N.key===e):null;g=kS(S)}else p=gs.ASSENTE;const w=p===gs.IGNOTA&&Number.isFinite(c)&&Number.isFinite(u)&&u-c>t3;return{presenza:p,owner:v,causa:_,identita:p===gs.PRESENTE?g:null,verificata:p!==gs.IGNOTA,oltreIlTetto:w}}function aE(){return{presenza:null,identita:null}}function i3(e,t){const n=e&&typeof e=="object"?e:aE();if(!t||t.presenza===gs.IGNOTA)return{runtime:{presenza:n.presenza,identita:n.identita},generazione:0,motivo:null};const s=t.presenza===gs.PRESENTE;let i=null;return s&&(n.presenza===gs.ASSENTE?i=xS.RITORNO:n.presenza===gs.PRESENTE&&n.identita!==null&&t.identita!==null&&n.identita!==t.identita&&(i=xS.IDENTITA)),{runtime:{presenza:t.presenza,identita:s?t.identita===void 0?null:t.identita:null},generazione:i?1:0,motivo:i}}const i_="nc_input_preferences_v1",qp="nc-input-preferences",lE=Object.freeze(["double-tap","single-tap","never"]),cE=Object.freeze(["full","compact"]);function r3(){try{return typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1}catch{return!1}}const Er=Object.freeze({terminalKeyboardGesture:"double-tap",keybarKeepsKeyboardClosed:!0,voiceKeepsKeyboardClosed:!0,showKeybarEnter:!0,keybarLayout:"full",showComposer:r3()});function r_(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{terminalKeyboardGesture:lE.includes(t.terminalKeyboardGesture)?t.terminalKeyboardGesture:Er.terminalKeyboardGesture,keybarKeepsKeyboardClosed:typeof t.keybarKeepsKeyboardClosed=="boolean"?t.keybarKeepsKeyboardClosed:Er.keybarKeepsKeyboardClosed,voiceKeepsKeyboardClosed:typeof t.voiceKeepsKeyboardClosed=="boolean"?t.voiceKeepsKeyboardClosed:Er.voiceKeepsKeyboardClosed,showKeybarEnter:typeof t.showKeybarEnter=="boolean"?t.showKeybarEnter:Er.showKeybarEnter,keybarLayout:cE.includes(t.keybarLayout)?t.keybarLayout:Er.keybarLayout,showComposer:typeof t.showComposer=="boolean"?t.showComposer:Er.showComposer}}function uE(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function CS(e=uE()){if(!e)return{...Er};try{return r_(JSON.parse(e.getItem(i_)||"null"))}catch{return{...Er}}}function o3(e,t=uE()){const n=r_(e);if(t)try{t.setItem(i_,JSON.stringify(n))}catch{}return n}function o_(){const[e,t]=y.useState(CS);y.useEffect(()=>{const s=i=>{if((i==null?void 0:i.type)==="storage"&&i.key!==i_&&i.key!==null)return;const l=i!=null&&i.detail?r_(i.detail):CS();t(l)};return window.addEventListener(qp,s),window.addEventListener("storage",s),()=>{window.removeEventListener(qp,s),window.removeEventListener("storage",s)}},[]);const n=y.useCallback(s=>{t(i=>{const l=o3({...i,...s||{}});return window.dispatchEvent(new CustomEvent(qp,{detail:l})),l})},[]);return[e,n]}const Tt=Object.freeze({SUBMITTED:"submitted",ADMITTED:"admitted",AWAITING_APPROVAL:"awaiting_approval",RUNNING:"running",CANCEL_REQUESTED:"cancel_requested",DONE:"done",ERROR:"error",CANCELLED:"cancelled",UNKNOWN:"unknown"}),a3=Object.freeze({[Tt.SUBMITTED]:"inviato",[Tt.ADMITTED]:"ammesso",[Tt.AWAITING_APPROVAL]:"in attesa di OK",[Tt.RUNNING]:"in corso",[Tt.CANCEL_REQUESTED]:"annullamento richiesto",[Tt.DONE]:"terminato",[Tt.ERROR]:"errore",[Tt.CANCELLED]:"annullato",[Tt.UNKNOWN]:"esito incerto"}),l3={run_done:Tt.DONE,run_error:Tt.ERROR,run_cancelled:Tt.CANCELLED},c3=new Set(["gap","reset"]);function Xi(e){return e.terminal!==null}function u3(e){return!!(e&&e.resolved==null&&!e.invalidated)}function d3(e){return!e||typeof e!="object"?null:e.type==="event"&&e.event?{target:e.target||null,event:e.event}:e.target&&c3.has(e.type)?{target:e.target,event:h3(e)}:e.event&&e.target?{target:e.target,event:e.event}:{target:null,event:e}}function h3(e){const t=e.data||{...e.count!==void 0?{count:e.count}:{},...e.reason!==void 0?{reason:e.reason}:{},...e.scope!==void 0?{scope:e.scope}:{},...e.currentCursor!==void 0?{currentCursor:e.currentCursor}:{}};return{sessionId:e.sessionId,runId:e.runId,source:e.source||{},type:e.type==="reset"?"stream_reset":"gap",data:t}}function dE(e){return!e||typeof e!="object"?"":`${e.kind||"unknown"}:${e.ref||""}`}function hE(e){return{runId:e||null,state:Tt.SUBMITTED,started:!1,turnEnded:!1,terminal:null,messages:[],tools:[],items:[],limit:null}}function f3({target:e,viewer:t={canApprove:!1},now:n=Date.now(),reviews:s={}}={}){return{target:e||null,targetKey:dE(e),sessionId:null,bootId:null,generation:null,lastSeq:-1,...hE(null),approval:null,approvals:{},approvalInvalid:{},fenced:!1,gap:null,reset:null,context:null,dropped:0,conflicts:[],viewer:t,now:n,reviews:s,seen:{},retired:[]}}function p3(e){try{return JSON.stringify(e)}catch{return String(e)}}function m3(e,t){return!!(e&&t&&e.bootId===t.bootId&&e.generation===t.generation)}function g3(e,t,n){return e.retired.some(s=>s.bootId===t&&s.generation===n)}function ES(e){return!e||!e.bootId?"none":`${e.bootId}:${e.generation}`}function v3(e,t){const n=t.data||{};if(t.type!=="stream_reset"){const l=t.source||{};return e.bootId&&l.bootId&&(l.bootId!==e.bootId||l.generation!==e.generation)?{kind:"drop"}:null}const s=n.currentCursor;if(!s||!s.bootId)return{kind:"conflict",reason:"missing-cursor"};const i=t.source||{};return i.bootId&&i.bootId!==s.bootId?{kind:"conflict",reason:"cursor-source-mismatch"}:g3(e,s.bootId,s.generation)?{kind:"conflict",reason:"retired-epoch"}:e.bootId&&s.bootId===e.bootId&&Number.isInteger(s.generation)&&Number.isInteger(e.generation)&&s.generation<e.generation?{kind:"conflict",reason:"older-same-boot"}:e.bootId&&(n.scope||"broker_view")==="broker_view"&&(s.bootId!==e.bootId||s.generation!==e.generation)?{kind:"conflict",reason:"broker-reset-source-mismatch"}:null}function Yg(e,t){return e.approval?{...e,approvalInvalid:{...e.approvalInvalid,[e.approval.approvalId]:t},approval:{...e.approval,actionable:!1,invalidated:t}}:e}function Kp(e,t,n){const s=Yg(e,t);return{...s,conflicts:[...s.conflicts,{kind:t,...n}]}}function _3(e,t,n,s){const i=n.messageId||`${s||"run"}:assistant`,l=Number.isInteger(n.fragmentIndex)?n.fragmentIndex:null,c=e.findIndex(p=>p.messageId===i);if(c<0)return{messages:[...e,{messageId:i,role:"assistant",text:typeof n.text=="string"?n.text:"",streaming:!0,fragments:l===null?[]:[l]}],items:[...t,{kind:"message",messageId:i}]};const u=e[c];if(!u.streaming)return{messages:e,items:t};if(l!==null&&u.fragments.includes(l))return{messages:e,items:t};const h=e.slice();return h[c]={...u,text:u.text+(typeof n.text=="string"?n.text:""),fragments:l===null?u.fragments:[...u.fragments,l]},{messages:h,items:t}}function y3(e,t,n,s){const i=n.messageId||`${s||"run"}:assistant`,l=n.role==="user"?"user":"assistant",c=typeof n.text=="string"?n.text:"",u=e.findIndex(h=>h.messageId===i);if(u>=0){const h=e.slice();return h[u]={...h[u],role:l,text:c,streaming:!1},{messages:h,items:t}}return{messages:[...e,{messageId:i,role:l,text:c,streaming:!1,fragments:[]}],items:[...t,{kind:"message",messageId:i}]}}function b3(e,t){return e.toolCallId||t.toolCallId||""}function NS(e,t,n,s){const i=b3(s,n);if(t==="tool_start")return[...e,{toolCallId:i||`tool-${e.length+1}`,name:n.name||"tool",state:"running",startedAt:Number.isFinite(n.at)?n.at:null,endedAt:null,isError:!1}];const l=e.findIndex(u=>u.toolCallId===i);if(l<0)return e;const c=e.slice();return c[l]={...c[l],state:n.isError===!0?"error":"ok",isError:n.isError===!0,endedAt:Number.isFinite(n.at)?n.at:null},c}function w3(e,t,n){const s=n.approvalId||"approval",i=e.approvals[s];if(i!=null&&i.resolved||Xi(e))return e;const l=Number.isFinite(n.remainingMs)?n.remainingMs:0,c=e.viewer.canApprove===!0&&e.reviews[s]||null,u=e.approvalInvalid[s]||(e.fenced?"cancel_requested":null),h=e.viewer.canApprove===!0&&c!==null&&c.complete===!0&&!Xi(e)&&e.gap===null&&e.reset===null&&!u&&!e.fenced,p={approvalId:s,runId:t.runId||e.runId,summary:n,review:c,expiresAt:e.now+l,resolved:null,actionable:h,...u?{invalidated:u}:{}},v=e.items.some(_=>_.kind==="approval"&&_.approvalId===s)?e.items:[...e.items,{kind:"approval",approvalId:s}];return{...e,approval:p,items:v,state:e.fenced?Tt.CANCEL_REQUESTED:Tt.AWAITING_APPROVAL}}function S3(e,t){var w;const n=d3(t);if(!n||!n.event)return e;const s=n.event,i=s.source||{};if(n.target&&e.targetKey&&dE(n.target)!==e.targetKey)return{...e,dropped:e.dropped+1};if(e.sessionId&&s.sessionId&&s.sessionId!==e.sessionId)return{...e,dropped:e.dropped+1};const l=i.bootId||e.bootId,c=Number.isInteger(i.generation)?i.generation:e.generation,u=typeof i.seq=="number"?i.seq:null;let h=e;if(u!==null&&l){const S=`${l}:${c}:${u}`,N=p3(s);if(h.seen[S]!==void 0)return h.seen[S]===N?{...h,dropped:h.dropped+1}:Kp({...h,dropped:h.dropped+1},"seq-payload",{key:S});h={...h,seen:{...h.seen,[S]:N}}}const p=v3(h,s);if((p==null?void 0:p.kind)==="drop")return{...h,dropped:h.dropped+1};if((p==null?void 0:p.kind)==="conflict")return Kp({...h,dropped:h.dropped+1},"stale-reset",{reason:p.reason,from:ES(h),to:ES((w=s.data)==null?void 0:w.currentCursor)});const v=s.data||{},_=s.runId||v.runId||h.runId;switch(s.type){case"cancel_requested":{const S={...h,fenced:!0,state:Tt.CANCEL_REQUESTED};return Yg(S,"cancel_requested")}case"run_started":return h.started&&_&&_===h.runId?h:{...h,...hE(_),sessionId:s.sessionId||h.sessionId,bootId:l||h.bootId,generation:Number.isInteger(c)?c:h.generation,lastSeq:u!==null?u:h.lastSeq,fenced:!1,approval:null,approvalInvalid:{},state:Tt.ADMITTED,started:!0}}if(_&&h.runId&&_!==h.runId)return{...h,dropped:h.dropped+1};const g={...h,sessionId:s.sessionId||h.sessionId,bootId:l,generation:c,lastSeq:u!==null?u:h.lastSeq,runId:_||h.runId};switch(s.type){case"text_delta":case"message":{if(Xi(g))return g;const S=g.started;let N=g.started,C=g.limit,j=g.state;N||(i.kind==="cli_adapter"?(N=!0,j=Tt.ADMITTED):(C="missing_run_started",j=Tt.UNKNOWN));const E=s.type==="text_delta"?_3(g.messages,g.items,v,g.runId):y3(g.messages,g.items,v,g.runId),R=g.fenced?Tt.CANCEL_REQUESTED:j===Tt.UNKNOWN?j:S?Tt.RUNNING:Tt.ADMITTED;return{...g,started:N,limit:C,messages:E.messages,items:E.items,state:R}}case"tool_start":{if(Xi(g))return g;if(!g.started&&i.kind!=="cli_adapter")return{...g,limit:"missing_run_started",state:Tt.UNKNOWN};const S=NS(g.tools,"tool_start",v,s);return{...g,started:!0,turnEnded:!1,tools:S,items:[...g.items,{kind:"tool",toolCallId:S[S.length-1].toolCallId}],state:g.fenced?Tt.CANCEL_REQUESTED:Tt.RUNNING}}case"tool_end":return Xi(g)?g:{...g,tools:NS(g.tools,"tool_end",v,s),state:g.fenced?Tt.CANCEL_REQUESTED:g.state===Tt.UNKNOWN?g.state:Tt.RUNNING};case"turn_end":return Xi(g)?g:{...g,turnEnded:!0};case"approval_requested":return w3(g,s,v);case"approval_resolved":{const S=v.approvalId;if(!S)return g;const N={...g.approvals,[S]:{resolved:v.decision||"resolved"}},C={...g.approvalInvalid};delete C[S];const j=!!(g.approval&&g.approval.approvalId===S),E=j?{...g.approval,resolved:v.decision||"resolved",actionable:!1}:g.approval;let R;return Xi(g)?R=g.state:g.fenced?R=Tt.CANCEL_REQUESTED:j?R=Tt.RUNNING:R=u3(E)?Tt.AWAITING_APPROVAL:Tt.RUNNING,{...g,approvals:N,approvalInvalid:C,approval:E,state:R}}case"context_status":return{...g,context:{...v}};case"gap":return{...Yg(g,"gap"),gap:{count:v.count??null,reason:v.reason||"unknown"},state:Xi(g)?g.state:g.fenced?Tt.CANCEL_REQUESTED:Tt.UNKNOWN};case"stream_reset":{const S=v.currentCursor,N=v.scope||"broker_view",C=!m3(h,S),j=C&&h.bootId?[...h.retired,{bootId:h.bootId,generation:h.generation}]:h.retired,E={scope:N,reason:v.reason||"unknown"};return C?{...g,reset:E,bootId:S.bootId,generation:S.generation,lastSeq:Number.isInteger(S.seq)?S.seq:-1,retired:j,gap:null,approval:null,approvalInvalid:{},fenced:!1,state:Xi(g)?g.state:Tt.UNKNOWN}:{...g,reset:E,lastSeq:Number.isInteger(S.seq)?S.seq:g.lastSeq,retired:j,gap:null,state:Xi(g)?g.state:g.fenced?Tt.CANCEL_REQUESTED:Tt.UNKNOWN}}case"run_done":case"run_error":case"run_cancelled":return g.terminal?g.terminal.type===s.type?{...g,dropped:g.dropped+1}:Kp(g,"terminal-conflict",{runId:g.runId,kept:g.terminal.type,late:s.type}):{...g,terminal:{type:s.type,stopReason:v.stopReason||null,effectsState:v.effectsState||null,at:Number.isFinite(v.at)?v.at:null},fenced:!1,approval:g.approval?{...g.approval,actionable:!1}:null,state:l3[s.type]};default:return g}}function x3(e,t){return(t||[]).reduce((n,s)=>S3(n,s),e)}const k3=new Set([Tt.SUBMITTED,Tt.UNKNOWN,Tt.DONE,Tt.ERROR,Tt.CANCELLED,Tt.CANCEL_REQUESTED]);function C3(e,t,n={}){return!(!e||!t||(n==null?void 0:n.canApprove)!==!0||t.resolved!=null||t.invalidated||t.actionable===!1||!t.review||t.review.complete!==!0||!e.state||k3.has(e.state)||e.terminal||e.fenced||e.gap||e.reset)}function Xg(e){return!e||!Number.isFinite(e.startedAt)||!Number.isFinite(e.endedAt)?null:Math.max(0,e.endedAt-e.startedAt)}function E3({state:e,terminal:t=null}){const n=a3[e]||e;return o.jsxs("span",{className:"nc-chat-state","data-state":e,role:"status","aria-live":"polite",children:[n,t!=null&&t.stopReason?o.jsxs("small",{className:"nc-chat-stop",children:[" · ",t.stopReason]}):null]})}function N3(e){if(!Number.isFinite(e))return"--:--";const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function j3({tools:e=[]}){const[t,n]=y.useState(!1),s=y.useId();return e.length===0?null:o.jsxs("div",{className:"nc-chat-tools-menu",children:[o.jsxs("button",{type:"button",className:"nc-chat-tools-toggle","aria-expanded":t,"aria-controls":s,onClick:()=>n(i=>!i),children:[e.length," tool",o.jsx("span",{className:"nc-chat-chevron","aria-hidden":"true",children:t?"▴":"▾"})]}),t&&o.jsx("ul",{id:s,className:"nc-chat-tools-list",children:e.map(i=>o.jsxs("li",{children:[o.jsx("span",{className:"nc-chat-tools-time",children:N3(i.startedAt)}),o.jsx("span",{className:"nc-chat-tools-name",children:i.name}),o.jsx("span",{className:"nc-chat-tools-state",children:i.state}),o.jsx("span",{className:"nc-chat-tools-dur",children:Xg(i)===null?"—":`${(Xg(i)/1e3).toFixed(1)} s`})]},i.toolCallId))})]})}const L3={ok:"ok",error:"errore",running:"in corso"};function R3(e){const t=Xg(e);return t===null?"durata sconosciuta":`${(t/1e3).toLocaleString("it-IT",{maximumFractionDigits:1})} s`}function A3({tool:e}){return o.jsxs("article",{className:"nc-chat-tool","data-state":e.state,"data-tool-call-id":e.toolCallId,children:[o.jsx("span",{className:"nc-chat-tool-dot","aria-hidden":"true"}),o.jsx("span",{className:"nc-chat-tool-name",children:e.name}),o.jsx("span",{className:"nc-chat-tool-result",children:L3[e.state]||e.state}),o.jsx("span",{className:"nc-chat-tool-dur",children:R3(e)})]})}function M3(e,t){return Number.isFinite(e)?Math.max(0,Math.ceil((e-t)/1e3)):null}function T3(e){const t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,"0")}`}function I3({run:e,approval:t,viewer:n={canApprove:!1},now:s=Date.now(),demo:i=!0}){var _;if(!t)return null;const l=M3(t.expiresAt,s),c=l===0,u=!!t.resolved,h=C3(e,t,n)&&!c&&!u,p=n.canApprove===!0&&!!t.review,v=u?`risolta: ${t.resolved}`:c?"scaduta":`scade ${T3(l)}`;return o.jsxs("section",{className:"nc-chat-approval","data-state":u?"resolved":c?"expired":"pending","aria-label":"Richiesta di approvazione",children:[o.jsxs("header",{className:"nc-chat-approval-head",children:[o.jsx("span",{className:"nc-chat-approval-title",children:"Comando distruttivo"}),o.jsx("span",{className:"nc-chat-approval-status",children:v})]}),p?o.jsxs(o.Fragment,{children:[o.jsx("pre",{className:"nc-chat-approval-command",children:t.review.displayCommand}),o.jsxs("dl",{className:"nc-chat-approval-meta",children:[t.review.cwd?o.jsxs("div",{children:[o.jsx("dt",{children:"cwd"}),o.jsx("dd",{children:t.review.cwd})]}):null,Array.isArray(t.review.targets)&&t.review.targets.length>0?o.jsxs("div",{children:[o.jsx("dt",{children:"target"}),o.jsx("dd",{children:t.review.targets.join(", ")})]}):null,t.review.effectiveUser?o.jsxs("div",{children:[o.jsx("dt",{children:"utente"}),o.jsx("dd",{children:t.review.effectiveUser})]}):null,(_=t.summary)!=null&&_.coverage?o.jsxs("div",{children:[o.jsx("dt",{children:"copertura"}),o.jsx("dd",{children:t.summary.coverage})]}):null]})]}):o.jsx("p",{className:"nc-chat-approval-redacted",children:"Dettaglio non disponibile a questo lettore."}),o.jsxs("div",{className:"nc-chat-approval-actions",children:[o.jsx("button",{type:"button",className:"nc-chat-btn",disabled:!h,"data-demo":i?"1":void 0,children:"Nega"}),o.jsx("button",{type:"button",className:"nc-chat-btn nc-chat-btn-primary",disabled:!h,"data-demo":i?"1":void 0,children:"Approva una volta"})]}),t.invalidated?o.jsxs("small",{className:"nc-chat-demo-hint","data-testid":"approval-invalidated",children:["richiesta non più valida: ",t.invalidated]}):null,i&&h?o.jsx("small",{className:"nc-chat-demo-hint",children:"demo: nessuna azione"}):null]})}function P3({message:e}){return o.jsxs("div",{className:`nc-chat-msg nc-chat-msg-${e.role}`,"data-message-id":e.messageId,children:[o.jsx("p",{children:e.text}),e.streaming?o.jsx("span",{className:"nc-chat-caret","aria-hidden":"true",children:"▍"}):null]})}const D3={"seq-payload":"evento duplicato con contenuto diverso","terminal-conflict":"terminale in conflitto (mantenuto il primo)","stale-reset":"reset rifiutato (epoch ritirato o precedente)"};function O3(e){return D3[e.kind]||e.kind}function B3({view:e,viewer:t,now:n=Date.now(),demo:s=!0}){const i=(l,c,u)=>l.find(h=>h[c]===u);return o.jsxs("div",{className:"nc-chat-log","data-testid":"chat-transcript",children:[e.conflicts.length>0?o.jsxs("div",{className:"nc-chat-notice nc-chat-notice-warn nc-chat-conflict",role:"alert","data-testid":"chat-conflicts",children:[o.jsx("strong",{children:"conflitto d'integrità"}),o.jsx("ul",{children:e.conflicts.map((l,c)=>o.jsx("li",{children:O3(l)},`${l.kind}:${c}`))})]}):null,e.gap?o.jsxs("div",{className:"nc-chat-notice",role:"status",children:[e.gap.count?`${e.gap.count} eventi mancanti`:"eventi mancanti"," · ",e.gap.reason]}):null,e.reset?o.jsxs("div",{className:"nc-chat-notice",role:"status",children:["vista azzerata · ",e.reset.reason]}):null,e.items.map(l=>{if(l.kind==="message"){const c=i(e.messages,"messageId",l.messageId);return c?o.jsx(P3,{message:c},`m:${l.messageId}`):null}if(l.kind==="tool"){const c=i(e.tools,"toolCallId",l.toolCallId);return c?o.jsx(A3,{tool:c},`t:${l.toolCallId}`):null}return l.kind==="approval"?o.jsx(I3,{run:e,approval:e.approval,viewer:t,now:n,demo:s},"approval"):null}),e.state===Tt.UNKNOWN&&!e.terminal?o.jsx("div",{className:"nc-chat-notice nc-chat-notice-warn",role:"status",children:"esito incerto: la sorgente non ha ancora fornito un terminale"}):null]})}function $3({context:e,capabilities:t}){const n=(e==null?void 0:e.cwd)||(t==null?void 0:t.cwd)||"—",s=(t==null?void 0:t.permissionPolicy)||(e==null?void 0:e.policy)||"—",i=Number.isFinite((e==null?void 0:e.contextPct)??(t==null?void 0:t.contextPct))?`${(e==null?void 0:e.contextPct)??(t==null?void 0:t.contextPct)}%`:"—",l=(t==null?void 0:t.ram)||"—";return o.jsxs("div",{className:"nc-chat-statusline","data-testid":"chat-statusline",children:[o.jsx("span",{title:"working directory",children:n}),o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsx("span",{title:"policy",children:s}),o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsx("span",{title:"context",children:`ctx ${i}`}),o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsx("span",{title:"RAM",children:`RAM ${l}`})]})}function z3({label:e="",running:t=!1,demo:n=!0}){const[s,i]=y.useState("");return o.jsxs("div",{className:"nc-chat-composer","data-demo":n?"1":void 0,children:[o.jsxs("div",{className:"nc-chat-pill",children:[o.jsx("button",{type:"button",className:"nc-chat-icon","aria-label":"Allega",disabled:!0,title:"demo",children:"+"}),o.jsxs("label",{className:"nc-chat-input",children:[o.jsxs("span",{className:"nc-chat-sr",children:["Messaggio",e?` per ${e}`:""]}),o.jsx("textarea",{rows:1,value:s,onChange:l=>i(l.target.value),placeholder:"Scrivi…"})]}),o.jsx("button",{type:"button",className:"nc-chat-icon","aria-label":"Cronologia messaggi",disabled:!0,title:"demo",children:"↺"}),o.jsx("button",{type:"button",className:"nc-chat-icon","aria-label":"Detta a voce",disabled:!0,title:"demo",children:"🎙"})]}),t?o.jsx("button",{type:"button",className:"nc-chat-send","aria-label":"Ferma il turno",disabled:!0,title:"demo: nessuna chiamata reale",children:"■"}):o.jsx("button",{type:"button",className:"nc-chat-send","aria-label":"Invia",disabled:!0,title:"demo: nessuna chiamata reale",children:"↑"})]})}const F3=new Set([Tt.RUNNING,Tt.CANCEL_REQUESTED,Tt.AWAITING_APPROVAL]);function H3(e){return(e||[]).some(t=>{var n;return(((n=t==null?void 0:t.event)==null?void 0:n.type)||(t==null?void 0:t.type))==="approval_requested"})}function a_({target:e,events:t=[],viewer:n={canApprove:!1},now:s,label:i="",capabilities:l=null,demo:c=!0,cancelRequested:u=!1,reviews:h={}}){const[p]=y.useState(()=>Number.isFinite(s)?s:Date.now()),v=y.useMemo(()=>H3(t),[t]),[_,g]=y.useState(p);y.useEffect(()=>{if(Number.isFinite(s)||!v)return;const S=setInterval(()=>g(Date.now()),1e3);return()=>clearInterval(S)},[s,v]);const w=y.useMemo(()=>{const S=u?[...t,{type:"cancel_requested"}]:t;return x3(f3({target:e,viewer:n,now:p,reviews:h}),S)},[e,n,t,p,u,h]);return o.jsxs("div",{className:"nc-chat","data-state":w.state,"data-target-kind":(e==null?void 0:e.kind)||"unknown",children:[o.jsxs("div",{className:"nc-chat-top",children:[o.jsx(E3,{state:w.state,terminal:w.terminal}),o.jsx(j3,{tools:w.tools})]}),c?o.jsx("p",{className:"nc-chat-demo-notice",role:"status","data-testid":"chat-demo-notice",children:"approvazioni dimostrative, semantica non qualificata"}):null,o.jsx(B3,{view:w,viewer:n,now:Number.isFinite(s)?s:_,demo:c}),o.jsx($3,{context:w.context,capabilities:l}),o.jsx(z3,{label:i,running:F3.has(w.state),demo:c})]})}const jS=17924e8,Jg="00000000000000000000000000000000",fE="11111111111111111111111111111111",pE="ui0-demo-cell",th=Object.freeze({vl:{kind:"vl_node",ref:`${Jg}:VL-${fE}`},cli:{kind:"cli_cell",ref:`${Jg}:cell-${pE}`}}),U3=Object.freeze({"ap-1":Object.freeze({displayCommand:"rm -rf build/tmp",cwd:"/srv/app",targets:Object.freeze(["build/tmp"]),effectiveUser:"demo",complete:!0}),"ap-incomplete":Object.freeze({displayCommand:"rm -rf …",cwd:"/srv/app",targets:Object.freeze(["build/tmp"]),effectiveUser:"demo",complete:!1})}),W3="a".repeat(64);function ri({target:e,sessionId:t,sourceKind:n="vl_host",bootId:s="boot-a",generation:i=1,seq:l,type:c,runId:u="run-1",toolCallId:h,data:p={}}){const v={kind:n,ownerId:Jg,...n==="vl_host"?{nodeId:fE}:{cellId:pE},bootId:s,generation:i,seq:l};return{protocol:"nc-chat/1",type:"event",target:e,event:{sessionId:t,runId:u,...h?{toolCallId:h}:{},type:c,source:v,data:p}}}function q3(e,t=96e3,n=W3){return{approvalId:e,commandHash:n,epoch:1,ruleIds:["d2.rm-recursive"],coverage:"complete",remainingMs:t,reviewAvailable:!0}}function K3(e="sess-vl-1"){const t={target:th.vl,sessionId:e,sourceKind:"vl_host",seq:0};return[ri({...t,seq:1,type:"run_started",data:{originRequestId:"req-1"}}),ri({...t,seq:2,type:"text_delta",data:{text:"Ciao",fragmentIndex:0}}),ri({...t,seq:3,type:"text_delta",data:{text:" dal nodo",fragmentIndex:1}}),ri({...t,seq:4,type:"message",data:{messageId:"run-1:assistant",role:"assistant",text:"Ciao dal nodo"}}),ri({...t,seq:5,type:"context_status",data:{contextPct:18}}),ri({...t,seq:6,type:"turn_end",data:{}}),ri({...t,seq:7,type:"run_done",data:{stopReason:"stop",effectsState:"none"}})]}function V3(e="sess-cli-1",{remainingMs:t=96e3,approvalId:n="ap-1"}={}){const s={target:th.cli,sessionId:e,sourceKind:"cli_adapter",seq:0};return[ri({...s,seq:1,type:"run_started",data:{originRequestId:"req-2"}}),ri({...s,seq:2,type:"context_status",data:{cwd:"/srv/app",contextPct:18}}),ri({...s,seq:3,type:"tool_start",toolCallId:"tc-1",data:{name:"bash",at:jS}}),ri({...s,seq:4,type:"tool_end",toolCallId:"tc-1",data:{name:"bash",at:jS+180,isError:!1,resultAvailable:!0}}),ri({...s,seq:5,type:"text_delta",data:{text:"Serve il tuo OK",fragmentIndex:0}}),ri({...s,seq:6,type:"approval_requested",data:q3(n,t)})]}const go=Object.freeze({vl:{label:"N900 (demo)",sub:"nodo VL sintetico · vl-agent/1",target:th.vl,events:K3(),viewer:{canApprove:!1},reviews:{}},cli:{label:"Dev (demo)",sub:"cella CLI sintetica · ACP",target:th.cli,events:V3(),viewer:{canApprove:!0},reviews:U3}}),G3={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function l_(e){try{const t=e||(typeof import.meta<"u"?G3:null);return(t==null?void 0:t.VITE_UI0_CHAT_DEMO)==="1"}catch{return!1}}function Y3(e){try{return new URLSearchParams(e||"").get("ui0")==="1"}catch{return!1}}function X3({session:e,node:t,ownerId:n,cellName:s,token:i,readonly:l=!1,focused:c,onFocus:u,onClose:h,onOpenSingle:p,onDragTileStart:v,floating:_=!1,minimized:g=!1,takeSize:w=!1,onDetach:S,onReattach:N,onToggleMinimize:C,onFloatDragStart:j,alive:E=!0,sessionAlive:R=E,available:x=!0,stale:W=!1,presence:$=null,fontSize:Y=bi,onZoom:q,decks:K=[],currentDeck:se,onSendToDeck:V,panelUrl:B="",panelCellId:D="",panelPort:O=0,chatPreview:P=null}){const[z]=o_(),A=s||e,T=y.useRef(()=>{}),L=y.useRef(()=>!1),H=y.useRef(()=>{}),M=y.useRef(!1),[U,ee]=y.useState(!1),[re,oe]=y.useState(!1),[je,te]=y.useState(!1),[ie,pe]=y.useState(!1),[xe,Be]=y.useState(null),[Te,Me]=y.useState(0),J=y.useRef(aE()),le=t?`${t}:${e}`:e,Q=l_()&&!!P,ge=K.filter(ve=>ve.id!==se&&ve.available!==!1),Z=$?$.presenza:R?gs.PRESENTE:gs.ASSENTE,fe=$?$.identita??null:null;return y.useEffect(()=>{const ve=i3(J.current,{presenza:Z,identita:fe});J.current=ve.runtime,ve.generazione&&Me(ke=>ke+ve.generazione)},[Z,fe]),o.jsxs("div",{className:`nc-tile${c?" focused":""}`,onMouseDown:()=>u&&u(le),children:[o.jsxs("div",{className:`nc-tile-head${_?" nc-float-head":""}`,draggable:!_,onPointerDown:_&&j?ve=>{ve.target&&ve.target.closest&&ve.target.closest(".nc-tile-actions")||j(ve)}:void 0,onDragStart:ve=>{_||(ve.dataTransfer.setData("text/nc-session",le),ve.dataTransfer.effectAllowed="move",v&&v(le))},children:[o.jsxs("button",{className:"nc-tile-name",onClick:()=>u&&u(le),title:t?`${A} · ${t}`:A,children:[o.jsx("span",{className:E?"nc-dot on":"nc-dot"}),o.jsx("b",{children:A})]}),o.jsxs("span",{className:"nc-tile-actions",children:[_?o.jsxs(o.Fragment,{children:[N&&o.jsx("button",{className:"nc-tile-float-btn",onClick:()=>N(le),title:f("tile-reattach"),"aria-label":f("tile-reattach"),children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"9",y:"3",width:"12",height:"12",rx:"1"}),o.jsx("path",{d:"M11 21H3v-8M3 21l9-9"})]})}),C&&o.jsx("button",{onClick:()=>C(le),title:f(g?"tile-restore":"tile-minimize"),"aria-label":f(g?"tile-restore":"tile-minimize"),children:"–"})]}):o.jsxs(o.Fragment,{children:[q&&o.jsx("button",{onClick:()=>q(-1),title:f("zoom-out"),"aria-label":f("zoom-out"),children:o.jsx(yt,{name:"zoomOut",size:14})}),q&&o.jsx("button",{onClick:()=>q(1),title:f("zoom-in"),"aria-label":f("zoom-in"),children:o.jsx(yt,{name:"zoomIn",size:14})}),V&&ge.length>0&&o.jsxs("select",{className:"nc-tile-deck",title:f("send-to-deck"),value:"",onMouseDown:ve=>ve.stopPropagation(),onChange:ve=>{const ke=ve.target.value;ke&&V(le,ke),ve.target.value=""},children:[o.jsx("option",{value:"",children:f("send-to-deck")}),ge.map(ve=>o.jsxs("option",{value:ve.id,children:[ve.ownerLabel," · ",ve.name]},ve.id))]}),!Q&&o.jsx("button",{onClick:()=>oe(ve=>!ve),title:f("composer"),children:"⌨"}),o.jsx("button",{onClick:()=>te(ve=>!ve),title:f("files"),children:"📁"}),B&&o.jsx("button",{onClick:()=>pe(ve=>!ve),title:f("panel"),"aria-pressed":ie,children:o.jsx(yt,{name:"monitor",size:14})}),p&&o.jsx("button",{onClick:()=>p({session:e,node:t,ownerId:n}),title:f("single-view"),children:"↗"})]}),!_&&S&&o.jsx("button",{className:"nc-tile-float-btn",onClick:()=>S(le),title:f("tile-detach"),"aria-label":f("tile-detach"),children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"3",y:"9",width:"12",height:"12",rx:"1"}),o.jsx("path",{d:"M13 3h8v8M21 3l-9 9"})]})}),h&&o.jsx("button",{className:"nc-tile-close",onClick:()=>h(le),title:f("close"),"aria-label":f("close"),children:"✕"})]})]}),o.jsxs("div",{className:"nc-tile-body",children:[$&&$.oltreIlTetto===!0&&o.jsx("div",{className:"nc-tile-unverified",role:"status","data-causa":$.causa||"",children:f("tile-unverified")}),Q?o.jsx(a_,{target:P.target||go.vl.target,events:P.events||go.vl.events,viewer:P.viewer||go.vl.viewer,reviews:P.reviews||{},label:P.label||A,capabilities:P.capabilities||{permissionPolicy:"yolo"}}):o.jsxs(o.Fragment,{children:[o.jsx(kc,{session:e,node:t,token:i,readonly:l,takeSize:w,focused:c,sendRef:T,composerRef:L,actionRef:H,ctrlRef:M,setCtrlArmed:ee,onFiles:Be,fontSize:Y,keyboardGesture:z.terminalKeyboardGesture},`${le}:${Te}`),!x&&o.jsx("div",{className:"nc-tile-unavailable",title:f("deck-owner-unavailable"),children:f("deck-owner-reconnecting")}),x&&W&&o.jsx("div",{className:"nc-tile-stale",title:f("deck-owner-stale"),children:f("deck-owner-stale")}),x&&je&&o.jsx("div",{className:"nc-tile-files",onMouseDown:ve=>ve.stopPropagation(),children:o.jsx(Kg,{session:e,node:t,token:i,filesEvent:xe,onClose:()=>te(!1)})})]})]}),x&&!Q&&re&&o.jsx("div",{className:"nc-tile-composer",onMouseDown:ve=>ve.stopPropagation(),children:o.jsx(oE,{submitText:ve=>L.current(ve),token:i,session:e,node:t,ownerId:n,readonly:l,keepKeyboardClosedOnVoice:z.voiceKeepsKeyboardClosed})}),x&&ie&&B&&D&&o.jsx(P1,{title:A,onClose:()=>pe(!1),children:o.jsx(Fv,{cellId:D,panelUrl:B,route:t?t.split("/"):[],panelPort:O,token:i,title:A})})]})}function Qg({session:e,node:t,ownerId:n,cells:s,nodeGroups:i}={}){const l=typeof e=="string"?e:"";if(!l)return null;if(t){const u=Array.isArray(i)?i:[];for(const h of u){if(!h||(Array.isArray(h.route)?h.route:[]).join("/")!==t||n&&h.instanceId&&String(n)!==String(h.instanceId))continue;const v=(Array.isArray(h.cells)?h.cells:[]).find(_=>_&&_.tmuxSession===l);if(v)return v}return null}return(Array.isArray(s)?s:[]).find(u=>u&&u.tmuxSession===l)||null}function Uc({session:e,cell:t,node:n,ownerId:s,cells:i,nodeGroups:l}={}){const c=typeof e=="string"?e:"";if(t&&typeof t.cell=="string"&&t.cell)return t.cell;const u=Qg({session:c,node:n,ownerId:s,cells:i,nodeGroups:l});return u&&u.cell?u.cell:c}const LS=.22,RS=.3,mE=(e,t)=>Array.from((e==null?void 0:e.types)||[]).includes(t),Vp=e=>mE(e,"text/nc-session"),AS=e=>{var t;return mE(e,"Files")||(((t=e==null?void 0:e.files)==null?void 0:t.length)||0)>0};function J3(e,t){return e&&Array.isArray(t)?t.find(n=>Array.isArray(n==null?void 0:n.route)&&n.route.join("/")===e):null}function Q3(e,t,n){const s=(e-n.left)/(n.width||1),i=(t-n.top)/(n.height||1);return s<LS?"left":s>1-LS?"right":i>=RS&&i<=1-RS?"center":i<.5?"top":"bottom"}const Z3=[["left","M15 6l-6 6 6 6",22],["top","M6 15l6-6 6 6",22],["center","M4 8h16M20 8l-3-3M20 8l-3 3M20 16H4M4 16l3-3M4 16l3 3",34],["bottom","M6 9l6 6 6-6",22],["right","M9 6l6 6-6 6",22]];function e6({active:e}){return o.jsx("div",{className:"nc-drop-zones","data-testid":"nc-drop-zones","aria-hidden":"true",children:Z3.map(([t,n,s])=>o.jsx("div",{className:`nc-drop-zone ${t}${e===t?" on":""}`,"data-zone":t,children:o.jsx("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:n})})},t))})}function Gp(e,t){for(const n of e.columns)for(const s of n.tiles)if(Wt(s)===t)return s.float||null;return null}function MS(e,t){for(const n of e.columns)for(const s of n.tiles)if(Wt(s)===t)return s.fontSize||null;return null}function t6({layout:e,onLayoutChange:t,token:n,readonly:s=!1,sessionsAlive:i,focusSession:l,onFocus:c,onOpenSingle:u,localVerified:h=!0,localIdentities:p=null,localVerifiedAt:v=null,decks:_=[],currentDeck:g,onSendToDeck:w,onResizeEnd:S,cells:N=[],nodeGroups:C=[],panelPort:j=0,nodePanelPorts:E={}}){Fn();const R=Date.now(),[x,W]=y.useState(null),[$,Y]=y.useState(null),q=y.useRef(null);q.current=$;const[K,se]=y.useState({z:{},next:1,focus:null,mini:{}}),[V,B]=y.useState(null),D=y.useRef(null);D.current=V;const O=y.useRef(null),P=y.useRef([]),z=y.useRef(null);function A(Z,fe,ve){const ke=()=>{window.removeEventListener("pointermove",Z),window.removeEventListener("pointerup",Ve),window.removeEventListener("pointercancel",ot),window.removeEventListener("blur",ot)},Ve=()=>{ke(),z.current=null,fe&&fe()},ot=()=>{ke(),z.current=null,ve&&ve()};window.addEventListener("pointermove",Z),window.addEventListener("pointerup",Ve),window.addEventListener("pointercancel",ot),window.addEventListener("blur",ot),z.current=ot}y.useEffect(()=>()=>{z.current&&z.current()},[]),y.useEffect(()=>{if(!x&&!V)return;const Z=fe=>{fe.key==="Escape"&&(W(null),V&&z.current&&z.current())};return window.addEventListener("keydown",Z),()=>{window.removeEventListener("keydown",Z)}},[x,V]),y.useEffect(()=>{const Z=()=>W(null);return window.addEventListener("dragend",Z),window.addEventListener("drop",Z),()=>{window.removeEventListener("dragend",Z),window.removeEventListener("drop",Z)}},[]);const T=e.columns.length,L=e.columns.flatMap(Z=>Z.tiles).filter(Z=>Z.float).map(Z=>Wt(Z)),H=Z=>!!Z&&Z.tiles.length>0&&Z.tiles.every(fe=>fe.float),M=Z=>x&&x.col===Z&&x.row===void 0,U=!!x&&x.col===T,ee=(Z,fe)=>x&&x.col===Z&&x.row===fe&&x.quadrant?` drop-${x.quadrant}`:"";function re(Z){var Ve;if(Z.preventDefault(),AS(Z.dataTransfer)){W(null);return}const fe=Z.dataTransfer.getData("text/nc-session"),ve=x;if(W(null),!fe||!ve)return;if(ve.quadrant==="center"){const ot=Wt(((Ve=e.columns[ve.col])==null?void 0:Ve.tiles[ve.row])||{});ot&&ot!==fe&&t(TP(e,fe,ot));return}let ke;if(ve.quadrant){if(ke=HP(e,ve.col,ve.row,ve.quadrant),!ke)return}else ke={col:ve.col};t(bs(e).includes(fe)?AP(e,fe,ke):zc(e,fe,ke))}function oe(Z,fe){var X,I,ce;Z.preventDefault(),Z.stopPropagation();try{Z.currentTarget.setPointerCapture&&Z.pointerId!=null&&Z.currentTarget.setPointerCapture(Z.pointerId)}catch{}const ve=O.current&&O.current.clientWidth||0,ke=O.current?O.current.getBoundingClientRect():null,Ve=ke?ke.left:0,ot=P.current[fe]?P.current[fe].getBoundingClientRect():null,rt=P.current[fe+1]?P.current[fe+1].getBoundingClientRect():null,$e=ot&&rt&&rt.right>ot.left?ot.left-(ke?ke.left:0):0,_e=Number.isFinite(Z.clientX)?Z.clientX:0,ze=e.columns[fe].width+(((X=e.columns[fe+1])==null?void 0:X.width)||0),Je=e.columns.reduce((ye,Re)=>ye+Re.width,0),He=ot&&rt&&rt.right>ot.left?rt.right-ot.left:ve*(ze/(Je||1)),nt=Math.min(PC,He/2),lt=ye=>{const Re=(Number.isFinite(ye.clientX)?ye.clientX:_e)-Ve;let ae=Math.max(nt,Math.min(He-nt,Re-$e)),Oe=!1;if(!ye.altKey){for(const gt of Sc)if(Math.abs(ae-gt*He)<=zg){ae=gt*He,Oe=!0;break}}return{border:ae,snapped:Oe,alt:ye.altKey===!0}};Y({kind:"col",ci:fe,coupleLeft:$e,couplePx:He,live:lt(Z),pxOther:O.current&&O.current.clientHeight||0,fsA:((I=e.columns[fe].tiles[0])==null?void 0:I.fontSize)||bi,fsB:((ce=e.columns[fe+1].tiles[0])==null?void 0:ce.fontSize)||bi}),A(ye=>Y(Re=>Re&&{...Re,live:lt(ye)}),()=>{var ae,Oe;const ye=q.current,Re=((ae=ye==null?void 0:ye.live)==null?void 0:ae.border)??He/2;Y(null),t(fS(e,fe,ve,Re,{snap:!((Oe=ye==null?void 0:ye.live)!=null&&Oe.alt)})),S&&S()},()=>Y(null))}function je(Z){const fe=O.current&&O.current.clientWidth||0;t(fS(e,Z,fe,Number.NaN,{snap:!0,half:!0})),S&&S()}function te(Z,fe,ve){var ae;Z.preventDefault(),Z.stopPropagation();try{Z.currentTarget.setPointerCapture&&Z.pointerId!=null&&Z.currentTarget.setPointerCapture(Z.pointerId)}catch{}const ke=P.current[fe],Ve=ke&&ke.clientHeight||O.current&&O.current.clientHeight||0,ot=O.current?O.current.getBoundingClientRect():null,rt=ot?ot.top:0,$e=ke?ke.getBoundingClientRect():null,_e=$e?$e.left-(ot?ot.left:0):0,ze=$e&&$e.width>0?$e.width:ke&&ke.clientWidth||0,Je=Number.isFinite(Z.clientY)?Z.clientY:0,He=e.columns[fe].tiles,nt=He[ve].height+(((ae=He[ve+1])==null?void 0:ae.height)||0),lt=He.reduce((Oe,gt)=>Oe+gt.height,0),X=He.slice(0,ve).reduce((Oe,gt)=>Oe+gt.height,0),I=($e&&$e.height>0?$e.top-rt:0)+Ve*(X/(lt||1)),ce=($e&&$e.height>0,Ve*(nt/(lt||1))),ye=Math.min(DC,ce/2),Re=Oe=>{const gt=(Number.isFinite(Oe.clientY)?Oe.clientY:Je)-rt;let At=Math.max(ye,Math.min(ce-ye,gt-I)),Lt=!1;if(!Oe.altKey){for(const Rt of Sc)if(Math.abs(At-Rt*ce)<=zg){At=Rt*ce,Lt=!0;break}}return{border:At,snapped:Lt,alt:Oe.altKey===!0}};Y({kind:"row",ci:fe,ri:ve,coupleTop:I,couplePx:ce,colLeft:_e,colWidth:ze,live:Re(Z),pxOther:ke&&ke.clientWidth||O.current&&O.current.clientWidth||0,fsA:He[ve].fontSize||bi,fsB:He[ve+1].fontSize||bi}),A(Oe=>Y(gt=>gt&&{...gt,live:Re(Oe)}),()=>{var At,Lt;const Oe=q.current,gt=((At=Oe==null?void 0:Oe.live)==null?void 0:At.border)??ce/2;Y(null),t(pS(e,fe,ve,Ve,gt,{snap:!((Lt=Oe==null?void 0:Oe.live)!=null&&Lt.alt)})),S&&S()},()=>Y(null))}function ie(Z,fe){const ve=P.current[Z],ke=ve&&ve.clientHeight||O.current&&O.current.clientHeight||0;t(pS(e,Z,fe,ke,Number.NaN,{snap:!0,half:!0})),S&&S()}function pe(Z){t(Fc(e,Z))}const xe={x:.45,y:.12,w:.42,h:.6},Be=8;function Te(Z){se(fe=>({...fe,z:{...fe.z,[Z]:fe.next},next:fe.next+1,focus:Z})),c&&c(Z)}function Me(Z){se(fe=>({...fe,mini:{...fe.mini,[Z]:!fe.mini[Z]}}))}function J(Z){L.length>=eu||t(IP(e,Z,xe))}function le(Z,fe){const ve=[0,1];let ke=!1,Ve=Z;for(const ot of[...ve,...fe])if(Math.abs(Z-ot)<=Be/window.innerWidth){Ve=ot,ke=!0;break}return{v:Math.max(0,Math.min(1,Ve)),snapped:ke}}function Q(Z,fe){Z.preventDefault(),Z.stopPropagation();try{Z.currentTarget.setPointerCapture&&Z.pointerId!=null&&Z.currentTarget.setPointerCapture(Z.pointerId)}catch{}const ve=Gp(e,fe);if(!ve)return;const ke=Number.isFinite(Z.clientX)?Z.clientX:0,Ve=Number.isFinite(Z.clientY)?Z.clientY:0,ot=L.filter(ze=>ze!==fe).map(ze=>Gp(e,ze)).filter(Boolean),rt=ot.flatMap(ze=>[ze.x,ze.x+ze.w]),$e=ot.flatMap(ze=>[ze.y,ze.y+ze.h]),_e=ze=>{const Je=(Number.isFinite(ze.clientX)?ze.clientX:ke)-ke,He=(Number.isFinite(ze.clientY)?ze.clientY:Ve)-Ve,nt=le(ve.x+Je/Math.max(1,window.innerWidth),rt),lt=le(ve.y+He/Math.max(1,window.innerHeight),$e);return{x:nt.v,y:lt.v,w:ve.w,h:ve.h,snappedX:nt.snapped,snappedY:lt.snapped}};B({key:fe,kind:"move",live:_e(Z)}),A(ze=>B(Je=>Je&&{...Je,live:_e(ze)}),()=>{var Je;const ze=(Je=D.current)==null?void 0:Je.live;B(null),ze&&t(mS(e,fe,ze))},()=>B(null))}function ge(Z,fe,ve){Z.preventDefault(),Z.stopPropagation();try{Z.currentTarget.setPointerCapture&&Z.pointerId!=null&&Z.currentTarget.setPointerCapture(Z.pointerId)}catch{}const ke=Gp(e,fe);if(!ke)return;const Ve=Number.isFinite(Z.clientX)?Z.clientX:0,ot=Number.isFinite(Z.clientY)?Z.clientY:0,rt=Math.max(1,window.innerWidth),$e=Math.max(1,window.innerHeight);MS(e,fe);const _e=ze=>{const Je=((Number.isFinite(ze.clientX)?ze.clientX:Ve)-Ve)/rt,He=((Number.isFinite(ze.clientY)?ze.clientY:ot)-ot)/$e;let{x:nt,y:lt,w:X,h:I}=ke;return ve.includes("e")&&(X=ke.w+Je),ve.includes("s")&&(I=ke.h+He),ve.includes("w")&&(nt=ke.x+Je,X=ke.w-Je),ve.includes("n")&&(lt=ke.y+He,I=ke.h-He),X=Math.max(.05,Math.min(1-nt,X)),I=Math.max(.05,Math.min(1-lt,I)),{x:nt,y:lt,w:X,h:I}};B({key:fe,kind:"resize",dir:ve,live:_e(Z),badge:!0}),A(ze=>B(Je=>Je&&{...Je,live:_e(ze)}),()=>{var Je;const ze=(Je=D.current)==null?void 0:Je.live;B(null),ze&&t(mS(e,fe,ze)),S&&S()},()=>B(null))}return o.jsxs("div",{className:`nc-grid${$||V?" gesturing":""}`,ref:O,onDragOver:Z=>{if(AS(Z.dataTransfer)){Z.preventDefault(),W(null);return}Vp(Z.dataTransfer)&&(Z.preventDefault(),x&&x.col===T||W({col:T}))},onDrop:re,onDragLeave:Z=>{const fe=Z.relatedTarget;(!fe||!(O.current&&O.current.contains(fe)))&&W(null)},children:[e.columns.flatMap((Z,fe)=>{const ve=[];return ve.push(o.jsx("div",{className:`nc-col${M(fe)?" drop-newcol":""}${H(Z)?" nc-col-emptyfloat":""}`,ref:ke=>{P.current[fe]=ke},style:{flexGrow:H(Z)?0:Z.width,flexBasis:0},onDragOver:ke=>{Vp(ke.dataTransfer)&&(ke.preventDefault(),ke.stopPropagation(),x&&x.col===fe&&x.row===void 0||W({col:fe}))},children:Z.tiles.flatMap((ke,Ve)=>{const ot=[],rt=Wt(ke),$e=J3(ke.node,C),_e=s3({tileKey:rt,node:ke.node,nodeGroups:C,sessionsAlive:i,localVerified:h,localIdentita:p?p.get(rt):null,lastVerifiedAt:ke.node?($e==null?void 0:$e.verifiedAt)??null:v,nowMs:R}),ze=ke.unavailable!==!0&&(ke.node?($e==null?void 0:$e.status)==="up":_e.owner==="ok"),Je=ke.unavailable!==!0&&_e.presenza!=="assente-verificata",He=Qg({session:ke.session,node:ke.node,ownerId:ke.ownerId,cells:N,nodeGroups:C}),nt=Uc({session:ke.session,cell:He,node:ke.node,ownerId:ke.ownerId,cells:N,nodeGroups:C}),lt=typeof(He==null?void 0:He.panelUrl)=="string"?He.panelUrl.trim():"",X=typeof(He==null?void 0:He.cell)=="string"?He.cell:"",I=ke.float||null,ce=!!(I&&K.mini[rt]);return ot.push(o.jsxs("div",{className:`nc-tile-slot${ee(fe,Ve)}${x&&x.from===rt?" nc-tile-source":""}${I?" nc-float":""}${ce?" nc-float-mini":""}`,style:I?{position:"fixed",left:`${I.x*100}%`,top:`${I.y*100}%`,width:`${I.w*100}%`,height:ce?"auto":`${I.h*100}%`,zIndex:20+(K.z[rt]||0)}:{flexGrow:ke.height,flexBasis:0},onPointerDown:I?()=>Te(rt):void 0,onDragOver:ye=>{if(!Vp(ye.dataTransfer))return;if(I){ye.stopPropagation();return}ye.preventDefault(),ye.stopPropagation();const Re=Q3(ye.clientX,ye.clientY,ye.currentTarget.getBoundingClientRect());x&&x.col===fe&&x.row===Ve&&x.quadrant===Re||W({col:fe,row:Ve,quadrant:Re,from:x==null?void 0:x.from,ghost:{x:ye.clientX,y:ye.clientY}})},children:[o.jsx(X3,{session:ke.session,node:ke.node,ownerId:ke.ownerId,cellName:nt,token:n,readonly:s,focused:l===rt,onFocus:c,onClose:pe,onOpenSingle:u,floating:!!I,minimized:ce,takeSize:!!I,onDetach:I?void 0:J,onReattach:I?ye=>t(PP(e,ye)):void 0,onToggleMinimize:I?Me:void 0,onFloatDragStart:I?ye=>Q(ye,rt):void 0,onDragTileStart:I?void 0:ye=>W(Re=>Re?{...Re,from:ye}:{from:ye}),available:ke.unavailable!==!0,stale:ke.stale===!0,alive:ze,sessionAlive:Je,presence:_e,fontSize:ke.fontSize,onZoom:ye=>t(FP(e,fe,Ve,ye)),decks:_,currentDeck:g,onSendToDeck:w,panelUrl:lt,panelCellId:X,panelPort:Oc(ke.node?ke.node.split("/"):[],E,j)}),!I&&x&&x.col===fe&&x.row===Ve&&x.quadrant&&o.jsx(e6,{active:x.quadrant}),I&&!ce&&["n","s","e","w","se"].map(ye=>o.jsx("div",{className:`nc-float-rz ${ye}`,"data-testid":`float-resize-${ye}`,onPointerDown:Re=>ge(Re,rt,ye)},`rz-${ye}`))]},rt)),Ve<Z.tiles.length-1&&ot.push(o.jsx("div",{className:`nc-divider-h${$&&$.kind==="row"&&$.ci===fe&&$.ri===Ve?" dragging":""}`,title:f("grid-resize-rows"),onPointerDown:ye=>te(ye,fe,Ve),onDoubleClick:()=>ie(fe,Ve)},`h${Ve}`)),ot})},`c${fe}`)),fe<T-1&&!H(Z)&&!H(e.columns[fe+1])&&ve.push(o.jsx("div",{className:`nc-divider-v${$&&$.kind==="col"&&$.ci===fe?" dragging":""}`,title:f("grid-resize-cols"),onPointerDown:ke=>oe(ke,fe),onDoubleClick:()=>je(fe)},`v${fe}`)),ve}),$&&o.jsx("div",{className:`nc-gesture-shield ${$.kind==="col"?"col":"row"}`,"data-testid":"nc-gesture-shield"}),$&&$.kind==="col"&&Sc.map(Z=>o.jsx("div",{className:"nc-gesture-ghost v",style:{left:$.coupleLeft+Z*$.couplePx}},`ghost-v-${Z}`)),$&&$.kind==="row"&&Sc.map(Z=>o.jsx("div",{className:"nc-gesture-ghost h",style:{top:$.coupleTop+Z*$.couplePx,left:$.colLeft,width:$.colWidth}},`ghost-h-${Z}`)),$&&$.kind==="col"&&o.jsx("div",{className:`nc-gesture-guide v${$.live.snapped?" snap":""}`,"data-testid":"nc-gesture-guide",style:{left:$.coupleLeft+$.live.border}}),$&&$.kind==="row"&&o.jsx("div",{className:`nc-gesture-guide h${$.live.snapped?" snap":""}`,"data-testid":"nc-gesture-guide",style:{top:$.coupleTop+$.live.border,left:$.colLeft,width:$.colWidth}}),$&&o.jsx("div",{className:"nc-gesture-badge","data-testid":"nc-gesture-badge",style:$.kind==="col"?{left:$.coupleLeft+$.live.border,top:"50%"}:{top:$.coupleTop+$.live.border,left:"50%"},children:[$.fsA,$.fsB].map((Z,fe)=>{const ve=fe===0?$.live.border:$.couplePx-$.live.border,ke=Math.max(1,Z*.6),Ve=Math.max(1,Z*1.2),ot=$.kind==="col"?`${Math.round(ve/ke)}×${Math.round($.pxOther/Ve)}`:`${Math.round($.pxOther/ke)}×${Math.round(ve/Ve)}`;return o.jsx("span",{className:"nc-gesture-chip",children:ot},fe)})}),V&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:`nc-gesture-shield ${V.kind==="resize"?"row":"col"}`,"data-testid":"nc-gesture-shield"}),V.live.snappedX&&o.jsx("div",{className:"nc-float-snap v",style:{left:`${V.live.x*100}%`}}),V.live.snappedY&&o.jsx("div",{className:"nc-float-snap h",style:{top:`${V.live.y*100}%`}}),V.kind==="resize"&&(()=>{const Z=MS(e,V.key)||bi,fe=Math.max(1,Z*.6),ve=Math.max(1,Z*1.2);return o.jsx("div",{className:"nc-gesture-badge","data-testid":"nc-gesture-badge",style:{left:`${(V.live.x+V.live.w/2)*100}%`,top:`${(V.live.y+V.live.h)*100}%`},children:o.jsx("span",{className:"nc-gesture-chip",children:`${Math.round(V.live.w*window.innerWidth/fe)}×${Math.round(V.live.h*window.innerHeight/ve)}`})})})()]}),x&&x.from&&x.ghost&&(()=>{const Z=e.columns.flatMap(ve=>ve.tiles).find(ve=>Wt(ve)===x.from),fe=Z?Uc({session:Z.session,node:Z.node,ownerId:Z.ownerId,cells:N,nodeGroups:C,cell:Qg({session:Z.session,node:Z.node,ownerId:Z.ownerId,cells:N,nodeGroups:C})}):x.from;return o.jsxs("div",{className:"nc-drag-ghost","data-testid":"nc-drag-ghost",style:{left:x.ghost.x,top:x.ghost.y},children:[o.jsxs("div",{className:"nc-drag-ghost-head",children:[o.jsx("span",{className:"nc-dot on"}),o.jsx("b",{children:fe})]}),o.jsx("div",{className:"nc-drag-ghost-body"})]})})(),U&&o.jsx("div",{className:"nc-drop-line-v nc-drop-line-end"}),T===0&&o.jsx("div",{className:"nc-grid-empty",children:f("grid-empty")})]})}const Zi="local",Xs=/^[a-f0-9]{16,64}$/,gE=3,Ha=new Map,ro=new Map,TS=128;function n6(e){const t=new Set;for(const n of Array.isArray(e)?e:[])!n||!Xs.test(String(n.instanceId||""))||!Array.isArray(n.route)||(t.add(n.instanceId),ro.set(n.instanceId,[...n.route]),Ha.set(n.instanceId,0));for(const n of[...ro.keys()]){if(t.has(n))continue;const s=(Ha.get(n)||0)+1;Ha.set(n,s),s>gE+32&&(Ha.delete(n),ro.delete(n))}if(ro.size>TS)for(const n of[...ro.keys()].slice(0,ro.size-TS))Ha.delete(n),ro.delete(n)}function Yo(e,t){return`${e&&Xs.test(e)?e:Zi}:${t}`}function su(e){const t=String(e||""),n=t.indexOf(":");if(n<1)return null;const s=t.slice(0,n),i=t.slice(n+1);return s!==Zi&&!Xs.test(s)||!/^[a-z0-9-]{1,32}$/.test(i)?null:{ownerId:s===Zi?null:s,name:i}}function Wc(e){return Array.isArray(e)&&e.length?e.join("/"):""}function c_(e){return{columns:Pi(e).columns.map(t=>({width:t.width,tiles:t.tiles.map(n=>({...n}))}))}}function s6(e){const t=new Map;for(const n of Array.isArray(e)?e:[])n&&Xs.test(String(n.instanceId||""))&&Array.isArray(n.route)&&t.set(Wc(n.route),n.instanceId);return t}function i6(e){const t=new Map;for(const n of Array.isArray(e)?e:[])n&&Xs.test(String(n.instanceId||""))&&Array.isArray(n.route)&&t.set(n.instanceId,[...n.route]);return t}function Zg(e,t,n=[]){const s=c_(e),i=s6(n);for(const l of s.columns)for(const c of l.tiles)c.ownerId||(!c.node&&Xs.test(String(t||""))?c.ownerId=t:c.node&&i.has(c.node)&&(c.ownerId=i.get(c.node)));return s}function rc(e,t){const n=su(e);return!n||!n.ownerId||!t||n.ownerId!==t?e:Yo(null,n.name)}function Ya(e,t,n=[]){const s=c_(e),i=new Map,l=new Set;for(const c of n)c&&Xs.test(String(c.instanceId||""))&&Array.isArray(c.route)&&(i.set(c.instanceId,[...c.route]),c.stale===!0&&l.add(c.instanceId));for(const c of s.columns)for(const u of c.tiles)if(u.ownerId)if(u.ownerId===t)delete u.node,delete u.unavailable,delete u.stale;else if(i.has(u.ownerId))u.node=Wc(i.get(u.ownerId)),delete u.unavailable,l.has(u.ownerId)?u.stale=!0:delete u.stale;else{const h=Ha.get(u.ownerId),p=ro.get(u.ownerId);p&&h!==void 0&&h<gE?(u.node=Wc(p),delete u.unavailable,u.stale=!0):(u.unavailable=!0,delete u.stale)}return s}function oc(e,t,n=[]){const s=c_(e),i=i6(n);for(const l of s.columns)for(const c of l.tiles)delete c.unavailable,delete c.stale,c.ownerId&&(c.ownerId===t?delete c.node:i.has(c.ownerId)&&(c.node=Wc(i.get(c.ownerId))));return s}function vE(e,t,n=[]){const s=Ar(e);if(!s)return null;if(s.ownerId)return s;if(!s.node)return{...s,...Xs.test(String(t||""))?{ownerId:t}:{}};const i=n.find(l=>Wc(l&&l.route)===s.node);return{...s,...i&&Xs.test(String(i.instanceId||""))?{ownerId:i.instanceId}:{}}}const r6=/^[a-z0-9-]{1,32}$/,oi="main",_E="nc_decks",yE="nc_deck_order_v1",bE=24;function IS(e){return typeof e!="string"?"":e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,32).replace(/-+$/,"")}function sl(e){return typeof e=="string"&&r6.test(e)}function o6(e){const t=String(e||"").match(/^\/deck\/([^/]+)\/?$/);if(t){let n;try{n=decodeURIComponent(t[1])}catch{n=t[1]}return sl(n)?n:oi}return oi}function a6(e){const t=String(e||"").match(/^\/deck\/([^/]+)\/([^/]+)\/?$/);if(t){let s,i;try{s=decodeURIComponent(t[1]),i=decodeURIComponent(t[2])}catch{return{id:Yo(null,oi),ownerId:null,name:oi}}if(Xs.test(s)&&sl(i))return{id:Yo(s,i),ownerId:s,name:i}}const n=o6(e);return{id:Yo(null,n),ownerId:null,name:n}}function Yp(e,t){const n=typeof e=="object"&&e?{ownerId:e.ownerId||null,name:e.name}:su(e)||{ownerId:null,name:e},s=sl(n.name)?n.name:oi,i=n.ownerId?`/deck/${encodeURIComponent(n.ownerId)}/${encodeURIComponent(s)}`:s===oi?"/":`/deck/${encodeURIComponent(s)}`;return t?`${i}#token=${encodeURIComponent(t)}`:i}function wE(e){return e===oi?"nc_grid_v1":`nc_grid_v1__${e}`}function SE(e){const t=[oi];if(Array.isArray(e)){for(const n of e)if(sl(n)&&n!==oi&&!t.includes(n)&&t.push(n),t.length>=bE)break}return t}function cl(){return typeof localStorage<"u"?localStorage:null}function l6(){const e=cl();if(!e)return[oi];try{return SE(JSON.parse(e.getItem(_E)||"null"))}catch{return[oi]}}function c6(e){const t=cl();if(t)try{t.setItem(_E,JSON.stringify(SE(e)))}catch{}}function iu(e){return e==="local"||Xs.test(String(e||""))}function Rh(e,t){const n=su(e);return!!n&&(n.ownerId||"local")===t}function ir(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[n,s]of Object.entries(e).slice(0,64)){if(!iu(n)||!Array.isArray(s))continue;const i=[...new Set(s.filter(l=>typeof l=="string"&&l.length<=100&&Rh(l,n)))].slice(0,bE);i.length&&(t[n]=i)}return t}function ac(e=cl()){if(!e)return{};try{return ir(JSON.parse(e.getItem(yE)||"null"))}catch{return{}}}function Xp(e,t=cl()){const n=ir(e);if(t)try{t.setItem(yE,JSON.stringify(n))}catch{}return n}function Ah(e,t){return Array.isArray(e==null?void 0:e[t])?e[t]:[]}function u6(e,t,n,s,i=[]){if(!iu(t)||n===s)return ir(e);const l=[...new Set(i.filter(_=>Rh(_,t)))];if(!l.includes(n)||!l.includes(s))return ir(e);const c=Ah(e,t).filter(_=>l.includes(_)),u=[...c,...l.filter(_=>!c.includes(_))],h=u.indexOf(n),p=u.indexOf(s);u.splice(h,1);const v=u.indexOf(s);return u.splice(h<p?v+1:v,0,n),ir({...e,[t]:u})}function d6(e,t,n,s){if(!iu(t)||!Rh(s,t))return ir(e);const i=Ah(e,t);return i.includes(n)?ir({...e,[t]:i.map(l=>l===n?s:l)}):ir(e)}function h6(e,t,n){return iu(t)?ir({...e,[t]:Ah(e,t).filter(s=>s!==n)}):ir(e)}function Jp(e,t={},n=[]){const s=new Map,i=new Map;for(const h of Array.isArray(e)?e:[]){const p=h!=null&&h.local?"local":String((h==null?void 0:h.ownerId)||"");!iu(p)||!Rh(h==null?void 0:h.id,p)||(s.has(p)||s.set(p,[]),i.has(p)||i.set(p,i.size),s.get(p).push(h))}const l=new Map;(Array.isArray(n)?n:[]).forEach((h,p)=>{typeof h=="string"&&!l.has(h)&&l.set(h,p)});const c=h=>{if(h==="local")return-1;const p=l.get(`id:${h}`);return p===void 0?Number.MAX_SAFE_INTEGER:p},u=[];for(const h of[...s.keys()].sort((p,v)=>c(p)-c(v)||i.get(p)-i.get(v))){const p=s.get(h),v=Ah(t,h),_=new Map(v.map((g,w)=>[g,w]));p.sort((g,w)=>{const S=_.has(g.id)?_.get(g.id):Number.MAX_SAFE_INTEGER,N=_.has(w.id)?_.get(w.id):Number.MAX_SAFE_INTEGER;return S-N}),u.push(...p)}return u}function ev(e){const t=cl();if(!t)return null;try{return JSON.parse(t.getItem(wE(e))||"null")}catch{return null}}function f6(e,t){const n=cl();if(n)try{n.setItem(wE(e),JSON.stringify(t))}catch{}}const u_="nc_deckbar_collapsed_v1",xE=64;function d_(e){return e===Zi||Xs.test(String(e||""))}function h_(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[s,i]of Object.entries(e)){if(n>=xE)break;if(d_(s)){if(i===!0)t[s]=!0;else if(i===!1)t[s]=!1;else continue;n+=1}}return t}function kE(e,t){return d_(t)&&Object.prototype.hasOwnProperty.call(e||{},t)?e[t]===!0:!0}function p6(e,t){const n=h_(e);return d_(t)&&(!Object.prototype.hasOwnProperty.call(n,t)&&Object.keys(n).length>=xE&&delete n[Object.keys(n)[0]],n[t]=!kE(n,t)),n}function CE(){return typeof localStorage<"u"?localStorage:null}function PS(e=CE()){if(!e)return{};try{return h_(JSON.parse(e.getItem(u_)||"null"))}catch{return{}}}function m6(e,t=CE()){const n=h_(e);if(t)try{t.setItem(u_,JSON.stringify(n))}catch{}return n}function g6(){const[e,t]=y.useState(PS);y.useEffect(()=>{const i=l=>{(l.key===u_||l.key===null)&&t(PS())};return window.addEventListener("storage",i),()=>window.removeEventListener("storage",i)},[]);const n=y.useCallback(i=>kE(e,i),[e]),s=y.useCallback(i=>{t(l=>m6(p6(l,i)))},[]);return{collapsed:e,isCollapsed:n,toggle:s}}const f_="nc_deck_presence_v1",DS=3e4,v6=18e4,EE=1e4,NE=32,_6=/^[A-Za-z0-9_-]{1,64}$/,y6=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),OS="working",b6="on",w6="neutral",S6="warn";function p_(e){return typeof e=="string"&&_6.test(e)&&!y6.has(e)}function jE(e){return typeof e=="string"&&su(e)!==null}function m_(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function il(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[s,i]of Object.entries(e)){if(n>=NE)break;p_(s)&&(!i||typeof i!="object"||jE(i.deckId)&&m_(i.ts)&&(t[s]={deckId:i.deckId,ts:i.ts,focus:i.focus===!0,visible:i.visible===!0},n+=1))}return t}function LE(e,t){const n=il(e);if(!m_(t))return n;const s={};for(const[i,l]of Object.entries(n)){const c=l.visible?DS:v6,u=t-c;l.ts>=u&&l.ts<=t+DS&&(s[i]=l)}return s}function BS(e,t,n,s){if(!p_(t)||!m_(s))return il(e);const i=LE(e,s);if(!jE(n==null?void 0:n.deckId))return i;if(!Object.prototype.hasOwnProperty.call(i,t)&&Object.keys(i).length>=NE){let l="",c=1/0;for(const[u,h]of Object.entries(i))h.ts<c&&(l=u,c=h.ts);l&&delete i[l]}return i[t]={deckId:n.deckId,ts:s,focus:(n==null?void 0:n.focus)===!0,visible:(n==null?void 0:n.visible)===!0},il(i)}function x6(e,t){const n=il(e);if(!p_(t))return n;const s={...n};return delete s[t],s}function k6(e,t){const n=LE(e,t),s={};for(const i of Object.values(n)){const l=i.focus&&i.visible?OS:b6;s[i.deckId]!==OS&&(s[i.deckId]=l)}return s}function RE(){return typeof localStorage<"u"?localStorage:null}function md(e=RE()){if(!e)return{};try{return il(JSON.parse(e.getItem(f_)||"null"))}catch{return{}}}function Qp(e,t=RE()){const n=il(e);if(t)try{t.setItem(f_,JSON.stringify(n))}catch{}return n}const C6=Math.min(EE,5e3);function E6(){var e,t;try{const n=(t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e);if(n)return`w${n.replaceAll("-","")}`}catch{}return`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,14)}`}const N6=E6();function $S(){const e=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0,t=typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState!=="hidden":!0;return{focus:e,visible:t}}function j6(e,t=!0){const s=y.useRef(N6).current,i=y.useRef(e);i.current=e;const[l,c]=y.useState(()=>({map:{},now:Date.now()})),u=y.useCallback(()=>{c({map:md(),now:Date.now()})},[]);y.useEffect(()=>{if(!t)return;const v=()=>{const C=Date.now(),j=BS(md(),s,{deckId:i.current,...$S()},C);return Qp(j),{map:j,now:C}},_=()=>c(v());_();const g=setInterval(v,EE),w=setInterval(u,C6),S=_,N=C=>{(C.key===f_||C.key===null)&&u()};return window.addEventListener("focus",S),window.addEventListener("blur",S),typeof document<"u"&&document.addEventListener("visibilitychange",S),window.addEventListener("storage",N),()=>{clearInterval(g),clearInterval(w),window.removeEventListener("focus",S),window.removeEventListener("blur",S),typeof document<"u"&&document.removeEventListener("visibilitychange",S),window.removeEventListener("storage",N);try{Qp(x6(md(),s))}catch{}}},[t,s,u]),y.useEffect(()=>{if(!t)return;const v=Date.now(),_=BS(md(),s,{deckId:e,...$S()},v);Qp(_),c({map:_,now:v})},[e,t,s]);const h=y.useMemo(()=>t?k6(l.map,l.now):{},[t,l]);return{dotFor:y.useCallback((v,_=!1)=>t?_?S6:h[v]||w6:null,[h,t]),windowId:s}}const zS=52,FS=18;function L6({ownerKey:e,deckId:t,label:n,onMove:s,onStep:i}){const l=y.useRef(null),c=y.useRef(0),[u,h]=y.useState(!1),p=()=>{var N,C,j,E;const S=l.current;(C=(N=S==null?void 0:S.over)==null?void 0:N.classList)==null||C.remove("nc-deck-over"),(E=(j=S==null?void 0:S.source)==null?void 0:j.classList)==null||E.remove("nc-deck-dragging"),c.current&&cancelAnimationFrame(c.current),c.current=0},v=(S=!1)=>{const N=l.current;if(!N)return;const C=N.target;p(),l.current=null,h(!1);try{N.handle.releasePointerCapture(N.pointerId)}catch{}S&&C&&C!==t&&s(t,C)},_=(S,N)=>{var x,W,$,Y,q,K,se,V;const C=l.current;if(!C)return;C.x=S,C.y=N;const j=(W=(x=document.elementFromPoint(S,N))==null?void 0:x.closest)==null?void 0:W.call(x,"[data-deck-id][data-owner-key]"),E=($=j==null?void 0:j.dataset)==null?void 0:$.deckId,R=((Y=j==null?void 0:j.dataset)==null?void 0:Y.ownerKey)===e&&E&&E!==t;C.over!==(R?j:null)&&((K=(q=C.over)==null?void 0:q.classList)==null||K.remove("nc-deck-over"),C.over=R?j:null,(V=(se=C.over)==null?void 0:se.classList)==null||V.add("nc-deck-over")),C.target=R?E:null},g=()=>{var C,j;const S=l.current;if(!S){c.current=0;return}const N=(j=(C=S.container)==null?void 0:C.getBoundingClientRect)==null?void 0:j.call(C);if(N){const E=S.x<N.left+zS?-FS:S.x>N.right-zS?FS:0;E&&(S.container.scrollLeft+=E,_(S.x,S.y))}c.current=requestAnimationFrame(g)};y.useEffect(()=>{const S=C=>{C.key==="Escape"&&l.current&&(C.preventDefault(),v(!1))},N=()=>v(!1);return window.addEventListener("keydown",S),window.addEventListener("blur",N),()=>{window.removeEventListener("keydown",S),window.removeEventListener("blur",N),p(),l.current=null}},[t,e]);const w=S=>{var j;if(S.pointerType==="mouse"&&S.button!==0)return;S.preventDefault(),S.stopPropagation(),S.currentTarget.focus({preventScroll:!0});const N=S.currentTarget.closest("[data-deck-id][data-owner-key]"),C=S.currentTarget.closest(".nc-deckbar");l.current={pointerId:S.pointerId,handle:S.currentTarget,source:N,container:C,target:null,over:null,x:S.clientX,y:S.clientY},(j=N==null?void 0:N.classList)==null||j.add("nc-deck-dragging");try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}h(!0),c.current=requestAnimationFrame(g)};return o.jsx("button",{type:"button",className:`nc-deck-handle${u?" active":""}`,"aria-label":`${f("reorder")} ${n}`,"aria-keyshortcuts":"ArrowLeft ArrowRight",title:f("reorder-deck-help"),onClick:S=>{S.preventDefault(),S.stopPropagation()},onDragStart:S=>S.preventDefault(),onKeyDown:S=>{S.key!=="ArrowLeft"&&S.key!=="ArrowRight"||(S.preventDefault(),S.stopPropagation(),i(S.key==="ArrowLeft"?-1:1))},onPointerDown:w,onPointerMove:S=>{!l.current||S.pointerId!==l.current.pointerId||(S.preventDefault(),S.stopPropagation(),_(S.clientX,S.clientY))},onPointerUp:S=>{!l.current||S.pointerId!==l.current.pointerId||(S.preventDefault(),S.stopPropagation(),v(!0))},onPointerCancel:()=>v(!1),onLostPointerCapture:()=>{l.current&&v(!1)},children:"↔"})}function R6({decks:e=[],currentDeck:t="local:main",onCreate:n,onRename:s,onDelete:i,onReorder:l,onOpenWindow:c,onNavigate:u,saveState:h="idle",error:p="",sidebarVisible:v,onToggleSidebar:_,conflict:g=!1,onReloadDeck:w=null}){Fn();const{isCollapsed:S,toggle:N}=g6(),{dotFor:C}=j6(t),[j,E]=y.useState(null),[R,x]=y.useState(""),[W,$]=y.useState(!1),[Y,q]=y.useState(""),[K,se]=y.useState(""),V=IS(R),B=sl(V),D=[];for(const T of e){const L=T.local?"local":T.ownerId;let H=D.find(M=>M.key===L);H||(H={key:L,label:T.ownerLabel||(T.local?"Local":L),local:!!T.local,decks:[]},D.push(H)),H.decks.push(T)}const O=async()=>{if(B){$(!0),q("");try{n&&await n(V,j),x(""),E(null)}catch(T){q(String(T.message||T))}$(!1)}},P=T=>{se(""),c&&c(T.id)||se(T.id)},z=async T=>{if(!(T.id===t||!u||W||T.available===!1)){$(!0),q("");try{await u(T.id)}catch(L){q(String((L==null?void 0:L.message)||L))}$(!1)}},A=(T,L,H)=>{const M=T.decks.findIndex(ee=>ee.id===L.id),U=T.decks[M+H];M>=0&&U&&l&&!W&&l(L.id,U.id)};return o.jsxs("div",{className:"nc-deckbar",children:[_&&o.jsx("button",{className:"nc-deck-sidebar-toggle",title:f("toggle-sidebar"),onClick:_,children:v?"◀":"☰"}),o.jsx("span",{className:"nc-deckbar-label",children:f("decks")}),o.jsx("div",{className:"nc-deck-chips",children:D.map(T=>{const L=S(T.key),H=`nc-deck-content-${T.key}`,M=T.local?"Local":T.label,U=T.decks.some(oe=>oe.id===t),ee=(T.decks.find(oe=>oe.id===t)||{}).name,re=f(T.decks.length===1?"owner-deck-count-one":"owner-deck-count-many").replace("{count}",T.decks.length);return o.jsxs("span",{className:`nc-deck-owner-group${L?" collapsed":""}`,"data-owner-key":T.key,"data-collapsed":L?"1":"0",children:[o.jsxs("button",{type:"button",className:"nc-deck-owner-toggle","aria-expanded":!L,"aria-controls":H,title:f(L?"expand-owner":"collapse-owner").replace("{owner}",M),onClick:()=>{!L&&j===T.key&&(x(""),E(null)),N(T.key)},children:[o.jsx("span",{className:"nc-deck-owner-caret","aria-hidden":"true",children:L?"▸":"▾"}),o.jsx("span",{className:"nc-deck-owner",children:M})]}),L&&o.jsxs("span",{className:"nc-deck-summary",title:re,children:[o.jsx("span",{className:"nc-deck-summary-count",children:T.decks.length}),U&&o.jsxs("span",{className:"nc-deck-summary-current",children:["• ",ee]})]}),o.jsxs("span",{id:H,className:"nc-deck-owner-content",hidden:L,children:[T.decks.map(oe=>{const je=C(oe.id,oe.available===!1);return o.jsxs("span",{"data-deck-id":oe.id,"data-owner-key":T.key,className:`nc-deck-chip${oe.id===t?" current":""}${oe.available===!1?" offline":""}`,children:[je&&o.jsx(A6,{state:je}),o.jsx(L6,{ownerKey:T.key,deckId:oe.id,label:`${T.label} · ${oe.name}`,onMove:(te,ie)=>{l&&!W&&l(te,ie)},onStep:te=>A(T,oe,te)}),o.jsxs("button",{className:"nc-deck-open",title:oe.available===!1?`${oe.ownerLabel} offline${oe.refreshFailedAt?" · aggiornamento in ritardo":""}`:oe.id===t?f("deck-current"):`${oe.ownerLabel} · ${oe.name}`,disabled:W||oe.available===!1,onClick:()=>z(oe),children:[oe.name,oe.id===t?" •":""]}),oe.available!==!1&&oe.stale===!0&&oe.refreshFailedAt?o.jsx("span",{className:"nc-deck-stale",title:`${oe.ownerLabel} · ${f("deck-stale")}`,children:f("deck-stale-badge")}):null,o.jsx("button",{className:"nc-deck-mini",disabled:oe.available===!1,title:f("detach-deck"),onClick:()=>P(oe),children:"↗"}),oe.name!==oi&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"nc-deck-mini",disabled:oe.available===!1,title:f("rename-deck"),onClick:()=>{const te=(typeof window<"u"?window.prompt(f("rename-deck"),oe.name):"")||"",ie=IS(te);sl(ie)&&ie!==oe.name&&s&&s(oe.id,ie).catch(pe=>q(String(pe.message||pe)))},children:"✎"}),o.jsx("button",{className:"nc-deck-mini nc-deck-del",disabled:oe.available===!1,title:f("delete-deck"),onClick:()=>{(typeof window>"u"||window.confirm(f("delete-deck-confirm").replace("{name}",`${oe.ownerLabel} · ${oe.name}`)))&&i&&i(oe.id).catch(te=>q(String(te.message||te)))},children:"✕"})]})]},oe.id)}),j===T.key?o.jsxs("span",{className:"nc-deck-add",children:[o.jsx("input",{autoFocus:!0,className:B||!R?"":"invalid",placeholder:f("deck-name"),value:R,onChange:oe=>x(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"&&O(),oe.key==="Escape"&&(x(""),E(null))}}),R&&B&&V!==R&&o.jsxs("span",{className:"nc-deck-slug",children:["→ ",V]}),o.jsx("button",{className:"nc-deck-ok",disabled:!B||W,onClick:O,children:f("create")}),o.jsx("button",{className:"nc-deck-cancel",onClick:()=>{x(""),E(null)},children:f("cancel")})]}):o.jsxs("button",{className:"nc-deck-newbtn",disabled:W||T.decks.every(oe=>oe.available===!1),title:`${f("new-deck")} · ${T.label}`,onClick:()=>{x(""),E(T.key)},children:["+ ",f("new")]})]})]},T.key)})}),o.jsx("span",{className:`nc-deck-state ${h}`,title:f("deck-autosave"),children:f(h==="saving"?"saving":h==="saved"?"saved":"deck-autosave")}),(Y||p)&&o.jsx("span",{className:"nc-deck-error",children:Y||p}),g&&w&&o.jsx("button",{className:"nc-deck-reload",onClick:w,children:f("reload")}),K&&o.jsx("button",{className:"nc-deck-fallback",onClick:()=>c&&c(K),children:f("popup-blocked")})]})}function A6({state:e}){if(!e)return null;const t=f(`dot-${e}`);return o.jsx("span",{className:`nc-deck-dot ${e}`,role:"img","aria-label":t,title:t})}var za={},Zp,HS;function M6(){return HS||(HS=1,Zp=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Zp}var em={},eo={},US;function sa(){if(US)return eo;US=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return eo.getSymbolSize=function(s){if(!s)throw new Error('"version" cannot be null or undefined');if(s<1||s>40)throw new Error('"version" should be in range from 1 to 40');return s*4+17},eo.getSymbolTotalCodewords=function(s){return t[s]},eo.getBCHDigit=function(n){let s=0;for(;n!==0;)s++,n>>>=1;return s},eo.setToSJISFunction=function(s){if(typeof s!="function")throw new Error('"toSJISFunc" is not a valid function.');e=s},eo.isKanjiModeEnabled=function(){return typeof e<"u"},eo.toSJIS=function(s){return e(s)},eo}var tm={},WS;function g_(){return WS||(WS=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(s){return s&&typeof s.bit<"u"&&s.bit>=0&&s.bit<4},e.from=function(s,i){if(e.isValid(s))return s;try{return t(s)}catch{return i}}})(tm)),tm}var nm,qS;function T6(){if(qS)return nm;qS=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const n=Math.floor(t/8);return(this.buffer[n]>>>7-t%8&1)===1},put:function(t,n){for(let s=0;s<n;s++)this.putBit((t>>>n-s-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),t&&(this.buffer[n]|=128>>>this.length%8),this.length++}},nm=e,nm}var sm,KS;function I6(){if(KS)return sm;KS=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,n,s,i){const l=t*this.size+n;this.data[l]=s,i&&(this.reservedBit[l]=!0)},e.prototype.get=function(t,n){return this.data[t*this.size+n]},e.prototype.xor=function(t,n,s){this.data[t*this.size+n]^=s},e.prototype.isReserved=function(t,n){return this.reservedBit[t*this.size+n]},sm=e,sm}var im={},VS;function P6(){return VS||(VS=1,(function(e){const t=sa().getSymbolSize;e.getRowColCoords=function(s){if(s===1)return[];const i=Math.floor(s/7)+2,l=t(s),c=l===145?26:Math.ceil((l-13)/(2*i-2))*2,u=[l-7];for(let h=1;h<i-1;h++)u[h]=u[h-1]-c;return u.push(6),u.reverse()},e.getPositions=function(s){const i=[],l=e.getRowColCoords(s),c=l.length;for(let u=0;u<c;u++)for(let h=0;h<c;h++)u===0&&h===0||u===0&&h===c-1||u===c-1&&h===0||i.push([l[u],l[h]]);return i}})(im)),im}var rm={},GS;function D6(){if(GS)return rm;GS=1;const e=sa().getSymbolSize,t=7;return rm.getPositions=function(s){const i=e(s);return[[0,0],[i-t,0],[0,i-t]]},rm}var om={},YS;function O6(){return YS||(YS=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const l=i.size;let c=0,u=0,h=0,p=null,v=null;for(let _=0;_<l;_++){u=h=0,p=v=null;for(let g=0;g<l;g++){let w=i.get(_,g);w===p?u++:(u>=5&&(c+=t.N1+(u-5)),p=w,u=1),w=i.get(g,_),w===v?h++:(h>=5&&(c+=t.N1+(h-5)),v=w,h=1)}u>=5&&(c+=t.N1+(u-5)),h>=5&&(c+=t.N1+(h-5))}return c},e.getPenaltyN2=function(i){const l=i.size;let c=0;for(let u=0;u<l-1;u++)for(let h=0;h<l-1;h++){const p=i.get(u,h)+i.get(u,h+1)+i.get(u+1,h)+i.get(u+1,h+1);(p===4||p===0)&&c++}return c*t.N2},e.getPenaltyN3=function(i){const l=i.size;let c=0,u=0,h=0;for(let p=0;p<l;p++){u=h=0;for(let v=0;v<l;v++)u=u<<1&2047|i.get(p,v),v>=10&&(u===1488||u===93)&&c++,h=h<<1&2047|i.get(v,p),v>=10&&(h===1488||h===93)&&c++}return c*t.N3},e.getPenaltyN4=function(i){let l=0;const c=i.data.length;for(let h=0;h<c;h++)l+=i.data[h];return Math.abs(Math.ceil(l*100/c/5)-10)*t.N4};function n(s,i,l){switch(s){case e.Patterns.PATTERN000:return(i+l)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return l%3===0;case e.Patterns.PATTERN011:return(i+l)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(l/3))%2===0;case e.Patterns.PATTERN101:return i*l%2+i*l%3===0;case e.Patterns.PATTERN110:return(i*l%2+i*l%3)%2===0;case e.Patterns.PATTERN111:return(i*l%3+(i+l)%2)%2===0;default:throw new Error("bad maskPattern:"+s)}}e.applyMask=function(i,l){const c=l.size;for(let u=0;u<c;u++)for(let h=0;h<c;h++)l.isReserved(h,u)||l.xor(h,u,n(i,h,u))},e.getBestMask=function(i,l){const c=Object.keys(e.Patterns).length;let u=0,h=1/0;for(let p=0;p<c;p++){l(p),e.applyMask(p,i);const v=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(p,i),v<h&&(h=v,u=p)}return u}})(om)),om}var gd={},XS;function AE(){if(XS)return gd;XS=1;const e=g_(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return gd.getBlocksCount=function(i,l){switch(l){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},gd.getTotalCodewordsCount=function(i,l){switch(l){case e.L:return n[(i-1)*4+0];case e.M:return n[(i-1)*4+1];case e.Q:return n[(i-1)*4+2];case e.H:return n[(i-1)*4+3];default:return}},gd}var am={},lc={},JS;function B6(){if(JS)return lc;JS=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let s=1;for(let i=0;i<255;i++)e[i]=s,t[s]=i,s<<=1,s&256&&(s^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),lc.log=function(s){if(s<1)throw new Error("log("+s+")");return t[s]},lc.exp=function(s){return e[s]},lc.mul=function(s,i){return s===0||i===0?0:e[t[s]+t[i]]},lc}var QS;function $6(){return QS||(QS=1,(function(e){const t=B6();e.mul=function(s,i){const l=new Uint8Array(s.length+i.length-1);for(let c=0;c<s.length;c++)for(let u=0;u<i.length;u++)l[c+u]^=t.mul(s[c],i[u]);return l},e.mod=function(s,i){let l=new Uint8Array(s);for(;l.length-i.length>=0;){const c=l[0];for(let h=0;h<i.length;h++)l[h]^=t.mul(i[h],c);let u=0;for(;u<l.length&&l[u]===0;)u++;l=l.slice(u)}return l},e.generateECPolynomial=function(s){let i=new Uint8Array([1]);for(let l=0;l<s;l++)i=e.mul(i,new Uint8Array([1,t.exp(l)]));return i}})(am)),am}var lm,ZS;function z6(){if(ZS)return lm;ZS=1;const e=$6();function t(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(s){this.degree=s,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(s){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(s.length+this.degree);i.set(s);const l=e.mod(i,this.genPoly),c=this.degree-l.length;if(c>0){const u=new Uint8Array(this.degree);return u.set(l,c),u}return l},lm=t,lm}var cm={},um={},dm={},ex;function ME(){return ex||(ex=1,dm.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),dm}var Gi={},tx;function TE(){if(tx)return Gi;tx=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const s="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
158
+ ]))+`;Gi.KANJI=new RegExp(n,"g"),Gi.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Gi.BYTE=new RegExp(s,"g"),Gi.NUMERIC=new RegExp(e,"g"),Gi.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+n+"$"),l=new RegExp("^"+e+"$"),c=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Gi.testKanji=function(h){return i.test(h)},Gi.testNumeric=function(h){return l.test(h)},Gi.testAlphanumeric=function(h){return c.test(h)},Gi}var nx;function ia(){return nx||(nx=1,(function(e){const t=ME(),n=TE();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(l,c){if(!l.ccBits)throw new Error("Invalid mode: "+l);if(!t.isValid(c))throw new Error("Invalid version: "+c);return c>=1&&c<10?l.ccBits[0]:c<27?l.ccBits[1]:l.ccBits[2]},e.getBestModeForData=function(l){return n.testNumeric(l)?e.NUMERIC:n.testAlphanumeric(l)?e.ALPHANUMERIC:n.testKanji(l)?e.KANJI:e.BYTE},e.toString=function(l){if(l&&l.id)return l.id;throw new Error("Invalid mode")},e.isValid=function(l){return l&&l.bit&&l.ccBits};function s(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(l,c){if(e.isValid(l))return l;try{return s(l)}catch{return c}}})(um)),um}var sx;function F6(){return sx||(sx=1,(function(e){const t=sa(),n=AE(),s=g_(),i=ia(),l=ME(),c=7973,u=t.getBCHDigit(c);function h(g,w,S){for(let N=1;N<=40;N++)if(w<=e.getCapacity(N,S,g))return N}function p(g,w){return i.getCharCountIndicator(g,w)+4}function v(g,w){let S=0;return g.forEach(function(N){const C=p(N.mode,w);S+=C+N.getBitsLength()}),S}function _(g,w){for(let S=1;S<=40;S++)if(v(g,S)<=e.getCapacity(S,w,i.MIXED))return S}e.from=function(w,S){return l.isValid(w)?parseInt(w,10):S},e.getCapacity=function(w,S,N){if(!l.isValid(w))throw new Error("Invalid QR Code version");typeof N>"u"&&(N=i.BYTE);const C=t.getSymbolTotalCodewords(w),j=n.getTotalCodewordsCount(w,S),E=(C-j)*8;if(N===i.MIXED)return E;const R=E-p(N,w);switch(N){case i.NUMERIC:return Math.floor(R/10*3);case i.ALPHANUMERIC:return Math.floor(R/11*2);case i.KANJI:return Math.floor(R/13);case i.BYTE:default:return Math.floor(R/8)}},e.getBestVersionForData=function(w,S){let N;const C=s.from(S,s.M);if(Array.isArray(w)){if(w.length>1)return _(w,C);if(w.length===0)return 1;N=w[0]}else N=w;return h(N.mode,N.getLength(),C)},e.getEncodedBits=function(w){if(!l.isValid(w)||w<7)throw new Error("Invalid QR Code version");let S=w<<12;for(;t.getBCHDigit(S)-u>=0;)S^=c<<t.getBCHDigit(S)-u;return w<<12|S}})(cm)),cm}var hm={},ix;function H6(){if(ix)return hm;ix=1;const e=sa(),t=1335,n=21522,s=e.getBCHDigit(t);return hm.getEncodedBits=function(l,c){const u=l.bit<<3|c;let h=u<<10;for(;e.getBCHDigit(h)-s>=0;)h^=t<<e.getBCHDigit(h)-s;return(u<<10|h)^n},hm}var fm={},pm,rx;function U6(){if(rx)return pm;rx=1;const e=ia();function t(n){this.mode=e.NUMERIC,this.data=n.toString()}return t.getBitsLength=function(s){return 10*Math.floor(s/3)+(s%3?s%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(s){let i,l,c;for(i=0;i+3<=this.data.length;i+=3)l=this.data.substr(i,3),c=parseInt(l,10),s.put(c,10);const u=this.data.length-i;u>0&&(l=this.data.substr(i),c=parseInt(l,10),s.put(c,u*3+1))},pm=t,pm}var mm,ox;function W6(){if(ox)return mm;ox=1;const e=ia(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(s){this.mode=e.ALPHANUMERIC,this.data=s}return n.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(i){let l;for(l=0;l+2<=this.data.length;l+=2){let c=t.indexOf(this.data[l])*45;c+=t.indexOf(this.data[l+1]),i.put(c,11)}this.data.length%2&&i.put(t.indexOf(this.data[l]),6)},mm=n,mm}var gm,ax;function q6(){if(ax)return gm;ax=1;const e=ia();function t(n){this.mode=e.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return t.getBitsLength=function(s){return s*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){for(let s=0,i=this.data.length;s<i;s++)n.put(this.data[s],8)},gm=t,gm}var vm,lx;function K6(){if(lx)return vm;lx=1;const e=ia(),t=sa();function n(s){this.mode=e.KANJI,this.data=s}return n.getBitsLength=function(i){return i*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(s){let i;for(i=0;i<this.data.length;i++){let l=t.toSJIS(this.data[i]);if(l>=33088&&l<=40956)l-=33088;else if(l>=57408&&l<=60351)l-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
159
+ Make sure your charset is UTF-8`);l=(l>>>8&255)*192+(l&255),s.put(l,13)}},vm=n,vm}var _m={exports:{}},cx;function V6(){return cx||(cx=1,(function(e){var t={single_source_shortest_paths:function(n,s,i){var l={},c={};c[s]=0;var u=t.PriorityQueue.make();u.push(s,0);for(var h,p,v,_,g,w,S,N,C;!u.empty();){h=u.pop(),p=h.value,_=h.cost,g=n[p]||{};for(v in g)g.hasOwnProperty(v)&&(w=g[v],S=_+w,N=c[v],C=typeof c[v]>"u",(C||N>S)&&(c[v]=S,u.push(v,S),l[v]=p))}if(typeof i<"u"&&typeof c[i]>"u"){var j=["Could not find a path from ",s," to ",i,"."].join("");throw new Error(j)}return l},extract_shortest_path_from_predecessor_list:function(n,s){for(var i=[],l=s;l;)i.push(l),n[l],l=n[l];return i.reverse(),i},find_path:function(n,s,i){var l=t.single_source_shortest_paths(n,s,i);return t.extract_shortest_path_from_predecessor_list(l,i)},PriorityQueue:{make:function(n){var s=t.PriorityQueue,i={},l;n=n||{};for(l in s)s.hasOwnProperty(l)&&(i[l]=s[l]);return i.queue=[],i.sorter=n.sorter||s.default_sorter,i},default_sorter:function(n,s){return n.cost-s.cost},push:function(n,s){var i={value:n,cost:s};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(_m)),_m.exports}var ux;function G6(){return ux||(ux=1,(function(e){const t=ia(),n=U6(),s=W6(),i=q6(),l=K6(),c=TE(),u=sa(),h=V6();function p(j){return unescape(encodeURIComponent(j)).length}function v(j,E,R){const x=[];let W;for(;(W=j.exec(R))!==null;)x.push({data:W[0],index:W.index,mode:E,length:W[0].length});return x}function _(j){const E=v(c.NUMERIC,t.NUMERIC,j),R=v(c.ALPHANUMERIC,t.ALPHANUMERIC,j);let x,W;return u.isKanjiModeEnabled()?(x=v(c.BYTE,t.BYTE,j),W=v(c.KANJI,t.KANJI,j)):(x=v(c.BYTE_KANJI,t.BYTE,j),W=[]),E.concat(R,x,W).sort(function(Y,q){return Y.index-q.index}).map(function(Y){return{data:Y.data,mode:Y.mode,length:Y.length}})}function g(j,E){switch(E){case t.NUMERIC:return n.getBitsLength(j);case t.ALPHANUMERIC:return s.getBitsLength(j);case t.KANJI:return l.getBitsLength(j);case t.BYTE:return i.getBitsLength(j)}}function w(j){return j.reduce(function(E,R){const x=E.length-1>=0?E[E.length-1]:null;return x&&x.mode===R.mode?(E[E.length-1].data+=R.data,E):(E.push(R),E)},[])}function S(j){const E=[];for(let R=0;R<j.length;R++){const x=j[R];switch(x.mode){case t.NUMERIC:E.push([x,{data:x.data,mode:t.ALPHANUMERIC,length:x.length},{data:x.data,mode:t.BYTE,length:x.length}]);break;case t.ALPHANUMERIC:E.push([x,{data:x.data,mode:t.BYTE,length:x.length}]);break;case t.KANJI:E.push([x,{data:x.data,mode:t.BYTE,length:p(x.data)}]);break;case t.BYTE:E.push([{data:x.data,mode:t.BYTE,length:p(x.data)}])}}return E}function N(j,E){const R={},x={start:{}};let W=["start"];for(let $=0;$<j.length;$++){const Y=j[$],q=[];for(let K=0;K<Y.length;K++){const se=Y[K],V=""+$+K;q.push(V),R[V]={node:se,lastCount:0},x[V]={};for(let B=0;B<W.length;B++){const D=W[B];R[D]&&R[D].node.mode===se.mode?(x[D][V]=g(R[D].lastCount+se.length,se.mode)-g(R[D].lastCount,se.mode),R[D].lastCount+=se.length):(R[D]&&(R[D].lastCount=se.length),x[D][V]=g(se.length,se.mode)+4+t.getCharCountIndicator(se.mode,E))}}W=q}for(let $=0;$<W.length;$++)x[W[$]].end=0;return{map:x,table:R}}function C(j,E){let R;const x=t.getBestModeForData(j);if(R=t.from(E,x),R!==t.BYTE&&R.bit<x.bit)throw new Error('"'+j+'" cannot be encoded with mode '+t.toString(R)+`.
160
+ Suggested mode is: `+t.toString(x));switch(R===t.KANJI&&!u.isKanjiModeEnabled()&&(R=t.BYTE),R){case t.NUMERIC:return new n(j);case t.ALPHANUMERIC:return new s(j);case t.KANJI:return new l(j);case t.BYTE:return new i(j)}}e.fromArray=function(E){return E.reduce(function(R,x){return typeof x=="string"?R.push(C(x,null)):x.data&&R.push(C(x.data,x.mode)),R},[])},e.fromString=function(E,R){const x=_(E,u.isKanjiModeEnabled()),W=S(x),$=N(W,R),Y=h.find_path($.map,"start","end"),q=[];for(let K=1;K<Y.length-1;K++)q.push($.table[Y[K]].node);return e.fromArray(w(q))},e.rawSplit=function(E){return e.fromArray(_(E,u.isKanjiModeEnabled()))}})(fm)),fm}var dx;function Y6(){if(dx)return em;dx=1;const e=sa(),t=g_(),n=T6(),s=I6(),i=P6(),l=D6(),c=O6(),u=AE(),h=z6(),p=F6(),v=H6(),_=ia(),g=G6();function w($,Y){const q=$.size,K=l.getPositions(Y);for(let se=0;se<K.length;se++){const V=K[se][0],B=K[se][1];for(let D=-1;D<=7;D++)if(!(V+D<=-1||q<=V+D))for(let O=-1;O<=7;O++)B+O<=-1||q<=B+O||(D>=0&&D<=6&&(O===0||O===6)||O>=0&&O<=6&&(D===0||D===6)||D>=2&&D<=4&&O>=2&&O<=4?$.set(V+D,B+O,!0,!0):$.set(V+D,B+O,!1,!0))}}function S($){const Y=$.size;for(let q=8;q<Y-8;q++){const K=q%2===0;$.set(q,6,K,!0),$.set(6,q,K,!0)}}function N($,Y){const q=i.getPositions(Y);for(let K=0;K<q.length;K++){const se=q[K][0],V=q[K][1];for(let B=-2;B<=2;B++)for(let D=-2;D<=2;D++)B===-2||B===2||D===-2||D===2||B===0&&D===0?$.set(se+B,V+D,!0,!0):$.set(se+B,V+D,!1,!0)}}function C($,Y){const q=$.size,K=p.getEncodedBits(Y);let se,V,B;for(let D=0;D<18;D++)se=Math.floor(D/3),V=D%3+q-8-3,B=(K>>D&1)===1,$.set(se,V,B,!0),$.set(V,se,B,!0)}function j($,Y,q){const K=$.size,se=v.getEncodedBits(Y,q);let V,B;for(V=0;V<15;V++)B=(se>>V&1)===1,V<6?$.set(V,8,B,!0):V<8?$.set(V+1,8,B,!0):$.set(K-15+V,8,B,!0),V<8?$.set(8,K-V-1,B,!0):V<9?$.set(8,15-V-1+1,B,!0):$.set(8,15-V-1,B,!0);$.set(K-8,8,1,!0)}function E($,Y){const q=$.size;let K=-1,se=q-1,V=7,B=0;for(let D=q-1;D>0;D-=2)for(D===6&&D--;;){for(let O=0;O<2;O++)if(!$.isReserved(se,D-O)){let P=!1;B<Y.length&&(P=(Y[B]>>>V&1)===1),$.set(se,D-O,P),V--,V===-1&&(B++,V=7)}if(se+=K,se<0||q<=se){se-=K,K=-K;break}}}function R($,Y,q){const K=new n;q.forEach(function(O){K.put(O.mode.bit,4),K.put(O.getLength(),_.getCharCountIndicator(O.mode,$)),O.write(K)});const se=e.getSymbolTotalCodewords($),V=u.getTotalCodewordsCount($,Y),B=(se-V)*8;for(K.getLengthInBits()+4<=B&&K.put(0,4);K.getLengthInBits()%8!==0;)K.putBit(0);const D=(B-K.getLengthInBits())/8;for(let O=0;O<D;O++)K.put(O%2?17:236,8);return x(K,$,Y)}function x($,Y,q){const K=e.getSymbolTotalCodewords(Y),se=u.getTotalCodewordsCount(Y,q),V=K-se,B=u.getBlocksCount(Y,q),D=K%B,O=B-D,P=Math.floor(K/B),z=Math.floor(V/B),A=z+1,T=P-z,L=new h(T);let H=0;const M=new Array(B),U=new Array(B);let ee=0;const re=new Uint8Array($.buffer);for(let pe=0;pe<B;pe++){const xe=pe<O?z:A;M[pe]=re.slice(H,H+xe),U[pe]=L.encode(M[pe]),H+=xe,ee=Math.max(ee,xe)}const oe=new Uint8Array(K);let je=0,te,ie;for(te=0;te<ee;te++)for(ie=0;ie<B;ie++)te<M[ie].length&&(oe[je++]=M[ie][te]);for(te=0;te<T;te++)for(ie=0;ie<B;ie++)oe[je++]=U[ie][te];return oe}function W($,Y,q,K){let se;if(Array.isArray($))se=g.fromArray($);else if(typeof $=="string"){let P=Y;if(!P){const z=g.rawSplit($);P=p.getBestVersionForData(z,q)}se=g.fromString($,P||40)}else throw new Error("Invalid data");const V=p.getBestVersionForData(se,q);if(!V)throw new Error("The amount of data is too big to be stored in a QR Code");if(!Y)Y=V;else if(Y<V)throw new Error(`
161
+ The chosen QR Code version cannot contain this amount of data.
162
+ Minimum version required to store current data is: `+V+`.
163
+ `);const B=R(Y,q,se),D=e.getSymbolSize(Y),O=new s(D);return w(O,Y),S(O),N(O,Y),j(O,q,0),Y>=7&&C(O,Y),E(O,B),isNaN(K)&&(K=c.getBestMask(O,j.bind(null,O,q))),c.applyMask(K,O),j(O,q,K),{modules:O,version:Y,errorCorrectionLevel:q,maskPattern:K,segments:se}}return em.create=function(Y,q){if(typeof Y>"u"||Y==="")throw new Error("No input text");let K=t.M,se,V;return typeof q<"u"&&(K=t.from(q.errorCorrectionLevel,t.M),se=p.from(q.version),V=c.from(q.maskPattern),q.toSJISFunc&&e.setToSJISFunction(q.toSJISFunc)),W(Y,se,K,V)},em}var ym={},bm={},hx;function IE(){return hx||(hx=1,(function(e){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let s=n.slice().replace("#","").split("");if(s.length<3||s.length===5||s.length>8)throw new Error("Invalid hex color: "+n);(s.length===3||s.length===4)&&(s=Array.prototype.concat.apply([],s.map(function(l){return[l,l]}))),s.length===6&&s.push("F","F");const i=parseInt(s.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+s.slice(0,6).join("")}}e.getOptions=function(s){s||(s={}),s.color||(s.color={});const i=typeof s.margin>"u"||s.margin===null||s.margin<0?4:s.margin,l=s.width&&s.width>=21?s.width:void 0,c=s.scale||4;return{width:l,scale:l?4:c,margin:i,color:{dark:t(s.color.dark||"#000000ff"),light:t(s.color.light||"#ffffffff")},type:s.type,rendererOpts:s.rendererOpts||{}}},e.getScale=function(s,i){return i.width&&i.width>=s+i.margin*2?i.width/(s+i.margin*2):i.scale},e.getImageWidth=function(s,i){const l=e.getScale(s,i);return Math.floor((s+i.margin*2)*l)},e.qrToImageData=function(s,i,l){const c=i.modules.size,u=i.modules.data,h=e.getScale(c,l),p=Math.floor((c+l.margin*2)*h),v=l.margin*h,_=[l.color.light,l.color.dark];for(let g=0;g<p;g++)for(let w=0;w<p;w++){let S=(g*p+w)*4,N=l.color.light;if(g>=v&&w>=v&&g<p-v&&w<p-v){const C=Math.floor((g-v)/h),j=Math.floor((w-v)/h);N=_[u[C*c+j]?1:0]}s[S++]=N.r,s[S++]=N.g,s[S++]=N.b,s[S]=N.a}}})(bm)),bm}var fx;function X6(){return fx||(fx=1,(function(e){const t=IE();function n(i,l,c){i.clearRect(0,0,l.width,l.height),l.style||(l.style={}),l.height=c,l.width=c,l.style.height=c+"px",l.style.width=c+"px"}function s(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(l,c,u){let h=u,p=c;typeof h>"u"&&(!c||!c.getContext)&&(h=c,c=void 0),c||(p=s()),h=t.getOptions(h);const v=t.getImageWidth(l.modules.size,h),_=p.getContext("2d"),g=_.createImageData(v,v);return t.qrToImageData(g.data,l,h),n(_,p,v),_.putImageData(g,0,0),p},e.renderToDataURL=function(l,c,u){let h=u;typeof h>"u"&&(!c||!c.getContext)&&(h=c,c=void 0),h||(h={});const p=e.render(l,c,h),v=h.type||"image/png",_=h.rendererOpts||{};return p.toDataURL(v,_.quality)}})(ym)),ym}var wm={},px;function J6(){if(px)return wm;px=1;const e=IE();function t(i,l){const c=i.a/255,u=l+'="'+i.hex+'"';return c<1?u+" "+l+'-opacity="'+c.toFixed(2).slice(1)+'"':u}function n(i,l,c){let u=i+l;return typeof c<"u"&&(u+=" "+c),u}function s(i,l,c){let u="",h=0,p=!1,v=0;for(let _=0;_<i.length;_++){const g=Math.floor(_%l),w=Math.floor(_/l);!g&&!p&&(p=!0),i[_]?(v++,_>0&&g>0&&i[_-1]||(u+=p?n("M",g+c,.5+w+c):n("m",h,0),h=0,p=!1),g+1<l&&i[_+1]||(u+=n("h",v),v=0)):h++}return u}return wm.render=function(l,c,u){const h=e.getOptions(c),p=l.modules.size,v=l.modules.data,_=p+h.margin*2,g=h.color.light.a?"<path "+t(h.color.light,"fill")+' d="M0 0h'+_+"v"+_+'H0z"/>':"",w="<path "+t(h.color.dark,"stroke")+' d="'+s(v,p,h.margin)+'"/>',S='viewBox="0 0 '+_+" "+_+'"',C='<svg xmlns="http://www.w3.org/2000/svg" '+(h.width?'width="'+h.width+'" height="'+h.width+'" ':"")+S+' shape-rendering="crispEdges">'+g+w+`</svg>
164
+ `;return typeof u=="function"&&u(null,C),C},wm}var mx;function Q6(){if(mx)return za;mx=1;const e=M6(),t=Y6(),n=X6(),s=J6();function i(l,c,u,h,p){const v=[].slice.call(arguments,1),_=v.length,g=typeof v[_-1]=="function";if(!g&&!e())throw new Error("Callback required as last argument");if(g){if(_<2)throw new Error("Too few arguments provided");_===2?(p=u,u=c,c=h=void 0):_===3&&(c.getContext&&typeof p>"u"?(p=h,h=void 0):(p=h,h=u,u=c,c=void 0))}else{if(_<1)throw new Error("Too few arguments provided");return _===1?(u=c,c=h=void 0):_===2&&!c.getContext&&(h=u,u=c,c=void 0),new Promise(function(w,S){try{const N=t.create(u,h);w(l(N,c,h))}catch(N){S(N)}})}try{const w=t.create(u,h);p(null,l(w,c,h))}catch(w){p(w)}}return za.create=t.create,za.toCanvas=i.bind(null,n.render),za.toDataURL=i.bind(null,n.renderToDataURL),za.toString=i.bind(null,function(l,c,u){return s.render(l,u)}),za}var Z6=Q6();const e4=mv(Z6);function gx(e){return typeof e=="string"?e.trim():e&&typeof e=="object"&&typeof e.data=="string"?e.data.trim():""}function t4(e){const t=String(e||"").trim();if(!t)return{kind:"empty"};const n=ZP(t);if(!n||!n.ok)return{kind:"invalid"};const s=[];return n.ssh||s.push("ssh"),n.name||s.push("name"),s.length?{kind:"partial",decoded:n,missing:s}:{kind:"complete",decoded:n}}function n4(e,t,n=new Set,s=!1){if(!t||!t.ok)return e;const i=eD(e,t,n);return t.version===2&&t.name&&!n.has("name")&&!s&&(i.name=t.name),!n.has("label")&&!i.label&&t.label&&(i.label=t.label),i}function vx(e,t,n=new Set,s=!1){const i=String(t||"").trim(),l=t4(i);let c={...e,pairingUrl:i};return(l.kind==="complete"||l.kind==="partial")&&(c={...n4(c,l.decoded,n,s),pairingUrl:i}),{classification:l,form:c}}function Id(e,t){const n=String(t||"").toLowerCase();if(!/^[a-f0-9]{16,64}$/.test(n))return"";const s=String(e||"NexusCrew").replace(/([a-z0-9])([A-Z])/g,"$1 $2");let i=mo(s);(i==="localhost"||i==="node")&&(i="nexuscrew");const l=n.slice(0,4),c=Math.max(1,32-l.length-1);return`${i.slice(0,c).replace(/-+$/g,"")||"n"}-${l}`}function s4(e,{deviceDefault:t="",localNodeId:n="",localNameDefault:s=""}={}){const i={name:e.name,ssh:e.ssh,pairingUrl:e.pairingUrl,...e.label?{label:e.label}:{},...e.sshPort?{sshPort:Number(e.sshPort)}:{}},l=e.localLabel||t;l&&(i.localLabel=l);const c=String(e.localName||Id(l,n)||s||"").trim();return c&&(i.localName=c),i}function i4(){const e=new Set;let t=!1;return{canAuto(n){return!t&&!e.has(String(n||""))},start(n){return t?!1:(t=!0,e.add(String(n||"")),!0)},finish(){t=!1},reset(n){e.delete(String(n||""))},isBusy(){return t}}}const r4=["validation","conflict","ssh-start","ssh-ready","join","tunnel-final","confirm","health"];function o4(e){const t=e&&e.data||{},n=typeof t.stage=="string"&&t.stage?t.stage:"",s=typeof t.detail=="string"&&t.detail?t.detail:"";return{stage:n,code:typeof t.code=="string"?t.code:"",detail:s,hint:typeof t.hint=="string"?t.hint:"",suggestedName:typeof t.suggestedName=="string"?t.suggestedName:"",retryable:typeof t.retryable=="boolean"?t.retryable:!n,message:s||String(e&&e.message||e)}}const a4="modulepreload",l4=function(e){return"/"+e},_x={},c4=function(t,n,s){let i=Promise.resolve();if(n&&n.length>0){let c=function(p){return Promise.all(p.map(v=>Promise.resolve(v).then(_=>({status:"fulfilled",value:_}),_=>({status:"rejected",reason:_}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),h=(u==null?void 0:u.nonce)||(u==null?void 0:u.getAttribute("nonce"));i=c(n.map(p=>{if(p=l4(p),p in _x)return;_x[p]=!0;const v=p.endsWith(".css"),_=v?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${_}`))return;const g=document.createElement("link");if(g.rel=v?"stylesheet":a4,v||(g.as="script"),g.crossOrigin="",g.href=p,h&&g.setAttribute("nonce",h),document.head.appendChild(g),v)return new Promise((w,S)=>{g.addEventListener("load",w),g.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${p}`)))})}))}function l(c){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=c,window.dispatchEvent(u),!u.defaultPrevented)throw c}return i.then(c=>{for(const u of c||[])u.status==="rejected"&&l(u.reason);return t().catch(l)})};class Ht{constructor(t,n,s,i,l){this._legacyCanvasSize=Ht.DEFAULT_CANVAS_SIZE,this._preferredCamera="environment",this._maxScansPerSecond=25,this._lastScanTimestamp=-1,this._destroyed=this._flashOn=this._paused=this._active=!1,this.$video=t,this.$canvas=document.createElement("canvas"),s&&typeof s=="object"?this._onDecode=n:(console.warn(s||i||l?"You're using a deprecated version of the QrScanner constructor which will be removed in the future":"Note that the type of the scan result passed to onDecode will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."),this._legacyOnDecode=n),n=typeof s=="object"?s:{},this._onDecodeError=n.onDecodeError||(typeof s=="function"?s:this._onDecodeError),this._calculateScanRegion=n.calculateScanRegion||(typeof i=="function"?i:this._calculateScanRegion),this._preferredCamera=n.preferredCamera||l||this._preferredCamera,this._legacyCanvasSize=typeof s=="number"?s:typeof i=="number"?i:this._legacyCanvasSize,this._maxScansPerSecond=n.maxScansPerSecond||this._maxScansPerSecond,this._onPlay=this._onPlay.bind(this),this._onLoadedMetaData=this._onLoadedMetaData.bind(this),this._onVisibilityChange=this._onVisibilityChange.bind(this),this._updateOverlay=this._updateOverlay.bind(this),t.disablePictureInPicture=!0,t.playsInline=!0,t.muted=!0;let c=!1;if(t.hidden&&(t.hidden=!1,c=!0),document.body.contains(t)||(document.body.appendChild(t),c=!0),s=t.parentElement,n.highlightScanRegion||n.highlightCodeOutline){if(i=!!n.overlay,this.$overlay=n.overlay||document.createElement("div"),l=this.$overlay.style,l.position="absolute",l.display="none",l.pointerEvents="none",this.$overlay.classList.add("scan-region-highlight"),!i&&n.highlightScanRegion){this.$overlay.innerHTML='<svg class="scan-region-highlight-svg" viewBox="0 0 238 238" preserveAspectRatio="none" style="position:absolute;width:100%;height:100%;left:0;top:0;fill:none;stroke:#e9b213;stroke-width:4;stroke-linecap:round;stroke-linejoin:round"><path d="M31 2H10a8 8 0 0 0-8 8v21M207 2h21a8 8 0 0 1 8 8v21m0 176v21a8 8 0 0 1-8 8h-21m-176 0H10a8 8 0 0 1-8-8v-21"/></svg>';try{this.$overlay.firstElementChild.animate({transform:["scale(.98)","scale(1.01)"]},{duration:400,iterations:1/0,direction:"alternate",easing:"ease-in-out"})}catch{}s.insertBefore(this.$overlay,this.$video.nextSibling)}n.highlightCodeOutline&&(this.$overlay.insertAdjacentHTML("beforeend",'<svg class="code-outline-highlight" preserveAspectRatio="none" style="display:none;width:100%;height:100%;fill:none;stroke:#e9b213;stroke-width:5;stroke-dasharray:25;stroke-linecap:round;stroke-linejoin:round"><polygon/></svg>'),this.$codeOutlineHighlight=this.$overlay.lastElementChild)}this._scanRegion=this._calculateScanRegion(t),requestAnimationFrame(()=>{let u=window.getComputedStyle(t);u.display==="none"&&(t.style.setProperty("display","block","important"),c=!0),u.visibility!=="visible"&&(t.style.setProperty("visibility","visible","important"),c=!0),c&&(console.warn("QrScanner has overwritten the video hiding style to avoid Safari stopping the playback."),t.style.opacity="0",t.style.width="0",t.style.height="0",this.$overlay&&this.$overlay.parentElement&&this.$overlay.parentElement.removeChild(this.$overlay),delete this.$overlay,delete this.$codeOutlineHighlight),this.$overlay&&this._updateOverlay()}),t.addEventListener("play",this._onPlay),t.addEventListener("loadedmetadata",this._onLoadedMetaData),document.addEventListener("visibilitychange",this._onVisibilityChange),window.addEventListener("resize",this._updateOverlay),this._qrEnginePromise=Ht.createQrEngine()}static set WORKER_PATH(t){console.warn("Setting QrScanner.WORKER_PATH is not required and not supported anymore. Have a look at the README for new setup instructions.")}static async hasCamera(){try{return!!(await Ht.listCameras(!1)).length}catch{return!1}}static async listCameras(t=!1){if(!navigator.mediaDevices)return[];let n=async()=>(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput"),s;try{t&&(await n()).every(i=>!i.label)&&(s=await navigator.mediaDevices.getUserMedia({audio:!1,video:!0}))}catch{}try{return(await n()).map((i,l)=>({id:i.deviceId,label:i.label||(l===0?"Default Camera":`Camera ${l+1}`)}))}finally{s&&(console.warn("Call listCameras after successfully starting a QR scanner to avoid creating a temporary video stream"),Ht._stopVideoStream(s))}}async hasFlash(){let t;try{if(this.$video.srcObject){if(!(this.$video.srcObject instanceof MediaStream))return!1;t=this.$video.srcObject}else t=(await this._getCameraStream()).stream;return"torch"in t.getVideoTracks()[0].getSettings()}catch{return!1}finally{t&&t!==this.$video.srcObject&&(console.warn("Call hasFlash after successfully starting the scanner to avoid creating a temporary video stream"),Ht._stopVideoStream(t))}}isFlashOn(){return this._flashOn}async toggleFlash(){this._flashOn?await this.turnFlashOff():await this.turnFlashOn()}async turnFlashOn(){if(!this._flashOn&&!this._destroyed&&(this._flashOn=!0,this._active&&!this._paused))try{if(!await this.hasFlash())throw"No flash available";await this.$video.srcObject.getVideoTracks()[0].applyConstraints({advanced:[{torch:!0}]})}catch(t){throw this._flashOn=!1,t}}async turnFlashOff(){this._flashOn&&(this._flashOn=!1,await this._restartVideoStream())}destroy(){this.$video.removeEventListener("loadedmetadata",this._onLoadedMetaData),this.$video.removeEventListener("play",this._onPlay),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("resize",this._updateOverlay),this._destroyed=!0,this._flashOn=!1,this.stop(),Ht._postWorkerMessage(this._qrEnginePromise,"close")}async start(){if(this._destroyed)throw Error("The QR scanner can not be started as it had been destroyed.");if((!this._active||this._paused)&&(window.location.protocol!=="https:"&&console.warn("The camera stream is only accessible if the page is transferred via https."),this._active=!0,!document.hidden))if(this._paused=!1,this.$video.srcObject)await this.$video.play();else try{let{stream:t,facingMode:n}=await this._getCameraStream();!this._active||this._paused?Ht._stopVideoStream(t):(this._setVideoMirror(n),this.$video.srcObject=t,await this.$video.play(),this._flashOn&&(this._flashOn=!1,this.turnFlashOn().catch(()=>{})))}catch(t){if(!this._paused)throw this._active=!1,t}}stop(){this.pause(),this._active=!1}async pause(t=!1){if(this._paused=!0,!this._active)return!0;this.$video.pause(),this.$overlay&&(this.$overlay.style.display="none");let n=()=>{this.$video.srcObject instanceof MediaStream&&(Ht._stopVideoStream(this.$video.srcObject),this.$video.srcObject=null)};return t?(n(),!0):(await new Promise(s=>setTimeout(s,300)),this._paused?(n(),!0):!1)}async setCamera(t){t!==this._preferredCamera&&(this._preferredCamera=t,await this._restartVideoStream())}static async scanImage(t,n,s,i,l=!1,c=!1){let u,h=!1;n&&("scanRegion"in n||"qrEngine"in n||"canvas"in n||"disallowCanvasResizing"in n||"alsoTryWithoutScanRegion"in n||"returnDetailedScanResult"in n)?(u=n.scanRegion,s=n.qrEngine,i=n.canvas,l=n.disallowCanvasResizing||!1,c=n.alsoTryWithoutScanRegion||!1,h=!0):console.warn(n||s||i||l||c?"You're using a deprecated api for scanImage which will be removed in the future.":"Note that the return type of scanImage will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."),n=!!s;try{let p,v;[s,p]=await Promise.all([s||Ht.createQrEngine(),Ht._loadImage(t)]),[i,v]=Ht._drawToCanvas(p,u,i,l);let _;if(s instanceof Worker){let g=s;n||Ht._postWorkerMessageSync(g,"inversionMode","both"),_=await new Promise((w,S)=>{let N,C,j,E=-1;C=x=>{x.data.id===E&&(g.removeEventListener("message",C),g.removeEventListener("error",j),clearTimeout(N),x.data.data!==null?w({data:x.data.data,cornerPoints:Ht._convertPoints(x.data.cornerPoints,u)}):S(Ht.NO_QR_CODE_FOUND))},j=x=>{g.removeEventListener("message",C),g.removeEventListener("error",j),clearTimeout(N),S("Scanner error: "+(x?x.message||x:"Unknown Error"))},g.addEventListener("message",C),g.addEventListener("error",j),N=setTimeout(()=>j("timeout"),1e4);let R=v.getImageData(0,0,i.width,i.height);E=Ht._postWorkerMessageSync(g,"decode",R,[R.data.buffer])})}else _=await Promise.race([new Promise((g,w)=>window.setTimeout(()=>w("Scanner error: timeout"),1e4)),(async()=>{try{var[g]=await s.detect(i);if(!g)throw Ht.NO_QR_CODE_FOUND;return{data:g.rawValue,cornerPoints:Ht._convertPoints(g.cornerPoints,u)}}catch(w){if(g=w.message||w,/not implemented|service unavailable/.test(g))return Ht._disableBarcodeDetector=!0,Ht.scanImage(t,{scanRegion:u,canvas:i,disallowCanvasResizing:l,alsoTryWithoutScanRegion:c});throw`Scanner error: ${g}`}})()]);return h?_:_.data}catch(p){if(!u||!c)throw p;let v=await Ht.scanImage(t,{qrEngine:s,canvas:i,disallowCanvasResizing:l});return h?v:v.data}finally{n||Ht._postWorkerMessage(s,"close")}}setGrayscaleWeights(t,n,s,i=!0){Ht._postWorkerMessage(this._qrEnginePromise,"grayscaleWeights",{red:t,green:n,blue:s,useIntegerApproximation:i})}setInversionMode(t){Ht._postWorkerMessage(this._qrEnginePromise,"inversionMode",t)}static async createQrEngine(t){if(t&&console.warn("Specifying a worker path is not required and not supported anymore."),t=()=>c4(()=>import("./qr-scanner-worker.min-D85Z9gVD.js"),[]).then(s=>s.createWorker()),!(!Ht._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(await BarcodeDetector.getSupportedFormats()).includes("qr_code")))return t();let n=navigator.userAgentData;return n&&n.brands.some(({brand:s})=>/Chromium/i.test(s))&&/mac ?OS/i.test(n.platform)&&await n.getHighEntropyValues(["architecture","platformVersion"]).then(({architecture:s,platformVersion:i})=>/arm/i.test(s||"arm")&&13<=parseInt(i||"13")).catch(()=>!0)?t():new BarcodeDetector({formats:["qr_code"]})}_onPlay(){this._scanRegion=this._calculateScanRegion(this.$video),this._updateOverlay(),this.$overlay&&(this.$overlay.style.display=""),this._scanFrame()}_onLoadedMetaData(){this._scanRegion=this._calculateScanRegion(this.$video),this._updateOverlay()}_onVisibilityChange(){document.hidden?this.pause():this._active&&this.start()}_calculateScanRegion(t){let n=Math.round(.6666666666666666*Math.min(t.videoWidth,t.videoHeight));return{x:Math.round((t.videoWidth-n)/2),y:Math.round((t.videoHeight-n)/2),width:n,height:n,downScaledWidth:this._legacyCanvasSize,downScaledHeight:this._legacyCanvasSize}}_updateOverlay(){requestAnimationFrame(()=>{if(this.$overlay){var t=this.$video,n=t.videoWidth,s=t.videoHeight,i=t.offsetWidth,l=t.offsetHeight,c=t.offsetLeft,u=t.offsetTop,h=window.getComputedStyle(t),p=h.objectFit,v=n/s,_=i/l;switch(p){case"none":var g=n,w=s;break;case"fill":g=i,w=l;break;default:(p==="cover"?v>_:v<_)?(w=l,g=w*v):(g=i,w=g/v),p==="scale-down"&&(g=Math.min(g,n),w=Math.min(w,s))}var[S,N]=h.objectPosition.split(" ").map((j,E)=>{const R=parseFloat(j);return j.endsWith("%")?(E?l-w:i-g)*R/100:R});h=this._scanRegion.width||n,_=this._scanRegion.height||s,p=this._scanRegion.x||0;var C=this._scanRegion.y||0;v=this.$overlay.style,v.width=`${h/n*g}px`,v.height=`${_/s*w}px`,v.top=`${u+N+C/s*w}px`,s=/scaleX\(-1\)/.test(t.style.transform),v.left=`${c+(s?i-S-g:S)+(s?n-p-h:p)/n*g}px`,v.transform=t.style.transform}})}static _convertPoints(t,n){if(!n)return t;let s=n.x||0,i=n.y||0,l=n.width&&n.downScaledWidth?n.width/n.downScaledWidth:1;n=n.height&&n.downScaledHeight?n.height/n.downScaledHeight:1;for(let c of t)c.x=c.x*l+s,c.y=c.y*n+i;return t}_scanFrame(){!this._active||this.$video.paused||this.$video.ended||("requestVideoFrameCallback"in this.$video?this.$video.requestVideoFrameCallback.bind(this.$video):requestAnimationFrame)(async()=>{if(!(1>=this.$video.readyState)){var t=Date.now()-this._lastScanTimestamp,n=1e3/this._maxScansPerSecond;t<n&&await new Promise(i=>setTimeout(i,n-t)),this._lastScanTimestamp=Date.now();try{var s=await Ht.scanImage(this.$video,{scanRegion:this._scanRegion,qrEngine:this._qrEnginePromise,canvas:this.$canvas})}catch(i){if(!this._active)return;this._onDecodeError(i)}!Ht._disableBarcodeDetector||await this._qrEnginePromise instanceof Worker||(this._qrEnginePromise=Ht.createQrEngine()),s?(this._onDecode?this._onDecode(s):this._legacyOnDecode&&this._legacyOnDecode(s.data),this.$codeOutlineHighlight&&(clearTimeout(this._codeOutlineHighlightRemovalTimeout),this._codeOutlineHighlightRemovalTimeout=void 0,this.$codeOutlineHighlight.setAttribute("viewBox",`${this._scanRegion.x||0} ${this._scanRegion.y||0} ${this._scanRegion.width||this.$video.videoWidth} ${this._scanRegion.height||this.$video.videoHeight}`),this.$codeOutlineHighlight.firstElementChild.setAttribute("points",s.cornerPoints.map(({x:i,y:l})=>`${i},${l}`).join(" ")),this.$codeOutlineHighlight.style.display="")):this.$codeOutlineHighlight&&!this._codeOutlineHighlightRemovalTimeout&&(this._codeOutlineHighlightRemovalTimeout=setTimeout(()=>this.$codeOutlineHighlight.style.display="none",100))}this._scanFrame()})}_onDecodeError(t){t!==Ht.NO_QR_CODE_FOUND&&console.log(t)}async _getCameraStream(){if(!navigator.mediaDevices)throw"Camera not found.";let t=/^(environment|user)$/.test(this._preferredCamera)?"facingMode":"deviceId",n=[{width:{min:1024}},{width:{min:768}},{}],s=n.map(i=>Object.assign({},i,{[t]:{exact:this._preferredCamera}}));for(let i of[...s,...n])try{let l=await navigator.mediaDevices.getUserMedia({video:i,audio:!1}),c=this._getFacingMode(l)||(i.facingMode?this._preferredCamera:this._preferredCamera==="environment"?"user":"environment");return{stream:l,facingMode:c}}catch{}throw"Camera not found."}async _restartVideoStream(){let t=this._paused;await this.pause(!0)&&!t&&this._active&&await this.start()}static _stopVideoStream(t){for(let n of t.getTracks())n.stop(),t.removeTrack(n)}_setVideoMirror(t){this.$video.style.transform="scaleX("+(t==="user"?-1:1)+")"}_getFacingMode(t){return(t=t.getVideoTracks()[0])?/rear|back|environment/i.test(t.label)?"environment":/front|user|face/i.test(t.label)?"user":null:null}static _drawToCanvas(t,n,s,i=!1){s=s||document.createElement("canvas");let l=n&&n.x?n.x:0,c=n&&n.y?n.y:0,u=n&&n.width?n.width:t.videoWidth||t.width,h=n&&n.height?n.height:t.videoHeight||t.height;return i||(i=n&&n.downScaledWidth?n.downScaledWidth:u,n=n&&n.downScaledHeight?n.downScaledHeight:h,s.width!==i&&(s.width=i),s.height!==n&&(s.height=n)),n=s.getContext("2d",{alpha:!1}),n.imageSmoothingEnabled=!1,n.drawImage(t,l,c,u,h,0,0,s.width,s.height),[s,n]}static async _loadImage(t){if(t instanceof Image)return await Ht._awaitImageLoad(t),t;if(t instanceof HTMLVideoElement||t instanceof HTMLCanvasElement||t instanceof SVGImageElement||"OffscreenCanvas"in window&&t instanceof OffscreenCanvas||"ImageBitmap"in window&&t instanceof ImageBitmap)return t;if(t instanceof File||t instanceof Blob||t instanceof URL||typeof t=="string"){let n=new Image;n.src=t instanceof File||t instanceof Blob?URL.createObjectURL(t):t.toString();try{return await Ht._awaitImageLoad(n),n}finally{(t instanceof File||t instanceof Blob)&&URL.revokeObjectURL(n.src)}}else throw"Unsupported image type."}static async _awaitImageLoad(t){t.complete&&t.naturalWidth!==0||await new Promise((n,s)=>{let i=l=>{t.removeEventListener("load",i),t.removeEventListener("error",i),l instanceof ErrorEvent?s("Image load error"):n()};t.addEventListener("load",i),t.addEventListener("error",i)})}static async _postWorkerMessage(t,n,s,i){return Ht._postWorkerMessageSync(await t,n,s,i)}static _postWorkerMessageSync(t,n,s,i){if(!(t instanceof Worker))return-1;let l=Ht._workerMessageId++;return t.postMessage({id:l,type:n,data:s},i),l}}Ht.DEFAULT_CANVAS_SIZE=400;Ht.NO_QR_CODE_FOUND="No QR code found";Ht._disableBarcodeDetector=!1;Ht._workerMessageId=0;function u4({onResult:e,onClose:t}){const n=y.useRef(null),s=y.useRef(null),i=y.useRef(!1),[l,c]=y.useState("");y.useEffect(()=>{let h=!1;const p=n.current,v=_=>{h||i.current||(i.current=!0,e(_))};return(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){c(f("qr-unsupported"));return}let _=!1;try{_=await Ht.hasCamera()}catch{_=!1}if(!_){c(f("qr-no-camera"));return}if(h||!p)return;const g=new Ht(p,w=>{const S=gx(w);S&&v(S)},{returnDetailedScanResult:!0,preferredCamera:"environment",calculateScanRegion:w=>{const S=w.videoWidth||640,N=w.videoHeight||480,C=Math.max(1,Math.round(Math.min(S,N)*.92));return{x:Math.round((S-C)/2),y:Math.round((N-C)/2),width:C,height:C,downScaledWidth:600,downScaledHeight:600}},highlightScanRegion:!0,highlightCodeOutline:!0});s.current=g;try{await g.start()}catch(w){if(h)return;const S=w&&w.name||"";c(f(S==="NotAllowedError"||S==="SecurityError"?"qr-permission":S==="NotFoundError"||S==="OverconstrainedError"||S==="NotReadableError"?"qr-no-camera":"qr-unsupported"))}})(),()=>{h=!0;const _=s.current;if(_){try{_.stop()}catch{}try{_.destroy()}catch{}s.current=null}const g=p,w=g&&g.srcObject;if(w&&typeof w.getTracks=="function"){for(const S of w.getTracks())try{S.stop()}catch{}try{g.srcObject=null}catch{}}}},[]);const u=async h=>{const p=h.target.files&&h.target.files[0];if(h.target.value="",!!p)try{const v=await Ht.scanImage(p,{returnDetailedScanResult:!0}),_=gx(v);if(!_)throw new Error("empty");i.current||(i.current=!0,e(_))}catch{c(f("pairing-qr-invalid"))}};return o.jsx("div",{className:"nc-sheet-overlay nc-qr-overlay",onClick:t,children:o.jsxs("div",{className:"nc-sheet nc-qr-modal",onClick:h=>h.stopPropagation(),children:[o.jsx("div",{className:"nc-sheet-head",children:o.jsx("b",{children:f("scan-qr")})}),o.jsx("video",{ref:n,className:"nc-qr-video",playsInline:!0,muted:!0}),l&&o.jsx("div",{className:"nc-err",role:"alert",children:l}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsxs("label",{className:"nc-btn ghost nc-qr-upload",children:[f("qr-upload"),o.jsx("input",{type:"file",accept:"image/*",hidden:!0,onChange:u})]}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:t,children:f("cancel")})]})]})})}function v_({line:e,note:t}){const[n,s]=y.useState(!1);return e?o.jsxs("div",{className:"nc-authkeys",role:"group",children:[o.jsx("div",{className:"nc-sheet-label",children:f("pair-authkeys-title")}),o.jsx("small",{className:"nc-set-hint",children:t||f("pair-authkeys-hint")}),o.jsx("textarea",{className:"nc-authkeys-line",readOnly:!0,rows:3,value:e,"aria-label":f("pair-authkeys-title"),onFocus:i=>i.target.select()}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:async()=>{s(await Dc(e))},children:f(n?"pair-authkeys-copied":"pair-authkeys-copy")})]}):null}const yx=()=>({name:"",label:"",ssh:"",sshPort:"",pairingUrl:"",localLabel:"",localName:""});function PE({token:e,initial:t="",autoStart:n=!1,deviceDefault:s="",localNodeId:i="",localNameDefault:l="",readonly:c=!1,onSuccess:u,onBusyChange:h}){const[p,v]=y.useState(yx),[_,g]=y.useState(!1),[w,S]=y.useState(!1),[N,C]=y.useState("idle"),[j,E]=y.useState(null),[R,x]=y.useState(""),[W,$]=y.useState(null),[Y,q]=y.useState(!1),[K,se]=y.useState(!1),V=y.useRef(i4()),B=y.useRef(new Set),D=N==="busy",O=Id(p.localLabel||s,i)||l,P=K?p.localName:O;y.useEffect(()=>(h&&h(D),()=>{h&&h(!1)}),[D,h]);const z=async U=>{const ee=String(U.pairingUrl||"").trim();if(V.current.start(ee)){C("busy"),E(null),x("");try{const re=await W5(e,s4({...U,localName:K?U.localName:Id(U.localLabel||s,i)||l},{deviceDefault:s,localNodeId:i,localNameDefault:l}));C("ok"),g(!1),v(yx()),$(re&&re.authorizedKeys?{line:re.authorizedKeys,note:re.authorizedKeysNote||""}:null),B.current=new Set,q(!1),se(!1),V.current.finish(),u&&await u(re)}catch(re){const oe=o4(re);E(oe),C("idle"),V.current.finish(),oe.code==="peer-name-conflict"&&Ug(oe.suggestedName)&&(se(!0),B.current.add("localName"),v(je=>({...je,localName:oe.suggestedName}))),(oe.stage==="validation"||oe.stage==="conflict"||oe.stage==="ssh-start"||oe.stage==="ssh-ready"||String(oe.code||"").startsWith("ssh-"))&&g(!0)}}},A=(U,ee=!0)=>{const{classification:re,form:oe}=vx(p,U,B.current,Y),je=oe.pairingUrl;if(E(null),x(""),N==="ok"&&C("idle"),v(oe),re.kind==="invalid"){E({stage:"validation",code:"bad-link",message:f("pair-invalid-link"),hint:f("pair-invalid-hint"),retryable:!0});return}if(re.kind==="partial"){g(!0),x(re.missing.includes("ssh")?f("pair-missing-ssh"):f("pair-missing-name"));return}re.kind==="complete"&&ee&&!c&&V.current.canAuto(je)&&z(oe)};y.useEffect(()=>{t&&A(t,n)},[]);const T=()=>{const U=String(p.pairingUrl||"").trim(),{classification:ee,form:re}=vx(p,U,B.current,Y);if(v(re),x(""),E(null),ee.kind==="empty"){E({stage:"validation",message:f("pairing-required"),retryable:!0});return}if(ee.kind==="invalid"){E({stage:"validation",code:"bad-link",message:f("pair-invalid-link"),hint:f("pair-invalid-hint"),retryable:!0});return}if(!re.ssh||!re.name){g(!0),x(re.ssh?f("pair-missing-name"):f("pair-missing-ssh"));return}if(re.label&&!tl(re.label)){E({stage:"validation",message:f("err-label"),retryable:!0});return}if(re.localLabel&&!tl(re.localLabel)){E({stage:"validation",message:f("err-label"),retryable:!0});return}const oe=K?re.localName:Id(re.localLabel||s,i)||l;if(!Ug(oe)||oe==="localhost"){g(!0),E({stage:"validation",code:"bad-local-name",message:f("err-local-name"),retryable:!0});return}V.current.reset(U),z(re)},L=async()=>{try{if(!navigator.clipboard||typeof navigator.clipboard.readText!="function")throw new Error("unsupported");const U=await navigator.clipboard.readText();U&&U.trim()?A(U):x(f("pair-clipboard-empty"))}catch{x(f("pair-clipboard-denied"))}},H=(U,ee)=>{B.current.add(U),v(re=>({...re,[U]:ee}))},M=j&&j.stage&&(r4.includes(j.stage)||j.stage==="internal")?f(`pair-stage-${j.stage}`):f("pair-stage-generic");return o.jsxs("div",{className:"nc-set-form nc-pair-card",children:[o.jsx("div",{className:"nc-sheet-label",children:f("pair-card-title")}),o.jsx("div",{className:"nc-set-info",children:f("pair-card-help")}),o.jsx("input",{className:"nc-pair-input",placeholder:f("pair-paste-ph"),value:p.pairingUrl,disabled:c||D,onChange:U=>{v({...p,pairingUrl:U.target.value}),E(null),x("")},onPaste:U=>{const ee=U.clipboardData&&U.clipboardData.getData("text")||"";ee.trim()&&(U.preventDefault(),A(ee))},onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),T())}}),o.jsxs("div",{className:"nc-pair-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:c||D,onClick:L,children:f("pair-paste-btn")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:c||D,onClick:()=>S(!0),children:f("scan-qr")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:c||D,title:c?f("settings-readonly"):"",onClick:T,children:f("test-and-connect")})]}),o.jsxs("div",{className:"nc-pair-status","aria-live":"polite",children:[D&&o.jsx("div",{className:"nc-pair-progress",children:f("pair-progress")}),N==="ok"&&o.jsx("div",{className:"nc-set-test ok",children:f("node-connected")}),N==="ok"&&W&&o.jsx(v_,{line:W.line,note:W.note}),R&&o.jsx("div",{className:"nc-set-hint nc-pair-notice",children:R}),j&&o.jsxs("div",{className:"nc-err",role:"alert",children:[o.jsx("b",{children:M})," — ",j.message,j.hint&&o.jsx("div",{className:"nc-pair-hint",children:j.hint}),j.retryable&&o.jsx("div",{children:o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:c||D,onClick:T,children:f("pair-retry")})})]})]}),o.jsxs("button",{type:"button",className:"nc-btn ghost nc-pair-advanced-toggle",disabled:D,onClick:()=>g(U=>!U),children:[_?"▾":"▸"," ",f("pair-advanced")]}),_&&o.jsxs("div",{className:"nc-pair-advanced",children:[o.jsxs("label",{className:"nc-field",children:[f("node-display-label"),o.jsx("input",{placeholder:"Home Relay",value:p.label,disabled:c||D,onChange:U=>{B.current.add("label"),v(ee=>({...ee,label:U.target.value,name:Y?ee.name:mo(U.target.value)}))}})]}),o.jsxs("label",{className:"nc-field",children:[f("node-name-label"),o.jsx("input",{placeholder:f("node-name-ph"),value:p.name,disabled:c||D,onChange:U=>{q(!0),B.current.add("name"),v(ee=>({...ee,name:U.target.value?mo(U.target.value):""}))}})]}),o.jsx("small",{className:"nc-set-hint",children:f("node-slug-hint").replace("{slug}",p.name||"home-relay")}),o.jsxs("label",{className:"nc-field",children:[f("pair-ssh-local-label"),o.jsx("input",{placeholder:"my-relay",value:p.ssh,disabled:c||D,onChange:U=>{B.current.add("ssh"),H("ssh",U.target.value)}}),o.jsx("small",{className:"nc-set-hint",children:f("node-ssh-local-help")})]}),o.jsxs("label",{className:"nc-field",children:[f("node-ssh-port-label"),o.jsx("input",{inputMode:"numeric",placeholder:f("node-ssh-port-help"),value:p.sshPort,disabled:c||D,onChange:U=>H("sshPort",U.target.value.replace(/[^0-9]/g,"").slice(0,5))})]}),o.jsxs("label",{className:"nc-field",children:[f("device-name-label"),o.jsx("input",{placeholder:s||"NexusCrew",value:p.localLabel,disabled:c||D,onChange:U=>H("localLabel",U.target.value)}),o.jsx("small",{className:"nc-set-hint",children:f("device-name-hint")})]}),o.jsxs("label",{className:"nc-field",children:[f("local-route-name-label"),o.jsx("input",{placeholder:O||"nexuscrew-5bd6",value:P,disabled:c||D,onChange:U=>{se(!0),B.current.add("localName"),v(ee=>({...ee,localName:U.target.value?mo(U.target.value):""}))}}),o.jsx("small",{className:"nc-set-hint",children:f("local-route-name-hint")})]})]}),w&&o.jsx(u4,{onResult:U=>{S(!1),A(U)},onClose:()=>S(!1)})]})}const Ji={routed:"peer-routed",routedStale:"peer-routed-stale",up:"tunnel-up",down:"tunnel-down",passive:"node-connected-client",vlOnline:"vl-poll-online",vlOffline:"vl-poll-offline"};function __(e){if(!e||typeof e!="object")return{key:Ji.down,up:!1};if(e.kind==="vl")return e.online?{key:Ji.vlOnline,up:!0}:{key:Ji.vlOffline,up:!1};if(e.kind==="transitive"){const n=e.stale===!0;return{key:n?Ji.routedStale:Ji.routed,up:!n,routed:!0}}const t=e.tunnel&&e.tunnel.status;return t==="up"?{key:Ji.up,up:!0}:t==="passive"?{key:Ji.passive,up:!1,passive:!0}:{key:Ji.down,up:!1}}function DE(e){if(!e||typeof e!="object")return{key:"peer-private",shortKey:"row-private",shared:!1};if(e.kind==="vl")return{key:"peer-vl-federated",shortKey:"row-vl-federated",shared:!0};if(e.shared!==!0)return{key:"peer-private",shortKey:"row-private",shared:!1};const t=e.visibility||"network";if(t==="relay-only")return{key:"visibility-relay",shortKey:"visibility-relay",shared:!0,visibility:t};if(t==="selected"){const n=Array.isArray(e.selected)?e.selected.length:0;return{key:"visibility-selected",shortKey:"visibility-selected",shared:!0,visibility:t,count:n}}return{key:"visibility-network",shortKey:"visibility-network",shared:!0,visibility:t}}function d4(e){const n=e.health&&typeof e.health.detail=="string"&&e.health.detail.trim()||f(e.online?Ji.vlOnline:Ji.vlOffline);return e.ownerLabel?`${e.ownerLabel} · ${n}`:n}function h4(e){if(!e||typeof e!="object")return null;const t=typeof e.name=="string"?e.name:"";if(!t)return null;const n=e.kind==="transitive";return{name:t,title:typeof e.label=="string"&&e.label.trim()||t,subtitle:e.kind==="vl"?d4(e):t,reach:__(e),exposure:DE(e),routed:n,routeLabel:n&&Array.isArray(e.route)?e.route.join(" › "):null}}function f4(e){if(!e||typeof e!="object"||typeof e.name!="string"||!e.name)return null;const t=e.kind==="transitive";return{name:e.name,title:typeof e.label=="string"&&e.label.trim()||e.name,routed:t,route:t&&Array.isArray(e.route)?[...e.route]:null,ssh:!t&&e.direction==="outbound"&&e.ssh?String(e.ssh):null,inbound:!t&&e.direction==="inbound",transport:e.tunnel&&typeof e.tunnel.transport=="string"&&e.tunnel.transport||null}}function p4(e){return!e||typeof e!="object"?null:e.kind==="transitive"?{key:"authority-routed",ownerEquivalent:!1,grants:[],model:"none"}:{key:"authority-owner-equivalent",ownerEquivalent:!0,grants:[],model:"none"}}function m4(e,t){if(!e||e.visibility!=="selected")return[];const n=[...new Set(Array.isArray(e.selected)?e.selected:[])],s=new Map;for(const i of Array.isArray(t)?t:[])i&&i.nodeId&&!s.has(i.nodeId)&&s.set(i.nodeId,i);return n.map(i=>{const l=s.get(i);return{id:i,label:l?typeof l.label=="string"&&l.label.trim()||l.name:i,known:!!l}})}function g4(e,t,n=""){if(!e)return[];const s=new Set(Array.isArray(e.selected)?e.selected:[]),i=String(n||"").trim().toLowerCase(),l=new Set,c=[],u=h=>e.nodeId?h.nodeId===e.nodeId:h.name===e.name;for(const h of Array.isArray(t)?t:[]){if(!h||!h.nodeId||u(h)||s.has(h.nodeId)||l.has(h.nodeId))continue;const p=typeof h.label=="string"&&h.label.trim()||h.name;i&&!`${p} ${h.name}`.toLowerCase().includes(i)||(l.add(h.nodeId),c.push({id:h.nodeId,label:p,name:h.name}))}return c.sort((h,p)=>h.label.localeCompare(p.label))}function v4(e,{readonly:t=!1,busy:n=!1}={}){if(!e||typeof e!="object")return[];const s=e.actions&&typeof e.actions=="object"?e.actions:{},i=__(e).up,l=[],c=(u,h,{mutating:p=!0,danger:v=!1}={})=>{l.push({key:u,action:h,danger:v,disabled:n||p&&t})};return s.edit&&c("edit","edit"),s.test&&c("node-test","test",{mutating:!1}),s.disconnect&&i&&c("tunnel-stop","down"),s.connect&&!i&&c("tunnel-start","up"),s.restart&&c("tunnel-restart","restart"),s.remove&&c("delete","remove",{danger:!0}),l}function OE(e){const t=e&&typeof e.cellVisibility=="string"?e.cellVisibility:"all";return["all","none","selected"].includes(t)?t:"all"}function _4(e,t){if(OE(e)!=="selected")return[];const n=[...new Set(Array.isArray(e.cells)?e.cells:[])];if(!Array.isArray(t))return n.map(i=>({id:i,label:i,known:!0}));const s=new Set(t.map(i=>typeof i=="string"?i:i&&(i.cell||i.id)).filter(Boolean));return n.map(i=>({id:i,label:i,known:s.has(i)}))}function y4(e,t,n=""){const s=new Set(Array.isArray(e&&e.cells)?e.cells:[]),i=String(n||"").trim().toLowerCase(),l=new Set,c=[];for(const u of Array.isArray(t)?t:[]){const h=typeof u=="string"?u:u&&(u.cell||u.id);!h||s.has(h)||l.has(h)||i&&!h.toLowerCase().includes(i)||(l.add(h),c.push({id:h,label:h}))}return c.sort((u,h)=>u.label.localeCompare(h.label))}function b4(e){if(!e||typeof e!="object"||e.kind!=="direct")return null;const t=e.access&&typeof e.access=="object"&&!Array.isArray(e.access)?e.access:null;return{label:typeof e.accessLabel=="string"?e.accessLabel:"unconfigured",configured:e.accessConfigured===!0,grants:t}}function w4(e,t,{readonly:n=!1,busy:s=!1}={}){const i=f4(e);return i?{identity:i,reach:__(e),authority:p4(e),exposure:DE(e),grants:m4(e,t),cellScope:OE(e),actions:v4(e,{readonly:n,busy:s}),canEditVisibility:!!(e.actions&&e.actions.visibility)&&e.shared===!0&&e.kind!=="transitive",canEditCellScope:!!(e.actions&&e.actions.edit)&&e.kind!=="transitive"}:null}const S4=Object.freeze(["cellVisibility","eventsAccess","nodeEventsAccess","askReplyAccess","filesReadAccess","liveHostAccess","panelAccess","peerOperatorAccess"]),x4=Object.freeze(["admin","user","nexushost"]),k4=Object.freeze({admin:Object.freeze({cellVisibility:"all",eventsAccess:!0,nodeEventsAccess:!0,askReplyAccess:!0,filesReadAccess:!0,liveHostAccess:!0,panelAccess:!0,peerOperatorAccess:!0}),user:Object.freeze({cellVisibility:"all",eventsAccess:!0,nodeEventsAccess:!0,askReplyAccess:!1,filesReadAccess:!0,liveHostAccess:!1,panelAccess:!1,peerOperatorAccess:!1}),nexushost:Object.freeze({cellVisibility:"none",eventsAccess:!1,nodeEventsAccess:!1,askReplyAccess:!1,filesReadAccess:!1,liveHostAccess:!1,panelAccess:!1,peerOperatorAccess:!1})});function C4(e,t,n=!1){const s=k4[t];if(!s)return[];const i=e&&typeof e=="object"?e:{},l=S4.map(c=>{const u=s[c],h=i[c];return{key:c,current:h,next:u,changed:h!==u}});return t==="admin"&&l.push({key:"eventsReceive",current:n===!0,next:!0,changed:n!==!0}),l}const BE="nc_push_local_v1",bx=Object.freeze({enabled:!0});function $E(e){return{enabled:(e&&typeof e=="object"&&!Array.isArray(e)?e:{}).enabled!==!1}}function y_(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function zE(e=y_()){if(!e)return{...bx};try{return $E(JSON.parse(e.getItem(BE)||"null"))}catch{return{...bx}}}function E4(e,t=y_()){const n=$E(e);if(t)try{t.setItem(BE,JSON.stringify(n))}catch{}return n}function N4(e=y_()){return zE(e).enabled===!1}function b_(){return typeof navigator<"u"&&"serviceWorker"in navigator&&typeof window<"u"&&"PushManager"in window&&typeof Notification<"u"}function j4(e){const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),s=atob(n),i=new Uint8Array(s.length);for(let l=0;l<s.length;l+=1)i[l]=s.charCodeAt(l);return i}async function FE(){if(!b_())return"unsupported";if(Notification.permission==="denied")return"denied";try{return await(await navigator.serviceWorker.ready).pushManager.getSubscription()?"subscribed":"idle"}catch{return"idle"}}async function HE(e){if(!b_())throw new Error("push-unsupported");if(N4())throw new Error("push-disabled-local");if(await Notification.requestPermission()!=="granted")throw new Error("push-denied");const n=await Vn("/api/push/vapid",e),{publicKey:s}=await n.json();if(!s)throw new Error("vapid non disponibile");const l=await(await navigator.serviceWorker.ready).pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:j4(s)}),c=await Vn("/api/push/subscribe",e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({subscription:l.toJSON()})});if(!c.ok){try{await l.unsubscribe()}catch{}const u=await c.json().catch(()=>({}));throw new Error(u.error||`HTTP ${c.status}`)}return!0}async function wx(e){if(!b_())return!1;const n=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!n)return!1;const s=n.endpoint;try{await n.unsubscribe()}catch{}try{await Vn("/api/push/subscribe",e,{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({endpoint:s})})}catch{}return!0}const L4=new Set(["update_candidate"]),Sx=4096,R4=new Set(["prompt"]),xx={logs:{limit:50}};function A4(e){if(!e||e.kind!=="vl")return[];const t=Array.isArray(e.capabilities)?e.capabilities:[],n=new Set,s=[];for(const i of t)typeof i!="string"||!i||L4.has(i)||R4.has(i)||n.has(i)||(n.add(i),s.push(i));return s}function kx(e){return!!(e&&e.kind==="vl"&&Array.isArray(e.capabilities)&&e.capabilities.includes("prompt"))}function M4(e){return xx[e]?{...xx[e]}:{}}function T4(e,t){return e?e.inflight&&typeof e.inflight=="object"?{phase:"inflight",kind:e.inflight.kind}:t?e.lastAck&&e.lastAck.id===t.id?{phase:"done",kind:t.kind,status:e.lastAck.status,result:e.lastAck.result,at:e.lastAck.at}:{phase:"submitted",kind:t.kind}:e.lastAck&&typeof e.lastAck=="object"?{phase:"done",kind:null,status:e.lastAck.status,result:e.lastAck.result,at:e.lastAck.at}:null:null}function I4({title:e,subtitle:t,status:n,footer:s,onClose:i,plain:l=!1,children:c}){const u=y.useRef(null),h=y.useRef(null);return y.useEffect(()=>(h.current=document.activeElement,u.current&&u.current.focus(),()=>{const p=h.current;p&&typeof p.focus=="function"&&document.contains(p)&&p.focus()}),[]),y.useEffect(()=>{const p=v=>{v.key==="Escape"&&(v.stopPropagation(),i&&i())};return document.addEventListener("keydown",p,!0),()=>document.removeEventListener("keydown",p,!0)},[i]),o.jsx("div",{className:"nc-detail-overlay",onMouseDown:p=>{p.target===p.currentTarget&&i&&i()},children:o.jsxs("div",{className:"nc-detail-sheet",ref:u,tabIndex:-1,role:"dialog","aria-modal":"true","aria-label":typeof e=="string"?e:void 0,children:[o.jsxs("div",{className:"nc-detail-head",children:[o.jsxs("div",{className:"nc-detail-title",children:[o.jsx("b",{children:e}),t&&o.jsx("small",{children:t})]}),n,o.jsx("button",{type:"button",className:"nc-btn ghost nc-detail-close",onClick:i,"aria-label":f("close"),children:o.jsx(yt,{name:"x",size:14})})]}),o.jsx("div",{className:`nc-detail-body${l?" plain":""}`,children:c}),s&&o.jsx("div",{className:"nc-detail-foot",children:s})]})})}function Po({title:e,hint:t,children:n}){return n==null||n===!1?null:o.jsxs("section",{className:"nc-detail-section",children:[e&&o.jsx("div",{className:"nc-sheet-label",children:e}),t&&o.jsx("small",{className:"nc-set-hint",children:t}),n]})}function P4({node:e,nodes:t,token:n,readonly:s,refresh:i,onClose:l,peerAccessRevision:c=null}){var lt,X;Fn();const[u,h]=y.useState(null),[p,v]=y.useState(null),[_,g]=y.useState(null),[w,S]=y.useState(null),[N,C]=y.useState(!1),[j,E]=y.useState(""),[R,x]=y.useState(!1),[W,$]=y.useState(null),[Y,q]=y.useState(!1),[K,se]=y.useState(""),[V,B]=y.useState(!1),[D,O]=y.useState(null),[P,z]=y.useState(!1),[A,T]=y.useState(""),[L,H]=y.useState(null),M=y.useMemo(()=>w4(e,t,{readonly:s,busy:!!u}),[e,t,s,u]);if(!M)return null;const{identity:U,reach:ee,authority:re,exposure:oe,grants:je,actions:te,canEditVisibility:ie,canEditCellScope:pe,cellScope:xe}=M,Be=b4(e),Te=U.routed?{up:ee.up,since:null}:Wg(e.tunnel,Date.now()),Me=async(I,ce)=>{v(null),h(I);try{await ce()}catch(ye){v(String(ye&&ye.message||ye))}h(null)},J=I=>{if(I==="edit"){S({label:e.label||e.name,ssh:e.ssh||"",sshPort:e.sshPort?String(e.sshPort):"",autostart:e.autostart===!0,visibility:e.visibility||"network"});return}if(I==="remove"){C(!0);return}Me(`${e.name}:${I}`,async()=>{const ce=await wv(n,e.name,I);I==="test"&&g(ce),await i()})},le=(I,ce=M4(I))=>Me(`${e.nodeId}:${I}`,async()=>{const ye=await dw(n,e.nodeId,I,ce,e.route||[]);O({id:ye.id,kind:I,submittedAt:Date.now()}),await i()}),Q=()=>{const I=A.trim().slice(0,Sx);I&&Me(`${e.nodeId}:prompt`,async()=>{const ce=await dw(n,e.nodeId,"prompt",{text:I},e.route||[]);O({id:ce.id,kind:"prompt",submittedAt:Date.now()}),T(""),z(!1),await i()})},ge=()=>{if(!tl(w.label)){v(f("err-label"));return}const I=U.inbound?{label:w.label,visibility:w.visibility,selected:w.visibility==="selected"?[...e.selected||[]]:[]}:{label:w.label,ssh:w.ssh,autostart:w.autostart,...w.sshPort?{sshPort:Number(w.sshPort)}:{}};return Me(`${e.name}:edit`,async()=>{await up(n,e.name,I),S(null),await i()})},Z=(I,ce)=>Me(`${e.name}:visibility`,async()=>{await X5(n,e.name,I,ce),await i()}),fe=ie&&e.visibility==="selected"?g4(e,t,j):[],ve=(I,ce)=>Me(`${e.name}:cell-scope`,async()=>{await up(n,e.name,I==="selected"?{cellVisibility:I,cells:Array.isArray(ce)?ce:e.cells||[]}:{cellVisibility:I}),await i()}),ke=I=>Me(`${e.name}:access`,async()=>{try{if(await up(n,e.name,{accessRole:I,accessRevision:c}),I==="admin"&&typeof Notification<"u"&&Notification.permission==="granted")try{await FE()==="idle"&&await HE(n)}catch{}H(null),await i()}catch(ce){if(ce&&ce.status===409)v(f("peer-access-conflict")),await i();else throw ce}}),Ve=async({retry:I=!1}={})=>{if(I&&Y)q(!1);else if(W!==null||Y)return;try{const ce=await uh(n);$(Array.isArray(ce&&ce.cells)?ce.cells:[])}catch{q(!0)}};y.useEffect(()=>{pe&&xe==="selected"&&W===null&&Ve()},[pe,xe,W]);const ot=_4(e,W),rt=xe==="selected"?y4(e,W,K):[],$e=o.jsxs("span",{className:`nc-set-tunnel${ee.up?" up":""}`,children:[f(ee.key),Te.since?` · ${Te.since}`:""]}),_e=e.kind==="vl",ze=_e?A4(e):[],Je=_e?T4(e,D):null,He=I=>{const ce=`vl-cmd-${I}`,ye=f(ce);return ye===ce?I:ye},nt=_e?[...ze.map(I=>o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!u||s,title:s?f("settings-readonly"):void 0,onClick:()=>le(I),children:He(I)},I)),...kx(e)?[o.jsx("button",{type:"button",className:`nc-btn ghost${P?" on":""}`,disabled:!!u||s,title:s?f("settings-readonly"):void 0,onClick:()=>z(I=>!I),children:He("prompt")},"prompt")]:[]]:te.map(I=>o.jsx("button",{type:"button",className:`nc-btn ${I.danger?"danger":"ghost"}`,disabled:I.disabled,title:I.disabled&&s?f("settings-readonly"):void 0,onClick:()=>J(I.action),children:I.action==="remove"?o.jsxs(o.Fragment,{children:[o.jsx(yt,{name:"trash",size:14})," ",f(I.key)]}):f(I.key)},I.action));return o.jsxs(I4,{title:U.title,subtitle:U.name,status:$e,footer:nt,onClose:l,children:[o.jsxs(Po,{title:f("node-detail-reach"),children:[o.jsxs("dl",{className:"nc-detail-facts",children:[U.route&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:f("node-detail-route")}),o.jsx("dd",{children:U.route.join(" › ")})]}),U.ssh&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:f("node-detail-ssh")}),o.jsxs("dd",{children:[U.ssh,e.sshPort?`:${e.sshPort}`:""]})]}),U.transport&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:f("node-detail-transport")}),o.jsx("dd",{children:U.transport})]}),_e&&e.ownerLabel&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:f("node-detail-owner")}),o.jsx("dd",{children:e.ownerLabel})]})]}),((lt=e.health)==null?void 0:lt.detail)&&o.jsx("div",{className:`nc-set-test${_e?e.health.state==="running"?" ok":e.health.state==="starting"?"":" ko":e.health.status==="healthy"?" ok":e.health.status==="passive"?"":" ko"}`,children:e.health.detail}),(()=>{const I=jP(e.health);return I?I.line?o.jsx(v_,{line:I.line,note:I.note}):o.jsx("small",{className:"nc-set-hint",children:I.note}):null})(),_&&o.jsxs("div",{className:`nc-set-test${_.ok?" ok":" ko"}`,children:[_.result,_.detail?` — ${_.detail}`:""]})]}),_e&&o.jsxs(Po,{title:f("node-detail-command"),children:[ze.length===0&&!kx(e)&&o.jsx("small",{className:"nc-set-hint",children:f("vl-no-commands")}),P&&o.jsxs("div",{className:"nc-vl-prompt",children:[o.jsx("textarea",{value:A,maxLength:Sx,placeholder:f("vl-prompt-placeholder"),"aria-label":f("vl-prompt-placeholder"),disabled:!!u||s,onChange:I=>T(I.target.value)}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:!!u||s||!A.trim(),onClick:Q,children:f("vl-prompt-send")})]}),Je&&o.jsxs("div",{className:`nc-set-test${Je.phase==="done"?Je.status==="ok"?" ok":" ko":""}`,children:[Je.kind&&`${He(Je.kind)}: `,Je.phase==="submitted"&&f("vl-cmd-phase-submitted"),Je.phase==="inflight"&&f("vl-cmd-phase-inflight"),Je.phase==="done"&&f(Je.status==="ok"?"vl-cmd-phase-done-ok":"vl-cmd-phase-done-error"),Je.phase==="done"&&((X=Je.result)!=null&&X.detail)?` — ${Je.result.detail}`:""]})]}),o.jsxs(Po,{title:f("node-detail-authority"),children:[o.jsx("div",{className:"nc-set-info",children:f(re.key)}),re.grants.length===0&&o.jsx("small",{className:"nc-set-hint",children:f(pe?"authority-no-grants":"authority-no-grants-elsewhere")})]}),o.jsxs(Po,{title:f("node-detail-network-view"),children:[o.jsx("div",{className:"nc-set-info",children:f(_e?oe.key:oe.shared?"peer-shared":"peer-private")}),ie&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"nc-field",children:[f("peer-visibility"),o.jsxs("select",{value:e.visibility||"network",disabled:s||!!u,onChange:I=>Z(I.target.value),children:[o.jsx("option",{value:"network",children:f("visibility-network")}),o.jsx("option",{value:"relay-only",children:f("visibility-relay")}),o.jsx("option",{value:"selected",children:f("visibility-selected")})]})]}),e.visibility==="selected"&&o.jsxs("div",{className:"nc-detail-grants",children:[je.length===0&&o.jsx("small",{className:"nc-set-hint",children:f("node-grant-none")}),je.map(I=>o.jsxs("div",{className:`nc-detail-grant${I.known?"":" unknown"}`,children:[o.jsxs("span",{children:[I.label,I.known?"":` — ${f("node-grant-unknown")}`]}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!u,onClick:()=>Z("selected",(e.selected||[]).filter(ce=>ce!==I.id)),children:f("node-grant-remove")})]},I.id)),!R&&o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!u,onClick:()=>{x(!0),E("")},children:f("node-grant-add")}),R&&o.jsxs("div",{className:"nc-detail-picker",children:[o.jsx("input",{value:j,placeholder:f("node-grant-search"),disabled:s||!!u,onChange:I=>E(I.target.value)}),o.jsxs("div",{className:"nc-detail-picker-list",children:[fe.length===0&&o.jsx("small",{className:"nc-set-hint",children:f("node-grant-no-candidates")}),fe.map(I=>o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!u,onClick:async()=>{await Z("selected",[...e.selected||[],I.id]),x(!1),E("")},children:I.label},I.id))]}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!u,onClick:()=>{x(!1),E("")},children:f("cancel")})]})]})]})]}),pe&&o.jsxs(Po,{title:f("cell-scope"),children:[o.jsx("small",{className:"nc-set-hint",children:f("cell-scope-help")}),o.jsx("label",{className:"nc-field",children:o.jsxs("select",{value:xe,"aria-label":f("cell-scope"),disabled:s||!!u,onChange:I=>{I.target.value==="selected"&&Ve(),ve(I.target.value)},children:[o.jsx("option",{value:"all",children:f("cell-scope-all")}),o.jsx("option",{value:"none",children:f("cell-scope-none")}),o.jsx("option",{value:"selected",children:f("cell-scope-selected")})]})}),xe==="selected"&&ot.length>0&&o.jsx("small",{className:"nc-set-hint",children:f("cell-scope-reset-warning")}),Y&&o.jsx("small",{className:"nc-set-hint",children:f("cell-scope-list-unavailable")}),xe==="selected"&&o.jsxs("div",{className:"nc-detail-grants",children:[ot.length===0&&o.jsx("small",{className:"nc-set-hint",children:f("cell-scope-none-granted")}),ot.map(I=>o.jsxs("div",{className:`nc-detail-grant${I.known?"":" unknown"}`,children:[o.jsxs("span",{children:[I.label,I.known?"":` — ${f("cell-scope-unknown")}`]}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!u,onClick:()=>ve("selected",(e.cells||[]).filter(ce=>ce!==I.id)),children:f("node-grant-remove")})]},I.id)),!V&&o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!u,onClick:async()=>{await Ve({retry:!0}),B(!0),se("")},children:f("cell-scope-add")}),V&&o.jsxs("div",{className:"nc-detail-picker",children:[o.jsx("input",{value:K,placeholder:f("cell-scope-search"),disabled:s||!!u,onChange:I=>se(I.target.value)}),o.jsxs("div",{className:"nc-detail-picker-list",children:[rt.length===0&&o.jsx("small",{className:"nc-set-hint",children:f("cell-scope-no-candidates")}),rt.map(I=>o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!u,onClick:async()=>{await ve("selected",[...e.cells||[],I.id]),B(!1),se("")},children:I.label},I.id))]}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!u,onClick:()=>{B(!1),se("")},children:f("cancel")})]})]})]}),Be&&c!=null&&!_e&&o.jsxs(Po,{title:f("peer-access"),children:[o.jsx("small",{className:"nc-set-hint",children:f("peer-access-help")}),o.jsxs("div",{className:"nc-set-info",children:[f("peer-access-current"),": ",o.jsx("b",{children:f(`access-label-${Be.label}`)})]}),o.jsx("label",{className:"nc-field",children:o.jsxs("select",{value:L||"","aria-label":f("peer-access-preset"),disabled:s||!!u,title:s?f("settings-readonly"):void 0,onChange:I=>H(I.target.value||null),children:[o.jsx("option",{value:"",children:f("peer-access-preset-none")}),x4.map(I=>o.jsx("option",{value:I,children:f(`access-label-${I}`)},I))]})}),L&&(()=>{const I=C4(Be.grants,L,e.eventsReceive),ce=I.filter(ye=>ye.changed).length;return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"nc-access-matrix",role:"table","aria-label":f("peer-access-matrix"),children:I.map(ye=>o.jsxs("div",{role:"row",className:`nc-access-row${ye.changed?" changed":""}`,children:[o.jsx("span",{role:"rowheader",children:f(`access-grant-${ye.key}`)}),o.jsx("span",{children:f(`access-value-${ye.current===!0?"yes":ye.current===!1?"no":String(ye.current)}`)}),o.jsx("span",{"aria-hidden":"true",children:"→"}),o.jsx("span",{children:f(`access-value-${ye.next===!0?"yes":ye.next===!1?"no":String(ye.next)}`)})]},ye.key))}),o.jsx("small",{className:"nc-set-hint",children:f(ce===0?"peer-access-unchanged":"peer-access-changed-hint")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:s||!!u,title:s?f("settings-readonly"):void 0,onClick:()=>ke(L),children:f("peer-access-apply")})]})})()]}),w&&o.jsxs(Po,{title:f("edit"),children:[o.jsxs("label",{className:"nc-field",children:[f("node-display-label"),o.jsx("input",{value:w.label,disabled:!!u,onChange:I=>S({...w,label:I.target.value})})]}),U.inbound?o.jsxs("label",{className:"nc-field",children:[f("peer-visibility"),o.jsxs("select",{value:w.visibility,disabled:!!u,onChange:I=>S({...w,visibility:I.target.value}),children:[o.jsx("option",{value:"network",children:f("visibility-network")}),o.jsx("option",{value:"relay-only",children:f("visibility-relay")}),o.jsx("option",{value:"selected",children:f("visibility-selected")})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"nc-field",children:[f("node-ssh-label"),o.jsx("input",{value:w.ssh,disabled:!!u,onChange:I=>S({...w,ssh:I.target.value})})]}),o.jsxs("label",{className:"nc-field",children:[f("node-ssh-port-label"),o.jsx("input",{inputMode:"numeric",value:w.sshPort,disabled:!!u,onChange:I=>S({...w,sshPort:I.target.value.replace(/[^0-9]/g,"").slice(0,5)})})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:w.autostart,disabled:!!u,onChange:I=>S({...w,autostart:I.target.checked})})," ",f("boot-persist")]})]}),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn primary",disabled:!!u,onClick:ge,children:f("save")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!u,onClick:()=>S(null),children:f("cancel")})]})]}),N&&o.jsxs("div",{className:"nc-set-confirm",children:[o.jsx("b",{children:f("node-remove-confirm").replace("{name}",U.title)}),o.jsx("small",{children:f("node-remove-warning")}),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn danger",disabled:!!u,onClick:()=>Me(`${e.name}:remove`,async()=>{await G5(n,e.name),C(!1),await i(),l&&l()}),children:f("delete")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!u,onClick:()=>C(!1),children:f("cancel")})]})]}),p&&o.jsx("div",{className:"nc-err",children:p})]})}function D4(e,t){y.useEffect(()=>{if(typeof document>"u"||!document.addEventListener){const u=setInterval(e,t);return()=>clearInterval(u)}let n=null;const s=()=>document.visibilityState!=="hidden",i=()=>{n!==null&&(clearInterval(n),n=null)},l=()=>{n===null&&s()&&(n=setInterval(e,t))},c=()=>{s()?(i(),e(),l()):i()};return l(),document.addEventListener("visibilitychange",c),()=>{i(),document.removeEventListener("visibilitychange",c)}},[e,t])}const tv="nexuscrew.fleet",UE=3,O4="nexuscrew.cells",WE=/^[A-Za-z0-9._-]{1,32}$/,Mh=/^[a-z0-9._-]{1,32}$/,qE=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,KE=new Set(["standard","unsafe"]),B4=4096,$4=4096,nh=256,VE=8192,z4=4096,F4=32,H4=64,vd=100,U4=128,W4=new Set(["format","version","exportedAt","cells","engines","models"]),q4=new Set(["id","cwdRel","engine","boot","model","models","permissionPolicies","commands","systemPrompt","prompt","label","mcp"]),K4=new Set(["id","cwd","engine","boot","model","models","permissionPolicies","systemPrompt","prompt"]);function $o(e){if(typeof e!="string"||e.length>$4)return null;for(let n=0;n<e.length;n+=1){const s=e.charCodeAt(n);if(s<=31||s===127||s===92)return null}if(e==="")return"";if(e.charAt(0)==="/"||/^[A-Za-z]:/.test(e))return null;const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n==="..")return null;t.push(n)}return t.join("/")}const V4=new Set(["id","label","rc","managed","command","args","envKeys","model","promptMode","promptFlag","panelUrl"]),G4=new Set(["client","provider","credentialProfile","model","permissionPolicy","displayName","protocol","baseUrl","envKey","providerId"]),Y4=new Set(["127.0.0.1","localhost","[::1]"]);function w_(e){if(typeof e!="string"||!e||e.length>512||/[\x00-\x1f\x7f]|\s/.test(e))return!1;let t;try{t=new URL(e)}catch{return!1}return!(t.protocol!=="http:"&&t.protocol!=="https:"||!Y4.has(t.hostname))}function Nr(e,t){return typeof e=="string"&&e.length<=t&&!/[\x00-\x1f\x7f]/.test(e)}function S_(e){const t=String(e||"");return/(?:bearer\s+|authorization\s*[:=]|(?:api[_-]?key|secret|token)\s*[:=])/i.test(t)||/^-{1,2}(?:api[-_]?key|access[-_]?key|auth(?:orization)?[-_]?token|token|secret|password|credential)(?:$|=)/i.test(t)||/\b(?:sk|fw|fpk|hf|zai)[-_][A-Za-z0-9._-]{8,}\b/i.test(t)||/https?:\/\/[^\s/@:]+:[^\s/@]+@/i.test(t)}function Nc(e,t){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))return null;const n=Object.entries(e);if(n.length>128)return null;const s={};for(const[i,l]of n){if(!Mh.test(i)||!t(l))return null;s[i]=l}return s}function GE(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(u=>!q4.has(u))||!WE.test(String(e.id||""))||typeof e.cwdRel!="string")return null;const t=$o(e.cwdRel);if(t===null||!Mh.test(String(e.engine||""))||e.boot!==void 0&&typeof e.boot!="boolean"||e.model!==void 0&&(typeof e.model!="string"||e.model.length>nh)||e.systemPrompt!==void 0&&e.prompt!==void 0&&e.systemPrompt!==e.prompt)return null;const n=e.systemPrompt===void 0?e.prompt===void 0?"":e.prompt:e.systemPrompt;if(typeof n!="string"||n.length>VE)return null;const s=Nc(e.models,u=>typeof u=="string"&&!!u&&u.length<=nh),i=Nc(e.permissionPolicies,u=>KE.has(u)),l=Nc(e.commands,u=>Nr(u,z4)&&!S_(u));if(s===null||i===null||l===null)return null;const c={id:e.id,cwdRel:t,engine:e.engine,boot:e.boot===!0,systemPrompt:n};if(e.model&&(c.model=e.model),e.label!==void 0){if(!Nr(e.label,H4)||!String(e.label).trim())return null;c.label=String(e.label).trim()}return Object.keys(s).length&&(c.models=s),Object.keys(i).length&&(c.permissionPolicies=i),Object.keys(l).length&&(c.commands=l),c}function X4(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(l=>!K4.has(l))||!WE.test(String(e.id||""))||typeof e.cwd!="string"||!e.cwd||e.cwd.length>B4||!Mh.test(String(e.engine||""))||e.boot!==void 0&&typeof e.boot!="boolean"||e.model!==void 0&&(typeof e.model!="string"||e.model.length>nh)||e.systemPrompt!==void 0&&e.prompt!==void 0&&e.systemPrompt!==e.prompt)return null;const t=e.systemPrompt===void 0?e.prompt===void 0?"":e.prompt:e.systemPrompt;if(typeof t!="string"||t.length>VE)return null;const n=Nc(e.models,l=>typeof l=="string"&&!!l&&l.length<=nh),s=Nc(e.permissionPolicies,l=>KE.has(l));if(n===null||s===null)return null;const i={id:e.id,cwd:e.cwd,engine:e.engine,boot:e.boot===!0,systemPrompt:t};return e.model&&(i.model=e.model),Object.keys(n).length&&(i.models=n),Object.keys(s).length&&(i.permissionPolicies=s),i}function J4(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(n=>!G4.has(n)))return null;const t={};for(const[n,s]of Object.entries(e)){if(typeof s!="string"||!Nr(s,n==="baseUrl"?512:128)||S_(s))return null;t[n]=s}return!t.client||!t.provider||t.envKey&&!qE.test(t.envKey)?null:t}function YE(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(s=>!V4.has(s))||!Mh.test(String(e.id||""))||!Nr(e.label||e.id,64)||e.rc!==void 0&&typeof e.rc!="boolean"||e.panelUrl!==void 0&&!w_(e.panelUrl))return null;const t={id:e.id,label:e.label||e.id,rc:e.rc===!0};if(e.panelUrl!==void 0&&(t.panelUrl=e.panelUrl),e.managed!==void 0){const s=J4(e.managed);return!s||["command","args","envKeys","model","promptMode","promptFlag"].some(i=>e[i]!==void 0)?null:(t.managed=s,t)}if(!Nr(e.command,512)||!e.command.startsWith("/")||!Array.isArray(e.args)||e.args.length>32||e.args.some(s=>!Nr(s,1024)||S_(s))||e.promptMode!=="flag"&&e.promptMode!=="send-keys"||e.promptMode==="flag"&&(!Nr(e.promptFlag,32)||/\s/.test(e.promptFlag)))return null;if(e.model!==void 0){if(!e.model||typeof e.model!="object"||Array.isArray(e.model)||Object.keys(e.model).some(s=>s!=="flag"&&s!=="value")||!Nr(e.model.flag,32)||/\s/.test(e.model.flag)||!Nr(e.model.value||"",128))return null;t.model={flag:e.model.flag,value:e.model.value||""}}const n=e.envKeys===void 0?[]:e.envKeys;return!Array.isArray(n)||n.length>32||n.some(s=>!qE.test(s))?null:(Object.assign(t,{command:e.command,args:[...e.args],envKeys:[...new Set(n)].sort(),promptMode:e.promptMode}),e.promptMode==="flag"&&(t.promptFlag=e.promptFlag),t)}function XE(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.managed?{id:e.id,label:e.label,rc:e.rc,managed:e.managed,...e.panelUrl!==void 0?{panelUrl:e.panelUrl}:{}}:{id:e.id,label:e.label,rc:e.rc,command:e.command,args:e.args,envKeys:e.envKeys,model:e.model,promptMode:e.promptMode,promptFlag:e.promptFlag,...e.panelUrl!==void 0?{panelUrl:e.panelUrl}:{}},n=YE(t);return n||null}function Q4(e,t,n){const s=new Set;for(const i of Array.isArray(t)?t:[]){if(!n.has(i.id)||!i.managed)continue;const{client:l,provider:c,credentialProfile:u}=i.managed;s.add(u?`${l}.${c}-${u}`:`${l}.${c}`),s.add(`${l}.${c}`)}return(Array.isArray(e)?e:[]).filter(i=>i&&s.has(i.engine))}function Z4(e,t,n=[],s=[],i=new Date,l=[]){n instanceof Date&&(i=n,n=[],s=[]);const c=t instanceof Set?t:new Set(t||[]),u=s instanceof Set?s:new Set(s||[]),h=[];for(const _ of Array.isArray(e)?e:[]){if(!c.has(_.id))continue;const g=GE({id:_.id,cwdRel:_.cwdRel,engine:_.engine,boot:_.boot===!0,..._.label?{label:_.label}:{},..._.model?{model:_.model}:{},..._.models?{models:_.models}:{},..._.permissionPolicies?{permissionPolicies:_.permissionPolicies}:{},systemPrompt:_.prompt||"",..._.commands?{commands:_.commands}:{}});if(!g)return{ok:!1,error:"invalid-cell",invalidCellIds:[_.id]};h.push(g)}const p=[];for(const _ of Array.isArray(n)?n:[]){if(!u.has(_.id))continue;const g=XE(_);g&&p.push(g)}const v=Q4(l,n,u);return{format:tv,version:UE,exportedAt:i.toISOString(),cells:h,engines:p,...v.length?{models:v}:{}}}function eO(e){let t;try{t=JSON.parse(String(e||""))}catch{return{ok:!1,error:"invalid-json",cells:[],engines:[]}}const n=(t==null?void 0:t.format)===O4&&(t==null?void 0:t.version)===1,s=(t==null?void 0:t.format)===tv&&(t==null?void 0:t.version)===2,i=(t==null?void 0:t.format)===tv&&(t==null?void 0:t.version)===UE,l=n||s,c=s||i;if(c&&Array.isArray(t.engines)&&t.engines.length>vd)return{ok:!1,error:"invalid-format",detail:`${t.engines.length} engine dichiarati, cap ${vd}; riduci gli engine a ${vd} o meno`,cells:[],engines:[]};if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(g=>!W4.has(g))||!n&&!s&&!i||!Array.isArray(t.cells)||t.cells.length>F4||c&&(!Array.isArray(t.engines)||t.engines.length>vd))return{ok:!1,error:"invalid-format",cells:[],engines:[]};const u=[],h=new Set;for(const g of t.cells){const w=l?X4(g):GE(g);if(!w)return{ok:!1,error:"invalid-cell",cells:[],engines:[]};if(h.has(w.id))return{ok:!1,error:"duplicate-cell",cells:[],engines:[]};h.add(w.id),u.push(w)}const p=[],v=new Set;for(const g of c?t.engines:[]){const w=YE(g);if(!w)return{ok:!1,error:"invalid-engine",cells:[],engines:[]};if(v.has(w.id))return{ok:!1,error:"duplicate-engine",cells:[],engines:[]};v.add(w.id),p.push(w)}const _=[];if(t.models!==void 0){if(!Array.isArray(t.models)||t.models.length>U4)return{ok:!1,error:"invalid-model",cells:[],engines:[]};const g=new Set;for(const w of t.models){if(!w||typeof w!="object"||Array.isArray(w))return{ok:!1,error:"invalid-model",cells:[],engines:[]};const S=new Set(["id","engine","label","contextWindow","maxTokens","tools","vision","reasoning"]);if(Object.keys(w).some(E=>!S.has(E)))return{ok:!1,error:"invalid-model",cells:[],engines:[]};const N=typeof w.id=="string"?w.id.trim():"",C=typeof w.engine=="string"?w.engine.trim():"";if(!N||!C)return{ok:!1,error:"invalid-model",cells:[],engines:[]};for(const E of["contextWindow","maxTokens"])if(w[E]!==void 0&&(!Number.isSafeInteger(w[E])||w[E]<1024||w[E]>1e8))return{ok:!1,error:"invalid-model",cells:[],engines:[]};for(const E of["tools","vision","reasoning"])if(w[E]!==void 0&&typeof w[E]!="boolean")return{ok:!1,error:"invalid-model",cells:[],engines:[]};const j=`${C}::${N}`;if(g.has(j))return{ok:!1,error:"duplicate-model",cells:[],engines:[]};g.add(j),_.push({...w,id:N,engine:C})}}return{ok:!0,cells:u,engines:p,models:_,legacy:l,exportedAt:typeof t.exportedAt=="string"?t.exportedAt:""}}function tO(e,t,n){const s=new Set(n||[]);if(!s.has(t))return null;const i=p=>Object.fromEntries(Object.entries(p||{}).filter(([v])=>s.has(v))),l={id:e.id,engine:t,boot:e.boot===!0,prompt:e.systemPrompt||""};typeof e.label=="string"&&e.label&&(l.label=e.label),typeof e.cwdRel=="string"?l.cwdRel=e.cwdRel:typeof e.cwd=="string"&&e.cwd&&(l.cwd=e.cwd),t===e.engine&&e.model?l.model=e.model:e.models&&e.models[t]&&(l.model=e.models[t]);const c=i(e.models),u=i(e.permissionPolicies),h=i(e.commands);return Object.keys(c).length&&(l.models=c),Object.keys(u).length&&(l.permissionPolicies=u),Object.keys(h).length&&(l.commands=h),l}const nO=()=>({kind:"managed",id:"claude.native",label:"",client:"claude",provider:"native",credentialProfile:"",managedModel:"",permissionPolicy:"unsafe",credentialSourcePolicy:"auto",displayName:"",protocol:"anthropic_messages",baseUrl:"",envKey:"",providerId:"nexuscrew-custom",vlBinary:"",vlConfigFile:"",vlProfile:"",effort:"",command:"",argsText:"",rc:!0,promptMode:"send-keys",promptFlag:"",modelFlag:"",modelValue:"",envRows:[],credentialValue:"",credentialReveal:!1,allowMissingCredential:!1,panelUrl:""}),Cx=(e="")=>({id:"",cwd:"",engine:e,boot:!1,label:"",model:"",prompt:"",commands:{},command:"",panelUrl:""}),JE=e=>e==="claude"?"unsafe":"standard",qc=(e,t)=>e.find(n=>n.client===t.client&&n.provider===t.provider&&(n.credentialProfile||"")===(t.credentialProfile||"")),sO=(e,t)=>{var n;return((n=qc(e,t))==null?void 0:n.label)||`${t.client} · ${t.provider}`};function iO(e){var t,n,s,i,l,c,u,h,p,v,_,g,w,S,N,C,j,E,R;return{kind:e.managed?"managed":"custom",id:e.id,label:e.label||"",command:e.command||"",argsText:(e.args||[]).join(`
165
+ `),rc:!!e.rc,client:((t=e.managed)==null?void 0:t.client)||"claude",provider:((n=e.managed)==null?void 0:n.provider)||"native",credentialProfile:((s=e.managed)==null?void 0:s.credentialProfile)||"",managedModel:((i=e.managed)==null?void 0:i.model)||"",permissionPolicy:((l=e.managed)==null?void 0:l.permissionPolicy)||JE((c=e.managed)==null?void 0:c.client),credentialSourcePolicy:((u=e.managed)==null?void 0:u.credentialSourcePolicy)||"auto",displayName:((h=e.managed)==null?void 0:h.displayName)||"",protocol:((p=e.managed)==null?void 0:p.protocol)||"",baseUrl:((v=e.managed)==null?void 0:v.baseUrl)||"",envKey:((_=e.managed)==null?void 0:_.envKey)||"",providerId:((g=e.managed)==null?void 0:g.providerId)||"nexuscrew-custom",vlBinary:((w=e.managed)==null?void 0:w.vlBinary)||"",vlConfigFile:((S=e.managed)==null?void 0:S.vlConfigFile)||"",vlProfile:((N=e.managed)==null?void 0:N.vlProfile)||"",effort:((C=e.managed)==null?void 0:C.effort)||"",modelOptions:e.availableModels||((j=e.managedInfo)==null?void 0:j.models)||[],promptMode:e.promptMode||"send-keys",promptFlag:e.promptFlag||"",modelFlag:((E=e.model)==null?void 0:E.flag)||"",modelValue:((R=e.model)==null?void 0:R.value)||"",envRows:(e.envKeys||[]).map(x=>({key:x,value:"",configured:!0,remove:!1})),credentialValue:"",credentialReveal:!1,allowMissingCredential:!1,panelUrl:e.panelUrl||""}}function Ex(e,t,n){const s=(t.panelUrl||"").trim();return n?s&&(e.panelUrl=s):e.panelUrl=s||null,e}function rO(e,t,n=[]){if(e.kind==="managed"){const i={client:e.client,provider:e.provider,model:e.client==="shell"?"":e.managedModel||"",permissionPolicy:e.client==="shell"?"standard":e.permissionPolicy||JE(e.client)};if(e.credentialProfile&&(i.credentialProfile=e.credentialProfile),e.credentialSourcePolicy&&e.credentialSourcePolicy!=="auto"&&(i.credentialSourcePolicy=e.credentialSourcePolicy),e.client==="vl")for(const c of["vlBinary","vlConfigFile","vlProfile","effort"]){const u=(e[c]||"").trim();u&&(i[c]=u)}const l=qc(n,e);return(l==null?void 0:l.credentialEnv)===!0&&(i.envKey=e.envKey),e.provider==="custom"&&Object.assign(i,{displayName:e.displayName,protocol:e.protocol,baseUrl:e.baseUrl,envKey:e.envKey,providerId:e.providerId}),Ex({...t?{id:e.id}:{},label:e.label||sO(n,e),rc:!!e.rc,managed:i},e,t)}const s={...t?{id:e.id}:{},label:e.label||e.id,rc:!!e.rc,command:e.command,args:e.argsText.split(`
166
+ `).filter(i=>i!==""),promptMode:e.promptMode};return e.modelFlag&&(s.model={flag:e.modelFlag,value:e.modelValue||""}),e.promptMode==="flag"&&(s.promptFlag=e.promptFlag),t&&(s.env=Object.fromEntries(e.envRows.filter(i=>!i.remove&&i.key).map(i=>[i.key,i.value]))),Ex(s,e,t)}function to({children:e,onClose:t,label:n,error:s=""}){const i=y.useRef(null),l=y.useRef(null),c=y.useRef(t);return c.current=t,y.useEffect(()=>{const u=document.activeElement,h=i.current,p=()=>Array.from((h==null?void 0:h.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'))||[]).filter(g=>g.offsetParent!==null),v=requestAnimationFrame(()=>{var g;return(g=p()[0]||h)==null?void 0:g.focus({preventScroll:!0})}),_=g=>{var C;if(g.key==="Escape"){g.preventDefault(),(C=c.current)==null||C.call(c);return}if(g.key!=="Tab")return;const w=p();if(!w.length){g.preventDefault(),h==null||h.focus();return}const S=w[0],N=w[w.length-1];g.shiftKey&&document.activeElement===S?(g.preventDefault(),N.focus()):!g.shiftKey&&document.activeElement===N&&(g.preventDefault(),S.focus())};return document.addEventListener("keydown",_),()=>{cancelAnimationFrame(v),document.removeEventListener("keydown",_),u&&u.isConnected&&typeof u.focus=="function"&&u.focus({preventScroll:!0})}},[]),y.useEffect(()=>{s&&requestAnimationFrame(()=>{var u;return(u=l.current)==null?void 0:u.scrollIntoView({block:"nearest"})})},[s]),o.jsx("div",{className:"nc-fleet-modal",role:"presentation",onMouseDown:u=>{u.target===u.currentTarget&&t()},children:o.jsxs("div",{ref:i,className:"nc-fleet-modal-dialog",role:"dialog","aria-modal":"true","aria-label":n||f("settings"),tabIndex:-1,children:[e,s&&o.jsx("div",{ref:l,className:"nc-err nc-fleet-modal-error",role:"alert","aria-live":"assertive",children:s})]})})}function Sm({token:e,targets:t=[],readonly:n=!1,onPower:s,onImport:i}){const[l,c]=y.useState([]),[u,h]=y.useState(0);y.useEffect(()=>{let C=!0;async function j(){const R=[{route:[],label:f("local")}].concat((t||[]).map(W=>({route:Array.isArray(W.route)?W.route:[],label:W.label||(W.route||[]).join(" › ")}))),x=await Promise.all(R.map(async W=>{const $={...W,available:!1,readonly:!1,capabilities:[],provider:null,cells:[],unmanaged:[],err:""};try{const Y=await rl(e,W.route);$.available=!!Y.available,$.capabilities=Y.capabilities||[],$.provider=Y.provider||null,$.cells=(Y.cells||[]).map(q=>({...q,route:W.route}));try{$.readonly=!!(await Yc(e,W.route)).readonlyDefault}catch{}try{const q=await bv(e,W.route),K=new Set($.cells.map(se=>se.tmuxSession).filter(Boolean));$.unmanaged=(q.sessions||[]).filter(se=>se&&!K.has(se.name))}catch{}}catch(Y){$.err=String(Y&&Y.message||Y)}return $}));C&&c(x)}j();const E=setInterval(j,6e3);return()=>{C=!1,clearInterval(E)}},[e,t,u]);const p=(C,j)=>Array.isArray(C.capabilities)&&C.capabilities.includes(j)&&!n&&!C.readonly,v=()=>h(C=>C+1),_=(C,j)=>{s&&s({...C,route:j})},g=(C,j)=>{s&&s({...C,route:j})},w=async(C,j)=>{try{await uc(e,C.cell,j)}catch{}v()},S=async(C,j)=>{if(window.confirm(f("fleet-remove-cell").replace("{id}",C.cell))){try{await f1(e,C.cell,!0,j)}catch{}v()}},N=async(C,j)=>{if(window.confirm(f("terminate-confirm").replace("{name}",C.name))){try{await _v(e,C.name,j)}catch{}v()}};return o.jsxs("div",{className:"nc-fleet-inventory",children:[o.jsxs("div",{className:"nc-fleet-section-head",children:[o.jsx("b",{children:f("fleet-inventory")}),o.jsx("small",{children:f("fleet-inventory-help")})]}),l.map(C=>{const j=C.route.length?C.route.join("/"):"local";return o.jsxs("div",{className:"nc-fleet-pos",children:[o.jsxs("div",{className:"nc-fleet-pos-title",children:[o.jsx("span",{className:`dot ${C.available?"on":"warn"}`}),o.jsx("b",{children:C.label}),o.jsx("small",{children:C.available?`${C.cells.length} ${f("fleet-cells")} · ${C.unmanaged.length} ${f("fleet-tmux")}`:C.err||f("fleet-not-available")})]}),C.cells.map(E=>o.jsxs("div",{className:"nc-fleet-item nc-fleet-cell",children:[o.jsxs("span",{children:[o.jsx("b",{children:E.cell}),o.jsx("small",{children:`${E.engine||""}${E.key?`·${E.key}`:""}${E.active?"":` · ${f("cell-off")}`}`})]}),o.jsxs("span",{className:"nc-fleet-cell-actions",children:[E.active&&p(C,"down")&&o.jsx("button",{className:"nc-btn ghost",title:f("power-off"),onClick:()=>g(E,C.route),children:f("stop")}),!E.active&&p(C,"up")&&o.jsx("button",{className:"nc-btn ghost",title:f("power-on"),onClick:()=>_(E,C.route),children:f("start")}),p(C,"restart")&&E.active&&o.jsx("button",{className:"nc-btn ghost",title:f("restart"),onClick:()=>w(E,C.route),children:f("restart")}),p(C,"remove")&&o.jsx("button",{className:"nc-btn danger",title:f("delete"),onClick:()=>S(E,C.route),children:"×"})]})]},`${j}:${E.cell}`)),C.unmanaged.map(E=>o.jsxs("div",{className:"nc-fleet-item nc-fleet-unmanaged",children:[o.jsxs("span",{children:[o.jsx("b",{children:E.name}),o.jsx("small",{children:f("fleet-tmux")})]}),o.jsxs("span",{className:"nc-fleet-cell-actions",children:[p(C,"import")&&i&&o.jsx("button",{className:"nc-btn ghost",title:f("import-as-cell"),onClick:()=>i(E,C.route),children:f("import-as-cell")}),o.jsx("button",{className:"nc-btn danger",title:f("terminate"),onClick:()=>N(E,C.route),children:"×"})]})]},`${j}:u:${E.name}`)),C.available&&C.cells.length===0&&C.unmanaged.length===0&&o.jsx("div",{className:"nc-empty",children:f("fleet-inventory-empty")})]},j)})]})}function oO({cells:e=[],engines:t=[],models:n=[],busy:s,canRestore:i=!1,onRestore:l,onClose:c}){const[u,h]=y.useState("export"),[p,v]=y.useState([]),[_,g]=y.useState(()=>new Set(e.map(z=>z.id))),[w,S]=y.useState(()=>new Set(t.map(z=>z.id))),[N,C]=y.useState([]),[j,E]=y.useState([]),[R,x]=y.useState(""),W=new Set(t.map(z=>z.id)),$=new Set(e.map(z=>z.id)),Y=(z,A)=>z(T=>{const L=new Set(T);return L.has(A)?L.delete(A):L.add(A),L}),q=()=>{const z=Z4(e,_,t,w,new Date,n);if(z.ok===!1){x(f(`fleet-backup-${z.error}`));return}const A=e.filter(U=>_.has(U.id)).length,T=t.filter(U=>w.has(U.id)).length;if(z.cells.length!==A){x(f("fleet-backup-invalid-cell"));return}if(z.engines.length!==T){x(f("fleet-backup-invalid-engine"));return}if(!z.cells.length&&!z.engines.length){x(f("fleet-backup-select-one"));return}const L=new Blob([`${JSON.stringify(z,null,2)}
167
+ `],{type:"application/json"}),H=URL.createObjectURL(L),M=document.createElement("a");M.href=H,M.download=`nexuscrew-fleet-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(M),M.click(),M.remove(),setTimeout(()=>URL.revokeObjectURL(H),0),x("")},K=async z=>{if(x(""),C([]),E([]),!!z){if(z.size>1024*1024){x(f("fleet-backup-too-large"));return}try{const A=eO(await z.text());if(!A.ok){x(f(`fleet-backup-${A.error}`));return}v(Array.isArray(A.models)?A.models:[]);const T=new Set(A.engines.map(L=>L.id));E(A.engines.map(L=>({engine:L,exists:W.has(L.id),selected:!W.has(L.id)}))),C(A.cells.map(L=>{const H=W.has(L.engine)||T.has(L.engine),M=$.has(L.id);return{cell:L,engine:H?L.engine:"",selected:H&&!M,exists:M}}))}catch(A){x(String(A.message||A))}}},se=(z,A)=>C(T=>T.map((L,H)=>H===z?{...L,...A}:L)),V=(z,A)=>E(T=>T.map((L,H)=>H===z?{...L,...A}:L)),B=new Set([...W,...j.filter(z=>z.selected).map(z=>z.engine.id)]),D=N.filter(z=>z.selected&&z.engine&&B.has(z.engine)),O=j.filter(z=>z.selected),P=[...(()=>{const z=new Map(t.map(A=>[A.id,A]));for(const A of j)!A.selected||z.has(A.engine.id)||z.set(A.engine.id,A.engine);return z})().values()];return o.jsxs("div",{className:"nc-set-form nc-fleet-form nc-backup-dialog",children:[o.jsx("b",{children:f("fleet-backup")}),o.jsx("small",{children:f("fleet-backup-help")}),o.jsxs("div",{className:"nc-set-tabs nc-backup-tabs",children:[o.jsx("button",{type:"button",className:`nc-set-tabbtn${u==="export"?" on":""}`,onClick:()=>{h("export"),x("")},children:f("fleet-backup-export")}),o.jsx("button",{type:"button",className:`nc-set-tabbtn${u==="import"?" on":""}`,disabled:!i,title:i?"":f("fleet-backup-restore-unavailable"),onClick:()=>{h("import"),x("")},children:f("fleet-backup-import")})]}),u==="export"?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{g(new Set(e.map(z=>z.id))),S(new Set(t.map(z=>z.id)))},children:f("select-all")}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{g(new Set),S(new Set)},children:f("select-none")})]}),o.jsxs("div",{className:"nc-backup-list",children:[o.jsx("b",{children:f("fleet-engines")}),t.map(z=>{var A;return o.jsxs("label",{className:"nc-check nc-backup-row",children:[o.jsx("input",{type:"checkbox",checked:w.has(z.id),onChange:()=>Y(S,z.id)}),o.jsxs("span",{children:[o.jsx("b",{children:z.label||z.id}),o.jsxs("small",{children:[z.id,(A=z.envKeys)!=null&&A.length?` · ${z.envKeys.length} ${f("fleet-backup-env-names")}`:""]})]})]},z.id)}),o.jsx("b",{children:f("fleet-cells")}),e.map(z=>o.jsxs("label",{className:"nc-check nc-backup-row",children:[o.jsx("input",{type:"checkbox",checked:_.has(z.id),onChange:()=>Y(g,z.id)}),o.jsxs("span",{children:[o.jsx("b",{children:z.id}),o.jsxs("small",{children:[z.engine," · ",f("fleet-system-prompt")," ",(z.prompt||"").length," ",f("characters")]})]})]},z.id)),!e.length&&!t.length&&o.jsx("div",{className:"nc-empty",children:f("fleet-backup-empty")})]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:f("cancel")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:!_.size&&!w.size,onClick:q,children:f("fleet-backup-download")})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("input",{type:"file",accept:"application/json,.json",disabled:s,onChange:z=>K(z.target.files&&z.target.files[0])}),o.jsx("small",{children:f("fleet-backup-import-help")}),!!(N.length||j.length)&&o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{E(z=>z.map(A=>({...A,selected:!0}))),C(z=>z.map(A=>({...A,selected:!!A.engine})))},children:f("select-all")}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{E(z=>z.map(A=>({...A,selected:!1}))),C(z=>z.map(A=>({...A,selected:!1})))},children:f("select-none")})]}),o.jsxs("div",{className:"nc-backup-list",children:[!!j.length&&o.jsx("b",{children:f("fleet-engines")}),j.map((z,A)=>{var T;return o.jsx("div",{className:"nc-backup-import-row",children:o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:z.selected,onChange:L=>V(A,{selected:L.target.checked})}),o.jsxs("span",{children:[o.jsx("b",{children:z.engine.label||z.engine.id}),o.jsxs("small",{children:[z.engine.id," · ",z.exists?f("fleet-backup-overwrite"):f("fleet-backup-new"),(T=z.engine.envKeys)!=null&&T.length?` · ${f("fleet-backup-env-values-required")}`:""]})]})]})},z.engine.id)}),!!N.length&&o.jsx("b",{children:f("fleet-cells")}),N.map((z,A)=>o.jsxs("div",{className:"nc-backup-import-row",children:[o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:z.selected,disabled:!z.engine||!B.has(z.engine),onChange:T=>se(A,{selected:T.target.checked})}),o.jsxs("span",{children:[o.jsx("b",{children:z.cell.id}),o.jsxs("small",{children:[z.exists?f("fleet-backup-overwrite"):f("fleet-backup-new")," · ",f("fleet-system-prompt")," ",z.cell.systemPrompt.length," ",f("characters")]})]})]}),o.jsxs("select",{value:z.engine,onChange:T=>se(A,{engine:T.target.value,selected:!!T.target.value}),children:[o.jsx("option",{value:"",children:f("fleet-backup-engine-missing")}),o.jsx(xh,{engines:P})]})]},z.cell.id))]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:f("cancel")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:s||!D.length&&!O.length,onClick:()=>l({engineRows:j,cellRows:N,models:p}),children:f("fleet-backup-restore")})]})]}),R&&o.jsx("div",{className:"nc-err",children:R})]})}const QE=["contextWindow","maxTokens"],Th=["tools","vision","reasoning"],aO=1024,lO=1e8,cO=8,uO=/^[a-z0-9][a-z0-9-]{0,15}$/;function zo(e){const t=Number(e);return Number.isSafeInteger(t)&&t>=aO&&t<=lO}function x_(e){if(e==null)return{ok:!0,levels:void 0};let t;if(Array.isArray(e)?t=e.map(s=>String(s).trim()):t=String(e).split(",").map(s=>s.trim()).filter(Boolean),!t.length)return{ok:!0,levels:void 0};if(t.length>cO)return{ok:!1,error:"too-many-levels"};const n=new Set;for(const s of t){if(!uO.test(s))return{ok:!1,error:"invalid-level"};if(n.has(s))return{ok:!1,error:"duplicate-level"};n.add(s)}return{ok:!0,levels:t}}function ZE(e){const t=e&&typeof e=="object"?e:{},n={};for(const i of QE){const l=t[i];if(l==null)continue;const c=String(l).trim();c&&!zo(c)&&(n[i]="out-of-range")}for(const i of Th){const l=t[i];l==null||l===""||l!==!0&&l!==!1&&l!=="true"&&l!=="false"&&(n[i]="not-a-boolean")}const s=x_(t.effortLevels);return s.ok||(n.effortLevels=s.error),n}function Nx(e){const t=e&&typeof e=="object"?e:{},n=ZE(t);if(Object.keys(n).length){const l=new Error(`invalid model values: ${Object.keys(n).join(", ")}`);throw l.code="invalid-model-values",l.fields=n,l}const s={};for(const l of QE){const c=t[l];if(c==null)continue;const u=String(c).trim();if(!u)continue;const h=Number(u);zo(h)&&(s[l]=h)}for(const l of Th){const c=t[l];c===!0||c==="true"?s[l]=!0:(c===!1||c==="false")&&(s[l]=!1)}const i=x_(t.effortLevels);return i.levels&&(s.effortLevels=i.levels),s}const jx=[["contextWindow","fleet-models-field-context"],["maxTokens","fleet-models-field-output"],["tools","fleet-models-field-tools"],["vision","fleet-models-field-vision"],["reasoning","fleet-models-field-reasoning"]],dO=[["contextWindow","fleet-models-field-context"],["maxTokens","fleet-models-field-output"]],Lx={user:"fleet-models-source-user",api:"fleet-models-source-api",public:"fleet-models-source-public",backup:"fleet-models-source-backup"},hO=["missing-key","key-rejected","access-denied","credential-unavailable","endpoint-unreachable","provider-error","invalid-response","anonymous-success"];function fO(e,t){return e==="missing-key"&&!t?"fleet-models-auth-missing-key-anonymous":`fleet-models-auth-${e}`}function Rx({model:e,fields:t,busy:n,onConfirm:s,onCancel:i,mode:l,error:c="",writing:u=!1}){const[h,p]=y.useState(()=>Object.fromEntries(t.map(({field:S,value:N,backup:C})=>[S,N!=null?String(N):C!==void 0?String(C):""]))),v=l==="missing",_=ZE(h),g=Object.keys(_).length>0,w=v?f("fleet-models-missing-title"):f("fleet-models-make-mine-title").replace("{model}",e);return o.jsxs("div",{className:"nc-fleet-missing",role:"dialog","aria-label":w,children:[o.jsx("b",{className:v?"nc-err":void 0,children:w}),o.jsx("small",{children:v?f("fleet-models-missing-why").replace("{model}",e):f("fleet-models-make-mine-why")}),t.map(({field:S,label:N,backup:C})=>Th.includes(S)?o.jsxs("label",{className:"nc-field",children:[f(N),o.jsxs("select",{"aria-label":f(N),value:h[S]||"",disabled:n,onChange:j=>p({...h,[S]:j.target.value}),children:[o.jsx("option",{value:"",children:f("fleet-models-value-absent")}),o.jsx("option",{value:"true",children:f("fleet-models-value-true")}),o.jsx("option",{value:"false",children:f("fleet-models-value-false")})]})]},S):o.jsxs("label",{className:"nc-field",children:[f(N),o.jsx("input",{inputMode:"numeric",value:h[S]||"",disabled:n,"aria-label":f(N),placeholder:C!==void 0?String(C):"",autoComplete:"off",onChange:j=>p({...h,[S]:j.target.value.replace(/[^0-9]/g,"").slice(0,9)})}),_[S]&&o.jsx("small",{className:"nc-err",children:f("model-editor-limit-invalid")}),C!==void 0&&o.jsx("small",{className:"nc-fleet-models-note",children:f("fleet-models-missing-backup").replace("{value}",String(C))})]},S)),o.jsx("small",{children:f("fleet-models-missing-user")}),c&&o.jsx("small",{className:"nc-err nc-fleet-write-error",children:c}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||u,onClick:i,children:f(v?"fleet-models-missing-empty":"cancel")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||u||g,onClick:()=>s(h),children:f(v?"fleet-models-missing-confirm":"fleet-models-make-mine-confirm")})]})]})}function pO({engineId:e,fetchModels:t,onPick:n,activeModel:s,onSetModelValue:i,busy:l}){const[c,u]=y.useState({loading:!0,refreshing:!1,result:null,error:""}),h=y.useRef(t);h.current=t;const p=ee=>h.current(e,ee).then(re=>({loading:!1,refreshing:!1,result:re,error:""})).catch(()=>({loading:!1,refreshing:!1,result:null,error:f("fleet-models-error")}));y.useEffect(()=>{let ee=!0;return u({loading:!0,refreshing:!1,result:null,error:""}),p(!1).then(re=>{ee&&u(re)}),()=>{ee=!1}},[e]);const v=()=>{c.loading||c.refreshing||(u({...c,refreshing:!0}),h.current(e,!0).then(ee=>{u({loading:!1,refreshing:!1,result:ee,error:""})}).catch(()=>{u({loading:!1,refreshing:!1,result:c.result,error:f("fleet-models-error")})}))},_=String(s||"").trim(),g=c.result,w=g&&Array.isArray(g.models)?g.models:[],S=g&&g.auth&&typeof g.auth=="object"?g.auth:null,N=S&&hO.includes(S.cause)?S.cause:"",C=S&&typeof S.envKey=="string"?S.envKey:"",j=_?w.find(ee=>ee.id===_):null,E=!c.loading&&!c.error&&g&&_?dO.filter(([ee])=>!j||j[ee]===void 0).map(([ee,re])=>({field:ee,label:re,backup:j&&j.backupValues?j.backupValues[ee]:void 0})):[],R=`${_}:${E.map(ee=>ee.field).join(",")}`,x=y.useRef(""),[W,$]=y.useState(!1);y.useEffect(()=>{!E.length||!i||x.current!==R&&(x.current=R,$(!0))},[R,i]);const Y=()=>{$(!1),B("")},q=async(ee,re)=>{let oe;try{const je=await Promise.resolve(i(e,ee,re));oe=je&&je.ok===!1?{ok:!1,error:je.error||f("fleet-models-write-failed")}:{ok:!0}}catch(je){oe={ok:!1,error:String(je&&je.message||je)}}if(oe.ok){u({loading:!0,refreshing:!1,result:null,error:""});try{u(await p(!1))}catch{}}return oe},[K,se]=y.useState(!1),[V,B]=y.useState(""),D=async ee=>{B(""),se(!0);const re=await q(_,ee);se(!1),re.ok?$(!1):B(re.error)},[O,P]=y.useState(null),[z,A]=y.useState(!1),[T,L]=y.useState(""),H=async ee=>{const re=O&&O.model;if(!re)return;L(""),A(!0);const oe=await q(re,ee);A(!1),oe.ok?P(null):L(oe.error)},M=(ee,re,oe)=>{L(""),P({model:ee.id,fields:[{field:re,label:oe,value:ee[re]}]})},U=ee=>{L(""),P({model:ee.id,fields:jx.map(([re,oe])=>({field:re,label:oe,value:ee[re]}))})};return o.jsxs("section",{className:"nc-fleet-models","aria-label":f("fleet-models-title"),children:[o.jsxs("div",{className:"nc-fleet-models-head",children:[o.jsx("b",{children:f("fleet-models-usable")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:c.loading||c.refreshing,onClick:v,children:f(c.refreshing?"fleet-models-refreshing":"fleet-models-refresh")})]}),c.loading&&o.jsx("small",{children:f("fleet-models-loading")}),!c.loading&&c.error&&o.jsx("small",{className:"nc-err",children:c.error}),!c.loading&&!c.error&&g&&g.stale===!0&&o.jsx("small",{className:"nc-fleet-models-note",children:f("fleet-models-stale")}),!c.loading&&!c.error&&g&&g.supported!==!1&&N&&o.jsx("small",{className:"nc-fleet-models-note nc-fleet-models-auth",children:f(fO(N,C)).replace("{key}",C)}),!c.loading&&g&&g.supported===!1&&o.jsx("small",{children:f("fleet-models-unsupported")}),!c.loading&&g&&g.supported!==!1&&!w.length&&o.jsx("small",{children:f("fleet-models-none")}),W&&E.length>0&&o.jsx(Rx,{mode:"missing",model:_,fields:E,busy:l,onConfirm:D,onCancel:Y,error:V,writing:K}),O&&o.jsx(Rx,{mode:"edit",model:O.model,fields:O.fields,busy:l,onConfirm:H,onCancel:()=>P(null),error:T,writing:z}),!W&&E.length>0&&i&&o.jsx("button",{type:"button",className:"nc-btn ghost nc-fleet-missing-open",onClick:()=>$(!0),children:f("fleet-models-missing-open").replace("{model}",_)}),w.map(ee=>o.jsxs("div",{className:`nc-fleet-model-row${ee.inApi===!1?" nc-model-not-in-api":""}`,children:[o.jsx("button",{type:"button",className:"nc-btn ghost nc-fleet-model-pick","aria-label":f("fleet-models-use").replace("{model}",ee.id),onClick:()=>n(ee.id),children:ee.id}),ee.inApi===!1&&o.jsx("b",{className:"nc-err",children:f("fleet-models-not-in-api")}),jx.map(([re,oe])=>{const je=ee.fieldSources?ee.fieldSources[re]:void 0;return o.jsxs("span",{className:"nc-fleet-model-field",children:[f(oe),": ",ee[re]===void 0?"–":String(ee[re]),je==="public"?o.jsx("small",{className:"nc-fleet-model-src",title:f("fleet-models-source-of").replace("{source}",f("fleet-models-source-public")),children:f("fleet-models-default-badge")}):je&&o.jsx("small",{className:"nc-fleet-model-src",title:f("fleet-models-source-of").replace("{source}",f(Lx[je]||je)),children:f(Lx[je]||je)}),i&&o.jsx("button",{type:"button",className:"nc-btn ghost nc-fleet-model-mine","aria-label":f("fleet-models-make-mine-field").replace("{field}",f(oe)).replace("{model}",ee.id),onClick:()=>M(ee,re,oe),children:f("fleet-models-make-mine")})]},re)}),i&&o.jsx("button",{type:"button",className:"nc-btn ghost nc-fleet-model-mine-row","aria-label":f("fleet-models-make-mine-row").replace("{model}",ee.id),onClick:()=>U(ee),children:f("fleet-models-make-mine")})]},ee.id)),g&&g.supported!==!1&&o.jsx("small",{className:"nc-fleet-models-note",children:f("fleet-models-cap").replace("{cap}",String(g.cap||128))})]})}function mO({state:e,setState:t,busy:n,onSave:s,catalog:i,fetchModels:l,onSetModelValue:c}){var R;const u=e.form,h=x=>t({...e,form:{...u,...x}}),p=u.envRows||[],v=[...new Map(i.map(x=>[x.client,x.clientLabel||x.client])).entries()],_=i.filter(x=>x.client===u.client),g=qc(i,u),w=typeof(g==null?void 0:g.credentialEnv)=="string"?g.credentialEnv:"",S=Array.isArray(g==null?void 0:g.credentialUsedBy)?g.credentialUsedBy:[],N=(g==null?void 0:g.credentialSource)||"missing",C=!!(g!=null&&g.credentialEnv)||u.credentialProfile==="a"||u.credentialProfile==="p",j=!!w&&e.mode==="new"&&(g==null?void 0:g.authConfigured)!==!0&&!u.credentialValue&&!u.allowMissingCredential,E=x=>{x&&h({client:x.client,provider:x.provider,credentialProfile:x.credentialProfile||"",managedModel:x.model||"",protocol:x.protocol||"",permissionPolicy:x.permissionPolicyDefault||"standard",credentialSourcePolicy:"auto",rc:!!x.rc,displayName:x.custom?f("fleet-custom-provider-default"):"",baseUrl:x.custom?"":x.endpoint||"",envKey:x.defaultEnvKey||"",providerId:"nexuscrew-custom",credentialValue:"",credentialReveal:!1,allowMissingCredential:!1,...e.mode==="new"?{id:x.id,label:""}:{}})};return o.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[o.jsx("b",{children:e.mode==="new"?f("fleet-new-engine"):`${f("edit")} ${u.id}`}),o.jsx("input",{value:u.id,disabled:e.mode!=="new",placeholder:"id",onChange:x=>h({id:x.target.value})}),o.jsx("input",{value:u.label,placeholder:f("label"),onChange:x=>h({label:x.target.value})}),o.jsxs("select",{value:u.kind,disabled:e.mode!=="new",onChange:x=>h({kind:x.target.value}),children:[o.jsx("option",{value:"managed",children:f("fleet-managed")}),o.jsx("option",{value:"custom",children:f("fleet-custom")})]}),u.kind==="managed"?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"nc-fleet-pair",children:[o.jsx("select",{value:u.client,disabled:e.mode!=="new",onChange:x=>E(i.find(W=>W.client===x.target.value&&W.default)||i.find(W=>W.client===x.target.value)),children:v.map(([x,W])=>o.jsx("option",{value:x,children:W},x))}),o.jsx("select",{value:((R=qc(i,u))==null?void 0:R.id)||"",disabled:e.mode!=="new",onChange:x=>E(i.find(W=>W.id===x.target.value)),children:_.map(x=>o.jsx("option",{value:x.id,children:x.label},x.id))})]}),u.client!=="shell"&&o.jsxs(o.Fragment,{children:[o.jsx("input",{value:u.managedModel,list:"nc-managed-models",placeholder:f(g!=null&&g.requiresModel?"fleet-model-required":"fleet-model-default"),onChange:x=>h({managedModel:x.target.value})}),o.jsx("datalist",{id:"nc-managed-models",children:[...(g==null?void 0:g.models)||[],...u.modelOptions||[]].filter((x,W,$)=>x&&$.indexOf(x)===W).map(x=>o.jsx("option",{value:x},x))}),l&&(e.mode==="edit"?u.id:g==null?void 0:g.id)&&o.jsx(pO,{engineId:e.mode==="edit"?u.id:g==null?void 0:g.id,fetchModels:l,onPick:x=>h({managedModel:x}),activeModel:u.managedModel,onSetModelValue:c,busy:n})]}),g!=null&&g.supportsUnsafe?o.jsxs("select",{value:u.permissionPolicy,onChange:x=>h({permissionPolicy:x.target.value}),children:[o.jsx("option",{value:"standard",children:f("fleet-standard-permissions")}),o.jsx("option",{value:"unsafe",children:f("fleet-unsafe-permissions")})]}):o.jsx("small",{children:f("fleet-standard-permissions")}),(g==null?void 0:g.supportsUnsafe)&&u.permissionPolicy==="unsafe"&&o.jsx("small",{className:"nc-err",children:f("fleet-unsafe-warning")}),C&&o.jsxs("select",{"aria-label":f("fleet-credential-source-policy"),value:u.credentialSourcePolicy||"auto",onChange:x=>h({credentialSourcePolicy:x.target.value}),children:[o.jsx("option",{value:"auto",children:f("fleet-credential-source-policy-auto")}),o.jsx("option",{value:"nexuscrew-store",children:f("fleet-credential-source-policy-nexuscrew-store")}),o.jsx("option",{value:"environment",children:f("fleet-credential-source-policy-environment")})]}),(g==null?void 0:g.credentialEnv)===!0&&o.jsxs(o.Fragment,{children:[o.jsx("input",{value:u.envKey,placeholder:f("fleet-api-key-env"),onChange:x=>h({envKey:x.target.value})}),o.jsx("small",{children:f("fleet-custom-secret-help")})]}),w&&o.jsxs("section",{className:"nc-fleet-key","aria-label":f("fleet-key-section"),children:[o.jsxs("div",{className:"nc-fleet-key-head",children:[o.jsx("b",{children:f("fleet-key-section")}),o.jsx("span",{children:f(`fleet-credential-source-${N}`)})]}),o.jsxs("label",{className:"nc-field",children:[f("fleet-key-variable"),o.jsx("input",{value:w,readOnly:!0,"aria-label":f("fleet-key-variable")})]}),o.jsx("small",{children:S.length?f("fleet-key-used-by").replace("{engines}",S.join(", ")):f("fleet-key-used-by-none")}),S.length>0&&o.jsx("small",{children:f("fleet-key-shared-impact").replace("{key}",w).replace("{engines}",S.join(", "))}),o.jsxs("div",{className:"nc-fleet-key-input",children:[o.jsx("input",{type:u.credentialReveal?"text":"password",value:u.credentialValue||"","aria-label":f("fleet-key-value").replace("{key}",w),autoComplete:"new-password",spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",placeholder:g!=null&&g.authConfigured||e.mode==="edit"?f("fleet-key-blank-keeps"):f("fleet-key-enter"),onChange:x=>h({credentialValue:x.target.value,allowMissingCredential:x.target.value?!1:u.allowMissingCredential})}),o.jsx("button",{type:"button",className:"nc-btn ghost","aria-label":f(u.credentialReveal?"fleet-key-hide":"fleet-key-reveal"),onClick:()=>h({credentialReveal:!u.credentialReveal}),children:f(u.credentialReveal?"fleet-key-hide":"fleet-key-reveal")})]}),o.jsx("small",{children:f("fleet-key-local-help")}),e.mode==="new"&&(g==null?void 0:g.authConfigured)!==!0&&!u.credentialValue&&o.jsxs("label",{className:"nc-check nc-fleet-key-missing",children:[o.jsx("input",{type:"checkbox",checked:!!u.allowMissingCredential,onChange:x=>h({allowMissingCredential:x.target.checked})}),f("fleet-key-create-missing")]}),(g==null?void 0:g.notice)&&o.jsx("small",{className:"nc-fleet-provider-notice",children:f(`fleet-provider-notice-${g.notice}`)})]}),(g==null?void 0:g.notice)&&!w&&o.jsx("small",{className:"nc-fleet-provider-notice",children:f(`fleet-provider-notice-${g.notice}`)}),u.provider==="custom"&&o.jsxs(o.Fragment,{children:[o.jsx("input",{value:u.displayName,placeholder:f("fleet-provider-display"),onChange:x=>h({displayName:x.target.value})}),o.jsx("input",{value:u.baseUrl,placeholder:"https://api.example.com/v1",onChange:x=>h({baseUrl:x.target.value})}),((g==null?void 0:g.protocols)||[]).length>1&&o.jsx("select",{value:u.protocol,onChange:x=>h({protocol:x.target.value}),children:g.protocols.map(x=>o.jsx("option",{value:x,children:x},x))}),o.jsxs("div",{className:"nc-fleet-pair",children:[o.jsx("input",{value:u.envKey,placeholder:f("fleet-api-key-env"),onChange:x=>h({envKey:x.target.value})}),o.jsx("input",{value:u.providerId,placeholder:f("fleet-provider-id"),onChange:x=>h({providerId:x.target.value})})]}),o.jsxs("small",{children:[u.protocol," · ",f("fleet-custom-secret-help")]})]}),u.client==="vl"&&o.jsxs(o.Fragment,{children:[o.jsx("input",{value:u.vlBinary||"",placeholder:f("fleet-vl-binary"),onChange:x=>h({vlBinary:x.target.value})}),o.jsx("input",{value:u.vlConfigFile||"",placeholder:f("fleet-vl-config-file"),onChange:x=>h({vlConfigFile:x.target.value})}),o.jsxs("div",{className:"nc-fleet-pair",children:[o.jsx("input",{value:u.vlProfile||"",placeholder:f("fleet-vl-profile"),onChange:x=>h({vlProfile:x.target.value})}),o.jsx("input",{value:u.effort||"",placeholder:f("fleet-vl-effort"),onChange:x=>h({effort:x.target.value})})]}),o.jsx("small",{children:f("fleet-vl-fields-help")})]}),o.jsx("small",{children:f(u.client==="shell"?"fleet-shell-engine-help":"fleet-managed-help")})]}):o.jsxs(o.Fragment,{children:[o.jsx("input",{value:u.command,placeholder:f("command-path"),onChange:x=>h({command:x.target.value})}),o.jsx("textarea",{value:u.argsText,placeholder:f("args-lines"),onChange:x=>h({argsText:x.target.value})}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:u.rc,onChange:x=>h({rc:x.target.checked})})," ",f("fleet-remote-control")]}),o.jsxs("select",{value:u.promptMode,onChange:x=>h({promptMode:x.target.value}),children:[o.jsx("option",{value:"send-keys",children:"send-keys"}),o.jsx("option",{value:"flag",children:"flag"})]}),u.promptMode==="flag"&&o.jsx("input",{value:u.promptFlag,placeholder:"prompt flag",onChange:x=>h({promptFlag:x.target.value})}),o.jsxs("div",{className:"nc-fleet-pair",children:[o.jsx("input",{value:u.modelFlag,placeholder:"model flag",onChange:x=>h({modelFlag:x.target.value})}),o.jsx("input",{value:u.modelValue,placeholder:"model default",onChange:x=>h({modelValue:x.target.value})})]}),o.jsx("small",{children:f("env-write-only")}),p.map((x,W)=>o.jsxs("div",{className:"nc-fleet-env",children:[o.jsx("input",{value:x.key,disabled:x.configured,placeholder:"ENV_KEY",onChange:$=>{const Y=p.slice();Y[W]={...x,key:$.target.value},h({envRows:Y})}}),o.jsx("input",{type:"password",value:x.value,placeholder:x.configured?"•••••• (unchanged)":"value",onChange:$=>{const Y=p.slice();Y[W]={...x,value:$.target.value},h({envRows:Y})}}),o.jsx("button",{className:"nc-btn danger",onClick:()=>h({envRows:p.filter(($,Y)=>Y!==W)}),children:"×"})]},`${x.key}-${W}`)),o.jsx("button",{className:"nc-btn ghost",onClick:()=>h({envRows:[...p,{key:"",value:"",configured:!1}]}),children:"+ env"})]}),o.jsx("input",{value:u.panelUrl||"",maxLength:512,placeholder:f("fleet-panel-url"),onChange:x=>h({panelUrl:x.target.value})}),o.jsx("small",{children:f("fleet-panel-url-help")}),u.panelUrl&&!w_(u.panelUrl)&&o.jsx("small",{className:"nc-err",children:f("fleet-panel-url-invalid")}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{className:"nc-btn ghost",onClick:()=>t(null),children:f("cancel")}),o.jsx("button",{className:"nc-btn primary",disabled:n||!u.id||j||u.kind==="custom"&&!u.command||u.kind==="managed"&&(g==null?void 0:g.requiresModel)&&!u.managedModel||u.kind==="managed"&&(g==null?void 0:g.credentialEnv)===!0&&!u.envKey||u.kind==="managed"&&u.provider==="custom"&&(!u.displayName||!u.baseUrl||!u.envKey||!u.providerId),onClick:s,children:f("save")})]})]})}function gO({state:e,setState:t,busy:n,onSave:s,onTest:i,profiles:l=[],canTest:c=!0}){const[u,h]=y.useState(null),[p,v]=y.useState(!1),_=e.form,g=R=>t({...e,form:{..._,...R}}),w=/^[^\x00-\x1f\x7f]{1,128}$/.test(_.id||""),S=["contextWindow","maxTokens"].every(R=>{const x=String(_[R]===void 0?"":_[R]).trim();return!x||zo(x)}),N=Array.isArray(_.effortLevels)?_.effortLevels.join(", "):String(_.effortLevels||""),C=x_(_.effortLevels).ok,j=!!(_.id||"").trim()&&!!(_.engine||"").trim()&&w&&S&&C,E=async()=>{h(null),v(!0);try{h(await i(_.engine,_.id))}catch(R){h({outcome:"unverified",detail:String(R&&R.message||R)})}v(!1)};return o.jsxs("div",{className:"nc-fleet-form",children:[o.jsxs("label",{className:"nc-field",children:[f("model-editor-engine"),o.jsxs("select",{value:_.engine||"",disabled:n||e.mode==="edit",onChange:R=>{h(null),g({engine:R.target.value})},children:[o.jsx("option",{value:"",children:"—"}),l.map(R=>o.jsx("option",{value:R.id,children:R.label?`${R.id} · ${R.label}`:R.id},R.id))]})]}),o.jsxs("label",{className:"nc-field",children:[f("model-editor-id"),o.jsx("input",{value:_.id||"",disabled:n||e.mode==="edit",placeholder:"qwen3.9-max",onChange:R=>{h(null),g({id:R.target.value})}})]}),o.jsx("small",{className:"nc-set-hint",children:f("model-editor-id-help")}),o.jsxs("label",{className:"nc-field",children:[f("model-editor-context"),o.jsx("input",{inputMode:"numeric","aria-label":f("fleet-models-field-context"),value:_.contextWindow||"",disabled:n,"aria-invalid":_.contextWindow&&!zo(_.contextWindow)?"true":"false",onChange:R=>g({contextWindow:R.target.value.replace(/[^0-9]/g,"").slice(0,9)})})]}),_.contextWindow&&!zo(_.contextWindow)&&o.jsx("small",{className:"nc-err",children:f("model-editor-limit-invalid")}),o.jsxs("label",{className:"nc-field",children:[f("model-editor-max-tokens"),o.jsx("input",{inputMode:"numeric","aria-label":f("fleet-models-field-output"),value:_.maxTokens||"",disabled:n,"aria-invalid":_.maxTokens&&!zo(_.maxTokens)?"true":"false",onChange:R=>g({maxTokens:R.target.value.replace(/[^0-9]/g,"").slice(0,9)})})]}),_.maxTokens&&!zo(_.maxTokens)&&o.jsx("small",{className:"nc-err",children:f("model-editor-limit-invalid")}),Th.map(R=>o.jsxs("label",{className:"nc-field",children:[f(`model-editor-${R==="reasoning"?"reasoning":R}`),o.jsxs("select",{value:_[R]===void 0||_[R]===null?"":String(_[R]),disabled:n,onChange:x=>g({[R]:x.target.value===""?void 0:x.target.value==="true"}),children:[o.jsx("option",{value:"",children:f("model-editor-absent")}),o.jsx("option",{value:"true",children:f("model-editor-true")}),o.jsx("option",{value:"false",children:f("model-editor-false")})]})]},R)),o.jsxs("label",{className:"nc-field",children:[f("model-editor-effort-levels"),o.jsx("input",{"aria-label":f("fleet-models-field-effort"),value:N,disabled:n,placeholder:"low, medium","aria-invalid":C?"false":"true",onChange:R=>g({effortLevels:R.target.value})})]}),!C&&o.jsx("small",{className:"nc-err",children:f("model-editor-effort-invalid")}),o.jsxs("div",{className:"nc-set-row",children:[c&&o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||p||!j,onClick:E,children:f(p?"model-test-running":"model-test")}),u&&o.jsxs("span",{className:`nc-model-test ${u.outcome}`,children:[f(`model-test-${u.outcome}`),u.outcome==="ok"&&Number.isInteger(u.latencyMs)?` · ${u.latencyMs}ms`:""]})]}),u&&u.detail&&o.jsx("small",{className:"nc-set-hint",children:u.detail}),u&&u.outcome==="unverified"&&o.jsx("small",{className:"nc-set-hint",children:f("model-test-unverified-help")}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>t(null),children:f("cancel")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||!j,onClick:()=>s(_),children:f("save")})]})]})}function vO({token:e,route:t,targets:n=[],location:s,setLocation:i,state:l,setState:c,engines:u,mcpServers:h=[],managedCatalog:p=[],busy:v,onSave:_}){var O,P,z;const[g,w]=y.useState(null),[S,N]=y.useState(""),C=l.form,j=A=>c({...l,form:{...C,...A}}),E=u.find(A=>A.id===C.engine),R=((O=E==null?void 0:E.managed)==null?void 0:O.client)==="shell",x=((P=E==null?void 0:E.managed)==null?void 0:P.client)||"",W=((z=p.find(A=>A.client===x))==null?void 0:z.mcpManaged)!==!1,$=A=>{var H,M,U,ee;const T=u.find(re=>re.id===A),L={...C.commands||{}};((H=E==null?void 0:E.managed)==null?void 0:H.client)==="shell"&&(C.command?L[C.engine]=C.command:delete L[C.engine]),j({engine:A,model:((M=C.models)==null?void 0:M[A])||((U=T==null?void 0:T.managed)==null?void 0:U.model)||((ee=T==null?void 0:T.model)==null?void 0:ee.value)||"",commands:L,command:L[A]||""})},Y=A=>{const T={...C.commands||{}};A?T[C.engine]=A:delete T[C.engine],j({command:A,commands:T})},q=R&&/[|&;<>()`$*?{}\[\]~]/.test(C.command||""),K=[...new Set([...h||[],...Array.isArray(C.mcp)?C.mcp:[]])].sort(),se=Array.isArray(C.mcp)?C.mcp.length?"some":"none":"all",V=A=>{var T;return j({mcp:A==="all"?void 0:A==="none"?[]:(T=C.mcp)!=null&&T.length?C.mcp:[...K]})},B=A=>{const T=Array.isArray(C.mcp)?C.mcp:[];j({mcp:T.includes(A)?T.filter(L=>L!==A):[...T,A].sort()})},D=async A=>{try{const T=await yv(e,A,t);w(T),j({cwd:T.path}),N("")}catch(T){N(String(T.message||T))}};return o.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[o.jsx("b",{children:l.mode==="new"?f("fleet-new-cell"):`${f("edit")} ${C.id}`}),l.mode==="new"&&o.jsxs("label",{className:"nc-field",children:[f("location"),o.jsx("span",{className:"nc-req",children:" *"}),o.jsxs("select",{value:s,onChange:A=>{i(A.target.value),j({engine:""})},children:[o.jsx("option",{value:"",children:f("local")}),n.map(A=>o.jsxs("option",{value:A.route.join("/"),disabled:A.status&&A.status!=="up",children:[A.label,A.status&&A.status!=="up"?` · ${f("node-offline")}`:""]},A.route.join("/")))]})]}),o.jsx("input",{value:C.id,disabled:l.mode!=="new",placeholder:"id",onChange:A=>j({id:A.target.value})}),o.jsx("input",{value:C.label||"",maxLength:64,placeholder:f("fleet-cell-label"),onChange:A=>j({label:A.target.value})}),o.jsxs("div",{className:"nc-fleet-pair",children:[o.jsx("input",{value:C.cwd,placeholder:f("cwd"),onChange:A=>j({cwd:A.target.value})}),o.jsx("button",{className:"nc-btn ghost",onClick:()=>g?w(null):D(C.cwd),children:f("browse")})]}),g&&o.jsxs("div",{className:"nc-fs",children:[o.jsx("div",{className:"nc-fs-path",children:g.path}),o.jsxs("div",{className:"nc-fs-list",children:[g.parent&&o.jsxs("button",{className:"nc-fs-item nc-fs-nav",onClick:()=>D(g.parent),children:["↑ ",f("fs-parent")]}),(g.dirs||[]).map(A=>o.jsxs("button",{className:"nc-fs-item",onClick:()=>D(`${g.path.replace(/\/$/,"")}/${A}`),children:["📁 ",A]},A))]})]}),S&&o.jsx("div",{className:"nc-err",children:S}),o.jsx("select",{value:C.engine,onChange:A=>$(A.target.value),children:o.jsx(xh,{engines:u})}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:!!C.boot,onChange:A=>j({boot:A.target.checked})})," ",f("fleet-boot")]}),o.jsx("input",{value:C.panelUrl||"",maxLength:512,placeholder:f("fleet-panel-url"),onChange:A=>j({panelUrl:A.target.value})}),o.jsx("small",{children:f("fleet-panel-url-help")}),C.panelUrl&&!w_(C.panelUrl)&&o.jsx("small",{className:"nc-err",children:f("fleet-panel-url-invalid")}),R?o.jsxs(o.Fragment,{children:[o.jsx("input",{value:C.command||"",maxLength:4096,placeholder:f("fleet-shell-command-placeholder"),onChange:A=>Y(A.target.value)}),o.jsx("small",{children:C.command?f("fleet-shell-command-help"):f("fleet-shell-interactive")}),q&&o.jsx("small",{className:"nc-note",children:f("fleet-shell-command-metachar")})]}):o.jsxs(o.Fragment,{children:[o.jsx("input",{value:C.model||"",list:"nc-cell-models",placeholder:f("fleet-model-override"),onChange:A=>j({model:A.target.value})}),o.jsx("datalist",{id:"nc-cell-models",children:((E==null?void 0:E.availableModels)||[]).map(A=>o.jsx("option",{value:A},A))}),o.jsx("textarea",{value:C.prompt||"",placeholder:f("cell-prompt"),onChange:A=>j({prompt:A.target.value})}),o.jsx("small",{children:f("cell-prompt-help")}),o.jsxs("label",{className:"nc-field",children:[f("cell-mcp"),o.jsxs("select",{value:se,onChange:A=>V(A.target.value),children:[o.jsx("option",{value:"all",children:f("cell-mcp-all")}),o.jsx("option",{value:"none",children:f("cell-mcp-none")}),o.jsx("option",{value:"some",children:f("cell-mcp-some")})]})]}),!W&&o.jsx("small",{className:"nc-note",children:f("cell-mcp-inert")}),se==="some"&&o.jsx("div",{className:"nc-fleet-mcp-list",children:K.map(A=>o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:(C.mcp||[]).includes(A),onChange:()=>B(A)})," ",A]},A))}),o.jsx("small",{children:f("cell-mcp-help")})]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{className:"nc-btn ghost",onClick:()=>c(null),children:f("cancel")}),o.jsx("button",{className:"nc-btn primary",disabled:v||!C.id||!C.cwd||!C.engine,onClick:_,children:f("save")})]})]})}function Ax({token:e,route:t=[],state:n,setState:s,busy:i,onSave:l}){const[c,u]=y.useState(null),[h,p]=y.useState([]),[v,_]=y.useState(""),g=Array.isArray(t)?t.join("/"):"";y.useEffect(()=>{let j=!0;return uh(e,g?g.split("/"):[]).then(E=>{j&&(p(E.engines||[]),_(""))}).catch(E=>{j&&(p([]),_(String(E.message||E)))}),()=>{j=!1}},[e,g]);const w=n.form,S=j=>s({...n,form:{...w,...j}}),N=async j=>{try{const E=await yv(e,j,t);u(E),S({cwd:E.path})}catch{}},C=!w.id&&w.tmuxSession?w.tmuxSession.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32):w.id;return o.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[o.jsxs("b",{children:[f("import-as-cell")," · ",w.tmuxSession]}),o.jsx("small",{children:f("import-help")}),o.jsx("input",{value:w.tmuxSession,disabled:!0,placeholder:"tmux session",readOnly:!0}),o.jsx("input",{value:w.id,placeholder:f("name"),onChange:j=>S({id:j.target.value})}),o.jsxs("div",{className:"nc-fleet-pair",children:[o.jsx("input",{value:w.cwd,placeholder:f("cwd"),onChange:j=>S({cwd:j.target.value})}),o.jsx("button",{className:"nc-btn ghost",type:"button",onClick:()=>c?u(null):N(w.cwd),children:f("browse")})]}),c&&o.jsxs("div",{className:"nc-fs",children:[o.jsx("div",{className:"nc-fs-path",children:c.path}),o.jsxs("div",{className:"nc-fs-list",children:[c.parent&&o.jsxs("button",{className:"nc-fs-item nc-fs-nav",onClick:()=>N(c.parent),children:["↑ ",f("fs-parent")]}),(c.dirs||[]).map(j=>o.jsxs("button",{className:"nc-fs-item",onClick:()=>N(`${c.path.replace(/\/$/,"")}/${j}`),children:["📁 ",j]},j))]})]}),o.jsxs("select",{value:w.engine,onChange:j=>S({engine:j.target.value}),children:[o.jsx("option",{value:"",children:f("import-engine-required")}),o.jsx(xh,{engines:h})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:!!w.boot,onChange:j=>S({boot:j.target.checked})})," ",f("fleet-boot")]}),(n.err||v)&&o.jsx("div",{className:"nc-err",children:n.err||v}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{className:"nc-btn ghost",onClick:()=>s(null),children:f("cancel")}),o.jsx("button",{className:"nc-btn primary",disabled:i||!w.tmuxSession||!w.engine||!h.length,onClick:l,children:f(C?"import-as-cell":"save")})]})]})}function _d(e){const t=$o(e);return t===null?`~/${e}`:t?`~/${t}`:"~"}function _O(e){if(!e||typeof e.path!="string"||typeof e.home!="string")return"";const{path:t,home:n}=e;return!n||t===n||!t.startsWith(n+"/")?"":t.slice(n.length+1).replace(/\/+$/,"")}function yO({token:e,route:t,cell:n,busy:s=!1,onSaved:i,onClose:l}){const[c,u]=y.useState(""),[h,p]=y.useState(null),[v,_]=y.useState(!1),[g,w]=y.useState(""),S=typeof(n==null?void 0:n.cwdSuggestion)=="string"&&$o(n.cwdSuggestion)!==null?$o(n.cwdSuggestion):null,[N,C]=y.useState(S),j=n==null?void 0:n.id,E=s||v,R=async K=>{const se=$o(K);if(se===null){p({rel:"",dirs:[],loading:!1,err:f("fleet-cwd-repair-invalid")});return}p({rel:se,dirs:[],loading:!0,err:""});try{const V=await yv(e,se,t),B=_O(V);p({rel:B,dirs:Array.isArray(V.dirs)?V.dirs:[],loading:!1,err:""})}catch(V){p({rel:se,dirs:[],loading:!1,err:String(V&&V.message||V)})}},x=K=>{if(!h)return;const se=h.rel?`${h.rel}/${K}`:K;R(se)},W=()=>{h!=null&&h.rel&&R(h.rel.split("/").slice(0,-1).join("/"))},$=()=>{h&&(u(h.rel||""),p(null),w(""),C(null))},Y=()=>{N!==null&&(u(N),C(null),w(""))},q=async()=>{if(E)return;const K=$o(c);if(K===null){w(f("fleet-cwd-repair-invalid"));return}const se=_d(K);let V=!0;try{V=window.confirm(f("fleet-cwd-repair-confirm").replace("{id}",String(j||"")).replace("{path}",se))}catch{V=!1}if(V){_(!0),w(""),C(null);try{const B=await h1(e,j,{cwdRel:K},t);i==null||i(B)}catch(B){const D=B&&B.data||{};if(D.code==="unportable-cwd"){w(f("fleet-cwd-repair-unportable"));const O=Array.isArray(D.cells)?D.cells.find(z=>z&&z.id===j):null,P=O&&typeof O.suggestion=="string"?O.suggestion:null;P!==null&&$o(P)!==null&&C(P)}else w(String(B&&B.message||B))}finally{_(!1)}}};return o.jsxs("div",{className:"nc-set-form nc-fleet-form nc-cwd-repair",children:[o.jsx("b",{children:f("fleet-cwd-repair-title").replace("{id}",String(j||""))}),o.jsx("small",{className:"nc-set-info",children:f("fleet-cwd-repair-help")}),o.jsx("small",{className:"nc-cwd-no-source",children:f("fleet-cwd-repair-no-source-path")}),o.jsxs("label",{className:"nc-field",children:[f("cwd"),o.jsxs("div",{className:"nc-cwd-rel-row",children:[o.jsx("span",{className:"nc-cwd-rel-prefix",children:"~/"}),o.jsx("input",{value:c,placeholder:f("fleet-cwd-repair-placeholder"),autoComplete:"off",spellCheck:"false",autoCapitalize:"none",onChange:K=>u(K.target.value)}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:E,onClick:()=>h?p(null):R(""),children:f(h?"close":"fleet-cwd-repair-browse")})]})]}),o.jsx("div",{className:"nc-cwd-preview",children:f("fleet-cwd-repair-preview").replace("{path}",_d(c))}),h&&o.jsxs("div",{className:"nc-fs",children:[o.jsx("div",{className:"nc-fs-path",children:_d(h.rel)}),o.jsxs("div",{className:"nc-fs-list",children:[h.rel&&o.jsxs("button",{type:"button",className:"nc-fs-item nc-fs-nav",onClick:W,children:["↑ ",f("fs-parent")]}),h.loading&&o.jsx("div",{className:"nc-fs-empty",children:"…"}),!h.loading&&h.dirs.length===0&&o.jsx("div",{className:"nc-fs-empty",children:f("fleet-cwd-repair-fs-empty")}),!h.loading&&h.dirs.map(K=>o.jsxs("button",{type:"button",className:"nc-fs-item",onClick:()=>x(K),children:["📁 ",K]},K))]}),h.err&&o.jsx("div",{className:"nc-err",children:h.err}),o.jsx("div",{className:"nc-sheet-actions",children:o.jsx("button",{type:"button",className:"nc-btn primary",disabled:E||h.loading||!!h.err,onClick:$,children:f("fleet-cwd-repair-use-current")})})]}),g&&o.jsx("div",{className:"nc-err",role:"alert",children:g}),N!==null&&o.jsxs("div",{className:"nc-cwd-suggestion",role:"status",children:[o.jsx("span",{children:f("fleet-cwd-repair-suggestion")}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:Y,children:f("fleet-cwd-repair-use-suggestion").replace("{path}",_d(N))})]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:v,onClick:l,children:f("cancel")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:E,onClick:q,children:v?"…":f("save")})]})]})}function bO({token:e,readonly:t,targets:n=[],startNewCell:s=!1,initialLocation:i=""}){const[l,c]=y.useState({engines:[],cells:[],managedCatalog:[]}),[u,h]=y.useState({available:!1,capabilities:[]}),[p,v]=y.useState(!1),[_,g]=y.useState(null),[w,S]=y.useState(null),[N,C]=y.useState({}),[j,E]=y.useState(null),[R,x]=y.useState(!1),[W,$]=y.useState(""),[Y,q]=y.useState(""),[K,se]=y.useState(i),[V,B]=y.useState(!1),[D,O]=y.useState(null),[P,z]=y.useState(null),[A,T]=y.useState(null),[L,H]=y.useState(!1),[M,U]=y.useState([]),[ee,re]=y.useState(null),[oe,je]=y.useState("manage"),te=y.useRef(!1),ie=K?K.split("/"):[],pe=y.useCallback(async()=>{try{const X=await rl(e,ie);h(X);try{const I=await Yc(e,ie);B(!!I.readonlyDefault)}catch{B(!1)}if(X.provider==="builtin"&&(X.capabilities||[]).includes("definitions")){const I=await uh(e,ie),ce=new Map((X.engines||[]).map(ye=>[ye.id,ye]));if(I.engines=(I.engines||[]).map(ye=>{var Re;return{...ye,availableModels:((Re=ce.get(ye.id))==null?void 0:Re.models)||[]}}),c(I),(X.capabilities||[]).includes("credentials"))try{U((await N5(e,ie)).credentials||[])}catch{U([])}else U([])}$("")}catch(X){$(String(X.message||X))}finally{v(!0)}},[e,K]);y.useEffect(()=>{document.visibilityState!=="hidden"&&pe()},[pe]),D4(pe,5e3);const xe=new Set((u.cells||[]).filter(X=>X.active).map(X=>X.cell)),Be=u.provider==="builtin"&&(u.capabilities||[]).includes("edit"),Te=(u.capabilities||[]).includes("restore");y.useEffect(()=>{!s||te.current||!Be||!l.engines.length||(te.current=!0,E({mode:"new",form:Cx(l.engines[0].id)}))},[s,Be,l.engines]);const Me=async X=>{x(!0),$(""),q("");try{await X(),await pe()}catch(I){$(String(I.message||I))}x(!1)},J=async(X,I)=>{const ce=await T5(e,X,I,ie);return C(ye=>({...ye,[`${X}::${I}`]:ce})),ce},le=X=>Me(async()=>{const I=Nx(X);if(w&&w.mode==="edit"){if((w.original||{}).effortLevels&&!I.effortLevels&&(I.effortLevels=null),!Object.keys(I).length){S(null);return}await uw(e,String(X.id||"").trim(),String(X.engine||"").trim(),I,ie)}else{const ce={id:String(X.id||"").trim(),engine:String(X.engine||"").trim(),...I};await cw(e,ce,ie)}S(null),await pe()}),Q=async(X,I,ce)=>{x(!0),$("");try{const ye=Nx(ce);return Object.keys(ye).length?((l.models||[]).find(ae=>ae.id===I&&ae.engine===X)?await uw(e,I,X,ye,ie):await cw(e,{id:I,engine:X,...ye},ie),await pe(),{ok:!0,written:!0}):{ok:!0,written:!1}}catch(ye){const Re=String(ye&&ye.message||ye);return $(Re),{ok:!1,error:Re}}finally{x(!1)}},ge=()=>Me(async()=>{var zt;const X=_.mode==="new",I=_.form,ce=l.managedCatalog||[],ye=I.kind==="managed"?qc(ce,I):null,Re=typeof(ye==null?void 0:ye.credentialEnv)=="string"?ye.credentialEnv:"",ae=Re&&I.credentialValue||"",Oe=rO(I,X,ce);!X&&_.form.kind==="custom"&&!_.form.modelFlag&&(Oe.model=null),!X&&_.form.kind==="custom"&&_.form.promptMode!=="flag"&&(Oe.promptFlag=null);let gt;if(X)gt=await L5(e,Oe,ie);else{const ft=_.original,Yt=new Set(_.form.envRows.filter(Bt=>!Bt.remove).map(Bt=>Bt.key)),$t=(ft.envKeys||[]).filter(Bt=>!Yt.has(Bt)),Zt=Object.fromEntries(_.form.envRows.filter(Bt=>!Bt.remove&&Bt.key&&(!Bt.configured||Bt.value!=="")).map(Bt=>[Bt.key,Bt.value]));gt=await R5(e,ft.id,Oe,_.form.kind==="custom"?{set:Zt,remove:$t}:void 0,ie)}let At=null;if(Re&&ae)try{At=await lw(e,Re,ae,ie),U(At.credentials||[])}catch{throw await pe(),X&&g({mode:"edit",original:{...Oe,id:I.id},form:{...I,credentialReveal:!1}}),new Error(f(X?"fleet-key-partial-create":"fleet-key-partial-edit"))}await pe(),g(null),q(f("fleet-saved"));const Lt=((zt=((At==null?void 0:At.credentials)||[]).find(ft=>ft.envKey===Re))==null?void 0:zt.activeCells)||[],Rt=[...new Set([...(gt==null?void 0:gt.activeCells)||[],...Lt])];if(Rt.length&&window.confirm(f("fleet-restart-confirm").replace("{cells}",Rt.join(", "))))for(const ft of Rt)await uc(e,ft,ie)}),Z=()=>Me(async()=>{var Lt,Rt,zt,ft,Yt,$t;const X=j.mode==="new",I=j.form,ce={...X?{id:I.id}:{},cwd:I.cwd,engine:I.engine,boot:!!I.boot},ye={...I.commands||{}},Re=l.engines.find(Zt=>Zt.id===I.engine);((Lt=Re==null?void 0:Re.managed)==null?void 0:Lt.client)==="shell"&&typeof I.command=="string"&&I.command.length?ye[I.engine]=I.command:((Rt=Re==null?void 0:Re.managed)==null?void 0:Rt.client)==="shell"&&delete ye[I.engine],(Object.keys(ye).length||!X)&&(ce.commands=ye);const ae=(I.label||"").trim();X?ae&&(ce.label=ae):ce.label=ae||null;const Oe=(I.panelUrl||"").trim();X?Oe&&(ce.panelUrl=Oe):ce.panelUrl=Oe||null,X?Array.isArray(I.mcp)&&(ce.mcp=I.mcp):ce.mcp=Array.isArray(I.mcp)?I.mcp:null,X?(((zt=Re==null?void 0:Re.managed)==null?void 0:zt.client)!=="shell"&&I.model&&(ce.model=I.model),((ft=Re==null?void 0:Re.managed)==null?void 0:ft.client)!=="shell"&&I.prompt&&(ce.prompt=I.prompt)):(ce.model=((Yt=Re==null?void 0:Re.managed)==null?void 0:Yt.client)==="shell"?null:I.model||null,(($t=Re==null?void 0:Re.managed)==null?void 0:$t.client)!=="shell"&&(ce.prompt=I.prompt||null));const gt=X?await P5(e,ce,ie):await h1(e,j.original.id,ce,ie),At=X?I.id:j.original.id;E(null),q(f("fleet-saved")),!X&&(gt!=null&&gt.active)&&window.confirm(f("fleet-restart-confirm").replace("{cells}",At))&&await uc(e,At,ie)}),fe=t||V,ve=u.capabilities||[],ke=ie.length>0&&fe,Ve=X=>M.find(I=>{var ce;return(ce=I.engines)==null?void 0:ce.includes(X.id)})||null,ot=()=>Me(async()=>{var ce;const X=await lw(e,ee.envKey,ee.value,ie);U(X.credentials||[]),re(null),q(f("fleet-credential-saved"));const I=((ce=(X.credentials||[]).find(ye=>ye.envKey===ee.envKey))==null?void 0:ce.activeCells)||[];if(I.length&&window.confirm(f("fleet-restart-confirm").replace("{cells}",I.join(", "))))for(const ye of I)await uc(e,ye,ie)}),rt=X=>Me(async()=>{if(!window.confirm(f("fleet-credential-remove-confirm").replace("{key}",X.envKey)))return;const I=await j5(e,X.envKey,ie);U(I.credentials||[]),q(f("fleet-credential-removed"))}),$e=X=>O({...X,route:Array.isArray(X==null?void 0:X.route)?X.route:ie}),_e=async X=>{if(!D)return;const I={...D,cell:D.cell||D.id};try{await n_({token:e,powerCell:I,payload:X,onNotice:q})}catch(ce){throw $(String(ce&&ce.message||ce)),ce}},ze=(X,I)=>{$(""),z({mode:"new",route:Array.isArray(I)?I:ie,form:{tmuxSession:X.name,id:"",engine:"",cwd:"",boot:!1},err:""})},Je=()=>Me(async()=>{const X=P.form;if(!X.engine){z({...P,err:f("import-engine-required")});return}await D5(e,{tmuxSession:X.tmuxSession,id:X.id||void 0,engine:X.engine,cwd:X.cwd||void 0,boot:!!X.boot},X.route||ie),z(null),q(f("fleet-saved"))}),He=({engineRows:X=[],cellRows:I=[],models:ce=[]})=>Me(async()=>{const ye=X.filter(ft=>ft.selected),Re=ye.map(ft=>XE(ft.engine));if(Re.some(ft=>!ft))throw new Error(f("fleet-backup-invalid-engine"));const ae=ye.filter(ft=>ft.exists).map(ft=>ft.engine.id);if(ae.length&&!window.confirm(f("fleet-backup-confirm-engine-overwrite").replace("{engines}",ae.join(", "))))return;const Oe=[...new Set([...l.engines.map(ft=>ft.id),...Re.map(ft=>ft.id)])],gt=[];for(const ft of I.filter(Yt=>Yt.selected)){const Yt=tO(ft.cell,ft.engine,Oe);if(!Yt)throw new Error(`${ft.cell.id}: ${f("fleet-backup-engine-missing")}`);gt.push(Yt)}const At=I.filter(ft=>ft.selected&&ft.exists).map(ft=>ft.cell.id);if(At.length&&!window.confirm(f("fleet-backup-confirm-overwrite").replace("{cells}",At.join(", "))))return;const Lt=Re.length?await B5(e,Re,ae.length>0,ie,ce):{needsRestart:[]},Rt=gt.length?await O5(e,gt,ie):{needsRestart:[]},zt=[...new Set([...Lt.needsRestart||[],...Rt.needsRestart||[]])];H(!1),q(`${f("fleet-backup-restored").replace("{n}",String(gt.length))}${Re.length?` · ${Re.length} ${f("fleet-engines").toLowerCase()}`:""}${zt.length?` · ${f("fleet-backup-needs-restart").replace("{cells}",zt.join(", "))}`:""}`)}),nt=o.jsxs("label",{className:"nc-field",children:[f("location"),o.jsxs("select",{value:K,onChange:X=>{se(X.target.value),g(null),E(null),$(""),q(""),B(!1),v(!1),h({available:!1,capabilities:[]}),c({engines:[],cells:[],managedCatalog:[]}),U([]),re(null)},children:[o.jsx("option",{value:"",children:f("local")}),n.map(X=>o.jsxs("option",{value:X.route.join("/"),disabled:X.status&&X.status!=="up",children:[X.label,X.status&&X.status!=="up"?` · ${f("node-offline")}`:""]},X.route.join("/")))]})]}),lt=o.jsxs("div",{className:"nc-fleet-view-tabs",role:"tablist","aria-label":f("tab-fleet"),children:[o.jsx("button",{type:"button",role:"tab","aria-selected":oe==="manage",className:`nc-set-tabbtn${oe==="manage"?" on":""}`,onClick:()=>je("manage"),children:f("fleet-manage-location")}),o.jsx("button",{type:"button",role:"tab","aria-selected":oe==="overview",className:`nc-set-tabbtn${oe==="overview"?" on":""}`,onClick:()=>je("overview"),children:f("fleet-network-overview")})]});return p?Be?o.jsxs("div",{className:"nc-set-tab nc-fleet-editor",children:[lt,oe==="overview"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"nc-set-info",children:f("fleet-overview-help")}),o.jsx(Sm,{token:e,targets:n,readonly:t,onPower:$e,onImport:ze})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"nc-set-info",children:f("fleet-manage-help")}),nt,o.jsxs("div",{className:"nc-set-row nc-fleet-backup-actions",children:[o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>{$(""),H(!0)},children:f("fleet-backup")}),o.jsx("small",{children:f("fleet-backup-help")})]}),o.jsxs("div",{className:"nc-fleet-section-head",children:[o.jsx("b",{children:f("fleet-cells")}),o.jsx("span",{className:"nc-fleet-head-actions",children:o.jsxs("button",{className:"nc-btn primary",disabled:fe||R||!l.engines.length,onClick:()=>{var X;$(""),E({mode:"new",form:Cx((X=l.engines[0])==null?void 0:X.id)})},children:["+ ",f("add")]})})]}),l.cells.map(X=>{const I=xe.has(X.id),ce=X.needsRepair===!0;return o.jsxs("div",{className:"nc-fleet-item",children:[o.jsxs("span",{children:[o.jsx("b",{children:X.id}),X.label?o.jsxs("small",{className:"nc-fleet-label",children:[" ",X.label]}):null,o.jsxs("small",{children:[X.engine," · ",ce?o.jsx("span",{className:"nc-fleet-tag nc-fleet-tag-warn",children:f("fleet-cwd-needs-repair")}):X.cwd,I?` · ${f("service-active")}`:` · ${f("cell-off")}`]})]}),o.jsxs("span",{children:[I&&ve.includes("down")&&o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>Me(()=>u1(e,{cell:X.id},ie)),children:f("stop")}),!I&&ve.includes("up")&&o.jsx("button",{className:"nc-btn primary",disabled:fe||R,onClick:()=>$e({cell:X.id,id:X.id,engine:X.engine,model:X.model,models:X.models,permissionPolicies:X.permissionPolicies,active:!1,boot:X.boot}),children:f("start")}),I&&ve.includes("restart")&&o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>Me(()=>uc(e,X.id,ie)),children:f("restart")}),ce?o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>{$(""),T(X)},children:f("fleet-cwd-repair")}):o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>{var ye;$(""),E({mode:"edit",original:X,form:{...X,commands:{...X.commands||{}},command:((ye=X.commands)==null?void 0:ye[X.engine])||""}})},children:f("edit")}),o.jsx("button",{className:"nc-btn danger",disabled:fe||R,onClick:()=>Me(async()=>{window.confirm(f("fleet-remove-cell").replace("{id}",X.id))&&await f1(e,X.id,!0,ie)}),children:"×"})]})]},X.id)}),o.jsxs("div",{className:"nc-fleet-section-head",children:[o.jsx("b",{children:f("fleet-engines")}),o.jsxs("button",{className:"nc-btn primary",disabled:fe||R,onClick:()=>{$(""),g({mode:"new",form:nO()})},children:["+ ",f("add")]})]}),l.engines.map(X=>{var ce,ye;const I=Ve(X);return o.jsxs("div",{className:"nc-fleet-item",children:[o.jsxs("span",{children:[o.jsx("b",{children:X.label}),o.jsx("small",{children:X.managed?`${X.id} · ${X.managed.client} / ${X.managed.provider} · ${(ce=X.managedInfo)!=null&&ce.configured?f("fleet-ready"):((ye=X.managedInfo)==null?void 0:ye.reason)||f("fleet-not-ready")}`:`${X.id} · ${X.command}`}),I&&o.jsxs("small",{children:[I.envKey," · ",f(`fleet-credential-source-${I.source||"missing"}`)]})]}),o.jsxs("span",{children:[I&&o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>{$(""),re({envKey:I.envKey,value:""})},children:I.configured?f("fleet-credential-change"):f("fleet-credential-set")}),(I==null?void 0:I.source)==="local"&&o.jsx("button",{className:"nc-btn danger",disabled:fe||R,onClick:()=>rt(I),children:f("fleet-credential-forget")}),o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>{$(""),g({mode:"edit",original:X,form:iO(X)})},children:f("edit")}),o.jsx("button",{className:"nc-btn danger",disabled:fe||R,onClick:()=>Me(async()=>{window.confirm(f("fleet-remove-engine").replace("{id}",X.id))&&await A5(e,X.id,ie)}),children:"×"})]})]},X.id)}),o.jsxs("div",{className:"nc-fleet-section-head",children:[o.jsx("b",{children:f("fleet-models")}),o.jsxs("button",{className:"nc-btn primary",disabled:fe||R,onClick:()=>{$(""),S({mode:"new",form:{id:"",engine:""}})},children:["+ ",f("add")]})]}),!(l.models||[]).length&&o.jsx("small",{className:"nc-set-hint",children:f("fleet-no-models")}),(l.models||[]).map(X=>{const I=`${X.engine}::${X.id}`,ce=N[I],ye=(l.engines||[]).some(Re=>Re.managed&&Re.managed.model===X.id);return o.jsxs("div",{className:"nc-fleet-item",children:[o.jsxs("span",{children:[o.jsx("b",{children:X.id}),o.jsxs("small",{children:[X.engine,X.contextWindow?` · ${X.contextWindow}`:"",ye?` · ${f("model-in-use")}`:""]}),ce&&o.jsxs("small",{className:`nc-model-test ${ce.outcome}`,children:[f(`model-test-${ce.outcome}`),ce.outcome==="ok"&&Number.isInteger(ce.latencyMs)?` · ${ce.latencyMs}ms`:""]})]}),o.jsxs("span",{children:[ve.includes("model-test")&&o.jsx("button",{className:"nc-btn ghost",disabled:R||ke,onClick:()=>Me(()=>J(X.engine,X.id)),children:f("model-test")}),ve.includes("edit-model")&&o.jsx("button",{className:"nc-btn ghost",disabled:fe||R,onClick:()=>{$(""),S({mode:"edit",original:X,form:{id:X.id,engine:X.engine,contextWindow:X.contextWindow,maxTokens:X.maxTokens,tools:X.tools,vision:X.vision,reasoning:X.reasoning,effortLevels:X.effortLevels}})},children:f("edit")}),o.jsx("button",{className:"nc-btn danger",disabled:fe||R,onClick:()=>Me(()=>M5(e,X.id,X.engine,ie)),children:"×"})]})]},I)})]}),w&&o.jsx(to,{onClose:()=>S(null),label:f("fleet-models"),error:W,children:o.jsx(gO,{state:w,setState:S,busy:R,onSave:le,onTest:J,profiles:l.managedCatalog||[],canTest:ve.includes("model-test")&&!ke})}),_&&o.jsx(to,{onClose:()=>g(null),label:f("fleet-new-engine"),error:W,children:o.jsx(mO,{state:_,setState:g,busy:R,onSave:ge,catalog:l.managedCatalog||[],fetchModels:ve.includes("model-discovery")?(X,I)=>I5(e,X,I,ie):void 0,onSetModelValue:ve.includes("edit-model")?Q:void 0})}),j&&o.jsx(to,{onClose:()=>E(null),label:f("fleet-new-cell"),error:W,children:o.jsx(vO,{token:e,route:ie,targets:n,location:K,setLocation:se,state:j,setState:E,engines:l.engines,mcpServers:l.mcpServers||[],managedCatalog:l.managedCatalog||[],busy:R,onSave:Z})}),A&&o.jsx(to,{onClose:()=>T(null),label:f("fleet-cwd-repair-title").replace("{id}",A.id),error:"",children:o.jsx(yO,{token:e,route:ie,cell:A,busy:R,onSaved:async()=>{T(null),q(f("fleet-cwd-repaired")),await pe()},onClose:()=>T(null)})}),Y&&o.jsx("div",{className:"nc-set-note",children:Y}),W&&o.jsx("div",{className:"nc-err",children:W}),L&&o.jsx(to,{onClose:()=>H(!1),label:f("fleet-backup"),error:W,children:o.jsx(oO,{cells:l.cells,engines:l.engines,models:l.models||[],busy:R,canRestore:Te,onRestore:He,onClose:()=>H(!1)})}),ee&&o.jsx(to,{onClose:()=>re(null),label:f("fleet-credential-title"),error:W,children:o.jsxs("div",{className:"nc-fleet-form nc-credential-form",children:[o.jsx("b",{children:f("fleet-credential-title")}),o.jsx("small",{children:f("fleet-credential-help")}),o.jsxs("label",{className:"nc-field",children:[ee.envKey,o.jsx("input",{type:"password",autoComplete:"off",spellCheck:"false",autoCapitalize:"none",value:ee.value,onChange:X=>re({...ee,value:X.target.value})})]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{className:"nc-btn ghost",onClick:()=>re(null),children:f("cancel")}),o.jsx("button",{className:"nc-btn primary",disabled:R||!ee.value,onClick:ot,children:f("save")})]})]})}),P&&o.jsx(to,{onClose:()=>z(null),label:f("import-as-cell"),error:W,children:o.jsx(Ax,{token:e,route:P.route||ie,state:P,setState:z,busy:R,onSave:Je})}),D&&o.jsx(Gd,{cell:D,token:e,route:Array.isArray(D.route)?D.route:ie,onConfirm:async X=>{try{await _e(X)}finally{pe()}},onClose:()=>O(null)})]}):o.jsxs("div",{className:"nc-set-tab",children:[lt,oe==="overview"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"nc-set-info",children:f("fleet-overview-help")}),o.jsx(Sm,{token:e,targets:n,readonly:t,onPower:$e,onImport:ze})]}):o.jsxs(o.Fragment,{children:[nt,o.jsxs("div",{className:"nc-set-info",children:[f(W?"fleet-editor-load-error":"fleet-editor-unavailable"),!W&&u.reason?` ${u.reason}`:""]})]}),W&&o.jsx("div",{className:"nc-err",children:W}),P&&o.jsx(to,{onClose:()=>z(null),label:f("import-as-cell"),error:W,children:o.jsx(Ax,{token:e,route:P.route||ie,state:P,setState:z,busy:R,onSave:Je})}),D&&o.jsx(Gd,{cell:D,token:e,route:Array.isArray(D.route)?D.route:ie,onConfirm:async X=>{try{await _e(X)}finally{pe()}},onClose:()=>O(null)})]}):o.jsxs("div",{className:"nc-set-tab",children:[lt,oe==="overview"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"nc-set-info",children:f("fleet-overview-help")}),o.jsx(Sm,{token:e,targets:n,readonly:t,onPower:$e,onImport:ze})]}):o.jsxs(o.Fragment,{children:[nt,o.jsx("div",{className:"nc-set-info",children:f("fleet-editor-loading")})]})]})}const eN="nc_bar_files_button",tN="nc_bar_keyboard_button",nN="nc_bar_panel_button";function k_(e,t){try{const n=localStorage.getItem(e);if(n==="on")return!0;if(n==="off")return!1}catch{}return t}function C_(e,t){try{localStorage.setItem(e,t?"on":"off")}catch{}}function sN(){return k_(eN,!0)}function iN(e){C_(eN,e)}function rN(){return k_(tN,!0)}function wO(e){C_(tN,e)}function oN(){return k_(nN,!1)}function SO(e){C_(nN,e)}const E_="nc_notification_speech_v1",yd="nc-notification-speech",nv="nc-notification-speech-preview",xO=320,kO=2,CO=3e4,EO=1e4,NO=6e4,jO=64,Mx=Object.freeze({enabled:!1}),LO=Object.freeze({it:"it-IT",en:"en-US",es:"es-ES"}),RO=Object.freeze({it:new Set(["che","con","correzione","della","delle","difetto","il","lavoro","nessun","non","per","pronto","pubblicata","pubblicato","rilascio","sono","stato","tutti","verificata","verificato","versione","completata","completato","riepilogo"]),en:new Set(["all","and","completed","fix","for","issue","no","published","ready","release","summary","the","verified","version","with","work"]),es:new Set(["con","correccion","defecto","el","esta","para","publicada","publicado","resumen","sin","todos","trabajo","verificada","verificado","version","y"])}),N_=new WeakSet;function j_(e){return{enabled:(e&&typeof e=="object"&&!Array.isArray(e)?e:{}).enabled===!0}}function aN(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function Tx(e=aN()){if(!e)return{...Mx};try{return j_(JSON.parse(e.getItem(E_)||"null"))}catch{return{...Mx}}}function AO(e,t=aN()){const n=j_(e);if(t)try{t.setItem(E_,JSON.stringify(n))}catch{}return n}function ul(){try{return typeof window<"u"?window:null}catch{return null}}function Kc(e=ul()){try{return!!(e&&e.speechSynthesis&&typeof e.speechSynthesis.speak=="function"&&typeof e.SpeechSynthesisUtterance=="function")}catch{return!1}}function lN(e=ul()){return!!(e&&(typeof e=="object"||typeof e=="function")&&N_.has(e))}function sv(e=ul()){e&&(typeof e=="object"||typeof e=="function")&&N_.delete(e)}function Xa(e){const t=String(e||"").trim().toLowerCase().split("-")[0];return LO[t]||""}function Ih(e){return String(e||"").normalize("NFC").replace(/[\p{Cc}\p{Cf}]+/gu," ").replace(/\s+/g," ").trim()}function MO(e){const t=Ih(e).normalize("NFD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase(),n=new Set(t.match(new RegExp("\\p{L}+","gu"))||[]);if(n.size<4)return"";const s=Object.entries(RO).map(([i,l])=>({lang:i,score:[...n].reduce((c,u)=>c+(l.has(u)?1:0),0)})).sort((i,l)=>l.score-i.score);return s[0].score>=3&&s[0].score-s[1].score>=2?s[0].lang:""}function TO(e,t){const n=Xa(e&&e.lang);return n||Xa(MO(e&&e.body))||Xa(t)}function cN(e){try{const t=e&&e.speechSynthesis&&e.speechSynthesis.getVoices;return typeof t=="function"?Array.from(t.call(e.speechSynthesis)||[]).filter(Boolean):[]}catch{return[]}}function uN(e,t){const n=Xa(t);if(!n)return null;const s=Array.from(e||[]).filter(u=>u&&typeof u.lang=="string"&&u.lang.trim()),i=s.filter(u=>u.lang.trim().toLowerCase()===n.toLowerCase()),l=n.slice(0,2).toLowerCase(),c=s.filter(u=>u.lang.trim().toLowerCase().split("-")[0]===l);return i.find(u=>u.default===!0)||i[0]||c.find(u=>u.default===!0)||c[0]||null}function Ix(e){return Ih(e).replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\b(?:sk|hf|zai|xox[baprs]|gh[pousr]|npm)[_-][A-Za-z0-9._-]{8,}\b/gi,"[redacted]").replace(/\b(?:token|password|secret|credential|api[_-]?key)\s*[=:]\s*(?:"[^"]*"|'[^']*'|\S+)/gi,"[redacted]").replace(/\b[A-Z][A-Z0-9_]{2,}\s*=\s*(?:"[^"]*"|'[^']*'|\S+)/g,"[redacted]").replace(/(?:\/home\/[^/\s]+|\/Users\/[^/\s]+|\/data\/(?:data|user\/\d+)\/[^/\s]+)(?:\/[^\s]*)?/g,"[private path]").replace(/\b[A-Za-z]:\\Users\\[^\\\s]+(?:\\[^\s]*)?/g,"[private path]")}function IO(e,t=xO){const n=Ix(e&&e.title),s=Ix(e&&e.body),i=[n,s&&s!==n?s:""].filter(Boolean).join(". "),l=Array.from(i);return l.length<=t?i:`${l.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function PO(e){try{return!!(e&&e.visibilityState==="visible"&&typeof e.hasFocus=="function"&&e.hasFocus())}catch{return!1}}function dN(e=ul()){if(!Kc(e))return!1;try{return e.speechSynthesis.cancel(),!0}catch{return!1}}function DO(e){try{e&&typeof e.dispatchEvent=="function"&&typeof e.Event=="function"&&e.dispatchEvent(new e.Event(nv))}catch{}}function OO(e,t,n=ul(),s={}){var p;if(sv(n),!Kc(n))return Promise.resolve(!1);const i=Ih(e);if(!i||(p=s.signal)!=null&&p.aborted)return Promise.resolve(!1);const l=Number.isFinite(s.timeoutMs)&&s.timeoutMs>0?s.timeoutMs:EO,c=s.setTimer||((v,_)=>setTimeout(v,_)),u=s.clearTimer||(v=>clearTimeout(v)),h=s.signal;return DO(n),new Promise(v=>{let _=!1,g=!1,w=null,S=null;const N=C=>{if(!_){if(_=!0,h&&S&&h.removeEventListener("abort",S),w!==null&&u(w),C!==!0)try{n.speechSynthesis.cancel()}catch{}else N_.add(n);v(C)}};S=()=>N("no-activation"),h&&h.addEventListener("abort",S,{once:!0});try{n.speechSynthesis.cancel();const C=new n.SpeechSynthesisUtterance(i);C.lang=Xa(t);const j=uN(cN(n),C.lang);j&&(C.voice=j),C.onstart=()=>{g=!0},C.onend=()=>N(g?!0:"no-activation"),C.onerror=()=>N("voice-error"),w=c(()=>N("timeout"),l),n.speechSynthesis.speak(C)}catch{N("no-activation")}})}function BO(e={}){const t=e.scope||ul(),n=e.document||t&&t.document,s=Number.isInteger(e.maxPending)&&e.maxPending>=0?e.maxPending:kO,i=Number.isFinite(e.watchdogMs)&&e.watchdogMs>0?e.watchdogMs:CO,l=Number.isFinite(e.dedupWindowMs)&&e.dedupWindowMs>0?e.dedupWindowMs:NO,c=Number.isInteger(e.maxDedup)&&e.maxDedup>0?e.maxDedup:jO,u=e.now||Date.now,h=e.setTimer||((V,B)=>setTimeout(V,B)),p=e.clearTimer||(V=>clearTimeout(V)),v=e.isPrimed||(()=>lN(t)),_=t&&t.speechSynthesis;let g=null,w=null,S=[],N=[],C=()=>{};const j=new Map,E=()=>{N=cN(t)};if(E(),_&&typeof _.addEventListener=="function")_.addEventListener("voiceschanged",E),C=()=>_.removeEventListener("voiceschanged",E);else if(_&&"onvoiceschanged"in _){const V=_.onvoiceschanged,B=(...D)=>{E(),typeof V=="function"&&V.apply(_,D)};_.onvoiceschanged=B,C=()=>{_.onvoiceschanged===B&&(_.onvoiceschanged=V)}}const R=V=>{if(V&&typeof V.id=="string"&&V.id)return`id:${V.id}`;const B=Number(V&&V.ts),D=Ih(V&&V.title);return Number.isFinite(B)&&D?`frame:${B}:${D}`:""},x=V=>{if(!V)return!0;const B=u();for(const[D,O]of j)B-O>=l&&j.delete(D);if(j.has(V))return!1;for(j.set(V,B);j.size>c;)j.delete(j.keys().next().value);return!0},W=()=>{w!==null&&p(w),w=null},$=()=>{W(),g&&(g.onend=null,g.onerror=null,g=null),dN(t)},Y=V=>{if(!Kc(t))return S=[],"unsupported";let B;try{B=new t.SpeechSynthesisUtterance(V.text),B.lang=Xa(V.lang);const O=uN(N,B.lang);O&&(B.voice=O)}catch{return S=[],"error"}g=B;const D=()=>{if(g!==B)return;W(),g=null,B.onend=null,B.onerror=null;const O=S.shift();O&&Y(O)};B.onend=D,B.onerror=D;try{return w=h(()=>{if(g!==B)return;g=null,B.onend=null,B.onerror=null;try{t.speechSynthesis.cancel()}catch{}W();const O=S.shift();O&&Y(O)},i),t.speechSynthesis.speak(B),"speaking"}catch{return D(),"error"}},q=(V,B)=>{if(!Kc(t))return"unsupported";const D=IO(V);if(!D)return"empty";if(!x(R(V)))return"duplicate";if(!PO(n))return"inactive";if(!v())return"unprimed";const O={text:D,lang:B};return V&&V.urgency==="high"?(S=[],$(),Y(O)):g?s===0?"dropped":(S.length>=s&&S.shift(),S.push(O),"queued"):Y(O)},K=()=>{S=[],$()};return{enqueue:q,stop:K,dispose:()=>{K(),C(),C=()=>{}}}}function hN(){const[e,t]=y.useState(Tx);y.useEffect(()=>{const s=i=>{if((i==null?void 0:i.type)==="storage"&&i.key!==E_&&i.key!==null)return;const l=(i==null?void 0:i.type)===yd?j_(i.detail):Tx();t(l)};return window.addEventListener(yd,s),window.addEventListener("storage",s),()=>{window.removeEventListener(yd,s),window.removeEventListener("storage",s)}},[]);const n=y.useCallback(s=>{const i=AO({enabled:s===!0});return t(i),window.dispatchEvent(new CustomEvent(yd,{detail:i})),i.enabled},[]);return[e.enabled,n]}const L_="nc_storage_persist_v1",$O=1440*60*1e3;function iv(e=globalThis.localStorage){return Ir(L_,{storage:e,fallback:()=>null,parse:t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0})}async function zO({manager:e=(s=>(s=globalThis.navigator)==null?void 0:s.storage)(),ls:t=globalThis.localStorage,now:n=Date.now}={}){const i=iv(t),l=n();let c;try{if(!e||typeof e.persist!="function")c={at:l,status:"unsupported"};else if(typeof e.persisted=="function"&&await e.persisted())c={at:l,status:"persistent"};else{if(i&&i.status==="denied"&&l-i.at<$O)return i;c={at:l,status:await e.persist()?"persistent":"denied"}}}catch(u){c={at:l,status:"error",note:String((u==null?void 0:u.message)||u).slice(0,120)}}return(!i||i.status!==c.status)&&er({reason:"storage-persist",note:c.status}),wi(L_,c,{storage:t}),c}const FO=e=>{try{return new Date(e).toLocaleString()}catch{return String(e)}},xm=e=>Array.isArray(e)?e.join(", "):"";function HO(){Fn();const[e,t]=y.useState(()=>Rg()),[n,s]=y.useState(()=>iv()),[i,l]=y.useState(!1);y.useEffect(()=>{const p=()=>{t(Rg()),s(iv())};return window.addEventListener("storage",p),window.addEventListener("nexuscrew-roster-preferences",p),()=>{window.removeEventListener("storage",p),window.removeEventListener("nexuscrew-roster-preferences",p)}},[]);const c=async()=>{try{await navigator.clipboard.writeText(JSON.stringify(e,null,2)),l(!0),setTimeout(()=>l(!1),1500)}catch{}},u=()=>{XI(),t([])},h=[...e].reverse();return o.jsxs("div",{className:"nc-set-form nc-prefs-journal",children:[o.jsx("div",{className:"nc-sheet-label",children:f("prefs-journal")}),o.jsxs("div",{"data-testid":"persist-status",className:"nc-set-hint","data-key":L_,children:[f("prefs-persist"),": ",n?n.status:f("prefs-persist-unknown")]}),!h.length&&o.jsx("div",{className:"nc-set-hint",children:f("prefs-journal-empty")}),o.jsx("div",{className:"nc-journal-list",style:{maxHeight:220,overflow:"auto"},children:h.map((p,v)=>o.jsxs("div",{"data-testid":"journal-row",className:"nc-set-hint",style:{overflowWrap:"anywhere"},children:[o.jsx("b",{children:p.reason})," · ",FO(p.t),p.position?` · ${p.position}`:"",p.key?` · ${p.key}`:"",p.note?` · ${p.note}`:"",p.before?o.jsxs("div",{children:[f("prefs-before"),": ",xm(p.before)]}):null,p.after?o.jsxs("div",{children:[f("prefs-after"),": ",xm(p.after)]}):null,p.visible?o.jsxs("div",{children:[f("prefs-visible"),": ",xm(p.visible)]}):null]},`${p.t}-${v}`))}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,disabled:!e.length,children:f(i?"copied":"prefs-journal-copy")}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:u,disabled:!e.length,children:f("prefs-journal-clear")})]})]})}const R_="nc_device_id_v1",fN="nc_prefs_sync_v1",UO="nexuscrew-roster-preferences",A_=/^[a-f0-9]{32}$/,WO=192,qO=256,Px=128,pN="nexuscrew-preferences",Wo=e=>e&&typeof e=="object"&&!Array.isArray(e),Pd=(e,t)=>typeof e=="string"&&e.length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),km=(e,t=qO)=>Array.isArray(e)&&e.length<=t&&e.every(n=>Pd(n,WO));function dl(e){if(!Wo(e)||Object.keys(e).some(n=>!["pins","orders","views","nodeOrder"].includes(n)))return null;const t={pins:[],orders:{},views:{},nodeOrder:[]};if(e.pins!==void 0){if(!km(e.pins))return null;t.pins=[...new Set(e.pins)]}if(e.nodeOrder!==void 0){if(!km(e.nodeOrder,128))return null;t.nodeOrder=[...new Set(e.nodeOrder)]}if(e.orders!==void 0){if(!Wo(e.orders)||Object.keys(e.orders).length>Px)return null;for(const[n,s]of Object.entries(e.orders)){if(!Pd(n,96)||!km(s))return null;t.orders[n]=[...new Set(s)]}}if(e.views!==void 0){if(!Wo(e.views)||Object.keys(e.views).length>Px)return null;for(const[n,s]of Object.entries(e.views)){if(!Pd(n,96)||!Wo(s))return null;const i={};if(s.open!==void 0){if(typeof s.open!="boolean")return null;i.open=s.open}if(s.filter!==void 0){if(!Pd(s.filter,16))return null;i.filter=s.filter}t.views[n]=i}}return t}const rv=e=>!e||!(e.pins||[]).length&&!(e.nodeOrder||[]).length&&!Object.keys(e.orders||{}).length&&!Object.keys(e.views||{}).length;function M_(e){const t={pins:io(),orders:bc(e),views:Td(e),nodeOrder:Dg(e)};return dl(t)||{pins:[],orders:{},views:{},nodeOrder:[]}}const ov=e=>Array.isArray(e)?`[${e.map(ov).join(",")}]`:Wo(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ov(e[t])}`).join(",")}}`:JSON.stringify(e),Dd=e=>{const t=ov(dl(e)||{});let n=2166136261;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,16777619);return(n>>>0).toString(16)},Cm=["nc_pins",ta,ea,Ch];function T_(e,{storage:t,note:n="restore"}={}){const s=dl(e);if(!s)return new Error("preferenze non valide");let i=t;try{i=i||globalThis.localStorage}catch(u){return u}const l={};for(const u of Cm)try{l[u]=i.getItem(u)}catch{l[u]=null}const c={nc_pins:s.pins,[ta]:s.orders,[ea]:s.views,[Ch]:s.nodeOrder};for(const u of Cm){const h=wi(u,c[u],{storage:t});if(h){for(const p of Cm)try{l[p]===null||l[p]===void 0?i.removeItem(p):i.setItem(p,l[p])}catch{}return er({reason:"prefs-restore-failed",key:u,note:String(h&&h.message||h).slice(0,120)}),h}}er({reason:"prefs-restore",note:n,after:s.pins});try{window.dispatchEvent(new Event(UO))}catch{}return null}const mN=e=>({status:"error",code:"storage-write-failed",note:String(e&&e.message||e).slice(0,120)}),I_=e=>{try{return e||globalThis.localStorage}catch{return null}},Ph=e=>{var t;try{const n=(t=I_(e))==null?void 0:t.getItem(R_);return A_.test(n||"")?n:""}catch{return""}},gN=(e,t)=>{var n;try{(n=I_(t))==null||n.setItem(R_,e)}catch{}};function KO(e,t){A_.test(e||"")&&!Ph(t)&&gN(e,t)}const VO=Ph,GO=e=>Ir(fN,{storage:e,fallback:()=>null,parse:t=>Wo(t)?t:void 0}),sh=(e,t,n)=>wi(fN,{revision:e,hash:Dd(t),at:Date.now()},{storage:n});function vN(e){return async(t,n,{headers:s={},body:i}={})=>Vn(n,e,{method:t,headers:{...i?{"content-type":"application/json"}:{},...s},body:i,timeoutMs:8e3})}async function Dx(e,t){let n=Ph(t);if(!n){const s=await e("POST","/api/prefs/devices");if(s.status!==201)throw Object.assign(new Error(`device ${s.status}`),{status:s.status});if(n=(await s.json()).deviceId,!A_.test(n||""))throw new Error("device non valido");gN(n,t)}return n}async function av(e,t,n,s,i){const l=await e("PUT","/api/prefs",{headers:{"x-nc-device":t,"if-match":`"${s}"`},body:JSON.stringify({data:n})});if(l.status===200){const u=await l.json();return sh(u.revision,n,i),{status:"uploaded",revision:u.revision}}const c=await l.json().catch(()=>({}));return l.status===409&&c.current?{status:"conflict",revision:c.current.revision,conflict:{local:n,server:dl(c.current.data)||null,revision:c.current.revision,deviceId:t}}:{status:"error",code:c.code||`http-${l.status}`}}async function YO({request:e,token:t,storage:n}={}){var i;const s=e||vN(t);try{let l=await Dx(s,n),c=await s("GET","/api/prefs",{headers:{"x-nc-device":l}});if(c.status===404){try{(i=I_(n))==null||i.removeItem(R_)}catch{}l=await Dx(s,n),c=await s("GET","/api/prefs",{headers:{"x-nc-device":l}})}if(c.status!==200)return{status:"error",code:`http-${c.status}`};const u=await c.json(),h=M_(n),p=dl(u.data);if(!p)return rv(h)?{status:"synced",revision:u.revision}:av(s,l,h,u.revision,n);if(rv(h)){const _=T_(p,{storage:n});return _?mN(_):(sh(u.revision,p,n),{status:"restored",revision:u.revision})}if(Dd(h)===Dd(p))return sh(u.revision,h,n),{status:"synced",revision:u.revision};const v=GO(n);return v&&v.revision===u.revision&&v.hash!==Dd(h)?av(s,l,h,u.revision,n):{status:"conflict",revision:u.revision,conflict:{local:h,server:p,revision:u.revision,deviceId:l}}}catch(l){return{status:"offline",note:String((l==null?void 0:l.message)||l).slice(0,120)}}}async function XO(e,t,{request:n,token:s,storage:i}={}){if(!t)return{status:"error",code:"no-conflict"};const l=n||vN(s);try{if(e==="server"){if(!t.server)return{status:"error",code:"no-server-copy"};const c=T_(t.server,{storage:i,note:"restore-from-server"});return c?mN(c):(sh(t.revision,t.server,i),{status:"restored",revision:t.revision})}return await av(l,t.deviceId||Ph(i),t.local,t.revision,i)}catch(c){return{status:"offline",note:String((c==null?void 0:c.message)||c).slice(0,120)}}}function JO(e){return JSON.stringify({kind:pN,version:1,exportedAt:new Date().toISOString(),data:M_(e)},null,2)}function QO(e,{storage:t}={}){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:"not-json"}}if(!Wo(n)||n.kind!==pN||n.version!==1)return{ok:!1,reason:"wrong-kind"};const s=dl(n.data);if(!s)return{ok:!1,reason:"bad-schema"};const i=T_(s,{storage:t,note:"import"});return i?{ok:!1,reason:"storage-write-failed",note:String(i&&i.message||i).slice(0,120)}:{ok:!0,data:s}}const ih={status:"idle"};let Rr=ih;const lv=new Set,rh=e=>{Rr=e,lv.forEach(t=>t(e))};let cv=null,Vc=0;const ZO=e=>{const t=e||null;cv!==t&&(cv=t,Vc+=1,Rr!==ih&&rh(ih))},_N=()=>{const[e,t]=y.useState(Rr);return y.useEffect(()=>(lv.add(t),t(Rr),()=>{lv.delete(t)}),[]),e};async function yN(e,t){var i;if(Rr.status!=="conflict")return;const n=Vc;if(cv!==(e||null)||((i=Rr.conflict)==null?void 0:i.deviceId)!==VO()){rh(ih);try{window.dispatchEvent(new Event("nexuscrew-roster-preferences"))}catch{}return}const s=await XO(t,Rr.conflict,{token:e});n===Vc&&rh({...s,at:Date.now()})}const eB=1500,tB=3e3,Ox="nexuscrew-roster-preferences";function nB(e){y.useEffect(()=>{if(ZO(e),!e)return;let n=null,s=!0;const i=async()=>{if(!s||Rr.status==="conflict")return;const u=Vc,h=await YO({token:e});s&&u===Vc&&rh({...h,at:Date.now()})},l=u=>{clearTimeout(n),n=setTimeout(i,u)},c=()=>{Rr.status!=="conflict"&&l(tB)};return l(eB),window.addEventListener(Ox,c),window.addEventListener("storage",c),()=>{s=!1,clearTimeout(n),window.removeEventListener(Ox,c),window.removeEventListener("storage",c)}},[e]);const t=y.useCallback(n=>yN(e,n),[e]);return{state:_N(),resolve:t}}const sB=e=>typeof e.text=="function"?e.text():new Promise((t,n)=>{const s=new FileReader;s.onload=()=>t(String(s.result||"")),s.onerror=()=>n(s.error),s.readAsText(e)});function iB({token:e=""}){Fn();const t=_N(),n=y.useRef(null),s=h=>yN(e,h),[i,l]=y.useState(null),c=()=>{try{const h=URL.createObjectURL(new Blob([JO()],{type:"application/json"})),p=document.createElement("a");p.href=h,p.download="nexuscrew-preferences.json",document.body.appendChild(p),p.click(),p.remove(),setTimeout(()=>URL.revokeObjectURL(h),1e3),l({ok:!0,text:f("prefs-export-done")})}catch(h){l({ok:!1,text:String((h==null?void 0:h.message)||h)})}},u=async h=>{const p=h.target.files&&h.target.files[0];if(h.target.value="",!p)return;let v="";try{v=await sB(p)}catch(g){l({ok:!1,text:String((g==null?void 0:g.message)||g)});return}if(!rv(M_())&&!window.confirm(f("prefs-import-confirm")))return;const _=QO(v);l(_.ok?{ok:!0,text:f("prefs-import-done")}:{ok:!1,text:f(_.reason==="not-json"||_.reason==="wrong-kind"?"prefs-import-wrong":_.reason==="storage-write-failed"?"prefs-import-storage":"prefs-import-bad")})};return o.jsxs("div",{className:"nc-set-form nc-prefs-backup",children:[o.jsx("div",{className:"nc-sheet-label",children:f("prefs-backup")}),o.jsxs("div",{"data-testid":"sync-status",className:"nc-set-hint",children:[f("prefs-sync"),": ",t.status,t.revision!==void 0?` (r${t.revision})`:"",t.code?` · ${t.code}`:"",t.note?` · ${t.note}`:""]}),t.status==="conflict"&&o.jsxs("div",{className:"nc-set-confirm",role:"group","aria-label":f("prefs-conflict"),children:[o.jsx("div",{children:f("prefs-conflict")}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>s("local"),children:f("prefs-keep-local")}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>s("server"),children:f("prefs-use-server")})]})]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:f("prefs-export")}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>n.current&&n.current.click(),children:f("prefs-import")}),o.jsx("input",{ref:n,type:"file",accept:"application/json,.json","aria-label":f("prefs-import"),style:{display:"none"},onChange:u})]}),i&&o.jsx("div",{className:i.ok?"nc-set-note":"nc-err",role:i.ok?"status":"alert",children:i.text})]})}function rB({text:e}){const[t,n]=y.useState(!1),s=async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),1500)}catch{}};return o.jsxs("div",{className:"nc-set-copyline",children:[o.jsx("code",{children:e}),o.jsxs("button",{type:"button",className:"nc-btn ghost",onClick:s,children:[o.jsx(yt,{name:"copy",size:14})," ",f(t?"copied":"copy")]})]})}function oB({value:e}){const[t,n]=y.useState("");return y.useEffect(()=>{let s=!0;return e4.toDataURL(e,{margin:1,width:220}).then(i=>{s&&n(i)}).catch(()=>{}),()=>{s=!1}},[e]),t?o.jsx("img",{src:t,width:"220",height:"220",alt:"NexusCrew pairing QR"}):null}function aB({token:e,nodes:t,roster:n,settings:s,readonly:i,refresh:l,refreshAliases:c,vlUnavailable:u=[],accessRevision:h=null}){const[p,v]=y.useState(null),[_,g]=y.useState(null),[w,S]=y.useState(null),[N,C]=y.useState({ssh:"",sshPort:"",name:""}),[j,E]=y.useState(""),[R,x]=y.useState(""),[W,$]=y.useState(!1),[Y,q]=y.useState(null),K=Date.now(),se=s&&s.deviceName||"",V=(t||[]).filter(L=>L&&L.direction==="outbound"&&L.name&&L.ssh),B=V.find(L=>L.name===j)||V[0]||null,D=B?Wg(B.tunnel,K):null,O=B!=null&&B.shared?D!=null&&D.up?"share-local-active":"share-local-pending":D!=null&&D.up?"share-local-private":"share-local-private-down",P=[{key:"peer-group-hubs",rows:(t||[]).filter(L=>L.kind!=="transitive"&&L.kind!=="vl"&&L.relation!=="client")},{key:"peer-group-clients",rows:(t||[]).filter(L=>L.kind!=="transitive"&&L.kind!=="vl"&&L.relation==="client")},{key:"peer-group-routed",rows:(t||[]).filter(L=>L.kind==="transitive")},{key:"peer-group-vl",rows:(t||[]).filter(L=>L.kind==="vl")}],z=Y&&(t||[]).find(L=>`${L.kind||"direct"}:${L.nodeId||L.name}`===Y)||null,A=async L=>{if(B){v(null),g(`${B.name}:share`);try{const H=await Y5(e,B.name,L);await l(),H&&H.reversePoolPending===!0&&v(`${B.name}: ${f("share-reverse-pool-pending")}`)}catch(H){const M=H!=null&&H.data&&H.data.shared===!1?H.data:null;if(M)try{await l()}catch{}const U=H!=null&&H.data&&typeof H.data.hint=="string"?H.data.hint:"",ee=(M==null?void 0:M.revoked)===!0&&(M==null?void 0:M.localReconcilePending)===!0?f("share-off-local-reconcile-pending"):(M==null?void 0:M.revoked)===!1&&(M==null?void 0:M.reconcilePending)===!0?f("share-off-hub-reconcile-pending"):"",re=H!=null&&H.data&&H.data.reversePoolPending===!0?f("share-reverse-pool-pending"):"",oe=H!=null&&H.data&&typeof H.data.code=="string"?H.data.code:"",je=H!=null&&H.data&&typeof H.data.detail=="string"?H.data.detail.trim():"",te=je&&je!==String(H.message||"")?je:"";v(`${B.name}: ${String(H.message||H)}${oe?` [${oe}]`:""}${te?` — ${te}`:""}${U?` — ${U}`:""}${ee?` — ${ee}`:""}${re?` — ${re}`:""}`)}g(null)}},T=async()=>{v(null);const L=mo(N.name||R||se||"NexusCrew"),H=GP({name:L,ssh:N.ssh,sshPort:N.sshPort});if(!H.ok){v(f(H.error));return}g("invite");try{S(await q5(e,{...R||se?{label:R||se}:{},name:L,ssh:H.value.ssh,...H.value.sshPort?{sshPort:H.value.sshPort}:{}}))}catch(M){v(String(M.message||M))}g(null)};return o.jsxs("div",{className:"nc-set-tab",children:[o.jsx("div",{className:"nc-sheet-label",children:f("peer-inventory-title")}),(t||[]).length===0&&o.jsx("div",{className:"nc-empty",children:f("no-nodes")}),P.map(L=>L.rows.length>0&&o.jsxs("div",{className:"nc-peer-group",children:[o.jsxs("div",{className:"nc-peer-group-title",children:[f(L.key)," ",o.jsx("span",{children:L.rows.length})]}),L.rows.map(H=>{const M=h4(H);if(!M)return null;const U=`${H.kind||"direct"}:${H.nodeId||H.name}`,ee=M.routed?{up:M.reach.up,since:null}:Wg(H.tunnel,K);return o.jsxs("button",{type:"button",className:`nc-set-node nc-node-row${M.routed?" routed":""}`,"aria-label":`${M.title} — ${f("node-detail-open")}`,onClick:()=>q(U),children:[o.jsx("span",{className:`nc-dot ${M.reach.up?"on":""}`}),o.jsxs("span",{className:"nc-node-row-text",children:[o.jsx("b",{children:M.title}),o.jsxs("small",{children:[M.routed?M.routeLabel:`${M.subtitle} · ${f(M.exposure.shortKey)}`,!M.routed&&M.exposure.shortKey==="visibility-selected"?` (${M.exposure.count})`:""]})]}),o.jsxs("span",{className:`nc-set-tunnel${M.reach.up?" up":""}`,children:[f(M.reach.key),ee.since?` · ${ee.since}`:""]}),o.jsx("span",{className:"nc-node-row-more",children:o.jsx(yt,{name:"chevronDown",size:14})})]},U)})]},L.key)),u.length>0&&o.jsxs("div",{className:"nc-err",children:[f("vl-owners-unavailable"),": ",u.map(L=>L.label||L.route.join("/")).join(", ")]}),z&&o.jsx(P4,{node:z,nodes:t||[],token:e,readonly:i,refresh:l,onClose:()=>q(null),peerAccessRevision:h}),(n||[]).some(L=>!L.direct&&L.instanceId)&&o.jsxs("div",{className:"nc-set-form",children:[o.jsx("div",{className:"nc-sheet-label",children:f("routed-node-aliases")}),o.jsx("small",{className:"nc-set-hint",children:f("routed-node-aliases-help")}),(n||[]).filter(L=>!L.direct&&L.instanceId).map(L=>o.jsxs("div",{className:"nc-set-node",children:[o.jsxs("div",{className:"nc-set-node-head",children:[o.jsx("span",{className:`nc-dot ${L.status==="up"?"on":""}`}),o.jsx("b",{children:L.label||L.name}),o.jsx("small",{children:(L.route||[]).join(" › ")})]}),o.jsxs("div",{className:"nc-set-node-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:i||!!_,onClick:async()=>{const H=window.prompt(f("node-local-alias"),L.alias||"");if(H!=null){if(H.trim()&&!tl(H.normalize("NFC"))){v(f("err-label"));return}g(`${L.instanceId}:alias`),v(null);try{H.trim()?await V5(e,L.instanceId,H):await fw(e,L.instanceId),c()}catch(M){v(String(M.message||M))}g(null)}},children:f("alias-on-device")}),L.alias&&o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:i||!!_,onClick:async()=>{g(`${L.instanceId}:alias-reset`),v(null);try{await fw(e,L.instanceId),c()}catch(H){v(String(H.message||H))}g(null)},children:f("reset-alias")})]})]},L.instanceId))]}),B&&o.jsxs("div",{className:"nc-set-form nc-local-share",children:[o.jsx("div",{className:"nc-sheet-label",children:f("share-local-heading")}),V.length>1&&o.jsxs("label",{className:"nc-field",children:[f("share-local-hub"),o.jsx("select",{value:B.name,disabled:i||!!_,onChange:L=>E(L.target.value),children:V.map(L=>o.jsx("option",{value:L.name,children:L.label||L.name},L.name))})]}),o.jsxs("label",{className:"nc-check nc-node-share",children:[o.jsx("input",{type:"checkbox",checked:B.shared===!0,disabled:i||!!_,onChange:L=>A(L.target.checked)}),o.jsxs("span",{children:[o.jsx("b",{children:f("share-local-through").replace("{device}",se||f("local")).replace("{hub}",B.label||B.name)}),o.jsx("small",{children:f(B.shared?"share-node-on-desc":"share-node-off-desc")})]})]}),o.jsx("div",{className:`nc-set-test${B.shared&&(D!=null&&D.up)?" ok":D!=null&&D.up?"":" ko"}`,children:f(O)}),!(D!=null&&D.up)&&o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:i||!!_,onClick:()=>A(B.shared===!0),children:f("share-local-reconnect")})]}),o.jsx(PE,{token:e,deviceDefault:se,localNodeId:s&&s.nodeId||"",localNameDefault:s&&s.localName||"",readonly:i,onSuccess:l}),o.jsxs("div",{className:"nc-set-form",children:[o.jsx("div",{className:"nc-sheet-label",children:f("invite-node")}),o.jsx("small",{className:"nc-set-hint",children:f("invite-v2-hint")}),o.jsxs("div",{className:"nc-set-info nc-invite-endpoint",children:[f("invite-target-local"),": ",o.jsx("b",{children:se||f("invite-target-this")})]}),o.jsxs("label",{className:"nc-field",children:[f("invite-endpoint-label"),o.jsx("input",{placeholder:"user@host",value:N.ssh,disabled:i,onChange:L=>C({...N,ssh:L.target.value})}),o.jsx("small",{className:"nc-set-hint",children:f("invite-endpoint-needed")})]}),V.length>0&&o.jsx("small",{className:"nc-set-hint nc-invite-hub-hint",children:f("invite-hub-only")}),W&&o.jsxs("div",{className:"nc-invite-advanced",children:[o.jsxs("label",{className:"nc-field",children:[f("node-ssh-port-label"),o.jsx("input",{inputMode:"numeric",placeholder:"22",value:N.sshPort,disabled:i,onChange:L=>C({...N,sshPort:L.target.value.replace(/[^0-9]/g,"").slice(0,5)})})]}),o.jsxs("label",{className:"nc-field",children:[f("device-name-label"),o.jsx("input",{placeholder:se||"NexusCrew",value:R,disabled:i,onChange:L=>x(L.target.value)}),o.jsx("small",{className:"nc-set-hint",children:f("device-name-hint")})]}),o.jsxs("label",{className:"nc-field",children:[f("node-name-label"),o.jsx("input",{placeholder:mo(R||se||f("node-name-ph")),value:N.name,disabled:i,onChange:L=>C({...N,name:L.target.value?mo(L.target.value):""})})]})]}),o.jsxs("div",{className:"nc-set-row nc-invite-actions",children:[o.jsx("button",{type:"button",className:"nc-btn primary",disabled:i||!!_||!N.ssh.trim(),onClick:T,children:f("create-pairing-link")}),o.jsxs("button",{type:"button",className:"nc-btn ghost",disabled:!!_,onClick:()=>$(L=>!L),children:[W?"▾":"▸"," ",f("pair-advanced")]})]}),w&&o.jsxs(o.Fragment,{children:[o.jsx(oB,{value:w.pairingUrl}),o.jsx(rB,{text:w.pairingUrl}),o.jsx("div",{className:"nc-set-info",children:f("invite-next-steps")})]})]}),p&&o.jsx("div",{className:"nc-err",children:p})]})}function lB({token:e,readonly:t}){const[n,s]=y.useState("idle"),[i,l]=y.useState(()=>zE()),[c,u]=y.useState(!1),[h,p]=y.useState(null);y.useEffect(()=>{let g=!1;return FE().then(w=>{g||s(w)}),()=>{g=!0}},[]);const v=async()=>{p(null),u(!0);try{n==="subscribed"?(await wx(e),s("idle")):(await HE(e),s("subscribed"))}catch(g){const w=String(g.message||g);w==="push-denied"?(s("denied"),p(f("push-denied"))):w==="push-unsupported"?(s("unsupported"),p(f("push-unsupported"))):p(w==="push-disabled-local"?f("push-local-disabled"):w)}u(!1)},_=async()=>{const g=E4({enabled:i.enabled!==!1});if(l(g),p(null),g.enabled===!1&&n==="subscribed"){u(!0);try{await wx(e),s("idle")}catch{}u(!1)}};return n==="unsupported"?o.jsx("div",{className:"nc-set-info",children:f("push-unsupported")}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:_,disabled:c,children:i.enabled===!1?f("push-local-on"):f("push-local-off")}),o.jsx("span",{className:"nc-set-info",children:i.enabled===!1?f("push-local-off-note"):f("push-local-help")})]}),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:t||c||n==="denied",title:t?f("settings-readonly"):"",onClick:v,children:f(n==="subscribed"?"push-disable":"push-enable")}),o.jsx("span",{className:"nc-set-info",children:f(n==="subscribed"?"push-on":n==="denied"?"push-denied":"push-off")})]}),h&&o.jsx("div",{className:"nc-err",children:h})]})}function cB(){const[e,t]=hN(),[n,s]=y.useState(""),[i,l]=y.useState(""),[c,u]=y.useState(!1),[h,p]=y.useState(lN),v=y.useRef(0),_=y.useRef(!1),g=y.useRef(null),w=Kc();y.useEffect(()=>()=>{var C;v.current+=1,_.current&&((C=g.current)==null||C.abort(),g.current=null,_.current=!1,sv())},[]);const S=async()=>{const C=v.current+=1,j=typeof AbortController=="function"?new AbortController:null;s(""),l(""),u(!0),p(!1),_.current=!0,g.current=j;const E=await OO(f("notification-speech-preview"),Jo(),void 0,j?{signal:j.signal}:{});return C!==v.current||(g.current=null,_.current=!1,u(!1),p(E===!0),E===!0?l(f("notification-speech-preview-ok")):s(f(E==="voice-error"?"notification-speech-preview-voice-error":E==="timeout"?"notification-speech-preview-timeout":"notification-speech-preview-failed"))),E},N=C=>{var j;if(t(C),s(""),l(""),C)S();else{v.current+=1;const E=_.current;(j=g.current)==null||j.abort(),g.current=null,_.current=!1,u(!1),p(!1),sv(),E||dN()}};return o.jsxs("div",{className:"nc-set-form",children:[o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox","aria-label":f("notification-speech-enable"),checked:e,disabled:!w,onChange:C=>N(C.target.checked)}),o.jsxs("span",{children:[o.jsx("b",{children:f("notification-speech-enable")}),o.jsx("small",{children:f("notification-speech-help")})]})]}),w?o.jsx("div",{className:"nc-set-row",children:o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!e||c,onClick:()=>{S()},children:f(c?"notification-speech-testing":"notification-speech-test")})}):o.jsx("div",{className:"nc-set-info",children:f("notification-speech-unsupported")}),e&&!h&&!c&&!n&&o.jsx("div",{className:"nc-set-info",children:f("notification-speech-needs-test")}),i&&o.jsx("div",{className:"nc-set-info",role:"status",children:i}),n&&o.jsx("div",{className:"nc-err",children:n})]})}function uB({token:e,readonly:t,nodes:n=[],settings:s=null}){const[i,l]=y.useState(null),[c,u]=y.useState([]),[h,p]=y.useState({name:"",mode:"primary-failover",targets:[]}),[v,_]=y.useState(null),[g,w]=y.useState(!1),[S,N]=y.useState(null),[C,j]=y.useState(""),E=y.useCallback(async()=>{try{const[A,T]=await Promise.all([J5(e),tj(e)]);l(A),u(Array.isArray(T==null?void 0:T.groups)?T.groups:[]),j("")}catch(A){j(String(A.message||A))}},[e]);y.useEffect(()=>{E()},[E]);const R=async A=>{w(!0),N(null),j("");try{l(await Q5(e,A))}catch(T){j(String(T.message||T))}w(!1)},x=async()=>{w(!0),N(null),j("");try{N({kind:"test",...await Z5(e)})}catch(A){j(String(A.message||A))}w(!1)},W=async()=>{w(!0),N(null),j("");try{N({kind:"stop",...await ej(e)})}catch(A){j(String(A.message||A))}w(!1)},$=[],Y=new Set,q=(A,T)=>{const L=typeof A=="string"?A.toLowerCase():"";!/^[a-f0-9]{32}$/.test(L)||Y.has(L)||(Y.add(L),$.push({id:L,label:T||L}))};q(s==null?void 0:s.nodeId,f("audio-group-local"));for(const A of n||[])q((A==null?void 0:A.nodeId)||(A==null?void 0:A.instanceId),(A==null?void 0:A.label)||(A==null?void 0:A.name)||(A==null?void 0:A.nodeId));for(const A of h.targets)q(A,`${A} (${f("audio-group-unavailable-target")})`);const K=(A=null)=>{j(""),A?(_(A.name),p({name:A.name,mode:A.mode,targets:[...A.targets||[]]})):(_(null),p({name:"",mode:"primary-failover",targets:[]}))},se=(A,T)=>p(L=>({...L,targets:T?[...new Set([...L.targets,A])]:L.targets.filter(H=>H!==A)})),V=async()=>{const A=h.name.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{0,31}$/.test(A)||h.targets.length<1){j(f("audio-group-invalid"));return}w(!0),j("");try{const T=await nj(e,A,{targets:h.targets,mode:h.mode}),L=T==null?void 0:T.group;if(!L||!L.name)throw new Error(f("audio-group-save-failed"));u(H=>[...H.filter(M=>M.name!==L.name),L].sort((M,U)=>M.name.localeCompare(U.name))),K(null)}catch(T){j(String(T.message||T))}w(!1)},B=async A=>{w(!0),j("");try{await sj(e,A),u(T=>T.filter(L=>L.name!==A)),v===A&&K(null)}catch(T){j(String(T.message||T))}w(!1)},D=(i==null?void 0:i.installed)===!0,O=(i==null?void 0:i.liveness)==="ready",P=(i==null?void 0:i.consent)===!0&&D&&O,z=S?S.kind==="stop"?f(S.stopped?"audio-stop-stopped":"audio-stop-idle"):S.status==="accepted"||S.status==="spoken"?f("audio-test-accepted"):S.status==="unknown"?f("audio-test-unknown"):`${f("audio-test-refused")}${S.reason?` (${S.reason})`:""}`:"";return o.jsxs("div",{className:"nc-set-tab nc-audio-settings",children:[o.jsxs("div",{className:"nc-set-info",children:[o.jsx("b",{children:f("audio-title")}),o.jsx("br",{}),f("audio-help")]}),i?o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox","aria-label":f("audio-consent"),checked:i.consent===!0,disabled:t||g,onChange:A=>{R(A.target.checked)}}),o.jsxs("span",{children:[o.jsx("b",{children:f("audio-consent")}),o.jsx("small",{children:f("audio-consent-help")})]})]}),o.jsxs("div",{className:"nc-set-form",children:[o.jsx("div",{className:"nc-sheet-label",children:f("audio-capability")}),o.jsxs("div",{className:"nc-set-info",children:[f("audio-adapter"),": ",i.adapter||f("audio-adapter-none"),o.jsx("br",{}),f("audio-installed"),": ",f(D?"audio-installed-yes":"audio-installed-no"),o.jsx("br",{}),f("audio-liveness"),": ",f(O?"audio-liveness-ready":"audio-liveness-unavailable"),Array.isArray(i.languages)&&i.languages.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),f("audio-languages"),": ",i.languages.join(", ")]})]}),i.limits&&o.jsxs("small",{className:"nc-set-hint",children:[f("audio-limits"),": ",i.limits]})]}),!i.consent&&o.jsx("div",{className:"nc-set-info",children:f("audio-test-needs-consent")}),!D&&o.jsx("div",{className:"nc-set-info",children:f("audio-unavailable")}),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn primary",disabled:t||g||!P,title:t?f("settings-readonly"):"",onClick:()=>{x()},children:f(g?"audio-testing":"audio-test")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:g,onClick:()=>{W()},children:f(g?"audio-stopping":"audio-stop")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:g,onClick:()=>{E()},children:f("refresh")})]}),o.jsxs("div",{className:"nc-set-form",children:[o.jsx("div",{className:"nc-sheet-label",children:f("audio-groups-title")}),o.jsx("small",{className:"nc-set-hint",children:f("audio-groups-help")}),c.length===0&&o.jsx("div",{className:"nc-set-info",children:f("audio-groups-empty")}),c.map(A=>{var T;return o.jsxs("div",{className:"nc-set-row",children:[o.jsxs("span",{children:[o.jsx("b",{children:A.name})," ",o.jsxs("small",{children:["· ",A.mode==="fanout"?f("audio-group-fanout"):f("audio-group-primary")," · ",((T=A.targets)==null?void 0:T.length)||0]})]}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:t||g,onClick:()=>K(A),children:f("audio-group-edit")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:t||g,onClick:()=>{B(A.name)},children:f("audio-group-delete")})]},A.name)}),o.jsx("div",{className:"nc-set-row",children:o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:t||g,onClick:()=>K(null),children:f("audio-group-new")})}),o.jsxs("label",{className:"nc-field",children:[f("audio-group-name"),o.jsx("input",{"aria-label":f("audio-group-name"),value:h.name,maxLength:"32",disabled:t||g,onChange:A=>p(T=>({...T,name:A.target.value}))})]}),o.jsxs("label",{className:"nc-field",children:[f("audio-group-mode"),o.jsxs("select",{"aria-label":f("audio-group-mode"),value:h.mode,disabled:t||g,onChange:A=>p(T=>({...T,mode:A.target.value})),children:[o.jsx("option",{value:"primary-failover",children:f("audio-group-primary")}),o.jsx("option",{value:"fanout",children:f("audio-group-fanout")})]})]}),o.jsx("div",{className:"nc-set-info",children:f("audio-group-targets")}),$.length===0?o.jsx("small",{className:"nc-set-hint",children:f("audio-group-no-targets")}):$.map(A=>o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:h.targets.includes(A.id),disabled:t||g,onChange:T=>se(A.id,T.target.checked)}),o.jsxs("span",{children:[A.label,o.jsx("small",{children:A.id})]})]},A.id)),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn primary",disabled:t||g,onClick:()=>{V()},children:f("audio-group-save")}),v&&o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:g,onClick:()=>K(null),children:f("audio-group-cancel")})]})]})]}):o.jsx("div",{className:"nc-set-info",children:f("audio-loading")}),z&&o.jsx("div",{className:"nc-set-note",role:"status",children:z}),C&&o.jsx("div",{className:"nc-err",children:C})]})}function dB(){const[e,t]=o_(),[n,s]=y.useState(sN),[i,l]=y.useState(rN),[c,u]=y.useState(oN);return o.jsxs("div",{className:"nc-set-tab nc-input-settings",children:[o.jsx("div",{className:"nc-set-info",children:f("input-settings-local")}),o.jsxs("div",{className:"nc-set-form",children:[o.jsxs("label",{className:"nc-field",children:[f("terminal-keyboard-gesture"),o.jsx("select",{"aria-label":f("terminal-keyboard-gesture"),value:e.terminalKeyboardGesture,onChange:h=>t({terminalKeyboardGesture:h.target.value}),children:lE.map(h=>o.jsx("option",{value:h,children:f(`terminal-keyboard-${h}`)},h))}),o.jsx("small",{children:f("terminal-keyboard-gesture-help")})]}),o.jsxs("label",{className:"nc-field",children:[f("keybar-layout"),o.jsx("select",{"aria-label":f("keybar-layout"),value:e.keybarLayout,onChange:h=>t({keybarLayout:h.target.value}),children:cE.map(h=>o.jsx("option",{value:h,children:f(`keybar-layout-${h}`)},h))}),o.jsx("small",{children:f("keybar-layout-help")})]})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:e.showComposer,onChange:h=>t({showComposer:h.target.checked})}),o.jsxs("span",{children:[o.jsx("b",{children:f("bar-menu-keyboard")}),o.jsx("small",{children:f("bar-menu-keyboard-desc")})]})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:n,onChange:h=>{s(h.target.checked),iN(h.target.checked)}}),o.jsxs("span",{children:[o.jsx("b",{children:f("bar-menu-files")}),o.jsx("small",{children:f("bar-menu-files-setting-desc")})]})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:i,onChange:h=>{l(h.target.checked),wO(h.target.checked)}}),o.jsxs("span",{children:[o.jsx("b",{children:f("bar-keyboard-button")}),o.jsx("small",{children:f("bar-keyboard-button-desc")})]})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:c,onChange:h=>{u(h.target.checked),SO(h.target.checked)}}),o.jsxs("span",{children:[o.jsx("b",{children:f("bar-panel-button")}),o.jsx("small",{children:f("bar-panel-button-desc")})]})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:e.keybarKeepsKeyboardClosed,onChange:h=>t({keybarKeepsKeyboardClosed:h.target.checked})}),o.jsxs("span",{children:[o.jsx("b",{children:f("keybar-ime-lock")}),o.jsx("small",{children:f("keybar-ime-lock-help")})]})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:e.voiceKeepsKeyboardClosed,onChange:h=>t({voiceKeepsKeyboardClosed:h.target.checked})}),o.jsxs("span",{children:[o.jsx("b",{children:f("voice-ime-lock")}),o.jsx("small",{children:f("voice-ime-lock-help")})]})]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:e.showKeybarEnter,onChange:h=>t({showKeybarEnter:h.target.checked})}),o.jsxs("span",{children:[o.jsx("b",{children:f("keybar-enter-show")}),o.jsx("small",{children:f("keybar-enter-show-help")})]})]}),o.jsx("div",{className:"nc-set-row",children:o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>t(Er),children:f("input-settings-reset")})})]})}function hB({token:e,roster:t=[],readonly:n}){const s=[{key:"local",route:[],label:f("diagnostics-local"),status:"up"},...t.filter(P=>Array.isArray(P.route)&&P.route.length).map(P=>({key:P.route.join("/"),route:P.route,label:P.label||P.name,status:P.status}))],[i,l]=y.useState("local"),c=s.find(P=>P.key===i)||s[0],[u,h]=y.useState(null),[p,v]=y.useState([]),[_,g]=y.useState(""),[w,S]=y.useState(!1),[N,C]=y.useState(!0),[j,E]=y.useState(900),[R,x]=y.useState("all"),[W,$]=y.useState(""),Y=y.useRef(0),q=y.useRef(null),K=y.useCallback(async()=>{try{const P=await aj(e,c.route);if(h(P),g(""),!w){const z=await lj(e,{after:Y.current,limit:200},c.route);Array.isArray(z.records)&&z.records.length&&(Y.current=z.cursor,v(A=>[...A,...z.records].slice(-500)))}}catch(P){g(P&&P.status===404?f("diagnostics-unsupported"):String(P.message||P))}},[e,c.key,w]);y.useEffect(()=>{Y.current=0,v([]),h(null),g("")},[c.key]),y.useEffect(()=>{let P=null,z=!0;const A=()=>{!z||document.visibilityState==="hidden"||K()},T=()=>{P&&clearInterval(P),P=document.visibilityState==="hidden"?null:setInterval(A,2e3),document.visibilityState!=="hidden"&&A()};return document.addEventListener("visibilitychange",T),T(),()=>{z=!1,P&&clearInterval(P),document.removeEventListener("visibilitychange",T)}},[K]),y.useEffect(()=>{N&&q.current&&(q.current.scrollTop=q.current.scrollHeight)},[p,N]);const se=p.filter(P=>(R==="all"||P.level===R)&&(!W||String(P.component||"").toLowerCase().includes(W.toLowerCase()))),V=se.map(P=>`${P.ts} ${P.level.toUpperCase()} ${P.component} ${P.code} ${P.message}${Object.keys(P.meta||{}).length?` ${JSON.stringify(P.meta)}`:""}`).join(`
168
+ `),B=async P=>{g("");try{const z=await P();h(z),await K()}catch(z){g(String(z.message||z))}},D=async()=>{try{await navigator.clipboard.writeText(V)}catch{g(f("copy-manual"))}},O=()=>{try{const P=new Blob([`${JSON.stringify(se,null,2)}
169
+ `],{type:"application/json"});JC(P,"nexuscrew-diagnostics.json")}catch{g(f("diagnostics-export-failed"))}};return o.jsxs("div",{className:"nc-set-tab nc-diagnostics",children:[o.jsxs("label",{className:"nc-field",children:[f("diagnostics-target"),o.jsx("select",{value:c.key,onChange:P=>l(P.target.value),children:s.map(P=>o.jsxs("option",{value:P.key,children:[P.label,P.status!=="up"?` · ${P.status}`:""]},P.key))})]}),o.jsxs("div",{className:"nc-set-form nc-diag-controls",children:[o.jsx("div",{className:"nc-sheet-label",children:f("diagnostics-verbose")}),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("select",{"aria-label":f("diagnostics-duration"),value:j,onChange:P=>E(Number(P.target.value)),disabled:n,children:[300,900,1800,3600].map(P=>o.jsxs("option",{value:P,children:[P/60," min"]},P))}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(u==null?void 0:u.verbose)===!0,onClick:()=>B(()=>pw(e,!0,j,c.route)),children:f("enable")}),o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||(u==null?void 0:u.verbose)!==!0,onClick:()=>B(()=>pw(e,!1,j,c.route)),children:f("stop")})]}),o.jsx("small",{className:"nc-set-hint",children:u!=null&&u.verbose?f("diagnostics-expires").replace("{time}",new Date(u.expiresAt).toLocaleTimeString()):f("diagnostics-off")})]}),o.jsxs("div",{className:"nc-diag-filters",children:[o.jsxs("select",{"aria-label":f("diagnostics-level"),value:R,onChange:P=>x(P.target.value),children:[o.jsx("option",{value:"all",children:f("diagnostics-all-levels")}),["debug","info","warn","error"].map(P=>o.jsx("option",{value:P,children:P},P))]}),o.jsx("input",{"aria-label":f("diagnostics-component"),placeholder:f("diagnostics-component"),value:W,onChange:P=>$(P.target.value)})]}),o.jsxs("div",{className:"nc-set-row",children:[o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:w,onChange:P=>S(P.target.checked)})," ",f("diagnostics-pause")]}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:N,onChange:P=>C(P.target.checked)})," ",f("diagnostics-autoscroll")]})]}),o.jsx("pre",{ref:q,className:"nc-diag-log","aria-label":f("diagnostics-log"),children:V||f("diagnostics-empty")}),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:D,children:f("copy")}),o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:O,children:f("diagnostics-export")}),o.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(f("diagnostics-clear-confirm"))&&B(async()=>{const P=await cj(e,c.route);return Y.current=0,v([]),P})},children:f("diagnostics-clear")})]}),_&&o.jsx("div",{className:"nc-err",children:_})]})}function fB(){typeof window<"u"&&window.location&&typeof window.location.reload=="function"&&window.location.reload()}function pB({token:e,settings:t,readonly:n,refresh:s,roster:i,section:l,setSection:c}){const[u,h]=y.useState(Pc),[p,v]=y.useState(null),[_,g]=y.useState(null),[w,S]=y.useState(!1),[N,C]=y.useState(!1),[j,E]=y.useState(null),[R,x]=y.useState(!1),[W,$]=y.useState(!1),[Y,q]=y.useState(null);y.useEffect(()=>{E(t&&t.update||null),x(!!(t&&t.autoUpdate===!0)),$(!!(t&&t.alternateScreen))},[t]);const K=async()=>{v(null),g(null),C(!0);try{const L=await U5(e);g(L.note||"ok"),S(!1)}catch(L){v(String(L.message||L))}C(!1)},se=async()=>{v(null),g(null),C(!0);try{const L=await ij(e);g(`${L.note||"ok"}${L.target?` (${L.target})`:""}`)}catch(L){v(String(L.message||L))}C(!1)},V=async L=>{v(null),g(null),C(!0);try{await Bd(e,{autoUpdate:L}),x(L),s&&await s()}catch(H){v(String(H.message||H))}C(!1)},B=async L=>{v(null),g(null),C(!0);try{await Bd(e,{alternateScreen:L}),$(L),s&&await s()}catch(H){v(String(H.message||H))}C(!1)},D=y.useCallback(async()=>{if(e)try{q(await H5(e))}catch{q(null)}},[e]);y.useEffect(()=>{D()},[D]);const O=async L=>{v(null),g(null),C(!0);try{if(!L&&Y&&Y.running&&!window.confirm(f("ai-desktop-confirm-stop"))){C(!1);return}const H=await _1(e,L);H&&H.ok===!1&&v(H.error||"comando fallito"),await D(),s&&await s()}catch(H){v(String(H.message||H))}C(!1)},P=async()=>{v(null),g(null),C(!0);try{E(await rj(e))}catch(L){v(String(L.message||L))}C(!1)},z=async()=>{v(null),g(null),C(!0);try{const L=await oj(e);E(L),g(f("npm-update-restarting"))}catch(L){v(String(L.message||L))}C(!1)},A=()=>{window.confirm(f("composer-clear-confirm"))&&(v(null),WD()?(window.dispatchEvent(new Event(Vg)),g(f("composer-clear-done"))):v(f("composer-clear-failed")))},T=t&&t.service;return o.jsxs("div",{className:"nc-set-tab",children:[o.jsx("div",{className:"nc-system-tabs",role:"tablist","aria-label":f("tab-system"),children:["general","diagnostics"].map(L=>o.jsx("button",{type:"button",role:"tab","aria-selected":l===L,className:`nc-set-tabbtn${l===L?" on":""}`,onClick:()=>c(L),children:f(`system-${L}`)},L))}),l==="general"&&o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"nc-system-group",children:[o.jsx("div",{className:"nc-set-info",children:f("input-settings-local")}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:u===vo,onChange:L=>{const H=eC(L.target.checked?vo:_o);h(H),fB()}}),o.jsxs("span",{children:[o.jsx("b",{children:f("bar-menu-renderer")}),o.jsx("small",{children:f("bar-menu-renderer-desc")})]})]})]}),o.jsxs("section",{className:"nc-system-group",children:[o.jsx("h3",{children:f("system-this-node")}),t&&o.jsxs("div",{className:"nc-set-info",children:["v",t.version," · ",t.platform," · :",t.port,o.jsx("br",{}),T&&T.installed?f("service-installed"):f("service-missing"),T&&T.installed?` · ${T.active?f("service-active"):f("service-inactive")}`:"",T?` · boot ${T.boot?"on":"off"}`:""]}),o.jsx("div",{className:"nc-set-row",children:o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||N,title:n?f("settings-readonly"):"",onClick:se,children:f("service-regenerate")})}),o.jsx(lB,{token:e,readonly:n}),o.jsx(cB,{})]}),o.jsxs("section",{className:"nc-system-group",children:[o.jsx("h3",{children:f("system-updates")}),o.jsxs("div",{className:"nc-set-form nc-update-settings",children:[o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox",checked:R,disabled:n||N||j&&!j.supported,onChange:L=>V(L.target.checked)}),o.jsxs("span",{children:[o.jsx("b",{children:f("npm-auto-update")}),o.jsx("small",{children:f("npm-auto-update-help")})]})]}),j&&o.jsxs("div",{className:"nc-set-info",children:[f("npm-update-current")," v",j.current,j.latest?` · ${f("npm-update-latest")} v${j.latest}`:""," · ",f(j.supported?j.phase==="idle"&&j.checked!==!0?"npm-update-never":`npm-update-${j.phase}`:"unsupported")]}),o.jsxs("div",{className:"nc-set-row",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||N||!j||!j.supported,onClick:P,children:f("npm-update-check")}),j&&j.available&&o.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||N||j.phase==="installing",onClick:z,children:f("npm-update-install")})]}),j&&j.lastError&&o.jsx("div",{className:"nc-err",children:j.lastError})]})]}),o.jsxs("section",{className:"nc-system-group",children:[o.jsx("h3",{children:f("ai-desktop-title")}),o.jsxs("div",{className:"nc-set-form",children:[o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox","aria-label":f("ai-desktop"),disabled:n||N,checked:!!(Y&&Y.desired),onChange:L=>O(L.target.checked)}),o.jsxs("span",{children:[o.jsx("b",{children:f("ai-desktop")}),o.jsx("small",{children:f("ai-desktop-help")})]})]}),Y&&!Y.desired&&Y.running&&o.jsx("div",{className:"nc-set-info",children:f("ai-desktop-stop-pending")})]})]}),o.jsxs("section",{className:"nc-system-group",children:[o.jsx("h3",{children:f("system-security")}),o.jsx("div",{className:"nc-set-row",children:o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||N,title:n?f("settings-readonly"):"",onClick:()=>{v(null),g(null),S(!0)},children:f("token-rotate")})})]}),o.jsxs("section",{className:"nc-system-group",children:[o.jsx("h3",{children:f("system-local-data")}),o.jsxs("div",{className:"nc-set-form",children:[o.jsx("div",{className:"nc-sheet-label",children:f("composer-clear-data")}),o.jsx("small",{className:"nc-set-hint",children:f("composer-clear-data-help")}),o.jsx("div",{className:"nc-set-row",children:o.jsx("button",{type:"button",className:"nc-btn ghost",onClick:A,children:f("composer-clear-data")})})]})]})]}),l==="diagnostics"&&o.jsxs("section",{className:"nc-system-group nc-system-diagnostics",children:[o.jsx("h3",{children:f("system-diagnostics")}),o.jsxs("div",{className:"nc-set-form nc-alternate-screen-settings",children:[o.jsx("div",{className:"nc-sheet-label",children:f("system-terminal")}),o.jsxs("label",{className:"nc-check",children:[o.jsx("input",{type:"checkbox","aria-label":f("alternate-screen"),checked:W,disabled:n||N,onChange:L=>B(L.target.checked)}),o.jsxs("span",{children:[o.jsx("b",{children:f("alternate-screen")}),o.jsx("small",{children:f("alternate-screen-help")})]})]})]}),o.jsx(iB,{token:e}),o.jsx(HO,{}),o.jsx(hB,{token:e,roster:i,readonly:n})]}),w&&o.jsxs("div",{className:"nc-set-confirm",children:[o.jsx("div",{children:f("token-rotate-explain")}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:N,onClick:()=>S(!1),children:f("cancel")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:N,onClick:K,children:f("confirm")})]})]}),_&&o.jsx("div",{className:"nc-set-note",children:_}),p&&o.jsx("div",{className:"nc-err",children:p})]})}function mB({token:e,onClose:t,initialTab:n="nodes",initialLocation:s="",startNewCell:i=!1}){Fn();const l=n==="diagnostics"?"diagnostics":"general",[c,u]=y.useState(n==="diagnostics"?"system":n),h=y.useRef(null),p=y.useRef(null),[v,_]=y.useState({start:!1,end:!1}),[g,w]=y.useState(l),[S,N]=y.useState(null),[C,j]=y.useState([]),[E,R]=y.useState(null),[x,W]=y.useState([]),[$,Y]=y.useState(!1),[q,K]=y.useState(null),[se,V]=y.useState(0),B=Vv(e,!0,se),D=y.useCallback(()=>{const M=h.current;if(!M)return;const U=M.scrollWidth>M.clientWidth+1,ee={start:U&&M.scrollLeft>1,end:U&&M.scrollLeft+M.clientWidth<M.scrollWidth-1};_(re=>re.start===ee.start&&re.end===ee.end?re:ee)},[]);y.useEffect(()=>{const M=h.current;if(!M)return;const U=typeof ResizeObserver=="function"?new ResizeObserver(D):null;return U==null||U.observe(M),window.addEventListener("resize",D),D(),()=>{U==null||U.disconnect(),window.removeEventListener("resize",D)}},[D]),y.useEffect(()=>{var U,ee;(ee=(U=p.current)==null?void 0:U.scrollIntoView)==null||ee.call(U,{behavior:"smooth",block:"nearest",inline:"nearest"});const M=window.requestAnimationFrame?window.requestAnimationFrame(D):setTimeout(D,0);return()=>{window.cancelAnimationFrame?window.cancelAnimationFrame(M):clearTimeout(M)}},[c,D]);const O=y.useRef(mh()),P=y.useRef(null),z=y.useRef([]),A=y.useRef(new Map),T=y.useRef({token:null,instanceId:null}),L=y.useCallback((M,U)=>{if(!M.isCurrent(U))return;const ee=z.current,re=[],oe=new Set;for(const je of A.current.values())for(const te of je){const ie=Array.isArray(te.route)&&te.route.length?te.route.join("/"):"local",pe=`${te.ownerInstanceId}:${ie}:${te.nodeId||te.name||te.label||""}`;oe.has(pe)||(oe.add(pe),re.push(te))}j([...ee,...re])},[]),H=y.useCallback(async()=>{const M=O.current,U=M.begin();if(U===null)return;const ee=new AbortController;P.current=ee;const re={timeoutMs:l1,signal:ee.signal};try{const oe=m1(e,re).then(ie=>{M.isCurrent(U)&&(N(ie),K(null))}).catch(ie=>{M.isCurrent(U)&&K(String((ie==null?void 0:ie.message)||ie))}),je=z5(e,re).then(ie=>{if(!M.isCurrent(U))return;const pe=ie.peers||[];z.current=pe,R(Number.isInteger(ie.accessRevision)?ie.accessRevision:null),L(M,U)}).catch(ie=>{M.isCurrent(U)&&K(String((ie==null?void 0:ie.message)||ie))}),te=(async()=>{const[ie,pe]=await Promise.all([Yc(e,[],re).then(J=>J).catch(()=>null),v1(e,re).then(J=>J).catch(()=>null)]);if(!M.isCurrent(U))return;const xe=ie&&typeof ie.instanceId=="string"?ie.instanceId:"";if(!xe)return;T.current.instanceId!==xe&&(A.current.clear(),T.current.instanceId=xe);const Be=[{instanceId:xe||null,route:[],label:null},...fC(pe,xe)],Te=J=>`${J.instanceId}:${J.route.join("/")}`;if(pe){const J=new Set(Be.map(Te));for(const le of A.current.keys())J.has(le)||A.current.delete(le)}if(!pe)for(const[J,le]of A.current)le.some(Q=>Q.route.length)&&A.current.set(J,le.map(Q=>({...Q,stale:!0,online:!1,canManage:!1,capabilities:[]})));const Me=new Map;W([]),L(M,U),await Promise.allSettled(Be.map(async J=>{const le=Te(J);try{const Q=await g1(e,J.route,{signal:ee.signal});if(!M.isCurrent(U))return;const ge=(Q.nodes||[]).map(Z=>hC(Z,J)).filter(Boolean);A.current.set(le,ge),Me.delete(le)}catch(Q){if(!M.isCurrent(U))return;if((Q==null?void 0:Q.status)===403||(Q==null?void 0:Q.status)===404)A.current.delete(le);else{const Z=A.current.get(le);Z&&A.current.set(le,Z.map(fe=>({...fe,stale:!0,online:!1,canManage:!1,capabilities:[]})))}J.route.length>0&&Me.set(le,{instanceId:J.instanceId,label:J.label,route:J.route,failure:/timeout/i.test(String((Q==null?void 0:Q.message)||Q))?"timeout":"unreachable"})}M.isCurrent(U)&&(W([...Me.values()]),L(M,U))}))})();await Promise.allSettled([oe,je,te])}finally{P.current===ee&&(P.current=null),M.end(U)}},[e,L]);return y.useEffect(()=>{T.current.token!==e&&(T.current={token:e,instanceId:null},z.current=[],A.current.clear(),j([]),W([]),R(null)),H();const M=setInterval(H,5e3);return()=>{clearInterval(M),O.current.reset(),P.current&&P.current.abort()}},[H]),y.useEffect(()=>{let M=!1;return Vn("/api/config",e).then(U=>U.json()).then(U=>{M||Y(!!U.readonlyDefault)}).catch(()=>{}),()=>{M=!0}},[e]),o.jsx("div",{className:"nc-set-overlay",onClick:t,children:o.jsxs("div",{className:"nc-set-panel",onClick:M=>M.stopPropagation(),children:[o.jsxs("div",{className:"nc-set-head",children:[o.jsx(yt,{name:"gear",size:18}),o.jsx("b",{children:f("settings")}),o.jsx("button",{type:"button",className:"nc-set-close",onClick:t,title:f("close"),children:o.jsx(yt,{name:"x",size:18})})]}),$&&o.jsx("div",{className:"nc-set-readonly",children:f("settings-readonly")}),q&&o.jsx("div",{className:"nc-err",children:q}),o.jsx("div",{className:`nc-set-tabs-wrap${v.start?" has-start-overflow":""}${v.end?" has-end-overflow":""}`,children:o.jsx("div",{className:"nc-set-tabs",ref:h,onScroll:D,children:["nodes","fleet","audio","input","system"].map(M=>o.jsx("button",{ref:c===M?p:null,type:"button",className:`nc-set-tabbtn${c===M?" on":""}`,onClick:()=>u(M),children:f(`tab-${M}`)},M))})}),o.jsxs("div",{className:"nc-set-body",children:[c==="nodes"&&o.jsx(aB,{token:e,nodes:C,roster:B,settings:S,readonly:$,vlUnavailable:x,accessRevision:E,refresh:H,refreshAliases:()=>V(M=>M+1)}),c==="fleet"&&o.jsx(bO,{token:e,readonly:$,startNewCell:i,initialLocation:s,targets:B.map(M=>({route:M.route,label:M.label||M.name,status:M.status}))}),c==="audio"&&o.jsx(uB,{token:e,readonly:$,nodes:C,settings:S}),c==="input"&&o.jsx(dB,{}),c==="system"&&o.jsx(pB,{token:e,settings:S,readonly:$,refresh:H,roster:B,section:g,setSection:w})]})]})})}function gB({token:e,initialPair:t,deviceDefault:n="",localNodeId:s="",localNameDefault:i="",deviceNameNeeded:l=!1,deviceNameSuggestion:c="",onPairDone:u,onDone:h}){Fn();const[p,v]=y.useState(t?"pair":"welcome"),[_,g]=y.useState(!1),[w,S]=y.useState(null),[N,C]=y.useState(c||""),[j,E]=y.useState(null),R=async()=>{g(!0),S(null);try{const x={wizardDone:!0};l&&N.trim()&&(x.deviceName=N.trim()),await Bd(e,x),u&&u(),h()}catch(x){S(String(x.message||x)),g(!1)}};return o.jsx("div",{className:"nc-wiz-overlay",children:o.jsxs("div",{className:"nc-wiz",children:[o.jsxs("div",{className:"nc-wiz-head",children:[o.jsx("b",{children:f("wizard-title")}),o.jsx("small",{children:f("hydra-simple")})]}),p==="welcome"&&o.jsxs("div",{className:"nc-wiz-body",children:[o.jsx("div",{className:"nc-wiz-done",children:f("local-ready")}),l&&o.jsx("div",{className:"nc-wiz-done",children:f("wizard-device-name")}),l&&o.jsxs("label",{className:"nc-field",children:[o.jsx("span",{children:f("device-name-label")}),o.jsx("input",{value:N,onChange:x=>C(x.target.value),maxLength:64,"data-testid":"wizard-device-name-input"})]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{className:"nc-btn ghost",disabled:_,onClick:R,children:f("local-only")}),o.jsx("button",{className:"nc-btn primary",disabled:_,onClick:()=>v("pair"),children:f("add-node")})]})]}),p==="pair"&&o.jsxs("div",{className:"nc-wiz-body",children:[o.jsx(PE,{token:e,initial:t||"",autoStart:!!t,deviceDefault:l&&N.trim()?N.trim():n,localNodeId:s,localNameDefault:i,onBusyChange:g,onSuccess:async x=>{E(x&&x.authorizedKeys?{line:x.authorizedKeys,note:x.authorizedKeysNote||""}:null),u&&u(),v("done")}}),o.jsx("div",{className:"nc-sheet-actions",children:o.jsx("button",{className:"nc-btn ghost",disabled:_,onClick:()=>{u&&u(),v("welcome")},children:f("back")})})]}),p==="done"&&o.jsxs("div",{className:"nc-wiz-body",children:[o.jsx("div",{className:"nc-wiz-done",children:f("node-connected")}),j&&o.jsx(v_,{line:j.line,note:j.note}),o.jsx("div",{className:"nc-sheet-actions",children:o.jsx("button",{className:"nc-btn primary",disabled:_,onClick:R,children:f("finish")})})]}),w&&o.jsx("div",{className:"nc-err",children:w})]})})}function vB({token:e,suggestion:t="",onSaved:n,onLater:s}){Fn();const[i,l]=y.useState(t||""),[c,u]=y.useState(!1),[h,p]=y.useState(null),v=async()=>{const _=i.trim();if(_){u(!0),p(null);try{await Bd(e,{deviceName:_}),n&&n(_)}catch(g){p(String(g.message||g)),u(!1)}}};return o.jsx("div",{className:"nc-wiz-overlay",role:"dialog","aria-label":f("device-name-ask-title"),"data-testid":"device-name-ask",children:o.jsxs("div",{className:"nc-wiz",children:[o.jsx("div",{className:"nc-wiz-head",children:o.jsx("b",{children:f("device-name-ask-title")})}),o.jsxs("div",{className:"nc-wiz-body",children:[o.jsx("p",{className:"nc-wiz-done",children:f("device-name-ask-text")}),o.jsxs("label",{className:"nc-field",children:[o.jsx("span",{children:f("device-name-label")}),o.jsx("input",{value:i,onChange:_=>l(_.target.value),maxLength:64,"data-testid":"device-name-input"})]}),o.jsxs("div",{className:"nc-sheet-actions",children:[o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:c,onClick:s,children:f("device-name-later")}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:c||!i.trim(),onClick:v,children:f("device-name-save")})]})]}),h&&o.jsx("div",{className:"nc-err",children:h})]})})}const _B=50;function yB(e){if(Number.isFinite(e))return e;const t=typeof e=="string"?Date.parse(e):NaN;return Number.isFinite(t)?t:0}function bN(e,t){return`${String(e)}|${String(t)}`}function Bx(e,t){if(!e||typeof e!="object")return null;const n=e.frame&&typeof e.frame=="object"?e.frame:e;if(n.type!=="notify"||!e.eventId||typeof n.askId=="string"&&n.askId)return null;const s=typeof n.title=="string"?n.title:"",i=typeof n.body=="string"?n.body:"";return!s&&!i?null:{key:bN(t,e.eventId),ownerId:String(t),eventId:String(e.eventId),title:s,body:i,urgency:n.urgency==="high"?"high":"normal",ts:yB(e.emittedAt??(e.frame&&e.frame.ts)??e.ts),arrivalSeq:0}}function $x(e){return[...e].sort((t,n)=>n.ts-t.ts).slice(0,_B)}function zx(e,t,n,s=null){const i=new Set((t||[]).map(c=>c&&c.key)),l=new Map;for(const c of e||[])s&&s.owners.has(c.ownerId)&&!i.has(c.key)&&!s.arrivedAfter(c)||(!n||n.has(c.ownerId))&&l.set(c.key,c);for(const c of t||[])c&&l.set(c.key,c);return[...l.values()]}function bB(e,t,n,s){if(typeof EventSource>"u"||!e)return()=>{};const i=new EventSource(`/api/events?token=${encodeURIComponent(e)}`);return i.onopen=()=>{typeof n=="function"&&n()},i.onerror=()=>{typeof s=="function"&&s()},i.onmessage=l=>{try{const c=JSON.parse(l.data);c&&typeof c=="object"&&typeof c.type=="string"&&t(c)}catch{}},()=>{try{i.close()}catch{}}}const wB=6e3,SB=12e3,ns=(e,t,n)=>`${t||""}:${n||e}`,xB=(e,t)=>{const n=e&&e[t];return n?n.stale===!0||n.error===!0?"degraded":"live":"missing"},wN=600*1e3,Fx=30*1e3,kB=300*1e3,uv=new Map,CB=900*1e3,Ka=new Map;function Em(e){Ka.set(e,Date.now()),Ka.size>4096&&Ka.delete(Ka.keys().next().value)}function Nm(e){const t=Ka.get(e);return t===void 0?!1:Date.now()-t>CB?(Ka.delete(e),!1):!0}const EB={pending:"ask-dismiss-local-pending",blocked:"ask-dismiss-local-blocked"},NB=e=>EB[e]||e,Xo=e=>Object.hasOwn(e,"ownerAskTs")?e.ownerAskTs:e.ownerAskId||e.originNode?null:e.ts;function SN(e,t){uv.set(e,t?{at:Date.now(),local:!0,ts:Xo(t),fingerprint:t.question===void 0?null:JSON.stringify([t.question,t.options||[],t.session])}:{at:Date.now()})}function xN(e){const t=ns(e.id,e.ownerId,e.ownerAskId),n=uv.get(t);if(n===void 0)return!1;if(n.local){const s=Xo(e);return!(n.ts&&s&&n.ts!==s)&&(n.fingerprint===null||n.fingerprint===JSON.stringify([e.question,e.options||[],e.session]))}return Date.now()-n.at>wN?(uv.delete(t),!1):!0}function Od(e,t){const n=new Map(e.map(s=>[ns(s.id,s.ownerId,s.ownerAskId),s]));for(const s of t||[]){if(!s||!s.id||xN(s))continue;const i=ns(s.id,s.ownerId,s.ownerAskId),l=n.get(i),c=Xo(s),u=l&&Xo(l);(!l||Number.isSafeInteger(c)&&c>0&&Number.isSafeInteger(u)&&u>0&&c>u)&&n.set(i,s)}return[...n.values()]}function jB(e,t){const n=Od([],e.filter(l=>l.imported)),s=new Set(n.map(l=>ns(l.id,l.ownerId,l.ownerAskId)));return[...(t||[]).filter(l=>l&&l.id&&!s.has(ns(l.id,l.ownerId,l.ownerAskId))&&!xN(l)),...n]}function LB({n:e,onClose:t}){return o.jsxs("div",{className:`nc-ntf-toast${e.urgency==="high"?" high":""}`,role:"status","aria-live":"polite",children:[o.jsxs("div",{className:"nc-ntf-toast-txt",children:[o.jsx("b",{children:e.title}),e.body&&o.jsx("small",{children:e.body}),e.session&&o.jsx("span",{className:"nc-ntf-from",children:e.session}),e.ownerId&&o.jsx("span",{className:"nc-ntf-from",children:f("feed-owner")})]}),o.jsx("button",{type:"button",className:"nc-ntf-x",onClick:t,title:f("close"),children:o.jsx(yt,{name:"x",size:14})})]})}function RB({ask:e,token:t,onAnswered:n,onDismiss:s,askReplyAccess:i=!1,feedViewState:l="live",initialUncertainRid:c=null,canDismissLocal:u=!1,canDismissRemote:h=!1,capabilityStatus:p="loading",onRefused:v=()=>{}}){const[_,g]=y.useState(""),[w,S]=y.useState(!1),[N,C]=y.useState(null),[j,E]=y.useState(!1),[R,x]=y.useState(c),[W,$]=y.useState(!1),[Y,q]=y.useState(!1),K=y.useRef(null);y.useEffect(()=>{c&&x(c)},[c]);const se=j||w||!!R||Y||!!e.ownerId&&p==="loading",V=!!e.ownerId&&!h,B=async P=>{const z=String(P||"").trim();if(!(!z||w||j||R||Y)){C(null),S(!0);try{if(e.ownerId){const A=e.ownerAskId||e.id,T=await fj(t,{ownerId:e.ownerId,askId:A,text:z,requestId:K.current||(K.current=crypto.randomUUID())});if(T&&T.uncertain){const L=T.reason==="delivery-unknown-block"&&!T.originalRequestId;x(L?null:T.originalRequestId||T.requestId||K.current),q(L);return}if(!T||T.status!=="committed"){K.current=null,v(),C(f("ask-reconcile"));return}n(e.id,e.ownerId,e.ownerAskId)}else await dj(t,e.id,z),n(e.id)}catch(A){C(String(A.message||A)),e.ownerId&&!A.status?x(K.current):K.current=null,v()}finally{S(!1)}}},D=async()=>{if(!se){C(null),E(!0);try{let P;if(V){if(P=await _j(t,{ownerId:e.ownerId,askId:e.ownerAskId||e.id}),(P==null?void 0:P.dismissed)!==!0||P.scope!=="local"||!["pending","blocked"].includes(P.ownerSync))throw new Error(f("ask-dismiss-unconfirmed"))}else e.ownerId?await vj(t,{ownerId:e.ownerId,askId:e.ownerAskId||e.id}):await hj(t,e.id);SN(ns(e.id,e.ownerId,e.ownerAskId),V?e:null),s(e.id,e.ownerId,e.ownerAskId,P)}catch(P){C(String(P&&P.message||P)),v()}finally{E(!1)}}},O=f(R||Y?"ask-uncertain":V?"ask-dismiss-local":l==="degraded"?"ask-dismiss-stale":"ask-dismiss");return o.jsxs("div",{className:"nc-ask-card",children:[o.jsxs("div",{className:"nc-ask-head",children:[o.jsx("span",{className:"nc-ntf-from",children:e.session}),e.ownerId&&o.jsx("span",{className:"nc-ntf-from",children:f("feed-owner")}),o.jsxs("code",{className:"nc-ask-id",children:["#",e.id]}),o.jsx("button",{type:"button",className:"nc-ask-dismiss",title:O,"aria-label":O,disabled:se,onClick:D,children:o.jsx(yt,{name:"x",size:14})})]}),o.jsx("div",{className:"nc-ask-q",children:e.question}),e.ownerId&&i===!1&&o.jsx("small",{className:"nc-set-hint",children:f(p==="loading"?"ask-capability-loading":p==="unsupported"?"ask-capability-unsupported":p==="unreachable"?"ask-capability-unreachable":"ask-remote-readonly")}),e.ownerId&&i!==!1&&l==="degraded"&&o.jsx("small",{className:"nc-set-hint",children:f("ask-feed-stale")}),(R||Y)&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"nc-err",children:f("ask-uncertain")}),Y&&!R&&o.jsx("div",{className:"nc-err",children:f("ask-reconcile")}),R&&o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:W,onClick:async()=>{$(!0);try{const P=await pj(t,{ownerId:e.ownerId,askId:e.ownerAskId||e.id,requestId:R});(P==null?void 0:P.state)==="committed"?n(e.id,e.ownerId,e.ownerAskId):(P==null?void 0:P.state)==="failed"&&(x(null),K.current=null,v())}catch(P){C(String(P.message||P)),v()}finally{$(!1)}},children:f("ask-verify")})]}),(!e.ownerId||i===!0)&&!R&&!Y&&o.jsxs(o.Fragment,{children:[Array.isArray(e.options)&&e.options.length>0&&o.jsx("div",{className:"nc-ask-opts",children:e.options.map(P=>o.jsx("button",{type:"button",className:"nc-btn ghost",disabled:w||j,onClick:()=>B(P),children:P},P))}),o.jsxs("div",{className:"nc-ask-reply",children:[o.jsx("textarea",{rows:2,placeholder:f("ask-reply-ph"),value:_,disabled:w||j,onChange:P=>g(P.target.value)}),o.jsx("button",{type:"button",className:"nc-btn primary",disabled:w||j||!_.trim(),onClick:()=>B(_),children:f("send")})]})]}),N&&o.jsx("div",{className:"nc-err",children:N})]})}function AB({token:e}){const[t]=Fn(),[n]=hN(),[s,i]=y.useState([]),[l,c]=y.useState([]),[u,h]=y.useState(null),[p,v]=y.useState([]),[_,g]=y.useState(()=>{try{return/(?:^|[#&])ask=/.test(location.hash)}catch{return!1}}),[w,S]=y.useState({}),N=y.useRef(new Map),C=y.useRef(0),[j,E]=y.useState(0),R=y.useRef(new Map),x=y.useRef(0),W=y.useRef(0),$=y.useRef(new Map),Y=y.useRef(new Map),q=y.useRef(new Map),K=te=>(te||[]).filter(ie=>{const pe=R.current.get(ns(ie.id,ie.ownerId,ie.ownerAskId));if(!pe)return!0;if(Date.now()-pe.at>wN)return R.current.delete(ns(ie.id,ie.ownerId,ie.ownerAskId)),!0;const xe=Xo(ie);return Number.isSafeInteger(xe)&&xe>0&&Number.isSafeInteger(pe.ts)&&pe.ts>0?xe!==pe.ts:pe.fingerprint!==null&&pe.fingerprint!==void 0&&pe.fingerprint!==JSON.stringify([ie.question,ie.options||[],ie.session])}),se=y.useRef(l);se.current=l;const V=y.useCallback((te=!1)=>{if(!e)return;const ie=new Set;for(const pe of se.current){if(!pe.ownerId)continue;const xe=pe.ownerAskId||pe.id,Be=`${pe.ownerId}|${xe}`;ie.add(Be);const Te=N.current.get(Be);if(Te&&(!te||Te.pending))continue;const Me=new AbortController,J=C.current,le={controller:Me,pending:!0};N.current.set(Be,le),S(Q=>({...Q,[Be]:{canReply:!1,status:"loading"}})),mj(e,{ownerId:pe.ownerId,askId:xe},{signal:Me.signal}).then(Q=>{if(J!==C.current||Me.signal.aborted||N.current.get(Be)!==le)return;const ge=Q&&Q.ownerId===pe.ownerId&&Q.askId===xe&&typeof Q.canReply=="boolean"&&(!Q.canReply||Q.status==="open");S(Z=>({...Z,[Be]:ge?Q:{canReply:!1,status:"unreachable"}}))}).catch(()=>{J===C.current&&!Me.signal.aborted&&N.current.get(Be)===le&&S(Q=>({...Q,[Be]:{canReply:!1,status:"unreachable"}}))}).finally(()=>{le.pending=!1})}for(const[pe,xe]of N.current)ie.has(pe)||(xe.controller.abort(),N.current.delete(pe))},[e]);y.useEffect(()=>{C.current++;for(const te of N.current.values())te.controller.abort();return N.current.clear(),S({}),()=>{C.current++;for(const te of N.current.values())te.controller.abort();N.current.clear()}},[e]),y.useEffect(()=>{V()},[l,V]);const B=y.useRef(!1);y.useEffect(()=>{_&&(B.current&&V(!0),B.current=!0)},[_,V]);const D=y.useRef(0),O=y.useRef(null);O.current||(O.current=BO());const P=y.useRef({enabled:n,lang:t});P.current={enabled:n,lang:t};const z=y.useCallback(te=>{i(ie=>ie.filter(pe=>pe.key!==te))},[]),A=y.useCallback(te=>{if(te.askId&&te.ownerId){const xe=Number.isSafeInteger(te.ownerAskTs)&&te.ownerAskTs>0?te.ownerAskTs:te.ownerAskFingerprint;if(xe){const Be=JSON.stringify([te.ownerId,te.ownerAskId||te.askId,xe]),Te=Date.now();for(const[Me,J]of q.current)Te-J>1440*60*1e3&&q.current.delete(Me);if(q.current.has(Be))return;q.current.set(Be,Te),q.current.size>4096&&q.current.delete(q.current.keys().next().value)}}const ie=`t${D.current+=1}`;i(xe=>[...xe.slice(-3),{...te,key:ie}]),setTimeout(()=>z(ie),te.urgency==="high"?SB:wB);const pe=P.current;if(pe.enabled)try{O.current.enqueue(te,TO(te,pe.lang))}catch{}},[z]);y.useEffect(()=>{n||O.current.stop()},[n]),y.useEffect(()=>{const te=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&O.current.stop()},ie=()=>O.current.stop();return document.addEventListener("visibilitychange",te),window.addEventListener("blur",te),window.addEventListener(nv,ie),()=>{document.removeEventListener("visibilitychange",te),window.removeEventListener("blur",te),window.removeEventListener(nv,ie),typeof O.current.dispose=="function"?O.current.dispose():O.current.stop()}},[]);const T=te=>{if(te.ownerAskId||!te.ownerId)return te;const ie=se.current.filter(xe=>xe.ownerId===te.ownerId&&(xe.id===te.id||xe.ownerAskId===te.id)),pe=new Set(ie.map(xe=>xe.ownerAskId||xe.id));return pe.size>1?null:{...te,ownerAskId:pe.size===1?[...pe][0]:te.id}},L=(te,ie)=>{const pe=se.current.find(Be=>ns(Be.id,Be.ownerId,Be.ownerAskId)===te),xe=pe&&Xo(pe);return Number.isSafeInteger(ie==null?void 0:ie.ownerAskTs)&&ie.ownerAskTs>0&&Number.isSafeInteger(xe)&&xe>0&&ie.ownerAskTs!==xe},H=(te,ie,pe,xe)=>{const Be=ns(te,ie,pe);(xe==null?void 0:xe.scope)==="local"&&["pending","blocked"].includes(xe.ownerSync)&&h(xe.ownerSync);const Te=se.current.find(le=>ns(le.id,le.ownerId,le.ownerAskId)===Be),Me=Te&&Xo(Te);if(L(Be,xe))return;const J=Te||(xe==null?void 0:xe.askGeneration);R.current.set(Be,{at:Date.now(),ts:Te?Me:xe==null?void 0:xe.ownerAskTs,fingerprint:J&&J.question!==void 0?JSON.stringify([J.question,J.options||[],J.session]):null}),$.current.delete(Be),R.current.size>4096&&R.current.delete(R.current.keys().next().value),c(le=>le.filter(Q=>ns(Q.id,Q.ownerId,Q.ownerAskId)!==Be))},M=async te=>{h(null);try{const ie=await bj(e,{ownerId:te.ownerId,eventId:te.eventId});if(!ie||ie.dismissed!==!0)throw new Error(f("remote-notices-dismiss-failed"));(ie.ownerSync==="pending"||ie.ownerSync==="blocked")&&h(ie.ownerSync),Em(te.key),v(pe=>pe.filter(xe=>xe.key!==te.key))}catch{h("remote-notices-dismiss-failed")}},U=async()=>{const te=p,ie=[...new Set(te.map(pe=>pe.ownerId))];if(ie.length!==0){h(null);try{const pe=await wj(e,{owners:ie}),xe=pe&&pe.results||{},Be=new Set;let Te=null;for(const Me of ie){const J=xe[Me];if(!J||J.failed){Te!=="blocked"&&(Te="failed");continue}J.blocked?Te="blocked":J.pending&&Te!=="blocked"&&Te!=="failed"&&(Te="pending"),Be.add(Me)}for(const Me of te)Be.has(Me.ownerId)&&Em(Me.key);v(Me=>Me.filter(J=>!Be.has(J.ownerId))),Te==="blocked"?h("blocked"):Te==="failed"?h("remote-notices-clear-failed"):Te==="pending"&&h("pending")}catch{h("remote-notices-clear-failed")}}};y.useEffect(()=>{if(!e)return;let te=!0,ie=!1,pe=null,xe=Fx;const Be=()=>{pe!==null&&clearTimeout(pe),pe=null},Te=()=>{!te||ie||pe!==null||(pe=setTimeout(()=>{pe=null,!(!te||ie)&&(E(J=>J+1),xe=Math.min(xe*2,kB),Te())},xe))},Me=bB(e,J=>{if(te){if(J.type==="feed-state-changed"){E(le=>le+1);return}if(J.type==="notify"&&J.ownerId&&J.eventId){const le=Bx(J,J.ownerId);le&&(le.arrivalSeq=++W.current),le&&!Nm(le.key)&&v(Q=>$x(zx(Q,[le],null)))}if(J.type==="notify-dismissed"){const le=String(J.ownerId||""),Q=String(J.eventId||"");if(le&&Q){const ge=bN(le,Q);Em(ge),v(Z=>Z.filter(fe=>fe.key!==ge))}return}if(J.type==="notify")A(J);else if(J.type==="ask"&&J.ask&&J.ask.id){const le=ns(J.ask.id,J.ask.ownerId,J.ask.ownerAskId);$.current.set(le,++x.current),$.current.size>4096&&$.current.delete($.current.keys().next().value),c(Q=>Od(Q,K([J.ask])))}else if(J.type==="ask-answered"&&J.id){const le=T(J);le&&H(le.id,le.ownerId,le.ownerAskId,J)}else if(J.type==="ask-dismissed"&&(J.id||J.ownerAskId)){const le=T(J);if(!le)return;const Q=ns(le.id,le.ownerId,le.ownerAskId);if(L(Q,J))return;const ge=J.scope==="local"&&se.current.find(Z=>ns(Z.id,Z.ownerId,Z.ownerAskId)===Q);SN(Q,J.scope==="local"?ge||{...J.askGeneration,ownerAskTs:J.ownerAskTs}:null),H(le.id,le.ownerId,le.ownerAskId,J)}}},()=>{te&&(ie=!0,xe=Fx,Be(),V(!0),E(J=>J+1))},()=>{te&&(ie=!1,Te())});return Te(),()=>{te=!1,Be(),Me()}},[e,A,V]),y.useEffect(()=>{let te=!0;const ie=x.current;return e&&uj(e).then(pe=>{te&&c(xe=>Od(jB(xe,K((pe.asks||[]).filter(Be=>!Be.ownerId||(Y.current.get(Be.ownerId)||0)<=ie))),K(xe.filter(Be=>($.current.get(ns(Be.id,Be.ownerId,Be.ownerAskId))||0)>ie))))}).catch(()=>{}),()=>{te=!1}},[e,j]);const[ee,re]=y.useState({});y.useEffect(()=>{if(!e)return;let te=!0;return gj(e).then(ie=>{if(!te)return;const pe={};for(const xe of ie&&ie.attempts||[])xe&&xe.state==="uncertain"&&xe.ownerId&&xe.askId&&xe.requestId&&(pe[xe.ownerId+"|"+xe.askId]=xe.requestId);re(pe)}).catch(()=>{}),()=>{te=!1}},[e]);const[oe,je]=y.useState({});return y.useEffect(()=>{let te=!0;const ie=x.current,pe=W.current;return yj(e).then(xe=>{if(!te)return;const Be={},Te=[],Me=new Map,J=new Set;for(const Q of xe&&xe.views||[]){Be[Q.ownerId]={stale:Q.stale===!0,error:!!Q.lastError},J.add(Q.ownerId);for(const ge of Q.asks||[])ge&&ge.id&&Te.push({...ge,ownerId:Q.ownerId,imported:!0});for(const ge of Q.notifications||[]){const Z=Bx(ge,Q.ownerId);Z&&Me.set(Z.key,Z)}}je(Be);const le=new Set((xe&&xe.views||[]).filter(Q=>{const ge=typeof Q.cursor=="string"&&/^([1-9]\d*):(\d+)$/.exec(Q.cursor);return Q.stale===!1&&Number.isSafeInteger(Q.viewEpoch)&&Q.viewEpoch>0&&ge&&Number(ge[1])===Q.viewEpoch&&Number.isSafeInteger(Number(ge[2]))&&!Q.lastError&&!Q.error&&Q.resyncRequired!==!0&&Array.isArray(Q.asks)&&Q.asks.length<=100}).map(Q=>Q.ownerId));for(const Q of le)Y.current.delete(Q),Y.current.set(Q,++x.current),Y.current.size>4096&&Y.current.delete(Y.current.keys().next().value);c(Q=>Od(Q.filter(ge=>!le.has(ge.ownerId)||($.current.get(ns(ge.id,ge.ownerId,ge.ownerAskId))||0)>ie),K(Te))),v(Q=>$x(zx(Q.filter(ge=>!Nm(ge.key)),[...Me.values()].filter(ge=>!Nm(ge.key)),J,{owners:le,arrivedAfter:ge=>(ge.arrivalSeq||0)>pe})))}).catch(()=>{}),()=>{te=!1}},[e,j]),o.jsxs(o.Fragment,{children:[u&&o.jsx("div",{className:"nc-ntf-toasts",children:o.jsxs("div",{className:"nc-ntf-toast",role:"status",children:[o.jsx("div",{className:"nc-ntf-toast-txt",children:f(NB(u))}),o.jsx("button",{type:"button",className:"nc-ntf-x",title:f("close"),onClick:()=>h(null),children:o.jsx(yt,{name:"x",size:14})})]})}),s.length>0&&o.jsx("div",{className:"nc-ntf-toasts",children:s.map(te=>o.jsx(LB,{n:te,onClose:()=>z(te.key)},te.key))}),(l.length>0||p.length>0)&&!_&&o.jsxs("button",{type:"button",className:"nc-ask-badge",onClick:()=>g(!0),title:f("asks-title"),children:["? ",o.jsx("span",{className:"nc-ask-count",children:l.length+p.length})]}),(l.length>0||p.length>0)&&_&&o.jsxs("div",{className:"nc-ask-panel",children:[o.jsxs("div",{className:"nc-ask-panel-head",children:[o.jsx("b",{children:f("asks-title")}),o.jsx("span",{className:"nc-ask-count",children:l.length}),o.jsx("button",{type:"button",className:"nc-ntf-x",onClick:()=>g(!1),title:f("close"),children:o.jsx(yt,{name:"x",size:16})})]}),o.jsxs("div",{className:"nc-ask-panel-body",children:[l.map(te=>{var ie,pe,xe,Be,Te,Me;return o.jsx(RB,{ask:te,token:e,askReplyAccess:!te.ownerId||((ie=w[te.ownerId+"|"+(te.ownerAskId||te.id)])==null?void 0:ie.canReply)===!0,canDismissLocal:((pe=w[te.ownerId+"|"+(te.ownerAskId||te.id)])==null?void 0:pe.canDismissLocal)===!0,canDismissRemote:((xe=w[te.ownerId+"|"+(te.ownerAskId||te.id)])==null?void 0:xe.canDismissRemote)===!0||((Be=w[te.ownerId+"|"+(te.ownerAskId||te.id)])==null?void 0:Be.canDismissRemote)===void 0&&((Te=w[te.ownerId+"|"+(te.ownerAskId||te.id)])==null?void 0:Te.canReply)===!0,capabilityStatus:((Me=w[te.ownerId+"|"+(te.ownerAskId||te.id)])==null?void 0:Me.status)||"loading",onRefused:()=>V(!0),feedViewState:te.ownerId?xB(oe,te.ownerId):"live",initialUncertainRid:te.ownerId&&ee[te.ownerId+"|"+(te.ownerAskId||te.id)]||null,onAnswered:H,onDismiss:H},ns(te.id,te.ownerId,te.ownerAskId))}),p.length>0&&o.jsxs("div",{className:"nc-remote-notices",children:[o.jsxs("div",{className:"nc-remote-notices-head",children:[o.jsx("b",{children:f("remote-notices-title")}),o.jsx("button",{type:"button",className:"nc-remote-notices-clear",onClick:U,children:f("remote-notices-clear")})]}),p.map(te=>o.jsxs("div",{className:"nc-remote-notice"+(te.urgency==="high"?" nc-remote-notice-high":""),children:[o.jsxs("div",{className:"nc-remote-notice-head",children:[te.title?o.jsx("b",{children:te.title}):null,o.jsx("button",{type:"button",className:"nc-ntf-x",title:f("remote-notices-dismiss"),"aria-label":f("remote-notices-dismiss"),onClick:()=>M(te),children:o.jsx(yt,{name:"x",size:14})})]}),te.body?o.jsx("div",{children:te.body}):null,o.jsxs("div",{className:"nc-remote-notice-meta",children:[te.ownerId.slice(0,8)," · ",new Date(te.ts||Date.now()).toLocaleString()]})]},te.key))]})]})]})]})}const kN="nc_fontsize",CN=9,EN=24;function dv(e=globalThis.localStorage){const t=Number(e.getItem(kN));return t>=CN&&t<=EN?t:13}function NN(e,t=globalThis.localStorage){const n=Math.max(CN,Math.min(EN,e));return t.setItem(kN,String(n)),n}async function MB(e){const t=await Vn("/api/sessions",e);if((t==null?void 0:t.ok)===!1)throw new Error(`HTTP ${t.status}`);const n=await t.json();if(!Array.isArray(n==null?void 0:n.sessions))throw new Error("invalid sessions payload");return n.sessions}async function TB(e,t=[]){var u;const[n,s]=await Promise.allSettled([t.length?bv(e,t):MB(e),rl(e,t)]),i=n.status==="fulfilled"&&Array.isArray((u=n.value)==null?void 0:u.sessions)?n.value.sessions:Array.isArray(n.value)?n.value:null,l=s.status==="fulfilled"?s.value:null,c=(l==null?void 0:l.available)===!0&&Array.isArray(l.cells)?l.cells:null;return{sessions:i,cells:c,fresh:Array.isArray(i)&&Array.isArray(c)}}function IB(e,t,n){return n===!0&&(e==null?void 0:e.degraded)!==!0&&(e==null?void 0:e.active)===!0&&e.tmux!==!1&&!!e.tmuxSession&&(t||[]).some(s=>(s==null?void 0:s.name)===e.tmuxSession)}function PB(e,t,n,s=[]){if(e.type==="session"){const c=e.value||{};return{kind:"session",key:e.key,cellName:e.label,session:e.label,node:t.length?t.join("/"):"",nodeLabel:n,route:t,live:!0,selectable:!0,working:!1,degraded:!1,active:!0,activity:e.activity||0,telemetry:c.telemetry||null,preview:c.preview||"",panelUrl:""}}const i=e.value||{},l=s.find(c=>c&&c.name===i.tmuxSession)||{};return{kind:"cell",key:e.key,cellName:i.cell,session:i.tmuxSession||i.cell,node:t.length?t.join("/"):"",nodeLabel:n,route:t,live:e.live===!0,selectable:e.live===!0,working:e.working===!0,degraded:!!i.degraded,active:i.active===!0,activity:e.activity||0,telemetry:l.telemetry||i.telemetry||null,preview:l.preview||i.preview||"",panelUrl:i.panelUrl||""}}function DB({token:e,current:t,onPick:n,onClose:s,panelPort:i=0,nodePanelPorts:l={},localNodeLabel:c="",hostByRoute:u={},onDesignateCell:h,onClearHostCell:p,onLiveHostApplied:v,sideKey:_=null,onToggleSide:g}){const[w,S]=y.useState(oD),[N,C]=y.useState(!1),[j,E]=y.useState("");y.useEffect(()=>Lc(e,[],I=>{let ce=null;if(!I.sessionsError&&I.sessionsJson)try{const Re=JSON.parse(I.sessionsJson);Re&&!Re.error&&Array.isArray(Re.sessions)&&(ce=Re.sessions)}catch{}const ye=kh({fs:I.fs,error:I.fleetError});S(Re=>({...Re,...ce?{sessions:ce}:{},...ye.kind==="data"?{cells:ye.cells,localFresh:!0}:{}}))}),[e]);const[R,x]=y.useState(null),W="stream",[$,Y]=y.useState(dv),q=I=>Y(ce=>NN(ce+I)),[K,se]=y.useState(null),[V,B]=y.useState(!1),[D,O]=y.useState(""),P=y.useRef(null),z=y.useRef(null),{pins:A,orders:T,views:L,togglePin:H,removePin:M,pinError:U,canMoveRoster:ee,moveRoster:re,stepRoster:oe}=Yv(),{groupsFor:je}=Eh(),{groups:te,hasLoaded:ie}=yC(e),pe=ie?te:w.nodeGroups||[],xe=y.useMemo(()=>je(pe||[]).filter(I=>Array.isArray(I.route)&&I.route.length&&I.kind!=="vl"),[je,pe]),Be=y.useMemo(()=>{const I=new Map,ce=Array.isArray(w.sessions)?w.sessions:[],ye=Array.isArray(w.cells)?w.cells:[],Re=new Map(ce.map(Oe=>[Oe.name,Oe])),ae=new Set(ye.map(Oe=>Oe.tmuxSession).filter(Boolean));I.set("local",e_(ye,ce.filter(Oe=>!ae.has(Oe.name)),Re));for(const Oe of xe)I.set(Oe.route.join("/"),Cc(Oe).rawItems);return I},[w,xe]),Te=y.useMemo(()=>{const I=Re=>N?"all":Ag(L,Re).filter,ce=Array.isArray(w.sessions)?w.sessions:[],ye=[];for(const[Re,ae]of Be){const Oe=xe.find(ft=>ft.route.join("/")===Re),gt=Oe&&(Oe.label||Oe.name)||"",At=Oe?Oe.route:[],Lt=Oe?Array.isArray(Oe.sessions)?Oe.sessions:[]:ce,Rt=fo(ae,A,I(Re),Di(T,Re)),zt=N?Rt:Rt.filter(ft=>{var Yt,$t;return ft.live===!0||ft.type==="cell"&&((Yt=ft.value)==null?void 0:Yt.degraded)===!0&&(($t=ft.value)==null?void 0:$t.active)===!0});ye.push(...zt.map(ft=>PB(ft,At,gt,Lt)))}return ye},[Be,xe,L,T,A,N,w.sessions]),Me=Te,J=y.useMemo(()=>R?Te.find(I=>I.key===R&&I.selectable):null,[Te,R]);y.useEffect(()=>{R&&!Te.some(I=>I.key===R&&I.selectable)&&x(null)},[Te,R]);const le=y.useMemo(()=>K?Me.find(I=>I.key===K.key):null,[Me,K]),Q=!!(K&&le);y.useEffect(()=>{U&&U.message&&E(U.message)},[U]),y.useEffect(()=>{var ye;const I=document.activeElement;(ye=z.current)==null||ye.focus();const ce=Re=>{Re.key==="Escape"&&!Q&&s()};return document.addEventListener("keydown",ce),()=>{var Re;document.removeEventListener("keydown",ce),(Re=I==null?void 0:I.focus)==null||Re.call(I)}},[s,Q]);const[ge,Z]=y.useState(""),fe={getLiveHost:I=>hh(e,I),designateHostCell:(I,ce,ye)=>fh(e,I,ce,ye),clearHostCell:(I,ce)=>ph(e,I,ce)},ve=I=>(u[Rs(I)]||{}).hostCell||null,ke=async(I,ce)=>{Z(I.key);const ye=await gh({action:ce?"remove":"use",cellId:I.cellName,route:I.route||[],api:fe});Z(""),E(f(ye.messageKey).replace("{cell}",ye.hostCell||I.cellName)),ye.ok&&v&&v({route:I.route||[],hostCell:ye.hostCell,revision:ye.revision})},Ve=I=>I.degraded?f("cell-degraded"):I.selectable?I.working?f("cell-working"):f("cell-idle"):f("cell-off"),ot=async I=>{if(E(""),!I.selectable){E(f("cell-switcher-not-active"));return}if(I.kind==="session"){n({session:I.session,...I.node?{node:I.node}:{}}),s();return}O(I.key);try{const ce=await TB(e,I.route),ye=(ce.cells||[]).find(Re=>(Re==null?void 0:Re.cell)===I.cellName&&(Re==null?void 0:Re.tmuxSession)===I.session);if(ce.fresh!==!0){n({session:I.session,...I.node?{node:I.node}:{},cellName:I.cellName}),s();return}if(!IB(ye,ce.sessions,ce.fresh)){E(f("cell-switcher-not-active"));return}n({session:I.session,...I.node?{node:I.node}:{},cellName:I.cellName}),s()}catch{n({session:I.session,...I.node?{node:I.node}:{},cellName:I.cellName}),s()}finally{O("")}},rt=I=>{if(!I.selectable){ot(I);return}if(R===I.key){ot(I);return}x(I.key)},$e=y.useRef(null),_e=8,ze=I=>{const ce=$e.current;if(I.isPrimary===!1){ce&&ce.state==="open"&&(ce.state="invalid");return}if(ce&&ce.state==="open"&&(ce.id!==I.pointerId||ce.row!==I.currentTarget)){ce.state="invalid";return}$e.current={id:I.pointerId,row:I.currentTarget,x:I.clientX,y:I.clientY,maxDelta:0,state:"open"}},Je=I=>{const ce=$e.current;!ce||ce.state!=="open"||ce.id!==I.pointerId||(ce.maxDelta=Math.max(ce.maxDelta,Math.hypot(I.clientX-ce.x,I.clientY-ce.y)),ce.maxDelta>_e&&(ce.state="invalid"))},He=I=>{const ce=$e.current;!ce||ce.id!==I.pointerId||ce.state!=="open"||(ce.state=ce.maxDelta<=_e?"tap":"invalid")},nt=I=>{const ce=$e.current;ce&&ce.id===I.pointerId&&(ce.state="invalid")},lt=I=>{const ce=$e.current;return $e.current=null,I.detail===0?!0:!ce||ce.state==="invalid"||ce.row!==I.currentTarget?!1:Math.hypot(I.clientX-ce.x,I.clientY-ce.y)<=_e},X=I=>({onToggleLive:()=>ke(I,ve(I.route||[])===I.cellName),onTogglePin:()=>Xv({view:Nh({item:{key:I.key,value:{cell:I.cellName}},pins:A,hostByRoute:u,route:I.route||[]}),itemKey:I.key,togglePin:H,removePin:M})});return o.jsxs("div",{className:"nc-cell-switcher-backdrop",onClick:s,children:[J&&o.jsxs("div",{className:"nc-cell-switcher-anteprima","data-testid":"cell-switcher-anteprima",onClick:I=>I.stopPropagation(),children:[o.jsxs("div",{className:"nc-cell-switcher-anteprima-testa",children:[o.jsxs("b",{children:[f("cell-switcher-preview-word")," ",J.cellName]}),o.jsx("small",{children:f("cell-switcher-preview-readonly")}),o.jsxs("span",{className:"nc-cell-switcher-anteprima-zoom",children:[o.jsx("button",{type:"button",onClick:()=>q(-1),title:f("zoom-out"),"aria-label":f("zoom-out"),children:"−"}),o.jsxs("span",{"data-testid":"cell-switcher-fontsize",children:[$," px"]}),o.jsx("button",{type:"button",onClick:()=>q(1),title:f("zoom-in"),"aria-label":f("zoom-in"),children:"+"})]})]}),o.jsx(Hv,{row:J,token:e,source:W,chrome:!1,panelPort:Oc(J.route||[],l,i),liveHost:Ja({liveHost:u[Rs(J.route||[])],cells:w.cells||[]}),onLiveHostApplied:v,fontSize:$,readOnly:!0})]}),o.jsxs("aside",{ref:P,className:`nc-cell-switcher${J?" with-anteprima":""}`,role:"dialog","aria-label":f("fleet-cells"),tabIndex:-1,onClick:I=>I.stopPropagation(),children:[o.jsxs("div",{className:"nc-cell-switcher-controls",children:[o.jsx("b",{children:f("cell-switcher-title")}),c&&o.jsx("small",{className:"nc-cell-switcher-node",children:c}),o.jsxs("div",{className:"nc-cell-switcher-filter",role:"group","aria-label":f("cell-switcher-filter"),children:[o.jsx("button",{type:"button",className:N?"":"on","aria-pressed":!N,onClick:()=>{E(""),C(!1)},children:f("cell-switcher-show-active")}),o.jsx("button",{type:"button",className:N?"on":"","aria-pressed":N,onClick:()=>{E(""),C(!0)},children:f("cell-switcher-show-all")})]}),o.jsx("button",{type:"button",className:`nc-cell-switcher-reorder${V?" on":""}`,"aria-pressed":V,title:f("reorder-help"),"aria-label":f("reorder"),onClick:()=>{E(""),B(I=>!I)},children:"↕"}),o.jsx("button",{ref:z,type:"button",className:"nc-cell-switcher-close","aria-label":f("cell-switcher-close"),title:f("cell-switcher-close"),onClick:s,children:"×"})]}),!J&&o.jsx("div",{className:"nc-cell-switcher-hint",children:f("cell-switcher-tap-hint")}),o.jsxs("div",{className:"nc-cell-switcher-list",children:[(()=>{const I=Ja({liveHost:u[Rs([])],cells:w.cells||[]});if(!I||!I.cell)return null;const{modeKey:ce}=Dj(I);return o.jsx("div",{className:"nc-cell-switcher-live-strip","data-testid":"cell-switcher-live-strip",children:f("cell-switcher-live-strip").replace("{cell}",I.cell).replace("{mode}",f(ce||"live-host-mode-unknown"))})})(),Te.length===0&&o.jsx("div",{className:"nc-empty",role:"status",children:f("cell-switcher-empty-active")}),Te.map((I,ce)=>{const ye=(t==null?void 0:t.session)===I.session&&((t==null?void 0:t.node)||"")===I.node,Re=!!K&&K.key===I.key,ae=_!=null&&_===I.key,Oe=Ve(I),gt=jg(f,I.activity),At=Lg(f,I.telemetry),Lt=[gt,At].filter(Boolean).join(" · "),Rt=I.node||"local",zt=ce>0?Te[ce-1].node||"local":null,ft=Rt!==zt,Yt=Be.get(Rt)||Me.filter($t=>($t.node||"local")===Rt);return o.jsxs(y.Fragment,{children:[ft&&o.jsx("div",{className:"nc-cell-switcher-position",children:f("cell-switcher-group").replace("{node}",I.nodeLabel||c||f("cell-switcher-group-local"))}),o.jsxs("div",{className:`nc-cell-switcher-row${ye?" current":""}${R===I.key?" selected":""}${ae?" side":""}${I.selectable?"":" off"}`,"data-roster-key":I.key,"data-position":Rt,children:[V&&o.jsx(Qi,{position:Rt,itemKey:I.key,label:I.cellName,canMove:ee,onMove:($t,Zt)=>re(Rt,$t,Zt,Yt),onStep:$t=>oe(Rt,I.key,$t,Yt)}),o.jsx("span",{className:"nc-cell-switcher-peek",children:o.jsx("span",{className:`nc-cell-switcher-dot${I.degraded?" warn":I.live?` on${I.working?" working":""}`:""}`})}),o.jsx("button",{type:"button",className:"nc-cell-switcher-row-select","aria-current":ye?"true":void 0,"aria-disabled":!I.selectable,"data-selected":R===I.key?"true":void 0,disabled:D===I.key,onPointerDown:ze,onPointerMove:Je,onPointerUp:He,onPointerCancel:nt,onClick:$t=>{lt($t)&&rt(I)},children:o.jsxs("span",{className:"nc-cell-switcher-copy",children:[o.jsxs("span",{className:"nc-cell-switcher-nameline",children:[o.jsx("b",{children:I.cellName}),ye&&o.jsx("span",{className:"nc-cell-switcher-here",children:f("cell-switcher-here")}),R===I.key&&o.jsx("span",{className:"nc-cell-switcher-taptwo",children:f("cell-switcher-two-taps")})]}),o.jsxs("span",{className:"nc-cell-switcher-stateline",children:[o.jsx("small",{className:"nc-cell-switcher-state",children:Oe}),Lt&&o.jsx("small",{className:"nc-cell-switcher-telemetry",children:Lt})]})]})}),g&&o.jsx("button",{type:"button",className:`nc-cell-switcher-side${ae?" on":""}`,title:f(ae?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-label":f(ae?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-pressed":ae?"true":"false",disabled:ye||!I.selectable,onClick:$t=>{$t.stopPropagation(),!ye&&I.selectable&&g(I)},children:o.jsx(yt,{name:"splitView",size:20})}),o.jsx("button",{type:"button",className:`nc-cell-switcher-menu${Re?" on":""}`,title:`${f("cell-actions-open")}: ${I.cellName}`,"aria-label":`${f("cell-actions-open")}: ${I.cellName}`,"aria-haspopup":"menu","aria-expanded":Re?"true":"false",onClick:$t=>{$t.stopPropagation(),se({key:I.key})},children:"⋯"})]})]},I.key)})]}),j&&o.jsx("div",{className:"nc-cell-switcher-notice",role:"status",children:j}),Q&&(()=>{const I=le,ce=Jv({...co({item:{key:I.key,value:{cell:I.cellName}},cellName:I.cellName,route:I.route||[],pins:A,hostByRoute:u}),canBoot:!1,alive:I.selectable,handlers:X(I)});return o.jsx(Qv,{cellName:I.cellName,items:ce,busy:ge===I.key,onClose:()=>se(null)})})()]})]})}const OB=2e3;function BB(e){if(e.kind==="gap")return`${f("vl-events-gap")} ${e.count||"?"}`;if(e.kind==="truncate")return f("vl-events-truncated");if(e.kind==="turn_end")return f("vl-events-turn-end");if(e.kind==="done")return f("vl-events-done");if(e.kind==="writer_epoch")return f("vl-events-writer-epoch");if(e.kind==="tool_start")return`${f("vl-events-tool")} ${e.name||""}`.trim();if(e.kind==="tool_end"){const t=e.isError?f("vl-events-tool-failed"):f("vl-events-tool-ok");return`${f("vl-events-tool")} ${e.name||""} — ${t}`.trim()}return e.kind==="usage"?e.text||f("vl-events-usage"):e.text||""}function $B({token:e,nodeId:t,route:n=[]}){const[s,i]=y.useState([]),[l,c]=y.useState(!1),u=y.useRef(0),h=y.useRef(!1);return y.useEffect(()=>{let p=!0;u.current=0,h.current=!1,i([]);const v=async()=>{if(!h.current){h.current=!0;try{const w=await F5(e,t,u.current,n);if(!p)return;c(!1);const N=(Array.isArray(w==null?void 0:w.events)?w.events:[]).filter(C=>Number.isSafeInteger(C==null?void 0:C.seq)&&C.seq>u.current);N.length&&(i(C=>C.concat(N).slice(-500)),u.current=N[N.length-1].seq),Number.isSafeInteger(w==null?void 0:w.cursor)&&w.cursor>u.current&&(u.current=w.cursor)}catch{p&&c(!0)}finally{h.current=!1}}},_=()=>{v().catch(()=>{})};_();const g=setInterval(_,OB);return()=>{p=!1,clearInterval(g)}},[e,t,JSON.stringify(n)]),o.jsxs("div",{className:"nc-vl-events",children:[l&&o.jsx("div",{className:"nc-set-hint nc-vl-events-stale",children:f("vl-events-stale")}),s.length===0&&!l&&o.jsx("small",{className:"nc-set-hint","data-testid":"vl-events-empty",children:f("vl-events-empty")}),s.length>0&&o.jsx("ol",{className:"nc-vl-events-list",children:s.map(p=>o.jsx("li",{"data-testid":`vl-ev-${p.seq}`,className:`nc-vl-ev nc-vl-ev-${p.kind}${p.isError?" error":""}${p.kind==="gap"?" gap":""}`,children:BB(p)},`${p.seq}-${p.kind}`))})]})}function Hx({peer:e,token:t,onBack:n}){var s;return Fn(),e?o.jsxs("section",{className:"nc-vl-session-view",children:[o.jsxs("header",{className:"nc-bar nc-bar-single",children:[o.jsxs("button",{onClick:n,title:f("back"),children:[o.jsx(yt,{name:"chevronLeft",size:18}),o.jsx("span",{className:"nc-bar-label",children:f("back")})]}),o.jsxs("span",{className:"nc-bar-center",children:[o.jsx("b",{title:e.label,children:e.label}),((s=e.session)==null?void 0:s.profile)&&o.jsxs("small",{className:"nc-bar-sub",children:[e.session.profile," · ",f("vl-events-title")]})]}),o.jsx("span",{className:"nc-bar-right"})]}),o.jsx("div",{className:"nc-vl-session-body",children:o.jsx($B,{token:t,nodeId:e.nodeId,route:e.route||[]})})]}):null}const oh="nc_dual_side";function hv(e,t){return!e||!t?!1:e.session===t.session&&(e.node||"")===(t.node||"")}function zB(e,t,n){return!n||!n.session||e&&hv(e,n)?t:t&&hv(t,n)?null:{session:n.session,...n.node?{node:n.node}:{},...n.ownerId?{ownerId:n.ownerId}:{}}}function FB(){try{const e=JSON.parse(localStorage.getItem(oh)||"null");return!e||!e.main||!e.side||!e.main.session||!e.side.session?null:e}catch{return null}}function HB(e,t){try{if(!e||!t||!e.session||!t.session){localStorage.removeItem(oh);return}const n=s=>({session:s.session,...s.node?{node:s.node}:{}});localStorage.setItem(oh,JSON.stringify({main:n(e),side:n(t)}))}catch{}}function Ux(){try{localStorage.removeItem(oh)}catch{}}const UB=.2;function bd(e){return Math.max(UB,e)}function WB(){try{if(typeof matchMedia=="function"&&matchMedia("(pointer: coarse)").matches)return!0}catch{}try{return Number(globalThis.navigator&&globalThis.navigator.maxTouchPoints)>0}catch{return!1}}function qB({onSubmit:e,reason:t=""}){Fn();const[n,s]=y.useState(""),[i,l]=y.useState(WB),c=n.trim(),u=h=>{h&&h.preventDefault&&h.preventDefault(),c&&e(c,i)};return o.jsxs("form",{className:"nc-auth",onSubmit:u,children:[o.jsx("p",{children:f("auth-prompt")}),t==="invalid"&&o.jsx("p",{className:"nc-auth-error",role:"alert",children:f("auth-invalid")}),o.jsx("input",{type:"text",value:n,placeholder:"token","aria-label":"token",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:h=>s(h.target.value)}),o.jsxs("label",{children:[o.jsx("input",{type:"checkbox",checked:i,onChange:h=>l(h.target.checked)})," ",f("remember-device")]}),o.jsx("button",{type:"submit",disabled:!c,children:"ok"})]})}const jm=e=>bs(Pi(e)).length===0;function Va(e,t){return Array.isArray(e)?e.flatMap(n=>{var c;const s={session:n.session,height:1,fontSize:n.fontSize};n.node&&(s.node=n.node),n.ownerId&&(s.ownerId=n.ownerId);const i=(c=t({columns:[{width:1,tiles:[s]}]}).columns[0])==null?void 0:c.tiles[0];if(!i)return[];const l={session:i.session,x:n.x,y:n.y,w:n.w,h:n.h,fontSize:n.fontSize};return i.node&&(l.node=i.node),i.ownerId&&(l.ownerId=i.ownerId),[l]}):[]}function Wx(e,t){return e.length?e:Array.isArray(t.floating)&&t.floating.length?[]:void 0}function KB(e,t,n,s,i){const l=c=>Va(c&&c.floating,u=>Ya(u,s,i));return BP(l(e),l(t),n)}function qx(e,t,n,s,i,l){const c=_=>Ya(_,i,l),u=_=>Va(_&&_.floating,c),{grid:h,floating:p}=Jd(n),v=$P(s(h),KB(e,t,p,i,l),{grid:e?c(e.layout):po(),floating:u(e)},{grid:c(t.layout),floating:u(t)},{grid:h,floating:p});return Hg(v.grid,v.floating)}const Lm=e=>Array.isArray(e)?e.join("/"):"",VB="nc-decks-cache-v1",jN=e=>`${VB}:${e}`;function GB(e){if(!e)return[];try{const t=localStorage.getItem(jN(e));if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)&&n.every(s=>s&&typeof s.id=="string"&&typeof s.name=="string")?n:[]}catch{return[]}}function YB(e,t){if(e)try{localStorage.setItem(jN(e),JSON.stringify(t))}catch{}}function XB(e){const t=new Set,n=[];for(const s of Array.isArray(e)?e:[])!s||!Xs.test(String(s.instanceId||""))||!Array.isArray(s.route)||!s.route.length||t.has(s.instanceId)||(t.add(s.instanceId),n.push({instanceId:s.instanceId,route:[...s.route],label:String(s.label||s.name||s.route.join(" › ")),status:s.status||"offline",stale:s.stale===!0,checking:s.checking===!0}));return n.sort((s,i)=>s.label.localeCompare(i.label))}function cc(e){return{instanceId:e.ownerId,route:e.ownerRoute||[],label:e.ownerLabel,status:e.available===!1?"offline":"up"}}function Do(e,t,n,s=!1,i=!0){const l=t.instanceId;return{...e,id:Yo(s?null:l,e.name),ownerId:l,ownerRoute:s?[]:[...t.route],ownerLabel:s?"Local":t.label,local:s,available:i,ownerTopology:Array.isArray(n)?n:[],layout:Zg(e.layout,l,n)}}function JB(e,t,n,s,i=[],l=[]){const[c,u]=y.useState([]),[h,p]=y.useState(!1),[v,_]=y.useState("idle"),[g,w]=y.useState(""),[S,N]=y.useState(!1),[C,j]=y.useState(""),E=y.useRef([]),R=y.useRef([]),x=y.useRef([]),W=y.useRef(new Map),$=y.useRef(""),Y=y.useRef(t),q=y.useRef(n),K=y.useRef(!1),se=y.useRef(!0),V=y.useRef(""),B=y.useMemo(()=>XB(i),[i]),D=B.map(J=>`${J.instanceId}:${Lm(J.route)}`).join("|"),O=B.map(J=>`${J.instanceId}:${J.status??""}:${J.checking?"checking":"settled"}`).join("|"),P=y.useRef(new Map(B.map(J=>[J.instanceId,J.checking?"pending":J.status])));R.current=B,x.current=l,q.current=n,Y.current=t,E.current=c;const z=y.useCallback(J=>Ya(J.layout,$.current,R.current),[]),A=y.useCallback(()=>rc(Y.current,$.current),[]),T=y.useCallback(J=>(Array.isArray(J)?J:[]).find(le=>le.id===A()),[A]),L=y.useCallback((J,le=!0,Q)=>{const ge=Q===void 0?A():rc(Q,$.current),Z=Jp(J,ac(),x.current),fe=E.current.some(ke=>ke.id===ge);E.current=Z,u(Z),YB($.current,Z.map(ke=>{if(!ke.refreshFailedAt)return ke;const Ve={...ke};return delete Ve.refreshFailedAt,Ve}));const ve=Z.find(ke=>ke.id===ge);if(le&&ve){se.current=!0;const ke=Hg(z(ve),Va(ve.floating,Ve=>Ya(Ve,$.current,R.current)));s(ke),ve.local&&f6(ve.name,Pi(ke))}else fe&&!ve&&(se.current=!0,s(po()),w("deck non più condiviso dal nodo owner"));c6(Z.filter(ke=>ke.local).map(ke=>ke.name))},[s,z]),H=y.useCallback(async J=>{let le=await ed(e);const Q=le.decks.find(ge=>ge.name==="main");if(le.decks.length===1&&Q&&Q.revision===0&&jm(Q.layout)){const ge=l6(),Z=Pi(ev("main")||po());if(!jm(Z)){const fe=Zg(Z,J,[]);le.decks[0]=await td(e,"main",fe,0,[])}for(const fe of ge.filter(ve=>ve!=="main"))try{let ve=await mw(e,fe,[]);const ke=Pi(ev(fe)||po());jm(ke)||(ve=await td(e,fe,Zg(ke,J,[]),ve.revision,[]))}catch{}le=await ed(e)}return le},[e]),M=y.useCallback((J,le)=>{const Q=new Map(le.map(fe=>[fe.id,fe])),ge=new Set,Z=[];for(const fe of E.current){if(fe.local||fe.ownerId!==J.instanceId){Z.push(fe);continue}const ve=Q.get(fe.id);ve&&(Z.push(ve),ge.add(fe.id))}for(const fe of le)ge.has(fe.id)||Z.push(fe);L(Z,!1)},[L]),U=y.useCallback(async J=>{try{const[le,Q]=await Promise.all([ed(e,J.route),hw(e,J.route).catch(()=>({nodes:[]}))]);M(J,le.decks.map(ge=>Do(ge,J,Q.nodes,!1,!0)))}catch(le){if(le&&(le.status===403||le.status===404)){M(J,[]);return}const Q=E.current.filter(ge=>!ge.local&&ge.ownerId===J.instanceId).map(ge=>({...ge,stale:!0,refreshFailedAt:Date.now(),ownerRoute:[...J.route],ownerLabel:J.label}));M(J,Q)}},[e,M]),ee=y.useCallback(async({migrate:J=!1}={})=>{const le=await Yc(e,[]),Q=Xs.test(String(le.instanceId||""))?le.instanceId:"";if(!Q)throw new Error("instanceId locale non disponibile");$.current=Q,j(Q);const[ge,Z]=await Promise.all([J?H(Q):ed(e),hw(e,[]).catch(()=>({nodes:[]}))]),fe={instanceId:Q,route:[],label:"Local"},ve=ge.decks.map(_e=>Do(_e,fe,Z.nodes,!0,!0)),ke=new Map(R.current.map(_e=>[_e.instanceId,_e])),Ve=E.current.length?E.current:GB(Q),ot=W.current,rt=Date.now(),$e=Ve.filter(_e=>!_e.local).flatMap(_e=>{const ze=ke.get(_e.ownerId);if(!ze){const nt=ot.get(_e.ownerId);return nt===void 0?(ot.set(_e.ownerId,rt),[{..._e,available:!1,stale:!0}]):rt-nt>Kv?[]:[{..._e,available:!1,stale:!0}]}ot.delete(_e.ownerId);const Je=ze.status==="up",He=ze.status==="pending"||ze.checking===!0;return[{..._e,available:He?_e.available:Je?_e.available!==!1:!1,stale:ze.stale===!0,ownerRoute:[...ze.route],ownerLabel:ze.label}]});return setTimeout(()=>{for(const _e of ke.values())_e.status==="up"&&!_e.checking&&U(_e)},0),[...ve,...$e]},[e,H,U,D]);y.useEffect(()=>{if(!e)return;let J=!1;const le=V.current!==e;return V.current=e,ee({migrate:le}).then(Q=>{if(J)return;const ge=T(E.current),Z=T(Q),fe=Z&&(!ge||Z.revision>ge.revision||ge.available!==Z.available||Lm(ge.ownerRoute)!==Lm(Z.ownerRoute));L(Q,le||!!fe&&!K.current),p(!0),Z&&w("")}).catch(Q=>{J||(p(!0),w(String(Q.message||Q)))}),()=>{J=!0}},[L,ee,D,e,T]),y.useEffect(()=>{if(!E.current.length)return;const J=Jp(E.current,ac(),l);(J.length!==E.current.length||J.some((Q,ge)=>Q.id!==E.current[ge].id))&&(E.current=J,u(J))},[l]),y.useEffect(()=>{const J=P.current,le=new Map;for(const Q of R.current){if(Q.checking||Q.status==="pending"){le.set(Q.instanceId,J.get(Q.instanceId)||"pending");continue}Q.status==="up"&&J.get(Q.instanceId)!=="up"&&U(Q),le.set(Q.instanceId,Q.status)}P.current=le},[O,U]);const re=y.useCallback(async(J,le=!0)=>{if(!h||!K.current)return!0;const Q=J===void 0?A():rc(J,$.current),ge=E.current.find(Z=>Z.id===Q);if(!ge)return w(`deck inesistente: ${Q}`),!1;if(ge.available===!1)return w(`nodo owner offline: ${ge.ownerLabel}`),!1;_("saving");try{const{grid:Z,floating:fe}=Jd(q.current),ve=oc(Pi(Z),ge.ownerId,ge.ownerTopology),ke=Va(fe,rt=>oc(rt,ge.ownerId,ge.ownerTopology)),Ve=await td(e,ge.name,ve,ge.revision,ge.ownerRoute,Wx(ke,ge)),ot=Do(Ve,cc(ge),ge.ownerTopology,ge.local,!0);return L(E.current.map(rt=>rt.id===Q?ot:rt),!1),K.current=!1,_("saved"),w(""),N(!1),setTimeout(()=>_("idle"),1500),!0}catch(Z){if(le&&Z.status===409&&Z.data&&Z.data.current){const fe=E.current.find(ve=>ve.id===Q);if(fe){const ve=Do(Z.data.current,cc(fe),fe.ownerTopology,fe.local,!0),ke=qx(fe,ve,q.current,Ve=>Ve,$.current,R.current);return zP(ke,q.current)||(q.current=ke,se.current=!0,s(ke)),L(E.current.map(Ve=>Ve.id===Q?ve:Ve),!1),K.current=!0,re(Q,!1)}}return _("error"),w(String(Z.message||Z)),Z.status===409&&N(!0),!1}},[h,e,L,s]),oe=y.useCallback(async()=>{try{const J=await ee();K.current=!1,N(!1),L(J,!0),w("")}catch(J){w(String(J.message||J))}},[ee,L]);y.useEffect(()=>{if(!h)return;const J=se.current&&!K.current;if(se.current=!1,J)return;K.current=!0,_("saving");const le=setTimeout(re,650);return()=>clearTimeout(le)},[n,h,re]),y.useEffect(()=>{if(!h)return;const J=()=>{if(!K.current)return;const le=E.current.find(ve=>ve.id===A());if(!le||le.available===!1)return;const{grid:Q,floating:ge}=Jd(q.current),Z=oc(Pi(Q),le.ownerId,le.ownerTopology),fe=Va(ge,ve=>oc(ve,le.ownerId,le.ownerTopology));Sj(e,le.name,Z,le.revision,le.ownerRoute,Wx(fe,le))};return window.addEventListener("pagehide",J),window.addEventListener("beforeunload",J),()=>{window.removeEventListener("pagehide",J),window.removeEventListener("beforeunload",J)}},[h,e,A]),y.useEffect(()=>{if(!h)return;const J=setInterval(async()=>{try{const le=await ee(),Q=T(E.current),ge=T(le),Z=!!(ge&&Q&&ge.revision>Q.revision),fe=!!(ge&&(!Q||Z||Q.available!==ge.available));if(Z&&K.current&&ge){const ve=qx(Q,ge,q.current,ke=>UP(z(ge),ke),$.current,R.current);L(le,!1),s(ve);return}L(le,fe&&!K.current)}catch{}},5e3);return()=>clearInterval(J)},[h,ee,L,z,s]);const je=y.useCallback(J=>{s(le=>{const Q=J(le);return Q!==le&&(se.current=!0),Q})},[]),te=async(J,le=null)=>{const Q=le===Zi?E.current.find(fe=>fe.local):le?E.current.find(fe=>fe.ownerId===le):null;if(!Q||Q.available===!1)throw new Error("nodo owner non disponibile");const ge=await mw(e,J,Q.ownerRoute),Z=Do(ge,cc(Q),Q.ownerTopology,Q.local,!0);return L([...E.current,Z],!1),Z},ie=async(J,le)=>{const Q=E.current.find(ke=>ke.id===J);if(!Q)throw new Error("deck inesistente");if(rc(J,$.current)===A()&&K.current&&!await re(J))throw new Error(`salvataggio di "${Q.name}" fallito: rinomina annullata`);const ge=E.current.find(ke=>ke.id===J);if(!ge)throw new Error("deck inesistente");const Z=await xj(e,ge.name,le,ge.revision,ge.ownerRoute),fe=Do(Z,cc(ge),ge.ownerTopology,ge.local,!0),ve=ge.local?Zi:ge.ownerId;return Xp(d6(ac(),ve,J,fe.id)),L(E.current.map(ke=>ke.id===J?fe:ke),!1),fe},pe=async J=>{const le=E.current.find(ge=>ge.id===J);if(!le)throw new Error("deck inesistente");rc(J,$.current)===A()&&(K.current=!1),await kj(e,le.name,le.revision,le.ownerRoute);const Q=le.local?Zi:le.ownerId;Xp(h6(ac(),Q,J)),L(E.current.filter(ge=>ge.id!==J),!1)},xe=(J,le)=>{const Q=E.current.find(Ve=>Ve.id===J),ge=E.current.find(Ve=>Ve.id===le);if(!Q||!ge)return!1;const Z=Q.local?Zi:Q.ownerId,fe=ge.local?Zi:ge.ownerId;if(Z!==fe)return!1;const ve=E.current.filter(Ve=>(Ve.local?Zi:Ve.ownerId)===Z).map(Ve=>Ve.id),ke=Xp(u6(ac(),Z,J,le,ve));return L(Jp(E.current,ke),!1),!0},Be=async(J,le)=>{const Q=E.current.find(Ve=>Ve.id===J);if(!Q)throw new Error("deck inesistente");if(Q.available===!1)throw new Error(`nodo owner offline: ${Q.ownerLabel}`);const ge=vE(le,$.current,R.current);if(!ge)throw new Error("riferimento sessione non valido");const Z=z(Q),fe=oc(TC(Z,ge),Q.ownerId,Q.ownerTopology),ve=await td(e,Q.name,fe,Q.revision,Q.ownerRoute),ke=Do(ve,cc(Q),Q.ownerTopology,Q.local,!0);return L(E.current.map(Ve=>Ve.id===J?ke:Ve),!1),ke},Te=y.useCallback(J=>Hg(z(J),Va(J.floating,le=>Ya(le,$.current,R.current))),[z]);return{decks:c,records:c,localNodeId:C,ready:h,saveState:v,error:g,setError:w,conflict:S,reloadCurrent:oe,saveNow:re,select:async J=>{if(K.current&&!await re(A()))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const le=E.current.find(Q=>Q.id===J);if(!le)throw new Error(`deck inesistente: ${J}`);return K.current=!1,se.current=!0,Te(le)},add:te,rename:ie,remove:pe,reorder:xe,addTileTo:Be,viewUpdate:je,vistaMaterializzata:Te,localMainId:Yo(null,"main"),parseDeckId:su}}const QB="/sw.js",fv="nc-sw-update";let Gc=null,ah=!1,lh=null,LN=Object.freeze({needed:!1,kind:null,version:"",browserVersion:""}),RN=!1;function P_(){typeof window<"u"&&window.dispatchEvent(new Event(fv))}function D_(){const e=lh||(ah?{kind:"reload",version:"",browserVersion:""}:null);LN=Object.freeze({needed:!!e,kind:(e==null?void 0:e.kind)||null,version:(e==null?void 0:e.version)||"",browserVersion:(e==null?void 0:e.browserVersion)||""})}function Kx(){return LN}function ZB(e){return typeof window>"u"?()=>{}:(window.addEventListener(fv,e),()=>window.removeEventListener(fv,e))}function O_(e){ah!==e&&(ah=e,D_(),P_())}const wd="nc-auto-reload",ch="nc-reload";function B_(){try{return typeof location<"u"?location:null}catch{return null}}function AN(){try{return typeof history<"u"?history:null}catch{return null}}function e$(e){const t=e===void 0?B_():e;if(!t||typeof t.search!="string")return null;try{return new URLSearchParams(t.search).get(ch)}catch{return null}}function t$(e,{location:t,history:n}={}){const s=t===void 0?B_():t,i=n===void 0?AN():n;if(!s||!i||typeof i.replaceState!="function")return!1;try{const l=new URLSearchParams(s.search||"");return l.set(ch,e),i.replaceState(i.state??null,"",`${s.pathname||"/"}?${l.toString()}${s.hash||""}`),!0}catch{return!1}}function n$({location:e,history:t}={}){const n=e===void 0?B_():e,s=t===void 0?AN():t;if(!n||!s||typeof s.replaceState!="function")return!1;try{const i=new URLSearchParams(n.search||"");if(!i.has(ch))return!1;i.delete(ch);const l=i.toString();return s.replaceState(s.state??null,"",`${n.pathname||"/"}${l?`?${l}`:""}${n.hash||""}`),!0}catch{return!1}}const MN="nc-update-dismissed";function TN(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function s$(e,t,n){return[e,t,n].map(s=>s||"").join("|")}let pv=null;function i$(e,t,n){const s=n;return e&&t&&e!==t&&e!==s?{kind:"install",version:e,browserVersion:s}:t&&s&&t!==s?{kind:"stale",version:t,browserVersion:s}:null}function r$(e,t){if(!e)return!1;try{return e.getItem(MN)===t}catch{return!1}}function o$(e={}){const t=e.storage===void 0?TN():e.storage;if(pv&&t)try{t.setItem(MN,pv)}catch{}ah=!1,lh=null,D_(),P_()}function a$(e,t,n,s={}){const i=s.storage===void 0?TN():s.storage,l=n,c=s$(e,t,l);pv=c;const u=i$(e,t,l);let h=r$(i,c)?null:u;if(h&&h.kind==="stale"){const v=`${t}|${l}`,_=e$(s.location)===v;let g=!1;if(!_&&i&&i.getItem(wd)!==v){try{i.setItem(wd,v)}catch{}g=i.getItem(wd)===v}g&&(t$(v,{location:s.location,history:s.history}),(s.applyImpl||IN)(),h=null)}const p=JSON.stringify(h)===JSON.stringify(lh);if(lh=h,D_(),p||P_(),!u){try{i&&i.removeItem(wd)}catch{}n$({location:s.location,history:s.history})}}const l$=1200;async function Vx(e){if(typeof fetch=="function")try{await Promise.race([fetch(e,{cache:"reload"}),new Promise(t=>setTimeout(t,l$))])}catch{}}async function IN(){try{Gc&&await Gc.update()}catch{}typeof location<"u"&&(await Vx(location.pathname),await Vx("/version.json"),location.reload())}function c$(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&O_(!0)})}function u$(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{RN&&location.reload()}),navigator.serviceWorker.register(QB).then(e=>{Gc=e,e.waiting&&O_(!0),e.addEventListener("updatefound",()=>{const t=e.installing;t&&c$(t)}),setInterval(()=>{e.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function d$(){RN=!0,O_(!1);const e=Gc&&Gc.waiting;e?(e.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function h$({hash:e="",origin:t="",pathname:n="",search:s=""}={}){const i=String(e||"").replace(/^#/,""),l=`${n||""}${s||""}`;if(!i)return{token:"",pair:"",device:"",nextUrl:l};const c=new URLSearchParams(i),u=c.get("token")||"",h=c.get("device")||"",p=/^[a-f0-9]{32}$/.test(h)?h:"",v=c.get("pair")||"",_=v?`${t||""}${n||""}#pair=${v}`:"";return{token:u,pair:_,device:p,nextUrl:l}}const PN="nc_side_w",Gx="nc_side_min",f$=240,Yx=new Set(["absent","present","active","unknown"]);function p$(){const e=Number(localStorage.getItem(PN));return e>=180&&e<=480?e:f$}function m$(){const e={token:"",pair:""};try{const{token:t,pair:n,device:s,nextUrl:i}=h$({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(t&&(e.token=t,a1(t,{remember:!0})),s&&KO(s),n){e.pair=n;try{sessionStorage.setItem("nc_pair",n)}catch{}}if(location.hash)try{history.replaceState(null,"",i)}catch{}}catch{}if(e.token||(e.token=w5()),!e.pair){const t=sessionStorage.getItem("nc_pair");t&&(e.pair=t)}return e}function Xx(e){try{return Pi(ev(e))}catch{return po()}}function Jx(e){if(!e)return"";const t=Math.floor(Date.now()/1e3)-e;return t<0||t<60?"ora":t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:`${Math.floor(t/86400)}g`}function g$({showComposer:e,showFiles:t,showPanel:n,hasPanel:s,rendererKind:i,filesSetting:l=null,handlers:c={}}={}){const u=[];return typeof c.onToggleComposer=="function"&&u.push({id:"keyboard",kind:"switch",on:!!e,labelKey:"bar-menu-keyboard",descKey:"bar-menu-keyboard-desc",run:c.onToggleComposer}),typeof c.onToggleFiles=="function"&&u.push(l===null?{id:"files",kind:"switch",on:!!t,labelKey:"bar-menu-files",descKey:"bar-menu-files-desc",run:c.onToggleFiles}:{id:"files",kind:"switch",on:!!l,labelKey:"bar-menu-files",descKey:"bar-menu-files-setting-desc",run:c.onToggleFiles}),s&&typeof c.onTogglePanel=="function"&&u.push({id:"panel",kind:"switch",on:!!n,labelKey:"bar-menu-panel",descKey:"bar-menu-panel-desc",run:c.onTogglePanel}),typeof c.onSwitchRenderer=="function"&&u.push({id:"renderer",kind:"switch",on:i==="webgl",labelKey:"bar-menu-renderer",descKey:"bar-menu-renderer-desc",run:c.onSwitchRenderer}),u}function v$(e,t){if(!e||!e.tmux)return"";const n=Zv(e,t||{});return n.stato==="lavora"?f("cell-working"):n.stato==="attesa"?f("cell-permission"):n.stato==="ferma"?f("cell-idle"):""}const Sd=e=>t=>{if(!e||!t[e])return t;const n={...t};return delete n[e],n};function Qx({session:e,node:t,ownerId:n,cellName:s,token:i,readonly:l=!1,panelPort:c=0,onBack:u,onCellSwitcher:h,cellSwitcherOpen:p=!1,chatPreview:v=null,liveHost:_=null,side:g=null,onSideClose:w=null,onSideGone:S=null}){var Ze;Fn();const[N]=o_(),C=zv(),[j,E]=y.useState(!1),[R,x]=y.useState(null),[W,$]=y.useState(()=>N.showComposer),[Y,q]=y.useState(dv),[K,se]=y.useState(()=>Pc()),V=()=>{eC(WT(Pc())),typeof window<"u"&&window.location.reload()},[B,D]=y.useState(s||e),[O,P]=y.useState(""),[z,A]=y.useState(""),[T,L]=y.useState(""),[H,M]=y.useState(!1),[U,ee]=y.useState(!1),re=!!g&&U,[oe,je]=y.useState(!1),[te,ie]=y.useState({v:{main:1,side:1},h:{main:1,side:1}}),[pe,xe]=y.useState(()=>window.matchMedia("(orientation: landscape)").matches);y.useEffect(()=>{const Ee=window.matchMedia("(orientation: landscape)"),ut=Pe=>xe(Pe.matches);return Ee.addEventListener("change",ut),()=>Ee.removeEventListener("change",ut)},[]);const Be=pe?te.h:te.v,Te=y.useRef(Be);Te.current=Be;const[Me,J]=y.useState(null),[le,Q]=y.useState(!0),ge=y.useRef(()=>{}),Z=y.useRef(()=>!1),fe=y.useRef(()=>{}),ve=y.useRef(!1),ke=y.useRef(!1),Ve=y.useRef(null),ot=y.useRef(null),[rt,$e]=y.useState(null),[_e,ze]=y.useState({}),Je=`${t||""}:${e}`,He=g?`${g.node||""}:${g.session}`:"",nt=y.useRef(Je);nt.current=Je;const lt=y.useRef(He);lt.current=He;const X=y.useRef(rt);X.current=rt;const I=y.useCallback(Ee=>{$e(ut=>ut&&ut.source==="main"?{source:"main",ev:Ee}:ut),ze(ut=>{var Pe;return((Pe=X.current)==null?void 0:Pe.source)==="main"?ut:{...ut,[nt.current]:!0}})},[]),ce=y.useCallback(Ee=>{$e(ut=>ut&&ut.source==="side"?{source:"side",ev:Ee}:ut),ze(ut=>{var Pe;return((Pe=X.current)==null?void 0:Pe.source)==="side"?ut:{...ut,[lt.current]:!0}})},[]),ye=!!g&&(rt==null?void 0:rt.source)==="side",Re=y.useCallback(()=>{const Ee=X.current;$e(null),Ee&&ze(Sd(Ee.source==="side"?lt.current:nt.current))},[]),ae=Ee=>{ee(Ee),nn((Ee?ve:Bt).current),Ft((Ee?ke:sn).current)},Oe=y.useRef(He);y.useEffect(()=>{const Ee=Oe.current;Oe.current=He,ee(!1),je(!1),ie({v:{main:1,side:1},h:{main:1,side:1}}),J(null),$e(ut=>ut&&ut.source==="side"?null:ut),Ee&&Ee!==He&&ze(Sd(Ee))},[He]);const gt=y.useMemo(()=>{const Ee=new Map;return ut=>{if(Ee.has(ut))return Ee.get(ut);let Pe=ut*.6;try{const We=document.createElement("span");We.style.cssText="position:absolute;visibility:hidden;white-space:pre;font-family:courier-new,courier,monospace;",We.style.fontSize=`${ut}px`,We.textContent="0".repeat(20),document.body.appendChild(We);const vt=We.getBoundingClientRect().width;document.body.removeChild(We),Number.isFinite(vt)&&vt>0&&(Pe=vt/20)}catch{}return Ee.set(ut,Pe),Pe}},[]),At=Math.max(.01,Be.main+Be.side),Lt=((Ze=ot.current)==null?void 0:Ze.clientWidth)||window.innerWidth,Rt=Math.max(0,Lt-12)*(Math.min(Be.main,Be.side)/At)-26,zt=!!g&&pe&&Rt/gt(Math.max(1,Y))<40,ft=Ee=>q(ut=>NN(ut+Ee));y.useEffect(()=>{p||q(dv())},[p]);const Yt=y.useRef(()=>{}),$t=y.useRef(()=>!1),Zt=y.useRef(()=>{}),Bt=y.useRef(!1),[Yn,nn]=y.useState(!1),rn=l_()&&!!v,sn=y.useRef(!1),[wn,Ft]=y.useState(!1),on=y.useRef(null),[un,Xt]=y.useState(!1),dn=()=>{const Ee=re?ve:Bt;Ee.current=!Ee.current,nn(Ee.current)},Js=()=>{const Ee=re?ke:sn;Ee.current=!Ee.current,Ft(Ee.current)};y.useEffect(()=>{D(s||e),M(!1)},[s,e]);const ds=y.useRef(Je);y.useEffect(()=>{const Ee=ds.current;ds.current=Je,Ee!==Je&&ze(Sd(Ee))},[Je]);const Vt=Ee=>{const ut=!Ee||Ee.sessionsError?null:Ee.sessionsJson;let Pe=null;ut&&Array.isArray(ut.sessions)&&(Pe=ut.sessions.find(Le=>Le.name===e));const We=!Ee||Ee.fleetError?null:Ee.fs;let vt=null;We&&We.available&&Array.isArray(We.cells)&&(vt=We.cells.find(Le=>Le.tmuxSession===e)),D(Uc({session:e,cell:vt||(s?{cell:s}:null)})),A(typeof(vt==null?void 0:vt.panelUrl)=="string"?vt.panelUrl.trim():""),L(typeof(vt==null?void 0:vt.cell)=="string"?vt.cell:"");let we="";vt?we=[`${vt.engine}${vt.key?`·${vt.key}`:""}`,v$(vt,Pe)].filter(Boolean).join(" · "):Pe&&(we=Pe.attached?`attached · ${Jx(Pe.activity)}`:Pe.activity?Jx(Pe.activity):""),P(we),Q(!!(Pe||vt))},Ms=y.useRef(Vt);Ms.current=Vt,y.useEffect(()=>{const Ee=t?t.split("/"):[],ut=Pe=>Ms.current(Pe);return ut(dc(Ee)),Lc(i,Ee,ut)},[t,i]),y.useEffect(()=>{Ms.current(dc(t?t.split("/"):[]))},[e,s]);const Xn=y.useRef(S);Xn.current=S;const Ts=Ee=>{var Ke;if(!g)return;const ut=!Ee||Ee.sessionsError?null:Ee.sessionsJson;let Pe=null,We=!1;ut&&Array.isArray(ut.sessions)&&(We=!0,Pe=ut.sessions.find(at=>at.name===g.session));const vt=!Ee||Ee.fleetError?null:Ee.fs;let we=null,Le=!1;vt&&vt.available&&Array.isArray(vt.cells)&&(Le=!0,we=vt.cells.find(at=>at.tmuxSession===g.session)),J({title:Uc({session:g.session,cell:we}),present:!!(Pe||we)}),(We||Le)&&!Pe&&!we&&((Ke=Xn.current)==null||Ke.call(Xn))},kt=y.useRef(Ts);kt.current=Ts,y.useEffect(()=>{if(!g){J(null);return}const Ee=g.node?g.node.split("/"):[],ut=Pe=>kt.current(Pe);return ut(dc(Ee)),Lc(i,Ee,ut)},[g,g==null?void 0:g.node,i]),y.useEffect(()=>{g&&kt.current(dc(g.node?g.node.split("/"):[]))},[g==null?void 0:g.session]);const ue=re?"side":"main",De=re?He:Je,Xe=()=>{ze(Sd(De)),$e(Ee=>Ee&&Ee.source===ue?null:{source:ue,ev:null})},[ct,It]=y.useState(sN),[G]=y.useState(rN),[he]=y.useState(oN),Ie=g$({showComposer:W,showFiles:(rt==null?void 0:rt.source)===ue,showPanel:H,hasPanel:!!z,rendererKind:K,filesSetting:C?null:ct,handlers:{onToggleComposer:()=>$(Ee=>!Ee),onToggleFiles:C?Xe:()=>It(Ee=>(iN(!Ee),!Ee)),onTogglePanel:()=>M(Ee=>!Ee),onSwitchRenderer:V}}),Qe=Ee=>{Ee.preventDefault();const ut=ot.current;if(!ut)return;const Pe=(wt,Nn)=>ie(hs=>({...hs,[pe?"h":"v"]:{main:wt,side:Nn}}));if(pe){const wt=Ee.clientX,Nn=Te.current,hs=ut.clientWidth||1,Gt=oe?-1:1,Hn=ws=>{const $i=Nn.main+Nn.side,xi=(ws.clientX-wt)/hs*$i*Gt,Jt=bd(Nn.main+xi);Pe(Jt,bd($i-Jt))},Pt=()=>{window.removeEventListener("pointermove",Hn),window.removeEventListener("pointerup",Pt),window.removeEventListener("pointercancel",Pt),window.removeEventListener("blur",Pt)};window.addEventListener("pointermove",Hn),window.addEventListener("pointerup",Pt),window.addEventListener("pointercancel",Pt),window.addEventListener("blur",Pt);return}const We=Ee.clientY,vt=Te.current,we=ut.clientHeight||1,Le=oe?-1:1,Ke=wt=>{const Nn=vt.main+vt.side,hs=(wt.clientY-We)/we*Nn*Le,Gt=bd(vt.main+hs);Pe(Gt,bd(Nn-Gt))},at=()=>{window.removeEventListener("pointermove",Ke),window.removeEventListener("pointerup",at),window.removeEventListener("pointercancel",at),window.removeEventListener("blur",at)};window.addEventListener("pointermove",Ke),window.addEventListener("pointerup",at),window.addEventListener("pointercancel",at),window.addEventListener("blur",at)},Ae=g&&o.jsxs("div",{className:`nc-dual-pane${re?"":" foco"}${zt&&re?" nascosto":""}`,"data-testid":"pane-main",style:{flexGrow:Be.main,flexBasis:pe?0:void 0},onPointerDown:()=>ae(!1),children:[o.jsxs("div",{className:"nc-dual-strip",children:[o.jsx("span",{className:`nc-dual-dot${le?" on":""}`,"aria-hidden":"true"}),o.jsx("b",{children:B}),!re&&o.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:f("dual-focus"),children:"✎"}),zt&&o.jsxs("button",{type:"button",className:"nc-dual-alt",title:f("dual-go-to").replace("{cell}",(Me==null?void 0:Me.title)||g.session),"aria-label":f("dual-go-to").replace("{cell}",(Me==null?void 0:Me.title)||g.session),onPointerDown:Ee=>Ee.stopPropagation(),onClick:Ee=>{Ee.stopPropagation(),ae(!re)},children:[o.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",focusable:"false",children:[o.jsx("rect",{x:"3.5",y:"6",width:"17",height:"12",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),o.jsx("rect",{x:"3.5",y:"6",width:"8.5",height:"12",fill:"currentColor"})]}),o.jsx("span",{className:`nc-dual-dot${Me!=null&&Me.present?" on":""}`,"aria-hidden":"true"})]})]}),o.jsx("div",{className:"nc-dual-body",children:o.jsx(kc,{session:e,node:t,token:i,readonly:l,takeSize:!0,focused:!re,sendRef:Yt,composerRef:$t,actionRef:Zt,ctrlRef:Bt,setCtrlArmed:nn,altRef:sn,setAltArmed:Ft,keyboardRef:on,onFiles:I,fontSize:Y,selectionMode:un,onSelectionModeChange:Xt,keyboardGesture:N.terminalKeyboardGesture,onRendererChange:se})})]},"pane-main"),Et=g&&o.jsxs("div",{className:`nc-dual-pane${re?" foco":""}${zt&&!re?" nascosto":""}`,"data-testid":"pane-side",style:{flexGrow:Be.side,flexBasis:pe?0:void 0},onPointerDown:()=>ae(!0),children:[o.jsxs("div",{className:"nc-dual-strip",children:[o.jsx("span",{className:`nc-dual-dot${Me!=null&&Me.present?" on":""}`,"aria-hidden":"true"}),o.jsx("b",{children:Me?Me.title:g.session}),re&&o.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:f("dual-focus"),children:"✎"}),o.jsxs("span",{className:"nc-dual-tasti",children:[o.jsx("button",{type:"button",title:f("dual-swap"),"aria-label":f("dual-swap"),onPointerDown:Ee=>Ee.stopPropagation(),onClick:Ee=>{Ee.stopPropagation(),je(ut=>!ut)},children:pe?"⇆":"⇅"}),o.jsx("button",{type:"button",title:f("dual-close"),"aria-label":f("dual-close"),onPointerDown:Ee=>Ee.stopPropagation(),onClick:Ee=>{Ee.stopPropagation(),w==null||w()},children:"✕"})]}),zt&&o.jsxs("button",{type:"button",className:"nc-dual-alt",title:f("dual-go-to").replace("{cell}",B),"aria-label":f("dual-go-to").replace("{cell}",B),onPointerDown:Ee=>Ee.stopPropagation(),onClick:Ee=>{Ee.stopPropagation(),ae(!re)},children:[o.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",focusable:"false",children:[o.jsx("rect",{x:"3.5",y:"6",width:"17",height:"12",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),o.jsx("rect",{x:"12",y:"6",width:"8.5",height:"12",fill:"currentColor"})]}),o.jsx("span",{className:`nc-dual-dot${le?" on":""}`,"aria-hidden":"true"})]})]}),o.jsx("div",{className:"nc-dual-body",children:o.jsx(kc,{session:g.session,node:g.node,token:i,readonly:l,takeSize:!1,focused:re,sendRef:ge,composerRef:Z,actionRef:fe,ctrlRef:ve,setCtrlArmed:nn,altRef:ke,setAltArmed:Ft,keyboardRef:Ve,onFiles:ce,fontSize:Y,selectionMode:un,onSelectionModeChange:Xt,keyboardGesture:N.terminalKeyboardGesture})})]},"pane-side"),Ct=o.jsx("div",{className:"nc-dual-handle","data-testid":"dual-handle",role:"separator","aria-orientation":pe?"vertical":"horizontal",onPointerDown:Qe},"dual-handle");return o.jsxs("div",{className:"nc-app",children:[o.jsxs("header",{className:"nc-bar nc-bar-single",children:[o.jsxs("button",{onClick:u,title:f("sessions"),children:[o.jsx(yt,{name:"chevronLeft",size:18}),o.jsx("span",{className:"nc-bar-label",children:f("sessions")})]}),o.jsxs("span",{className:"nc-bar-center",children:[o.jsx("b",{title:t?`${B} · ${t}`:B,children:B}),_&&_.cell&&_.cell===s?o.jsx("span",{className:`nc-live-host-dot ${kv(_)} nc-live-host-dot-header`,"data-testid":"live-host-header-dot",title:f("live-host-indicator").replace("{cell}",_.cell).replace("{mode}",f(_.mode?`live-host-mode-${_.mode}`:"live-host-mode-unknown")).replace("{state}",f(`live-host-state-${_.state}`))}):null,O&&o.jsx("small",{className:"nc-bar-sub",children:O})]}),o.jsxs("span",{className:"nc-bar-right",children:[o.jsx("button",{onClick:()=>ft(-1),title:f("zoom-out"),"aria-label":f("zoom-out"),children:o.jsx(yt,{name:"zoomOut",size:18})}),o.jsx("button",{onClick:()=>ft(1),title:f("zoom-in"),"aria-label":f("zoom-in"),children:o.jsx(yt,{name:"zoomIn",size:18})}),ct&&o.jsxs("button",{type:"button",className:"nc-bar-files",onClick:Xe,title:f("bar-menu-files"),"aria-label":f("bar-menu-files"),"aria-pressed":(rt==null?void 0:rt.source)===ue?"true":"false",children:[o.jsx(yt,{name:"folder",size:18}),_e[De]&&(rt==null?void 0:rt.source)!==ue&&o.jsx("span",{className:"nc-bar-dot-nuovi","data-testid":"bar-files-dot",title:f("new-files-outbox"),"aria-label":f("new-files-outbox")})]}),G&&o.jsx("button",{type:"button",onClick:()=>$(Ee=>!Ee),title:f("bar-menu-keyboard"),"aria-label":f("bar-menu-keyboard"),"aria-pressed":W?"true":"false",children:o.jsx(yt,{name:"keyboard",size:18})}),z&&he&&o.jsx("button",{type:"button",onClick:()=>M(Ee=>!Ee),title:f("bar-menu-panel"),"aria-label":f("bar-menu-panel"),"aria-pressed":H?"true":"false",children:o.jsx(yt,{name:"monitor",size:18})}),o.jsx("button",{type:"button",className:`nc-bar-menu${j?" on":""}`,title:f("bar-menu-open"),"aria-label":f("bar-menu-open"),"aria-haspopup":"menu","aria-expanded":j?"true":"false",onClick:Ee=>{j||x(Ee.currentTarget.getBoundingClientRect()),E(ut=>!ut)},children:"⋯"})]})]}),o.jsxs("div",{className:"nc-termwrap",children:[g?o.jsx("div",{className:`nc-dual${pe?" row":""}`,ref:ot,children:zt?oe?[Et,Ae]:[Ae,Et]:oe?[Et,Ct,Ae]:[Ae,Ct,Et]}):rn?o.jsx(a_,{target:v.target||go.vl.target,events:v.events||go.vl.events,viewer:v.viewer||go.vl.viewer,reviews:v.reviews||{},label:v.label||B,capabilities:v.capabilities||{permissionPolicy:"yolo"}}):o.jsx(kc,{session:e,node:t,token:i,readonly:l,takeSize:!0,sendRef:Yt,composerRef:$t,actionRef:Zt,ctrlRef:Bt,setCtrlArmed:nn,altRef:sn,setAltArmed:Ft,keyboardRef:on,onFiles:I,fontSize:Y,selectionMode:un,onSelectionModeChange:Xt,keyboardGesture:N.terminalKeyboardGesture,onRendererChange:se}),H&&z&&T&&o.jsx(Fv,{cellId:T,panelUrl:z,route:t?t.split("/"):[],panelPort:c,token:i,title:B})]}),!rn&&o.jsx(pD,{onKeyboard:()=>$(Ee=>!Ee),onCellSwitcher:h,cellSwitcherOpen:p,send:Ee=>(re?ge:Yt).current(Ee),action:Ee=>(re?fe:Zt).current(Ee),ctrlArmed:Yn,onCtrl:dn,altArmed:wn,onAlt:Js,onAltConsume:()=>{const Ee=re?ke:sn;Ee.current=!1,Ft(!1)},onKeyboardKeep:()=>{var Ee,ut;return(ut=(Ee=re?Ve:on).current)==null?void 0:ut.call(Ee)},selectionMode:un,onSelectionMode:Xt,keepKeyboardClosed:N.keybarKeepsKeyboardClosed,showEnter:N.showKeybarEnter,keybarLayout:N.keybarLayout}),!rn&&W&&o.jsx(oE,{submitText:Ee=>(re?Z:$t).current(Ee),token:i,session:re?g.session:e,node:re?g.node:t,ownerId:re?g.ownerId:n,readonly:l,keepKeyboardClosedOnVoice:N.voiceKeepsKeyboardClosed}),rt&&(ye?o.jsx(Kg,{session:g.session,node:g.node,token:i,filesEvent:rt.ev,onClose:Re}):rt.source==="main"?o.jsx(Kg,{session:e,node:t,token:i,filesEvent:rt.ev,onClose:Re}):null),j&&(C?o.jsx(kC,{anchorRect:R,items:Ie,onClose:()=>E(!1)}):o.jsx(Qv,{cellName:B,items:Ie,onClose:()=>E(!1)}))]})}function _$(){Fn();const[e]=y.useState(m$),[t,n]=y.useState(e.token),[s,i]=y.useState(!1);nB(s?"":t);const l=y.useRef(e.token);l.current=t,y.useEffect(()=>{const we=Le=>{Le&&Le.detail&&Le.detail.token===l.current&&i(!0)};return window.addEventListener(Am,we),()=>window.removeEventListener(Am,we)},[]);const c=y.useCallback((we,Le)=>{const Ke=a1(we,{remember:Le});if(!Ke.ok||Le&&Ke.where!=="local")try{window.dispatchEvent(new CustomEvent(Mm))}catch{}i(!1),n(we)},[]),[u,h]=y.useState(e.pair||""),p=y.useCallback(()=>{h("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),v=zv(),[_]=y.useState(()=>a6(typeof location<"u"?location.pathname:"/")),[g,w]=y.useState(_.id),S=g===Yo(null,oi),[N,C]=y.useState(null),j=we=>{const Le=Ar(we);C(Le?{...Le,...typeof(we==null?void 0:we.cellName)=="string"&&we.cellName?{cellName:we.cellName}:{}}:null)},[E,R]=y.useState(null);y.useEffect(()=>{const we=FB();R(we&&N&&hv(we.main,N)?we.side:null)},[N]);const x=we=>{const Le=N?{session:N.session,node:N.node}:null,Ke=zB(Le,E,we);R(Ke),Ke?HB(Le,Ke):Ux()},W=()=>{R(null),Ux()},[$,Y]=y.useState([]),[q,K]=y.useState(!0),[se,V]=y.useState(null),[B,D]=y.useState([]),[O,P]=y.useState([]),[z,A]=y.useState(!1),[T,L]=y.useState(null),[H,M]=y.useState(()=>_.ownerId?po():Xx(_.name)),[U,ee]=y.useState(null),[re,oe]=y.useState(null),je=we=>oe(Ar(we)),[te,ie]=y.useState(null),pe=Vv(t,v),xe=y.useMemo(()=>(pe||[]).filter(we=>we.instanceId).map(we=>({instanceId:we.instanceId,route:we.route,label:we.label,status:we.status,stale:we.stale===!0,checking:we.checking===!0})),[pe]),{order:Be}=Eh(),Te=JB(t,g,H,M,xe,Be),{notice:Me,showActionNotice:J}=HC(),le=Te.decks;y.useEffect(()=>{const we=new Map;for(const Le of pe||[]){const Ke=(Le.route||[Le.name]).join("/"),at=new Set((Le.sessions||[]).map(wt=>wt.name));for(const wt of Le.cells||[])!wt.cell||!wt.tmuxSession||wt.cell===wt.tmuxSession||at.has(wt.cell)||we.set(`${Ke}:${wt.cell}`,`${Ke}:${wt.tmuxSession}`)}M(Le=>MP(Le,we))},[pe]),y.useEffect(()=>{Te.localNodeId&&_.ownerId&&_.ownerId===Te.localNodeId&&M(we=>we.columns.some(Le=>Le.tiles.length)?we:Xx(_.name))},[Te.localNodeId]),y.useEffect(()=>{Te.localNodeId&&(n6(xe),Te.viewUpdate(we=>{const Le=Ya(we,Te.localNodeId,xe);return JSON.stringify(Le)===JSON.stringify(we)?we:Le}))},[xe,Te.localNodeId,Te.viewUpdate]);const[Q,ge]=y.useState(null),[Z,fe]=y.useState(null),ve=y.useRef(0),[ke,Ve]=y.useState(!1),[ot,rt]=y.useState(p$),[$e,_e]=y.useState(!S),[ze,Je]=y.useState(()=>S?localStorage.getItem(Gx)==="1":!0),[He,nt]=y.useState(!1),[lt,X]=y.useState("nodes"),[I,ce]=y.useState(!1),[ye,Re]=y.useState(""),[ae,Oe]=y.useState(!1),gt=(we="nodes",Le=!1,Ke="")=>{X(we),ce(Le),Re(Ke),nt(!0)},[At,Lt]=y.useState(!1),[Rt,zt]=y.useState(null),[ft,Yt]=y.useState({deviceDefault:"",localNodeId:"",localNameDefault:"",deviceNameNeeded:!1,deviceNameSuggestion:""}),[$t,Zt]=y.useState(""),[Bt,Yn]=y.useState(!1),[nn,rn]=y.useState(0),[sn,wn]=y.useState({});y.useEffect(()=>{try{localStorage.setItem(PN,String(ot))}catch{}},[ot]),y.useEffect(()=>{try{localStorage.setItem(Gx,ze?"1":"")}catch{}},[ze]),y.useEffect(()=>{if(!t)return;let we=!1;return Promise.all([m1(t),Vn("/api/config",t).then(Le=>Le.json())]).then(([Le,Ke])=>{if(!we){if(Yt({deviceDefault:Le.deviceName||"",localNodeId:Le.nodeId||"",localNameDefault:Le.localName||"",deviceNameNeeded:Le.deviceNameNeeded===!0,deviceNameSuggestion:Le.deviceNameSuggestion||""}),Zt(Le.deviceName||""),Yn(!!Ke.readonlyDefault),GT(Ke.terminal),rn(Number.isInteger(Ke.panelPort)?Ke.panelPort:0),wn(Ke.nodePanelPorts&&typeof Ke.nodePanelPorts=="object"&&!Array.isArray(Ke.nodePanelPorts)?Ke.nodePanelPorts:{}),BI(Ke.hostOnlyNodes),Le.firstRun===!0&&!Ke.readonlyDefault)Lt(!0);else if(u)Lt(!0);else if(Le.deviceNameNeeded===!0&&!Ke.readonlyDefault){let at=!1;try{at=sessionStorage.getItem("nc_device_ask_later")==="1"}catch{}at||zt({suggestion:Le.deviceNameSuggestion||""})}}}).catch(()=>{}),()=>{we=!0}},[t,u]);const[Ft,on]=y.useState({}),un=y.useCallback(({route:we,hostCell:Le,revision:Ke})=>{const at=Rs(we);on(wt=>({...wt,[at]:{hostCell:Le||null,hostLease:null,hostRevision:Number.isInteger(Ke)?Ke:(wt[at]||{}).hostRevision||0,threadStatus:"absent"}}))},[]),Xt=we=>{const Le=Rs(we),Ke=we.length?((pe||[]).find(at=>Rs(Array.isArray(at.route)?at.route:[])===Le)||{}).cells||[]:B;return Ja({liveHost:Ft[Le]||null,cells:Ke,localNodeId:Te.localNodeId,ownerId:we.length?Le:Te.localNodeId})},dn=y.useRef(pe);y.useEffect(()=>{dn.current=pe},[pe]);const Js=y.useRef(null);Js.current||(Js.current=mh());const ds=3500;y.useEffect(()=>{let we=!1;const Le=async()=>{const at=Js.current,wt=at.begin();if(wt!==null)try{const Nn=[[],...(dn.current||[]).filter(Gt=>Gt.kind!=="vl"&&Gt.status==="up").map(Gt=>Array.isArray(Gt.route)&&Gt.route.length?Gt.route:[Gt.name])],hs=await Promise.all(Nn.map(async Gt=>{const Hn=Rs(Gt);try{const Pt=await hh(t,Gt,{timeoutMs:ds});return[Hn,{hostCell:Pt&&typeof Pt.hostCell=="string"?Pt.hostCell:null,hostLease:Pt&&Pt.host&&typeof Pt.host.lease=="string"?Pt.host.lease:null,hostRevision:Number.isInteger(Pt&&Pt.revision)?Pt.revision:0,threadStatus:Pt&&Yx.has(Pt.threadStatus)?Pt.threadStatus:"unknown"}]}catch{return[Hn,{error:!0}]}}));if(we||!at.isCurrent(wt))return;on(Gt=>{let Hn=!1;const Pt={...Gt};for(const ws of hs){if(!ws)continue;const[$i,xi]=ws;Pt[$i]=xi.error?{...Gt[$i]||{},threadStatus:"unknown"}:xi,Hn=!0}return Hn?Pt:Gt})}finally{at.end(wt)}};Le();const Ke=setInterval(Le,4e3);return()=>{we=!0,clearInterval(Ke),Js.current.reset()}},[t]),y.useEffect(()=>{if(!v)return;const we=Le=>{if(!Le)return;const Ke=Le.sessionsError?null:Le.sessionsJson;Ke&&!Ke.error?(Y(Ke.sessions||[]),K(!0),V(Le.at)):K(!1);const at=kh({fs:Le.fs,error:Le.fleetError});at.kind==="data"?(Za("local",at.cells),D(at.cells),P(at.capabilities),A(!1),L(null)):at.kind==="stale"?(D(wt=>wt.length?wt:qv("local")),A(!0),L(null)):(D([]),Za("local",[]),P([]),A(!1),L(at.reason||""))};return we(dc([])),Lc(t,[],we)},[v,t]);const Vt=y.useCallback(async(we,Le=[])=>{const Ke=Rs(Le),at=Ft[Ke]&&Ft[Ke].hostRevision||0;try{const wt=await fh(t,we,at,Le);return on(Nn=>({...Nn,[Ke]:{hostCell:wt.hostCell||null,hostLease:wt.host&&typeof wt.host.lease=="string"?wt.host.lease:null,hostRevision:Number.isInteger(wt.revision)?wt.revision:at,threadStatus:Yx.has(wt.threadStatus)?wt.threadStatus:"unknown"}})),{ok:!0}}catch(wt){return{ok:!1,error:wt}}},[t,Ft]),Ms=y.useCallback(async(we,Le=[])=>{const Ke=await Vt(we,Le);return Ke.ok||window.alert(f(Pm(Ke.error))),Ke.ok},[Vt]),Xn=y.useCallback(async(we=[])=>{const Le=Rs(we),Ke=Ft[Le]&&Ft[Le].hostRevision||0;try{const at=await ph(t,Ke,we);return on(wt=>({...wt,[Le]:{hostCell:at.hostCell||null,hostLease:null,hostRevision:Number.isInteger(at.revision)?at.revision:Ke,threadStatus:"unknown"}})),{ok:!0}}catch(at){return{ok:!1,error:at}}},[t,Ft]),Ts=y.useCallback(async(we=[])=>{const Le=await Xn(we);return Le.ok||window.alert(f(Pm(Le.error))),Le.ok},[Xn]);y.useEffect(()=>{let we=!1;const Le=()=>{Vn("/api/config",t).then(at=>at.json()).then(at=>{we||a$(at.version,at.uiVersion,"0.9.78")}).catch(()=>{})};Le();const Ke=setInterval(Le,6e4);return()=>{we=!0,clearInterval(Ke)}},[t]);const kt=new Set([...$.map(we=>we.name),...pe.flatMap(we=>we.sessions.map(Le=>Le.key))]),ue=y.useMemo(()=>{const we=new Map;for(const Le of $)Le&&typeof Le.name=="string"&&Number.isFinite(Le.created)&&we.set(Le.name,Le.created);return we},[$]),De=bs(H),Xe=we=>M(Le=>{const Ke=vE(we,Te.localNodeId,xe)||we,at=TC(Le,Ke);return at===Le&&bs(Le).length>=9&&Te.setError(f("grid-full")),at}),ct=async(we,Le=[])=>{try{await _v(t,we,Le)}catch{return}const Ke=Le.length?`${Le.join("/")}:${we}`:we;M(at=>Fc(at,Ke)),hc(Le,t)},It=async(we,Le,Ke=[])=>{try{await p1(t,we,Le,Ke)}catch{return}hc(Ke,t)},G=async(we,Le,Ke=[])=>{await d1(t,{cell:we,enabled:!!Le},Ke),hc(Ke,t)},he=async we=>{if(!Q)return;const{cell:Le}=Q,Ke=Array.isArray(Q.route)?Q.route:[];if(!await n_({token:t,powerCell:Q,payload:we,onNotice:J})){const wt=we.action==="up"?!!we.boot:we.boot?!1:!!Q.boot;fe({id:++ve.current,cell:Le,route:Ke,enabled:wt})}hc(Ke,t)},Ie=y.useCallback(we=>{fe(Le=>(Le==null?void 0:Le.id)===we?null:Le)},[]),Qe=async we=>{if(!(!(we!=null&&we.direct)||ke)){Ve(!0);try{await wv(t,we.name,we.tunnelStatus==="up"?"down":"up")}finally{Ve(!1)}}},Ae=async(we,Le)=>{const Ke=String(Le||"").trim();return!(we!=null&&we.direct)||!tl(Ke)?!1:(await y1(t,we.name,Ke),!0)},Et=we=>{const Le=le.find(Ke=>Ke.id===we);if(!Le)return!1;try{const Ke=window.open(Yp(Le,t),"_blank");return Ke&&(Ke.opener=null),!!Ke}catch{return!1}},Ct=async we=>{if(!we||we===g)return;const Le=await Te.select(we),Ke=Te.records.find(at=>at.id===we);w(we),M(Le),ee(null),oe(null);try{history.replaceState(null,"",Yp(Ke||we,null))}catch{}},Ze=async(we,Le)=>{const Ke=await Te.add(we,Le);await Ct(Ke.id)},Ee=async(we,Le)=>{const Ke=await Te.rename(we,Le);if(we===g){w(Ke.id),M(Te.vistaMaterializzata(Ke)),ee(null),oe(null);try{history.replaceState(null,"",Yp(Ke,null))}catch{}}},ut=async we=>{await Te.remove(we),we===g&&await Ct(Te.localMainId)},Pe=async(we,Le)=>{!Le||Le===g||(await Te.addTileTo(Le,we),M(Ke=>Fc(Ke,we)))};if(!t||s)return o.jsx(qB,{onSubmit:c,reason:s?"invalid":""});const We=o.jsxs(o.Fragment,{children:[He&&o.jsx(mB,{token:t,initialTab:lt,initialLocation:ye,startNewCell:I,onClose:()=>{nt(!1),ce(!1),Re("")}}),At&&o.jsx(gB,{token:t,initialPair:u,...ft,onPairDone:p,onDone:()=>Lt(!1)}),Rt&&o.jsx(vB,{token:t,suggestion:Rt.suggestion,onSaved:we=>{Zt(we),Yt(Le=>({...Le,deviceDefault:we,deviceNameNeeded:!1})),zt(null)},onLater:()=>{try{sessionStorage.setItem("nc_device_ask_later","1")}catch{}zt(null)}}),o.jsx(AB,{token:t})]});if(!v)return te?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"nc-single-overlay",children:o.jsx(Hx,{peer:te,token:t,onBack:()=>ie(null)})}),We]}):N?o.jsxs(o.Fragment,{children:[o.jsx(Qx,{session:N.session,node:N.node,ownerId:N.ownerId,cellName:N.cellName,token:t,readonly:Bt,liveHost:Xt(N.node?N.node.split("/"):[]),panelPort:Oc(N.node?N.node.split("/"):[],sn,nn),side:E,onSideClose:W,onSideGone:W,onBack:()=>C(null),onCellSwitcher:()=>Oe(!0),cellSwitcherOpen:ae}),ae&&o.jsx(DB,{token:t,current:N,localNodeLabel:$t,panelPort:nn,nodePanelPorts:sn,hostByRoute:Ft,onDesignateCell:Vt,onClearHostCell:Xn,onLiveHostApplied:un,sideKey:E?$c(E.node?E.node.split("/"):[],E.session):null,onToggleSide:x,onPick:we=>{j(we),Oe(!1)},onClose:()=>Oe(!1)}),We]}):o.jsxs(o.Fragment,{children:[o.jsx(lD,{onPick:j,token:t,onSettings:gt,onOpenVlSession:ie,panelPort:nn,nodePanelPorts:sn,hostByRoute:Ft,onDesignateCell:Ms,onClearHostCell:Ts}),We]});const vt=S||!$e;return o.jsxs("div",{className:"nc-workspace",children:[vt&&o.jsx(QD,{sessions:$,cells:B,localVerified:q,activeSessions:De,nodeGroups:pe,token:t,onPeekOpen:()=>Oe(!1),overlayOpen:ae,fleetCapabilities:O,fleetStale:z,fleetOff:T,bootSettlement:Z,onBootSettlementApplied:Ie,localNodeId:Te.localNodeId,hostByRoute:Ft,onDesignateCell:Ms,onClearHostCell:Ts,onPick:je,onAddTile:Xe,onPower:ge,onBoot:G,onBootError:we=>Te.setError(String((we==null?void 0:we.message)||we)),onNodePower:Qe,onNodeRename:Ae,onKill:ct,onVisibility:It,onNew:()=>gt("fleet",!0),onSettings:gt,onOpenVlSession:ie,width:ot,collapsed:ze,onResize:rt,onToggleCollapse:()=>Je(we=>!we)}),o.jsxs("div",{className:"nc-workspace-main",children:[o.jsx(R6,{decks:le,currentDeck:g,onCreate:Ze,onRename:Ee,onDelete:ut,onReorder:Te.reorder,onOpenWindow:Et,onNavigate:Ct,saveState:Te.saveState,error:Te.error,conflict:Te.conflict,onReloadDeck:Te.reloadCurrent,sidebarVisible:vt,onToggleSidebar:S?null:()=>_e(we=>!we)}),Me&&o.jsx("div",{className:"nc-notice nc-deck-notice",role:"status",title:Me,children:Me}),o.jsx(t6,{layout:H,onLayoutChange:M,onResizeEnd:()=>{Te.saveNow()},token:t,readonly:Bt,sessionsAlive:kt,localVerified:q,localIdentities:ue,localVerifiedAt:se,focusSession:U,onFocus:ee,onOpenSingle:je,decks:le,currentDeck:g,onSendToDeck:Pe,cells:B,nodeGroups:pe,panelPort:nn,nodePanelPorts:sn})]}),te&&o.jsx("div",{className:"nc-single-overlay",children:o.jsx(Hx,{peer:te,token:t,onBack:()=>ie(null)})}),re&&o.jsx("div",{className:"nc-single-overlay",children:o.jsx(Qx,{session:re.session,node:re.node,ownerId:re.ownerId,cellName:Uc({session:re.session,node:re.node,ownerId:re.ownerId,cells:B,nodeGroups:pe}),token:t,readonly:Bt,liveHost:Xt(re.node?re.node.split("/"):[]),panelPort:Oc(re.node?re.node.split("/"):[],sn,nn),onBack:()=>oe(null)})}),Q&&o.jsx(Gd,{cell:Q,token:t,route:Array.isArray(Q.route)?Q.route:[],onConfirm:he,onClose:()=>ge(null)}),We]})}function y$(e){return e.kind==="install"?f("update-installed-restart").replace("{v}",e.version):e.kind==="stale"?f("update-stale").replace("{ui}",e.version).replace("{browser}",e.browserVersion):f("update-available").replace("{v}",e.version).replace(" "," ").trim()}function b$(){Fn();const e=y.useSyncExternalStore(ZB,Kx,Kx);return e.needed?o.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[o.jsx("span",{className:"nc-update-msg",children:y$(e)}),e.kind==="stale"&&o.jsx("button",{className:"nc-update-btn",onClick:IN,children:f("reload-no-cache")}),e.kind==="reload"&&o.jsx("button",{className:"nc-update-btn",onClick:d$,children:f("reload")}),o.jsx("button",{className:"nc-update-close",onClick:o$,"aria-label":f("update-dismiss"),title:f("update-dismiss"),children:"×"})]}):null}function w$(){Fn();const[e,t]=y.useState(!1);return y.useEffect(()=>{const n=()=>t(!0);return window.addEventListener(Mm,n),()=>window.removeEventListener(Mm,n)},[]),e?o.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[o.jsx("span",{className:"nc-update-msg",children:f("auth-not-remembered")}),o.jsx("button",{className:"nc-update-close",onClick:()=>t(!1),"aria-label":f("update-dismiss"),title:f("update-dismiss"),children:"×"})]}):null}function Zx({fixture:e}){return o.jsxs("section",{className:"nc-tile nc-ui0-tile","aria-label":`${e.label}, chat`,children:[o.jsxs("header",{className:"nc-tile-head",children:[o.jsxs("span",{className:"nc-tile-name",title:`${e.label} · ${e.sub}`,children:[o.jsx("span",{className:"nc-dot on"}),o.jsx("b",{children:e.label})]}),o.jsx("small",{className:"nc-ui0-sub",children:e.sub})]}),o.jsx("div",{className:"nc-tile-body",children:o.jsx(a_,{target:e.target,events:e.events,viewer:e.viewer,reviews:e.reviews,label:e.label,capabilities:{permissionPolicy:"yolo"}})})]})}function S$(){return o.jsxs("div",{className:"nc-ui0-demo",children:[o.jsxs("header",{className:"nc-ui0-bar",children:[o.jsx("b",{children:"UI-0 · chat per cella"}),o.jsx("span",{children:"fixture nc-chat/1 statiche · nessuna rete"})]}),o.jsxs("main",{className:"nc-ui0-grid",children:[o.jsx(Zx,{fixture:go.vl}),o.jsx(Zx,{fixture:go.cli})]})]})}const DN=Y3(window.location.search)&&l_();DN||(u$(),zO());y5.createRoot(document.getElementById("root")).render(o.jsx(h5.StrictMode,{children:DN?o.jsx(S$,{}):o.jsxs(o.Fragment,{children:[o.jsx(_$,{}),o.jsx(b$,{}),o.jsx(w$,{})]})}));