var Ua=Object.defineProperty;var ja=(e,t,i)=>t in e?Ua(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var D=(e,t,i)=>ja(e,typeof t!="symbol"?t+"":t,i);import{d as ls,Z as si,d7 as pe,dw as Ka,dx as rt,dy as es,dz as qa,c8 as Co,cX as xo,cY as Va,z as ko,dA as Ga,dB as Ya,dC as Xa,e as Eo,cW as Ja,bq as Za,dD as Qa,bF as Ro,dE as ge,bh as el,bg as tl,b_ as xt,dF as il,dG as sl,dH as rl,dI as nl,dm as zr,j as m,ak as Bo,dJ as Mo,al as Lo,B as ol,r as U,A as fs,m as $i,dK as Ur,dL as jr,cv as al,dM as ll,c as ts,dN as hl,dO as cl,K as dl,dP as ul,dQ as _l,dR as fl}from"./index-BOwCLZTK.js";import{a as pl}from"./ping-LiBbR-Oy.js";import{g as ml,r as gl}from"./system-BNWIl4nC.js";import{g as vi,B as Do,r as To,T as $o}from"./ascii-burst-DN6etEs5.js";import{P as vl,B as Sl,C as yl}from"./PageLayout-QKntxcnp.js";import{K as Ao,S as wl}from"./KeycapButton-uJlkDPOC.js";import{D as Kr}from"./download-B9g5-0oH.js";import{S as qr}from"./search-Ba9CRHru.js";import{C as bl}from"./chevron-right-DJVm4pVP.js";import"./keycap-sfx-ByZp-njj.js";/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Cl=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]],Po=ls("book-open-text",Cl);/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const xl=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],kl=ls("corner-down-left",xl);/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const El=[["path",{d:"M20 5a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h2.5a1.5 1.5 0 0 1 1.2.6l.6.8a1.5 1.5 0 0 0 1.2.6z",key:"a4852j"}],["path",{d:"M3 8.268a2 2 0 0 0-1 1.738V19a2 2 0 0 0 2 2h11a2 2 0 0 0 1.732-1",key:"yxbcw3"}]],Rl=ls("folders",El);/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bl=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],Ml=ls("package",Bl);/**
 * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
 * @license MIT
 *
 * Originally forked from (with the author's permission):
 *   Fabrice Bellard's javascript vt100 for jslinux:
 *   http://bellard.org/jslinux/
 *   Copyright (c) 2011 Fabrice Bellard
 */var No=Object.defineProperty,Ll=Object.getOwnPropertyDescriptor,Dl=(e,t)=>{for(var i in t)No(e,i,{get:t[i],enumerable:!0})},_e=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ll(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(r=(s?o(t,i,r):o(r))||r);return s&&r&&No(t,i,r),r},$=(e,t)=>(i,s)=>t(i,s,e),Vr="Terminal input",Os={get:()=>Vr,set:e=>Vr=e},Gr="Too much output to announce, navigate to rows manually to read",Fs={get:()=>Gr,set:e=>Gr=e};function Tl(e){return e.replace(/\r?\n/g,"\r")}function $l(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function Al(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Pl(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let r=e.clipboardData.getData("text/plain");Io(r,t,i,s)}}function Io(e,t,i,s){e=Tl(e),e=$l(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Oo(e,t,i){let s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function Yr(e,t,i,s,r){Oo(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Ct(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function hs(e,t=0,i=e.length){let s="";for(let r=t;r<i;++r){let n=e[r];n>65535?(n-=65536,s+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):s+=String.fromCharCode(n)}return s}var Nl=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){let n=e.charCodeAt(r++);56320<=n&&n<=57343?t[s++]=(this._interim-55296)*1024+n-56320+65536:(t[s++]=this._interim,t[s++]=n),this._interim=0}for(let n=r;n<i;++n){let o=e.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=i)return this._interim=o,s;let a=e.charCodeAt(n);56320<=a&&a<=57343?t[s++]=(o-55296)*1024+a-56320+65536:(t[s++]=o,t[s++]=a);continue}o!==65279&&(t[s++]=o)}return s}},Il=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r,n,o,a,h=0,l=0;if(this.interim[0]){let u=!1,f=this.interim[0];f&=(f&224)===192?31:(f&240)===224?15:7;let _=0,p;for(;(p=this.interim[++_]&63)&&_<4;)f<<=6,f|=p;let g=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,x=g-_;for(;l<x;){if(l>=i)return 0;if(p=e[l++],(p&192)!==128){l--,u=!0;break}else this.interim[_++]=p,f<<=6,f|=p&63}u||(g===2?f<128?l--:t[s++]=f:g===3?f<2048||f>=55296&&f<=57343||f===65279||(t[s++]=f):f<65536||f>1114111||(t[s++]=f)),this.interim.fill(0)}let c=i-4,d=l;for(;d<i;){for(;d<c&&!((r=e[d])&128)&&!((n=e[d+1])&128)&&!((o=e[d+2])&128)&&!((a=e[d+3])&128);)t[s++]=r,t[s++]=n,t[s++]=o,t[s++]=a,d+=4;if(r=e[d++],r<128)t[s++]=r;else if((r&224)===192){if(d>=i)return this.interim[0]=r,s;if(n=e[d++],(n&192)!==128){d--;continue}if(h=(r&31)<<6|n&63,h<128){d--;continue}t[s++]=h}else if((r&240)===224){if(d>=i)return this.interim[0]=r,s;if(n=e[d++],(n&192)!==128){d--;continue}if(d>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[d++],(o&192)!==128){d--;continue}if(h=(r&15)<<12|(n&63)<<6|o&63,h<2048||h>=55296&&h<=57343||h===65279)continue;t[s++]=h}else if((r&248)===240){if(d>=i)return this.interim[0]=r,s;if(n=e[d++],(n&192)!==128){d--;continue}if(d>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[d++],(o&192)!==128){d--;continue}if(d>=i)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=o,s;if(a=e[d++],(a&192)!==128){d--;continue}if(h=(r&7)<<18|(n&63)<<12|(o&63)<<6|a&63,h<65536||h>1114111)continue;t[s++]=h}}return s}},Fo="",kt=" ",xi=class Ho{constructor(){this.fg=0,this.bg=0,this.extended=new is}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 Ho;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}},is=class Wo{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}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 Wo(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Ze=class zo extends xi{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new is,this.combinedData=""}static fromCharData(t){let i=new zo;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ct(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 i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let r=t[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(s-55296)*1024+r-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Xr="di$target",Hs="di$dependencies",ps=new Map;function Ol(e){return e[Hs]||[]}function Me(e){if(ps.has(e))return ps.get(e);let t=function(i,s,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Fl(t,i,r)};return t._id=e,ps.set(e,t),t}function Fl(e,t,i){t[Xr]===t?t[Hs].push({id:e,index:i}):(t[Hs]=[{id:e,index:i}],t[Xr]=t)}var Oe=Me("BufferService"),Uo=Me("CoreMouseService"),Ft=Me("CoreService"),Hl=Me("CharsetService"),Rr=Me("InstantiationService"),jo=Me("LogService"),Fe=Me("OptionsService"),Ko=Me("OscLinkService"),Wl=Me("UnicodeService"),ki=Me("DecorationService"),Ws=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var c;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],r=this._optionsService.rawOptions.linkHandler,n=new Ze,o=i.getTrimmedLength(),a=-1,h=-1,l=!1;for(let d=0;d<o;d++)if(!(h===-1&&!i.hasContent(d))){if(i.loadCell(d,n),n.hasExtendedAttrs()&&n.extended.urlId)if(h===-1){h=d,a=n.extended.urlId;continue}else l=n.extended.urlId!==a;else h!==-1&&(l=!0);if(l||h!==-1&&d===o-1){let u=(c=this._oscLinkService.getLinkData(a))==null?void 0:c.uri;if(u){let f={start:{x:h+1,y:e},end:{x:d+(!l&&d===o-1?1:0),y:e}},_=!1;if(!(r!=null&&r.allowNonHttpProtocols))try{let p=new URL(u);["http:","https:"].includes(p.protocol)||(_=!0)}catch{_=!0}_||s.push({text:u,range:f,activate:(p,g)=>r?r.activate(p,g,f):zl(p,g),hover:(p,g)=>{var x;return(x=r==null?void 0:r.hover)==null?void 0:x.call(r,p,g,f)},leave:(p,g)=>{var x;return(x=r==null?void 0:r.leave)==null?void 0:x.call(r,p,g,f)}})}l=!1,n.hasExtendedAttrs()&&n.extended.urlId?(h=d,a=n.extended.urlId):(h=-1,a=-1)}}t(s)}};Ws=_e([$(0,Oe),$(1,Fe),$(2,Ko)],Ws);function zl(e,t){if(confirm(`Do you want to navigate to ${t}?

WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var cs=Me("CharSizeService"),pt=Me("CoreBrowserService"),Br=Me("MouseService"),mt=Me("RenderService"),Ul=Me("SelectionService"),qo=Me("CharacterJoinerService"),ei=Me("ThemeService"),Vo=Me("LinkProviderService"),jl=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Jr.isErrorNoTelemetry(e)?new Jr(e.message+`

`+e.stack):new Error(e.message+`

`+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)}},Kl=new jl;function zi(e){ql(e)||Kl.onUnexpectedError(e)}var zs="Canceled";function ql(e){return e instanceof Vl?!0:e instanceof Error&&e.name===zs&&e.message===zs}var Vl=class extends Error{constructor(){super(zs),this.name=this.message}};function Gl(e){return new Error(`Illegal argument: ${e}`)}var Jr=class Us extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Us)return t;let i=new Us;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},js=class Go extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Go.prototype)}};function je(e,t=0){return e[e.length-(1+t)]}var Yl;(e=>{function t(n){return n<0}e.isLessThan=t;function i(n){return n<=0}e.isLessThanOrEqual=i;function s(n){return n>0}e.isGreaterThan=s;function r(n){return n===0}e.isNeitherLessOrGreaterThan=r,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Yl||(Yl={}));function Xl(e,t){let i=this,s=!1,r;return function(){return s||(s=!0,t||(r=e.apply(i,arguments))),r}}var Yo;(e=>{function t(M){return M&&typeof M=="object"&&typeof M[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*r(M){yield M}e.single=r;function n(M){return t(M)?M:r(M)}e.wrap=n;function o(M){return M||i}e.from=o;function*a(M){for(let N=M.length-1;N>=0;N--)yield M[N]}e.reverse=a;function h(M){return!M||M[Symbol.iterator]().next().done===!0}e.isEmpty=h;function l(M){return M[Symbol.iterator]().next().value}e.first=l;function c(M,N){let K=0;for(let ie of M)if(N(ie,K++))return!0;return!1}e.some=c;function d(M,N){for(let K of M)if(N(K))return K}e.find=d;function*u(M,N){for(let K of M)N(K)&&(yield K)}e.filter=u;function*f(M,N){let K=0;for(let ie of M)yield N(ie,K++)}e.map=f;function*_(M,N){let K=0;for(let ie of M)yield*N(ie,K++)}e.flatMap=_;function*p(...M){for(let N of M)yield*N}e.concat=p;function g(M,N,K){let ie=K;for(let ae of M)ie=N(ie,ae);return ie}e.reduce=g;function*x(M,N,K=M.length){for(N<0&&(N+=M.length),K<0?K+=M.length:K>M.length&&(K=M.length);N<K;N++)yield M[N]}e.slice=x;function z(M,N=Number.POSITIVE_INFINITY){let K=[];if(N===0)return[K,M];let ie=M[Symbol.iterator]();for(let ae=0;ae<N;ae++){let J=ie.next();if(J.done)return[K,e.empty()];K.push(J.value)}return[K,{[Symbol.iterator](){return ie}}]}e.consume=z;async function O(M){let N=[];for await(let K of M)N.push(K);return Promise.resolve(N)}e.asyncToArray=O})(Yo||(Yo={}));function It(e){if(Yo.is(e)){let t=[];for(let i of e)if(i)try{i.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 Jl(...e){return oe(()=>It(e))}function oe(e){return{dispose:Xl(()=>{e()})}}var Xo=class Jo{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{It(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?Jo.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)}};Xo.DISABLE_DISPOSED_WARNING=!1;var Et=Xo,G=class{constructor(){this._store=new Et,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)}};G.None=Object.freeze({dispose(){}});var Zt=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}},ft=typeof window=="object"?window:globalThis,Ks=class qs{constructor(t){this.element=t,this.next=qs.Undefined,this.prev=qs.Undefined}};Ks.Undefined=new Ks(void 0);var le=Ks,Zr=class{constructor(){this._first=le.Undefined,this._last=le.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===le.Undefined}clear(){let e=this._first;for(;e!==le.Undefined;){let t=e.next;e.prev=le.Undefined,e.next=le.Undefined,e=t}this._first=le.Undefined,this._last=le.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new le(e);if(this._first===le.Undefined)this._first=i,this._last=i;else if(t){let r=this._last;this._last=i,i.prev=r,r.next=i}else{let r=this._first;this._first=i,i.next=r,r.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==le.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==le.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==le.Undefined&&e.next!==le.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===le.Undefined&&e.next===le.Undefined?(this._first=le.Undefined,this._last=le.Undefined):e.next===le.Undefined?(this._last=this._last.prev,this._last.next=le.Undefined):e.prev===le.Undefined&&(this._first=this._first.next,this._first.prev=le.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==le.Undefined;)yield e.element,e=e.next}},Zl=globalThis.performance&&typeof globalThis.performance.now=="function",Ql=class Zo{static create(t){return new Zo(t)}constructor(t){this._now=Zl&&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}},De;(e=>{e.None=()=>G.None;function t(P,S){return d(P,()=>{},0,void 0,!0,void 0,S)}e.defer=t;function i(P){return(S,L=null,B)=>{let T=!1,H;return H=P(R=>{if(!T)return H?H.dispose():T=!0,S.call(L,R)},null,B),T&&H.dispose(),H}}e.once=i;function s(P,S,L){return l((B,T=null,H)=>P(R=>B.call(T,S(R)),null,H),L)}e.map=s;function r(P,S,L){return l((B,T=null,H)=>P(R=>{S(R),B.call(T,R)},null,H),L)}e.forEach=r;function n(P,S,L){return l((B,T=null,H)=>P(R=>S(R)&&B.call(T,R),null,H),L)}e.filter=n;function o(P){return P}e.signal=o;function a(...P){return(S,L=null,B)=>{let T=Jl(...P.map(H=>H(R=>S.call(L,R))));return c(T,B)}}e.any=a;function h(P,S,L,B){let T=L;return s(P,H=>(T=S(T,H),T),B)}e.reduce=h;function l(P,S){let L,B={onWillAddFirstListener(){L=P(T.fire,T)},onDidRemoveLastListener(){L==null||L.dispose()}},T=new C(B);return S==null||S.add(T),T.event}function c(P,S){return S instanceof Array?S.push(P):S&&S.add(P),P}function d(P,S,L=100,B=!1,T=!1,H,R){let Y,se,xe,Ve=0,Pe,re={leakWarningThreshold:H,onWillAddFirstListener(){Y=P(He=>{Ve++,se=S(se,He),B&&!xe&&(Ge.fire(se),se=void 0),Pe=()=>{let ut=se;se=void 0,xe=void 0,(!B||Ve>1)&&Ge.fire(ut),Ve=0},typeof L=="number"?(clearTimeout(xe),xe=setTimeout(Pe,L)):xe===void 0&&(xe=0,queueMicrotask(Pe))})},onWillRemoveListener(){T&&Ve>0&&(Pe==null||Pe())},onDidRemoveLastListener(){Pe=void 0,Y.dispose()}},Ge=new C(re);return R==null||R.add(Ge),Ge.event}e.debounce=d;function u(P,S=0,L){return e.debounce(P,(B,T)=>B?(B.push(T),B):[T],S,void 0,!0,void 0,L)}e.accumulate=u;function f(P,S=(B,T)=>B===T,L){let B=!0,T;return n(P,H=>{let R=B||!S(H,T);return B=!1,T=H,R},L)}e.latch=f;function _(P,S,L){return[e.filter(P,S,L),e.filter(P,B=>!S(B),L)]}e.split=_;function p(P,S=!1,L=[],B){let T=L.slice(),H=P(se=>{T?T.push(se):Y.fire(se)});B&&B.add(H);let R=()=>{T==null||T.forEach(se=>Y.fire(se)),T=null},Y=new C({onWillAddFirstListener(){H||(H=P(se=>Y.fire(se)),B&&B.add(H))},onDidAddFirstListener(){T&&(S?setTimeout(R):R())},onDidRemoveLastListener(){H&&H.dispose(),H=null}});return B&&B.add(Y),Y.event}e.buffer=p;function g(P,S){return(L,B,T)=>{let H=S(new z);return P(function(R){let Y=H.evaluate(R);Y!==x&&L.call(B,Y)},void 0,T)}}e.chain=g;let x=Symbol("HaltChainable");class z{constructor(){this.steps=[]}map(S){return this.steps.push(S),this}forEach(S){return this.steps.push(L=>(S(L),L)),this}filter(S){return this.steps.push(L=>S(L)?L:x),this}reduce(S,L){let B=L;return this.steps.push(T=>(B=S(B,T),B)),this}latch(S=(L,B)=>L===B){let L=!0,B;return this.steps.push(T=>{let H=L||!S(T,B);return L=!1,B=T,H?T:x}),this}evaluate(S){for(let L of this.steps)if(S=L(S),S===x)break;return S}}function O(P,S,L=B=>B){let B=(...Y)=>R.fire(L(...Y)),T=()=>P.on(S,B),H=()=>P.removeListener(S,B),R=new C({onWillAddFirstListener:T,onDidRemoveLastListener:H});return R.event}e.fromNodeEventEmitter=O;function M(P,S,L=B=>B){let B=(...Y)=>R.fire(L(...Y)),T=()=>P.addEventListener(S,B),H=()=>P.removeEventListener(S,B),R=new C({onWillAddFirstListener:T,onDidRemoveLastListener:H});return R.event}e.fromDOMEventEmitter=M;function N(P){return new Promise(S=>i(P)(S))}e.toPromise=N;function K(P){let S=new C;return P.then(L=>{S.fire(L)},()=>{S.fire(void 0)}).finally(()=>{S.dispose()}),S.event}e.fromPromise=K;function ie(P,S){return P(L=>S.fire(L))}e.forward=ie;function ae(P,S,L){return S(L),P(B=>S(B))}e.runAndSubscribe=ae;class J{constructor(S,L){this._observable=S,this._counter=0,this._hasChanged=!1;let B={onWillAddFirstListener:()=>{S.addObserver(this)},onDidRemoveLastListener:()=>{S.removeObserver(this)}};this.emitter=new C(B),L&&L.add(this.emitter)}beginUpdate(S){this._counter++}handlePossibleChange(S){}handleChange(S,L){this._hasChanged=!0}endUpdate(S){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function Te(P,S){return new J(P,S).emitter.event}e.fromObservable=Te;function X(P){return(S,L,B)=>{let T=0,H=!1,R={beginUpdate(){T++},endUpdate(){T--,T===0&&(P.reportChanges(),H&&(H=!1,S.call(L)))},handlePossibleChange(){},handleChange(){H=!0}};P.addObserver(R),P.reportChanges();let Y={dispose(){P.removeObserver(R)}};return B instanceof Et?B.add(Y):Array.isArray(B)&&B.push(Y),Y}}e.fromObservableLight=X})(De||(De={}));var Vs=class Gs{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Gs._idPool++}`,Gs.all.add(this)}start(t){this._stopWatch=new Ql,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}}};Vs.all=new Set,Vs._idPool=0;var eh=Vs,th=-1,Qo=class ea{constructor(t,i,s=(ea._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i<s)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=s*.5;let[n,o]=this.getMostFrequentStack(),a=`[${this.name}] potential listener LEAK detected, having ${i} listeners already. MOST frequent listener (${o}):`;console.warn(a),console.warn(n);let h=new rh(a,n);this._errorHandler(h)}return()=>{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,r]of this._stacks)(!t||i<r)&&(t=[s,r],i=r);return t}};Qo._idPool=1;var ih=Qo,sh=class ta{constructor(t){this.value=t}static create(){let t=new Error;return new ta(t.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},rh=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},nh=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},oh=0,ms=class{constructor(e){this.value=e,this.id=oh++}},ah=2,lh,C=class{constructor(t){var i,s,r,n;this._size=0,this._options=t,this._leakageMon=(i=this._options)!=null&&i.leakWarningThreshold?new ih((t==null?void 0:t.onListenerError)??zi,((s=this._options)==null?void 0:s.leakWarningThreshold)??th):void 0,this._perfMon=(r=this._options)!=null&&r._profName?new eh(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var t,i,s,r;this._disposed||(this._disposed=!0,((t=this._deliveryQueue)==null?void 0:t.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(s=(i=this._options)==null?void 0:i.onDidRemoveLastListener)==null||s.call(i),(r=this._leakageMon)==null||r.dispose())}get event(){return this._event??(this._event=(t,i,s)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],_=new nh(`${u}. HINT: Stack shows most frequent listener (${f[1]}-times)`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||zi)(_),G.None}if(this._disposed)return G.None;i&&(t=t.bind(i));let r=new ms(t),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=sh.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ms?(this._deliveryQueue??(this._deliveryQueue=new hh),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null||l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null||d.call(c,this)),this._size++;let o=oe(()=>{n==null||n(),this._removeListener(r)});return s instanceof Et?s.add(o):Array.isArray(s)&&s.push(o),o}),this._event}_removeListener(t){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null||o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null||h.call(a,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-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--,i[s]=void 0;let r=this._deliveryQueue.current===this;if(this._size*ah<=i.length){let l=0;for(let c=0;c<i.length;c++)i[c]?i[l++]=i[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);i.length=l}}_deliver(t,i){var r;if(!t)return;let s=((r=this._options)==null?void 0:r.onListenerError)||zi;if(!s){t.value(i);return}try{t.value(i)}catch(n){s(n)}}_deliverQueue(t){let i=t.current._listeners;for(;t.i<t.end;)this._deliver(i[t.i++],t.value);t.reset()}fire(t){var i,s,r,n;if((i=this._deliveryQueue)!=null&&i.current&&(this._deliverQueue(this._deliveryQueue),(s=this._perfMon)==null||s.stop()),(r=this._perfMon)==null||r.start(this._size),this._listeners)if(this._listeners instanceof ms)this._deliver(this._listeners,t);else{let o=this._deliveryQueue;o.enqueue(this,t,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null||n.stop()}hasListeners(){return this._size>0}},hh=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Ys=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new C,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new C,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Ys.INSTANCE=new Ys;var Mr=Ys;function ch(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Mr.INSTANCE.onDidChangeZoomLevel;function dh(e){return Mr.INSTANCE.getZoomFactor(e)}Mr.INSTANCE.onDidChangeFullscreen;var ti=typeof navigator=="object"?navigator.userAgent:"",Xs=ti.indexOf("Firefox")>=0,uh=ti.indexOf("AppleWebKit")>=0,Lr=ti.indexOf("Chrome")>=0,_h=!Lr&&ti.indexOf("Safari")>=0;ti.indexOf("Electron/")>=0;ti.indexOf("Android")>=0;var gs=!1;if(typeof ft.matchMedia=="function"){let e=ft.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ft.matchMedia("(display-mode: fullscreen)");gs=e.matches,ch(ft,e,({matches:i})=>{gs&&t.matches||(gs=i)})}var Gt="en",Js=!1,Zs=!1,Ui=!1,ia=!1,Ai,ji=Gt,Qr=Gt,fh,tt,Nt=globalThis,Le,yo;typeof Nt.vscode<"u"&&typeof Nt.vscode.process<"u"?Le=Nt.vscode.process:typeof process<"u"&&typeof((yo=process==null?void 0:process.versions)==null?void 0:yo.node)=="string"&&(Le=process);var wo,ph=typeof((wo=Le==null?void 0:Le.versions)==null?void 0:wo.electron)=="string",mh=ph&&(Le==null?void 0:Le.type)==="renderer",bo;if(typeof Le=="object"){Js=Le.platform==="win32",Zs=Le.platform==="darwin",Ui=Le.platform==="linux",Ui&&Le.env.SNAP&&Le.env.SNAP_REVISION,Le.env.CI||Le.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Ai=Gt,ji=Gt;let e=Le.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Ai=t.userLocale,Qr=t.osLocale,ji=t.resolvedLanguage||Gt,fh=(bo=t.languagePack)==null?void 0:bo.translationsConfigFile}catch{}ia=!0}else typeof navigator=="object"&&!mh?(tt=navigator.userAgent,Js=tt.indexOf("Windows")>=0,Zs=tt.indexOf("Macintosh")>=0,(tt.indexOf("Macintosh")>=0||tt.indexOf("iPad")>=0||tt.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Ui=tt.indexOf("Linux")>=0,(tt==null?void 0:tt.indexOf("Mobi"))>=0,ji=globalThis._VSCODE_NLS_LANGUAGE||Gt,Ai=navigator.language.toLowerCase(),Qr=Ai):console.error("Unable to resolve platform.");var sa=Js,ct=Zs,gh=Ui,en=ia,dt=tt,vt=ji,vh;(e=>{function t(){return vt}e.value=t;function i(){return vt.length===2?vt==="en":vt.length>=3?vt[0]==="e"&&vt[1]==="n"&&vt[2]==="-":!1}e.isDefaultVariant=i;function s(){return vt==="en"}e.isDefault=s})(vh||(vh={}));var Sh=typeof Nt.postMessage=="function"&&!Nt.importScripts;(()=>{if(Sh){let e=[];Nt.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,r=e.length;s<r;s++){let n=e[s];if(n.id===i.data.vscodeScheduleAsyncWork){e.splice(s,1),n.callback();return}}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),Nt.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var yh=!!(dt&&dt.indexOf("Chrome")>=0);dt&&dt.indexOf("Firefox")>=0;!yh&&dt&&dt.indexOf("Safari")>=0;dt&&dt.indexOf("Edg/")>=0;dt&&dt.indexOf("Android")>=0;var Ut=typeof navigator=="object"?navigator:{};en||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ut&&Ut.clipboard&&Ut.clipboard.writeText,en||Ut&&Ut.clipboard&&Ut.clipboard.readText;var Dr=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}},vs=new Dr,tn=new Dr,sn=new Dr,wh=new Array(230),ra;(e=>{function t(a){return vs.keyCodeToStr(a)}e.toString=t;function i(a){return vs.strToKeyCode(a)}e.fromString=i;function s(a){return tn.keyCodeToStr(a)}e.toUserSettingsUS=s;function r(a){return sn.keyCodeToStr(a)}e.toUserSettingsGeneral=r;function n(a){return tn.strToKeyCode(a)||sn.strToKeyCode(a)}e.fromUserSettings=n;function o(a){if(a>=98&&a<=113)return null;switch(a){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return vs.keyCodeToStr(a)}e.toElectronAccelerator=o})(ra||(ra={}));var bh=class na{constructor(t,i,s,r,n){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=r,this.keyCode=n}equals(t){return t instanceof na&&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",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",r=this.metaKey?"1":"0";return`K${t}${i}${s}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Ch([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Ch=class{constructor(e){if(e.length===0)throw Gl("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t<i;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 xh(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return ra.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(Xs)switch(t){case 59:return 85;case 60:if(gh)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(ct)return 57;break}else if(uh&&(ct&&t===93||!ct&&t===92))return 57;return wh[t]||0}var kh=ct?256:2048,Eh=512,Rh=1024,Bh=ct?2048:256,rn=class{constructor(e){var i;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=(i=t.getModifierState)==null?void 0:i.call(t,"AltGraph"),this.keyCode=xh(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|=kh),this.altKey&&(t|=Eh),this.shiftKey&&(t|=Rh),this.metaKey&&(t|=Bh),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new bh(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},nn=new WeakMap;function Mh(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!=="null"&&i.origin!=="null"&&t.origin!==i.origin)return null}catch{return null}return e.parent}var Lh=class{static getSameOriginWindowChain(e){let t=nn.get(e);if(!t){t=[],nn.set(e,t);let i=e,s;do s=Mh(i),s?t.push({window:new WeakRef(i),iframeElement:i.frameElement||null}):t.push({window:new WeakRef(i),iframeElement:null}),i=s;while(i)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,s=0,r=this.getSameOriginWindowChain(e);for(let n of r){let o=n.window.deref();if(i+=(o==null?void 0:o.scrollY)??0,s+=(o==null?void 0:o.scrollX)??0,o===t||!n.iframeElement)break;let a=n.iframeElement.getBoundingClientRect();i+=a.top,s+=a.left}return{top:i,left:s}}},Pi=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type==="dblclick"&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX=="number"?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let i=Lh.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},on=class{constructor(e,t=0,i=0){var r;this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let s=!1;if(Lr){let n=navigator.userAgent.match(/Chrome\/(\d+)/);s=(n?parseInt(n[1]):123)<=122}if(e){let n=e,o=e,a=((r=e.view)==null?void 0:r.devicePixelRatio)||1;if(typeof n.wheelDeltaY<"u")s?this.deltaY=n.wheelDeltaY/(120*a):this.deltaY=n.wheelDeltaY/120;else if(typeof o.VERTICAL_AXIS<"u"&&o.axis===o.VERTICAL_AXIS)this.deltaY=-o.detail/3;else if(e.type==="wheel"){let h=e;h.deltaMode===h.DOM_DELTA_LINE?Xs&&!ct?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof n.wheelDeltaX<"u")_h&&sa?this.deltaX=-(n.wheelDeltaX/120):s?this.deltaX=n.wheelDeltaX/(120*a):this.deltaX=n.wheelDeltaX/120;else if(typeof o.HORIZONTAL_AXIS<"u"&&o.axis===o.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type==="wheel"){let h=e;h.deltaMode===h.DOM_DELTA_LINE?Xs&&!ct?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(s?this.deltaY=e.wheelDelta/(120*a):this.deltaY=e.wheelDelta/120)}}preventDefault(){var e;(e=this.browserEvent)==null||e.preventDefault()}stopPropagation(){var e;(e=this.browserEvent)==null||e.stopPropagation()}},oa=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}}),Dh;(e=>{function t(i){return i===e.None||i===e.Cancelled||i instanceof Th?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:De.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:oa})})(Dh||(Dh={}));var Th=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?oa:(this._emitter||(this._emitter=new C),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Tr=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new js("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new js("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},$h=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new js("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=oe(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ah;(e=>{async function t(s){let r,n=await Promise.all(s.map(o=>o.then(a=>a,a=>{r||(r=a)})));if(typeof r<"u")throw r;return n}e.settled=t;function i(s){return new Promise(async(r,n)=>{try{await s(r,n)}catch(o){n(o)}})}e.withAsyncBody=i})(Ah||(Ah={}));var an=class Xe{static fromArray(t){return new Xe(i=>{i.emitMany(t)})}static fromPromise(t){return new Xe(async i=>{i.emitMany(await t)})}static fromPromises(t){return new Xe(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new Xe(async i=>{await Promise.all(t.map(async s=>{for await(let r of s)i.emitOne(r)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new C,queueMicrotask(async()=>{let s={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(s)),this.resolve()}catch(r){this.reject(r)}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 De.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new Xe(async s=>{for await(let r of t)s.emitOne(i(r))})}map(t){return Xe.map(this,t)}static filter(t,i){return new Xe(async s=>{for await(let r of t)i(r)&&s.emitOne(r)})}filter(t){return Xe.filter(this,t)}static coalesce(t){return Xe.filter(t,i=>!!i)}coalesce(){return Xe.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return Xe.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())}};an.EMPTY=an.fromArray([]);var{getWindow:ht,getWindowId:Ph,onDidRegisterWindow:Nh}=(function(){let e=new Map,t={window:ft,disposables:new Et};e.set(ft.vscodeWindowId,t);let i=new C,s=new C,r=new C;function n(o,a){return(typeof o=="number"?e.get(o):void 0)??(a?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:s.event,registerWindow(o){if(e.has(o.vscodeWindowId))return G.None;let a=new Et,h={window:o,disposables:a.add(new Et)};return e.set(o.vscodeWindowId,h),a.add(oe(()=>{e.delete(o.vscodeWindowId),s.fire(o)})),a.add(j(o,ke.BEFORE_UNLOAD,()=>{r.fire(o)})),i.fire(h),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return e.has(o)},getWindowById:n,getWindow(o){var l;let a=o;if((l=a==null?void 0:a.ownerDocument)!=null&&l.defaultView)return a.ownerDocument.defaultView.window;let h=o;return h!=null&&h.view?h.view.window:ft},getDocument(o){return ht(o).document}}})(),Ih=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,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 j(e,t,i,s){return new Ih(e,t,i,s)}var ln=function(e,t,i,s){return j(e,t,i,s)},$r,Oh=class extends $h{constructor(e){super(),this.defaultTarget=e&&ht(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},hn=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){zi(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,r=n=>{i.set(n,!1);let o=e.get(n)??[];for(t.set(n,o),e.set(n,[]),s.set(n,!0);o.length>0;)o.sort(hn.sort),o.shift().execute();s.set(n,!1)};$r=(n,o,a=0)=>{let h=Ph(n),l=new hn(o,a),c=e.get(h);return c||(c=[],e.set(h,c)),c.push(l),i.get(h)||(i.set(h,!0),n.requestAnimationFrame(()=>r(h))),l}})();function Fh(e){let t=e.getBoundingClientRect(),i=ht(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var ke={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"},Hh=class{constructor(e){this.domNode=e,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(e){let t=We(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=We(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=We(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=We(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=We(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=We(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=We(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=We(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=We(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=We(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=We(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=We(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=We(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=We(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function We(e){return typeof e=="number"?`${e}px`:e}function Si(e){return new Hh(e)}var aa=class{constructor(){this._hooks=new Et,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add(oe(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=ht(e)}this._hooks.add(j(n,ke.POINTER_MOVE,o=>{if(o.buttons!==i){this.stopMonitoring(!0);return}o.preventDefault(),this._pointerMoveCallback(o)})),this._hooks.add(j(n,ke.POINTER_UP,o=>this.stopMonitoring(!0)))}};function Wh(e,t,i){let s=null,r=null;if(typeof i.value=="function"?(s="value",r=i.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",r=i.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;i[s]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,o)}),this[n]}}var lt;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(lt||(lt={}));var ui=class $e extends G{constructor(){super(),this.dispatched=!1,this.targets=new Zr,this.ignoreTargets=new Zr,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(De.runAndSubscribe(Nh,({window:t,disposables:i})=>{i.add(j(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(j(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(j(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:ft,disposables:this._store}))}static addTarget(t){if(!$e.isTouchDevice())return G.None;$e.INSTANCE||($e.INSTANCE=new $e);let i=$e.INSTANCE.targets.push(t);return oe(i)}static ignoreTarget(t){if(!$e.isTouchDevice())return G.None;$e.INSTANCE||($e.INSTANCE=new $e);let i=$e.INSTANCE.ignoreTargets.push(t);return oe(i)}static isTouchDevice(){return"ontouchstart"in ft||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,r=t.targetTouches.length;s<r;s++){let n=t.targetTouches.item(s);this.activeTouches[n.identifier]={id:n.identifier,initialTarget:n.target,initialTimeStamp:i,initialPageX:n.pageX,initialPageY:n.pageY,rollingTimestamps:[i],rollingPageX:[n.pageX],rollingPageY:[n.pageY]};let o=this.newGestureEvent(lt.Start,n.target);o.pageX=n.pageX,o.pageY=n.pageY,this.dispatchEvent(o)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let s=Date.now(),r=Object.keys(this.activeTouches).length;for(let n=0,o=i.changedTouches.length;n<o;n++){let a=i.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(a.identifier))){console.warn("move of an UNKNOWN touch",a);continue}let h=this.activeTouches[a.identifier],l=Date.now()-h.initialTimeStamp;if(l<$e.HOLD_DELAY&&Math.abs(h.initialPageX-je(h.rollingPageX))<30&&Math.abs(h.initialPageY-je(h.rollingPageY))<30){let c=this.newGestureEvent(lt.Tap,h.initialTarget);c.pageX=je(h.rollingPageX),c.pageY=je(h.rollingPageY),this.dispatchEvent(c)}else if(l>=$e.HOLD_DELAY&&Math.abs(h.initialPageX-je(h.rollingPageX))<30&&Math.abs(h.initialPageY-je(h.rollingPageY))<30){let c=this.newGestureEvent(lt.Contextmenu,h.initialTarget);c.pageX=je(h.rollingPageX),c.pageY=je(h.rollingPageY),this.dispatchEvent(c)}else if(r===1){let c=je(h.rollingPageX),d=je(h.rollingPageY),u=je(h.rollingTimestamps)-h.rollingTimestamps[0],f=c-h.rollingPageX[0],_=d-h.rollingPageY[0],p=[...this.targets].filter(g=>h.initialTarget instanceof Node&&g.contains(h.initialTarget));this.inertia(t,p,s,Math.abs(f)/u,f>0?1:-1,c,Math.abs(_)/u,_>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(lt.End,h.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===lt.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>$e.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===lt.Change||t.type===lt.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let r=0,n=t.initialTarget;for(;n&&n!==s;)r++,n=n.parentElement;i.push([r,s])}i.sort((s,r)=>s[0]-r[0]);for(let[s,r]of i)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,r,n,o,a,h,l){this.handle=$r(t,()=>{let c=Date.now(),d=c-s,u=0,f=0,_=!0;r+=$e.SCROLL_FRICTION*d,a+=$e.SCROLL_FRICTION*d,r>0&&(_=!1,u=n*r*d),a>0&&(_=!1,f=h*a*d);let p=this.newGestureEvent(lt.Change);p.translationX=u,p.translationY=f,i.forEach(g=>g.dispatchEvent(p)),_||this.inertia(t,i,c,r,n,o+u,a,h,l+f)})}onTouchMove(t){let i=Date.now();for(let s=0,r=t.changedTouches.length;s<r;s++){let n=t.changedTouches.item(s);if(!this.activeTouches.hasOwnProperty(String(n.identifier))){console.warn("end of an UNKNOWN touch",n);continue}let o=this.activeTouches[n.identifier],a=this.newGestureEvent(lt.Change,o.initialTarget);a.translationX=n.pageX-je(o.rollingPageX),a.translationY=n.pageY-je(o.rollingPageY),a.pageX=n.pageX,a.pageY=n.pageY,this.dispatchEvent(a),o.rollingPageX.length>3&&(o.rollingPageX.shift(),o.rollingPageY.shift(),o.rollingTimestamps.shift()),o.rollingPageX.push(n.pageX),o.rollingPageY.push(n.pageY),o.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};ui.SCROLL_FRICTION=-.005,ui.HOLD_DELAY=700,ui.CLEAR_TAP_COUNT_TIME=400,_e([Wh],ui,"isTouchDevice",1);var zh=ui,Ar=class extends G{onclick(e,t){this._register(j(e,ke.CLICK,i=>t(new Pi(ht(e),i))))}onmousedown(e,t){this._register(j(e,ke.MOUSE_DOWN,i=>t(new Pi(ht(e),i))))}onmouseover(e,t){this._register(j(e,ke.MOUSE_OVER,i=>t(new Pi(ht(e),i))))}onmouseleave(e,t){this._register(j(e,ke.MOUSE_LEAVE,i=>t(new Pi(ht(e),i))))}onkeydown(e,t){this._register(j(e,ke.KEY_DOWN,i=>t(new rn(i))))}onkeyup(e,t){this._register(j(e,ke.KEY_UP,i=>t(new rn(i))))}oninput(e,t){this._register(j(e,ke.INPUT,t))}onblur(e,t){this._register(j(e,ke.BLUR,t))}onfocus(e,t){this._register(j(e,ke.FOCUS,t))}onchange(e,t){this._register(j(e,ke.CHANGE,t))}ignoreGesture(e){return zh.ignoreTarget(e)}},cn=11,Uh=class extends Ar{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=cn+"px",this.domNode.style.height=cn+"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 aa),this._register(ln(this.bgDomNode,ke.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(ln(this.domNode,ke.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Oh),this._pointerdownScheduleRepeatTimer=this._register(new Tr)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,ht(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},jh=class Qs{constructor(t,i,s,r,n,o,a){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,r=r|0,n=n|0,o=o|0,a=a|0),this.rawScrollLeft=r,this.rawScrollTop=a,i<0&&(i=0),r+i>s&&(r=s-i),r<0&&(r=0),n<0&&(n=0),a+n>o&&(a=o-n),a<0&&(a=0),this.width=i,this.scrollWidth=s,this.scrollLeft=r,this.height=n,this.scrollHeight=o,this.scrollTop=a}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,i){return new Qs(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Qs(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,i){let s=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,a=this.scrollHeight!==t.scrollHeight,h=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,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:r,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:a,scrollTopChanged:h}}},Kh=class extends G{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new C),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new jh(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 i=this._state.withScrollDimensions(e,t);this._setState(i,!!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 i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new un(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=un.start(this._state,i,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 i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},dn=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function Ss(e,t){let i=t-e;return function(s){return e+i*Gh(s)}}function qh(e,t,i){return function(s){return s<i?e(s/i):t((s-i)/(1-i))}}var un=class er{constructor(t,i,s,r){this.from=t,this.to=i,this.duration=r,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,i,s){if(Math.abs(t-i)>2.5*s){let r,n;return t<i?(r=t+.75*s,n=i-.75*s):(r=t-.75*s,n=i+.75*s),qh(Ss(t,r),Ss(n,i),.33)}return Ss(t,i)}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 i=(t-this.startTime)/this.duration;if(i<1){let s=this.scrollLeft(i),r=this.scrollTop(i);return new dn(s,r,!1)}return new dn(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,s){return er.start(t,i,s)}static start(t,i,s){s=s+10;let r=Date.now()-10;return new er(t,i,r,s)}};function Vh(e){return Math.pow(e,3)}function Gh(e){return 1-Vh(1-e)}var Yh=class extends G{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Tr)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,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 e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},Xh=140,la=class extends Ar{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Yh(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new aa),this._shouldRender=!0,this.domNode=Si(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(j(this.domNode.domNode,ke.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Uh(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Si(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(j(this.slider.domNode,ke.POINTER_DOWN,r=>{r.button===0&&(r.preventDefault(),this._sliderPointerDown(r))})),this.onclick(this.slider.domNode,r=>{r.leftButton&&r.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(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(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let r=Fh(this.domNode.domNode);t=e.pageX-r.left,i=e.pageY-r.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,r=>{let n=this._sliderOrthogonalPointerPosition(r),o=Math.abs(n-i);if(sa&&o>Xh){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let a=this._sliderPointerPosition(r)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(a))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},ha=class tr{constructor(t,i,s,r,n,o){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new tr(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,r,n){let o=Math.max(0,s-t),a=Math.max(0,o-2*i),h=r>0&&r>s;if(!h)return{computedAvailableSize:Math.round(o),computedIsNeeded:h,computedSliderSize:Math.round(a),computedSliderRatio:0,computedSliderPosition:0};let l=Math.round(Math.max(20,Math.floor(s*a/r))),c=(a-l)/(r-s),d=n*c;return{computedAvailableSize:Math.round(o),computedIsNeeded:h,computedSliderSize:Math.round(l),computedSliderRatio:c,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=tr._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 i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i<this._computedSliderPosition?s-=this._visibleSize:s+=this._visibleSize,s}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let i=this._computedSliderPosition+t;return Math.round(i/this._computedSliderRatio)}},Jh=class extends la{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new ha(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,s.width,s.scrollWidth,r.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Zh=class extends la{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new ha(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,r.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}},Qh=500,_n=50,ec=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},ir=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,i=0,s=1,r=this._rear;do{let n=r===this._front?t:Math.pow(2,-s);if(t-=n,i+=this._memory[r].score*n,r===this._front)break;r=(this._capacity+r-1)%this._capacity,s++}while(!0);return i<=.5}acceptStandardWheelEvent(t){if(Lr){let i=ht(t.browserEvent),s=dh(i);this.accept(Date.now(),t.deltaX*s,t.deltaY*s)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,i,s){let r=null,n=new ec(t,i,s);this._front===-1&&this._rear===-1?(this._memory[0]=n,this._front=0,this._rear=0):(r=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]=n),n.score=this._computeScore(n,r)}_computeScore(t,i){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),i){let r=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(i.deltaX),a=Math.abs(i.deltaY),h=Math.max(Math.min(r,o),1),l=Math.max(Math.min(n,a),1),c=Math.max(r,o),d=Math.max(n,a);c%h===0&&d%l===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};ir.INSTANCE=new ir;var tc=ir,ic=class extends Ar{constructor(e,t,i){super(),this._onScroll=this._register(new C),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new C),this.onWillScroll=this._onWillScroll.event,this._options=rc(t),this._scrollable=i,this._register(this._scrollable.onScroll(r=>{this._onWillScroll.fire(r),this._onDidScroll(r),this._onScroll.fire(r)}));let s={onMouseWheel:r=>this._onMouseWheel(r),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Zh(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Jh(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=Si(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Si(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Si(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,r=>this._onMouseOver(r)),this.onmouseleave(this._listenOnDomNode,r=>this._onMouseLeave(r)),this._hideTimeout=this._register(new Tr),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=It(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,ct&&(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 on(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=It(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new on(i))};this._mouseWheelToDispose.push(j(this._listenOnDomNode,ke.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var r;if((r=e.browserEvent)!=null&&r.defaultPrevented)return;let t=tc.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let n=e.deltaY*this._options.mouseWheelScrollSensitivity,o=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&o+n===0?o=n=0:Math.abs(n)>=Math.abs(o)?o=0:n=0),this._options.flipAxes&&([n,o]=[o,n]);let a=!ct&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!o&&(o=n,n=0),e.browserEvent&&e.browserEvent.altKey&&(o=o*this._options.fastScrollSensitivity,n=n*this._options.fastScrollSensitivity);let h=this._scrollable.getFutureScrollPosition(),l={};if(n){let c=_n*n,d=h.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(l,d)}if(o){let c=_n*o,d=h.scrollLeft-(c<0?Math.floor(c):Math.ceil(c));this._horizontalScrollbar.writeScrollPosition(l,d)}l=this._scrollable.validateScrollPosition(l),(h.scrollLeft!==l.scrollLeft||h.scrollTop!==l.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(l):this._scrollable.setScrollPositionNow(l),i=!0)}let s=i;!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,i=e.scrollLeft>0,s=i?" left":"",r=t?" top":"",n=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${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(),Qh)}},sc=class extends ic{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function rc(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,ct&&(t.className+=" mac"),t}var sr=class extends G{constructor(e,t,i,s,r,n,o,a){super(),this._bufferService=i,this._optionsService=o,this._renderService=a,this._onRequestScrollLines=this._register(new C),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let h=this._register(new Kh({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:l=>$r(s.window,l)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{h.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new sc(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},h)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(l=>{this._scrollableElement.updateOptions({handleMouseWheel:!(l&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(De.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(oe(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(oe(()=>this._styleElement.remove())),this._register(De.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",`  background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",`  background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",`  background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
`)})),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(l=>this._handleScroll(l)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=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,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};sr=_e([$(2,Oe),$(3,pt),$(4,Uo),$(5,ei),$(6,Fe),$(7,mt)],sr);var rr=class extends G{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,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(n=>this._removeDecoration(n))),this._register(oe(()=>{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 e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};rr=_e([$(1,Oe),$(2,pt),$(3,ki),$(4,mt)],rr);var nc=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(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},ot={full:0,left:0,center:0,right:0},St={full:0,left:0,center:0,right:0},ri={full:0,left:0,center:0,right:0},ss=class extends G{constructor(e,t,i,s,r,n,o,a){var l;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=n,this._themeService=o,this._coreBrowserService=a,this._colorZoneStore=new nc,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(),(l=this._viewportElement.parentElement)==null||l.insertBefore(this._canvas,this._viewportElement),this._register(oe(()=>{var c;return(c=this._canvas)==null?void 0:c.remove()}));let h=this._canvas.getContext("2d");if(h)this._ctx=h;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 e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);St.full=this._canvas.width,St.left=e,St.center=t,St.right=e,this._refreshDrawHeightConstants(),ri.full=1,ri.left=1,ri.center=1+St.left,ri.right=1+St.left+St.center}_refreshDrawHeightConstants(){ot.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);ot.left=t,ot.center=t,ot.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.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 t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);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(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(ri[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-ot[e.position||"full"]/2),St[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+ot[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};ss=_e([$(2,Oe),$(3,ki),$(4,mt),$(5,Fe),$(6,ei),$(7,pt)],ss);var v;(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=`
`,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=""))(v||(v={}));var Ki;(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=""))(Ki||(Ki={}));var ca;(e=>e.ST=`${v.ESC}\\`)(ca||(ca={}));var nr=class{constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,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(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.length<e.length?this._coreService.triggerDataEvent(`${v.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),i=this._renderService.dimensions.css.cell.height,s=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+"px",this._compositionView.style.top=s+"px",this._compositionView.style.height=i+"px",this._compositionView.style.lineHeight=i+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let n=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+"px",this._textarea.style.top=s+"px",this._textarea.style.width=Math.max(n.width,1)+"px",this._textarea.style.height=Math.max(n.height,1)+"px",this._textarea.style.lineHeight=n.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};nr=_e([$(2,Oe),$(3,Fe),$(4,Ft),$(5,mt)],nr);var Ee=0,Re=0,Be=0,ue=0,fn={css:"#00000000",rgba:0},ve;(e=>{function t(r,n,o,a){return a!==void 0?`#${Tt(r)}${Tt(n)}${Tt(o)}${Tt(a)}`:`#${Tt(r)}${Tt(n)}${Tt(o)}`}e.toCss=t;function i(r,n,o,a=255){return(r<<24|n<<16|o<<8|a)>>>0}e.toRgba=i;function s(r,n,o,a){return{css:e.toCss(r,n,o,a),rgba:e.toRgba(r,n,o,a)}}e.toColor=s})(ve||(ve={}));var ne;(e=>{function t(h,l){if(ue=(l.rgba&255)/255,ue===1)return{css:l.css,rgba:l.rgba};let c=l.rgba>>24&255,d=l.rgba>>16&255,u=l.rgba>>8&255,f=h.rgba>>24&255,_=h.rgba>>16&255,p=h.rgba>>8&255;Ee=f+Math.round((c-f)*ue),Re=_+Math.round((d-_)*ue),Be=p+Math.round((u-p)*ue);let g=ve.toCss(Ee,Re,Be),x=ve.toRgba(Ee,Re,Be);return{css:g,rgba:x}}e.blend=t;function i(h){return(h.rgba&255)===255}e.isOpaque=i;function s(h,l,c){let d=qi.ensureContrastRatio(h.rgba,l.rgba,c);if(d)return ve.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=s;function r(h){let l=(h.rgba|255)>>>0;return[Ee,Re,Be]=qi.toChannels(l),{css:ve.toCss(Ee,Re,Be),rgba:l}}e.opaque=r;function n(h,l){return ue=Math.round(l*255),[Ee,Re,Be]=qi.toChannels(h.rgba),{css:ve.toCss(Ee,Re,Be,ue),rgba:ve.toRgba(Ee,Re,Be,ue)}}e.opacity=n;function o(h,l){return ue=h.rgba&255,n(h,ue*l/255)}e.multiplyOpacity=o;function a(h){return[h.rgba>>24&255,h.rgba>>16&255,h.rgba>>8&255]}e.toColorRGB=a})(ne||(ne={}));var he;(e=>{let t,i;try{let r=document.createElement("canvas");r.width=1,r.height=1;let n=r.getContext("2d",{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return Ee=parseInt(r.slice(1,2).repeat(2),16),Re=parseInt(r.slice(2,3).repeat(2),16),Be=parseInt(r.slice(3,4).repeat(2),16),ve.toColor(Ee,Re,Be);case 5:return Ee=parseInt(r.slice(1,2).repeat(2),16),Re=parseInt(r.slice(2,3).repeat(2),16),Be=parseInt(r.slice(3,4).repeat(2),16),ue=parseInt(r.slice(4,5).repeat(2),16),ve.toColor(Ee,Re,Be,ue);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let n=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(n)return Ee=parseInt(n[1]),Re=parseInt(n[2]),Be=parseInt(n[3]),ue=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),ve.toColor(Ee,Re,Be,ue);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=r,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Ee,Re,Be,ue]=t.getImageData(0,0,1,1).data,ue!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:ve.toRgba(Ee,Re,Be,ue),css:r}}e.toColor=s})(he||(he={}));var Ne;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,r,n){let o=s/255,a=r/255,h=n/255,l=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),c=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),d=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4);return l*.2126+c*.7152+d*.0722}e.relativeLuminance2=i})(Ne||(Ne={}));var qi;(e=>{function t(o,a){if(ue=(a&255)/255,ue===1)return a;let h=a>>24&255,l=a>>16&255,c=a>>8&255,d=o>>24&255,u=o>>16&255,f=o>>8&255;return Ee=d+Math.round((h-d)*ue),Re=u+Math.round((l-u)*ue),Be=f+Math.round((c-f)*ue),ve.toRgba(Ee,Re,Be)}e.blend=t;function i(o,a,h){let l=Ne.relativeLuminance(o>>8),c=Ne.relativeLuminance(a>>8);if(_t(l,c)<h){if(c<l){let f=s(o,a,h),_=_t(l,Ne.relativeLuminance(f>>8));if(_<h){let p=r(o,a,h),g=_t(l,Ne.relativeLuminance(p>>8));return _>g?f:p}return f}let d=r(o,a,h),u=_t(l,Ne.relativeLuminance(d>>8));if(u<h){let f=s(o,a,h),_=_t(l,Ne.relativeLuminance(f>>8));return u>_?d:f}return d}}e.ensureContrastRatio=i;function s(o,a,h){let l=o>>24&255,c=o>>16&255,d=o>>8&255,u=a>>24&255,f=a>>16&255,_=a>>8&255,p=_t(Ne.relativeLuminance2(u,f,_),Ne.relativeLuminance2(l,c,d));for(;p<h&&(u>0||f>0||_>0);)u-=Math.max(0,Math.ceil(u*.1)),f-=Math.max(0,Math.ceil(f*.1)),_-=Math.max(0,Math.ceil(_*.1)),p=_t(Ne.relativeLuminance2(u,f,_),Ne.relativeLuminance2(l,c,d));return(u<<24|f<<16|_<<8|255)>>>0}e.reduceLuminance=s;function r(o,a,h){let l=o>>24&255,c=o>>16&255,d=o>>8&255,u=a>>24&255,f=a>>16&255,_=a>>8&255,p=_t(Ne.relativeLuminance2(u,f,_),Ne.relativeLuminance2(l,c,d));for(;p<h&&(u<255||f<255||_<255);)u=Math.min(255,u+Math.ceil((255-u)*.1)),f=Math.min(255,f+Math.ceil((255-f)*.1)),_=Math.min(255,_+Math.ceil((255-_)*.1)),p=_t(Ne.relativeLuminance2(u,f,_),Ne.relativeLuminance2(l,c,d));return(u<<24|f<<16|_<<8|255)>>>0}e.increaseLuminance=r;function n(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}e.toChannels=n})(qi||(qi={}));function Tt(e){let t=e.toString(16);return t.length<2?"0"+t:t}function _t(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var oc=class extends xi{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}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()]}},rs=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Ze}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 i=[],s=t.translateToString(!0),r=0,n=0,o=0,a=t.getFg(0),h=t.getBg(0);for(let l=0;l<t.getTrimmedLength();l++)if(t.loadCell(l,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==a||this._workCell.bg!==h){if(l-r>1){let c=this._getJoinedRanges(s,o,n,t,r);for(let d=0;d<c.length;d++)i.push(c[d])}r=l,o=n,a=this._workCell.fg,h=this._workCell.bg}n+=this._workCell.getChars().length||kt.length}if(this._bufferService.cols-r>1){let l=this._getJoinedRanges(s,o,n,t,r);for(let c=0;c<l.length;c++)i.push(l[c])}return i}_getJoinedRanges(e,t,i,s,r){let n=e.substring(t,i),o=[];try{o=this._characterJoiners[0].handler(n)}catch(a){console.error(a)}for(let a=1;a<this._characterJoiners.length;a++)try{let h=this._characterJoiners[a].handler(n);for(let l=0;l<h.length;l++)rs._mergeRanges(o,h[l])}catch(h){console.error(h)}return this._stringRangesToCellRanges(o,s,r),o}_stringRangesToCellRanges(e,t,i){let s=0,r=!1,n=0,o=e[s];if(o){for(let a=i;a<this._bufferService.cols;a++){let h=t.getWidth(a),l=t.getString(a).length||kt.length;if(h!==0){if(!r&&o[0]<=n&&(o[0]=a,r=!0),o[1]<=n){if(o[1]=a,o=e[++s],!o)break;o[0]<=n?(o[0]=a,r=!0):r=!1}n+=l}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let s=0;s<e.length;s++){let r=e[s];if(i){if(t[1]<=r[0])return e[s-1][1]=t[1],e;if(t[1]<=r[1])return e[s-1][1]=Math.max(t[1],r[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=r[0])return e.splice(s,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),i=!0);continue}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};rs=_e([$(0,Oe)],rs);function ac(e){return 57508<=e&&e<=57558}function lc(e){return 9472<=e&&e<=9631}function hc(e){return ac(e)||lc(e)}function cc(){return{css:{canvas:Ni(),cell:Ni()},device:{canvas:Ni(),cell:Ni(),char:{width:0,height:0,left:0,top:0}}}}function Ni(){return{width:0,height:0}}var or=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new Ze,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,n,o,a,h,l,c){let d=[],u=this._characterJoinerService.getJoinedCharacters(t),f=this._themeService.colors,_=e.getNoBgTrimmedLength();i&&_<n+1&&(_=n+1);let p,g=0,x="",z=0,O=0,M=0,N=0,K=!1,ie=0,ae=!1,J=0,Te=0,X=[],P=l!==-1&&c!==-1;for(let S=0;S<_;S++){e.loadCell(S,this._workCell);let L=this._workCell.getWidth();if(L===0)continue;let B=!1,T=S>=Te,H=S,R=this._workCell;if(u.length>0&&S===u[0][0]&&T){let I=u.shift(),q=this._isCellInSelection(I[0],t);for(z=I[0]+1;z<I[1];z++)T&&(T=q===this._isCellInSelection(z,t));T&&(T=!i||n<I[0]||n>=I[1]),T?(B=!0,R=new oc(this._workCell,e.translateToString(!0,I[0],I[1]),I[1]-I[0]),H=I[1]-1,L=R.getWidth()):Te=I[1]}let Y=this._isCellInSelection(S,t),se=i&&S===n,xe=P&&S>=l&&S<=c,Ve=!1;this._decorationService.forEachDecorationAtCell(S,t,void 0,I=>{Ve=!0});let Pe=R.getChars()||kt;if(Pe===" "&&(R.isUnderline()||R.isOverline())&&(Pe=" "),J=L*a-h.get(Pe,R.isBold(),R.isItalic()),!p)p=this._document.createElement("span");else if(g&&(Y&&ae||!Y&&!ae&&R.bg===O)&&(Y&&ae&&f.selectionForeground||R.fg===M)&&R.extended.ext===N&&xe===K&&J===ie&&!se&&!B&&!Ve&&T){R.isInvisible()?x+=kt:x+=Pe,g++;continue}else g&&(p.textContent=x),p=this._document.createElement("span"),g=0,x="";if(O=R.bg,M=R.fg,N=R.extended.ext,K=xe,ie=J,ae=Y,B&&n>=S&&n<=H&&(n=S),!this._coreService.isCursorHidden&&se&&this._coreService.isCursorInitialized){if(X.push("xterm-cursor"),this._coreBrowserService.isFocused)o&&X.push("xterm-cursor-blink"),X.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":X.push("xterm-cursor-outline");break;case"block":X.push("xterm-cursor-block");break;case"bar":X.push("xterm-cursor-bar");break;case"underline":X.push("xterm-cursor-underline");break}}if(R.isBold()&&X.push("xterm-bold"),R.isItalic()&&X.push("xterm-italic"),R.isDim()&&X.push("xterm-dim"),R.isInvisible()?x=kt:x=R.getChars()||kt,R.isUnderline()&&(X.push(`xterm-underline-${R.extended.underlineStyle}`),x===" "&&(x=" "),!R.isUnderlineColorDefault()))if(R.isUnderlineColorRGB())p.style.textDecorationColor=`rgb(${xi.toColorRGB(R.getUnderlineColor()).join(",")})`;else{let I=R.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&R.isBold()&&I<8&&(I+=8),p.style.textDecorationColor=f.ansi[I].css}R.isOverline()&&(X.push("xterm-overline"),x===" "&&(x=" ")),R.isStrikethrough()&&X.push("xterm-strikethrough"),xe&&(p.style.textDecoration="underline");let re=R.getFgColor(),Ge=R.getFgColorMode(),He=R.getBgColor(),ut=R.getBgColorMode(),ii=!!R.isInverse();if(ii){let I=re;re=He,He=I;let q=Ge;Ge=ut,ut=q}let nt,k,A=!1;this._decorationService.forEachDecorationAtCell(S,t,void 0,I=>{I.options.layer!=="top"&&A||(I.backgroundColorRGB&&(ut=50331648,He=I.backgroundColorRGB.rgba>>8&16777215,nt=I.backgroundColorRGB),I.foregroundColorRGB&&(Ge=50331648,re=I.foregroundColorRGB.rgba>>8&16777215,k=I.foregroundColorRGB),A=I.options.layer==="top")}),!A&&Y&&(nt=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,He=nt.rgba>>8&16777215,ut=50331648,A=!0,f.selectionForeground&&(Ge=50331648,re=f.selectionForeground.rgba>>8&16777215,k=f.selectionForeground)),A&&X.push("xterm-decoration-top");let F;switch(ut){case 16777216:case 33554432:F=f.ansi[He],X.push(`xterm-bg-${He}`);break;case 50331648:F=ve.toColor(He>>16,He>>8&255,He&255),this._addStyle(p,`background-color:#${pn((He>>>0).toString(16),"0",6)}`);break;case 0:default:ii?(F=f.foreground,X.push("xterm-bg-257")):F=f.background}switch(nt||R.isDim()&&(nt=ne.multiplyOpacity(F,.5)),Ge){case 16777216:case 33554432:R.isBold()&&re<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(re+=8),this._applyMinimumContrast(p,F,f.ansi[re],R,nt,void 0)||X.push(`xterm-fg-${re}`);break;case 50331648:let I=ve.toColor(re>>16&255,re>>8&255,re&255);this._applyMinimumContrast(p,F,I,R,nt,k)||this._addStyle(p,`color:#${pn(re.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(p,F,f.foreground,R,nt,k)||ii&&X.push("xterm-fg-257")}X.length&&(p.className=X.join(" "),X.length=0),!se&&!B&&!Ve&&T?g++:p.textContent=x,J!==this.defaultSpacing&&(p.style.letterSpacing=`${J}px`),d.push(p),S=H}return p&&g&&(p.textContent=x),d}_applyMinimumContrast(e,t,i,s,r,n){if(this._optionsService.rawOptions.minimumContrastRatio===1||hc(s.getCode()))return!1;let o=this._getContrastCache(s),a;if(!r&&!n&&(a=o.getColor(t.rgba,i.rgba)),a===void 0){let h=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=ne.ensureContrastRatio(r||t,n||i,h),o.setColor((r||t).rgba,(n||i).rgba,a??null)}return a?(this._addStyle(e,`color:${a.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e<s[0]&&t<=s[1]:e<i[0]&&t>=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t<s[1]||i[1]===s[1]&&t===i[1]&&e>=i[0]&&e<s[0]||i[1]<s[1]&&t===s[1]&&e<s[0]||i[1]<s[1]&&t===i[1]&&e>=i[0]}};or=_e([$(1,qo),$(2,Fe),$(3,pt),$(4,Ft),$(5,ki),$(6,ei)],or);function pn(e,t,i){for(;e.length<i;)e=t+e;return e}var dc=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.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 i=e.createElement("span");i.classList.add("xterm-char-measure-element");let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.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(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&e.length===1&&(s=e.charCodeAt(0))<256){if(this._flat[s]!==-9999)return this._flat[s];let o=this._measure(e,0);return o>0&&(this._flat[s]=o),o}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(n===void 0){let o=0;t&&(o|=1),i&&(o|=2),n=this._measure(e,o),n>0&&this._holey.set(r,n)}return n}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},uc=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,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,a=Math.max(n,0),h=Math.min(o,e.rows-1);if(a>=e.rows||h<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=h,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol):!1}};function _c(){return new uc}var ys="xterm-dom-renderer-owner-",Ye="xterm-rows",Ii="xterm-fg-",mn="xterm-bg-",ni="xterm-focus",Oi="xterm-selection",fc=1,ar=class extends G{constructor(e,t,i,s,r,n,o,a,h,l,c,d,u,f){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=n,this._linkifier2=o,this._charSizeService=h,this._optionsService=l,this._bufferService=c,this._coreService=d,this._coreBrowserService=u,this._themeService=f,this._terminalClass=fc++,this._rowElements=[],this._selectionRenderModel=_c(),this.onRequestRedraw=this._register(new C).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Ye),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(Oi),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=cc(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(_=>this._injectCss(_))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(or,document),this._element.classList.add(ys+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(_=>this._handleLinkHover(_))),this._register(this._linkifier2.onHideLinkUnderline(_=>this._handleLinkLeave(_))),this._register(oe(()=>{this._element.classList.remove(ys+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new dc(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 e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),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/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),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 i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Ye} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,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(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Ye} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Ye} .xterm-dim { color: ${ne.multiplyOpacity(e.foreground,.5).css};}`,t+=`${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 i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% {  border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% {  box-shadow: none; }}`,t+=`@keyframes ${r} { 0% {  background-color: ${e.cursor.css};  color: ${e.cursorAccent.css}; } 50% {  background-color: inherit;  color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Ye}.${ni} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Ye}.${ni} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${Ye}.${ni} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Oi} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Oi} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Oi} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${Ii}${n} { color: ${o.css}; }${this._terminalSelector} .${Ii}${n}.xterm-dim { color: ${ne.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${mn}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${Ii}257 { color: ${ne.opaque(e.background).css}; }${this._terminalSelector} .${Ii}257.xterm-dim { color: ${ne.multiplyOpacity(ne.opaque(e.background),.5).css}; }${this._terminalSelector} .${mn}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),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(ni),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ni),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(i){let h=e[0]>t[0];a.appendChild(this._createSelectionElement(n,h?t[0]:e[0],h?e[0]:t[0],o-n+1))}else{let h=s===n?e[0]:0,l=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,h,l));let c=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,c)),n!==o){let d=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,d))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){let r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=`${s*this.dimensions.css.cell.height}px`,r.style.top=`${e*this.dimensions.css.cell.height}px`,r.style.left=`${n}px`,r.style.width=`${o}px`,r}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 e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=t;h++){let l=h+i.ydisp,c=this._rowElements[h],d=i.lines.get(l);if(!c||!d)break;c.replaceChildren(...this._rowFactory.createRow(d,l,l===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${ys}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);let o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);let a=this._bufferService.buffer,h=a.ybase+a.y,l=Math.min(a.x,r-1),c=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let f=i;f<=s;++f){let _=f+a.ydisp,p=this._rowElements[f],g=a.lines.get(_);if(!p||!g)break;p.replaceChildren(...this._rowFactory.createRow(g,_,_===h,d,u,l,c,this.dimensions.css.cell.width,this._widthCache,n?f===i?e:0:-1,n?(f===s?t:r)-1:-1))}}};ar=_e([$(7,Rr),$(8,cs),$(9,Fe),$(10,Oe),$(11,Ft),$(12,pt),$(13,ei)],ar);var lr=class extends G{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new C),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new mc(this._optionsService))}catch{this._measureStrategy=this._register(new pc(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};lr=_e([$(2,Fe)],lr);var da=class extends G{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)}},pc=class extends da{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,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}},mc=class extends da{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},gc=class extends G{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new vc(this._window)),this._onDprChange=this._register(new C),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new C),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(De.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(j(this._textarea,"focus",()=>this._isFocused=!0)),this._register(j(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,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}},vc=class extends G{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Zt),this._onDprChange=this._register(new C),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(oe(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=j(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.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)}},Sc=class extends G{constructor(){super(),this.linkProviders=[],this._register(oe(()=>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 Pr(e,t,i){let s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}function yc(e,t,i,s,r,n,o,a,h){if(!n)return;let l=Pr(e,t,i);if(l)return l[0]=Math.ceil((l[0]+(h?o/2:0))/o),l[1]=Math.ceil(l[1]/a),l[0]=Math.min(Math.max(l[0],1),s+(h?1:0)),l[1]=Math.min(Math.max(l[1],1),r),l}var hr=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return yc(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let i=Pr(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};hr=_e([$(0,mt),$(1,cs)],hr);var wc=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!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 e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},ua={};Dl(ua,{getSafariVersion:()=>Cc,isChromeOS:()=>ma,isFirefox:()=>_a,isIpad:()=>xc,isIphone:()=>kc,isLegacyEdge:()=>bc,isLinux:()=>Nr,isMac:()=>ns,isNode:()=>ds,isSafari:()=>fa,isWindows:()=>pa});var ds=typeof process<"u"&&"title"in process,Ei=ds?"node":navigator.userAgent,Ri=ds?"node":navigator.platform,_a=Ei.includes("Firefox"),bc=Ei.includes("Edge"),fa=/^((?!chrome|android).)*safari/i.test(Ei);function Cc(){if(!fa)return 0;let e=Ei.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var ns=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Ri),xc=Ri==="iPad",kc=Ri==="iPhone",pa=["Windows","Win16","Win32","WinCE"].includes(Ri),Nr=Ri.indexOf("Linux")>=0,ma=/\bCrOS\b/.test(Ei),ga=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,i=0,s=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),r=e.timeRemaining(),i*1.5>r){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=r}this.clear()}},Ec=class extends ga{_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())}}},Rc=class extends ga{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},os=!ds&&"requestIdleCallback"in window?Rc:Ec,Bc=class{constructor(){this._queue=new os}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},cr=class extends G{constructor(e,t,i,s,r,n,o,a,h){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=r,this._coreBrowserService=a,this._renderer=this._register(new Zt),this._pausedResizeTask=new Bc,this._observerDisposable=this._register(new Zt),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 C),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new C),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new C),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new C),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new wc((l,c)=>this._renderRows(l,c),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Mc(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(oe(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>{var l;return(l=this._renderer.value)==null?void 0:l.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(h.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(l=>this._registerIntersectionObserver(l,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=oe(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.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(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,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(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};cr=_e([$(2,Fe),$(3,cs),$(4,Ft),$(5,ki),$(6,Oe),$(7,pt),$(8,ei)],cr);var Mc=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,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 Lc(e,t,i,s){let r=i.buffer.x,n=i.buffer.y;if(!i.buffer.hasScrollback)return $c(r,n,e,t,i,s)+us(n,t,i,s)+Ac(r,n,e,t,i,s);let o;if(n===t)return o=r>e?"D":"C",wi(Math.abs(r-e),yi(o,s));o=n>t?"D":"C";let a=Math.abs(n-t),h=Tc(n>t?e:r,i)+(a-1)*i.cols+1+Dc(n>t?r:e);return wi(h,yi(o,s))}function Dc(e,t){return e-1}function Tc(e,t){return t.cols-e}function $c(e,t,i,s,r,n){return us(t,s,r,n).length===0?"":wi(Sa(e,t,e,t-Ot(t,r),!1,r).length,yi("D",n))}function us(e,t,i,s){let r=e-Ot(e,i),n=t-Ot(t,i),o=Math.abs(r-n)-Pc(e,t,i);return wi(o,yi(va(e,t),s))}function Ac(e,t,i,s,r,n){let o;us(t,s,r,n).length>0?o=s-Ot(s,r):o=t;let a=s,h=Nc(e,t,i,s,r,n);return wi(Sa(e,o,i,a,h==="C",r).length,yi(h,n))}function Pc(e,t,i){var o;let s=0,r=e-Ot(e,i),n=t-Ot(t,i);for(let a=0;a<Math.abs(r-n);a++){let h=va(e,t)==="A"?-1:1;(o=i.buffer.lines.get(r+h*a))!=null&&o.isWrapped&&s++}return s}function Ot(e,t){let i=0,s=t.buffer.lines.get(e),r=s==null?void 0:s.isWrapped;for(;r&&e>=0&&e<t.rows;)i++,s=t.buffer.lines.get(--e),r=s==null?void 0:s.isWrapped;return i}function Nc(e,t,i,s,r,n){let o;return us(i,s,r,n).length>0?o=s-Ot(s,r):o=t,e<i&&o<=s||e>=i&&o<s?"C":"D"}function va(e,t){return e>t?"A":"B"}function Sa(e,t,i,s,r,n){let o=e,a=t,h="";for(;(o!==i||a!==s)&&a>=0&&a<n.buffer.lines.length;)o+=r?1:-1,r&&o>n.cols-1?(h+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(h+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return h+n.buffer.translateBufferLineToString(a,!1,e,o)}function yi(e,t){let i=t?"O":"[";return v.ESC+i+e}function wi(e,t){e=Math.floor(e);let i="";for(let s=0;s<e;s++)i+=t;return i}var Ic=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 gn(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 ws=50,Oc=15,Fc=50,Hc=500,Wc=" ",zc=new RegExp(Wc,"g"),dr=class extends G{constructor(e,t,i,s,r,n,o,a,h){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=a,this._coreBrowserService=h,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Ze,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new C),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new C),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new C),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new C),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=l=>this._handleMouseMove(l),this._mouseUpListener=l=>this._handleMouseUp(l),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(l=>this._handleTrim(l)),this._register(this._bufferService.buffers.onBufferActivate(l=>this._handleBufferActivate(l))),this.enable(),this._model=new Ic(this._bufferService),this._activeSelectionMode=0,this._register(oe(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(l=>{l.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 e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let a=i.translateBufferLineToString(o,!0,r,n);s.push(a)}}else{let r=e[1]===t[1]?t[0]:void 0;s.push(i.translateBufferLineToString(e[1],!0,e[0],r));for(let n=e[1]+1;n<=t[1]-1;n++){let o=i.lines.get(n),a=i.translateBufferLineToString(n,!0);o!=null&&o.isWrapped?s[s.length-1]+=a:s.push(a)}if(e[1]!==t[1]){let n=i.lines.get(t[1]),o=i.translateBufferLineToString(t[1],!0,0,t[0]);n&&n.isWrapped?s[s.length-1]+=o:s.push(o)}}return s.map(r=>r.replace(zc," ")).join(pa?`\r
`:`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Nr&&e&&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(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var r,n;let i=(n=(r=this._linkifier.currentLink)==null?void 0:r.link)==null?void 0:n.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=gn(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Pr(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-ws),ws),t/=ws,t/Math.abs(t)+Math.round(t*(Oc-1)))}shouldForceSelection(e){return ns?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),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(),Fc)}_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(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(ns&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!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(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let s=i.lines.get(this._model.selectionEnd[1]);s&&s.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[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 e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Hc&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&i[0]!==void 0&&i[1]!==void 0){let s=Lc(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(s,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!i){this._oldHasSelection&&this._fireOnSelectionChange(e,t,i);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let r=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;let o=r.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(n,e[0]),h=a,l=e[0]-a,c=0,d=0,u=0,f=0;if(o.charAt(a)===" "){for(;a>0&&o.charAt(a-1)===" ";)a--;for(;h<o.length&&o.charAt(h+1)===" ";)h++}else{let g=e[0],x=e[0];n.getWidth(g)===0&&(c++,g--),n.getWidth(x)===2&&(d++,x++);let z=n.getString(x).length;for(z>1&&(f+=z-1,h+=z-1);g>0&&a>0&&!this._isCharWordSeparator(n.loadCell(g-1,this._workCell));){n.loadCell(g-1,this._workCell);let O=this._workCell.getChars().length;this._workCell.getWidth()===0?(c++,g--):O>1&&(u+=O-1,a-=O-1),a--,g--}for(;x<n.length&&h+1<o.length&&!this._isCharWordSeparator(n.loadCell(x+1,this._workCell));){n.loadCell(x+1,this._workCell);let O=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,x++):O>1&&(f+=O-1,h+=O-1),h++,x++}}h++;let _=a+l-c+u,p=Math.min(this._bufferService.cols,h-a+c+d-u-f);if(!(!t&&o.slice(a,h).trim()==="")){if(i&&_===0&&n.getCodePoint(0)!==32){let g=r.lines.get(e[1]-1);if(g&&n.isWrapped&&g.getCodePoint(this._bufferService.cols-1)!==32){let x=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(x){let z=this._bufferService.cols-x.start;_-=z,p+=z}}}if(s&&_+p===this._bufferService.cols&&n.getCodePoint(this._bufferService.cols-1)!==32){let g=r.lines.get(e[1]+1);if(g!=null&&g.isWrapped&&g.getCodePoint(0)!==32){let x=this._getWordAt([0,e[1]+1],!1,!1,!0);x&&(p+=x.length)}}return{start:_,length:p}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=gn(i,this._bufferService.cols)}};dr=_e([$(3,Oe),$(4,Ft),$(5,Br),$(6,Fe),$(7,mt),$(8,pt)],dr);var vn=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Sn=class{constructor(){this._color=new vn,this._css=new vn}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},we=Object.freeze((()=>{let e=[he.toColor("#2e3436"),he.toColor("#cc0000"),he.toColor("#4e9a06"),he.toColor("#c4a000"),he.toColor("#3465a4"),he.toColor("#75507b"),he.toColor("#06989a"),he.toColor("#d3d7cf"),he.toColor("#555753"),he.toColor("#ef2929"),he.toColor("#8ae234"),he.toColor("#fce94f"),he.toColor("#729fcf"),he.toColor("#ad7fa8"),he.toColor("#34e2e2"),he.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:ve.toCss(s,r,n),rgba:ve.toRgba(s,r,n)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:ve.toCss(s,s,s),rgba:ve.toRgba(s,s,s)})}return e})()),$t=he.toColor("#ffffff"),_i=he.toColor("#000000"),yn=he.toColor("#ffffff"),wn=_i,oi={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Uc=$t,ur=class extends G{constructor(e){super(),this._optionsService=e,this._contrastCache=new Sn,this._halfContrastCache=new Sn,this._onChangeColors=this._register(new C),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:$t,background:_i,cursor:yn,cursorAccent:wn,selectionForeground:void 0,selectionBackgroundTransparent:oi,selectionBackgroundOpaque:ne.blend(_i,oi),selectionInactiveBackgroundTransparent:oi,selectionInactiveBackgroundOpaque:ne.blend(_i,oi),scrollbarSliderBackground:ne.opacity($t,.2),scrollbarSliderHoverBackground:ne.opacity($t,.4),scrollbarSliderActiveBackground:ne.opacity($t,.5),overviewRulerBorder:$t,ansi:we.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(e={}){let t=this._colors;if(t.foreground=Z(e.foreground,$t),t.background=Z(e.background,_i),t.cursor=ne.blend(t.background,Z(e.cursor,yn)),t.cursorAccent=ne.blend(t.background,Z(e.cursorAccent,wn)),t.selectionBackgroundTransparent=Z(e.selectionBackground,oi),t.selectionBackgroundOpaque=ne.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Z(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ne.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Z(e.selectionForeground,fn):void 0,t.selectionForeground===fn&&(t.selectionForeground=void 0),ne.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ne.opacity(t.selectionBackgroundTransparent,.3)),ne.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ne.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Z(e.scrollbarSliderBackground,ne.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Z(e.scrollbarSliderHoverBackground,ne.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Z(e.scrollbarSliderActiveBackground,ne.opacity(t.foreground,.5)),t.overviewRulerBorder=Z(e.overviewRulerBorder,Uc),t.ansi=we.slice(),t.ansi[0]=Z(e.black,we[0]),t.ansi[1]=Z(e.red,we[1]),t.ansi[2]=Z(e.green,we[2]),t.ansi[3]=Z(e.yellow,we[3]),t.ansi[4]=Z(e.blue,we[4]),t.ansi[5]=Z(e.magenta,we[5]),t.ansi[6]=Z(e.cyan,we[6]),t.ansi[7]=Z(e.white,we[7]),t.ansi[8]=Z(e.brightBlack,we[8]),t.ansi[9]=Z(e.brightRed,we[9]),t.ansi[10]=Z(e.brightGreen,we[10]),t.ansi[11]=Z(e.brightYellow,we[11]),t.ansi[12]=Z(e.brightBlue,we[12]),t.ansi[13]=Z(e.brightMagenta,we[13]),t.ansi[14]=Z(e.brightCyan,we[14]),t.ansi[15]=Z(e.brightWhite,we[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s<i;s++)t.ansi[s+16]=Z(e.extendedAnsi[s],we[s+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t];return}switch(e){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[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(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()}}};ur=_e([$(0,Fe)],ur);function Z(e,t){if(e!==void 0)try{return he.toColor(e)}catch{}return t}var jc=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},Kc=class{constructor(){this._services=new jc,this._services.set(Rr,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=Ol(e).sort((n,o)=>n.index-o.index),s=[];for(let n of i){let o=this._services.get(n.id);if(!o)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${n.id._id}.`);s.push(o)}let r=i.length>0?i[0].index:t.length;if(t.length!==r)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${r+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},qc={trace:0,debug:1,info:2,warn:3,error:4,off:5},Vc="xterm.js: ",_r=class extends G{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=qc[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,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":Vc)+t,...i)}trace(e,...t){var i;this._logLevel<=0&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.trace.bind(this._optionsService.options.logger))??console.log,e,t)}debug(e,...t){var i;this._logLevel<=1&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.debug.bind(this._optionsService.options.logger))??console.log,e,t)}info(e,...t){var i;this._logLevel<=2&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.info.bind(this._optionsService.options.logger))??console.info,e,t)}warn(e,...t){var i;this._logLevel<=3&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.warn.bind(this._optionsService.options.logger))??console.warn,e,t)}error(e,...t){var i;this._logLevel<=4&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.error.bind(this._optionsService.options.logger))??console.error,e,t)}};_r=_e([$(0,Fe)],_r);var bn=class extends G{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new C),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new C),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new C),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,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(e,t,...i){if(t){for(let s=e;s<this._length-t;s++)this._array[this._getCyclicIndex(s)]=this._array[this._getCyclicIndex(s+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let s=this._length-1;s>=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;s<i.length;s++)this._array[this._getCyclicIndex(e+s)]=i[s];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+i,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},V=3,me=Object.freeze(new xi),Fi=0,bs=2,fi=class ya{constructor(t,i,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*V);let r=i||Ze.fromCharData([0,Fo,1,0]);for(let n=0;n<t;++n)this.setCell(n,r);this.length=t}get(t){let i=this._data[t*V+0],s=i&2097151;return[this._data[t*V+1],i&2097152?this._combined[t]:s?Ct(s):"",i>>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*V+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*V+0]=t|2097152|i[2]<<22):this._data[t*V+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*V+0]>>22}hasWidth(t){return this._data[t*V+0]&12582912}getFg(t){return this._data[t*V+1]}getBg(t){return this._data[t*V+2]}hasContent(t){return this._data[t*V+0]&4194303}getCodePoint(t){let i=this._data[t*V+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*V+0]&2097152}getString(t){let i=this._data[t*V+0];return i&2097152?this._combined[t]:i&2097151?Ct(i&2097151):""}isProtected(t){return this._data[t*V+2]&536870912}loadCell(t,i){return Fi=t*V,i.content=this._data[Fi+0],i.fg=this._data[Fi+1],i.bg=this._data[Fi+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*V+0]=i.content,this._data[t*V+1]=i.fg,this._data[t*V+2]=i.bg}setCellFromCodepoint(t,i,s,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*V+0]=i|s<<22,this._data[t*V+1]=r.fg,this._data[t*V+2]=r.bg}addCodepointToCell(t,i,s){let r=this._data[t*V+0];r&2097152?this._combined[t]+=Ct(i):r&2097151?(this._combined[t]=Ct(r&2097151)+Ct(i),r&=-2097152,r|=2097152):r=i|1<<22,s&&(r&=-12582913,r|=s<<22),this._data[t*V+0]=r}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length-t){let r=new Ze;for(let n=this.length-t-i-1;n>=0;--n)this.setCell(t+i+n,this.loadCell(t+n,r));for(let n=0;n<i;++n)this.setCell(t+n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,s);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(t,i,s){if(t%=this.length,i<this.length-t){let r=new Ze;for(let n=0;n<this.length-t-i;++n)this.setCell(t+n,this.loadCell(t+i+n,r));for(let n=this.length-i;n<this.length;++n)this.setCell(n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,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,i,s,r=!1){if(r){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length&&this.getWidth(i-1)===2&&!this.isProtected(i)&&this.setCellFromCodepoint(i,0,1,s);t<i&&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),i<this.length&&this.getWidth(i-1)===2&&this.setCellFromCodepoint(i,0,1,s);t<i&&t<this.length;)this.setCell(t++,s)}resize(t,i){if(t===this.length)return this._data.length*4*bs<this._data.buffer.byteLength;let s=t*V;if(t>this.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let r=new Uint32Array(s);r.set(this._data),this._data=r}for(let r=this.length;r<t;++r)this.setCell(r,i)}else{this._data=this._data.subarray(0,s);let r=Object.keys(this._combined);for(let o=0;o<r.length;o++){let a=parseInt(r[o],10);a>=t&&delete this._combined[a]}let n=Object.keys(this._extendedAttrs);for(let o=0;o<n.length;o++){let a=parseInt(n[o],10);a>=t&&delete this._extendedAttrs[a]}}return this.length=t,s*4*bs<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*bs<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,i=!1){if(i){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 i in t._combined)this._combined[i]=t._combined[i];this._extendedAttrs={};for(let i in t._extendedAttrs)this._extendedAttrs[i]=t._extendedAttrs[i];this.isWrapped=t.isWrapped}clone(){let t=new ya(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let i in this._combined)t._combined[i]=this._combined[i];for(let i in this._extendedAttrs)t._extendedAttrs[i]=this._extendedAttrs[i];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*V+0]&4194303)return t+(this._data[t*V+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*V+0]&4194303||this._data[t*V+2]&50331648)return t+(this._data[t*V+0]>>22);return 0}copyCellsFrom(t,i,s,r,n){let o=t._data;if(n)for(let h=r-1;h>=0;h--){for(let l=0;l<V;l++)this._data[(s+h)*V+l]=o[(i+h)*V+l];o[(i+h)*V+2]&268435456&&(this._extendedAttrs[s+h]=t._extendedAttrs[i+h])}else for(let h=0;h<r;h++){for(let l=0;l<V;l++)this._data[(s+h)*V+l]=o[(i+h)*V+l];o[(i+h)*V+2]&268435456&&(this._extendedAttrs[s+h]=t._extendedAttrs[i+h])}let a=Object.keys(t._combined);for(let h=0;h<a.length;h++){let l=parseInt(a[h],10);l>=i&&(this._combined[l-i+s]=t._combined[l])}}translateToString(t,i,s,r){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),r&&(r.length=0);let n="";for(;i<s;){let o=this._data[i*V+0],a=o&2097151,h=o&2097152?this._combined[i]:a?Ct(a):kt;if(n+=h,r)for(let l=0;l<h.length;++l)r.push(i);i+=o>>22||1}return r&&r.push(i),n}};function Gc(e,t,i,s,r,n){let o=[];for(let a=0;a<e.length-1;a++){let h=a,l=e.get(++h);if(!l.isWrapped)continue;let c=[e.get(a)];for(;h<e.length&&l.isWrapped;)c.push(l),l=e.get(++h);if(!n&&s>=a&&s<h){a+=c.length-1;continue}let d=0,u=bi(c,d,t),f=1,_=0;for(;f<c.length;){let g=bi(c,f,t),x=g-_,z=i-u,O=Math.min(x,z);c[d].copyCellsFrom(c[f],_,u,O,!1),u+=O,u===i&&(d++,u=0),_+=O,_===g&&(f++,_=0),u===0&&d!==0&&c[d-1].getWidth(i-1)===2&&(c[d].copyCellsFrom(c[d-1],i-1,u++,1,!1),c[d-1].setCell(i-1,r))}c[d].replaceCells(u,i,r);let p=0;for(let g=c.length-1;g>0&&(g>d||c[g].getTrimmedLength()===0);g--)p++;p>0&&(o.push(a+c.length-p),o.push(p)),a+=c.length-1}return o}function Yc(e,t){let i=[],s=0,r=t[s],n=0;for(let o=0;o<e.length;o++)if(r===o){let a=t[++s];e.onDeleteEmitter.fire({index:o-n,amount:a}),o+=a-1,n+=a,r=t[++s]}else i.push(o);return{layout:i,countRemoved:n}}function Xc(e,t){let i=[];for(let s=0;s<t.length;s++)i.push(e.get(t[s]));for(let s=0;s<i.length;s++)e.set(s,i[s]);e.length=t.length}function Jc(e,t,i){let s=[],r=e.map((h,l)=>bi(e,l,t)).reduce((h,l)=>h+l),n=0,o=0,a=0;for(;a<r;){if(r-a<i){s.push(r-a);break}n+=i;let h=bi(e,o,t);n>h&&(n-=h,o++);let l=e[o].getWidth(n-1)===2;l&&n--;let c=l?i-1:i;s.push(c),a+=c}return s}function bi(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,r=e[t+1].getWidth(0)===2;return s&&r?i-1:i}var wa=class ba{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=ba._nextId++,this._onDispose=this.register(new C),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),It(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};wa._nextId=1;var Zc=wa,Ce={},At=Ce.B;Ce[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Ce.A={"#":"£"};Ce.B=void 0;Ce[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Ce.C=Ce[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ce.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Ce.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Ce.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Ce.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Ce.E=Ce[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Ce.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Ce.H=Ce[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ce["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Cn=4294967295,xn=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=me.clone(),this.savedCharset=At,this.markers=[],this._nullCell=Ze.fromCharData([0,Fo,1,0]),this._whitespaceCell=Ze.fromCharData([0,kt,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new os,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new bn(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 is),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 is),this._whitespaceCell}getBlankLine(e,t){return new fi(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>Cn?Cn:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=me);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 bn(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(me),s=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let o=0;o<this.lines.length;o++)s+=+this.lines.get(o).resize(e,i);let n=0;if(this._rows<t)for(let o=this._rows;o<t;o++)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 fi(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new fi(e,i)));else for(let o=this._rows;o>t;o--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){let o=this.lines.length-r;o>0&&(this.lines.trimStart(o),this.ybase=Math.max(this.ybase-o,0),this.ydisp=Math.max(this.ydisp-o,0),this.savedY=Math.max(this.savedY-o,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),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 n=0;n<this.lines.length;n++)s+=+this.lines.get(n).resize(e,i);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 i=this._optionsService.rawOptions.reflowCursorLine,s=Gc(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(me),i);if(s.length>0){let r=Yc(this.lines,s);Xc(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(me),r=i;for(;r-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new fi(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(me),r=[],n=0;for(let o=this.lines.length-1;o>=0;o--){let a=this.lines.get(o);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let h=[a];for(;a.isWrapped&&o>0;)a=this.lines.get(--o),h.unshift(a);if(!i){let O=this.ybase+this.y;if(O>=o&&O<o+h.length)continue}let l=h[h.length-1].getTrimmedLength(),c=Jc(h,this._cols,e),d=c.length-h.length,u;this.ybase===0&&this.y!==this.lines.length-1?u=Math.max(0,this.y-this.lines.maxLength+d):u=Math.max(0,this.lines.length-this.lines.maxLength+d);let f=[];for(let O=0;O<d;O++){let M=this.getBlankLine(me,!0);f.push(M)}f.length>0&&(r.push({start:o+h.length+n,newLines:f}),n+=f.length),h.push(...f);let _=c.length-1,p=c[_];p===0&&(_--,p=c[_]);let g=h.length-d-1,x=l;for(;g>=0;){let O=Math.min(x,p);if(h[_]===void 0)break;if(h[_].copyCellsFrom(h[g],x-O,p-O,O,!0),p-=O,p===0&&(_--,p=c[_]),x-=O,x===0){g--;let M=Math.max(g,0);x=bi(h,M,this._cols)}}for(let O=0;O<h.length;O++)c[O]<e&&h[O].setCell(c[O],s);let z=d-u;for(;z-- >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+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(r.length>0){let o=[],a=[];for(let p=0;p<this.lines.length;p++)a.push(this.lines.get(p));let h=this.lines.length,l=h-1,c=0,d=r[c];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let u=0;for(let p=Math.min(this.lines.maxLength-1,h+n-1);p>=0;p--)if(d&&d.start>l+u){for(let g=d.newLines.length-1;g>=0;g--)this.lines.set(p--,d.newLines[g]);p++,o.push({index:l+1,amount:d.newLines.length}),u+=d.newLines.length,d=r[++c]}else this.lines.set(p,a[l--]);let f=0;for(let p=o.length-1;p>=0;p--)o[p].index+=f,this.lines.onInsertEmitter.fire(o[p]),f+=o[p].amount;let _=Math.max(0,h+n-this.lines.maxLength);_>0&&this.lines.onTrimEmitter.fire(_)}}translateBufferLineToString(e,t,i=0,s){let r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}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 Zc(e);return this.markers.push(t),t.register(this.lines.onTrim(i=>{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.line<i.index+i.amount&&t.dispose(),t.line>i.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Qc=class extends G{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new C),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 xn(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new xn(!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(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),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(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Ca=2,xa=1,fr=class extends G{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new C),this.onResize=this._onResize.event,this._onScroll=this._register(new C),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Ca),this.rows=Math.max(e.rawOptions.rows||0,xa),this.buffers=this._register(new Qc(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=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:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(i.scrollTop===0){let o=i.lines.isFull;n===i.lines.length-1?o?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),o?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let o=n-r+1;i.lines.shiftElements(r+1,o-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};fr=_e([$(0,Fe)],fr);var jt={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:ns,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},ed=["normal","bold","100","200","300","400","500","600","700","800","900"],td=class extends G{constructor(e){super(),this._onOptionChange=this._register(new C),this.onOptionChange=this._onOptionChange.event;let t={...jt};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(oe(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in jt))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in jt))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=jt[e]),!id(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=jt[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=ed.includes(t)?t:jt[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function id(e){return e==="block"||e==="underline"||e==="bar"}function pi(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&pi(e[s],t-1);return i}var kn=Object.freeze({insertMode:!1}),En=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),pr=class extends G{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new C),this.onData=this._onData.event,this._onUserInput=this._register(new C),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new C),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new C),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=pi(kn),this.decPrivateModes=pi(En)}reset(){this.modes=pi(kn),this.decPrivateModes=pi(En)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};pr=_e([$(0,Oe),$(1,jo),$(2,Fe)],pr);var Rn={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 Cs(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var xs=String.fromCharCode,Bn={DEFAULT:e=>{let t=[Cs(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${xs(t[0])}${xs(t[1])}${xs(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Cs(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Cs(e,!0)};${e.x};${e.y}${t}`}},mr=class extends G{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new C),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Rn))this.addProtocol(s,Rn[s]);for(let s of Object.keys(Bn))this.addEncoding(s,Bn[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,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=s+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_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,i){if(i){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)}};mr=_e([$(0,Oe),$(1,Ft),$(2,Fe)],mr);var ks=[[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]],sd=[[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]],be;function rd(e,t){let i=0,s=t.length-1,r;if(e<t[0][0]||e>t[s][1])return!1;for(;s>=i;)if(r=i+s>>1,e>t[r][1])i=r+1;else if(e<t[r][0])s=r-1;else return!0;return!1}var nd=class{constructor(){if(this.version="6",!be){be=new Uint8Array(65536),be.fill(1),be[0]=0,be.fill(0,1,32),be.fill(0,127,160),be.fill(2,4352,4448),be[9001]=2,be[9002]=2,be.fill(2,11904,42192),be[12351]=1,be.fill(2,44032,55204),be.fill(2,63744,64256),be.fill(2,65040,65050),be.fill(2,65072,65136),be.fill(2,65280,65377),be.fill(2,65504,65511);for(let e=0;e<ks.length;++e)be.fill(0,ks[e][0],ks[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?be[e]:rd(e,sd)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let r=Pt.extractWidth(t);r===0?s=!1:r>i&&(i=r)}return Pt.createPropertyValue(0,i,s)}},Pt=class Vi{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new C,this.onChange=this._onChange.event;let t=new nd;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,i,s=!1){return(t&16777215)<<3|(i&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 i=0,s=0,r=t.length;for(let n=0;n<r;++n){let o=t.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=r)return i+this.wcwidth(o);let l=t.charCodeAt(n);56320<=l&&l<=57343?o=(o-55296)*1024+l-56320+65536:i+=this.wcwidth(l)}let a=this.charProperties(o,s),h=Vi.extractWidth(a);Vi.extractShouldJoin(a)&&(h-=Vi.extractWidth(s)),i+=h,s=a}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},od=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Mn(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),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var ai=2147483647,ad=256,ka=class gr{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>ad)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new gr;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s<t.length;++s){let r=t[s];if(Array.isArray(r))for(let n=0;n<r.length;++n)i.addSubParam(r[n]);else i.addParam(r)}return i}clone(){let t=new gr(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 i=0;i<this.length;++i){t.push(this.params[i]);let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,r))}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>ai?ai: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>ai?ai:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i<this.length;++i){let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&(t[i]=this._subParams.slice(s,r))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,r=s[i-1];s[i-1]=~r?Math.min(r*10+t,ai):t}},li=[],ld=class{constructor(){this._state=0,this._active=li,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=li}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=li,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||li,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",hs(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t<i;){let s=e[t++];if(s===59){this._state=2,this._start();break}if(s<48||57<s){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+s-48}this._state===2&&i-t>0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=li,this._id=-1,this._state=0}}},Ke=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=hs(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},hi=[],hd=class{constructor(){this._handlers=Object.create(null),this._active=hi,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=hi}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=hi,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||hi,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",hs(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=hi,this._ident=0}},mi=new ka;mi.addParam(0);var Ln=class{constructor(e){this._handler=e,this._data="",this._params=mi,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():mi,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=hs(e,t,i),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(i=>(this._params=mi,this._data="",this._hitLimit=!1,i));return this._params=mi,this._data="",this._hitLimit=!1,t}},cd=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=i<<4|s}},Je=160,dd=(function(){let e=new cd(4095),t=Array.apply(null,Array(256)).map((a,h)=>h),i=(a,h)=>t.slice(a,h),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));let n=i(0,14),o;e.setDefault(1,0),e.addMany(s,0,2,0);for(o in n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,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(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,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(Je,0,2,0),e.add(Je,8,5,8),e.add(Je,6,0,6),e.add(Je,11,0,11),e.add(Je,13,13,13),e})(),ud=class extends G{constructor(e=dd){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new ka,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(oe(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new ld),this._dcsParser=this._register(new hd),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let r=0;r<e.intermediates.length;++r){let n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=n}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}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(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s=0,r=0,n=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,n=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let a=this._parseStack.handlers,h=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&h>-1){for(;h>=0&&(o=a[h](this._params),o!==!0);h--)if(o instanceof Promise)return this._parseStack.handlerPos=h,o}this._parseStack.handlers=[];break;case 4:if(i===!1&&h>-1){for(;h>=0&&(o=a[h](),o!==!0);h--)if(o instanceof Promise)return this._parseStack.handlerPos=h,o}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],o=this._oscParser.end(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,n=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let a=n;a<t;++a){switch(s=e[a],r=this._transitions.table[this.currentState<<8|(s<160?s:Je)],r>>4){case 2:for(let u=a+1;;++u){if(u>=t||(s=e[u])<32||s>126&&s<Je){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(s=e[u])<32||s>126&&s<Je){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(s=e[u])<32||s>126&&s<Je){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(s=e[u])<32||s>126&&s<Je){this._printHandler(e,a,u),a=u-1;break}}break;case 3:this._executeHandlers[s]?this._executeHandlers[s]():this._executeHandlerFb(s),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:a,code:s,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let h=this._csiHandlers[this._collect<<8|s],l=h?h.length-1:-1;for(;l>=0&&(o=h[l](this._params),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(3,h,l,r,a),o;l<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++a<t&&(s=e[a])>47&&s<60);a--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let c=this._escHandlers[this._collect<<8|s],d=c?c.length-1:-1;for(;d>=0&&(o=c[d](),o!==!0);d--)if(o instanceof Promise)return this._preserveStack(4,c,d,r,a),o;d<0&&this._escHandlerFb(this._collect<<8|s),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|s,this._params);break;case 13:for(let u=a+1;;++u)if(u>=t||(s=e[u])===24||s===26||s===27||s>127&&s<Je){this._dcsParser.put(e,a,u),a=u-1;break}break;case 14:if(o=this._dcsParser.unhook(s!==24&&s!==26),o)return this._preserveStack(6,[],0,r,a),o;s===27&&(r|=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 u=a+1;;u++)if(u>=t||(s=e[u])<32||s>127&&s<Je){this._oscParser.put(e,a,u),a=u-1;break}break;case 6:if(o=this._oscParser.end(s!==24&&s!==26),o)return this._preserveStack(5,[],0,r,a),o;s===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=r&15}}},_d=/^([\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})$/,fd=/^[\da-f]+$/;function Dn(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let i=_d.exec(t);if(i){let s=i[1]?15:i[4]?255:i[7]?4095:65535;return[Math.round(parseInt(i[1]||i[4]||i[7]||i[10],16)/s*255),Math.round(parseInt(i[2]||i[5]||i[8]||i[11],16)/s*255),Math.round(parseInt(i[3]||i[6]||i[9]||i[12],16)/s*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),fd.exec(t)&&[3,6,9,12].includes(t.length))){let i=t.length/3,s=[0,0,0];for(let r=0;r<3;++r){let n=parseInt(t.slice(i*r,i*r+i),16);s[r]=i===1?n<<4:i===2?n:i===3?n>>4:n>>8}return s}}function Es(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function pd(e,t=16){let[i,s,r]=e;return`rgb:${Es(i,t)}/${Es(s,t)}/${Es(r,t)}`}var md={"(":0,")":1,"*":2,"+":3,"-":1,".":2},yt=131072,Tn=10;function $n(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 An=5e3,Pn=0,gd=class extends G{constructor(e,t,i,s,r,n,o,a,h=new ud){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=a,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Nl,this._utf8Decoder=new Il,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=me.clone(),this._eraseAttrDataInternal=me.clone(),this._onRequestBell=this._register(new C),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new C),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new C),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new C),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new C),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new C),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new C),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new C),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new C),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new C),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new C),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new C),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new C),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 vr(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(l=>this._activeBuffer=l.activeBuffer)),this._parser.setCsiHandlerFallback((l,c)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(l),params:c.toArray()})}),this._parser.setEscHandlerFallback(l=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(l)})}),this._parser.setExecuteHandlerFallback(l=>{this._logService.debug("Unknown EXECUTE code: ",{code:l})}),this._parser.setOscHandlerFallback((l,c,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:l,action:c,data:d})}),this._parser.setDcsHandlerFallback((l,c,d)=>{c==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(l),action:c,payload:d})}),this._parser.setPrintHandler((l,c,d)=>this.print(l,c,d)),this._parser.registerCsiHandler({final:"@"},l=>this.insertChars(l)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},l=>this.scrollLeft(l)),this._parser.registerCsiHandler({final:"A"},l=>this.cursorUp(l)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},l=>this.scrollRight(l)),this._parser.registerCsiHandler({final:"B"},l=>this.cursorDown(l)),this._parser.registerCsiHandler({final:"C"},l=>this.cursorForward(l)),this._parser.registerCsiHandler({final:"D"},l=>this.cursorBackward(l)),this._parser.registerCsiHandler({final:"E"},l=>this.cursorNextLine(l)),this._parser.registerCsiHandler({final:"F"},l=>this.cursorPrecedingLine(l)),this._parser.registerCsiHandler({final:"G"},l=>this.cursorCharAbsolute(l)),this._parser.registerCsiHandler({final:"H"},l=>this.cursorPosition(l)),this._parser.registerCsiHandler({final:"I"},l=>this.cursorForwardTab(l)),this._parser.registerCsiHandler({final:"J"},l=>this.eraseInDisplay(l,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},l=>this.eraseInDisplay(l,!0)),this._parser.registerCsiHandler({final:"K"},l=>this.eraseInLine(l,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},l=>this.eraseInLine(l,!0)),this._parser.registerCsiHandler({final:"L"},l=>this.insertLines(l)),this._parser.registerCsiHandler({final:"M"},l=>this.deleteLines(l)),this._parser.registerCsiHandler({final:"P"},l=>this.deleteChars(l)),this._parser.registerCsiHandler({final:"S"},l=>this.scrollUp(l)),this._parser.registerCsiHandler({final:"T"},l=>this.scrollDown(l)),this._parser.registerCsiHandler({final:"X"},l=>this.eraseChars(l)),this._parser.registerCsiHandler({final:"Z"},l=>this.cursorBackwardTab(l)),this._parser.registerCsiHandler({final:"`"},l=>this.charPosAbsolute(l)),this._parser.registerCsiHandler({final:"a"},l=>this.hPositionRelative(l)),this._parser.registerCsiHandler({final:"b"},l=>this.repeatPrecedingCharacter(l)),this._parser.registerCsiHandler({final:"c"},l=>this.sendDeviceAttributesPrimary(l)),this._parser.registerCsiHandler({prefix:">",final:"c"},l=>this.sendDeviceAttributesSecondary(l)),this._parser.registerCsiHandler({final:"d"},l=>this.linePosAbsolute(l)),this._parser.registerCsiHandler({final:"e"},l=>this.vPositionRelative(l)),this._parser.registerCsiHandler({final:"f"},l=>this.hVPosition(l)),this._parser.registerCsiHandler({final:"g"},l=>this.tabClear(l)),this._parser.registerCsiHandler({final:"h"},l=>this.setMode(l)),this._parser.registerCsiHandler({prefix:"?",final:"h"},l=>this.setModePrivate(l)),this._parser.registerCsiHandler({final:"l"},l=>this.resetMode(l)),this._parser.registerCsiHandler({prefix:"?",final:"l"},l=>this.resetModePrivate(l)),this._parser.registerCsiHandler({final:"m"},l=>this.charAttributes(l)),this._parser.registerCsiHandler({final:"n"},l=>this.deviceStatus(l)),this._parser.registerCsiHandler({prefix:"?",final:"n"},l=>this.deviceStatusPrivate(l)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},l=>this.softReset(l)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},l=>this.setCursorStyle(l)),this._parser.registerCsiHandler({final:"r"},l=>this.setScrollRegion(l)),this._parser.registerCsiHandler({final:"s"},l=>this.saveCursor(l)),this._parser.registerCsiHandler({final:"t"},l=>this.windowOptions(l)),this._parser.registerCsiHandler({final:"u"},l=>this.restoreCursor(l)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},l=>this.insertColumns(l)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},l=>this.deleteColumns(l)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},l=>this.selectProtected(l)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},l=>this.requestMode(l,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},l=>this.requestMode(l,!1)),this._parser.setExecuteHandler(v.BEL,()=>this.bell()),this._parser.setExecuteHandler(v.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(v.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(v.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(v.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(v.BS,()=>this.backspace()),this._parser.setExecuteHandler(v.HT,()=>this.tab()),this._parser.setExecuteHandler(v.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(v.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Ki.IND,()=>this.index()),this._parser.setExecuteHandler(Ki.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Ki.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Ke(l=>(this.setTitle(l),this.setIconName(l),!0))),this._parser.registerOscHandler(1,new Ke(l=>this.setIconName(l))),this._parser.registerOscHandler(2,new Ke(l=>this.setTitle(l))),this._parser.registerOscHandler(4,new Ke(l=>this.setOrReportIndexedColor(l))),this._parser.registerOscHandler(8,new Ke(l=>this.setHyperlink(l))),this._parser.registerOscHandler(10,new Ke(l=>this.setOrReportFgColor(l))),this._parser.registerOscHandler(11,new Ke(l=>this.setOrReportBgColor(l))),this._parser.registerOscHandler(12,new Ke(l=>this.setOrReportCursorColor(l))),this._parser.registerOscHandler(104,new Ke(l=>this.restoreIndexedColor(l))),this._parser.registerOscHandler(110,new Ke(l=>this.restoreFgColor(l))),this._parser.registerOscHandler(111,new Ke(l=>this.restoreBgColor(l))),this._parser.registerOscHandler(112,new Ke(l=>this.restoreCursorColor(l))),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 l in Ce)this._parser.registerEscHandler({intermediates:"(",final:l},()=>this.selectCharset("("+l)),this._parser.registerEscHandler({intermediates:")",final:l},()=>this.selectCharset(")"+l)),this._parser.registerEscHandler({intermediates:"*",final:l},()=>this.selectCharset("*"+l)),this._parser.registerEscHandler({intermediates:"+",final:l},()=>this.selectCharset("+"+l)),this._parser.registerEscHandler({intermediates:"-",final:l},()=>this.selectCharset("-"+l)),this._parser.registerEscHandler({intermediates:".",final:l},()=>this.selectCharset("."+l)),this._parser.registerEscHandler({intermediates:"/",final:l},()=>this.selectCharset("/"+l));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(l=>(this._logService.error("Parsing error: ",l),l)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Ln((l,c)=>this.requestStatusString(l,c)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),An))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${An} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>yt&&(n=this._parseStack.position+yt)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,l=>String.fromCharCode(l)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(l=>l.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<yt&&(this._parseBuffer=new Uint32Array(Math.min(e.length,yt))),o||this._dirtyRowTracker.clearRange(),e.length>yt)for(let l=n;l<e.length;l+=yt){let c=l+yt<e.length?l+yt:e.length,d=typeof e=="string"?this._stringDecoder.decode(e.substring(l,c),this._parseBuffer):this._utf8Decoder.decode(e.subarray(l,c),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,d))return this._preserveStack(s,r,d,l),this._logSlowResolvingAsync(i),i}else if(!o){let l=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,l))return this._preserveStack(s,r,l,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==s||this._activeBuffer.y!==r)&&this._onCursorMove.fire();let a=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(a,this._bufferService.rows-1)})}print(e,t,i){let s,r,n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,a=this._bufferService.cols,h=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,c=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,c);let u=this._parser.precedingJoinState;for(let f=t;f<i;++f){if(s=e[f],s<127&&n){let x=n[String.fromCharCode(s)];x&&(s=x.charCodeAt(0))}let _=this._unicodeService.charProperties(s,u);r=Pt.extractWidth(_);let p=Pt.extractShouldJoin(_),g=p?Pt.extractWidth(u):0;if(u=_,o&&this._onA11yChar.fire(Ct(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-g>a){if(h){let x=d,z=this._activeBuffer.x-g;for(this._activeBuffer.x=g,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),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),g>0&&d instanceof fi&&d.copyCellsFrom(x,z,0,g,!1);z<a;)x.setCellFromCodepoint(z++,0,1,c)}else if(this._activeBuffer.x=a-1,r===2)continue}if(p&&this._activeBuffer.x){let x=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-x,s,r);for(let z=r-g;--z>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,c);continue}if(l&&(d.insertCells(this._activeBuffer.x,r-g,this._activeBuffer.getNullCell(c)),d.getWidth(a-1)===2&&d.setCellFromCodepoint(a-1,0,1,c)),d.setCellFromCodepoint(this._activeBuffer.x++,s,r,c),r>0)for(;--r;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,c)}this._parser.precedingJoinState=u,this._activeBuffer.x<a&&i-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,c),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>$n(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Ln(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Ke(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,i,s=!1,r=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i<this._bufferService.rows;i++)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(i);break;case 1:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let r=this._activeBuffer.lines.length-this._bufferService.rows;r>0&&(this._activeBuffer.lines.trimStart(r),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-r,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-r,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 i=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(i,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 i=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(i,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(me));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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);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 i=e.params[0]||1,s=Pt.extractWidth(t),r=this._activeBuffer.x-s,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*i),a=0;for(let l=0;l<n.length;){let c=n.codePointAt(l)||0;o[a++]=c,l+=c>65535?2:1}let h=a;for(let l=1;l<i;++l)o.copyWithin(h,0,a),h+=a;return this.print(o,0,h),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(v.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(v.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(v.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(v.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(v.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,At),this._charsetService.setgCharset(1,At),this._charsetService.setgCharset(2,At),this._charsetService.setgCharset(3,At);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){(p=>(p[p.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",p[p.SET=1]="SET",p[p.RESET=2]="RESET",p[p.PERMANENTLY_SET=3]="PERMANENTLY_SET",p[p.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:n}=this._coreMouseService,o=this._coreService,{buffers:a,cols:h}=this._bufferService,{active:l,alt:c}=a,d=this._optionsService.rawOptions,u=(p,g)=>(o.triggerDataEvent(`${v.ESC}[${t?"":"?"}${p};${g}$y`),!0),f=p=>p?1:2,_=e.params[0];return t?_===2?u(_,4):_===4?u(_,f(o.modes.insertMode)):_===12?u(_,3):_===20?u(_,f(d.convertEol)):u(_,0):_===1?u(_,f(s.applicationCursorKeys)):_===3?u(_,d.windowOptions.setWinLines?h===80?2:h===132?1:0:0):_===6?u(_,f(s.origin)):_===7?u(_,f(s.wraparound)):_===8?u(_,3):_===9?u(_,f(r==="X10")):_===12?u(_,f(d.cursorBlink)):_===25?u(_,f(!o.isCursorHidden)):_===45?u(_,f(s.reverseWraparound)):_===66?u(_,f(s.applicationKeypad)):_===67?u(_,4):_===1e3?u(_,f(r==="VT200")):_===1002?u(_,f(r==="DRAG")):_===1003?u(_,f(r==="ANY")):_===1004?u(_,f(s.sendFocus)):_===1005?u(_,4):_===1006?u(_,f(n==="SGR")):_===1015?u(_,4):_===1016?u(_,f(n==="SGR_PIXELS")):_===1048?u(_,1):_===47||_===1047||_===1049?u(_,f(l===c)):_===2004?u(_,f(s.bracketedPasteMode)):_===2026?u(_,f(s.synchronizedOutput)):u(_,0)}_updateAttrColor(e,t,i,s,r){return t===2?(e|=50331648,e&=-16777216,e|=xi.fromColorRGB([i,s,r])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){let o=e.getSubParams(t+n),a=0;do s[1]===5&&(r=1),s[n+a+1+r]=o[a];while(++a<o.length&&a+n+1+r<s.length);break}if(s[1]===5&&n+r>=2||s[1]===2&&n+r>=5)break;s[1]&&(r=1)}while(++n+t<e.length&&n+r<s.length);for(let o=2;o<s.length;++o)s[o]===-1&&(s[o]=0);switch(s[0]){case 38:i.fg=this._updateAttrColor(i.fg,s[1],s[3],s[4],s[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,s[1],s[3],s[4],s[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,s[1],s[3],s[4],s[5])}return n}_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=me.fg,e.bg=me.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,i,s=this._curAttrData;for(let r=0;r<t;r++)i=e.params[r],i>=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=me.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=me.bg&16777215):i===38||i===48||i===58?r+=this._extractColor(e,r,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=me.fg&16777215,s.bg&=-67108864,s.bg|=me.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${v.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${v.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${v.ESC}[?${t};${i}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=me.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 i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!$n(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(`${v.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Tn&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Tn&&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=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),r=i.shift();if(/^\d+$/.exec(s)){let n=parseInt(s);if(Nn(n))if(r==="?")t.push({type:0,index:n});else{let o=Dn(r);o&&t.push({type:1,index:n,color:o})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,r=i.findIndex(n=>n.startsWith("id="));return r!==-1&&(s=i[r].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 i=e.split(";");for(let s=0;s<i.length&&!(t>=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Dn(i[s]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}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=[],i=e.split(";");for(let s=0;s<i.length;++s)if(/^\d+$/.exec(i[s])){let r=parseInt(i[s]);Nn(r)&&t.push({type:2,index:r})}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,At),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(md[e[0]],Ce[e[1]]||At),!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=me.clone(),this._eraseAttrDataInternal=me.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 Ze;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 i=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(i);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=o=>(this._coreService.triggerDataEvent(`${v.ESC}${o}${v.ESC}\\`),!0),s=this._bufferService.buffer,r=this._optionsService.rawOptions;return i(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}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},vr=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&&(Pn=e,e=t,t=Pn),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vr=_e([$(0,Oe)],vr);function Nn(e){return 0<=e&&e<256}var vd=5e7,In=12,Sd=50,yd=class extends G{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new C),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>vd)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+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],r=this._action(s,t);if(r){let o=a=>performance.now()-i>=In?setTimeout(()=>this._innerWrite(0,a)):this._innerWrite(i,a);r.catch(a=>(queueMicrotask(()=>{throw a}),Promise.resolve(!1))).then(o);return}let n=this._callbacks[this._bufferOffset];if(n&&n(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=In)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Sd&&(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()}},Sr=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let a=t.addMarker(t.ybase+t.y),h={data:e,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(h,a)),this._dataByLinkId.set(h.id,h),h.id}let i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Sr=_e([$(0,Oe)],Sr);var On=!1,wd=class extends G{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Zt),this._onBinary=this._register(new C),this.onBinary=this._onBinary.event,this._onData=this._register(new C),this.onData=this._onData.event,this._onLineFeed=this._register(new C),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new C),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new C),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new C),this._instantiationService=new Kc,this.optionsService=this._register(new td(e)),this._instantiationService.setService(Fe,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(fr)),this._instantiationService.setService(Oe,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(_r)),this._instantiationService.setService(jo,this._logService),this.coreService=this._register(this._instantiationService.createInstance(pr)),this._instantiationService.setService(Ft,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(mr)),this._instantiationService.setService(Uo,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Pt)),this._instantiationService.setService(Wl,this.unicodeService),this._charsetService=this._instantiationService.createInstance(od),this._instantiationService.setService(Hl,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sr),this._instantiationService.setService(Ko,this._oscLinkService),this._inputHandler=this._register(new gd(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(De.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(De.forward(this._bufferService.onResize,this._onResize)),this._register(De.forward(this.coreService.onData,this._onData)),this._register(De.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 yd((t,i)=>this._inputHandler.parse(t,i))),this._register(De.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new C),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.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(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!On&&(this._logService.warn("writeSync is unreliable and will be removed soon."),On=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Ca),t=Math.max(t,xa),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Mn.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Mn(this._bufferService),!1))),this._windowsWrappingHeuristics.value=oe(()=>{for(let t of e)t.dispose()})}}},bd={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 Cd(e,t,i,s){var o;let r={type:0,cancel:!1,key:void 0},n=(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?r.key=v.ESC+"OA":r.key=v.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?r.key=v.ESC+"OD":r.key=v.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?r.key=v.ESC+"OC":r.key=v.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?r.key=v.ESC+"OB":r.key=v.ESC+"[B");break;case 8:r.key=e.ctrlKey?"\b":v.DEL,e.altKey&&(r.key=v.ESC+r.key);break;case 9:if(e.shiftKey){r.key=v.ESC+"[Z";break}r.key=v.HT,r.cancel=!0;break;case 13:r.key=e.altKey?v.ESC+v.CR:v.CR,r.cancel=!0;break;case 27:r.key=v.ESC,e.altKey&&(r.key=v.ESC+v.ESC),r.cancel=!0;break;case 37:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"D":t?r.key=v.ESC+"OD":r.key=v.ESC+"[D";break;case 39:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"C":t?r.key=v.ESC+"OC":r.key=v.ESC+"[C";break;case 38:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"A":t?r.key=v.ESC+"OA":r.key=v.ESC+"[A";break;case 40:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"B":t?r.key=v.ESC+"OB":r.key=v.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(r.key=v.ESC+"[2~");break;case 46:n?r.key=v.ESC+"[3;"+(n+1)+"~":r.key=v.ESC+"[3~";break;case 36:n?r.key=v.ESC+"[1;"+(n+1)+"H":t?r.key=v.ESC+"OH":r.key=v.ESC+"[H";break;case 35:n?r.key=v.ESC+"[1;"+(n+1)+"F":t?r.key=v.ESC+"OF":r.key=v.ESC+"[F";break;case 33:e.shiftKey?r.type=2:e.ctrlKey?r.key=v.ESC+"[5;"+(n+1)+"~":r.key=v.ESC+"[5~";break;case 34:e.shiftKey?r.type=3:e.ctrlKey?r.key=v.ESC+"[6;"+(n+1)+"~":r.key=v.ESC+"[6~";break;case 112:n?r.key=v.ESC+"[1;"+(n+1)+"P":r.key=v.ESC+"OP";break;case 113:n?r.key=v.ESC+"[1;"+(n+1)+"Q":r.key=v.ESC+"OQ";break;case 114:n?r.key=v.ESC+"[1;"+(n+1)+"R":r.key=v.ESC+"OR";break;case 115:n?r.key=v.ESC+"[1;"+(n+1)+"S":r.key=v.ESC+"OS";break;case 116:n?r.key=v.ESC+"[15;"+(n+1)+"~":r.key=v.ESC+"[15~";break;case 117:n?r.key=v.ESC+"[17;"+(n+1)+"~":r.key=v.ESC+"[17~";break;case 118:n?r.key=v.ESC+"[18;"+(n+1)+"~":r.key=v.ESC+"[18~";break;case 119:n?r.key=v.ESC+"[19;"+(n+1)+"~":r.key=v.ESC+"[19~";break;case 120:n?r.key=v.ESC+"[20;"+(n+1)+"~":r.key=v.ESC+"[20~";break;case 121:n?r.key=v.ESC+"[21;"+(n+1)+"~":r.key=v.ESC+"[21~";break;case 122:n?r.key=v.ESC+"[23;"+(n+1)+"~":r.key=v.ESC+"[23~";break;case 123:n?r.key=v.ESC+"[24;"+(n+1)+"~":r.key=v.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?r.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?r.key=v.NUL:e.keyCode>=51&&e.keyCode<=55?r.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?r.key=v.DEL:e.keyCode===219?r.key=v.ESC:e.keyCode===220?r.key=v.FS:e.keyCode===221&&(r.key=v.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let a=(o=bd[e.keyCode])==null?void 0:o[e.shiftKey?1:0];if(a)r.key=v.ESC+a;else if(e.keyCode>=65&&e.keyCode<=90){let h=e.ctrlKey?e.keyCode-64:e.keyCode+32,l=String.fromCharCode(h);e.shiftKey&&(l=l.toUpperCase()),r.key=v.ESC+l}else if(e.keyCode===32)r.key=v.ESC+(e.ctrlKey?v.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let h=e.code.slice(3,4);e.shiftKey||(h=h.toLowerCase()),r.key=v.ESC+h,r.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(r.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?r.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(r.key=v.US),e.key==="@"&&(r.key=v.NUL));break}return r}var fe=0,xd=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new os,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new os,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(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((r,n)=>this._getKey(r)-this._getKey(n)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let r=0;r<s.length;r++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[r]=e[t],t++):s[r]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(fe=this._search(t),fe===-1)||this._getKey(this._array[fe])!==t)return!1;do if(this._array[fe]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(fe),!0;while(++fe<this._array.length&&this._getKey(this._array[fe])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((r,n)=>r-n),t=0,i=new Array(this._array.length-e.length),s=0;for(let r=0;r<this._array.length;r++)e[t]===r?t++:i[s++]=this._array[r];this._array=i,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(fe=this._search(e),!(fe<0||fe>=this._array.length)&&this._getKey(this._array[fe])===e))do yield this._array[fe];while(++fe<this._array.length&&this._getKey(this._array[fe])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(fe=this._search(e),!(fe<0||fe>=this._array.length)&&this._getKey(this._array[fe])===e))do t(this._array[fe]);while(++fe<this._array.length&&this._getKey(this._array[fe])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let s=t+i>>1,r=this._getKey(this._array[s]);if(r>e)i=s-1;else if(r<e)t=s+1;else{for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},Rs=0,Fn=0,kd=class extends G{constructor(){super(),this._decorations=new xd(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new C),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new C),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(oe(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Ed(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.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,i){let s=0,r=0;for(let n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e<r&&(!i||(n.options.layer??"bottom")===i)&&(yield n)}forEachDecorationAtCell(e,t,i,s){this._decorations.forEachByKey(t,r=>{Rs=r.options.x??0,Fn=Rs+(r.options.width??1),e>=Rs&&e<Fn&&(!i||(r.options.layer??"bottom")===i)&&s(r)})}},Ed=class extends Et{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new C),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new C),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=he.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=he.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Rd=1e3,Bd=class{constructor(e,t=Rd){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t;let s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let r=s-this._lastRefreshMs,n=this._debounceThresholdMS-r;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},n)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Hn=20,as=class extends G{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=n=>this._handleBoundaryFocus(n,0),this._bottomBoundaryFocusListener=n=>this._handleBoundaryFocus(n,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=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Bd(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(n=>this._handleResize(n.rows))),this._register(this._terminal.onRender(n=>this._refreshRows(n.start,n.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(n=>this._handleChar(n))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
`))),this._register(this._terminal.onA11yTab(n=>this._handleTab(n))),this._register(this._terminal.onKey(n=>this._handleKey(n.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(j(r,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(oe(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<Hn+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Hn+1&&(this._liveRegion.textContent+=Fs.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 i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){let n=i.lines.get(i.ydisp+r),o=[],a=(n==null?void 0:n.translateToString(!0,void 0,void 0,o))||"",h=(i.ydisp+r+1).toString(),l=this._rowElements[r];l&&(a.length===0?(l.textContent=" ",this._rowColumns.set(l,[0,1])):(l.textContent=a,this._rowColumns.set(l,o)),l.setAttribute("aria-posinset",h),l.setAttribute("aria-setsize",s),this._alignRowWidth(l))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],r=i.getAttribute("aria-posinset"),n=t===0?"1":`${this._terminal.buffer.lines.length}`;if(r===n||e.relatedTarget!==s)return;let o,a;if(t===0?(o=i,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(o=this._rowElements.shift(),a=i,this._rowContainer.removeChild(o)),o.removeEventListener("focus",this._topBoundaryFocusListener),a.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 a;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},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,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(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((a=s.textContent)==null?void 0:a.length)??0}),!this._rowContainer.contains(i.node))return;let r=({node:h,offset:l})=>{let c=h instanceof Text?h.parentNode:h,d=parseInt(c==null?void 0:c.getAttribute("aria-posinset"),10)-1;if(isNaN(d))return console.warn("row is invalid. Race condition?"),null;let u=this._rowColumns.get(c);if(!u)return console.warn("columns is null. Race condition?"),null;let f=l<u.length?u[l]:u.slice(-1)[0]+1;return f>=this._terminal.cols&&(++d,f=0),{row:d,column:f}},n=r(t),o=r(i);if(!(!n||!o)){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.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 r,n;e.style.transform="";let t=e.getBoundingClientRect().width,i=(n=(r=this._rowColumns.get(e))==null?void 0:r.slice(-1))==null?void 0:n[0];if(!i)return;let s=i*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${s/t})`}};as=_e([$(1,Rr),$(2,pt),$(3,mt)],as);var yr=class extends G{constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new C),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new C),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(oe(()=>{var n;It(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(n=this._activeProviderReplies)==null||n.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(j(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(j(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(j(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(j(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 i=e.composedPath();for(let s=0;s<i.length;s++){let r=i[s];if(r.classList.contains("xterm"))break;if(r.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,r;(!this._activeProviderReplies||!t)&&((s=this._activeProviderReplies)==null||s.forEach(n=>{n==null||n.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())t?(r=this._activeProviderReplies)!=null&&r.get(n)&&(i=this._checkLinkProviderResult(n,e,i)):o.provideLinks(e.y,a=>{var l,c;if(this._isMouseOut)return;let h=a==null?void 0:a.map(d=>({link:d}));(l=this._activeProviderReplies)==null||l.set(n,h),i=this._checkLinkProviderResult(n,e,i),((c=this._activeProviderReplies)==null?void 0:c.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;s<t.size;s++){let r=t.get(s);if(r)for(let n=0;n<r.length;n++){let o=r[n],a=o.link.range.start.y<e?0:o.link.range.start.x,h=o.link.range.end.y>e?this._bufferService.cols:o.link.range.end.x;for(let l=a;l<=h;l++){if(i.has(l)){r.splice(n--,1);break}i.add(l)}}}}_checkLinkProviderResult(e,t,i){var n;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),r=!1;for(let o=0;o<e;o++)(!this._activeProviderReplies.has(o)||this._activeProviderReplies.get(o))&&(r=!0);if(!r&&s){let o=s.find(a=>this._linkAtPosition(a.link,t));o&&(i=!0,this._handleNewLink(o))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let o=0;o<this._activeProviderReplies.size;o++){let a=(n=this._activeProviderReplies.get(o))==null?void 0:n.find(h=>this._linkAtPosition(h.link,t));if(a){i=!0,this._handleNewLink(a);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Md(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,It(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 i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,r,n;(s=this._currentLink)!=null&&s.state&&((n=(r=this._currentLink)==null?void 0:r.state)==null?void 0:n.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,r=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=r&&(this._clearCurrentLink(s,r),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(e,t,i){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(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){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(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){let s=i.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,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};yr=_e([$(1,Br),$(2,mt),$(3,Oe),$(4,Vo)],yr);function Md(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 Ld=class extends wd{constructor(e={}){super(e),this._linkifier=this._register(new Zt),this.browser=ua,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Zt),this._onCursorMove=this._register(new C),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new C),this.onKey=this._onKey.event,this._onRender=this._register(new C),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new C),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new C),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new C),this.onBell=this._onBell.event,this._onFocus=this._register(new C),this._onBlur=this._register(new C),this._onA11yCharEmitter=this._register(new C),this._onA11yTabEmitter=this._register(new C),this._onWillOpen=this._register(new C),this._setup(),this._decorationService=this._instantiationService.createInstance(kd),this._instantiationService.setService(ki,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Sc),this._instantiationService.setService(Vo,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Ws)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(De.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(De.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(De.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(De.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(oe(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.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(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let r=ne.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${v.ESC}]${s};${pd(r)}${ca.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(n=>n.ansi[t.index]=ve.toColor(...t.color));else{let n=i;this._themeService.modifyColors(o=>o[n]=ve.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(as,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(v.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(v.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(j(this.element,"copy",t=>{this.hasSelection()&&Al(t,this._selectionService)}));let e=t=>Pl(t,this.textarea,this.coreService,this.optionsService);this._register(j(this.textarea,"paste",e)),this._register(j(this.element,"paste",e)),_a?this._register(j(this.element,"mousedown",t=>{t.button===2&&Yr(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(j(this.element,"contextmenu",t=>{Yr(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Nr&&this._register(j(this.element,"auxclick",t=>{t.button===1&&Oo(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(j(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(j(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(j(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(j(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(j(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(j(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(j(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var r;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((r=this.element)==null?void 0:r.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.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"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(j(this.screenElement,"mousemove",n=>this.updateCursorStyle(n))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Os.get()),ma||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",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(gc,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(pt,this._coreBrowserService),this._register(j(this.textarea,"focus",n=>this._handleTextAreaFocus(n))),this._register(j(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(lr,this._document,this._helperContainer),this._instantiationService.setService(cs,this._charSizeService),this._themeService=this._instantiationService.createInstance(ur),this._instantiationService.setService(ei,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(rs),this._instantiationService.setService(qo,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(cr,this.rows,this.screenElement)),this._instantiationService.setService(mt,this._renderService),this._register(this._renderService.onRenderedViewportChange(n=>this._onRender.fire(n))),this.onResize(n=>this._renderService.resize(n.cols,n.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(nr,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(hr),this._instantiationService.setService(Br,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(yr,this.screenElement));this.element.appendChild(t);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(sr,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(n=>{super.scrollLines(n,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(dr,this.element,this.screenElement,s)),this._instantiationService.setService(Ul,this._selectionService),this._register(this._selectionService.onRequestScrollLines(n=>this.scrollLines(n.amount,n.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(n=>this._renderService.handleSelectionChanged(n.start,n.end,n.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(n=>{this.textarea.value=n,this.textarea.focus(),this.textarea.select()})),this._register(De.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var n;this._selectionService.refresh(),(n=this._viewport)==null||n.queueSync()})),this._register(this._instantiationService.createInstance(rr,this.screenElement)),this._register(j(this.element,"mousedown",n=>this._selectionService.handleMouseDown(n))),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(as,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",n=>this._handleScreenReaderModeOptionChange(n))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ss,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",n=>{!this._overviewRulerRenderer&&n&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ss,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ar,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(n){var l,c,d,u,f;let o=e._mouseService.getMouseReportCoords(n,e.screenElement);if(!o)return!1;let a,h;switch(n.overrideType||n.type){case"mousemove":h=32,n.buttons===void 0?(a=3,n.button!==void 0&&(a=n.button<3?n.button:3)):a=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case"mouseup":h=0,a=n.button<3?n.button:3;break;case"mousedown":h=1,a=n.button<3?n.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(n)===!1)return!1;let _=n.deltaY;if(_===0||e.coreMouseService.consumeWheelEvent(n,(u=(d=(c=(l=e._renderService)==null?void 0:l.dimensions)==null?void 0:c.device)==null?void 0:d.cell)==null?void 0:u.height,(f=e._coreBrowserService)==null?void 0:f.dpr)===0)return!1;h=_<0?0:1,a=4;break;default:return!1}return h===void 0||a===void 0||a>4?!1:e.coreMouseService.triggerMouseEvent({col:o.col,row:o.row,x:o.x,y:o.y,button:a,action:h,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:n=>(i(n),n.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(n)),wheel:n=>(i(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&i(n)},mousemove:n=>{n.buttons||i(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(n)),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()),n&8?s.mousemove||(t.addEventListener("mousemove",r.mousemove),s.mousemove=r.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),n&16?s.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),s.wheel=r.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),n&2?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),n&4?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(j(t,"mousedown",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return i(n),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(n)})),this._register(j(t,"wheel",n=>{var o,a,h,l,c;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(n,(l=(h=(a=(o=e._renderService)==null?void 0:o.dimensions)==null?void 0:a.device)==null?void 0:h.cell)==null?void 0:l.height,(c=e._coreBrowserService)==null?void 0:c.dpr)===0)return this.cancel(n,!0);let d=v.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(n.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(d,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?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(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Io(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}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 e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=Cd(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===v.ETX||i.key===v.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Dd(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.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 e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(me));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){var t;this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),(t=this._selectionService)==null||t.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){var e;(e=this._renderService)==null||e.clearTextureAtlas()}_reportFocus(){var e;(e=this.element)!=null&&e.classList.contains("focus")?this.coreService.triggerDataEvent(v.ESC+"[I"):this.coreService.triggerDataEvent(v.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),i=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${v.ESC}[4;${i};${t}t`);break;case 1:let s=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${v.ESC}[6;${r};${s}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function Dd(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Td=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(t===-1)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},$d=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Ze)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Wn=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 $d(t)}getNullCell(){return new Ze}},Ad=class extends G{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new C),this.onBufferChange=this._onBufferChange.event,this._normal=new Wn(this._core.buffers.normal,"normal"),this._alternate=new Wn(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)}},Pd=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,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)}},Nd=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},Id=["cols","rows"],at=0,Od=class extends G{constructor(e){super(),this._core=this._register(new Ld(e)),this._addonManager=this._register(new Td),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,r)=>{this._checkReadonlyOptions(s),this._core.options[s]=r};for(let s in this._core.options){let r={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,r)}}_checkReadonlyOptions(e){if(Id.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 Pd(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Nd(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 Ad(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,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}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
`,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 Os.get()},set promptLabel(e){Os.set(e)},get tooMuchOutput(){return Fs.get()},set tooMuchOutput(e){Fs.set(e)}}}_verifyIntegers(...e){for(at of e)if(at===1/0||isNaN(at)||at%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(at of e)if(at&&(at===1/0||isNaN(at)||at%1!==0||at<0))throw new Error("This API only accepts positive integers")}};/**
 * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
 * @license MIT
 *
 * Originally forked from (with the author's permission):
 *   Fabrice Bellard's javascript vt100 for jslinux:
 *   http://bellard.org/jslinux/
 *   Copyright (c) 2011 Fabrice Bellard
 */var Fd=2,Hd=1,Wd=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 d;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:((d=this._terminal.options.overviewRuler)==null?void 0:d.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),r=Math.max(0,parseInt(i.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),o={top:parseInt(n.getPropertyValue("padding-top")),bottom:parseInt(n.getPropertyValue("padding-bottom")),right:parseInt(n.getPropertyValue("padding-right")),left:parseInt(n.getPropertyValue("padding-left"))},a=o.top+o.bottom,h=o.right+o.left,l=s-a,c=r-h-t;return{cols:Math.max(Fd,Math.floor(c/e.css.cell.width)),rows:Math.max(Hd,Math.floor(l/e.css.cell.height))}}};/**
 * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
 * @license MIT
 *
 * Originally forked from (with the author's permission):
 *   Fabrice Bellard's javascript vt100 for jslinux:
 *   http://bellard.org/jslinux/
 *   Copyright (c) 2011 Fabrice Bellard
 */var zd=class{constructor(e,t,i,s={}){this._terminal=e,this._regex=t,this._handler=i,this._options=s}provideLinks(e,t){let i=jd.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(i))}_addCallbacks(e){return e.map(t=>(t.leave=this._options.leave,t.hover=(i,s)=>{if(this._options.hover){let{range:r}=t;this._options.hover(i,s,r)}},t))}};function Ud(e){try{let t=new URL(e),i=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(i.toLocaleLowerCase())}catch{return!1}}var jd=class Gi{static computeLink(t,i,s,r){let n=new RegExp(i.source,(i.flags||"")+"g"),[o,a]=Gi._getWindowedLineStrings(t-1,s),h=o.join(""),l,c=[];for(;l=n.exec(h);){let d=l[0];if(!Ud(d))continue;let[u,f]=Gi._mapStrIdx(s,a,0,l.index),[_,p]=Gi._mapStrIdx(s,u,f,d.length);if(u===-1||f===-1||_===-1||p===-1)continue;let g={start:{x:f+1,y:u+1},end:{x:p,y:_+1}};c.push({range:g,text:d,activate:r})}return c}static _getWindowedLineStrings(t,i){let s,r=t,n=t,o=0,a="",h=[];if(s=i.buffer.active.getLine(t)){let l=s.translateToString(!0);if(s.isWrapped&&l[0]!==" "){for(o=0;(s=i.buffer.active.getLine(--r))&&o<2048&&(a=s.translateToString(!0),o+=a.length,h.push(a),!(!s.isWrapped||a.indexOf(" ")!==-1)););h.reverse()}for(h.push(l),o=0;(s=i.buffer.active.getLine(++n))&&s.isWrapped&&o<2048&&(a=s.translateToString(!0),o+=a.length,h.push(a),a.indexOf(" ")===-1););}return[h,r]}static _mapStrIdx(t,i,s,r){let n=t.buffer.active,o=n.getNullCell(),a=s;for(;r;){let h=n.getLine(i);if(!h)return[-1,-1];for(let l=a;l<h.length;++l){h.getCell(l,o);let c=o.getChars();if(o.getWidth()&&(r-=c.length||1,l===h.length-1&&c==="")){let d=n.getLine(i+1);d&&d.isWrapped&&(d.getCell(0,o),o.getWidth()===2&&(r+=1))}if(r<0)return[i,l]}i++,a=0}return[i,a]}},Kd=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function qd(e,t){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}var Vd=class{constructor(t=qd,i={}){this._handler=t,this._options=i}activate(t){this._terminal=t;let i=this._options,s=i.urlRegex||Kd;this._linkProvider=this._terminal.registerLinkProvider(new zd(this._terminal,s,this._handler,i))}dispose(){var t;(t=this._linkProvider)==null||t.dispose()}};class Gd{constructor(){D(this,"commands",[])}register(...t){this.commands.push(...t)}find(t){let i;for(const s of this.commands)s.matches(t)&&(!i||s.name.length>i.name.length)&&(i=s);return i}all(){return this.commands}}class te{constructor(){D(this,"aliases",[]);D(this,"params")}matches(t){const i=t.toLowerCase().trim(),s=r=>i===r||i.startsWith(r+" ");return s(this.name)||this.aliases.some(s)}argsAfterName(t){const i=t.toLowerCase().trim(),s=[this.name,...this.aliases].sort((r,n)=>n.length-r.length);for(const r of s)if(i.startsWith(r))return t.trim().slice(r.length).trim();return t.trim()}}const Qe="\x1B[",ee=`${Qe}0m`,Rt=`${Qe}1m`,Yd=`${Qe}2m`,Xd=`${Qe}3m`,_s=`${Qe}32m`,Qt=`${Qe}31m`,Bi=`${Qe}33m`,Ea=`${Qe}36m`,Mi=`${Qe}34m`,Ht=`${Qe}90m`,Jd=`${Qe}92m`,Zd=`${Qe}96m`;function zn(e,t){switch(t){case"success":return`${_s}${e}${ee}`;case"error":return`${Qt}${e}${ee}`;case"warning":return`${Bi}${e}${ee}`;case"info":return`${Ea}${e}${ee}`;case"value":return`${Mi}${e}${ee}`;case"system":return`${Ht}${e}${ee}`;default:return e}}function it(e){return`${Rt}${e}${ee}`}function Ae(e){return`${Yd}${e}${ee}`}function Qd(e){return`${Bi}${e}${ee}`}function y(e){return`${Mi}${e}${ee}`}function w(e){return`${Ht}${e}${ee}`}function b(e,t){return`${Ht}${e}: ${ee}${Mi}${Rt}${t}${ee}`}function E(e,t,i=22){const s=e.split(" "),r=s[0];let n=Ea;r==="get"?n=_s:r==="set"&&(n=Bi);const o=s.length>1?`${n}${Rt}${r}${ee} ${Mi}${s.slice(1).join(" ")}${ee}`:`${n}${Rt}${e}${ee}`,a=" ".repeat(Math.max(1,i-e.length));return`  ${o}${a}${Ht}${t}${ee}`}function W(e){return`${Rt}${Mi}${e}${ee}`}function st(e){return`${Ht}${Xd}${e}${ee}`}function eu(e){return`\x1B[1;92m${e||"user"}@pyMC${ee}: \x1B[38;2;91;91;214m$${ee} `}function Bs(e){return`${Qt}${Rt}●${ee} ${Ht}${e}${ee}`}function tu(e){return e<1500?Jd:e<4e3?_s:e<8e3?Bi:e<15e3?Qt:`${Qt}${Rt}`}function iu(e){const t=e<1e3?`${e.toFixed(0)}ms`:`${(e/1e3).toFixed(1)}s`;return`${tu(e)}${t}${ee}`}function Ir(e){switch(e){case"excellent":return Zd;case"good":return _s;case"fair":return Bi;case"poor":return Qt;case"critical":return`${Qt}${Rt}`;default:return Ht}}function su(e,t){return`${Ir(t)}${e}${ee}`}function Un(e){return e.replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}\uFE0F\u200D]/gu,"").trim()}const Hi="\x1B[2K\r";function ru(e=1){return`\x1B[${e}A`}const nu="\x1B[K",ou="\x1B[H",au="\x1B[J",lu="\x1B[?1049h",jn="\x1B[?1049l",hu="\x1B[?25l",Kn="\x1B[?25h";function Ra(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function cu(e){return Ra(e).length}function wr(e,t){let i=0;for(const s of e){const r=Ra(s).length;i+=r===0?1:Math.ceil(r/t)}return i}function du(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function et(e,t){return du(e)||t}function uu(){return document.documentElement.dataset.mode==="light"}function Ba(){const e=uu(),t=et("--terminal-bg","#0d0d0d"),i=et("--sys-blue",pe.blue);if(e){const f="#EFF0F1";return{background:f,foreground:"#111314",cursor:pe.blue,cursorAccent:f,selectionBackground:`${pe.blue}30`,selectionForeground:"#111314",black:"#111314",red:pe.red,green:pe.green,yellow:pe.amber,blue:pe.blue,magenta:pe.purple,cyan:pe.cyan,white:f,brightBlack:si[500],brightRed:pe.red,brightGreen:pe.green,brightYellow:pe.orange,brightBlue:pe.indigo,brightMagenta:pe.pink,brightCyan:pe.teal,brightWhite:si[600]}}const s=et("--text-primary","#e0e0e0"),r=i+"40",n=et("--sys-red",pe.red),o=et("--sys-green",pe.green),a=et("--sys-purple",pe.purple),h=et("--sys-blue",pe.blue),l=et("--sys-cyan",pe.cyan),c=et("--text-muted",si[500]),d=et("--text-secondary",si[400]),u=et("--bg-surface",si[900]);return{background:t,foreground:s,cursor:i,cursorAccent:t,selectionBackground:r,selectionForeground:s,black:u,red:n,green:o,yellow:a,blue:h,magenta:a,cyan:l,white:s,brightBlack:c,brightRed:n,brightGreen:"#4ADE80",brightYellow:a,brightBlue:h,brightMagenta:a,brightCyan:l,brightWhite:d}}function _u(e){return Ka.subscribe(()=>{e.options.theme=Ba()})}const Li="\x1B[",Bt=`${Li}0m`,fu=`${Li}1m`,pu=`${Li}2m`,Ma=`${Li}34m`,Di=`${Li}90m`,Ms=24,Ls=13,qn="  ",Vn="        ",mu=[{label:"INFORMATION",entries:[{cmd:"status",desc:"Repeater status summary",alias:"st"},{cmd:"top",desc:"Live system overview (Ctrl+C to exit)",alias:"htop"},{cmd:"ver",desc:"Version info",alias:"version"},{cmd:"clock",desc:"System UTC time"},{cmd:"uptime",desc:"System uptime"},{cmd:"board",desc:"Board / platform info"},{cmd:"packets",desc:"Packet statistics"},{cmd:"stats-packets",desc:"Packet counters (firmware compat)"},{cmd:"stats-radio",desc:"Radio health stats (firmware compat)"},{cmd:"stats-core",desc:"Engine vitals (firmware compat)"}]},{label:"NETWORK",entries:[{cmd:"neighbors [sort]",desc:"Direct RF neighbors",alias:"nb",sub:"sig · name · rssi · snr · dist · heard"},{cmd:"ping {name}",desc:"Ping neighbor (name or 0xXX)"},{cmd:"identities",desc:"List configured identities",alias:"id ids"},{cmd:"keys",desc:"Transport keys"},{cmd:"acl",desc:"ACL statistics"},{cmd:"rooms",desc:"Room statistics"}]},{label:"RADIO",entries:[{cmd:"get {param}",desc:"Read parameter"},{cmd:"set {param} {value}",desc:"Write parameter"},{cmd:"advert",desc:"Send advertisement"}]},{label:"SYSTEM",entries:[{cmd:"restart",desc:"Restart service",alias:"reboot"},{cmd:"start cap [seconds]",desc:"Start packet capture"},{cmd:"end cap",desc:"Stop capture"},{cmd:"list cap",desc:"List captures"},{cmd:"export cap [id]",desc:"Download capture"}]},{label:"TOOLS",entries:[{cmd:"convert hex {value}",desc:"Hex → base64"},{cmd:"convert base64 {value}",desc:"Base64 → hex"},{cmd:"clear",desc:"Clear terminal",alias:"cls"},{cmd:"help [command]",desc:"Show this help",alias:"? h"}]}],gu=[{cat:"Identity",params:["name","role","lat","lon","public.key"]},{cat:"Radio",params:["radio","freq","tx","bw","sf","cr"]},{cat:"Timing",params:["txdelay","direct.txdelay","rxdelay"]},{cat:"Repeater",params:["mode","duty","repeat","flood.max","advert.interval"]},{cat:"Advanced",params:["multi.acks","int.thresh","agc.reset.interval"]},{cat:"set only",params:["log","prv.key"]}];function La(e){return`${Di}${"─".repeat(e)}${Bt}`}function vu(e){const t="pymc console",i="terminal",s=Math.max(3,e-t.length-i.length-6);return`  ${Ma}${fu}${t}${Bt} ${La(s)} ${Di}${i}${Bt}`}function Da(e){return`  ${Di}${e}${Bt}`}function Su(e,t){const i=[],s=e.alias?`  ${pu}${e.alias}${Bt}`:"";return 4+Math.max(e.cmd.length,Ms)+e.desc.length+(e.alias?2+e.alias.length:0)<=t?i.push(qn+E(e.cmd,e.desc,Ms)+s):(i.push(qn+E(e.cmd,"",Ms)),i.push(Vn+w(e.desc)+s)),e.sub&&i.push(`${Vn}${Ae("└ "+e.sub)}`),i}function Gn(e){return e.split(" · ").map(t=>`${Ma}${t}${Bt}`).join(`${Di} · ${Bt}`)}function yu(e,t){const s=[];let r=[],n=0;for(const o of e){const a=r.length>0?3+o.length:o.length;n+a>t&&r.length>0?(s.push(r),r=[o],n=o.length):(r.push(o),n+=a)}return r.length>0&&s.push(r),s}function wu(e){const t=["",Da("GET/SET QUALIFIERS")],i=Math.max(20,e-4-Ls);for(const s of gu){const r=`${Di}${s.cat.padEnd(Ls)}${Bt}`,n=yu(s.params,i),o=" ".repeat(4+Ls);t.push(`    ${r}${Gn(n[0].join(" · "))}`);for(let a=1;a<n.length;a++)t.push(`${o}${Gn(n[a].join(" · "))}`)}return t}function bu(e){const t=Math.min(e-4,56);return[`  ${La(t)}`,`  ${st("<command> help for detailed usage")}`]}class Cu extends te{constructor(i){super();D(this,"name","help");D(this,"description","Show available commands");D(this,"aliases",["?","h"]);this.registry=i}execute({output:i,rawInput:s,cols:r}){const n=this.argsAfterName(s).toLowerCase().trim();if(n&&n!=="help"){const a=this.registry.find(n+" help")||this.registry.find(n);if(a){a.execute({output:i,rawInput:a.name+" help",args:[a.name,"help"],cols:r,signal:new AbortController().signal});return}i.write(`Unknown command: ${y(n)}`,"warning");return}const o=[vu(r),""];for(const a of mu){o.push(Da(a.label));for(const h of a.entries)o.push(...Su(h,r));a.label==="RADIO"&&o.push(...wu(r)),o.push("")}o.push(...bu(r)),i.write(o.join(`
`))}}class xu extends te{constructor(){super(...arguments);D(this,"name","clear");D(this,"description","Clear terminal screen");D(this,"aliases",["cls"])}execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("clear"),`  ${w("Clear all terminal output.")}`,"",E("clear","clear the screen"),"",W("Aliases"),`  ${w("cls")}`].join(`
`));return}i.clear()}}function Or(e){const t=Math.floor(e/86400),i=Math.floor(e%86400/3600),s=Math.floor(e%3600/60);return t>0?`${t}d ${i}h ${s}m`:i>0?`${i}h ${s}m`:`${s}m`}class ku extends te{constructor(){super(...arguments);D(this,"name","status");D(this,"description","Get repeater status summary");D(this,"aliases",["st"])}async execute({output:i,rawInput:s}){var n,o,a;if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("status"),`  ${w("Show a quick summary of mode, neighbor count, and uptime.")}`,"",E("status","show summary"),"",W("Aliases"),`  ${w("st")}`].join(`
`));return}const r=i.write("processing...","system");try{const h=await rt(),l=((o=(n=h.config)==null?void 0:n.repeater)==null?void 0:o.mode)||"unknown",c=Object.keys(h.neighbors||{}).length,d=Object.values(h.neighbors||{}).filter(_=>_.zero_hop).length,u=((a=h.config)==null?void 0:a.node_name)||h.node_name||"unknown",f=Or(h.uptime_seconds||0);i.update(r,[`${it(u)}  ${w("repeater")}`,"",`  ${b("Mode",y(l))}`,`  ${b("Neighbors",`${y(String(d))} direct  ${w(`${c} total`)}`)}`,`  ${b("RX / TX",`${y(String(h.rx_count??0))} / ${y(String(h.tx_count??0))}`)}`,`  ${b("Uptime",y(f))}`].join(`
`))}catch(h){i.update(r,`Error: ${h instanceof Error?h.message:"Command failed"}`,"error")}}}class Eu extends te{constructor(){super(...arguments);D(this,"name","uptime");D(this,"description","Show system uptime")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("uptime"),`  ${w("Display how long the repeater service has been running.")}`,"",E("uptime","show uptime")].join(`
`));return}const r=i.write("processing...","system");try{const n=await rt();i.update(r,b("Uptime",y(Or(n.uptime_seconds||0))))}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class Ru extends te{constructor(){super(...arguments);D(this,"name","packets");D(this,"description","Show packet statistics")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("packets"),`  ${w("Display packet counters (received, transmitted, forwarded, dropped).")}`,"",E("packets","show packet stats")].join(`
`));return}const r=i.write("processing...","system");try{const n=await rt(),o=(n.rx_count??0)+(n.tx_count??0);i.update(r,[W("Packet Stats")+`  ${w(`${o} total`)}`,"",`  ${b("Received",y(String(n.rx_count??0)))}`,`  ${b("Transmitted",y(String(n.tx_count??0)))}`,`  ${b("Forwarded",y(String(n.forwarded_count??0)))}`,`  ${b("Dropped",y(String(n.dropped_count??0)))}`].join(`
`))}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}function Kt(e){return e>=1073741824?`${(e/1073741824).toFixed(1)} GB`:e>=1048576?`${(e/1048576).toFixed(0)} MB`:`${(e/1024).toFixed(0)} KB`}function Ds(e){const t=Math.floor(e/86400),i=Math.floor(e%86400/3600),s=Math.floor(e%3600/60);return t>0?`${t}d ${i}h ${s}m`:i>0?`${i}h ${s}m`:`${s}m`}class Bu extends te{constructor(){super(...arguments);D(this,"name","board");D(this,"description","Show board/platform info")}async execute({output:i,rawInput:s}){var n;if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("board"),`  ${w("Display platform and hardware information.")}`,"",E("board","show board info")].join(`
`));return}const r=i.write("loading...","system");try{const[o,a]=await Promise.all([es(),rt()]),h=[];if(h.push(`  ${b("Node",y(a.node_name||"Unknown"))}`),h.push(`  ${b("Runtime",y(`pyMC_Repeater v${a.version||"?"}`))}`),a.core_version&&h.push(`  ${b("Core",y(a.core_version))}`),h.push(""),o.success&&o.data){const l=o.data;h.push(`  ${b("CPU",y(`${l.cpu.usage_percent.toFixed(1)}%`))}  ${w(`${l.cpu.count} core${l.cpu.count>1?"s":""}`)}`),l.cpu.load_avg&&h.push(`  ${b("Load",y(`${l.cpu.load_avg["1min"].toFixed(2)} / ${l.cpu.load_avg["5min"].toFixed(2)} / ${l.cpu.load_avg["15min"].toFixed(2)}`))}`);const c=Object.entries(l.temperatures||{});if(c.length>0){const d=c[0];h.push(`  ${b("Temp",y(`${d[1].toFixed(1)}°C`))}${c.length>1?`  ${w(c.slice(1).map(([u,f])=>`${u}: ${f.toFixed(1)}°C`).join(", "))}`:""}`)}h.push(""),h.push(`  ${b("Memory",y(`${Kt(l.memory.used)} / ${Kt(l.memory.total)}`))}  ${w(`${l.memory.usage_percent.toFixed(0)}%`)}`),h.push(`  ${b("Disk",y(`${Kt(l.disk.used)} / ${Kt(l.disk.total)}`))}  ${w(`${l.disk.usage_percent.toFixed(0)}%`)}`),h.push(""),(n=l.system)!=null&&n.uptime&&h.push(`  ${b("System uptime",y(Ds(l.system.uptime)))}`),h.push(`  ${b("Service uptime",y(Ds(a.uptime_seconds)))}`),l.network&&h.push(`  ${b("Net TX/RX",y(`${Kt(l.network.bytes_sent)} / ${Kt(l.network.bytes_recv)}`))}`)}else h.push(`  ${b("Platform",y("Linux"))}`),h.push(`  ${b("Service uptime",y(Ds(a.uptime_seconds)))}`),h.push(`  ${w("Hardware stats unavailable")}`);i.update(r,h.join(`
`),"value")}catch(o){i.update(r,`Error: ${o instanceof Error?o.message:"Failed to load hardware stats"}`,"error")}}}const Yi="\x1B[0m",Xi="\x1B[1m",br="\x1B[2m",Yn="\x1B[36m",Xn="\x1B[96m",Mu="\x1B[97m",Lu="\x1B[93m",qe=48,Du=14,wt=22,gi=5,Ji=22,Tu=5,$u=wt+gi+Ji+Tu,Au=50;function Ta(e,t,i,s){return r=>{if(r<=0)return 0;if(r>=1)return 1;let n=r;for(let o=0;o<8;o++){const a=3*(1-n)*(1-n)*n*e+3*(1-n)*n*n*i+n*n*n-r,h=3*(1-n)*(1-n)*e+6*(1-n)*n*(i-e)+3*n*n*(1-i);if(Math.abs(h)<1e-7)break;n=Math.max(0,Math.min(1,n-a/h))}return 3*(1-n)*(1-n)*n*t+3*(1-n)*n*n*s+n*n*n}}const Pu=Ta(.25,1,.5,1),Nu=Ta(.4,0,1,1);function Iu(e,t){const i=e%Du;return Math.sin(.45*i+.04*i*i+t*.25)}const Ou=[1,2,4,64],Fu=[8,16,32,128],Jn=Ou.map((e,t)=>e|Fu[t]);function Yt(e,t,i,s){s<4?e[i]|=Jn[s]:t[i]|=Jn[s-4]}function Hu(e){return e>.8?Mu+Xi:e>.6?Lu+Xi:e>.4?Xn+Xi:e>.2?Xn:e>.08?Yn:Yn+br}function Zn(e,t,i){const s=new Uint8Array(qe),r=new Uint8Array(qe),n=new Float32Array(qe),o=e*.35;for(let a=0;a<qe;a++){const h=i?qe-1-a:a;if(h>=t)continue;const l=t-h,c=Math.min(1,l/3),d=Math.min(1,h/2),u=l<5?1+.3*(1-l/5):1,f=Math.min(1,c*d*u);if(f<.04)continue;const _=1+.06*Math.sin(e*.7+h*.3),g=Iu(h,o)*f*_*3.5+3.5,x=Math.abs(g-3.5)/3.5,z=l<6?1-l/6:0;n[a]=Math.min(1,x*.65+z*.35)*f;const O=Math.max(0,Math.min(7,Math.round(g)));if(g>=3.5){for(let N=3;N<=O;N++)Yt(s,r,a,N);const M=Math.round((g-3.5)*.4);for(let N=Math.max(0,3-M);N<3;N++)Yt(s,r,a,N)}else{for(let N=O;N<=4;N++)Yt(s,r,a,N);const M=Math.round((3.5-g)*.4);for(let N=5;N<=Math.min(7,4+M);N++)Yt(s,r,a,N)}}return{top:s,bot:r,heat:n}}function Qn(e,t,i){const s=new Uint8Array(qe),r=new Uint8Array(qe),n=new Float32Array(qe),o=Math.exp(-t*.5),a=Math.max(0,10-t*2.5),h=.7+t*.2;for(let l=0;l<Math.ceil(a);l++){const c=e?qe-1-l:l;if(c<0||c>=qe)continue;const d=o*(1-l/a);if(d<.04)continue;n[c]=d;const f=Math.sin(l*h+i*.6)*d*3.5+3.5,_=Math.max(0,Math.min(7,Math.round(f)));if(f>=3.5)for(let p=3;p<=_;p++)Yt(s,r,c,p);else for(let p=_;p<=4;p++)Yt(s,r,c,p)}return{top:s,bot:r,heat:n}}function eo(e,t){let i="",s="";for(let r=0;r<qe;r++){const n=String.fromCodePoint(10240+e[r]),o=e[r]?Hu(t[r]):"";o!==s&&(i+=o,s=o),i+=n}return i+Yi}function to(e,t,i){const s=e%$u;let r,n,o;if(s<wt){const l=s/(wt-1);({top:r,bot:n,heat:o}=Zn(e,Math.round(Pu(l)*qe),!1))}else if(s<wt+gi)({top:r,bot:n,heat:o}=Qn(!0,s-wt,e));else if(s<wt+gi+Ji){const l=(s-wt-gi)/(Ji-1);({top:r,bot:n,heat:o}=Zn(e,Math.round(Nu(l)*qe),!0))}else({top:r,bot:n,heat:o}=Qn(!1,s-wt-gi-Ji,e));const a=(i/1e3).toFixed(1),h=`${br} ── chirp → ${Yi}${Xi}${t}${Yi}${br} ── ${a}s${Yi}`;return[eo(r,o),eo(n,o),h]}function $a(e,t){const i=Date.now();let s=0;const r=e.write(to(0,t,0).join(`
`)),n=setInterval(()=>{s++,e.update(r,to(s,t,Date.now()-i).join(`
`))},Au);return{id:r,stop:()=>clearInterval(n)}}class Wu extends te{constructor(){super(...arguments);D(this,"name","advert");D(this,"description","Send repeater advertisement")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("advert"),`  ${w("Broadcast a repeater advertisement to the mesh network.")}`,"",E("advert","send advert now"),"",st("Adverts announce this repeater's presence to neighbors.")].join(`
`));return}const r=$a(i,"broadcast");try{const n=await qa();r.stop(),n.success?i.update(r.id,`✓ ${y("Advert sent")}`,"success"):i.update(r.id,`Error: ${n.error||"Failed"}`,"error")}catch(n){r.stop(),i.update(r.id,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}const zu=["sig","name","rssi","snr","dist","heard"],io={excellent:5,good:4,fair:3,poor:2,critical:1};function so(e){const t=Math.floor(Date.now()/1e3-e);return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`}function Uu(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}function ro(e){return e<1e3?`${Math.round(e)}m`:`${(e/1e3).toFixed(1)}km`}const ju={excellent:5,good:4,fair:3,poor:2,critical:1};function no(e){const t=ju[e]??0,i=Ir(e),s=t>0?`${i}${"█".repeat(t)}${ee}`:"",r=w("⣿".repeat(5-t));return s+r}const oo=3.5;function Ku(e){var i;const t=(i=e.config)==null?void 0:i.radio;return!(t!=null&&t.spreading_factor)||!(t!=null&&t.bandwidth)?null:{sf:t.spreading_factor,bwHz:t.bandwidth}}function qu(e){var i;const t=(i=e.config)==null?void 0:i.repeater;return!t||!xo(t.latitude,t.longitude)?null:{lat:t.latitude,lon:t.longitude}}function qt(e,t=i=>i){return{text:e,color:t}}function Vu(e,t){return{text:e,color:i=>i,rendered:t}}function Ts(e){return w("+"+e.map(t=>"-".repeat(t+2)).join("+")+"+")}function ao(e,t){const i=e.map((s,r)=>{if(s.rendered!=null){const n=Math.max(0,t[r]-s.text.length);return" "+s.rendered+" ".repeat(n)+" "}return" "+s.color(Uu(s.text,t[r]))+" "});return w("|")+i.join(w("|"))+w("|")}const Gu=70,Yu=55;class Xu extends te{constructor(){super(...arguments);D(this,"name","neighbors");D(this,"description","Show direct RF neighbors with signal stats");D(this,"aliases",["nb","get neighbors","get neighbor"]);D(this,"params","[sig|name|rssi|snr|dist|heard]")}async execute(i){const{output:s,cols:r}=i,n=this.argsAfterName(i.rawInput).toLowerCase().trim();if(n==="help"){this.printUsage(s);return}const o=zu.includes(n)?n:null,a=s.write("processing...","system");try{const h=await rt(),l=h.neighbors||{},c=Object.entries(l).filter(([,g])=>g.zero_hop);if(c.length===0){const g=Object.keys(l).length;s.update(a,g>0?`No direct neighbors. ${g} relayed neighbor${g!==1?"s":""} known.`:"No neighbors discovered yet.","warning");return}const d=Ku(h),u=qu(h),f=h.noise_floor_dbm;this.sortNeighbors(c,o,d,u,f);const _=o?`  ${Ae(`sorted by ${o}`)}`:"",p=[W(`Direct Neighbors (${c.length})`)+_,""];if(r<Yu)for(const[g,x]of c)p.push(...this.cardLayout(g,x,d,u,f));else{const g=r>=Gu&&u!=null,x=c.map(([J,Te])=>this.buildRow(J,Te,d,u,f,g)),z=g?["SIG","NAME","RSSI","SNR","DIST","HEARD"]:["SIG","NAME","RSSI","SNR","HEARD"],O=z.slice(1).map((J,Te)=>Math.max(J.length,...x.map(X=>X[Te+1].text.length))),M=5,N=O.reduce((J,Te)=>J+Te+3,0),K=Math.max(4,r-N-M-7),ie=Math.min(K,Math.max(4,...x.map(J=>J[1].text.length))),ae=[M,ie,...O.slice(1)];p.push(Ts(ae),...x.map(J=>ao(J,ae)),Ts(ae),ao(z.map(J=>qt(J,it)),ae),Ts(ae)),p.push(this.footer(d,f))}s.update(a,p.join(`
`))}catch(h){s.update(a,`Error: ${h instanceof Error?h.message:"Command failed"}`,"error")}}sortNeighbors(i,s,r,n,o){switch(s){case"sig":i.sort(([,a],[,h])=>{const l=io[this.gradeNeighbor(a,r,o)]??0,c=io[this.gradeNeighbor(h,r,o)]??0;return l-c});break;case"name":i.sort(([a,h],[l,c])=>{const d=(h.name||h.node_name||a.slice(0,8)).toLowerCase(),u=(c.name||c.node_name||l.slice(0,8)).toLowerCase();return d.localeCompare(u)});break;case"rssi":i.sort(([,a],[,h])=>(a.rssi??-999)-(h.rssi??-999));break;case"snr":i.sort(([,a],[,h])=>(a.snr??-999)-(h.snr??-999));break;case"dist":i.sort(([,a],[,h])=>{const l=this.distTo(a,n)??1/0,c=this.distTo(h,n)??1/0;return l-c});break;case"heard":i.sort(([,a],[,h])=>(a.last_seen||0)-(h.last_seen||0));break;default:i.sort(([,a],[,h])=>(h.last_seen||0)-(a.last_seen||0))}}gradeNeighbor(i,s,r){const n=i.rssi!=null?i.rssi-oo:null,o=r!=null&&r>-100?1:0,a=Co(i.snr??null,n,s,o);return(a==null?void 0:a.finalGrade)??"critical"}distTo(i,s){return!s||!xo(i.latitude,i.longitude)?null:Va(s.lat,s.lon,i.latitude,i.longitude)}buildRow(i,s,r,n,o,a){const h=this.gradeNeighbor(s,r,o),l=Un(s.name||s.node_name||i.slice(0,8))||i.slice(0,8),c=s.rssi!=null?`${s.rssi} dBm`:"-",d=s.snr!=null?`${s.snr} dB`:"-",u=s.last_seen?so(s.last_seen):"-",f=no(h),_=[Vu("|||||",f),qt(l,it),qt(c,y),qt(d,y)];if(a){const p=this.distTo(s,n);_.push(qt(p!=null?ro(p):"-",Ae))}return _.push(qt(u,Ae)),_}cardLayout(i,s,r,n,o){const a=this.gradeNeighbor(s,r,o),h=Un(s.name||s.node_name||i.slice(0,8))||i.slice(0,8),l=s.rssi!=null?`${s.rssi}`:"-",c=s.snr!=null?`${s.snr}`:"-",d=s.last_seen?so(s.last_seen):"-",u=this.distTo(s,n),f=u!=null?`  ${w("dist")} ${y(ro(u))}`:"";return[`${no(a)} ${it(h)}`,`  ${w("rssi")} ${y(l)}  ${w("snr")} ${y(c)}${f}  ${Ae(d)}`,""]}footer(i,s){const r=[];return i&&r.push(`SF${i.sf}/${i.bwHz>=1e3?i.bwHz/1e3+"kHz":i.bwHz+"Hz"}`),r.push(`ant ${oo}dBi`),s!=null&&r.push(`nf ${s}dBm`),w(r.join("  "))}printUsage(i){const s=[W("neighbors"),`  ${w("Show direct RF neighbors with signal quality, RSSI, SNR, and distance.")}`,"",W("Usage"),E("neighbors","default sort (most recent)"),E("neighbors sig","sort by signal grade (weakest first)"),E("neighbors name","sort alphabetically"),E("neighbors rssi","sort by RSSI (weakest first)"),E("neighbors snr","sort by SNR (lowest first)"),E("neighbors dist","sort by distance (closest first)"),E("neighbors heard","sort by last seen (oldest first)"),E("neighbors help","show this help"),"",W("Aliases"),`  ${w("nb, get neighbors, get neighbor")}`,"",st("Signal bars factor radio config, noise floor, and 3.5 dBi antenna gain."),st("Only zero-hop (direct RF) neighbors are shown.")];i.write(s.join(`
`))}}class Ju extends te{constructor(){super(...arguments);D(this,"name","get");D(this,"description","Get repeater parameter");D(this,"params","{parameter}")}async execute({output:i,rawInput:s}){const r=this.argsAfterName(s).toLowerCase().trim();if(r==="help"||!r){i.write([W("get"),`  ${w("Read a repeater configuration parameter.")}`,"",W("Identity"),E("get name","node name"),E("get role","node role"),E("get public.key","public key"),"",W("Location"),E("get lat","latitude"),E("get lon","longitude"),"",W("Radio"),E("get radio","full radio summary"),E("get freq","frequency (MHz)"),E("get tx","TX power (dBm)"),E("get bw","bandwidth (kHz)"),E("get sf","spreading factor"),E("get cr","coding rate"),"",W("Timing"),E("get af","airtime factor (pending backend)"),E("get txdelay","TX delay factor"),E("get direct.txdelay","direct TX delay"),E("get rxdelay","RX delay base"),"",W("Repeater"),E("get mode","forward or monitor"),E("get flood.max","max flood hops"),E("get advert.interval","advert interval"),E("get duty","duty cycle state"),"",W("Advanced"),E("get multi.acks","multi-ack count"),E("get int.thresh","interference threshold (dBm)"),E("get agc.reset.interval","AGC reset interval")].join(`
`));return}const n=i.write("processing...","system");try{const o=await rt(),{result:a,type:h}=Zu(r,o);i.update(n,a,h)}catch(o){i.update(n,`Error: ${o instanceof Error?o.message:"Command failed"}`,"error")}}}function Zu(e,t){const i=t.config||{},s=i.radio||{},r=i.repeater||{},n=i.delays||{},o=i.duty_cycle||{},a=(h,l)=>({result:b(h,y(l)),type:"value"});switch(e){case"name":return a("name",i.node_name||"Unknown");case"role":return a("role","repeater");case"lat":return a("lat",r.latitude!=null?String(r.latitude):"not set");case"lon":return a("lon",r.longitude!=null?String(r.longitude):"not set");case"freq":return a("freq",s.frequency?`${(s.frequency/1e6).toFixed(3)} MHz`:"?");case"tx":return a("tx",s.tx_power!=null?`${s.tx_power} dBm`:"?");case"bw":return a("bw",s.bandwidth?`${s.bandwidth/1e3} kHz`:"?");case"sf":return a("sf",String(s.spreading_factor??"?"));case"cr":return a("cr",s.coding_rate?`4/${s.coding_rate}`:"?");case"radio":return s.frequency?{result:[`  ${b("freq",y(`${(s.frequency/1e6).toFixed(3)} MHz`))}`,`  ${b("bw",y(`${s.bandwidth/1e3} kHz`))}`,`  ${b("sf",y(String(s.spreading_factor)))}`,`  ${b("cr",y(`4/${s.coding_rate}`))}`,`  ${b("tx",y(`${s.tx_power} dBm`))}`].join(`
`),type:"value"}:a("radio","?");case"af":case"airtime.factor":return{result:`${w("airtime_factor is not yet exposed by the pyMC_Repeater API.")}
${w("Firmware range: 0-9. Controls airtime budget fraction.")}
${w("Tracked in CLI-Alignment.md — needs backend support.")}`,type:"warning"};case"txdelay":return a("txdelay",String(n.tx_delay_factor??"1.0"));case"direct.txdelay":return a("direct.txdelay",String(n.direct_tx_delay_factor??"0.5"));case"rxdelay":return a("rxdelay",String(n.rx_delay_base??"0.0"));case"mode":return a("mode",r.mode||"forward");case"repeat":return a("repeat",r.mode==="forward"?"on":"off");case"flood.max":return a("flood.max",String(r.max_flood_hops??"3"));case"flood.advert.interval":return a("flood.advert.interval",r.send_advert_interval_hours!=null?`${r.send_advert_interval_hours}h`:"?");case"advert.interval":return a("advert.interval",r.advert_interval_minutes!=null?`${r.advert_interval_minutes}m`:"120m");case"duty":case"duty.enabled":return a("duty",o.enforcement_enabled?"on":"off");case"duty.max":return a("duty.max",o.max_airtime_percent!=null?`${o.max_airtime_percent}%`:"?");case"multi.acks":return a("multi.acks",String(r.multi_acks??"0"));case"int.thresh":return a("int.thresh",`${r.interference_threshold??-120} dBm`);case"agc.reset.interval":return a("agc.reset.interval",String(r.agc_reset_interval??"0"));case"public.key":return a("public.key",t.public_key||"not available");case"prv.key":return{result:`${w("Private key stored in /etc/pymc_repeater/config.yaml")}

  ${b("view",y("sudo grep identity_key /etc/pymc_repeater/config.yaml"))}
  ${b("set",y("sudo ./convert_firmware_key.sh <64-byte-hex>"))}`,type:"info"};case"guest.password":case"allow.read.only":return{result:`${w("Security settings not exposed via stats API.")}
${w("Check /etc/pymc_repeater/config.yaml")}`,type:"warning"};default:return{result:`Unknown parameter: ${y(e)}
${w('Run "get help" to see available parameters.')}`,type:"error"}}}class Qu extends te{constructor(){super(...arguments);D(this,"name","set");D(this,"description","Set repeater parameter");D(this,"params","{parameter} {value}")}async execute({output:i,rawInput:s}){var l;const n=this.argsAfterName(s).split(/\s+/),o=(l=n[0])==null?void 0:l.toLowerCase(),a=n.slice(1).join(" ");if(o==="help"||!o){i.write([W("set"),`  ${w("Write a repeater configuration parameter.")}`,"",W("Identity"),E("set name <name>","node name"),E("set lat <deg>","latitude (-90 to 90)"),E("set lon <deg>","longitude (-180 to 180)"),"",W("Radio"),E("set freq <MHz>","frequency"),E("set tx <dBm>","TX power (2-22)"),E("set bw <kHz>","bandwidth"),E("set sf <5-12>","spreading factor"),E("set cr <5-8>","coding rate"),"",W("Timing"),E("set af <0-9>","airtime factor (pending backend)"),E("set txdelay <0-5>","TX delay factor"),E("set direct.txdelay <0-5>","direct TX delay"),E("set rxdelay <n>","RX delay base"),"",W("Repeater"),E("set mode <fwd|mon>","forward or monitor"),E("set flood.max <0-64>","max flood hops"),E("set advert.interval <m>","advert interval (min)"),E("set duty <on|off>","duty cycle enforcement"),E("set log <level>","log level"),"",W("Advanced"),E("set multi.acks <n>","multi-ack count"),E("set int.thresh <dBm>","interference threshold"),E("set agc.reset.interval <n>","AGC reset interval (x4)"),"",st("Some changes require a service restart.")].join(`
`));return}const h=i.write("processing...","system");try{const{result:c,type:d}=await e_(o,a,s);i.update(h,c,d)}catch(c){i.update(h,`Error: ${c instanceof Error?c.message:"Command failed"}`,"error")}}}async function e_(e,t,i){switch(e){case"mode":return t_(t);case"duty":return i_(t);case"tx":return ze("tx_power",Vt(t,2,22,"TX power must be 2-22 dBm"));case"sf":return ze("spreading_factor",Vt(t,5,12,"SF must be 5-12"));case"af":case"airtime.factor":return{result:`Error: airtime_factor is not yet exposed by the pyMC_Repeater API.
Firmware range: 0-9. Tracked in CLI-Alignment.md — needs backend support.`,type:"info"};case"txdelay":return ze("tx_delay_factor",ci(t,0,5,"TX delay must be 0.0-5.0"));case"direct.txdelay":return ze("direct_tx_delay_factor",ci(t,0,5,"Direct TX delay must be 0.0-5.0"));case"rxdelay":return ze("rx_delay_base",r_(t,0,"RX delay must be >= 0"));case"flood.max":return ze("max_flood_hops",Vt(t,0,64,"Max flood hops must be 0-64"));case"log":return s_(t);case"multi.acks":return ze("multi_acks",Vt(t,0,255,"Multi-acks must be 0-255"));case"int.thresh":return ze("interference_threshold",Vt(t,-200,0,"Interference threshold must be -200 to 0 dBm"));case"agc.reset.interval":{const s=As(t);if(!s.ok)return de(s.error);if(s.value<0)return de("AGC reset interval must be >= 0");const r=Math.floor(s.value/4)*4;return $s("agc_reset_interval",r,`OK - AGC reset interval set to ${r}${r!==s.value?` (rounded from ${s.value})`:""}`)}case"name":{const s=i.trim().substring(i.toLowerCase().indexOf("name")+5).trim();return s?/[\[\]\\/\\:,?*]/.test(s)?de("Name contains invalid characters: [ ] \\ / : , ? * are not allowed"):ze("node_name",{ok:!0,value:s}):de("Node name cannot be empty")}case"lat":return ze("latitude",ci(t,-90,90,"Latitude must be -90 to 90"));case"lon":return ze("longitude",ci(t,-180,180,"Longitude must be -180 to 180"));case"freq":{const s=ci(t,100,1e3,"Frequency must be 100-1000 MHz");return s.ok?ze("frequency",{ok:!0,value:s.value*1e6}):de(s.error)}case"bw":{const s=[7.8,10.4,15.6,20.8,31.25,41.7,62.5,125,250,500],r=parseFloat(t);return isNaN(r)||!s.includes(r)?de(`BW must be one of: ${s.join(", ")} kHz`):ze("bandwidth",{ok:!0,value:r*1e3})}case"cr":return ze("coding_rate",Vt(t,5,8,"Coding rate must be 5-8"));case"advert.interval":{const s=As(t);return s.ok?s.value!==0&&(s.value<1||s.value>10080)?de("Advert interval must be 0 (off) or 1-10080 minutes"):$s("advert_interval_minutes",s.value,s.value===0?"OK - Local adverts disabled":`OK - Local advert interval set to ${s.value}m`):de(s.error)}case"flood.advert.interval":{const s=As(t);return s.ok?s.value!==0&&(s.value<3||s.value>168)?de("Flood advert interval must be 0 (off) or 3-168 hours"):$s("flood_advert_interval_hours",s.value,s.value===0?"OK - Flood adverts disabled":`OK - Flood advert interval set to ${s.value}h`):de(s.error)}case"prv.key":{const s=t.trim();return s?/^[0-9a-fA-F]+$/.test(s)?s.length!==128?de(`Key must be 64 bytes (128 hex chars), got ${s.length} chars`):{result:`To set this key, run on the Pi:

  sudo ./convert_firmware_key.sh ${s}

Then restart: sudo systemctl restart pymc-repeater`,type:"info"}:de("Private key must be a hex string"):de("Private key cannot be empty")}default:return de(`Unknown parameter: ${e}`)}}async function t_(e){const t=e.toLowerCase();return t!=="forward"&&t!=="monitor"?de('Mode must be "forward" or "monitor"'):(await Xa(t)).success?Ti(`OK - Mode set to ${t}`):de("Failed")}async function i_(e){const t=e.toLowerCase()==="on"||e==="1";return(await Ya(t)).success?Ti(`OK - Duty cycle ${t?"enabled":"disabled"}`):de("Failed")}async function s_(e){const t=e.toUpperCase();if(!["DEBUG","INFO","WARNING","ERROR"].includes(t))return de("Level must be debug, info, warning, or error");const i=await Ga(t);return i.success?Ti(`OK - Log level set to ${t}`):de(i.error||"Failed")}async function ze(e,t){if(!t.ok)return de(t.error);const i=await ko({[e]:t.value});if(!i.success)return de(i.error||"Failed");let s=`OK - ${e} set to ${t.value}`;return i.restart_required&&(s+=`
⚠ Service restart required for changes to take effect
Run: sudo systemctl restart pymc_repeater`),Ti(s)}async function $s(e,t,i){const s=await ko({[e]:t});if(!s.success)return de(s.error||"Failed");let r=i;return s.restart_required&&(r+=`
⚠ Service restart required for changes to take effect
Run: sudo systemctl restart pymc_repeater`),Ti(r)}function Vt(e,t,i,s){const r=parseInt(e);return isNaN(r)||r<t||r>i?{ok:!1,error:`Error: ${s}`}:{ok:!0,value:r}}function ci(e,t,i,s){const r=parseFloat(e);return isNaN(r)||r<t||r>i?{ok:!1,error:`Error: ${s}`}:{ok:!0,value:r}}function r_(e,t,i){const s=parseFloat(e);return isNaN(s)||s<t?{ok:!1,error:`Error: ${i}`}:{ok:!0,value:s}}function As(e){const t=parseInt(e);return isNaN(t)?{ok:!1,error:"Error: Expected a number"}:{ok:!0,value:t}}function Ti(e){return{result:e,type:"success"}}function de(e){return{result:`Error: ${e}`,type:"error"}}const n_={excellent:5,good:4,fair:3,poor:2,critical:1};function o_(e){const t=n_[e]??0,i=Ir(e);return(t>0?`${i}${"█".repeat(t)}${ee}`:"")+w("·".repeat(5-t))}const lo=3.5;class a_ extends te{constructor(){super(...arguments);D(this,"name","ping");D(this,"description","Ping neighbor (name or 0xXX)");D(this,"params","{target} [timeout]")}async execute({output:i,rawInput:s}){var u,f,_,p;const r=this.argsAfterName(s).trim(),n=r.split(/\s+/);if(((u=n[0])==null?void 0:u.toLowerCase())==="help"){i.write([W("ping"),`  ${w("Send a ping to a neighbor and measure round-trip time, signal quality, and path.")}`,"",E("ping <name>","ping by node name"),E("ping 0xAB","ping by hex prefix"),E("ping <name> 60","ping with custom timeout (seconds)"),"",st("Default timeout: 30s. Signal bars factor radio config and noise floor.")].join(`
`));return}const o=n[n.length-1],a=parseInt(o),h=n.length>1&&!isNaN(a)&&a>0,l=h?n.slice(0,-1).join(" "):r,c=h?a:30;if(!l){i.write([W("ping"),`  ${w("Send a ping to a neighbor and measure round-trip time.")}`,"",E("ping <name>","ping by node name"),E("ping <name> 60","with custom timeout"),"",st('Run "ping help" for full usage.')].join(`
`));return}const d=$a(i,l);try{const[g,x]=await Promise.all([pl(l,c),rt()]);if(d.stop(),g.success&&g.data){const z=g.data,O=(f=x.config)==null?void 0:f.radio,M=O!=null&&O.spreading_factor&&(O!=null&&O.bandwidth)?{sf:O.spreading_factor,bwHz:O.bandwidth}:null,N=x.noise_floor_dbm,K=N!=null&&N>-100?1:0,ie=z.rssi-lo,ae=Co(z.snr_db,ie,M,K),J=(ae==null?void 0:ae.finalGrade)??"critical",Te=o_(J),X=(_=z.path)!=null&&_.length?z.path.length:0,P=(p=z.path)!=null&&p.length?z.path.join(" > "):"direct",S=J.charAt(0).toUpperCase()+J.slice(1),L=[`${Te} ${it("Reply from")} ${y(z.target_id)}`,"",`  ${b("RTT",iu(z.rtt_ms))}`,`  ${b("RSSI",`${z.rssi} dBm`)}`,`  ${b("SNR",`${z.snr_db} dB`)}`,`  ${b("Path",P)}${X>0?w(` (${X} hop${X!==1?"s":""})`):""}`,`  ${b("Quality",su(S,J))}`],B=[];M&&B.push(`SF${M.sf}/${M.bwHz>=1e3?M.bwHz/1e3+"kHz":M.bwHz+"Hz"}`),B.push(`ant ${lo}dBi`),N!=null&&B.push(`nf ${N}dBm`),L.push("",w(B.join("  "))),i.update(d.id,L.join(`
`))}else i.update(d.id,g.error||"Ping failed","error")}catch(g){d.stop(),i.update(d.id,`Error: ${g instanceof Error?g.message:"Ping failed"}`,"error")}}}class l_ extends te{constructor(){super(...arguments);D(this,"name","convert");D(this,"description","Convert between hex and base64");D(this,"params","hex|base64 {value}")}execute({output:i,args:s}){var o;const r=(o=s[1])==null?void 0:o.toLowerCase(),n=s.slice(2).join(" ").trim();if(r==="help"||!r&&!n){i.write([W("convert"),`  ${w("Convert between hex and base64 encodings.")}`,"",E("convert hex <hex>","hex → base64"),E("convert base64 <b64>","base64 → hex"),"",st("Example: convert hex 48656C6C6F")].join(`
`));return}r==="hex"?this.hexToBase64(i,n):r==="base64"?this.base64ToHex(i,n):i.write([W("convert"),`  ${w("Convert between hex and base64 encodings.")}`,"",E("convert hex <hex>","hex → base64"),E("convert base64 <b64>","base64 → hex")].join(`
`))}hexToBase64(i,s){if(!s){i.write("Usage: convert hex <hex-string>","error");return}if(!/^[0-9a-fA-F]+$/.test(s)){i.write("Error: Input must be a hex string","error");return}if(s.length%2!==0){i.write("Error: Hex string must have even length","error");return}try{const r=new Uint8Array(s.length/2);for(let h=0;h<s.length;h+=2)r[h/2]=parseInt(s.substring(h,h+2),16);let n="";const o=8192;for(let h=0;h<r.length;h+=o)n+=String.fromCharCode.apply(null,Array.from(r.subarray(h,Math.min(h+o,r.length))));const a=typeof globalThis.btoa=="function"?globalThis.btoa(n):Buffer.from(n,"binary").toString("base64");i.write(`  ${b("hex",y(s))}
  ${b("base64",y(a))}`)}catch(r){i.write(`Error: Failed to convert - ${r instanceof Error?r.message:"unknown error"}`,"error")}}base64ToHex(i,s){if(!s){i.write("Usage: convert base64 <base64-string>","error");return}try{const r=typeof globalThis.atob=="function"?globalThis.atob(s):Buffer.from(s,"base64").toString("binary");let n="";for(let o=0;o<r.length;o++)n+=r.charCodeAt(o).toString(16).padStart(2,"0");i.write(`  ${b("base64",y(s))}
  ${b("hex",y(n.toUpperCase()))}`)}catch(r){i.write(`Error: Invalid base64 string - ${r instanceof Error?r.message:"unknown error"}`,"error")}}}const h_=10,c_=500;function d_(){const e=new Date;return`${e.toISOString().slice(0,10)}_${e.toTimeString().slice(0,8).replace(/:/g,"-")}`}function u_(e,t){const i=e.toISOString().slice(0,10),s=e.toTimeString().slice(0,5).replace(":","");return`pymc-${i}-${s}-${t}s.json`}const bt=Eo((e,t)=>({isCapturing:!1,captureStartTime:null,captureStartPacketHashes:new Set,captureTimer:null,reports:[],startCapture:i=>{const{captureTimer:s}=t();s&&clearTimeout(s),e({isCapturing:!0,captureStartTime:new Date,captureStartPacketHashes:new Set(i.map(r=>r.packet_hash))})},stopCapture:i=>{const{isCapturing:s,captureStartTime:r,captureStartPacketHashes:n,captureTimer:o}=t();if(!s||!r)return null;o&&clearTimeout(o);const a=new Date,h=Math.round((a.getTime()-r.getTime())/1e3),l=r.getTime()/1e3,c=i.filter(u=>!n.has(u.packet_hash)&&u.timestamp>=l).sort((u,f)=>u.timestamp-f.timestamp),d={id:d_(),filename:u_(r,h),startTime:r,endTime:a,durationSec:h,packetCount:c.length,packets:c,sizeBytes:c.length*c_};return e(u=>({isCapturing:!1,captureStartTime:null,captureStartPacketHashes:new Set,captureTimer:null,reports:[d,...u.reports].slice(0,h_)})),d},getReport:i=>t().reports.find(s=>s.id===i),_setTimer:i=>e({captureTimer:i})})),Aa=()=>bt(e=>e.reports);function Se(e){var t;return((t=e.match(/.{1,2}/g))==null?void 0:t.join(" ").toUpperCase())||""}function Pa(e){return e===void 0?"UNKNOWN":tl[e]??`TYPE_${e}`}function Na(e){return e===void 0?"UNKNOWN":el[e]??`ROUTE_${e}`}function __(e){const t=[];let i=0;if(e.length>=32&&(t.push({name:"public_key",offset:i,length:32,bytes:Se(ge(e.slice(i,i+32))),decoded:{value:ge(e.slice(i,i+32))}}),i+=32),e.length>=i+4){const s=e.slice(i,i+4),r=s[0]|s[1]<<8|s[2]<<16|s[3]<<24;t.push({name:"timestamp",offset:i,length:4,bytes:Se(ge(s)),decoded:{value:r>>>0,iso:new Date(r*1e3).toISOString()}}),i+=4}if(e.length>=i+64&&(t.push({name:"signature",offset:i,length:64,bytes:Se(ge(e.slice(i,i+64))),decoded:{value:ge(e.slice(i,i+64))}}),i+=64),e.length>i){const s=e[i],r=[];if(s&1&&r.push("CHAT_NODE"),s&2&&r.push("REPEATER"),s&3&&r.push("ROOM_SERVER"),s&16&&r.push("HAS_LOCATION"),s&128&&r.push("HAS_NAME"),t.push({name:"flags",offset:i,length:1,bytes:Se(ge(e.slice(i,i+1))),decoded:{value:s,binary:s.toString(2).padStart(8,"0"),flags:r}}),i+=1,s&16&&e.length>=i+8){const n=e.slice(i,i+8),o=new ArrayBuffer(8);new Uint8Array(o).set(n);const a=new DataView(o),h=a.getInt32(0,!0),l=a.getInt32(4,!0);t.push({name:"location",offset:i,length:8,bytes:Se(ge(n)),decoded:{lat_raw:h,lon_raw:l,latitude:h/1e6,longitude:l/1e6}}),i+=8}if(s&128&&e.length>i){const n=e.slice(i);let o=n.indexOf(0);o===-1&&(o=n.length);const a=new TextDecoder().decode(n.slice(0,o));t.push({name:"name",offset:i,length:o+(n[o]===0?1:0),bytes:Se(ge(n.slice(0,o+1))),decoded:{value:a,encoding:"utf-8",null_terminated:n[o]===0}})}}return t}function f_(e){if(e.length<4)return[];const t=e.slice(0,4),i=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;return[{name:"crc",offset:0,length:4,bytes:Se(ge(t)),decoded:{value:i>>>0,hex:(i>>>0).toString(16).toUpperCase().padStart(8,"0"),note:"CRC of the acknowledged packet (little-endian)"}}]}function p_(e){const t=[];if(e.length<9)return t;const i=e.slice(0,4),s=i[0]|i[1]<<8|i[2]<<16|i[3]<<24;t.push({name:"trace_tag",offset:0,length:4,bytes:Se(ge(i)),decoded:{value:s>>>0,hex:(s>>>0).toString(16).toUpperCase().padStart(8,"0")}});const r=e.slice(4,8),n=r[0]|r[1]<<8|r[2]<<16|r[3]<<24;if(t.push({name:"auth_code",offset:4,length:4,bytes:Se(ge(r)),decoded:{value:n>>>0}}),t.push({name:"flags",offset:8,length:1,bytes:Se(ge(e.slice(8,9))),decoded:{value:e[8],binary:e[8].toString(2).padStart(8,"0")}}),e.length>9){const o=e.slice(9),a=Array.from(o).map(h=>h.toString(16).toUpperCase().padStart(2,"0"));t.push({name:"target_path",offset:9,length:o.length,bytes:Se(ge(o)),decoded:{hops:a,path_string:a.join("->")}})}return t}function m_(e){if(e.length===0)return[];const t=Array.from(e).map(i=>i.toString(16).toUpperCase().padStart(2,"0"));return[{name:"path_hops",offset:0,length:e.length,bytes:Se(ge(e)),decoded:{hops:t,path_string:t.join("->")}}]}function g_(e){const t=[];if(e.length<1)return t;if(t.push({name:"channel_hash",offset:0,length:1,bytes:Se(ge(e.slice(0,1))),decoded:{value:e[0].toString(16).toUpperCase().padStart(2,"0")}}),e.length>13){const s=e.length-1-12;t.push({name:"ciphertext",offset:1,length:s,bytes:Se(ge(e.slice(1,1+s))),decoded:{length:s,note:"Encrypted message content"}}),t.push({name:"mac",offset:1+s,length:12,bytes:Se(ge(e.slice(-12))),decoded:{note:"Message authentication code"}})}return t}function v_(e){return e.length===0?[]:[{name:"raw_data",offset:0,length:e.length,bytes:Se(ge(e)),decoded:{length:e.length}}]}function Ia(e,t){switch(e){case 4:return __(t);case 3:return f_(t);case 9:return p_(t);case 8:return m_(t);case 5:return g_(t);default:return v_(t)}}function S_(e){const t=e.type??e.payload_type??0,i=e.route??e.route_type??0,s=e.raw_packet||"";let r,n=null;if(s){const o=Za.fromHex(s);if(o.success&&o.packet){const a=o.packet;try{n=Qa(a)}catch{n=null}const h=Ro(s);let l=0;const c={offset:0,length:1,bytes:Se(s.slice(0,2)),decoded:{route_type:a.routeType,route_name:a.routeTypeName,payload_type:a.payloadType,payload_name:a.payloadTypeName,version:a.payloadVersion}};l+=1,a.hasTransportCodes()&&(l+=4);const u={offset:l,length:1,bytes:Se(ge(h.slice(l,l+1))),decoded:{value:a.pathLen}};l+=1;const f=l,_=h.slice(l,l+a.pathLen),p=Array.from(a.path).map(M=>M.toString(16).toUpperCase().padStart(2,"0")),g=a.payloadType===9,x={offset:f,length:a.pathLen,bytes:Se(ge(_)),decoded:{hops:p,path_string:p.length>0?p.join("->"):"(direct)",...g&&{note:"For TRACE packets, path bytes are SNR×4 values, not node hashes",snr_values:Array.from(a.path).map(M=>{let N=M;return N>127&&(N-=256),N/4})}}};l+=a.pathLen;const O={offset:l,length:a.payload.length,bytes:Se(a.payloadHex),sections:Ia(a.payloadType,a.payload)};r={header:c,path_length:u,path:x,payload:O}}else r=ho(e)}else r=ho(e);return{timestamp:e.timestamp,packet_hash:e.packet_hash,type:t,type_name:Pa(t),route:i,route_name:Na(i),rssi:e.rssi,snr:e.snr,length:e.length??0,src_hash:e.src_hash,dst_hash:e.dst_hash,transmitted:e.transmitted,drop_reason:e.drop_reason,is_duplicate:e.is_duplicate,lbt_attempts:e.lbt_attempts,lbt_backoff_delays_ms:e.lbt_backoff_delays_ms,lbt_channel_busy:e.lbt_channel_busy,raw_packet:s,structure:r,decoded:n}}function ho(e){var r;const t=e.type??e.payload_type??0,i=e.route??e.route_type??0,s=e.original_path??e.forwarded_path??[];return{header:{offset:0,length:1,bytes:"??",decoded:{route_type:i,route_name:Na(i),payload_type:t,payload_name:Pa(t),version:0}},path_length:{offset:1,length:1,bytes:s.length.toString(16).toUpperCase().padStart(2,"0"),decoded:{value:s.length}},path:{offset:2,length:s.length,bytes:s.join(" "),decoded:{hops:s,path_string:s.length>0?s.join("->"):"(direct)"}},payload:{offset:2+s.length,length:((r=e.payload)==null?void 0:r.length)??0,bytes:e.payload??"",sections:e.payload?Ia(t,Ro(e.payload)):[]}}}function y_(e,t){var i;return{capture:{start:e.startTime.toISOString(),end:e.endTime.toISOString(),duration_sec:e.durationSec,packet_count:e.packetCount,node_name:(t==null?void 0:t.node_name)??"unknown",local_hash:(t==null?void 0:t.local_hash)??"unknown",pymc_console_version:Ja,pymc_repeater_version:(t==null?void 0:t.version)??"unknown",radio_config:(i=t==null?void 0:t.config)!=null&&i.radio?{frequency:t.config.radio.frequency,tx_power:t.config.radio.tx_power,bandwidth:t.config.radio.bandwidth,spreading_factor:t.config.radio.spreading_factor}:null},packets:e.packets.map(S_)}}function Oa(e,t){const i=y_(e,t),s=JSON.stringify(i,null,2),r=new Blob([s],{type:"application/json"}),n=URL.createObjectURL(r),o=document.createElement("a");o.href=n,o.download=e.filename,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n)}function Zi(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}class w_ extends te{constructor(){super(...arguments);D(this,"name","cap");D(this,"description","Packet capture (start/end/list/export)")}matches(i){const s=i.toLowerCase().trim();return s==="cap"||s==="cap help"||s.startsWith("start cap")||s.startsWith("end cap")||s.startsWith("list cap")||s.startsWith("export cap")}async execute({output:i,rawInput:s}){const r=s.toLowerCase().trim();if(r==="cap"||r==="cap help")return this.showHelp(i);if(r.startsWith("start cap"))return this.startCapture(i,r);if(r==="end cap")return this.endCapture(i);if(r==="list cap")return this.listCaptures(i);if(r.startsWith("export cap"))return this.exportCapture(i,r);this.showHelp(i)}showHelp(i){const s=bt.getState(),r=s.isCapturing?`
${Bs('Recording in progress... use "end cap" to stop')}`:"",n=s.reports.length,o=n>0?` (${n} saved)`:"",a=[W("Packet Capture"),"",E("start cap","Start capture (default: 120s)"),E("end cap","Stop capture early"),E("list cap",`List saved captures${o}`),E("export cap","Download capture by ID"),"",st("Captures stored in session memory. JSON includes decoded payloads."),r].filter(Boolean);i.write(a.join(`
`))}startCapture(i,s){const r=s.slice(9).trim(),n=r?parseInt(r):120;if(isNaN(n)||n<1||n>3600){i.write("Error: Duration must be 1-3600 seconds","error");return}const o=bt.getState();if(o.isCapturing){i.write('Error: Capture already in progress. Use "end cap" first.',"error");return}const a=xt.getState().packets;o.startCapture(a);let h=n;const l=i.write(Bs(`Capturing... ${h}s remaining`),"system"),c=setInterval(()=>{h--;const u=bt.getState();if(h>=0&&u.isCapturing){const _=xt.getState().packets.filter(g=>{if(!u.captureStartTime)return!1;const x=u.captureStartTime.getTime()/1e3;return g.timestamp>=x&&!u.captureStartPacketHashes.has(g.packet_hash)}).length,p=h>0?`${h}s remaining`:"finishing...";i.update(l,Bs(`Capturing... ${p} (${_} captured)`),"system")}},1e3),d=setTimeout(()=>{clearInterval(c);const u=bt.getState();if(u.isCapturing){const f=xt.getState().packets,_=u.stopCapture(f);_?i.write(`✓ Capture complete!
  Captured: ${_.packetCount} packets
  Duration: ${_.durationSec}s
  Size: ~${Zi(_.sizeBytes)}

Run \`export cap ${_.id}\` to download.`,"value"):i.write("Capture completed with no packets.","warning")}},n*1e3);o._setTimer(d)}endCapture(i){const s=bt.getState();if(!s.isCapturing){i.write("No capture in progress.","warning");return}const r=xt.getState().packets,n=s.stopCapture(r);n?i.write(`✓ Capture stopped!
  Captured: ${n.packetCount} packets
  Duration: ${n.durationSec}s
  Size: ~${Zi(n.sizeBytes)}

Run \`export cap ${n.id}\` to download.`,"value"):i.write("Capture stopped with no packets.","warning")}listCaptures(i){const{reports:s}=bt.getState();if(s.length===0){i.write(`No capture reports available.
Start a capture with: start cap [seconds]`,"info");return}const r=s.map((n,o)=>`  ${o+1}. ${n.packetCount} pkts • ${n.durationSec}s • ~${Zi(n.sizeBytes)} (id: ${n.id})`);i.write(`Capture Reports (${s.length}):
${r.join(`
`)}`,"info")}exportCapture(i,s){const r=s.slice(10).trim(),n=bt.getState(),o=xt.getState().stats;if(!r){if(n.reports.length===0)i.write(`No capture reports available.
Start a capture with: start cap [seconds]`,"info");else{const h=n.reports.map((l,c)=>`  ${c+1}. ${l.id}`);i.write(`Usage: export cap <id>

Available reports:
${h.join(`
`)}`,"info")}return}let a=n.getReport(r);if(!a){const h=parseInt(r)-1;a=n.reports[h]}if(!a){i.write(`Error: Report "${r}" not found.
Use "list cap" to see available reports.`,"error");return}Oa(a,o),i.write(`✓ Downloading ${a.filename}...`,"value")}}class b_ extends te{constructor(){super(...arguments);D(this,"name","identities");D(this,"description","List configured identities");D(this,"aliases",["id","ids"])}async execute({output:i,rawInput:s}){var n;if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("identities"),`  ${w("List all configured repeater and room server identities.")}`,"",E("identities","list identities"),"",W("Aliases"),`  ${w("id, ids")}`].join(`
`));return}const r=i.write("processing...","system");try{const o=await il();if(!o.success||!o.data){i.update(r,o.error||"Failed to fetch identities","error");return}const a=o.data,h=(n=a.configured)!=null&&n.length?a.configured:a.registered||[];if(h.length===0){i.update(r,"No identities configured.","warning");return}const l=[W(`Identities (${h.length})`),"",...h.map((c,d)=>{var p;const u=c.name||"Unnamed",f=c.type||"unknown",_=((p=c.hash)==null?void 0:p.slice(0,8))||"—";return`  ${w(`${d+1}.`)} ${it(u)}  ${Ae(f)}  ${y(_)}`})];i.update(r,l.join(`
`))}catch(o){i.update(r,`Error: ${o instanceof Error?o.message:"Command failed"}`,"error")}}}class C_ extends te{constructor(){super(...arguments);D(this,"name","keys");D(this,"description","List transport keys")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("keys"),`  ${w("List configured transport encryption keys.")}`,"",E("keys","list transport keys")].join(`
`));return}const r=i.write("processing...","system");try{const n=await ml();if(!n.success||!n.data){i.update(r,n.error||"Failed to fetch transport keys","error");return}const o=n.data;if(o.length===0){i.update(r,"No transport keys configured.","warning");return}const a=[W(`Transport Keys (${o.length})`),"",...o.map(h=>{const l=h.parent_id?`  ${Ae(`parent: ${h.parent_id}`)}`:"";return`  ${it(h.name)}  ${b("flood",y(h.flood_policy))}${l}`})];i.update(r,a.join(`
`))}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class x_ extends te{constructor(){super(...arguments);D(this,"name","acl");D(this,"description","Show ACL statistics")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("acl"),`  ${w("Display access control list statistics.")}`,"",E("acl","show ACL stats")].join(`
`));return}const r=i.write("processing...","system");try{const n=await sl();if(!n.success||!n.data){i.update(r,n.error||"Failed to fetch ACL stats","error");return}const o=n.data,a=[W("ACL Stats"),"",`  ${b("Identities",y(String(o.total_identities)))}`,`  ${b("Total clients",y(String(o.total_clients)))}`,`  ${b("Admin",y(String(o.admin_clients)))}`,`  ${b("Guest",y(String(o.guest_clients)))}`];if(o.by_identity_type){const h=o.by_identity_type.repeater,l=o.by_identity_type.room_server;h&&a.push(`  ${b("Repeater",`${y(String(h.count))} ids  ${w(`${h.clients} clients`)}`)}`),l&&a.push(`  ${b("Room Server",`${y(String(l.count))} ids  ${w(`${l.clients} clients`)}`)}`)}i.update(r,a.join(`
`))}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class k_ extends te{constructor(){super(...arguments);D(this,"name","rooms");D(this,"description","Show room server statistics")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("rooms"),`  ${w("Display room server statistics and sync status.")}`,"",E("rooms","list rooms")].join(`
`));return}const r=i.write("processing...","system");try{const n=await rl();if(!n.success||!n.data){i.update(r,n.error||"Failed to fetch room stats","error");return}const o=n.data.rooms||[];if(o.length===0){i.update(r,"No room servers configured.","warning");return}const a=[W(`Rooms (${o.length})`),"",...o.map(h=>[`  ${it(h.room_name)}`,`    ${b("msgs",y(String(h.total_messages)))}  ${b("clients",`${y(String(h.active_clients))}${Ae(`/${h.total_clients}`)}`)}  ${b("sync",h.sync_running?y("running"):Ae("idle"))}`]).flat()];i.update(r,a.join(`
`))}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class E_ extends te{constructor(){super(...arguments);D(this,"name","restart");D(this,"description","Restart pymc-repeater service");D(this,"aliases",["reboot"])}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("restart"),`  ${w("Restart the pymc-repeater systemd service.")}`,"",E("restart","restart the service"),"",W("Aliases"),`  ${w("reboot")}`,"",st("Requires polkit permissions for the web user."),st("The page will need a manual refresh after restart.")].join(`
`));return}const r=i.write("Restarting service...","system");try{const n=await gl(AbortSignal.timeout(8e3));if(n.success){i.update(r,"Service restart initiated.","success"),await this.waitForService(i);return}const o=n.status;if(o===403||o===401){i.update(r,`Error: Permission denied.

The web user needs polkit permissions to restart the service.
See: /etc/polkit-1/localauthority/50-local.d/pymc-repeater.pkla`,"error");return}i.update(r,n.error||"Restart failed","error")}catch(n){const o=n instanceof Error?n.message:"";o.includes("ERR_NETWORK")||o.includes("ECONNRESET")||o.includes("Failed to fetch")||o.includes("Load failed")||o.includes("network connection was lost")||o.includes("abort")||o.includes("timeout")||n instanceof DOMException&&n.name==="TimeoutError"||n instanceof DOMException&&n.name==="AbortError"?(i.update(r,"Service is restarting (connection dropped).","success"),await this.waitForService(i)):i.update(r,`Error: ${o||"Restart failed"}`,"error")}}waitForService(i){return new Promise(s=>{const r=i.write("Waiting for service...","system");let n=0;const o=30;setTimeout(()=>{const a=setInterval(async()=>{n++,i.update(r,`Waiting for service... ${n}s`,"system");try{const h=new AbortController,l=setTimeout(()=>h.abort(),3e3);await fetch(`${nl}/api/stats`,{signal:h.signal}),clearTimeout(l),clearInterval(a),i.update(r,`Service connected. (${n+4}s)`,"success"),s();return}catch{}n>=o&&(clearInterval(a),i.update(r,`Service did not respond within ${o+4}s. Check manually.`,"warning"),s())},1e3)},4e3)})}}const Wt="\x1B[",Ie=`${Wt}0m`,Fa=`${Wt}32m`,Fr=`${Wt}33m`,Hr=`${Wt}31m`,R_=`${Wt}36m`,Mt=`${Wt}90m`,Ha=`${Wt}1m`;function Xt(e){return e>=1073741824?`${(e/1073741824).toFixed(1)}G`:e>=1048576?`${(e/1048576).toFixed(0)}M`:e>=1024?`${(e/1024).toFixed(0)}K`:`${e}B`}function co(e){const t=Math.floor(e/86400),i=Math.floor(e%86400/3600),s=Math.floor(e%3600/60);return t>0?`${t}d ${i}h ${s}m`:i>0?`${i}h ${s}m`:`${s}m`}function B_(e,t){const i=Math.max(0,Math.min(100,e)),s=Math.round(i/100*t),r=t-s,n=i>=90?Hr:i>=70?Fr:Fa,o=`${n}${"█".repeat(s)}${Ie}${Mt}${"░".repeat(r)}${Ie}`,a=`${i.toFixed(1)}%`.padStart(6);return`[${o}] ${n}${a}${Ie}`}function M_(e){return e>=80?`${Hr}${Ha}${e.toFixed(1)}°C${Ie}`:e>=60?`${Fr}${e.toFixed(1)}°C${Ie}`:`${Fa}${e.toFixed(1)}°C${Ie}`}const Ci=2,uo="  ";function Jt(e,t){const i=" ".repeat(Ci),s=t-Ci,r=uo.length,n=[];let o="",a=0;for(const h of e){const l=cu(h);a===0?(o=h,a=l):a+r+l<=s?(o+=uo+h,a+=r+l):(n.push(i+o),o=h,a=l)}return a>0&&n.push(i+o),n}function L_(e,t,i){var d,u;const s=e.node_name||"unknown",r=e.version?`v${e.version}`:"",n=(d=t.system)!=null&&d.uptime?co(t.system.uptime):"?",o=co(e.uptime_seconds||0),a=Math.max(3,i-Ci*2),h=((u=t.cpu.load_avg)==null?void 0:u["1min"].toFixed(2))??"?",l=t.cpu.load_avg?`${h} ${t.cpu.load_avg["5min"].toFixed(2)} ${t.cpu.load_avg["15min"].toFixed(2)}`:"?",c=i>=60?l:h;return[`  ${R_}${Ha}${s}${Ie}  ${Mt}${r}${Ie}`,`  ${Mt}${"─".repeat(a)}${Ie}`,...Jt([b("Sys",y(n)),b("Svc",y(o)),b("Load",y(c))],i)]}function D_(e,t){const s=Ci+4+1+2+6,r=Math.max(6,Math.min(30,t-s)),n=s+r,o=t-n-2,a=[""],h=`${e.cpu.count} core${e.cpu.count>1?"s":""}`,l=`${Xt(e.memory.used)}/${Xt(e.memory.total)}`,c=`${Xt(e.disk.used)}/${Xt(e.disk.total)}`,d=(f,_,p)=>{const g=B_(_,r),x=o>=p.length?`  ${Ae(p)}`:"";return`  ${w(f.padEnd(4))}${g}${x}`};a.push(d("CPU",e.cpu.usage_percent,h)),a.push(d("Mem",e.memory.usage_percent,l)),a.push(d("Dsk",e.disk.usage_percent,c));const u=Object.entries(e.temperatures||{});if(u.length>0){const f=u.map(([_,p])=>`${Ae(_+":")} ${M_(p)}`);a.push(...Jt(f,t))}return a}function T_(e,t){var l,c;const i=e.neighbors||{},s=Object.keys(i).length,r=Object.values(i).filter(d=>d.zero_hop).length,n=((c=(l=e.config)==null?void 0:l.repeater)==null?void 0:c.mode)||"?",o=e.noise_floor_dbm!=null?`${e.noise_floor_dbm}dBm`:"?",a=e.duty_cycle_percent??0,h=["",`  ${Mt}MESH${Ie}`];return h.push(...Jt([b("Mode",y(n)),b("Nbrs",`${y(String(r))}${Ae(`/${s}`)}`),b("Noise",y(o)),b("Air",y(`${a.toFixed(1)}%`))],t)),h.push(...Jt([b("RX",y(String(e.rx_count??0))),b("TX",y(String(e.tx_count??0))),b("FWD",y(String(e.forwarded_count??0))),b("Drop",y(String(e.dropped_count??0)))],t)),h.push(...Jt([b("RX/h",y(String(Math.round(e.rx_per_hour??0)))),b("FWD/h",y(String(Math.round(e.forwarded_per_hour??0))))],t)),h}function $_(e,t){if(!e.network)return[];const i=["",`  ${Mt}NET${Ie}`];return i.push(...Jt([b("TX",y(Xt(e.network.bytes_sent))),b("RX",y(Xt(e.network.bytes_recv))),b("Pkt",`${y(String(e.network.packets_sent))}${Ae("/")}${y(String(e.network.packets_recv))}`)],t)),i}function A_(e,t,i){if(e.length===0)return[];const s=t>=50,r=t>=50?6:5,n=t>=50?6:5,o=s?7:0,a=Ci+0,h=Math.max(4,t-a-o-r-n-4),l=3,c=t>=50?8:5,d=i!=null?Math.max(0,Math.min(c,i-l)):c;if(d<=0)return[];const u=["",`  ${Mt}PROCS${Ie}`],f=(s?"PID".padEnd(o):"")+"CPU".padStart(r)+"MEM".padStart(n)+"  NAME";u.push(`  ${Ae(f)}`);for(const _ of e.slice(0,d)){const p=s?Ae(String(_.pid).padEnd(o)):"",g=(t>=50?_.cpu_percent.toFixed(1):_.cpu_percent.toFixed(0)).padStart(r),x=(t>=50?_.memory_percent.toFixed(1):_.memory_percent.toFixed(0)).padStart(n),z=_.name.length>h?_.name.slice(0,h-1)+"…":_.name,O=_.cpu_percent>=50?Hr:_.cpu_percent>=20?Fr:"",M=O?`${O}${g}${Ie}`:g;u.push(`  ${p}${M}${Ae(x)}  ${z}`)}return u}function P_(){return new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function _o(e,t,i,s,r){if(!e||!t)return`  ${Mt}Waiting for data…${Ie}`;const n=L_(e,t,s),o=D_(t,s),a=T_(e,s),h=$_(t,s),l=["",`  ${Mt}${P_()}  ·  Ctrl+C to exit${Ie}`],c=[...n,...o,...a,...h,...l],d=r?wr(c,s):0,u=r?Math.max(0,r-d):void 0,f=A_(i,s,u),_=[...c.slice(0,-l.length),...f,...l];return r&&_.length>r&&(_.length=r),_.join(`
`)}const N_=3e3;class I_ extends te{constructor(){super(...arguments);D(this,"name","top");D(this,"description","Live system overview (Ctrl+C to exit)");D(this,"aliases",["htop"])}async execute({output:i,rawInput:s,cols:r,signal:n}){var l,c;if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("top"),`  ${w("Live-updating system overview combining hardware")}`,`  ${w("stats, mesh metrics, and running processes.")}`,`  ${w("Refreshes every 3s. Press Ctrl+C to exit.")}`,"",E("top","start live display"),"",W("Sections"),`  ${w("Header     Node name, version, uptime, load average")}`,`  ${w("Gauges     CPU, memory, disk usage with bar charts")}`,`  ${w("Mesh       Mode, neighbors, packet counts, airtime")}`,`  ${w("Network    TCP/IP bytes and packet counters")}`,`  ${w("Processes  Top 8 processes by CPU usage")}`,"",W("Aliases"),`  ${w("htop")}`].join(`
`));return}let o=null,a=[],h=xt.getState().stats;try{const[d,u]=await Promise.all([es(),zr()]);d.success&&d.data&&(o=d.data),u.success&&u.data&&(a=u.data.processes.sort((f,_)=>_.cpu_percent-f.cpu_percent))}catch{}if(!n.aborted){(l=i.enterFullscreen)==null||l.call(i);try{const d=i.write(_o(h,o,a,i.cols??r,i.rows));await new Promise(u=>{if(n.aborted){u();return}const f=async()=>{h=xt.getState().stats;try{const[p,g]=await Promise.all([es(),zr()]);p.success&&p.data&&(o=p.data),g.success&&g.data&&(a=g.data.processes.sort((x,z)=>z.cpu_percent-x.cpu_percent))}catch{}n.aborted||i.update(d,_o(h,o,a,i.cols??r,i.rows))},_=setInterval(()=>{if(n.aborted){clearInterval(_),u();return}f()},N_);n.addEventListener("abort",()=>{clearInterval(_),u()},{once:!0})})}finally{(c=i.exitFullscreen)==null||c.call(i)}}}}const fo=["DONT PANIC","C0FFEE","FEED C0DE","LOL","I CANNOT DO THAT"];function Wr(){return fo[Math.floor(Math.random()*fo.length)]}const Cr=new EventTarget,xr="shell-phrase";function Wa(e){Cr.dispatchEvent(new CustomEvent(xr,{detail:e??Wr()}))}function O_(e){const t=i=>e(i.detail);return Cr.addEventListener(xr,t),()=>Cr.removeEventListener(xr,t)}class F_ extends te{constructor(){super(...arguments);D(this,"name","fortune");D(this,"description","Display a fortune on the header");D(this,"aliases",["lol"])}execute({output:i}){const s=Wr();Wa(s),i.write(w(`  ${s}`))}}const kr=new EventTarget,Er="party-time";function H_(){kr.dispatchEvent(new Event(Er))}function W_(e){return kr.addEventListener(Er,e),()=>kr.removeEventListener(Er,e)}class z_ extends te{constructor(){super(...arguments);D(this,"name","partytime");D(this,"description","Party on, Garth!");D(this,"aliases",["party","excellent","waynesworld"])}execute({output:i}){H_(),Wa("PARTY 0N GARTH"),i.write(w("  SCHWING!"))}}class U_ extends te{constructor(){super(...arguments);D(this,"name","ver");D(this,"description","Show version info");D(this,"aliases",["version"])}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("ver"),`  ${w("Display pyMC_Repeater, core, and console version.")}`,`  ${w('Equivalent to firmware serial CLI "ver" command.')}`,"",E("ver","show version"),"",W("Aliases"),`  ${w("version")}`].join(`
`));return}const r=i.write("processing...","system");try{const n=await rt();i.update(r,[`  ${b("pyMC_Repeater",y(`v${n.version||"?"}`))}`,`  ${b("pyMC_Core",y(n.core_version||"?"))}`,`  ${b("pyMC_Console",y("v0.9.302"))}`].join(`
`),"value")}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class j_ extends te{constructor(){super(...arguments);D(this,"name","clock");D(this,"description","Show system UTC time")}execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("clock"),`  ${w("Display the current system UTC time.")}`,`  ${w('Equivalent to firmware serial CLI "clock" command.')}`,`  ${w("Use to verify NTP sync and correlate packet timestamps.")}`,"",E("clock","show UTC time")].join(`
`));return}const r=new Date;i.write([`  ${b("UTC",y(r.toUTCString()))}`,`  ${b("ISO",y(r.toISOString()))}`,`  ${b("Unix",y(String(Math.floor(r.getTime()/1e3))))}`].join(`
`),"value")}}class K_ extends te{constructor(){super(...arguments);D(this,"name","stats-packets");D(this,"description","Packet counters")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("stats-packets"),`  ${w("Display packet counters: sent, received, forwarded, dropped.")}`,`  ${w('Equivalent to firmware serial CLI "stats-packets" command.')}`,"",E("stats-packets","show packet counters")].join(`
`));return}const r=i.write("processing...","system");try{const n=await rt(),o=n.rx_count??0,a=n.tx_count??0,h=n.forwarded_count??0,l=n.dropped_count??0,c=n.rx_per_hour??0,d=n.forwarded_per_hour??0,u=n.duplicate_cache_size??0;i.update(r,[`  ${it("Packet Counters")}`,"",`  ${b("RX",y(String(o)))}        ${w(`${c.toFixed(1)}/hr`)}`,`  ${b("TX",y(String(a)))}`,`  ${b("Forwarded",y(String(h)))}  ${w(`${d.toFixed(1)}/hr`)}`,`  ${b("Dropped",y(String(l)))}`,"",`  ${b("Dup cache",y(String(u)))}`].join(`
`),"value")}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}function Ps(e){return e>=6e4?`${(e/6e4).toFixed(1)}m`:e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e.toFixed(0)}ms`}class q_ extends te{constructor(){super(...arguments);D(this,"name","stats-radio");D(this,"description","Radio health stats")}async execute({output:i,rawInput:s}){var n;if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("stats-radio"),`  ${w("Display radio health: airtime, noise floor, duty cycle.")}`,`  ${w('Equivalent to firmware serial CLI "stats-radio" command.')}`,"",E("stats-radio","show radio stats")].join(`
`));return}const r=i.write("processing...","system");try{const o=await rt(),a=(n=o.config)==null?void 0:n.radio,h=o.noise_floor_dbm,l=o.airtime_used_ms??0,c=o.airtime_remaining_ms??0,d=o.duty_cycle_percent??0,u=o.utilization_percent??0,f=o.total_airtime_ms??0,_=[`  ${it("Radio Stats")}`,""];if(a){const p=a.frequency?`${(a.frequency/1e6).toFixed(3)} MHz`:"?",g=a.bandwidth?`${a.bandwidth/1e3} kHz`:"?";_.push(`  ${b("Radio",y(`${p}  SF${a.spreading_factor??"?"}  BW ${g}  CR 4/${a.coding_rate??"?"}  ${a.tx_power??"?"} dBm`))}`),_.push("")}_.push(`  ${b("Noise floor",h!=null?y(`${h} dBm`):w("N/A"))}`),_.push(`  ${b("Airtime used",y(Ps(l)))}  ${w(`remaining: ${Ps(c)}`)}`),_.push(`  ${b("Total airtime",y(Ps(f)))}`),_.push(`  ${b("Duty cycle",y(`${d.toFixed(1)}%`))}`),_.push(`  ${b("Utilization",y(`${u.toFixed(1)}%`))}`),i.update(r,_.join(`
`),"value")}catch(o){i.update(r,`Error: ${o instanceof Error?o.message:"Command failed"}`,"error")}}}function po(e){return e>=1073741824?`${(e/1073741824).toFixed(1)} GB`:e>=1048576?`${(e/1048576).toFixed(0)} MB`:`${(e/1024).toFixed(0)} KB`}class V_ extends te{constructor(){super(...arguments);D(this,"name","stats-core");D(this,"description","Engine vitals")}async execute({output:i,rawInput:s}){if(this.argsAfterName(s).toLowerCase().trim()==="help"){i.write([W("stats-core"),`  ${w("Display engine vitals: uptime, memory, CPU, queue depth.")}`,`  ${w('Equivalent to firmware serial CLI "stats-core" command.')}`,`  ${w("On firmware this shows free heap — here we show Linux process health.")}`,"",E("stats-core","show core stats")].join(`
`));return}const r=i.write("processing...","system");try{const[n,o]=await Promise.all([rt(),es()]),a=[`  ${it("Core Stats")}`,"",`  ${b("Uptime",y(Or(n.uptime_seconds??0)))}`,`  ${b("Dup cache",y(`${n.duplicate_cache_size??0} entries`))}  ${w(`TTL ${n.cache_ttl??"?"}s`)}`];if(o.success&&o.data){const h=o.data;a.push(""),a.push(`  ${b("CPU",y(`${h.cpu.usage_percent.toFixed(1)}%`))}  ${w(`${h.cpu.count} core${h.cpu.count>1?"s":""}`)}`),h.cpu.load_avg&&a.push(`  ${b("Load",y(`${h.cpu.load_avg["1min"].toFixed(2)} / ${h.cpu.load_avg["5min"].toFixed(2)} / ${h.cpu.load_avg["15min"].toFixed(2)}`))}`),a.push(`  ${b("Memory",y(`${po(h.memory.used)} / ${po(h.memory.total)}`))}  ${w(`${h.memory.usage_percent.toFixed(0)}%`)}`);const l=Object.entries(h.temperatures||{});l.length>0&&a.push(`  ${b("Temp",y(`${l[0][1].toFixed(1)}°C`))}`)}i.update(r,a.join(`
`),"value")}catch(n){i.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}const Ns=["@@@@@@@   @@@ @@@  @@@@@@@@@@    @@@@@@@  ","@@@@@@@@  @@@ @@@  @@@@@@@@@@@  @@@@@@@@  ","@@!  @@@  @@! !@@  @@! @@! @@!  !@@       ","!@!  @!@  !@! @!!  !@! !@! !@!  !@!       ","@!@@!@!    !@!@!   @!! !!@ @!@  !@!       ","!!@!!!      @!!!   !@!   ! !@!  !!!       ","!!:         !!:    !!:     !!:  :!!       ",":!:         :!:    :!:     :!:  :!:       "," ::          ::    :::     ::    ::: :::  "," :           :      :      :     :: :: :  "],mo=$o-1;class G_ extends te{constructor(){super(...arguments);D(this,"name","hello");D(this,"description","Play the PYMC burst intro");D(this,"aliases",["hi","intro"])}async execute({output:i,signal:s}){if(s.aborted)return;let r=0;const n=i.write(vi(Ns,0).join(`
`));try{await new Promise(o=>{const a=setInterval(()=>{if(s.aborted||r>=mo){clearInterval(a),s.aborted||i.update(n,vi(Ns,mo).join(`
`)),o();return}r++,i.update(n,vi(Ns,r).join(`
`))},Do);s.addEventListener("abort",()=>{clearInterval(a),o()},{once:!0})})}finally{To()}}}function Y_(){const e=new Gd,t=new Cu(e);return e.register(t,new xu,new ku,new U_,new j_,new Eu,new Ru,new Bu,new K_,new q_,new V_,new Wu,new Xu,new a_,new Ju,new Qu,new l_,new w_,new b_,new C_,new x_,new k_,new E_,new I_,new F_,new z_,new G_),e}const X_=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)}),go=Eo(e=>({entries:[],commandHistory:[],isInitialized:!1,addEntry:t=>{const i=X_(),s={...t,id:i,timestamp:Date.now()};return e(r=>({entries:[...r.entries,s]})),i},updateEntry:(t,i)=>{e(s=>({entries:s.entries.map(r=>r.id===t?{...r,...i}:r)}))},addCommand:t=>{e(i=>({commandHistory:[...i.commandHistory,t]}))},clearEntries:()=>{e({entries:[],commandHistory:[]})},setInitialized:t=>{e({isInitialized:t})}}));function J_({isOpen:e,onClose:t}){const i=Aa(),s=xt(n=>n.stats),r=n=>{const o=i.find(a=>a.id===n);o&&Oa(o,s)};return m.jsxs(Bo,{open:e,onClose:t,size:"sm",children:[m.jsx(Mo,{icon:m.jsx(Kr,{size:20}),title:"Download Captures",onClose:t}),m.jsx(Lo,{className:"flex flex-col gap-2",children:i.length===0?m.jsxs("div",{className:"flex flex-col items-center gap-2 py-6 text-fg-muted",children:[m.jsx(Ml,{className:"w-8 h-8 opacity-40"}),m.jsx("p",{className:"text-sm",children:"No captures available."})]}):i.map(n=>m.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 radius-inset bg-elevated/50 border border-edge-subtle",children:[m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("p",{className:"type-label text-fg-primary truncate",children:n.filename}),m.jsxs("p",{className:"text-xs text-fg-muted mt-0.5",children:[n.packetCount," packets · ",n.durationSec,"s · ~",Zi(n.sizeBytes)]})]}),m.jsx(ol,{plain:!0,color:"primary",onClick:()=>r(n.id),title:"Download",className:"flex-shrink-0",children:m.jsx(Kr,{"data-slot":"icon"})})]},n.id))})]})}function Z_(){const e=Aa(),[t,i]=U.useState(!1);return m.jsxs(m.Fragment,{children:[m.jsx(Ao,{icon:m.jsx(Rl,{size:20}),onClick:()=>i(!0),title:e.length>0?`Download captures (${e.length})`:"Captures",variant:"red",iconActiveColor:pe.red}),m.jsx(J_,{isOpen:t,onClose:()=>i(!1)})]})}const vo=[{name:"acl",description:"Access control list statistics — identity and client counts.",body:["```","> acl","ACL Stats","","  Identities     2","  Total clients  5","  Admin          2","  Guest          3","  Repeater       1 ids  3 clients","  Room Server    1 ids  2 clients","```"],searchText:"acl access control list statistics identity client"},{name:"advert",description:"Broadcast a repeater advertisement to the mesh.",body:["```","> advert","✓ Advert sent","```"],searchText:"advert advertisement broadcast mesh"},{name:"board",description:"Hardware and platform info — CPU, memory, disk, temperatures, network I/O.",body:["```","> board","  Node     Local-Node","  Runtime  pyMC_Repeater v1.0.0","  Core     v1.12.0","","  CPU      12.3%  4 cores","  Load     0.42 / 0.38 / 0.35","  Temp     48.2°C","","  Memory   412 MB / 664 MB  62%","  Disk     5.2 GB / 28.7 GB  18%","","  System uptime   14d 3h 22m","  Service uptime  2d 14h 32m","  Net TX/RX       128 MB / 342 MB","```"],searchText:"board hardware platform cpu memory disk temperature network"},{name:"cap",description:"Packet capture — start, stop, list, and export captures.",body:["**Sub-commands:** `start cap [sec]` · `end cap` · `list cap` · `export cap [id]`","","**`start cap [seconds]`** — Begin capture (default 120s, max 3600):","```","> start cap","Capturing... 118s remaining (4 captured)","","✓ Capture complete!","  Captured: 23 packets","  Duration: 120s","  Size: ~14.2 KB","```","","**`end cap`** — Stop capture early:","```","> end cap","✓ Capture stopped!","  Captured: 12 packets","```","","**`list cap`** — List saved captures:","```","> list cap","Capture Reports (2):","  1. 23 pkts • 120s • ~14.2 KB (id: abc123)","  2. 12 pkts • 34s • ~7.1 KB (id: def456)","```","","**`export cap [id]`** — Download by ID or index:","```","> export cap 1","✓ Downloading capture-abc123.json...","```"],searchText:"cap capture packet start end list export download diagnostic"},{name:"clear",description:"Clear the terminal screen.",body:["**Alias:** `cls`","```","> clear","```"],searchText:"clear cls screen"},{name:"clock",description:"Current system UTC time. Useful for NTP sync and packet timestamp correlation.",body:["```","> clock","  UTC   Wed, 12 Feb 2026 00:01:34 GMT","  ISO   2026-02-12T00:01:34.000Z","  Unix  1770768094","```"],searchText:"clock time utc ntp unix iso timestamp"},{name:"convert",description:"Convert between hex and base64 encodings.",body:["**Usage:** `convert hex <value>` · `convert base64 <value>`","```","> convert hex 48656C6C6F","  hex     48656C6C6F","  base64  SGVsbG8=","","> convert base64 SGVsbG8=","  base64  SGVsbG8=","  hex     48656C6C6F","```"],searchText:"convert hex base64 encoding decode"},{name:"get",description:"Read a configuration parameter.",body:[],interactive:"get",searchText:"get read config parameter name role lat lon radio freq tx bw sf cr txdelay mode duty flood advert"},{name:"help",description:"Show all commands, or detailed help for a specific command.",body:["**Alias:** `?` · `h`","```","> help           Full command listing","> help ping      Detailed help for ping","> ping help      Same thing","```"],searchText:"help commands reference guide"},{name:"identities",description:"List all configured repeater and room server identities.",body:["**Alias:** `id` · `ids`","```","> identities","Identities (2)","","  1. Local-Node   repeater     0A1B2C3D","  2. local-room   room_server  0E5F6A7B","```"],searchText:"identities id ids repeater room server identity"},{name:"keys",description:"List configured transport encryption keys.",body:["```","> keys","Transport Keys (1)","","  main-transport  flood: allow","```"],searchText:"keys transport encryption"},{name:"neighbors",description:"Direct RF neighbors with signal quality, RSSI, SNR, distance, and last-heard.",body:["**Alias:** `nb`","","**Sort qualifiers:** `sig` · `name` · `rssi` · `snr` · `dist` · `heard`","```","> neighbors","Direct Neighbors (4)","","+-------+-----------+-----------+--------+-------+--------+","| ▁▃▅▇█ | Node-1 | -87 dBm  | 8.5 dB | 2.1km | 3m ago |","| ▁▃▅▇. | Relay-2   | -94 dBm  | 5.2 dB | 4.8km | 1m ago |","| ▁▃▅.. | Node-3   | -108 dBm | 1.0 dB | 8.3km | 5m ago |","| ▁▃... | Node-4  | -118 dBm | -3 dB  | 14km  | 12m ago|","+-------+-----------+-----------+--------+-------+--------+","| SIG   | NAME      | RSSI      | SNR    | DIST  | HEARD  |","+-------+-----------+-----------+--------+-------+--------+","SF11/250kHz  ant 3.5dBi  nf -112dBm","```","","- **sig** — signal grade (weakest first)","- **name** — alphabetical","- **rssi** — RSSI (weakest first)","- **snr** — SNR (lowest first)","- **dist** — distance (closest first)","- **heard** — last seen (oldest first)"],searchText:"neighbors nb signal rssi snr distance sort direct rf"},{name:"packets",description:"Packet counters — received, transmitted, forwarded, dropped.",body:["```","> packets","Packet Stats  1321 total","","  Received     1284","  Transmitted  37","  Forwarded    891","  Dropped      14","```"],searchText:"packets received transmitted forwarded dropped counter"},{name:"ping",description:"Ping a neighbor by name or hex prefix. Shows RTT, signal quality, and path.",body:["**Usage:** `ping <target> [timeout]`","```","> ping Node-1","▁▃▅▇█ Reply from Node-1","","  RTT      342ms","  RSSI     -87 dBm","  SNR      8.5 dB","  Path     direct","  Quality  Excellent","```","","Custom timeout (default 30s):","```","> ping Node-4 60","```"],searchText:"ping rtt round trip time signal quality path neighbor"},{name:"restart",description:"Restart the pymc-repeater systemd service.",body:["**Alias:** `reboot`","```","> restart","Service is restarting (connection dropped).","Waiting for service... 8s","Service connected. (12s)","```","","The terminal polls automatically until the service comes back up."],searchText:"restart reboot service systemd"},{name:"rooms",description:"Room server statistics — message counts, active clients, sync status.",body:["```","> rooms","Rooms (1)","","  Local Room","    msgs 142  clients 3/5  sync running","```"],searchText:"rooms room server messages clients sync"},{name:"set",description:"Write a configuration parameter.",body:[],interactive:"set",searchText:"set write config parameter name lat lon freq tx bw sf cr txdelay mode duty log flood advert"},{name:"stats-core",description:"Engine vitals — uptime, duplicate cache, CPU, memory, temperature.",body:["```","> stats-core","  Core Stats","","  Uptime     2d 14h 32m","  Dup cache  128 entries  TTL 900s","","  CPU        12.3%  4 cores","  Load       0.42 / 0.38 / 0.35","  Memory     412 MB / 664 MB  62%","  Temp       48.2°C","```"],searchText:"stats core engine vitals uptime cache cpu memory temperature"},{name:"stats-packets",description:"Firmware-compatible packet counters with rates and duplicate cache depth.",body:["```","> stats-packets","  Packet Counters","","  RX         1284        22.4/hr","  TX         37","  Forwarded  891   15.2/hr","  Dropped    14","","  Dup cache  128","```"],searchText:"stats packets firmware counter rate duplicate cache"},{name:"stats-radio",description:"Radio health — noise floor, airtime, duty cycle, and radio configuration.",body:["```","> stats-radio","  Radio Stats","","  Radio        906.875 MHz  SF11  BW 250 kHz  CR 4/5  22 dBm","","  Noise floor  -112 dBm","  Airtime used 4.2s  remaining: 55.8m","  Total airtime 1.2m","  Duty cycle   1.2%","  Utilization  0.8%","```"],searchText:"stats radio noise floor airtime duty cycle utilization"},{name:"status",description:"Quick summary of mode, neighbors, and uptime.",body:["**Alias:** `st`","```","> status","Local-Node  repeater","","  Mode       forward","  Neighbors  4 direct  12 total","  RX / TX    1284 / 37","  Uptime     2d 14h 32m","```"],searchText:"status st summary mode neighbors uptime"},{name:"top",description:"Live-updating system overview — CPU/memory gauges, mesh counters, processes.",body:["**Alias:** `htop`","","Refreshes every 3s. Press **Ctrl+C** to exit.","```","> top","Local-Node  v1.0.0","──────────────────────────────────","  Sys 14d 3h 22m  Svc 2d 14h 32m  Load 0.42 0.38 0.35","","  CPU [████░░░░░░░░░░░░]  12.3%  4 cores","  Mem [██████████░░░░░░]  62.1%  412M/664M","  Dsk [███░░░░░░░░░░░░░]  18.4%  5.2G/28.7G","  cpu_thermal: 48.2°C","","  MESH","  Mode forward  Nbrs 4/12  Noise -112dBm  Air 1.2%","  RX 1284  TX 37  FWD 891  Drop 14","  RX/h 22  FWD/h 15","","  PROCS","    CPU   MEM  NAME","    8.2   3.1  python3","    2.1   1.4  cherrypy","","  14:32:08  ·  Ctrl+C to exit","```","","Uses alternate screen buffer — scrollback is preserved."],searchText:"top htop live system overview cpu memory gauges mesh processes"},{name:"uptime",description:"How long the repeater service has been running.",body:["```","> uptime","Uptime  2d 14h 32m","```"],searchText:"uptime service running duration"},{name:"ver",description:"Version info for all three components.",body:["**Alias:** `version`","```","> ver","  pyMC_Repeater  v1.0.0","  pyMC_Core      v1.12.0","  pyMC_Console   v1.0.0","```"],searchText:"ver version pymc repeater core console"}],Q_=[{param:"name",category:"Identity",example:["> get name","name  Local-Node"]},{param:"role",category:"Identity",example:["> get role","role  repeater"]},{param:"lat",category:"Identity",example:["> get lat","lat  34.0522"],range:"-90 to 90"},{param:"lon",category:"Identity",example:["> get lon","lon  -118.2437"],range:"-180 to 180"},{param:"public.key",category:"Identity",example:["> get public.key","public.key  0A1B2C3D4E5F..."]},{param:"radio",category:"Radio",example:["> get radio","  freq  906.875 MHz","  bw    250 kHz","  sf    11","  cr    4/5","  tx    22 dBm"]},{param:"freq",category:"Radio",example:["> get freq","freq  906.875 MHz"],range:"100–1000 MHz"},{param:"tx",category:"Radio",example:["> get tx","tx  22 dBm"],range:"2–22 dBm"},{param:"bw",category:"Radio",example:["> get bw","bw  250 kHz"],range:"7.8–500 kHz"},{param:"sf",category:"Radio",example:["> get sf","sf  11"],range:"5–12"},{param:"cr",category:"Radio",example:["> get cr","cr  4/5"],range:"5–8"},{param:"af",category:"Timing",example:["> get af","⚠ airtime_factor not yet exposed by pyMC_Repeater API.","  Firmware range: 0-9. Tracked in CLI-Alignment.md."],range:"0–9 (pending)"},{param:"txdelay",category:"Timing",example:["> get txdelay","txdelay  1.0"],range:"0.0–5.0"},{param:"direct.txdelay",category:"Timing",example:["> get direct.txdelay","direct.txdelay  0.5"],range:"0.0–5.0"},{param:"rxdelay",category:"Timing",example:["> get rxdelay","rxdelay  0.0"],range:"≥ 0"},{param:"mode",category:"Repeater",example:["> get mode","mode  forward"],range:"forward / monitor"},{param:"duty",category:"Repeater",example:["> get duty","duty  on"],range:"on / off"},{param:"flood.max",category:"Repeater",example:["> get flood.max","flood.max  3"],range:"0–64"},{param:"advert.interval",category:"Repeater",example:["> get advert.interval","advert.interval  120m"],range:"0 (off) or 1–10080 min"},{param:"multi.acks",category:"Advanced",example:["> get multi.acks","multi.acks  0"],range:"0–255"},{param:"int.thresh",category:"Advanced",example:["> get int.thresh","int.thresh  -120 dBm"],range:"-200 to 0 dBm"},{param:"agc.reset.interval",category:"Advanced",example:["> get agc.reset.interval","agc.reset.interval  0"],range:"≥ 0 (×4)"}],ef=[{param:"name",category:"Identity",example:["> set name Local-Node","OK - node_name set to Local-Node"],range:"text (no [ ] \\ / : , ? *)"},{param:"lat",category:"Identity",example:["> set lat 34.0522","OK - latitude set to 34.0522"],range:"-90 to 90"},{param:"lon",category:"Identity",example:["> set lon -118.2437","OK - longitude set to -118.2437"],range:"-180 to 180"},{param:"freq",category:"Radio",example:["> set freq 906.875","OK - frequency set to 906875000"],range:"100–1000 MHz"},{param:"tx",category:"Radio",example:["> set tx 22","OK - tx_power set to 22"],range:"2–22 dBm"},{param:"bw",category:"Radio",example:["> set bw 250","OK - bandwidth set to 250000"],range:"7.8, 10.4, 15.6, 20.8, 31.25, 41.7, 62.5, 125, 250, 500 kHz"},{param:"sf",category:"Radio",example:["> set sf 11","OK - spreading_factor set to 11"],range:"5–12"},{param:"cr",category:"Radio",example:["> set cr 5","OK - coding_rate set to 5"],range:"5–8"},{param:"af",category:"Timing",example:["> set af 2","⚠ airtime_factor not yet exposed by pyMC_Repeater API.","  Firmware range: 0-9. Needs backend support."],range:"0–9 (pending)"},{param:"txdelay",category:"Timing",example:["> set txdelay 1.0","OK - tx_delay_factor set to 1"],range:"0.0–5.0"},{param:"direct.txdelay",category:"Timing",example:["> set direct.txdelay 0.5","OK - direct_tx_delay_factor set to 0.5"],range:"0.0–5.0"},{param:"rxdelay",category:"Timing",example:["> set rxdelay 0","OK - rx_delay_base set to 0"],range:"≥ 0"},{param:"mode",category:"Repeater",example:["> set mode forward","OK - Mode set to forward"],range:"forward / monitor"},{param:"flood.max",category:"Repeater",example:["> set flood.max 3","OK - max_flood_hops set to 3"],range:"0–64"},{param:"advert.interval",category:"Repeater",example:["> set advert.interval 120","OK - Local advert interval set to 120m"],range:"0 (off) or 1–10080 min"},{param:"duty",category:"Repeater",example:["> set duty on","OK - Duty cycle enabled"],range:"on / off"},{param:"log",category:"Repeater",example:["> set log info","OK - Log level set to INFO"],range:"debug, info, warning, error"},{param:"multi.acks",category:"Advanced",example:["> set multi.acks 0","OK - multi_acks set to 0"],range:"0–255"},{param:"int.thresh",category:"Advanced",example:["> set int.thresh -120","OK - interference_threshold set to -120"],range:"-200 to 0 dBm"},{param:"agc.reset.interval",category:"Advanced",example:["> set agc.reset.interval 8","OK - AGC reset interval set to 8"],range:"≥ 0 (rounded to ×4)"},{param:"prv.key",category:"Advanced",example:["> set prv.key <128-hex>","To set this key, run on the Pi:","","  sudo ./convert_firmware_key.sh <key>","","Then restart: sudo systemctl restart pymc-repeater"],range:"128-char hex (SSH only)"}];function tf({mode:e}){const t=e==="get"?Q_:ef,[i,s]=U.useState(0),r=t[i],n=U.useMemo(()=>{const o=new Map;for(const a of t){const h=o.get(a.category)||[];h.push(a),o.set(a.category,h)}return Array.from(o.entries())},[t]);return m.jsxs("div",{className:"flex flex-col gap-2",children:[m.jsx("div",{className:"flex flex-col gap-1.5",children:n.map(([o,a])=>m.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[m.jsx("span",{className:"text-xs text-fg-muted w-16 shrink-0 text-right pr-1",children:o}),a.map(h=>{const l=t.indexOf(h),c=l===i;return m.jsx("button",{onClick:()=>s(l),className:ts("px-1.5 py-0.5 type-data-xs radius-badge transition-colors cursor-pointer",c?"bg-sys-blue text-fg-invert font-semibold":"bg-elevated text-fg-secondary hover:bg-elevated/80 hover:text-sys-blue"),children:h.param},h.param)})]},o))}),m.jsx("pre",{className:"px-3 py-2.5 radius-inner bg-body text-fg-secondary type-code overflow-x-auto border border-edge-subtle",children:r.example.map((o,a)=>m.jsx("div",{children:o||" "},a))}),r.range&&m.jsxs("p",{className:"text-xs text-fg-muted",children:[m.jsx("span",{className:"text-fg-secondary font-medium",children:r.param})," — ",r.range]})]})}function So(e,t){const i=e.split(/(\*\*[^*]+\*\*)/g);return m.jsx("span",{children:i.map((s,r)=>s.startsWith("**")&&s.endsWith("**")?m.jsx("strong",{className:"text-fg-primary font-semibold",children:s.slice(2,-2)},r):s.split(/(`[^`]+`)/g).map((o,a)=>o.startsWith("`")&&o.endsWith("`")?m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue type-data-xs",children:o.slice(1,-1)},`${r}-${a}`):m.jsx("span",{children:o},`${r}-${a}`)))},t)}function sf({lines:e}){const t=[];let i=0;for(;i<e.length;){const s=e[i];if(s==="```"){const r=[];for(i++;i<e.length&&e[i]!=="```";)r.push(e[i]),i++;i++,t.push(m.jsx("pre",{className:"px-3 py-2.5 my-2 radius-inner bg-body text-fg-secondary type-code overflow-x-auto border border-edge-subtle",children:r.map((n,o)=>m.jsx("div",{children:n||" "},o))},t.length));continue}if(!s.trim()){t.push(m.jsx("div",{className:"h-1.5"},t.length)),i++;continue}if(s.startsWith("- ")){t.push(m.jsxs("div",{className:"flex gap-2 text-sm text-fg-secondary pl-2 py-0.5",children:[m.jsx("span",{className:"text-fg-muted shrink-0",children:"•"}),m.jsx("span",{children:So(s.slice(2),0)})]},t.length)),i++;continue}t.push(m.jsx("p",{className:"text-sm text-fg-secondary py-0.5",children:So(s,0)},t.length)),i++}return m.jsx(m.Fragment,{children:t})}function rf({isOpen:e,onClose:t,onUseCommand:i}){const[s,r]=U.useState(""),n=U.useMemo(()=>{if(!s.trim())return vo;const a=s.toLowerCase();return vo.filter(h=>h.name.includes(a)||h.searchText.includes(a)||h.description.toLowerCase().includes(a))},[s]),o=s.trim().length>0;return m.jsxs(Bo,{open:e,onClose:t,size:"3xl",motionPlus:!0,className:"sm:min-w-[540px] md:min-w-[680px]",children:[m.jsx(Mo,{icon:m.jsx(Po,{size:20}),title:"Terminal Command Guide",onClose:t}),m.jsxs(Lo,{className:"flex flex-col gap-0 !px-0 !py-0",children:[m.jsx("div",{className:"sticky top-0 z-10 px-5 py-3 border-b border-edge-subtle bg-surface/95 backdrop-blur-sm",children:m.jsxs("div",{className:"relative",children:[m.jsx(qr,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-muted"}),m.jsx("input",{type:"text",value:s,onChange:a=>r(a.target.value),placeholder:"Search commands...",className:"w-full pl-8 pr-3 py-1.5 text-sm bg-elevated border border-edge-subtle radius-inner text-fg-primary placeholder:text-fg-muted focus:outline-none focus:ring-1 focus:ring-sys-blue/50",autoFocus:!0})]})}),m.jsxs("div",{className:"overflow-y-auto px-5 py-3 h-[420px] sm:h-[520px] md:h-[600px]",children:[m.jsx(fs,{mode:"popLayout",children:n.length===0?m.jsxs($i.div,{initial:{opacity:0,scale:.96},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.96},transition:{duration:jr.normal,ease:Ur.easeOut},className:"flex flex-col items-center gap-2 py-10 text-fg-muted",children:[m.jsx(qr,{className:"w-6 h-6 opacity-40"}),m.jsxs("p",{className:"text-sm",children:['No commands match "',s,'"']})]},"empty"):m.jsx($i.div,{initial:!1,className:"flex flex-col gap-1",children:m.jsx(fs,{initial:!1,children:n.map(a=>m.jsx($i.div,{layout:"position",initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:al.fade,className:"min-w-0",children:m.jsx(ll,{children:({open:h})=>m.jsxs("div",{className:ts("radius-inner border transition-colors",h?"border-edge-subtle bg-elevated/50":"border-transparent hover:bg-elevated/30"),children:[m.jsxs("div",{className:"flex items-center w-full min-w-0",children:[m.jsxs(hl,{className:"flex items-center gap-3 flex-1 min-w-0 px-3 py-2 text-left cursor-pointer",children:[m.jsx(bl,{size:14,className:ts("shrink-0 text-fg-muted transition-transform duration-150",h&&"rotate-90")}),m.jsx("code",{className:"text-sm font-semibold text-sys-blue font-mono shrink-0",children:a.name}),m.jsx("span",{className:"text-xs text-fg-muted truncate min-w-0",children:a.description})]}),i&&m.jsx("button",{onClick:l=>{l.stopPropagation(),i(a.name)},className:"shrink-0 mr-2 px-2 py-0.5 text-xs font-semibold uppercase tracking-wider radius-badge bg-elevated text-fg-muted hover:text-sys-blue hover:bg-elevated/80 transition-colors cursor-pointer",title:`Use "${a.name}" in terminal`,children:"use"})]}),m.jsx(cl,{className:"px-3 pb-3 pt-0 pl-9",children:a.interactive?m.jsx(tf,{mode:a.interactive}):m.jsx(sf,{lines:a.body})})]})})},a.name))})},"list")}),m.jsx(fs,{children:!o&&m.jsxs($i.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:6},transition:{duration:jr.normal,ease:Ur.easeOut},className:"mt-4 px-3 py-3 radius-inner border border-edge-subtle bg-elevated/30",children:[m.jsx("p",{className:"text-xs font-semibold text-fg-muted mb-2",children:"Tips"}),m.jsxs("div",{className:"flex flex-col gap-1 text-xs text-fg-muted",children:[m.jsxs("p",{children:["Type ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"<command> help"})," in the terminal for detailed usage."]}),m.jsxs("p",{children:["Most commands have shorter aliases (e.g. ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"st"}),", ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"nb"}),", ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"id"}),")."]}),m.jsxs("p",{children:["Signal bars ",m.jsx("span",{className:"font-mono",children:"▁▃▅▇█"})," are colored by link quality grade based on RSSI, SNR, and radio config."]}),m.jsx("p",{children:"Captures are stored in browser session only — export before closing the tab."})]})]})})]})]})]})}function nf({onUseCommand:e}){const[t,i]=U.useState(!1),s=e?r=>{i(!1),e(r)}:void 0;return m.jsxs(m.Fragment,{children:[m.jsx(Ao,{icon:m.jsx(Po,{size:17,className:"translate-y-px"}),onClick:()=>i(!0),title:"CLI Command Guide"}),m.jsx(rf,{isOpen:t,onClose:()=>i(!1),onUseCommand:s})]})}const za=Y_(),Qi=za.all().flatMap(e=>[{cmd:e.name,desc:e.description,params:e.params,required:!!e.params},...e.aliases.filter(t=>t.includes(" ")).map(t=>({cmd:t,desc:e.description,params:e.params,required:!!e.params}))]);Qi.push({cmd:"start cap",desc:"Start packet capture",params:"[seconds]",required:!0},{cmd:"end cap",desc:"Stop capture"},{cmd:"list cap",desc:"List captures"},{cmd:"export cap",desc:"Download capture",params:"[id]",required:!0});const Wi=["sig","name","rssi","snr","dist","heard"],of={get:["name","role","lat","lon","radio","freq","tx","bw","sf","cr","af","txdelay","direct.txdelay","rxdelay","mode","repeat","flood.max","flood.advert.interval","advert.interval","duty","duty.max","multi.acks","int.thresh","agc.reset.interval","public.key","prv.key"],set:["name","lat","lon","freq","tx","bw","sf","cr","af","txdelay","direct.txdelay","rxdelay","mode","repeat","flood.max","flood.advert.interval","advert.interval","duty","log","multi.acks","int.thresh","agc.reset.interval","prv.key"],convert:["hex","base64"],neighbors:Wi,nb:Wi,"get neighbors":Wi,"get neighbor":Wi,"set mode":["forward","monitor"],"set duty":["on","off"],"set repeat":["on","off"],"set tx":["10","14","17","20","22"],"set sf":["7","8","9","10","11","12"],"set bw":["125","250","500"],"set cr":["5","6","7","8"],"set af":["0.5","1.0","1.5","2.0"],"set txdelay":["0.5","0.7","1.0","1.5"],"set direct.txdelay":["0.3","0.5","0.7"],"set log":["debug","info","warning","error"],"start cap":["30","60","120","300"]},Is=["@@@@@@@   @@@ @@@  @@@@@@@@@@    @@@@@@@  ","@@@@@@@@  @@@ @@@  @@@@@@@@@@@  @@@@@@@@  ","@@!  @@@  @@! !@@  @@! @@! @@!  !@@       ","!@!  @!@  !@! @!!  !@! !@! !@!  !@!       ","@!@@!@!    !@!@!   @!! !!@ @!@  !@!       ","!!@!!!      @!!!   !@!   ! !@!  !!!       ","!!:         !!:    !!:     !!:  :!!       ",":!:         :!:    :!:     :!:  :!:       "," ::          ::    :::     ::    ::: :::  "," :           :      :      :     :: :: :  "];function di(){return/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)||window.innerWidth<640}function af(e,t){const i=e.toLowerCase(),s=i.trim();if(!s)return[];const r=i.length>s.length&&i.endsWith(" ");if(!s.includes(" ")&&!r)return Qi.filter(h=>h.cmd.toLowerCase().startsWith(s));const n=r?s:s.substring(0,s.lastIndexOf(" ")),o=r?"":s.substring(s.lastIndexOf(" ")+1);if(n==="ping"&&t.length>0)return t.filter(h=>h.toLowerCase().startsWith(o)).slice(0,10).map(h=>({cmd:`ping ${h}`,desc:`→ ${h}`}));const a=of[n];if(a){const h=a.filter(l=>l.toLowerCase().startsWith(o)).map(l=>({cmd:`${n} ${l}`,desc:`→ ${l}`}));if(!r&&o){const l=new Set(h.map(c=>c.cmd));for(const c of Qi){const d=c.cmd.toLowerCase();d.startsWith(s)&&!l.has(d)&&(h.push(c),l.add(d))}}return h}return Qi.filter(h=>h.cmd.toLowerCase().startsWith(s))}function Cf(){const e=dl(),{addCommand:t}=go(),i=U.useRef(null),s=U.useRef(null),r=U.useRef(null),n=U.useRef(null),o=U.useRef(""),a=U.useRef(-1),h=U.useRef(""),l=U.useRef(!1),c=U.useRef(null),d=U.useRef(!1),u=U.useRef(!1),f=U.useRef(!1),_=U.useRef(!1),p=U.useRef([]),g=U.useRef(()=>{}),x=ul(),[z,O]=U.useState("C0dE"),[M,N]=U.useState(!1),K=U.useRef(null),ie=7,ae=280,J="C0dE",Te=U.useCallback(k=>{K.current&&(clearInterval(K.current),K.current=null);const A=J.padEnd(ie),F=A+"  "+k+"  "+A;let I=0;const q=F.length-ie;N(!0),O(F.slice(0,ie)),K.current=setInterval(()=>{if(I++,I>q){clearInterval(K.current),K.current=null,N(!1),O(J);return}O(F.slice(I,I+ie))},ae)},[]);U.useEffect(()=>{const k=O_(Te),A=setInterval(()=>{Math.random()<.02&&Te(Wr())},45e3);return()=>{k(),clearInterval(A),K.current&&clearInterval(K.current)}},[Te]);const[X,P]=U.useState(!1),S=U.useRef(null);U.useEffect(()=>{const k=W_(()=>{S.current&&clearTimeout(S.current),P(!0),S.current=setTimeout(()=>P(!1),5e3)});return()=>{k(),S.current&&clearTimeout(S.current)}},[]);const[L,B]=U.useState({show:!1,options:[],selectedIndex:0,input:""}),T=U.useRef([]),H=U.useRef(0);U.useEffect(()=>{e!=null&&e.neighbors&&(p.current=Object.values(e.neighbors).map(k=>k.node_name||k.name).filter(k=>!!k).sort())},[e==null?void 0:e.neighbors]);const R=U.useCallback(()=>{var k;(k=s.current)==null||k.write(eu(_l()))},[]),Y=U.useCallback(()=>{const k=s.current;k&&(k.write(Hi),R(),k.write(o.current))},[R]),se=U.useCallback(k=>{const A=af(k,p.current);T.current=A,H.current=0;const F=A.length>0&&k.trim().length>0;B({show:F,options:A,selectedIndex:0,input:k.trim()})},[]),xe=U.useCallback(()=>{T.current=[],H.current=0,B({show:!1,options:[],selectedIndex:0,input:""})},[]),Ve=U.useCallback(k=>{var F;const A=T.current[k];A&&(o.current=A.required?A.cmd+" ":A.cmd,Y(),A.required?se(o.current):xe(),(F=s.current)==null||F.focus())},[Y,se,xe]),Pe=U.useCallback(async k=>{const A=s.current;if(!A)return;const F=k.trim();if(!F){R();return}l.current=!0;const I=new AbortController;c.current=I,t(F),a.current=-1;let q=0;const ce={get cols(){return A.cols},get rows(){return A.rows},write(Q,ye="default"){const zt=(ye==="default"?Q:zn(Q,ye)).split(`
`);for(const Dt of zt)A.writeln(Dt);return q=wr(zt,A.cols),String(q)},update(Q,ye,Lt){if(f.current)A.write(ou);else if(q>0)for(let gt=0;gt<q;gt++)A.write(ru()),A.write(Hi);const Dt=(Lt?zn(ye,Lt):ye).split(`
`);if(f.current){for(const gt of Dt)A.write(gt+nu+`\r
`);A.write(au)}else for(const gt of Dt)A.writeln(gt);q=wr(Dt,A.cols)},clear(){A.clear(),q=0},enterFullscreen(){A.write(lu+hu),f.current=!0,q=0},exitFullscreen(){A.write(Kn+jn),f.current=!1,q=0}};A.writeln("");const Ue=za.find(F);if(Ue){const Q=F.split(/\s+/);try{await Ue.execute({output:ce,args:Q,rawInput:F,cols:A.cols,signal:I.signal})}catch(ye){ye instanceof DOMException&&ye.name==="AbortError"||ce.write(`Error: ${ye instanceof Error?ye.message:"Command failed"}`,"error")}}else ce.write(`Unknown command: ${F}
Type 'help' for available commands.`,"error");c.current=null,l.current=!1,A.writeln(""),R()},[t,R]),re=U.useCallback(k=>{const A=s.current;if(!A||!u.current)return;if(l.current){for(let q=0;q<k.length;q++)k.charCodeAt(q)===3&&c.current&&(c.current.abort(),A.writeln("^C"));return}const F=go.getState().commandHistory,I=q=>requestAnimationFrame(()=>{var ce;return(ce=document.querySelector(`[data-ac-index="${q}"]`))==null?void 0:ce.scrollIntoView({block:"nearest"})});for(let q=0;q<k.length;q++){const ce=k.charCodeAt(q);if(ce===13){if(T.current.length>0){const Q=T.current[H.current];Q&&(o.current=Q.cmd,Y())}xe();const Ue=o.current;o.current="",A.writeln(""),Pe(Ue);continue}if(ce===127||ce===8){o.current.length>0&&(o.current=o.current.slice(0,-1),A.write("\b \b"),se(o.current));continue}if(ce===3){o.current="",xe(),A.writeln("^C"),R();continue}if(ce===12){A.clear(),xe(),Y();continue}if(ce===9){T.current.length>0&&Ve(H.current);continue}if(ce===27){if(k.charCodeAt(q+1)===91){const Ue=k.charCodeAt(q+2);if(q+=2,Ue===65){if(T.current.length>0){const Q=Math.max(H.current-1,0);H.current=Q,B(ye=>({...ye,selectedIndex:Q})),I(Q)}else F.length>0&&(a.current===-1&&(h.current=o.current),a.current<F.length-1&&(a.current++,o.current=F[F.length-1-a.current]||"",Y()));continue}if(Ue===66){if(T.current.length>0){const Q=Math.min(H.current+1,T.current.length-1);H.current=Q,B(ye=>({...ye,selectedIndex:Q})),I(Q)}else a.current>0?(a.current--,o.current=F[F.length-1-a.current]||"",Y()):a.current===0&&(a.current=-1,o.current=h.current,Y());continue}if(Ue===67||Ue===68)continue;continue}T.current.length>0&&xe();continue}ce>=32&&(o.current+=k[q],A.write(k[q]),a.current=-1,se(o.current))}},[xe,se,Ve,R,Y,Pe]);U.useEffect(()=>{g.current=re},[re]);const Ge=U.useCallback(async()=>{const k=s.current;if(!k||d.current)return;d.current=!0,_.current=!1;const A="\x1B[94m",F="\x1B[0m",I=()=>_.current,q=Is.length,ce=$o-1;try{const Q=vi(Is,0);for(const ye of Q)k.writeln(ye);await new Promise(ye=>{let Lt=0;const zt=setInterval(()=>{if(I()){clearInterval(zt),ye();return}if(Lt>=ce){clearInterval(zt),ye();return}Lt++,k.write(`\x1B[${q}F`);const Dt=vi(Is,Lt);for(const gt of Dt)k.write(`\x1B[2K${gt}
`)},Do)})}finally{To()}if(I()||(k.writeln(""),k.write(w("● Initializing terminal...")),await new Promise(Q=>setTimeout(Q,300)),I())||(k.write(Hi),k.writeln(`${A}✓ Initializing terminal...${F}`),k.write(w("● Connecting to repeater...")),await new Promise(Q=>setTimeout(Q,500)),I()))return;k.write(Hi),fl.getState().health==="connected"?k.writeln(`${A}✓ Connected to repeater${F}`):k.writeln(Qd("~ Connection status unknown")),k.writeln(w("Ready. Type 'help' for commands.")),k.writeln(""),R(),u.current=!0},[R]);U.useEffect(()=>{const k=i.current;if(!k)return;const A=di()?12:13,F=new Od({theme:Ba(),fontFamily:'"JetBrains Mono", "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',fontSize:A,lineHeight:di()?1.1:.65,cursorBlink:!1,cursorStyle:"underline",scrollback:1e4,convertEol:!0,allowTransparency:!0,rightClickSelectsWord:!1}),I=new Wd;F.loadAddon(I),F.loadAddon(new Vd),F.open(k),I.fit(),s.current=F,r.current=I;const q=F.onData(Q=>g.current(Q)),ce=_u(F),Ue=new ResizeObserver(()=>{requestAnimationFrame(()=>I.fit())});return Ue.observe(k),Ge(),di()||F.focus(),()=>{var Q;_.current=!0,(Q=c.current)==null||Q.abort(),f.current&&(F.write(Kn+jn),f.current=!1),q.dispose(),ce(),Ue.disconnect(),F.dispose(),s.current=null,r.current=null,d.current=!1,u.current=!1}},[]);const He=U.useCallback(k=>{const A=k.target.value;A.length>0&&(re(A),k.target.value="")},[re]),ut=U.useCallback(k=>{k.key==="Enter"?(k.preventDefault(),re("\r")):k.key==="Backspace"?(k.preventDefault(),re("")):k.key==="ArrowUp"?(k.preventDefault(),re("\x1B[A")):k.key==="ArrowDown"&&(k.preventDefault(),re("\x1B[B"))},[re]),ii=U.useCallback(()=>{var k,A;di()?(k=n.current)==null||k.focus():(A=s.current)==null||A.focus()},[]);U.useEffect(()=>{if(!di())return;const k=()=>{var q;const I=(q=i.current)==null?void 0:q.querySelector(".xterm-viewport");I&&(I.scrollTop=I.scrollHeight),requestAnimationFrame(()=>{var ce;return(ce=r.current)==null?void 0:ce.fit()})},A=window.visualViewport;if(A){const I=()=>{A.height<window.innerHeight*.75&&k()};return A.addEventListener("resize",I),()=>A.removeEventListener("resize",I)}const F=n.current;if(F){const I=()=>setTimeout(k,300);return F.addEventListener("focus",I),()=>F.removeEventListener("focus",I)}},[]);const nt=U.useCallback(k=>{o.current=k+" ",Y(),se(o.current),setTimeout(()=>{var A;(A=i.current)==null||A.click()},400)},[Y,se]);return m.jsx(vl,{children:m.jsx(Sl,{ready:!0,children:m.jsxs("div",{className:"terminal-card flex flex-col gap-1 sm:gap-1.5",children:[m.jsxs("div",{className:"card-terminal-header flex-wrap",children:[m.jsx("span",{className:"seven-seg-panel",children:m.jsx(wl,{text:z,minChars:7,size:24,noCycle:M})}),m.jsx("div",{className:"header-well self-stretch flex-col sm:order-first",children:m.jsxs("div",{className:`indicator-key${x==="connected"?" indicator-key--active":x==="degraded"?" indicator-key--sending":""}`,children:[m.jsx("span",{className:"indicator-key__label",children:"ONLINE"}),m.jsx("span",{className:"indicator-key__led"})]})}),m.jsx("div",{className:"card-terminal-ridge flex-1 min-w-4 sm:hidden"}),m.jsxs("div",{className:"header-well flex items-center gap-1 sm:order-last",children:[m.jsx(nf,{onUseCommand:nt}),m.jsx(Z_,{})]}),m.jsx("div",{className:"card-terminal-ridge flex-1 min-w-8 hidden sm:block"})]}),m.jsx(yl,{noPadding:!0,isLoaded:!0,className:"flex flex-col flex-1 min-h-0 overflow-hidden card-terminal",onClick:ii,children:m.jsxs("div",{className:"card-terminal-well flex-1 min-h-0 flex flex-col overflow-hidden",children:[m.jsxs("div",{className:"flex-1 min-h-0 terminal-gutter relative",children:[m.jsx("div",{ref:i,className:"h-full w-full"}),X&&m.jsxs("div",{className:"absolute inset-0 z-10 flex items-center justify-center",onClick:()=>P(!1),children:[m.jsx("div",{className:"absolute inset-0 animate-[partytime-bg_5s_ease-out_forwards]",style:{background:"rgba(0,0,0,0.82)"}}),m.jsxs("div",{className:"relative z-10 animate-[partytime-crt_5s_ease-out_forwards] partytime-glow",children:[m.jsx("img",{src:"/assets/partytime.gif",alt:"No way.",className:"max-h-[60vh] max-w-[70vw] object-contain rounded"}),m.jsx("div",{className:"absolute inset-0 pointer-events-none rounded partytime-scanlines"})]})]})]}),L.show&&L.options.length>0&&m.jsxs("div",{className:"flex-shrink-0 overflow-hidden terminal-completions",style:{borderTop:"1px solid var(--terminal-border)",background:"var(--terminal-bg-input)"},children:[m.jsx("div",{className:"overflow-y-auto",style:{maxHeight:"176px"},children:L.options.map((k,A)=>{const F=A===L.selectedIndex,I=L.input.length;return m.jsxs("div",{"data-ac-index":A,onClick:()=>Ve(A),className:ts("terminal-ac-option",F?"text-sys-blue":"text-fg-primary"),style:{background:F?"var(--terminal-autocomplete-hover)":void 0},onMouseEnter:q=>{F||(q.currentTarget.style.background="var(--terminal-autocomplete-hover)")},onMouseLeave:q=>{F||(q.currentTarget.style.background="")},children:[m.jsx("span",{className:"terminal-ac-option__indicator",children:F?"▸":""}),m.jsxs("span",{className:"terminal-ac-option__cmd",children:[m.jsx("span",{className:"font-semibold text-sys-blue",children:k.cmd.substring(0,I)}),k.cmd.substring(I)]}),m.jsx("span",{className:"terminal-ac-option__desc",children:k.desc})]},k.cmd)})}),m.jsxs("div",{className:"terminal-ac-hints",children:[m.jsx("span",{className:"hidden sm:inline",children:"Tab · ↑↓ · Esc"}),m.jsx("span",{className:"sm:hidden",children:"Tap to select"}),m.jsxs("span",{children:[L.options.length," match",L.options.length!==1?"es":""]})]})]}),m.jsxs("div",{className:"terminal-mobile-input-bar sm:hidden",children:[m.jsx("input",{ref:n,type:"text",className:"terminal-mobile-input",onChange:He,onKeyDown:ut,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,enterKeyHint:"send","aria-label":"Terminal input",placeholder:"Type command..."}),m.jsx("button",{type:"button",className:"terminal-send-btn",onClick:()=>re("\r"),"aria-label":"Run command",children:m.jsx(kl,{})})]}),m.jsxs("div",{className:"terminal-status-bar",children:[m.jsx("span",{className:"hidden sm:inline",children:"↑↓ History · Tab · Esc"}),m.jsx("span",{className:"sm:hidden",children:"Tap input to type"}),(e==null?void 0:e.version)&&m.jsxs("span",{children:["pyMC v",e.version]})]})]})})]})})})}export{Cf as default};
