var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,d=(e,t)=>{for(var n in t)l(e,n,{get:t[n],enumerable:!0})},f=(e,t,n,r)=>{for(var i=r>1?void 0:r?u(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&l(t,n,i),i},p=(e,t)=>(n,r)=>t(n,r,e),m=`Terminal input`,h={get:()=>m,set:e=>m=e},g=`Too much output to announce, navigate to rows manually to read`,_={get:()=>g,set:e=>g=e};function v(e){return e.replace(/\r?\n/g,`\r`)}function y(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function b(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function x(e,t,n,r){e.stopPropagation(),e.clipboardData&&S(e.clipboardData.getData(`text/plain`),t,n,r)}function S(e,t,n,r){e=v(e),e=y(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function C(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function w(e,t,n,r,i){C(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function T(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function E(e,t=0,n=e.length){let r=``;for(let i=t;i65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var D=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},O=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},k=``,ee=` `,te=class e{constructor(){this.fg=0,this.bg=0,this.extended=new ne}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;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)}isBgDefault(){return!(this.bg&50331648)}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):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},ne=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},A=class e extends te{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new ne,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?T(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},re=`di$target`,j=`di$dependencies`,M=new Map;function N(e){return e[j]||[]}function P(e){if(M.has(e))return M.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);ie(t,e,r)};return t._id=e,M.set(e,t),t}function ie(e,t,n){t[re]===t?t[j].push({id:e,index:n}):(t[j]=[{id:e,index:n}],t[re]=t)}var F=P(`BufferService`),I=P(`CoreMouseService`),L=P(`CoreService`),R=P(`CharsetService`),ae=P(`InstantiationService`),oe=P(`LogService`),z=P(`OptionsService`),se=P(`OscLinkService`),ce=P(`UnicodeService`),le=P(`DecorationService`),ue=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new A,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;ti?i.activate(e,t,a):de(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};ue=f([p(0,F),p(1,z),p(2,se)],ue);function de(e,t){if(confirm(`Do you want to navigate to ${t}? WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var fe=P(`CharSizeService`),B=P(`CoreBrowserService`),pe=P(`MouseService`),me=P(`RenderService`),he=P(`SelectionService`),ge=P(`CharacterJoinerService`),_e=P(`ThemeService`),ve=P(`LinkProviderService`),ye=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Te.isErrorNoTelemetry(e)?new Te(e.message+` `+e.stack):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)}};function be(e){Se(e)||ye.onUnexpectedError(e)}var xe=`Canceled`;function Se(e){return e instanceof Ce||e instanceof Error&&e.name===xe&&e.message===xe}var Ce=class extends Error{constructor(){super(xe),this.name=this.message}};function we(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var Te=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},Ee=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function De(e,t=0){return e[e.length-(1+t)]}var Oe;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Oe||={});var ke=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||Oe.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};ke.empty=new ke(e=>{});function Ae(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var je;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Re(...e){return ze(()=>Le(e))}function ze(e){let t=Ne({dispose:Ae(()=>{Pe(t),e()})});return t}var Be=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,Ne(this)}dispose(){this._isDisposed||(Pe(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Le(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return Fe(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(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(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Fe(e,null))}};Be.DISABLE_DISPOSED_WARNING=!1;var Ve=Be,V=class{constructor(){this._store=new Ve,Ne(this),Fe(this._store,this)}dispose(){Pe(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};V.None=Object.freeze({dispose(){}});var He=class{constructor(){this._isDisposed=!1,Ne(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Fe(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Pe(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Fe(e,null),e}},Ue=typeof window==`object`?window:globalThis,We=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};We.Undefined=new We(void 0);var Ge=We,Ke=class{constructor(){this._first=Ge.Undefined,this._last=Ge.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Ge.Undefined}clear(){let e=this._first;for(;e!==Ge.Undefined;){let t=e.next;e.prev=Ge.Undefined,e.next=Ge.Undefined,e=t}this._first=Ge.Undefined,this._last=Ge.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new Ge(e);if(this._first===Ge.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==Ge.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Ge.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Ge.Undefined&&e.next!==Ge.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Ge.Undefined&&e.next===Ge.Undefined?(this._first=Ge.Undefined,this._last=Ge.Undefined):e.next===Ge.Undefined?(this._last=this._last.prev,this._last.next=Ge.Undefined):e.prev===Ge.Undefined&&(this._first=this._first.next,this._first.prev=Ge.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==Ge.Undefined;)yield e.element,e=e.next}},qe=globalThis.performance&&typeof globalThis.performance.now==`function`,Je=class e{static create(t){return new e(t)}constructor(e){this._now=qe&&e===!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._now()-this._startTime:this._stopTime-this._startTime}},Ye;(e=>{e.None=()=>V.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(Re(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new H({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new H({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new H({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new H({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new H({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new H;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new H(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Ve?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(Ye||={});var Xe=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Je,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Xe.all=new Set,Xe._idPool=0;var Ze=Xe,Qe=-1,$e=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t0||this._options?.leakWarningThreshold?new et(e?.onListenerError??be,this._options?.leakWarningThreshold??Qe):void 0,this._perfMon=this._options?._profName?new Ze(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new rt(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||be)(n),V.None}if(this._disposed)return V.None;t&&(e=e.bind(t));let r=new at(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=tt.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof at?(this._deliveryQueue??=new st,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=ze(()=>{i?.(),this._removeListener(r)});return n instanceof Ve?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*ot<=t.length){let e=0;for(let n=0;n0}},st=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},ct=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new H,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new H,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};ct.INSTANCE=new ct;var lt=ct;function ut(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}lt.INSTANCE.onDidChangeZoomLevel;function dt(e){return lt.INSTANCE.getZoomFactor(e)}lt.INSTANCE.onDidChangeFullscreen;var ft=typeof navigator==`object`?navigator.userAgent:``,pt=ft.indexOf(`Firefox`)>=0,mt=ft.indexOf(`AppleWebKit`)>=0,ht=ft.indexOf(`Chrome`)>=0,gt=!ht&&ft.indexOf(`Safari`)>=0;ft.indexOf(`Electron/`),ft.indexOf(`Android`);var _t=!1;if(typeof Ue.matchMedia==`function`){let e=Ue.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=Ue.matchMedia(`(display-mode: fullscreen)`);_t=e.matches,ut(Ue,e,({matches:e})=>{_t&&t.matches||(_t=e)})}function vt(){return _t}var yt=`en`,bt=!1,xt=!1,St=!1,Ct=!1,wt=!1,Tt=yt,Et,Dt=globalThis,Ot;typeof Dt.vscode<`u`&&typeof Dt.vscode.process<`u`?Ot=Dt.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(Ot=process);var kt=typeof Ot?.versions?.electron==`string`&&Ot?.type===`renderer`;if(typeof Ot==`object`){bt=Ot.platform===`win32`,xt=Ot.platform===`darwin`,St=Ot.platform===`linux`,St&&Ot.env.SNAP&&Ot.env.SNAP_REVISION,Ot.env.CI||Ot.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Tt=yt;let e=Ot.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Tt=t.resolvedLanguage||yt,t.languagePack?.translationsConfigFile}catch{}Ct=!0}else typeof navigator==`object`&&!kt?(Et=navigator.userAgent,bt=Et.indexOf(`Windows`)>=0,xt=Et.indexOf(`Macintosh`)>=0,(Et.indexOf(`Macintosh`)>=0||Et.indexOf(`iPad`)>=0||Et.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,St=Et.indexOf(`Linux`)>=0,Et?.indexOf(`Mobi`),wt=!0,Tt=globalThis._VSCODE_NLS_LANGUAGE||yt,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var At=bt,jt=xt,Mt=St,Nt=Ct;wt&&typeof Dt.importScripts==`function`&&Dt.origin;var Pt=Et,Ft=Tt,It;(e=>{function t(){return Ft}e.value=t;function n(){return Ft.length===2?Ft===`en`:Ft.length>=3&&Ft[0]===`e`&&Ft[1]===`n`&&Ft[2]===`-`}e.isDefaultVariant=n;function r(){return Ft===`en`}e.isDefault=r})(It||={});var Lt=typeof Dt.postMessage==`function`&&!Dt.importScripts;(()=>{if(Lt){let e=[];Dt.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n{let r=++t;e.push({id:r,callback:n}),Dt.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var Rt=!!(Pt&&Pt.indexOf(`Chrome`)>=0);Pt&&Pt.indexOf(`Firefox`),!Rt&&Pt&&Pt.indexOf(`Safari`),Pt&&Pt.indexOf(`Edg/`),Pt&&Pt.indexOf(`Android`);var zt=typeof navigator==`object`?navigator:{};Nt||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||zt&&zt.clipboard&&zt.clipboard.writeText,Nt||zt&&zt.clipboard&&zt.clipboard.readText,Nt||vt()||zt.keyboard,`ontouchstart`in Ue||zt.maxTouchPoints,Ue.PointerEvent&&(`ontouchstart`in Ue||navigator.maxTouchPoints);var Bt=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}},Vt=new Bt,Ht=new Bt,Ut=new Bt,Wt=Array(230),Gt;(e=>{function t(e){return Vt.keyCodeToStr(e)}e.toString=t;function n(e){return Vt.strToKeyCode(e)}e.fromString=n;function r(e){return Ht.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Ut.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Ht.strToKeyCode(e)||Ut.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Vt.keyCodeToStr(e)}e.toElectronAccelerator=o})(Gt||={});var Kt=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new qt([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},qt=class{constructor(e){if(e.length===0)throw we(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t{function t(t){return t===e.None||t===e.Cancelled||t instanceof cn?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Ye.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:on})})(sn||={});var cn=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?on:(this._emitter||=new H,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},ln=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 Ee(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ee(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},un=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new Ee(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=ze(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var dn;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(dn||={});var fn=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new H,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};fn.EMPTY=fn.fromArray([]);function pn(e){return mn(e,0)}function mn(e,t){switch(typeof e){case`object`:return e===null?hn(349,t):Array.isArray(e)?vn(e,t):yn(e,t);case`string`:return _n(e,t);case`boolean`:return gn(e,t);case`number`:return hn(e,t);case`undefined`:return hn(937,t);default:return hn(617,t)}}function hn(e,t){return(t<<5)-t+e|0}function gn(e,t){return hn(e?433:863,t)}function _n(e,t){t=hn(149417,t);for(let n=0,r=e.length;nmn(t,e),t)}function yn(e,t){return t=hn(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=_n(n,t),mn(e[n],t)),t)}var{registerWindow:bn,getWindow:xn,getDocument:Sn,getWindows:Cn,getWindowsCount:wn,getWindowId:Tn,getWindowById:En,hasWindow:Dn,onDidRegisterWindow:On,onWillUnregisterWindow:kn,onDidUnregisterWindow:An}=function(){let e=new Map,t={window:Ue,disposables:new Ve};e.set(Ue.vscodeWindowId,t);let n=new H,r=new H,i=new H;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return V.None;let a=new Ve,o={window:t,disposables:a.add(new Ve)};return e.set(t.vscodeWindowId,o),a.add(ze(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(U(t,Bn.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:Ue},getDocument(e){return xn(e).document}}}(),jn=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!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,null)}};function U(e,t,n,r){return new jn(e,t,n,r)}function Mn(e,t){return function(n){return t(new rn(e,n))}}function Nn(e){return function(t){return e(new $t(t))}}var Pn=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=Mn(xn(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=Nn(n)),U(e,t,i,r)},Fn,In=class extends un{constructor(e){super(),this.defaultTarget=e&&xn(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Ln=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){be(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(Ln.sort),a.shift().execute();r.set(i,!1)};Fn=(t,r,a=0)=>{let o=Tn(t),s=new Ln(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var Rn=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};Rn.None=new Rn(0,0);function zn(e){let t=e.getBoundingClientRect(),n=xn(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=pn(n),a=r.get(i);if(a)a.users+=1;else{let o=new H,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(ze(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var Bn={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:mt?`webkitAnimationStart`:`animationstart`,ANIMATION_END:mt?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:mt?`webkitAnimationIteration`:`animationiteration`},Vn=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=Hn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Hn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Hn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Hn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Hn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Hn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Hn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Hn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Hn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Hn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Hn(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=Hn(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=Hn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Hn(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 Hn(e){return typeof e==`number`?`${e}px`:e}function Un(e){return new Vn(e)}var Wn=class{constructor(){this._hooks=new Ve,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 n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(ze(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=xn(e)}this._hooks.add(U(a,Bn.POINTER_MOVE,e=>{if(e.buttons!==n){this.stopMonitoring(!0);return}e.preventDefault(),this._pointerMoveCallback(e)})),this._hooks.add(U(a,Bn.POINTER_UP,e=>this.stopMonitoring(!0)))}};function Gn(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Kn;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Kn||={});var qn=class e extends V{constructor(){super(),this.dispatched=!1,this.targets=new Ke,this.ignoreTargets=new Ke,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Ye.runAndSubscribe(On,({window:e,disposables:t})=>{t.add(U(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(U(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(U(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:Ue,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Ie(new e),ze(e.INSTANCE.targets.push(t))):V.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Ie(new e),ze(e.INSTANCE.ignoreTargets.push(t))):V.None}static isTouchDevice(){return`ontouchstart`in Ue||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n=e.HOLD_DELAY&&Math.abs(s.initialPageX-De(s.rollingPageX))<30&&Math.abs(s.initialPageY-De(s.rollingPageY))<30){let e=this.newGestureEvent(Kn.Contextmenu,s.initialTarget);e.pageX=De(s.rollingPageX),e.pageY=De(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=De(s.rollingPageX),n=De(s.rollingPageY),i=De(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Kn.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Kn.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Kn.Change||t.type===Kn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=Fn(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Kn.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};qn.SCROLL_FRICTION=-.005,qn.HOLD_DELAY=700,qn.CLEAR_TAP_COUNT_TIME=400,f([Gn],qn,`isTouchDevice`,1);var Jn=qn,Yn=class extends V{onclick(e,t){this._register(U(e,Bn.CLICK,n=>t(new rn(xn(e),n))))}onmousedown(e,t){this._register(U(e,Bn.MOUSE_DOWN,n=>t(new rn(xn(e),n))))}onmouseover(e,t){this._register(U(e,Bn.MOUSE_OVER,n=>t(new rn(xn(e),n))))}onmouseleave(e,t){this._register(U(e,Bn.MOUSE_LEAVE,n=>t(new rn(xn(e),n))))}onkeydown(e,t){this._register(U(e,Bn.KEY_DOWN,e=>t(new $t(e))))}onkeyup(e,t){this._register(U(e,Bn.KEY_UP,e=>t(new $t(e))))}oninput(e,t){this._register(U(e,Bn.INPUT,t))}onblur(e,t){this._register(U(e,Bn.BLUR,t))}onfocus(e,t){this._register(U(e,Bn.FOCUS,t))}onchange(e,t){this._register(U(e,Bn.CHANGE,t))}ignoreGesture(e){return Jn.ignoreTarget(e)}},Xn=11,Zn=class extends Yn{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=Xn+`px`,this.domNode.style.height=Xn+`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 Wn),this._register(Pn(this.bgDomNode,Bn.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(Pn(this.domNode,Bn.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new In),this._pointerdownScheduleRepeatTimer=this._register(new ln)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,xn(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Qn=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(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(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},$n=class extends V{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Qn(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.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(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new rr(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=rr.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},er=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function tr(e,t){let n=t-e;return function(t){return e+n*ar(t)}}function nr(e,t,n){return function(r){return r2.5*n){let r,i;return e{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},sr=140,cr=class extends Yn{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 or(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Wn),this._shouldRender=!0,this.domNode=Un(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(U(this.domNode.domNode,Bn.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Zn(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Un(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(U(this.slider.domNode,Bn.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.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,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=zn(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(At&&a>sr){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{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()}},lr=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._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(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};gr.INSTANCE=new gr;var _r=gr,vr=class extends Yn{constructor(e,t,n){super(),this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new H),this.onWillScroll=this._onWillScroll.event,this._options=br(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new dr(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new ur(this._scrollable,this._options,r)),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=Un(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Un(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Un(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,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new ln),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Le(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,jt&&(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 an(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Le(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(U(this._listenOnDomNode,Bn.MOUSE_WHEEL,e=>{this._onMouseWheel(new an(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=_r.INSTANCE;mr&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!jt&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=pr*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=pr*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(mr&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(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 Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_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(),fr)}},yr=class extends vr{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function br(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,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,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,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,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,jt&&(t.className+=` mac`),t}var xr=class extends V{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new H),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new $n({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>Fn(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new yr(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Ye.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ze(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(ze(()=>this._styleElement.remove())),this._register(Ye.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.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(e=>this._handleScroll(e)))}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(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.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),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};xr=f([p(2,F),p(3,B),p(4,I),p(5,_e),p(6,z),p(7,me)],xr);var Sr=class extends V{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,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(e=>this._removeDecoration(e))),this._register(ze(()=>{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){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.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 n=e.options.x??0;return n&&n>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 n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};Sr=f([p(1,F),p(2,B),p(3,le),p(4,me)],Sr);var Cr=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=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},wr={full:0,left:0,center:0,right:0},Tr={full:0,left:0,center:0,right:0},Er={full:0,left:0,center:0,right:0},Dr=class extends V{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new Cr,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(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(ze(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw 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(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Tr.full=this._canvas.width,Tr.left=e,Tr.center=t,Tr.right=e,this._refreshDrawHeightConstants(),Er.full=1,Er.left=1,Er.center=1+Tr.left,Er.right=1+Tr.left+Tr.center}_refreshDrawHeightConstants(){wr.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);wr.left=t,wr.center=t,wr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.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 e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);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(Er[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-wr[e.position||`full`]/2),Tr[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+wr[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}))}};Dr=f([p(2,F),p(3,le),p(4,me),p(5,z),p(6,_e),p(7,B)],Dr);var W;(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=``))(W||={});var Or;(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=`Ÿ`))(Or||={});var kr;(e=>e.ST=`${W.ESC}\\`)(kr||={});var Ar=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,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)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};Ar=f([p(2,F),p(3,z),p(4,L),p(5,me)],Ar);var jr=0,Mr=0,Nr=0,Pr=0,Fr={css:`#00000000`,rgba:0},Ir;(e=>{function t(e,t,n,r){return r===void 0?`#${Vr(e)}${Vr(t)}${Vr(n)}`:`#${Vr(e)}${Vr(t)}${Vr(n)}${Vr(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Ir||={});var Lr;(e=>{function t(e,t){if(Pr=(t.rgba&255)/255,Pr===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return jr=a+Math.round((n-a)*Pr),Mr=o+Math.round((r-o)*Pr),Nr=s+Math.round((i-s)*Pr),{css:Ir.toCss(jr,Mr,Nr),rgba:Ir.toRgba(jr,Mr,Nr)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=Br.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Ir.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[jr,Mr,Nr]=Br.toChannels(t),{css:Ir.toCss(jr,Mr,Nr),rgba:t}}e.opaque=i;function a(e,t){return Pr=Math.round(t*255),[jr,Mr,Nr]=Br.toChannels(e.rgba),{css:Ir.toCss(jr,Mr,Nr,Pr),rgba:Ir.toRgba(jr,Mr,Nr,Pr)}}e.opacity=a;function o(e,t){return Pr=e.rgba&255,a(e,Pr*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Lr||={});var Rr;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return jr=parseInt(e.slice(1,2).repeat(2),16),Mr=parseInt(e.slice(2,3).repeat(2),16),Nr=parseInt(e.slice(3,4).repeat(2),16),Ir.toColor(jr,Mr,Nr);case 5:return jr=parseInt(e.slice(1,2).repeat(2),16),Mr=parseInt(e.slice(2,3).repeat(2),16),Nr=parseInt(e.slice(3,4).repeat(2),16),Pr=parseInt(e.slice(4,5).repeat(2),16),Ir.toColor(jr,Mr,Nr,Pr);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return jr=parseInt(r[1]),Mr=parseInt(r[2]),Nr=parseInt(r[3]),Pr=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Ir.toColor(jr,Mr,Nr,Pr);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[jr,Mr,Nr,Pr]=t.getImageData(0,0,1,1).data,Pr!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Ir.toRgba(jr,Mr,Nr,Pr),css:e}}e.toColor=r})(Rr||={});var zr;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(zr||={});var Br;(e=>{function t(e,t){if(Pr=(t&255)/255,Pr===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return jr=a+Math.round((n-a)*Pr),Mr=o+Math.round((r-o)*Pr),Nr=s+Math.round((i-s)*Pr),Ir.toRgba(jr,Mr,Nr)}e.blend=t;function n(e,t,n){let a=zr.relativeLuminance(e>>8),o=zr.relativeLuminance(t>>8);if(Hr(a,o)>8));if(sHr(a,zr.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Hr(a,zr.relativeLuminance(s>>8));if(cHr(a,zr.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Hr(zr.relativeLuminance2(o,s,c),zr.relativeLuminance2(r,i,a));for(;l0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Hr(zr.relativeLuminance2(o,s,c),zr.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Hr(zr.relativeLuminance2(o,s,c),zr.relativeLuminance2(r,i,a));for(;l>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(Br||={});function Vr(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Hr(e,t){return e1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t=E,re=k,j=this._workCell;if(f.length>0&&k===f[0][0]&&A){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v=r[1],A?(ne=!0,j=new Ur(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),re=r[1]-1,m=j.getWidth()):E=r[1]}let M=this._isCellInSelection(k,t),N=n&&k===a,P=O&&k>=l&&k<=u,ie=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{ie=!0});let F=j.getChars()||ee;if(F===` `&&(j.isUnderline()||j.isOverline())&&(F=`\xA0`),T=m*s-c.get(F,j.isBold(),j.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(M&&w||!M&&!w&&j.bg===y)&&(M&&w&&p.selectionForeground||j.fg===b)&&j.extended.ext===x&&P===S&&T===C&&!N&&!ne&&!ie&&A){j.isInvisible()?_+=ee:_+=F,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=j.bg,b=j.fg,x=j.extended.ext,S=P,C=T,w=M,ne&&a>=k&&a<=re&&(a=k),!this._coreService.isCursorHidden&&N&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`)}}if(j.isBold()&&D.push(`xterm-bold`),j.isItalic()&&D.push(`xterm-italic`),j.isDim()&&D.push(`xterm-dim`),_=j.isInvisible()?ee:j.getChars()||ee,j.isUnderline()&&(D.push(`xterm-underline-${j.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!j.isUnderlineColorDefault())){if(j.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${te.toColorRGB(j.getUnderlineColor()).join(`,`)})`;else{let e=j.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&j.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}j.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),j.isStrikethrough()&&D.push(`xterm-strikethrough`),P&&(h.style.textDecoration=`underline`);let I=j.getFgColor(),L=j.getFgColorMode(),R=j.getBgColor(),ae=j.getBgColorMode(),oe=!!j.isInverse();if(oe){let e=I;I=R,R=e;let t=L;L=ae,ae=t}let z,se,ce=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&ce||(e.backgroundColorRGB&&(ae=50331648,R=e.backgroundColorRGB.rgba>>8&16777215,z=e.backgroundColorRGB),e.foregroundColorRGB&&(L=50331648,I=e.foregroundColorRGB.rgba>>8&16777215,se=e.foregroundColorRGB),ce=e.options.layer===`top`)}),!ce&&M&&(z=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,R=z.rgba>>8&16777215,ae=50331648,ce=!0,p.selectionForeground&&(L=50331648,I=p.selectionForeground.rgba>>8&16777215,se=p.selectionForeground)),ce&&D.push(`xterm-decoration-top`);let le;switch(ae){case 16777216:case 33554432:le=p.ansi[R],D.push(`xterm-bg-${R}`);break;case 50331648:le=Ir.toColor(R>>16,R>>8&255,R&255),this._addStyle(h,`background-color:#${Zr((R>>>0).toString(16),`0`,6)}`);break;default:oe?(le=p.foreground,D.push(`xterm-bg-257`)):le=p.background}switch(z||j.isDim()&&(z=Lr.multiplyOpacity(le,.5)),L){case 16777216:case 33554432:j.isBold()&&I<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(I+=8),this._applyMinimumContrast(h,le,p.ansi[I],j,z,void 0)||D.push(`xterm-fg-${I}`);break;case 50331648:let e=Ir.toColor(I>>16&255,I>>8&255,I&255);this._applyMinimumContrast(h,le,e,j,z,se)||this._addStyle(h,`color:#${Zr(I.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,le,p.foreground,j,z,se)||oe&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!N&&!ne&&!ie&&A?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=re}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||qr(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=Lr.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.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 n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};Xr=f([p(1,ge),p(2,z),p(3,B),p(4,L),p(5,le),p(6,_e)],Xr);function Zr(e,t,n){for(;e.length0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},$r=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function ei(){return new $r}var ti=`xterm-dom-renderer-owner-`,ni=`xterm-rows`,ri=`xterm-fg-`,ii=`xterm-bg-`,ai=`xterm-focus`,oi=`xterm-selection`,si=1,ci=class extends V{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=si++,this._rowElements=[],this._selectionRenderModel=ei(),this.onRequestRedraw=this._register(new H).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(ni),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=Jr(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Xr,document),this._element.classList.add(ti+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(ze(()=>{this._element.classList.remove(ti+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Qr(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 e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${ni} 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} .${ni} { 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} .${ni} .xterm-dim { color: ${Lr.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 n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${ni}.${ai} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${ni}.${ai} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${ni}.${ai} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${ni} .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,r]of e.ansi.entries())t+=`${this._terminalSelector} .${ri}${n} { color: ${r.css}; }${this._terminalSelector} .${ri}${n}.xterm-dim { color: ${Lr.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${ii}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${ri}257 { color: ${Lr.opaque(e.background).css}; }${this._terminalSelector} .${ri}257.xterm-dim { color: ${Lr.multiplyOpacity(Lr.opaque(e.background),.5).css}; }${this._terminalSelector} .${ii}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 e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}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(ai),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ai),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}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 n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${ti}${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,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};ci=f([p(7,ae),p(8,fe),p(9,z),p(10,F),p(11,L),p(12,B),p(13,_e)],ci);var li=class extends V{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new H),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new fi(this._optionsService))}catch{this._measureStrategy=this._register(new di(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())}};li=f([p(2,z)],li);var ui=class extends V{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)}},di=class extends ui{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},fi=class extends ui{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 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}},pi=class extends V{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new mi(this._window)),this._onDprChange=this._register(new H),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new H),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Ye.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(U(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(U(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}},mi=class extends V{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new He),this._onDprChange=this._register(new H),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ze(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=U(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.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)}},hi=class extends V{constructor(){super(),this.linkProviders=[],this._register(ze(()=>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 gi(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function _i(e,t,n,r,i,a,o,s,c){if(!a)return;let l=gi(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var vi=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return _i(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=gi(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};vi=f([p(0,me),p(1,fe)],vi);var yi=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,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=[]}},bi={};d(bi,{getSafariVersion:()=>Di,isChromeOS:()=>Ni,isFirefox:()=>wi,isIpad:()=>ki,isIphone:()=>Ai,isLegacyEdge:()=>Ti,isLinux:()=>Mi,isMac:()=>Oi,isNode:()=>xi,isSafari:()=>Ei,isWindows:()=>ji});var xi=typeof process<`u`&&`title`in process,Si=xi?`node`:navigator.userAgent,Ci=xi?`node`:navigator.platform,wi=Si.includes(`Firefox`),Ti=Si.includes(`Edge`),Ei=/^((?!chrome|android).)*safari/i.test(Si);function Di(){if(!Ei)return 0;let e=Si.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Oi=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(Ci),ki=Ci===`iPad`,Ai=Ci===`iPhone`,ji=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(Ci),Mi=Ci.indexOf(`Linux`)>=0,Ni=/\bCrOS\b/.test(Si),Pi=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ii){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Fi=class extends Pi{_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())}}},Ii=class extends Pi{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Li=!xi&&`requestIdleCallback`in window?Ii:Fi,Ri=class{constructor(){this._queue=new Li}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},zi=class extends V{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new He),this._pausedResizeTask=new Ri,this._observerDisposable=this._register(new He),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 H),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new H),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new H),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new H),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new yi((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Bi(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ze(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.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(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=ze(()=>n.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,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(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),!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(e=>this.refreshRows(e.start,e.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(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),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(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};zi=f([p(2,z),p(3,fe),p(4,L),p(5,le),p(6,F),p(7,B),p(8,_e)],zi);var Bi=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Vi(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return Wi(i,a,e,t,n,r)+Gi(a,t,n,r)+Ki(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,$i(Math.abs(i-e),Qi(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return $i(Ui(a>t?e:i,n)+(s-1)*n.cols+1+Hi(a>t?i:e,n),Qi(o,r))}function Hi(e,t){return e-1}function Ui(e,t){return t.cols-e}function Wi(e,t,n,r,i,a){return Gi(t,r,i,a).length===0?``:$i(Zi(e,t,e,t-Ji(t,i),!1,i).length,Qi(`D`,a))}function Gi(e,t,n,r){let i=e-Ji(e,n),a=t-Ji(t,n);return $i(Math.abs(i-a)-qi(e,t,n),Qi(Xi(e,t),r))}function Ki(e,t,n,r,i,a){let o;o=Gi(t,r,i,a).length>0?r-Ji(r,i):t;let s=r,c=Yi(e,t,n,r,i,a);return $i(Zi(e,o,n,s,c===`C`,i).length,Qi(c,a))}function qi(e,t,n){let r=0,i=e-Ji(e,n),a=t-Ji(t,n);for(let o=0;o=0&&e0?r-Ji(r,i):t,e=n&&ot?`A`:`B`}function Zi(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&sa.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Qi(e,t){let n=t?`O`:`[`;return W.ESC+n+e}function $i(e,t){e=Math.floor(e);let n=``;for(let r=0;rthis._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 ta(e,t){if(e.start.y>e.end.y)throw 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 na=50,ra=15,ia=50,aa=500,oa=RegExp(`\xA0`,`g`),sa=class extends V{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new A,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new H),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new H),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new H),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new H),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new ea(this._bufferService),this._activeSelectionMode=0,this._register(ze(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.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 n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]e.replace(oa,` `)).join(ji?`\r `:` `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),Mi&&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),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=ta(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,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=gi(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-na),na),t/=na,t/Math.abs(t)+Math.round(t*(ra-1)))}shouldForceSelection(e){return Oi?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(),ia)}_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&&!(Oi&&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]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]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&&tthis._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={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=ta(n,this._bufferService.cols)}};sa=f([p(3,F),p(4,L),p(5,pe),p(6,z),p(7,me),p(8,B)],sa);var ca=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},la=class{constructor(){this._color=new ca,this._css=new ca}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},ua=Object.freeze((()=>{let e=[Rr.toColor(`#2e3436`),Rr.toColor(`#cc0000`),Rr.toColor(`#4e9a06`),Rr.toColor(`#c4a000`),Rr.toColor(`#3465a4`),Rr.toColor(`#75507b`),Rr.toColor(`#06989a`),Rr.toColor(`#d3d7cf`),Rr.toColor(`#555753`),Rr.toColor(`#ef2929`),Rr.toColor(`#8ae234`),Rr.toColor(`#fce94f`),Rr.toColor(`#729fcf`),Rr.toColor(`#ad7fa8`),Rr.toColor(`#34e2e2`),Rr.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Ir.toCss(r,i,a),rgba:Ir.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Ir.toCss(n,n,n),rgba:Ir.toRgba(n,n,n)})}return e})()),da=Rr.toColor(`#ffffff`),fa=Rr.toColor(`#000000`),pa=Rr.toColor(`#ffffff`),ma=fa,ha={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},ga=da,_a=class extends V{constructor(e){super(),this._optionsService=e,this._contrastCache=new la,this._halfContrastCache=new la,this._onChangeColors=this._register(new H),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:da,background:fa,cursor:pa,cursorAccent:ma,selectionForeground:void 0,selectionBackgroundTransparent:ha,selectionBackgroundOpaque:Lr.blend(fa,ha),selectionInactiveBackgroundTransparent:ha,selectionInactiveBackgroundOpaque:Lr.blend(fa,ha),scrollbarSliderBackground:Lr.opacity(da,.2),scrollbarSliderHoverBackground:Lr.opacity(da,.4),scrollbarSliderActiveBackground:Lr.opacity(da,.5),overviewRulerBorder:da,ansi:ua.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=G(e.foreground,da),t.background=G(e.background,fa),t.cursor=Lr.blend(t.background,G(e.cursor,pa)),t.cursorAccent=Lr.blend(t.background,G(e.cursorAccent,ma)),t.selectionBackgroundTransparent=G(e.selectionBackground,ha),t.selectionBackgroundOpaque=Lr.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=G(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Lr.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?G(e.selectionForeground,Fr):void 0,t.selectionForeground===Fr&&(t.selectionForeground=void 0),Lr.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Lr.opacity(t.selectionBackgroundTransparent,.3)),Lr.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Lr.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=G(e.scrollbarSliderBackground,Lr.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=G(e.scrollbarSliderHoverBackground,Lr.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=G(e.scrollbarSliderActiveBackground,Lr.opacity(t.foreground,.5)),t.overviewRulerBorder=G(e.overviewRulerBorder,ga),t.ansi=ua.slice(),t.ansi[0]=G(e.black,ua[0]),t.ansi[1]=G(e.red,ua[1]),t.ansi[2]=G(e.green,ua[2]),t.ansi[3]=G(e.yellow,ua[3]),t.ansi[4]=G(e.blue,ua[4]),t.ansi[5]=G(e.magenta,ua[5]),t.ansi[6]=G(e.cyan,ua[6]),t.ansi[7]=G(e.white,ua[7]),t.ansi[8]=G(e.brightBlack,ua[8]),t.ansi[9]=G(e.brightRed,ua[9]),t.ansi[10]=G(e.brightGreen,ua[10]),t.ansi[11]=G(e.brightYellow,ua[11]),t.ansi[12]=G(e.brightBlue,ua[12]),t.ansi[13]=G(e.brightMagenta,ua[13]),t.ansi[14]=G(e.brightCyan,ua[14]),t.ansi[15]=G(e.brightWhite,ua[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;re.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},ba={trace:0,debug:1,info:2,warn:3,error:4,off:5},xa=`xterm.js: `,Sa=class extends V{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),Ca=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=ba[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*K+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*K+0]=e|2097152|t[2]<<22):this._data[e*K+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*K+0]>>22}hasWidth(e){return this._data[e*K+0]&12582912}getFg(e){return this._data[e*K+1]}getBg(e){return this._data[e*K+2]}hasContent(e){return this._data[e*K+0]&4194303}getCodePoint(e){let t=this._data[e*K+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*K+0]&2097152}getString(e){let t=this._data[e*K+0];return t&2097152?this._combined[e]:t&2097151?T(t&2097151):``}isProtected(e){return this._data[e*K+2]&536870912}loadCell(e,t){return Ea=e*K,t.content=this._data[Ea+0],t.fg=this._data[Ea+1],t.bg=this._data[Ea+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*K+0]=t.content,this._data[e*K+1]=t.fg,this._data[e*K+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*K+0]=t|n<<22,this._data[e*K+1]=r.fg,this._data[e*K+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*K+0];r&2097152?this._combined[e]+=T(t):r&2097151?(this._combined[e]=T(r&2097151)+T(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*K+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;rthis.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*Da=0;--e)if(this._data[e*K+0]&4194303)return e+(this._data[e*K+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*K+0]&4194303||this._data[e*K+2]&50331648)return e+(this._data[e*K+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t>22||1}return r&&r.push(t),i}};function ka(e,t,n,r,i,a){let o=[];for(let s=0;s=s&&r0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function Aa(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;oNa(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;sc&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function Na(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Pa=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new H),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Le(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};Pa._nextId=1;var Fa=Pa,Ia={},La=Ia.B;Ia[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:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Ia.A={"#":`£`},Ia.B=void 0,Ia[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Ia.C=Ia[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Ia.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Ia.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Ia.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Ia.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Ia.E=Ia[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Ia.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Ia.H=Ia[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Ia[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var Ra=4294967295,za=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Ta.clone(),this.savedCharset=La,this.markers=[],this._nullCell=A.fromCharData([0,k,1,0]),this._whitespaceCell=A.fromCharData([0,ee,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Li,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new wa(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 ne),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 ne),this._whitespaceCell}getBlankLine(e,t){return new Oa(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&&eRa?Ra:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ta);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 wa(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(Ta),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new Oa(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),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 t=0;t.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._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=ka(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ta),n);if(r.length>0){let n=Aa(this.lines,r);ja(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(Ta),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=Na(c,Math.max(g,0),this._cols))}for(let t=0;t0;)this.ybase===0?this.y0){let e=[],t=[];for(let e=0;e=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Ba=class extends V{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new H),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 za(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new za(!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)}},Va=2,Ha=1,Ua=class extends V{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new H),this.onResize=this._onResize.event,this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Va),this.rows=Math.max(e.rawOptions.rows||0,Ha),this.buffers=this._register(new Ba(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Ua=f([p(0,z)],Ua);var Wa={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:Oi,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Ga=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Ka=class extends V{constructor(e){super(),this._onOptionChange=this._register(new H),this.onOptionChange=this._onOptionChange.event;let t={...Wa};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ze(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Wa))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Wa))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Wa[e],!qa(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Wa[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Ga.includes(t)?t:Wa[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw 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 Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function qa(e){return e===`block`||e===`underline`||e===`bar`}function Ja(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Ja(e[r],t-1);return n}var Ya=Object.freeze({insertMode:!1}),Xa=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Za=class extends V{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new H),this.onData=this._onData.event,this._onUserInput=this._register(new H),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new H),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new H),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Ja(Ya),this.decPrivateModes=Ja(Xa)}reset(){this.modes=Ja(Ya),this.decPrivateModes=Ja(Xa)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.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(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Za=f([p(0,F),p(1,oe),p(2,z)],Za);var Qa={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 $a(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var eo=String.fromCharCode,to={DEFAULT:e=>{let t=[$a(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${eo(t[0])}${eo(t[1])}${eo(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${$a(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${$a(e,!0)};${e.x};${e.y}${t}`}},no=class extends V{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new H),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Qa))this.addProtocol(e,Qa[e]);for(let e of Object.keys(to))this.addEncoding(e,to[e]);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 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 Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};no=f([p(0,F),p(1,L),p(2,z)],no);var ro=[[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]],io=[[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]],ao;function oo(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=co.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return co.createPropertyValue(0,n,r)}},co=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new H,this.onChange=this._onChange.event;let e=new so;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},lo=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 uo(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var fo=2147483647,po=256,mo=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>po)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>fo?fo:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>fo?fo:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,fo):e}},ho=[],go=class{constructor(){this._state=0,this._active=ho,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 n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,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=ho}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=ho,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ho,!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,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,E(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}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 n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=ho,this._id=-1,this._state=0}}},_o=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=E(e,t,n),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(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},vo=[],yo=class{constructor(){this._handlers=Object.create(null),this._active=vo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=vo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,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=vo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||vo,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,E(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=vo,this._ident=0}},bo=new mo;bo.addParam(0);var xo=class{constructor(e){this._handler=e,this._data=``,this._params=bo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():bo,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=E(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=bo,this._data=``,this._hitLimit=!1,e));return this._params=bo,this._data=``,this._hitLimit=!1,t}},So=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;it),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(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(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Co,0,2,0),e.add(Co,8,5,8),e.add(Co,6,0,6),e.add(Co,11,0,11),e.add(Co,13,13,13),e}(),To=class extends V{constructor(e=wo){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 mo,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ze(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new go),this._dcsParser=this._register(new yo),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;tr||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}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 n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,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 n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,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,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),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|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r=t||(r=e[i])<32||r>127&&r>4:i>>8}return n}}function ko(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function Ao(e,t=16){let[n,r,i]=e;return`rgb:${ko(n,t)}/${ko(r,t)}/${ko(i,t)}`}var jo={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Mo=131072,No=10;function Po(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 Fo=5e3,Io=0,Lo=class extends V{constructor(e,t,n,r,i,a,o,s,c=new To){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new D,this._utf8Decoder=new O,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ta.clone(),this._eraseAttrDataInternal=Ta.clone(),this._onRequestBell=this._register(new H),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new H),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new H),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new H),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new H),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new H),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new H),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new H),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new H),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new H),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new H),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new H),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 Ro(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(W.BEL,()=>this.bell()),this._parser.setExecuteHandler(W.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(W.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(W.BS,()=>this.backspace()),this._parser.setExecuteHandler(W.HT,()=>this.tab()),this._parser.setExecuteHandler(W.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(W.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Or.IND,()=>this.index()),this._parser.setExecuteHandler(Or.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Or.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new _o(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new _o(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new _o(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new _o(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new _o(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new _o(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new _o(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new _o(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new _o(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new _o(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new _o(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new _o(e=>this.restoreCursorColor(e))),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 e in Ia)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new xo((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),Fo))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${Fo} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Mo&&(a=this._parseStack.position+Mo)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.lengthMo)for(let t=a;t0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;ps){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,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),m>0&&d instanceof Oa&&d.copyCellsFrom(e,t,0,m,!1);t=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!Po(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new xo(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _o(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(){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&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}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)}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.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=s;for(let e=1;e0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(W.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(W.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(W.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(W.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(W.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${W.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=te.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Ta.fg,e.bg=Ta.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=Ta.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=Ta.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=Ta.fg&16777215,r.bg&=-67108864,r.bg|=Ta.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${W.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.ESC}[?${e};${t}R`)}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=Ta.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`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Po(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(`${W.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>No&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>No&&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())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(zo(n)){if(r===`?`)t.push({type:0,index:n});else{let e=Oo(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Oo(n[e]);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=[],n=e.split(`;`);for(let e=0;e=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=Ta.clone(),this._eraseAttrDataInternal=Ta.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 A;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${W.ESC}${e}${W.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Ro=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Io=e,e=t,t=Io),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Ro=f([p(0,F)],Ro);function zo(e){return 0<=e&&e<256}var Bo=5e7,Vo=12,Ho=50,Uo=class extends V{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 H),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 n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Bo)throw 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 n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=Vo?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=Vo)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Ho&&(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()}},Wo=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 n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Wo=f([p(0,F)],Wo);var Go=!1,Ko=class extends V{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new He),this._onBinary=this._register(new H),this.onBinary=this._onBinary.event,this._onData=this._register(new H),this.onData=this._onData.event,this._onLineFeed=this._register(new H),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new H),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new H),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new H),this._instantiationService=new ya,this.optionsService=this._register(new Ka(e)),this._instantiationService.setService(z,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Ua)),this._instantiationService.setService(F,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Sa)),this._instantiationService.setService(oe,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Za)),this._instantiationService.setService(L,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(no)),this._instantiationService.setService(I,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(co)),this._instantiationService.setService(ce,this.unicodeService),this._charsetService=this._instantiationService.createInstance(lo),this._instantiationService.setService(R,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Wo),this._instantiationService.setService(se,this._oscLinkService),this._inputHandler=this._register(new Lo(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Ye.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Ye.forward(this._bufferService.onResize,this._onResize)),this._register(Ye.forward(this.coreService.onData,this._onData)),this._register(Ye.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 Uo((e,t)=>this._inputHandler.parse(e,t))),this._register(Ye.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new H),this._onScroll.event(e=>{this._onScrollApi?.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&&!Go&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Go=!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,Va),t=Math.max(t,Ha),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(uo.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(uo(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ze(()=>{for(let t of e)t.dispose()})}}},qo={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 Jo(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?W.ESC+`OA`:W.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?W.ESC+`OD`:W.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?W.ESC+`OC`:W.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?W.ESC+`OB`:W.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:W.DEL,e.altKey&&(i.key=W.ESC+i.key);break;case 9:if(e.shiftKey){i.key=W.ESC+`[Z`;break}i.key=W.HT,i.cancel=!0;break;case 13:i.key=e.altKey?W.ESC+W.CR:W.CR,i.cancel=!0;break;case 27:i.key=W.ESC,e.altKey&&(i.key=W.ESC+W.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`D`:t?W.ESC+`OD`:W.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`C`:t?W.ESC+`OC`:W.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`A`:t?W.ESC+`OA`:W.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`B`:t?W.ESC+`OB`:W.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=W.ESC+`[2~`);break;case 46:i.key=a?W.ESC+`[3;`+(a+1)+`~`:W.ESC+`[3~`;break;case 36:i.key=a?W.ESC+`[1;`+(a+1)+`H`:t?W.ESC+`OH`:W.ESC+`[H`;break;case 35:i.key=a?W.ESC+`[1;`+(a+1)+`F`:t?W.ESC+`OF`:W.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?W.ESC+`[5;`+(a+1)+`~`:W.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?W.ESC+`[6;`+(a+1)+`~`:W.ESC+`[6~`;break;case 112:i.key=a?W.ESC+`[1;`+(a+1)+`P`:W.ESC+`OP`;break;case 113:i.key=a?W.ESC+`[1;`+(a+1)+`Q`:W.ESC+`OQ`;break;case 114:i.key=a?W.ESC+`[1;`+(a+1)+`R`:W.ESC+`OR`;break;case 115:i.key=a?W.ESC+`[1;`+(a+1)+`S`:W.ESC+`OS`;break;case 116:i.key=a?W.ESC+`[15;`+(a+1)+`~`:W.ESC+`[15~`;break;case 117:i.key=a?W.ESC+`[17;`+(a+1)+`~`:W.ESC+`[17~`;break;case 118:i.key=a?W.ESC+`[18;`+(a+1)+`~`:W.ESC+`[18~`;break;case 119:i.key=a?W.ESC+`[19;`+(a+1)+`~`:W.ESC+`[19~`;break;case 120:i.key=a?W.ESC+`[20;`+(a+1)+`~`:W.ESC+`[20~`;break;case 121:i.key=a?W.ESC+`[21;`+(a+1)+`~`:W.ESC+`[21~`;break;case 122:i.key=a?W.ESC+`[23;`+(a+1)+`~`:W.ESC+`[23~`;break;case 123:i.key=a?W.ESC+`[24;`+(a+1)+`~`:W.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=W.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=W.DEL:e.keyCode===219?i.key=W.ESC:e.keyCode===220?i.key=W.FS:e.keyCode===221&&(i.key=W.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=qo[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=W.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=W.ESC+n}else if(e.keyCode===32)i.key=W.ESC+(e.ctrlKey?W.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=W.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=W.US),e.key===`@`&&(i.key=W.NUL))}return i}var Yo=0,Xo=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Li,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Li,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((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,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||(Yo=this._search(t),Yo===-1)||this._getKey(this._array[Yo])!==t)return!1;do if(this._array[Yo]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Yo),!0;while(++Yoe-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Yo=this._search(e),!(Yo<0||Yo>=this._array.length)&&this._getKey(this._array[Yo])===e))do yield this._array[Yo];while(++Yo=this._array.length)&&this._getKey(this._array[Yo])===e))do t(this._array[Yo]);while(++Yo=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Zo=0,Qo=0,$o=class extends V{constructor(){super(),this._decorations=new Xo(e=>e?.marker.line),this._onDecorationRegistered=this._register(new H),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new H),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ze(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new es(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e{Zo=t.options.x??0,Qo=Zo+(t.options.width??1),e>=Zo&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_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)}},rs=20,is=class extends V{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new ns(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(U(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ze(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` `&&(this._liveRegionLineCount++,this._liveRegionLineCount===rs+1&&(this._liveRegion.textContent+=_.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}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(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)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{Le(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(U(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(U(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(U(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(U(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;tthis._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;ethis._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&os(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,Le(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||e.link.decorations.underline,pointerCursor:e.link.decorations===void 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:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};as=f([p(1,pe),p(2,me),p(3,F),p(4,ve)],as);function os(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 ss=class extends Ko{constructor(e={}){super(e),this._linkifier=this._register(new He),this.browser=bi,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new He),this._onCursorMove=this._register(new H),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new H),this.onKey=this._onKey.event,this._onRender=this._register(new H),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new H),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new H),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new H),this.onBell=this._onBell.event,this._onFocus=this._register(new H),this._onBlur=this._register(new H),this._onA11yCharEmitter=this._register(new H),this._onA11yTabEmitter=this._register(new H),this._onWillOpen=this._register(new H),this._setup(),this._decorationService=this._instantiationService.createInstance($o),this._instantiationService.setService(le,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(hi),this._instantiationService.setService(ve,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(ue)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Ye.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ye.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ye.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ye.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(ze(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.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 e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=Lr.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${W.ESC}]${n};${Ao(r)}${kr.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Ir.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Ir.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_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(is,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(W.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(W.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 n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(U(this.element,`copy`,e=>{this.hasSelection()&&b(e,this._selectionService)}));let e=e=>x(e,this.textarea,this.coreService,this.optionsService);this._register(U(this.textarea,`paste`,e)),this._register(U(this.element,`paste`,e)),wi?this._register(U(this.element,`mousedown`,e=>{e.button===2&&w(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(U(this.element,`contextmenu`,e=>{w(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Mi&&this._register(U(this.element,`auxclick`,e=>{e.button===1&&C(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(U(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(U(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(U(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(U(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(U(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(U(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(U(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw 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`),this.element?.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(U(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,h.get()),Ni||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`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(pi,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(B,this._coreBrowserService),this._register(U(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(U(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(li,this._document,this._helperContainer),this._instantiationService.setService(fe,this._charSizeService),this._themeService=this._instantiationService.createInstance(_a),this._instantiationService.setService(_e,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Wr),this._instantiationService.setService(ge,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(zi,this.rows,this.screenElement)),this._instantiationService.setService(me,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(Ar,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(vi),this._instantiationService.setService(pe,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(as,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(xr,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(sa,this.element,this.screenElement,r)),this._instantiationService.setService(he,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Ye.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(Sr,this.screenElement)),this._register(U(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),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(is,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Dr,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Dr,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ci,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),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()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(U(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(U(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=W.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.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){S(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 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 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,n){this._selectionService.setSelection(e,t,n)}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(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.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 n=Jo(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.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((n.key===W.ETX||n.key===W.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=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`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(cs(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){this._charSizeService?.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=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new A)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},ds=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 us(t)}getNullCell(){return new A}},fs=class extends V{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new H),this.onBufferChange=this._onBufferChange.event,this._normal=new ds(this._core.buffers.normal,`normal`),this._alternate=new ds(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 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)}},ps=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.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)}},ms=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}},hs=[`cols`,`rows`],gs=0,_s=class extends V{constructor(e){super(),this._core=this._register(new ss(e)),this._addonManager=this._register(new ls),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(hs.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw 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||=new ps(this._core),this._parser}get unicode(){return this._checkProposedApi(),new ms(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._register(new fs(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`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r `,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 h.get()},set promptLabel(e){h.set(e)},get tooMuchOutput(){return _.get()},set tooMuchOutput(e){_.set(e)}}}_verifyIntegers(...e){for(gs of e)if(gs===1/0||isNaN(gs)||gs%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(gs of e)if(gs&&(gs===1/0||isNaN(gs)||gs%1!=0||gs<0))throw Error(`This API only accepts positive integers`)}},vs=2,ys=1,bs=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(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(vs,Math.floor(u/e.css.cell.width)),rows:Math.max(ys,Math.floor(l/e.css.cell.height))}}},xs=[[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]],Ss=[[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]],Cs;function ws(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=lc.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return lc.createPropertyValue(0,n,r)}},Es=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?js.isErrorNoTelemetry(e)?new js(e.message+` `+e.stack):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)}};function Ds(e){ks(e)||Es.onUnexpectedError(e)}var Os=`Canceled`;function ks(e){return e instanceof As||e instanceof Error&&e.name===Os&&e.message===Os}var As=class extends Error{constructor(){super(Os),this.name=this.message}},js=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}};function Ms(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var Ns;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Ns||={});var Ps=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||Ns.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};Ps.empty=new Ps(e=>{});var Fs;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Vs(...e){return Hs(()=>Bs(e))}function Hs(e){let t=Ls({dispose:Ms(()=>{Rs(t),e()})});return t}var Us=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,Ls(this)}dispose(){this._isDisposed||(Rs(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Bs(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return zs(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(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(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),zs(e,null))}};Us.DISABLE_DISPOSED_WARNING=!1;var Ws=Us,Gs=class{constructor(){this._store=new Ws,Ls(this),zs(this._store,this)}dispose(){Rs(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};Gs.None=Object.freeze({dispose(){}});var Ks=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Ks.Undefined=new Ks(void 0);var qs=globalThis.performance&&typeof globalThis.performance.now==`function`,Js=class e{static create(t){return new e(t)}constructor(e){this._now=qs&&e===!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._now()-this._startTime:this._stopTime-this._startTime}},Ys;(e=>{e.None=()=>Gs.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(Vs(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new sc({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new sc({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new sc({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new sc({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new sc({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new sc;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new sc(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Ws?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(Ys||={});var Xs=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Js,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Xs.all=new Set,Xs._idPool=0;var Zs=Xs,Qs=-1,$s=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t0||this._options?.leakWarningThreshold?new ec(e?.onListenerError??Ds,this._options?.leakWarningThreshold??Qs):void 0,this._perfMon=this._options?._profName?new Zs(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new rc(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||Ds)(n),Gs.None}if(this._disposed)return Gs.None;t&&(e=e.bind(t));let r=new ac(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=tc.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ac?(this._deliveryQueue??=new cc,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=Hs(()=>{i?.(),this._removeListener(r)});return n instanceof Ws?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*oc<=t.length){let e=0;for(let n=0;n0}},cc=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},lc=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new sc,this.onChange=this._onChange.event;let e=new Ts;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},uc=0,dc=-3,fc=class{constructor(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}},pc=class{constructor(e,t){this.tag=0,this.bitcount=0,this.destLen=0,this.sourceIndex=0,this.source=e,this.dest=t,this.ltree=new fc,this.dtree=new fc}},mc=new fc,hc=new fc,gc=new Uint8Array(30),_c=new Uint16Array(30),vc=new Uint8Array(30),yc=new Uint16Array(30),bc=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),xc=new fc,Sc=new Uint8Array(320);function Cc(e,t,n,r){for(var i=0,a;i>>=1,t}function Oc(e,t,n){if(!t)return n;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,r+n}function kc(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++i,n+=t.table[i],r-=t.table[i];while(r>=0);return e.tag=a,e.bitcount-=i,t.trans[n+r]}function Ac(e,t,n){for(var r=Oc(e,5,257),i=Oc(e,5,1),a=Oc(e,4,4),o=0,s,c;o<19;++o)Sc[o]=0;for(o=0;o8;)e.sourceIndex--,e.bitcount-=8;if(t=e.source[e.sourceIndex+1],t=256*t+e.source[e.sourceIndex],n=e.source[e.sourceIndex+3],n=256*n+e.source[e.sourceIndex+2],t!==(~n&65535))return dc;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,uc}function Nc(e,t){var n=new pc(e,t),r,i,a;do{switch(r=Dc(n),i=Oc(n,2,0),i){case 0:a=Mc(n);break;case 1:a=jc(n,mc,hc);break;case 2:Ac(n,n.ltree,n.dtree),a=jc(n,n.ltree,n.dtree);break;default:a=dc}if(a!==uc)throw Error(`Data error`)}while(!r);return n.destLen>Fc,zc=(1<>Ic,Uc=Hc+(1024>>Ic)+32,Wc=1<1114111?this.errorValue:e<55296||e>56319&&e<=65535?(t=(this.data[e>>Ic]<>Ic)]<>Fc)],t=this.data[t+(e>>Ic&zc)],t=(t<>$c}function ml(e,t){let n=(e&Xc)>>Zc,r=(t&Xc)>>Zc;return hl(n,r)?r===rl?fl:r+16:r-16}function hl(e,t){return e>=al&&e<=ll&&(e==al&&(t==al||t==ol||t==cl||t==ll)||(e==cl||e==ol)&&(t==ol||t==sl)||(e==ll||e==sl)&&t==sl)||t==nl||t==ul||e==tl||t==il||e==ul&&t==dl||t==rl&&e==rl}function gl(e){return Yc.get(e)}var _l=class e{constructor(e=!0){this.ambiguousCharsAreWide=!1,this.version=e?`15-graphemes`:`15`,this.handleGraphemes=e}charProperties(t,n){if(t>=32&&t<127&&!(n>>3))return e._plainNarrowProperties;let r=gl(t),i=pl(r),a=!1;if(i=i>=2&&(i===3||this.ambiguousCharsAreWide||t===65039)?2:1,n!==0){let e=lc.extractWidth(n);r=this.handleGraphemes?ml(lc.extractCharKind(n),r):+(i===0),a=r>0,a&&(e>i?i=e:r===32&&(i=2))}return lc.createPropertyValue(r,i,a)}wcwidth(e){let t=gl(e),n=pl(t),r=(t&Xc)>>Zc;return r===nl||r===tl?0:n>=2&&(n===3||this.ambiguousCharsAreWide)?2:1}};_l._plainNarrowProperties=lc.createPropertyValue(el,1,!1);var vl=_l,yl=class{constructor(){this._oldVersion=``}activate(e){this._provider15||=new vl(!1),this._provider15Graphemes||=new vl(!0);let t=e.unicode;this._unicode=t,t.register(this._provider15),t.register(this._provider15Graphemes),this._oldVersion=t.activeVersion,t.activeVersion=`15-graphemes`}dispose(){this._unicode&&(this._unicode.activeVersion=this._oldVersion)}},bl=o((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;ac?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),xl=o((e=>{e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),Sl=o((e=>{var t=bl(),n=xl(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(_e(e,ArrayBuffer)||e&&_e(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(_e(e,SharedArrayBuffer)||e&&_e(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);let i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){let t=e.length<0?0:_(e.length)|0,n=o(t);for(let r=0;r=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),_e(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);ir.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else if(s.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||_e(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return B(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return he(e).length;default:if(i)return r?-1:B(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return j(this,t,n);case`utf8`:case`utf-8`:return ee(this,t,n);case`ascii`:return A(this,t,n);case`latin1`:case`binary`:return re(this,t,n);case`base64`:return k(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return M(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;tn&&(t+=` ... `),``},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,ve(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(i)n=0;else return-1}if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;lo&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;ri&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o=0;for(;o>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function ee(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return ne(r)}var te=4096;function ne(e){let t=e.length;if(t<=te)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;rr)&&(n=r);let i=``;for(let r=t;rn&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),tn)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);let r=this[e],i=1,a=0;for(;++a>>=0,t>>>=0,n||N(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t+this[++e]*256+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*256+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*256+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*256+n;return(BigInt(r)<>>=0,t>>>=0,n||N(e,t,this.length);let r=this[e],i=1,a=0;for(;++a=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=this[e+4]+this[e+5]*256+this[e+6]*2**16+(n<<24);return(BigInt(r)<>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*256+this[++e];return(BigInt(r)<>>=0,t||N(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!1,52,8)};function P(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||te.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;P(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a>>=0,n>>>=0,!r){let r=2**(8*n)-1;P(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function ie(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function F(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}s.prototype.writeBigUInt64LE=be(function(e,t=0){return ie(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=be(function(e,t=0){return F(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);P(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);P(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=be(function(e,t=0){return ie(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=be(function(e,t=0){return F(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function I(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function L(e,t,r,i,a){return t=+t,r>>>=0,a||I(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)};function R(e,t,r,i,a){return t=+t,r>>>=0,a||I(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i2**32?i=z(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=z(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function z(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function se(e,t,n){le(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&ue(t,e.length-(n+1))}function ce(e,t,n,r,i,a){if(e>n||e3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new ae.ERR_OUT_OF_RANGE(`value`,i,e)}se(r,i,a)}function le(e,t){if(typeof e!=`number`)throw new ae.ERR_INVALID_ARG_TYPE(t,`number`,e)}function ue(e,t,n){throw Math.floor(e)===e?t<0?new ae.ERR_BUFFER_OUT_OF_BOUNDS:new ae.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(le(e,n),new ae.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var de=/[^+/0-9A-Za-z-_]/g;function fe(e){if(e=e.split(`=`)[0],e=e.trim().replace(de,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function B(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function pe(e){let t=[];for(let n=0;n>8,i=n%256,a.push(i),a.push(r);return a}function he(e){return t.toByteArray(fe(e))}function ge(e,t,n,r){let i=0;for(;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function _e(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function ve(e){return e!==e}var ye=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function be(e){return typeof BigInt>`u`?xe:e}function xe(){throw Error(`BigInt not supported`)}}))(),Cl=globalThis.performance,wl={env:{TERM:`xterm-256color`,TERM_PROGRAM:`xtermjs`},platform:`browser`,nextTick:e=>queueMicrotask(e)},Tl=new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?".split(``)),q={shift:1,alt:2,ctrl:4,super:8},El=192,J={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},Dl={up:-1,down:-2,right:-3,left:-4},Ol={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},kl=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,Dl.left],[57418,Dl.right],[57419,Dl.up],[57420,Dl.down],[57421,Ol.pageUp],[57422,Ol.pageDown],[57423,Ol.home],[57424,Ol.end],[57425,Ol.insert],[57426,Ol.delete]]);function Al(e){return kl.get(e)??e}function jl(e,t){return t&-193&q.shift&&e>=65&&e<=90?e+32:e}var Ml={up:[`\x1B[A`,`\x1BOA`],down:[`\x1B[B`,`\x1BOB`],right:[`\x1B[C`,`\x1BOC`],left:[`\x1B[D`,`\x1BOD`],home:[`\x1B[H`,`\x1BOH`,`\x1B[1~`,`\x1B[7~`],end:[`\x1B[F`,`\x1BOF`,`\x1B[4~`,`\x1B[8~`],insert:[`\x1B[2~`],delete:[`\x1B[3~`],pageUp:[`\x1B[5~`,`\x1B[[5~`],pageDown:[`\x1B[6~`,`\x1B[[6~`],clear:[`\x1B[E`,`\x1BOE`],f1:[`\x1BOP`,`\x1B[11~`,`\x1B[[A`],f2:[`\x1BOQ`,`\x1B[12~`,`\x1B[[B`],f3:[`\x1BOR`,`\x1B[13~`,`\x1B[[C`],f4:[`\x1BOS`,`\x1B[14~`,`\x1B[[D`],f5:[`\x1B[15~`,`\x1B[[E`],f6:[`\x1B[17~`],f7:[`\x1B[18~`],f8:[`\x1B[19~`],f9:[`\x1B[20~`],f10:[`\x1B[21~`],f11:[`\x1B[23~`],f12:[`\x1B[24~`]},Nl={up:[`\x1B[a`],down:[`\x1B[b`],right:[`\x1B[c`],left:[`\x1B[d`],clear:[`\x1B[e`],insert:[`\x1B[2$`],delete:[`\x1B[3$`],pageUp:[`\x1B[5$`],pageDown:[`\x1B[6$`],home:[`\x1B[7$`],end:[`\x1B[8$`]},Pl={up:[`\x1BOa`],down:[`\x1BOb`],right:[`\x1BOc`],left:[`\x1BOd`],clear:[`\x1BOe`],insert:[`\x1B[2^`],delete:[`\x1B[3^`],pageUp:[`\x1B[5^`],pageDown:[`\x1B[6^`],home:[`\x1B[7^`],end:[`\x1B[8^`]},Fl=(e,t)=>t.includes(e),Il=(e,t,n)=>n===q.shift?Fl(e,Nl[t]):n===q.ctrl&&Fl(e,Pl[t]);function Ll(e){return!e.includes(`\x1B[200~`)&&!!(e.includes(`:3u`)||e.includes(`:3~`)||e.includes(`:3A`)||e.includes(`:3B`)||e.includes(`:3C`)||e.includes(`:3D`)||e.includes(`:3H`)||e.includes(`:3F`))}function Rl(e){if(!e)return`press`;let t=parseInt(e,10);return t===2?`repeat`:t===3?`release`:`press`}function zl(e){let t=e.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(t){let e=parseInt(t[1],10),n=t[2]&&t[2].length>0?parseInt(t[2],10):void 0,r=t[3]?parseInt(t[3],10):void 0,i=t[4]?parseInt(t[4],10):1,a=Rl(t[5]);return{codepoint:e,shiftedKey:n,baseLayoutKey:r,modifier:i-1,eventType:a}}let n=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(n){let e=parseInt(n[1],10),t=Rl(n[2]);return{codepoint:{A:-1,B:-2,C:-3,D:-4}[n[3]],modifier:e-1,eventType:t}}let r=e.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(r){let e=parseInt(r[1],10),t=r[2]?parseInt(r[2],10):1,n=Rl(r[3]),i={2:Ol.insert,3:Ol.delete,5:Ol.pageUp,6:Ol.pageDown,7:Ol.home,8:Ol.end}[e];if(i!==void 0)return{codepoint:i,modifier:t-1,eventType:n}}let i=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(i){let e=parseInt(i[1],10),t=Rl(i[2]);return{codepoint:i[3]===`H`?Ol.home:Ol.end,modifier:e-1,eventType:t}}return null}function Y(e,t,n){let r=zl(e);if(!r||(r.modifier&-193)!=(n&-193))return!1;let i=jl(Al(r.codepoint),r.modifier);if(i===jl(Al(t),n))return!0;if(r.baseLayoutKey!==void 0&&r.baseLayoutKey===t){let e=i,t=e>=97&&e<=122,n=Tl.has(String.fromCharCode(e));if(!t&&!n)return!0}return!1}function Bl(e){let t=e.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!t)return null;let n=parseInt(t[1],10);return{codepoint:parseInt(t[2],10),modifier:n-1}}function Vl(e,t,n){let r=Bl(e);return r?r.codepoint===t&&r.modifier===n:!1}function Hl(){return!!wl.env.WT_SESSION&&!wl.env.SSH_CONNECTION&&!wl.env.SSH_CLIENT&&!wl.env.SSH_TTY}function Ul(e,t){return e===``?t===0:e===`\b`?Hl()?t===q.ctrl:t===0:!1}function Wl(e){let t=e.toLowerCase(),n=t.charCodeAt(0);return n>=97&&n<=122||t===`[`||t===`\\`||t===`]`||t===`_`?String.fromCharCode(n&31):t===`-`?``:null}function Gl(e){return e>=`0`&&e<=`9`}function Kl(e,t,n){if(n===0)return!1;let r=Bl(e);return!r||r.modifier!==n?!1:jl(r.codepoint,r.modifier)===jl(t,n)}function ql(e){let t=e.toLowerCase().split(`+`),n=t[t.length-1];return n?{key:n,ctrl:t.includes(`ctrl`),shift:t.includes(`shift`),alt:t.includes(`alt`),super:t.includes(`super`)}:null}function Jl(e,t){let n=ql(t);if(!n)return!1;let{key:r,ctrl:i,shift:a,alt:o,super:s}=n,c=0;switch(a&&(c|=q.shift),o&&(c|=q.alt),i&&(c|=q.ctrl),s&&(c|=q.super),r){case`escape`:case`esc`:return c===0?e===`\x1B`||Y(e,J.escape,0)||Vl(e,J.escape,0):!1;case`space`:return c===q.ctrl&&e===`\0`||c===q.alt&&e===`\x1B `?!0:c===0?e===` `||Y(e,J.space,0)||Vl(e,J.space,0):Y(e,J.space,c)||Vl(e,J.space,c);case`tab`:return c===q.shift?e===`\x1B[Z`||Y(e,J.tab,q.shift)||Vl(e,J.tab,q.shift):c===0?e===` `||Y(e,J.tab,0):Y(e,J.tab,c)||Vl(e,J.tab,c);case`enter`:case`return`:return c===q.shift?!!(Y(e,J.enter,q.shift)||Y(e,J.kpEnter,q.shift)||Vl(e,J.enter,q.shift)):c===q.alt?Y(e,J.enter,q.alt)||Y(e,J.kpEnter,q.alt)||Vl(e,J.enter,q.alt)?!0:e===`\x1B\r`:c===0?e===`\r`||e===` `||e===`\x1BOM`||Y(e,J.enter,0)||Y(e,J.kpEnter,0):Y(e,J.enter,c)||Y(e,J.kpEnter,c)||Vl(e,J.enter,c);case`backspace`:return c===q.alt?e===`\x1B`||e===`\x1B\b`||Y(e,J.backspace,q.alt)||Vl(e,J.backspace,q.alt):c===q.ctrl?Ul(e,q.ctrl)?!0:Y(e,J.backspace,q.ctrl)||Vl(e,J.backspace,q.ctrl):c===0?Ul(e,0)||Y(e,J.backspace,0)||Vl(e,J.backspace,0):Y(e,J.backspace,c)||Vl(e,J.backspace,c);case`insert`:return c===0?Fl(e,Ml.insert)||Y(e,Ol.insert,0):Il(e,`insert`,c)?!0:Y(e,Ol.insert,c);case`delete`:return c===0?Fl(e,Ml.delete)||Y(e,Ol.delete,0):Il(e,`delete`,c)?!0:Y(e,Ol.delete,c);case`clear`:return c===0?Fl(e,Ml.clear):Il(e,`clear`,c);case`home`:return c===0?Fl(e,Ml.home)||Y(e,Ol.home,0):Il(e,`home`,c)?!0:Y(e,Ol.home,c);case`end`:return c===0?Fl(e,Ml.end)||Y(e,Ol.end,0):Il(e,`end`,c)?!0:Y(e,Ol.end,c);case`pageup`:return c===0?Fl(e,Ml.pageUp)||Y(e,Ol.pageUp,0):Il(e,`pageUp`,c)?!0:Y(e,Ol.pageUp,c);case`pagedown`:return c===0?Fl(e,Ml.pageDown)||Y(e,Ol.pageDown,0):Il(e,`pageDown`,c)?!0:Y(e,Ol.pageDown,c);case`up`:return c===q.alt?e===`\x1Bp`||Y(e,Dl.up,q.alt):c===0?Fl(e,Ml.up)||Y(e,Dl.up,0):Il(e,`up`,c)?!0:Y(e,Dl.up,c);case`down`:return c===q.alt?e===`\x1Bn`||Y(e,Dl.down,q.alt):c===0?Fl(e,Ml.down)||Y(e,Dl.down,0):Il(e,`down`,c)?!0:Y(e,Dl.down,c);case`left`:return c===q.alt?e===`\x1B[1;3D`||e===`\x1BB`||e===`\x1Bb`||Y(e,Dl.left,q.alt):c===q.ctrl?e===`\x1B[1;5D`||Il(e,`left`,q.ctrl)||Y(e,Dl.left,q.ctrl):c===0?Fl(e,Ml.left)||Y(e,Dl.left,0):Il(e,`left`,c)?!0:Y(e,Dl.left,c);case`right`:return c===q.alt?e===`\x1B[1;3C`||e===`\x1BF`||e===`\x1Bf`||Y(e,Dl.right,q.alt):c===q.ctrl?e===`\x1B[1;5C`||Il(e,`right`,q.ctrl)||Y(e,Dl.right,q.ctrl):c===0?Fl(e,Ml.right)||Y(e,Dl.right,0):Il(e,`right`,c)?!0:Y(e,Dl.right,c);case`f1`:case`f2`:case`f3`:case`f4`:case`f5`:case`f6`:case`f7`:case`f8`:case`f9`:case`f10`:case`f11`:case`f12`:return c===0&&Fl(e,Ml[r])}if(r.length===1&&(r>=`a`&&r<=`z`||Gl(r)||Tl.has(r))){let t=r.charCodeAt(0),n=Wl(r),i=r>=`a`&&r<=`z`,a=Gl(r);return c===q.ctrl+q.alt&&n&&e===`\x1b${n}`||c===q.alt&&(i||a||Tl.has(r))&&e===`\x1b${r}`?!0:c===q.ctrl?n&&e===n?!0:Y(e,t,q.ctrl)||Kl(e,t,q.ctrl):c===q.shift+q.ctrl?Y(e,t,q.shift+q.ctrl)||Kl(e,t,q.shift+q.ctrl):c===q.shift?i&&e===r.toUpperCase()?!0:Y(e,t,q.shift)||Kl(e,t,q.shift):c===0?e===r||Y(e,t,0):Y(e,t,c)||Kl(e,t,c)}return!1}var Yl=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,Xl=q.shift|El;function Zl(e){let t=e.match(Yl);if(!t)return;let n=Number.parseInt(t[1]??``,10);if(!Number.isFinite(n))return;let r=t[2]&&t[2].length>0?Number.parseInt(t[2],10):void 0,i=t[4]?Number.parseInt(t[4],10):1,a=Number.isFinite(i)?i-1:0;if((a&~Xl)!==0||a&(q.alt|q.ctrl))return;let o=n;if(a&q.shift&&typeof r==`number`&&(o=r),o=Al(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}function Ql(e){let t=Bl(e);if(t&&!(t.modifier&-193&~q.shift)&&!(!Number.isFinite(t.codepoint)||t.codepoint<32))try{return String.fromCodePoint(t.codepoint)}catch{return}}function $l(e){return Zl(e)??Ql(e)}var eu={"tui.editor.cursorUp":{defaultKeys:`up`,description:`Move cursor up`},"tui.editor.cursorDown":{defaultKeys:`down`,description:`Move cursor down`},"tui.editor.historyPrevious":{defaultKeys:[],description:`Select previous prompt history entry`},"tui.editor.historyNext":{defaultKeys:[],description:`Select next prompt history entry`},"tui.editor.cursorLeft":{defaultKeys:[`left`,`ctrl+b`],description:`Move cursor left`},"tui.editor.cursorRight":{defaultKeys:[`right`,`ctrl+f`],description:`Move cursor right`},"tui.editor.cursorWordLeft":{defaultKeys:[`alt+left`,`ctrl+left`,`alt+b`],description:`Move cursor word left`},"tui.editor.cursorWordRight":{defaultKeys:[`alt+right`,`ctrl+right`,`alt+f`],description:`Move cursor word right`},"tui.editor.cursorLineStart":{defaultKeys:[`home`,`ctrl+home`,`ctrl+a`],description:`Move to line start`},"tui.editor.cursorLineEnd":{defaultKeys:[`end`,`ctrl+end`,`ctrl+e`],description:`Move to line end`},"tui.editor.jumpForward":{defaultKeys:`ctrl+]`,description:`Jump forward to character`},"tui.editor.jumpBackward":{defaultKeys:`ctrl+alt+]`,description:`Jump backward to character`},"tui.editor.pageUp":{defaultKeys:[`pageUp`,`ctrl+pageUp`],description:`Page up`},"tui.editor.pageDown":{defaultKeys:[`pageDown`,`ctrl+pageDown`],description:`Page down`},"tui.editor.deleteCharBackward":{defaultKeys:`backspace`,description:`Delete character backward`},"tui.editor.deleteCharForward":{defaultKeys:[`delete`,`ctrl+d`],description:`Delete character forward`},"tui.editor.deleteWordBackward":{defaultKeys:[`ctrl+w`,`alt+backspace`],description:`Delete word backward`},"tui.editor.deleteWordForward":{defaultKeys:[`alt+d`,`alt+delete`],description:`Delete word forward`},"tui.editor.deleteToLineStart":{defaultKeys:`ctrl+u`,description:`Delete to line start`},"tui.editor.deleteToLineEnd":{defaultKeys:`ctrl+k`,description:`Delete to line end`},"tui.editor.yank":{defaultKeys:`ctrl+y`,description:`Yank`},"tui.editor.yankPop":{defaultKeys:`alt+y`,description:`Yank pop`},"tui.editor.undo":{defaultKeys:`ctrl+-`,description:`Undo`},"tui.input.newLine":{defaultKeys:[`shift+enter`,`ctrl+j`],description:`Insert newline`},"tui.input.submit":{defaultKeys:`enter`,description:`Submit input`},"tui.input.tab":{defaultKeys:`tab`,description:`Tab / autocomplete`},"tui.input.copy":{defaultKeys:`ctrl+c`,description:`Copy selection`},"tui.select.up":{defaultKeys:`up`,description:`Move selection up`},"tui.select.down":{defaultKeys:`down`,description:`Move selection down`},"tui.select.pageUp":{defaultKeys:`pageUp`,description:`Selection page up`},"tui.select.pageDown":{defaultKeys:`pageDown`,description:`Selection page down`},"tui.select.confirm":{defaultKeys:`enter`,description:`Confirm selection`},"tui.select.cancel":{defaultKeys:[`escape`,`ctrl+c`],description:`Cancel selection`},"tui.altScreen.pageUp":{defaultKeys:`pageUp`,description:`Scroll viewport up one page`},"tui.altScreen.pageDown":{defaultKeys:`pageDown`,description:`Scroll viewport down one page`},"tui.altScreen.halfPageUp":{defaultKeys:[],description:`Scroll viewport up half a page`},"tui.altScreen.halfPageDown":{defaultKeys:[],description:`Scroll viewport down half a page`},"tui.altScreen.lineUp":{defaultKeys:[],description:`Scroll viewport up one line`},"tui.altScreen.lineDown":{defaultKeys:[],description:`Scroll viewport down one line`},"tui.altScreen.previousPrompt":{defaultKeys:[`ctrl+shift+up`,`ctrl+up`],description:`Jump to previous semantic prompt`},"tui.altScreen.nextPrompt":{defaultKeys:[`ctrl+shift+down`,`ctrl+down`],description:`Jump to next semantic prompt`},"tui.altScreen.search":{defaultKeys:`ctrl+shift+f`,description:`Search the primary scroll view`},"tui.altScreen.searchNext":{defaultKeys:[`enter`,`ctrl+g`],description:`Select the next search match`},"tui.altScreen.searchPrevious":{defaultKeys:[`shift+enter`,`ctrl+shift+g`],description:`Select the previous search match`},"tui.altScreen.searchClose":{defaultKeys:`escape`,description:`Close transcript search`},"tui.altScreen.top":{defaultKeys:`home`,description:`Scroll viewport to top`},"tui.altScreen.bottom":{defaultKeys:`end`,description:`Scroll viewport to bottom`}};function tu(e){if(e===void 0)return[];let t=Array.isArray(e)?e:[e],n=new Set,r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}var nu=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(e,t={}){this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,n]of Object.entries(this.userBindings))if(t in this.definitions)for(let r of tu(n)){let n=e.get(r)??new Set;n.add(t),e.set(r,n)}for(let[t,n]of e)n.size>1&&this.conflicts.push({key:t,keybindings:[...n]});for(let[e,t]of Object.entries(this.definitions)){let n=this.userBindings[e],r=tu(n===void 0?t.defaultKeys:n);this.keysById.set(e,r)}}matches(e,t){let n=this.keysById.get(t)??[];for(let t of n)if(Jl(e,t))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let n=this.keysById.get(t)??[];e[t]=n.length===1?n[0]:[...n]}return e}},ru=null;function iu(e){ru=e}function au(){return ru||=new nu(eu),ru}var ou=class{ring=[];push(e,t){if(e){if(t.accumulate&&this.ring.length>0){let n=this.ring.pop();this.ring.push(t.prepend?e+n:n+e)}else this.ring.push(e)}}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};function su(e){let t=e.startsWith(`#`)?e.slice(1):e;return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}}function cu(e){if(!/^[0-9a-f]+$/i.test(e))return;let t=16**e.length-1;if(!(t<=0))return Math.round(parseInt(e,16)/t*255)}var lu=/^\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,uu=/^(?:\x1b\[\?997;(1|2)n)+$/;function du(e){return lu.test(e)}function fu(e){let t=e.match(lu);if(!t)return;let n=t[1].trim();if(n.startsWith(`#`)){let e=n.slice(1);if(/^[0-9a-f]{6}$/i.test(e))return su(n);if(/^[0-9a-f]{12}$/i.test(e)){let t=cu(e.slice(0,4)),n=cu(e.slice(4,8)),r=cu(e.slice(8,12));return t!==void 0&&n!==void 0&&r!==void 0?{r:t,g:n,b:r}:void 0}return}let[r,i,a]=n.replace(/^rgba?:/i,``).split(`/`);if(r===void 0||i===void 0||a===void 0)return;let o=cu(r),s=cu(i),c=cu(a);return o!==void 0&&s!==void 0&&c!==void 0?{r:o,g:s,b:c}:void 0}function pu(e){let t=e.match(uu);if(t)return t[1]===`2`?`light`:`dark`}var mu={images:null,trueColor:!0,hyperlinks:!0},hu=()=>mu,gu=e=>{mu={...e,images:null}},_u=()=>!1,vu=()=>void 0,yu=()=>void 0,bu=e=>e,xu=()=>``,Su=()=>``,Cu=()=>``;function wu(e,t){try{let n=new URL(t);return![`https:`,`http:`].includes(n.protocol)||/[\x00-\x20\x7f-\x9f]/.test(t)?e:`\x1b]8;;${n.href}\x07${e}\x1b]8;;\x07`}catch{return e}}var Tu=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Eu=[12288,12288,65281,65376,65504,65510],Du=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],Ou=(e,t)=>{let n=0,r=Math.floor(e.length/2)-1;for(;n<=r;){let i=Math.floor((n+r)/2),a=i*2;if(te[a+1])n=i+1;else return!0}return!1},ku=19968,[Au,ju]=Mu(Du);function Mu(e){let t=e[0],n=e[1];for(let r=0;r=i&&ku<=a)return[i,a];a-i>n-t&&(t=i,n=a)}return[t,n]}var Nu=e=>e<161||e>1114109?!1:Ou(Tu,e),Pu=e=>e<12288||e>65510?!1:Ou(Eu,e),Fu=e=>e>=Au&&e<=ju?!0:e<4352||e>262141?!1:Ou(Du,e);function Iu(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Lu(e,{ambiguousAsWide:t=!1}={}){return Iu(e),Pu(e)||Fu(e)||t&&Nu(e)?2:1}var Ru=new Intl.Segmenter(void 0,{granularity:`grapheme`}),zu=new Intl.Segmenter(void 0,{granularity:`word`});function Bu(){return Ru}function Vu(){return zu}function Hu(e){let t=e.codePointAt(0);return t>=126976&&t<=130047||t>=8960&&t<=9215||t>=9728&&t<=10175||t>=11088&&t<=11093||e.includes(`️`)||e.length>2}var Uu=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$`,`v`),Wu=RegExp(`^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+`,`v`),Gu=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$`,`v`),Ku=RegExp(`^\\p{Mark}$`,`v`),qu=RegExp(`^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$`,`v`),Ju=RegExp(`^\\p{RGI_Emoji}$`,`v`),Yu=512,Xu=new Map,Zu=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u;function Qu(e){for(let t=0;t126)return!1}return!0}function $u(e,t){if(t<=0||e.length===0)return{text:``,width:0};if(Qu(e)){let n=e.slice(0,t);return{text:n,width:n.length}}let n=e.includes(`\x1B`),r=e.includes(` `);if(!n&&!r){let n=``,r=0;for(let{segment:i}of Ru.segment(e)){let e=td(i);if(r+e>t)break;n+=i,r+=e}return{text:n,width:r}}let i=``,a=0,o=0,s=``;for(;ot)break;s&&=(i+=s,``),i+=` `,a+=3,o++;continue}let r=o;for(;rt)return{text:i,width:a};s&&=(i+=s,``),i+=n,a+=e}o=r}return{text:i,width:a}}function ed(e,t,n,r,i,a){let o=`\x1B[0m`,s=fd(e),c=t+r,l;return l=n.length>0?`${e}${s}${o}${n}${o}`:`${e}${s}${o}`,a?l+` `.repeat(Math.max(0,i-c)):l}function td(e){if(e===` `)return 3;if(qu.test(e))return[...e].length;if(Uu.test(e))return 0;if(Hu(e)&&Ju.test(e))return 2;let t=e.replace(Wu,``),n=t.codePointAt(0);if(n===void 0)return 0;if(n>=127462&&n<=127487)return 2;let r=Lu(n),i=!1,a=[...t];for(let e of a.slice(1))if(qu.test(e))r+=1,i=!1;else if(Ku.test(e))i=!0;else if(!Gu.test(e)){let t=e.codePointAt(0);i||t>=65280&&t<=65519?r+=Lu(t):(t===3635||t===3763)&&(r+=1),i=!1}return r}function X(e){if(e.length===0)return 0;if(Qu(e))return e.length;let t=Xu.get(e);if(t!==void 0)return t;let n=e;if(e.includes(` `)&&(n=n.replace(/\t/g,` `)),n.includes(`\x1B`)){let e=``,t=0;for(;t=Yu){let e=Xu.keys().next().value;e!==void 0&&Xu.delete(e)}return Xu.set(e,r),r}function nd(e){if(!e.includes(`\x1B`))return e;let t=``,n=0;for(;n0&&t>=n&&t=r&&te===`ำ`?`ํา`:`ໍາ`)),!t.includes(` `))return t;let n=``,r=0;for(;r=e.length||e[t]!==`\x1B`)return null;let n=e[t+1];if(n===`[`){let n=t+2;for(;n=30&&e<=37||e>=90&&e<=97?this.fgColor=String(e):(e>=40&&e<=47||e>=100&&e<=107)&&(this.bgColor=String(e))}a++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push(`1`),this.dim&&e.push(`2`),this.italic&&e.push(`3`),this.underline&&e.push(`4`),this.blink&&e.push(`5`),this.inverse&&e.push(`7`),this.hidden&&e.push(`8`),this.strikethrough&&e.push(`9`),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1b[${e.join(`;`)}m`:``;return this.activeHyperlink&&(t+=ud(this.activeHyperlink)),t}getActiveBackgroundCode(){return this.bgColor?`\x1b[${this.bgColor}m`:``}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e=``;return this.underline&&(e+=`\x1B[24m`),this.activeHyperlink&&(e+=dd(this.activeHyperlink.terminator)),e}};function md(e,t){let n=0;for(;n{n&&(t.push(n),n=``,i=null)};for(;a0?t[t.length-1]+=r:n=r),n&&t.push(n),t}function _d(e,t){if(!e)return[``];let n=e.split(/\r\n|\r|\n/),r=[],i=new pd;for(let e of n){let n=vd((r.length>0?i.getActiveCodes():``)+e,t);for(let e of n)r.push(e);md(e,i)}return r.length>0?r:[``]}function vd(e,t){if(!e)return[``];if(X(e)<=t)return[e];let n=[],r=new pd,i=gd(e),a=``,o=0;for(let e of i){let i=X(e),s=e.trim()===``;if(i>t&&!s){if(a){let e=r.getLineEndReset();e&&(a+=e),n.push(a),a=``,o=0}let i=xd(e,t,r);for(let e=0;et&&o>0){let t=a.trimEnd(),c=r.getLineEndReset();c&&(t+=c),n.push(t),s?(a=r.getActiveCodes(),o=0):(a=r.getActiveCodes()+e,o=i)}else a+=e,o+=i;md(e,r)}return a&&n.push(a),n.length>0?n.map(e=>e.trimEnd()):[``]}var yd=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function bd(e){return/\s/.test(e)}function xd(e,t,n){let r=[],i=n.getActiveCodes(),a=0,o=0,s=[];for(;ot){let e=n.getLineEndReset();e&&(i+=e),r.push(i),i=n.getActiveCodes(),a=0}i+=o,a+=s}return i&&r.push(i),r.length>0?r:[``]}function Sd(e,t,n){let r=X(e),i=Math.max(0,t-r);return n(e+` `.repeat(i))}function Cd(e,t,n=`...`,r=!1){if(t<=0)return``;if(e.length===0)return r?` `.repeat(t):``;let i=X(n);if(i>=t){let i=X(e);if(i<=t)return r?e+` `.repeat(t-i):e;let a=$u(n,t);return a.width===0?r?` `.repeat(t):``:ed(``,0,a.text,a.width,t,r)}if(Qu(e)){if(e.length<=t)return r?e+` `.repeat(t-e.length):e;let a=t-i;return ed(e.slice(0,a),a,n,i,t,r)}let a=t-i,o=``,s=``,c=0,l=0,u=!0,d=!1,f=!1,p=e.includes(`\x1B`),m=e.includes(` `);if(!p&&!m){for(let{segment:n}of Ru.segment(e)){let e=td(n);if(u&&l+e<=a?(o+=n,l+=e):u=!1,c+=e,c>t){d=!0;break}}f=!d}else{let n=0;for(;nt){d=!0;break}n++;continue}let i=n;for(;it){d=!0;break}}if(d)break;n=i}f=n>=e.length}return!d&&f?r?e+` `.repeat(Math.max(0,t-c)):e:ed(o,l,n,i,t,r)}function wd(e,t,n,r=!1){return Td(e,t,n,r).text}function Td(e,t,n,r=!1){if(n<=0)return{text:``,width:0};let i=t+n,a=``,o=0,s=0,c=0,l=``;for(;c=t&&s=t&&s=i)break}if(c=u,s>=i)break}return{text:a,width:o}}var Ed=new pd;function Dd(e,t,n,r,i=!1){let a=``,o=0,s=``,c=0,l=0,u=0,d=``,f=!1,p=n+r;for(Ed.clear();u=n&&l=n&&l=t:l>=p)break}if(u=h,r<=0?l>=t:l>=p)break}return{before:a,beforeWidth:o,after:s,afterWidth:c}}function Od(e,t){let n=e.handleMouse?.(t);if(n){if(`target`in n)return n;if(n.handled||n.capture||n.focus)return{...n,handled:!0,...n.focus?{focusTarget:e}:{},target:{component:e,originX:t.screenX-t.x,originY:t.screenY-t.y,width:t.width,height:t.height}}}}function kd(e,t){return{...e,x:e.screenX-t.originX,y:e.screenY-t.originY,width:t.width,height:t.height}}function Ad(e){return e!==null&&`focused`in e}var jd=`\x1B_pi:c\x07`;function Md(e,t){if(e===void 0)return;if(typeof e==`number`)return e;let n=e.match(/^(\d+(?:\.\d+)?)%$/);if(n)return Math.floor(t*parseFloat(n[1])/100)}var Nd=class{children=[];mouseLayout;addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}handleMouse(e){if(e.y<0||e.y>=e.height)return;let t=this.mouseLayout?.width===e.width?this.mouseLayout.children:this.children.map(t=>({component:t,height:t.render(e.width).length})),n=0;for(let{component:r,height:i}of t){if(e.y>=n&&e.y0}overlayFocusRestore={status:`inactive`};constructor(e,t,n){super(),this.terminal=e,this.logDirectory=n,t!==void 0&&(this.showHardwareCursor=t)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.terminal.hideCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:`clear`})}setFocusInternal({component:e,overlayFocusRestore:t}){let n=this.focusedComponent,r=e,i=n?this.overlayStack.find(e=>e.component===n&&this.isOverlayVisible(e)):void 0,a=r?this.overlayStack.some(e=>e.component===r):!1,o=this.getVisibleOverlayFocusRestore();r&&!a?o.status===`blocked`&&o.blockedBy===n?o.resume.status===`focus-target`||!this.isComponentMounted(o.blockedBy)?r=this.resolveBlockedOverlayFocusResume(o):this.overlayFocusRestore={status:`blocked`,overlay:o.overlay,blockedBy:r,resume:o.resume}:i&&o.status!==`inactive`&&o.overlay===i&&!this.isOverlayFocusAncestor(i,r)&&(this.overlayFocusRestore={status:`blocked`,overlay:i,blockedBy:r,resume:{status:`restore-overlay`}}):r===null&&(o.status===`blocked`&&o.blockedBy===n?r=this.resolveBlockedOverlayFocusResume(o):t===`clear`&&this.clearOverlayFocusRestore()),Ad(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=r,Ad(r)&&(r.focused=!0);let s=r?this.overlayStack.find(e=>e.component===r&&this.isOverlayVisible(e)):void 0;s&&(this.overlayFocusRestore={status:`eligible`,overlay:s})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:`inactive`}}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!==`inactive`&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(e){return e.resume.status===`restore-overlay`?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status===`inactive`?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:`inactive`}:e}isOverlayFocusAncestor(e,t){let n=new Set,r=e.preFocus;for(;r&&!n.has(r);){if(n.add(r),r===t)return!0;r=this.overlayStack.find(e=>e.component===r)?.preFocus??null}return!1}retargetOverlayPreFocus(e){for(let t of this.overlayStack)t!==e&&t.preFocus===e.component&&(t.preFocus=e.preFocus)}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(t=>this.containsComponent(t,e))}containsComponent(e,t){return e===t||e instanceof Nd&&e.children.some(e=>this.containsComponent(e,t))}showOverlay(e,t){let n={component:e,...t===void 0?{}:{options:t},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(n),!t?.nonCapturing&&this.isOverlayVisible(n)&&this.setFocus(e),this.terminal.hideCursor(),this.requestRender(),{hide:()=>{let t=this.overlayStack.indexOf(n);if(t!==-1){if(this.clearOverlayFocusRestoreFor(n),this.retargetOverlayPreFocus(n),this.overlayStack.splice(t,1),this.focusedComponent===e){let e=this.getTopmostVisibleOverlay();this.setFocus(e?.component??n.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}},setHidden:r=>{if(n.hidden!==r){if(n.hidden=r,r){if(this.clearOverlayFocusRestoreFor(n),this.focusedComponent===e){let e=this.getTopmostVisibleOverlay();this.setFocus(e?.component??n.preFocus)}}else!t?.nonCapturing&&this.isOverlayVisible(n)&&(n.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender()}},isHidden:()=>n.hidden,focus:()=>{this.overlayStack.includes(n)&&this.isOverlayVisible(n)&&(n.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender())},unfocus:t=>{let r=this.focusedComponent===e,i=this.overlayFocusRestore,a=i.status!==`inactive`&&i.overlay===n;if(r||a){if(i.status===`blocked`&&i.overlay===n&&this.focusedComponent===i.blockedBy){t?this.overlayFocusRestore={status:`blocked`,overlay:n,blockedBy:i.blockedBy,resume:{status:`focus-target`,target:t.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(n),r||t){let e=this.getTopmostVisibleOverlay(),r=e&&e!==n?e.component:n.preFocus;this.setFocus(t?t.target:r)}this.requestRender()}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(this.overlayStack.includes(n)&&this.isOverlayVisible(n)&&n.bounds)return{...n.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??e.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let t=this.overlayStack.length-1;t>=0;t--){let n=this.overlayStack[t];if(this.isOverlayVisible(n)&&this.containsComponent(n.component,e))return n.component}return e}dispatchMouseToOverlay(e){for(let t=this.renderedOverlayLayouts.length-1;t>=0;t--){let n=this.renderedOverlayLayouts[t];if(e.screenX=n.col+n.width||e.screenY=n.row+n.height)continue;let r=Od(n.entry.component,{...e,x:e.screenX-n.col,y:e.screenY-n.row,width:n.width,height:n.height});return r?{hit:!0,result:r.focus?{...r,focusTarget:n.entry.component}:r}:{hit:!0}}return{hit:!1}}isOverlayVisible(e){return e.hidden?!1:!e.options?.visible||e.options.visible(this.terminal.columns,this.terminal.rows)}getTopmostVisibleOverlay(){let e;for(let t of this.overlayStack)!t.options?.nonCapturing&&this.isOverlayVisible(t)&&(!e||t.focusOrder>e.focusOrder)&&(e=t);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate()}start(){this.stopped=!1,this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write(`\x1B[?2031h`),this.queryCellSize(),this.requestRender()}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e)}}removeInputListener(e){this.inputListeners.delete(e)}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e)}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?`\x1B[?2031h`:`\x1B[?2031l`))}queryCellSize(){hu().images&&this.terminal.write(`\x1B[16t`)}stop(e={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write(`\x1B[?2031l`),this.beforeTerminalStop(e),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(e)}renderNow(e=!1){e&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=Cl.now(),this.doRender()}requestRender(e=!1){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,wl.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,wl.nextTick(()=>{this.immediateRenderScheduled=!1,!this.stopped&&this.renderRequested&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=Cl.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&=(clearTimeout(this.renderTimer),void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let t=Cl.now()-this.lastRenderAt,n=Math.max(0,e.MIN_RENDER_INTERVAL_MS-t);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!this.stopped&&this.renderRequested&&(this.renderRequested=!1,this.lastRenderAt=Cl.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},n)}handleTerminalInput(e){if(this.consumeOsc11BackgroundResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let t=e;for(let e of this.inputListeners){let n=e(t);if(n?.consume)return;n?.data!==void 0&&(t=n.data)}if(t.length===0)return;e=t}if(this.consumeCellSizeResponse(e))return;if(Jl(e,`shift+ctrl+d`)&&this.onDebug){this.onDebug();return}let t=this.overlayStack.find(e=>e.component===this.focusedComponent);if(t&&!this.isOverlayVisible(t)){let e=this.getTopmostVisibleOverlay();e?this.setFocus(e.component):this.setFocusInternal({component:t.preFocus,overlayFocusRestore:`preserve`})}if(!this.overlayStack.some(e=>e.component===this.focusedComponent)){let e=this.getVisibleOverlayFocusRestore();e.status===`eligible`?this.setFocus(e.overlay.component):e.status===`blocked`&&e.blockedBy!==this.focusedComponent&&(e.resume.status===`restore-overlay`?this.setFocus(e.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(e.resume.target)))}if(this.focusedComponent?.handleInput){if(Ll(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender()}}consumeOsc11BackgroundResponse(e){if(this.pendingOsc11BackgroundReplies<=0||!du(e))return!1;let t=fu(e);--this.pendingOsc11BackgroundReplies;let n=this.pendingOsc11BackgroundQueries.shift();return n&&!n.settled&&(n.settled=!0,n.timer&&=(clearTimeout(n.timer),void 0),n.resolve?.(t),n.resolve=void 0),!0}consumeTerminalColorSchemeReport(e){let t=pu(e);if(!t)return!1;for(let e of this.terminalColorSchemeListeners)e(t);return!0}consumeCellSizeResponse(e){let t=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!t)return!1;let n=parseInt(t[1],10),r=parseInt(t[2],10);return n<=0||r<=0||(this.invalidate(),this.requestRender(),!0)}resolveOverlayLayout(e,t,n,r){let i=e??{},a=typeof i.margin==`number`?{top:i.margin,right:i.margin,bottom:i.margin,left:i.margin}:i.margin??{},o=Math.max(0,a.top??0),s=Math.max(0,a.right??0),c=Math.max(0,a.bottom??0),l=Math.max(0,a.left??0),u=Math.max(1,n-l-s),d=Math.max(1,r-o-c),f=Md(i.width,n)??Math.min(80,u);i.minWidth!==void 0&&(f=Math.max(f,i.minWidth)),f=Math.max(1,Math.min(f,u));let p=Md(i.maxHeight,r);p!==void 0&&(p=Math.max(1,Math.min(p,d)));let m=p===void 0?t:Math.min(t,p),h,g;if(i.row!==void 0){if(typeof i.row==`string`){let e=i.row.match(/^(\d+(?:\.\d+)?)%$/);if(e){let t=Math.max(0,d-m),n=parseFloat(e[1])/100;h=o+Math.floor(t*n)}else h=this.resolveAnchorRow(`center`,m,d,o)}else h=i.row}else{let e=i.anchor??`center`;h=this.resolveAnchorRow(e,m,d,o)}if(i.col!==void 0){if(typeof i.col==`string`){let e=i.col.match(/^(\d+(?:\.\d+)?)%$/);if(e){let t=Math.max(0,u-f),n=parseFloat(e[1])/100;g=l+Math.floor(t*n)}else g=this.resolveAnchorCol(`center`,f,u,l)}else g=i.col}else{let e=i.anchor??`center`;g=this.resolveAnchorCol(e,f,u,l)}return i.offsetY!==void 0&&(h+=i.offsetY),i.offsetX!==void 0&&(g+=i.offsetX),h=Math.max(o,Math.min(h,r-c-m)),g=Math.max(l,Math.min(g,n-s-f)),{width:f,row:h,col:g,maxHeight:p}}resolveAnchorRow(e,t,n,r){switch(e){case`top-left`:case`top-center`:case`top-right`:return r;case`bottom-left`:case`bottom-center`:case`bottom-right`:return r+n-t;case`left-center`:case`center`:case`right-center`:return r+Math.floor((n-t)/2)}}resolveAnchorCol(e,t,n,r){switch(e){case`top-left`:case`left-center`:case`bottom-left`:return r;case`top-right`:case`right-center`:case`bottom-right`:return r+n-t;case`top-center`:case`center`:case`bottom-center`:return r+Math.floor((n-t)/2)}}compositeOverlays(e,t,n){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let r=[...e];for(let e of this.overlayStack)e.bounds=void 0;let i=[],a=r.length,o=this.overlayStack.filter(e=>this.isOverlayVisible(e));o.sort((e,t)=>e.focusOrder-t.focusOrder);for(let e of o){let{component:r,options:o}=e,{width:s,maxHeight:c}=this.resolveOverlayLayout(o,0,t,n),l=r.render(s);c!==void 0&&l.length>c&&(l=l.slice(0,c));let{row:u,col:d}=this.resolveOverlayLayout(o,l.length,t,n);e.bounds={row:u,col:d,width:s,height:l.length},i.push({entry:e,overlayLines:l,row:u,col:d,w:s}),a=Math.max(a,u+l.length)}this.renderedOverlayLayouts=i.map(({entry:e,row:t,col:n,w:r,overlayLines:i})=>({entry:e,row:t,col:n,width:r,height:i.length}));let s=Math.max(r.length,n,a);for(;r.length=0&&so?wd(e[i],0,o,!0):e[i];r[s]=this.compositeLineAt(r[s],n,a,o,t)}}return r}applyLineResets(e){let t=Pd;for(let n=0;n=n;t--){let n=e[t],r=n.indexOf(jd);if(r!==-1){let i=X(n.slice(0,r));return e[t]=n.slice(0,r)+n.slice(r+7),{row:t,col:i}}}return null}queryTerminalBackgroundColor({timeoutMs:e}){return new Promise(t=>{let n={settled:!1,resolve:t,timer:void 0};n.timer=setTimeout(()=>{n.settled||(n.settled=!0,n.timer=void 0,n.resolve?.(void 0),n.resolve=void 0)},e),this.pendingOsc11BackgroundQueries.push(n),this.pendingOsc11BackgroundReplies+=1,this.terminal.write(`\x1B]11;?\x07`)})}queryTerminalColorScheme({timeoutMs:e}){return new Promise(t=>{let n=!1,r,i=()=>{},a=e=>{n||(n=!0,r&&=(clearTimeout(r),void 0),i(),t(e))};i=this.onTerminalColorSchemeChange(a),r=setTimeout(()=>a(void 0),e),this.terminal.write(`\x1B[?996n`)})}},Rd=class{stack=[];push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}},zd=Vu();function Bd(e,t,n){if(t<=0)return 0;let r=e.slice(0,t),i=n?.segment,a=n?.isAtomicSegment,o=i?[...i(r)]:[...zd.segment(r)],s=t;for(;o.length>0&&!a?.(o[o.length-1]?.segment||``)&&bd(o[o.length-1]?.segment||``);)s-=o.pop()?.segment.length||0;if(o.length===0)return s;let c=o[o.length-1];if(a?.(c.segment))s-=c.segment.length;else if(c.isWordLike){let e=c.segment,t=[...e.matchAll(new RegExp(yd,`g`))];if(t.length<=0)s-=e.length;else{let n=t[t.length-1];s-=e.length-(n.index+n[0].length)}}else for(;o.length>0&&!a?.(o[o.length-1]?.segment||``)&&!o[o.length-1]?.isWordLike&&!bd(o[o.length-1]?.segment||``);)s-=o.pop()?.segment.length||0;return s}function Vd(e,t,n){if(t>=e.length)return e.length;let r=e.slice(t),i=n?.segment,a=n?.isAtomicSegment,o=(i?i(r):zd.segment(r))[Symbol.iterator](),s=o.next(),c=t;for(;!s.done&&!a?.(s.value.segment)&&bd(s.value.segment);)c+=s.value.segment.length,s=o.next();if(s.done)return c;if(a?.(s.value.segment))c+=s.value.segment.length;else if(s.value.isWordLike)c+=yd.exec(s.value.segment)?.index??s.value.segment.length;else for(;!s.done&&!a?.(s.value.segment)&&!s.value.isWordLike&&!bd(s.value.segment);)c+=s.value.segment.length,s=o.next();return c}var Hd=Bu(),Ud=class{value=``;cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer=``;isInPaste=!1;killRing=new ou;lastAction=null;undoStack=new Rd;constructor(e={}){this.prompt=e.prompt??`> `,this.placeholder=e.placeholder??``,this.placeholderStyle=e.placeholderStyle??(e=>e)}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes(`\x1B[200~`)&&(this.isInPaste=!0,this.pasteBuffer=``,e=e.replace(`\x1B[200~`,``)),this.isInPaste){this.pasteBuffer+=e;let t=this.pasteBuffer.indexOf(`\x1B[201~`);if(t!==-1){let e=this.pasteBuffer.substring(0,t);this.handlePaste(e),this.isInPaste=!1;let n=this.pasteBuffer.substring(t+6);this.pasteBuffer=``,n&&this.handleInput(n)}return}let t=au();if(t.matches(e,`tui.select.cancel`)){this.onEscape&&this.onEscape();return}if(t.matches(e,`tui.editor.undo`)){this.undo();return}if(t.matches(e,`tui.input.submit`)||e===` `){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,`tui.editor.deleteCharBackward`)){this.handleBackspace();return}if(t.matches(e,`tui.editor.deleteCharForward`)){this.handleForwardDelete();return}if(t.matches(e,`tui.editor.deleteWordBackward`)){this.deleteWordBackwards();return}if(t.matches(e,`tui.editor.deleteWordForward`)){this.deleteWordForward();return}if(t.matches(e,`tui.editor.deleteToLineStart`)){this.deleteToLineStart();return}if(t.matches(e,`tui.editor.deleteToLineEnd`)){this.deleteToLineEnd();return}if(t.matches(e,`tui.editor.yank`)){this.yank();return}if(t.matches(e,`tui.editor.yankPop`)){this.yankPop();return}if(t.matches(e,`tui.editor.cursorLeft`)){if(this.lastAction=null,this.cursor>0){let e=this.value.slice(0,this.cursor),t=[...Hd.segment(e)],n=t[t.length-1];this.cursor-=n?n.segment.length:1}return}if(t.matches(e,`tui.editor.cursorRight`)){if(this.lastAction=null,this.cursor{let t=e.charCodeAt(0);return t<32||t===127||t>=128&&t<=159})||this.insertCharacter(e)}handleMouse(e){if(e.type!==`press`||e.button!==`left`||e.y!==0)return;let t=Math.max(0,e.x-2),n=this.renderedStartColumn+t,r=0;this.cursor=this.value.length;for(let e of Hd.segment(this.value)){let t=r+X(e.segment);if(n0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...Hd.segment(e)],n=t[t.length-1],r=n?n.segment.length:1;this.value=this.value.slice(0,this.cursor-r)+this.value.slice(this.cursor),this.cursor-=r}}handleForwardDelete(){if(this.lastAction=null,this.cursor=this.value.length)return;this.pushUndo();let e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`,this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction===`kill`;this.pushUndo();let t=this.cursor;this.moveWordBackwards();let n=this.cursor;this.cursor=t;let r=this.value.slice(n,this.cursor);this.killRing.push(r,{prepend:!0,accumulate:e}),this.lastAction=`kill`,this.value=this.value.slice(0,n)+this.value.slice(this.cursor),this.cursor=n}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction===`kill`;this.pushUndo();let t=this.cursor;this.moveWordForwards();let n=this.cursor;this.cursor=t;let r=this.value.slice(this.cursor,n);this.killRing.push(r,{prepend:!1,accumulate:e}),this.lastAction=`kill`,this.value=this.value.slice(0,this.cursor)+this.value.slice(n)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction=`yank`)}yankPop(){if(this.lastAction!==`yank`||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||``;this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||``;this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction=`yank`}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=Bd(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=Vd(this.value,this.cursor))}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,``).replace(/\r/g,``).replace(/\n/g,``).replace(/\t/g,` `);this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let t=e-X(this.prompt);if(t<=0)return[Cd(this.prompt,e,``)];if(this.value.length===0&&this.placeholder){let e=Cd(this.placeholder,t,``),n=[...Hd.segment(e)][0]?.segment??` `,r=e.slice(n.length),i=(this.focused?jd:``)+`\x1b[7m${this.placeholderStyle(n)}\x1b[27m`+this.placeholderStyle(r),a=` `.repeat(Math.max(0,t-X(i)));return[this.prompt+i+a]}let n=``,r=this.cursor;this.renderedStartColumn=0;let i=X(this.value);if(i0){let t=Math.floor(e/2),o=0;o=ai-t?Math.max(0,i-e):Math.max(0,a-t),this.renderedStartColumn=o,n=wd(this.value,o,e,!0),r=wd(this.value,o,Math.max(0,a-o),!0).length}else n=``,r=0}let a=[...Hd.segment(n.slice(r))][0],o=n.slice(0,r),s=a?.segment??` `,c=n.slice(r+s.length),l=this.focused?jd:``,u=`\x1b[7m${s}\x1b[27m`,d=o+l+u+c,f=X(d),p=` `.repeat(Math.max(0,t-f));return[this.prompt+d+p]}},Wd=Bu(),Gd=/^[\x20-\x7e]*$/;function Kd(e){let t=[],n=[],r=0,i=!1,a=()=>{i&&=(t.push(` `),r+=1,!1)};for(let o=0;o0&&(i=!0),c+=1,e+=1;continue}let l=e+1;for(;l0&&(i=!0),c+=l;continue}a(),t.push(s),n.push({textStart:r,textEnd:r+s.length,row:o,startCol:c,endCol:c+l,linearColumns:!1}),r+=s.length,c+=l}r>0&&(i=!0)}return{text:t.join(``),spans:n}}function qd(e){return e.replace(/\s+/gu,` `).trim()}function Jd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Yd(e,t){if(!t)return[];let n=new RegExp(Jd(t),`giu`),r=[],i=0;for(let t of e.text.matchAll(n)){let n=t.index,a=n+t[0].length;for(;i=a)break;if(r.textEnd<=n)continue;let i=r.linearColumns?r.startCol+Math.max(n,r.textStart)-r.textStart:r.startCol,s=r.linearColumns?r.startCol+Math.min(a,r.textEnd)-r.textStart:r.endCol,c=o[o.length-1];c&&c.row===r.row&&i<=c.endCol?c.endCol=Math.max(c.endCol,s):o.push({row:r.row,startCol:i,endCol:s})}for(;i0&&r.push({segments:o})}return r}var Xd=class{sourceLines;corpus;normalizedQuery;matches=[];search(e,t){let n=this.sourceLines?.length!==e.length;if(!n&&this.sourceLines){for(let t=0;t`\x1b[2m${e}\x1b[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(e,t=e=>e){this.onQueryChange=e,this.navigationButtonStyle=t}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}setResult(e,t){this.resultIndex=e,this.resultCount=t}getNavigationDirectionAt(e,t){if(e===2){if(t>=this.previousButtonStart&&t=this.nextButtonStart&&te?e.split(`+`).map(e=>wl.platform===`darwin`&&e.toLowerCase()===`alt`?`Option`:e.charAt(0).toUpperCase()+e.slice(1)).join(`+`):`Unbound`,i=au(),a=r(i.getKeys(`tui.altScreen.searchPrevious`)[0]),o=r(i.getKeys(`tui.altScreen.searchNext`)[0]),s=Cd(this.input.getValue()?this.resultCount===0?`No matches`:`${this.resultIndex+1}/${this.resultCount}`:``,Math.max(0,n-3),``),c=s?`\x1b[2m ${s} \x1b[22m`:``,l=Math.max(0,n-X(c)),u=Cd(this.input.render(Math.max(1,l))[0]??``,l,``),d=`${u}${` `.repeat(Math.max(0,l-X(u)))}${c}`,f=`↑ ${a}`,p=`↓ ${o}`,m=` · `,h=Math.max(0,n-2-1),g=X(f)+X(m)+X(p);g>h&&(f=`↑`,p=`↓`,m=` `,g=X(f)+X(m)+X(p));let _=g<=h,v=_?this.navigationButtonStyle(f,this.hoveredNavigationDirection===-1)+m+this.navigationButtonStyle(p,this.hoveredNavigationDirection===1):``,y=_?2:0,b=v&&n>g+y?1:0,x=Math.max(0,n-(_?g:0)-y-b),S=1+x+1;return this.previousButtonStart=_?S:-1,this.previousButtonEnd=_?S+X(f):-1,this.nextButtonStart=_?this.previousButtonEnd+X(m):-1,this.nextButtonEnd=_?this.nextButtonStart+X(p):-1,t===1?[`┌`,`│`,`└`]:[`┌${`─`.repeat(n)}┐`,`│${d}│`,`└${`─`.repeat(x)}${v?` `:``}${v}${v?` `:``}${`─`.repeat(b)}┘`]}},$d=1e3,ef=class{entries=[];nextId=0;requestRender;constructor(e){this.requestRender=e}flash(e,t=$d){let n=this.nextId++,r=setTimeout(()=>{let e=this.entries.findIndex(e=>e.id===n);e!==-1&&(this.entries.splice(e,1),this.requestRender())},Math.max(0,t));r.unref?.(),this.entries.push({id:n,message:e,timer:r}),this.requestRender()}dispose(){for(let e of this.entries)clearTimeout(e.timer);this.entries.length=0}invalidate(){}render(e){return this.entries.map(t=>`\x1b[7m${Cd(` ${t.message} `,e,``)}\x1b[27m`)}},tf=Symbol.for(`@earendil-works/pi-tui/layout-node`);function nf(e){let t=e;return typeof t[tf]==`function`?t[tf]():void 0}var rf=class extends Nd{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(e,t={}){if(super(),t.axis!==void 0&&t.axis!==`vertical`)throw Error(`Unsupported ScrollView axis: ${t.axis}`);this.child=e,this.children.push(e),this.followEnd=(t.follow??`none`)===`end`,this.followingEnd=this.followEnd,this.primary=t.primary??!1,this.overscroll=t.overscroll??`chain`,this.currentScrollbar=t.scrollbar??`hidden`,this.scrollbarTrackStyle=t.scrollbarTrackStyle??(e=>`\x1b[90m${e}\x1b[39m`),this.scrollbarThumbStyle=t.scrollbarThumbStyle??(e=>`\x1b[37m${e}\x1b[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(t.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar===`always`?this.currentViewportHeight>0:this.scrollbar===`auto`&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(e){e!==this.currentScrollbar&&(this.currentScrollbar=e,e===`auto`?this.scrollbarActive&&this.markScrollbarActivity():this.hideTransientScrollbar(),this.requestRenderCallback?.())}getContentWidth(e){return this.scrollbar===`always`&&e>1?e-1:e}markScrollbarActivity(){this.scrollbar!==`auto`||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&=(clearTimeout(this.scrollbarHideTimer),void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref?.()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&=(clearTimeout(this.scrollbarHideTimer),void 0)}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(e,t={}){let n=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,r=Math.max(0,this.contentHeight-this.currentViewportHeight),i=Math.max(0,Math.min(r,n)),a=t.disableFollow===!0&&i===r,o=!a&&this.followEnd&&i===r;if(i===this.currentScrollTop&&o===this.followingEnd&&a===this.followSuppressedAtEnd)return;let s=i!==this.currentScrollTop;this.currentScrollTop=i,this.followingEnd=o,this.followSuppressedAtEnd=a,s&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(e){let t=Number.isFinite(e)?Math.trunc(e):0;if(t===0)return 0;let n=Math.max(0,this.contentHeight-this.currentViewportHeight),r=this.followingEnd?n:this.currentScrollTop,i=Math.max(0,Math.min(n,r+t)),a=i-r,o=this.followingEnd;return this.currentScrollTop=i,this.followingEnd=this.followEnd&&i===n,this.followSuppressedAtEnd=!1,a!==0&&this.markScrollbarActivity(),(a!==0||this.followingEnd!==o)&&this.requestRenderCallback?.(),t-a}scrollToStart(){let e=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,e&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),t=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,t&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(e,t,n){this.contentHeight=Math.max(0,Math.floor(e)),this.currentViewportHeight=Math.max(0,Math.floor(t)),this.requestRenderCallback=n;let r=Math.max(0,this.contentHeight-this.currentViewportHeight);this.currentScrollTop=this.followingEnd?r:Math.max(0,Math.min(this.currentScrollTop,r)),this.currentScrollTop`${e} `)}[tf](){return{type:`scroll`,component:this.child,state:this}}};function af(e){return!(`render`in e)}function of(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}var sf=class extends Nd{entries=[];gap;align;constructor(e=[],t={}){super(),this.gap=of(t.gap,0),this.align=t.align??`stretch`;for(let t of e)af(t)?this.addChild(t.component,t):this.addChild(t)}addChild(e,t={}){super.addChild(e),this.entries.push({component:e,...t.basis===void 0?{}:{basis:t.basis},...t.grow===void 0?{}:{grow:of(t.grow,0)},...t.shrink===void 0?{}:{shrink:of(t.shrink,1)},...t.minSize===void 0?{}:{minSize:of(t.minSize,0)},...t.maxSize===void 0?{}:{maxSize:of(t.maxSize,2**53-1)},...t.visible===void 0?{}:{visible:t.visible}})}removeChild(e){super.removeChild(e);let t=this.entries.findIndex(t=>t.component===e);t!==-1&&this.entries.splice(t,1)}clear(){super.clear(),this.entries.length=0}[tf](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function cf(e,t){return e.filter(e=>e.visible?.(t)??!0)}function lf(e,t){let n=Math.max(0,Math.floor(t.minSize??0)),r=Math.max(n,Math.floor(t.maxSize??2**53-1));return Math.max(n,Math.min(r,Math.max(0,Math.floor(e))))}function uf(e,t,n,r){let i=n;for(;i>0;){let n=t.map((e,t)=>({entry:e,index:t})).filter(({entry:t,index:n})=>r===`grow`?(t.grow??0)>0&&e[n]<(t.maxSize??2**53-1):(t.shrink??1)>0&&e[n]>(t.minSize??0));if(n.length===0)return;let a=n.reduce((t,{entry:n,index:i})=>t+(r===`grow`?n.grow??0:(n.shrink??1)*Math.max(1,e[i])),0),o=0;for(let{entry:t,index:s}of n){if(i<=0)break;let n=r===`grow`?t.grow??0:(t.shrink??1)*Math.max(1,e[s]),c=Math.max(1,Math.floor(i*n/a)),l=r===`grow`?(t.maxSize??2**53-1)-e[s]:e[s]-(t.minSize??0),u=Math.min(i,c,l);u<=0||(e[s]=e[s]+(r===`grow`?u:-u),i-=u,o+=u)}if(o===0)return}}function df(e,t,n,r){let i=e.map((e,n)=>lf(e.basis===void 0||e.basis===`auto`?t[n]??0:e.basis,e));if(n===void 0)return i;let a=Math.max(0,Math.floor(n)-Math.max(0,e.length-1)*r),o=i.reduce((e,t)=>e+t,0);return oa&&uf(i,e,o-a,`shrink`),i}var ff=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function pf(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return{x:n,y:r,width:Math.max(0,i-n),height:Math.max(0,a-r)}}function mf(e,t,n){let r=Math.max(1,Math.floor(n)),i=e.renderCache.get(t);i||(i=new Map,e.renderCache.set(t,i));let a=i.get(r);return a||(a=t.render(r),i.set(r,a)),a}function hf(e,t,n){return mf(e,t,n).length}function gf(e,t,n){return mf(e,t,n).reduce((e,t)=>Math.max(e,X(t)),0)}function _f(e,t){return e.parent=t,e}function vf(e,t){e.rect.y+=t;for(let n of e.children)vf(n,t)}function yf(e,t){e.clip=pf(t,e.rect);for(let t of e.children)yf(t,e.clip)}function bf(e,t,n,r,i,a,o){let s=Math.max(1,Math.floor(i)),c=nf(t);if(!c){let i=mf(e,t,s),c=a===void 0?i.length:Math.max(0,Math.floor(a)),l=0;if(i.length>c&&c>0){let e=i.findIndex(e=>e.includes(jd));e>=c&&(l=e-c+1)}return{component:t,rect:{x:n,y:r,width:s,height:c},clip:pf(o,{x:n,y:r,width:s,height:c}),children:[],lines:i,lineOffset:l,layer:0}}if(c.type===`scroll`){let i=c.state.scrollTop,l=c.state.getContentWidth(s),u=bf(e,c.component,n,r-i,l,void 0,o),d=u.rect.height,f=a===void 0?d:Math.max(0,Math.floor(a));c.state.updateLayout(d,f,e.requestRender),vf(u,i-c.state.scrollTop);let p=c.state;(c.state.primary||!e.primaryScrollView)&&(e.primaryScrollView=p);let m={x:n,y:r,width:s,height:f},h=pf(o,m),g={component:t,rect:m,clip:h,children:[u],scrollView:p,scrollContentLines:mf(e,c.component,l),layer:0};return u.parent=g,yf(u,h),g}let l=cf(c.entries,e.viewport),u=Math.max(0,l.length-1)*c.gap;if(c.type===`vstack`){let i=df(l,l.map(t=>typeof t.basis==`number`?t.basis:hf(e,t.component,s)),a,c.gap),d=i.reduce((e,t)=>e+t,0)+u,f={x:n,y:r,width:s,height:a===void 0?d:Math.max(0,Math.floor(a))},p={component:t,rect:f,clip:pf(o,f),children:[],layer:0},m=r;for(let t=0;ttypeof t.basis==`number`?t.basis:gf(e,t.component,s)),s,c.gap),f=l.map((t,n)=>hf(e,t.component,Math.max(1,d[n]))),p=a===void 0?f.reduce((e,t)=>Math.max(e,t),0):Math.max(0,a),m={x:n,y:r,width:s,height:p},h={component:t,rect:m,clip:pf(o,m),children:[],layer:0},g=n;for(let t=0;tr;if(!e.scrollView.isScrollbarVisible&&!i)return;let a=Math.max(Math.min(2,r),Math.min(r,Math.round(r*r/n))),o=Math.max(0,n-r),s=r-a,c=o===0?0:Math.round(e.scrollView.scrollTop/o*s),l=e.rect.x+e.rect.width-1;if(!(l=e.clip.x+e.clip.width))return{column:l,trackTop:e.rect.y,trackHeight:r,thumbTop:e.rect.y+c,thumbHeight:a,maxScrollTop:o}}function Cf(e,t,n){let r=Sf(e);if(r&&e.scrollView)for(let i=0;i=e.clip.y+e.clip.height||a<0||a>=t.length)continue;let o=a>=r.thumbTop&&a=n&&(_u(a)||!t[o])?t[o]=a:t[o]=Fd(t[o]??``,a,e.rect.x,e.rect.width,n)}}for(let r of e.children)wf(r,t,n);if(e.scrollView&&e.scrollContentLines&&e.scrollView.scrollTop>0&&e.rect.height>0)for(let r=e.scrollView.scrollTop-1;r>=0;r--){let i=e.scrollContentLines[r]??``,a=yu(i);if(a){let o=e.scrollView.scrollTop-r;if(o=n&&(t[e.rect.y]=r)}break}if(i!==``)break}Cf(e,t,n)}function Tf(e,t,n,r){let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.floor(n)),o={viewport:{width:i,height:a},renderCache:new Map,requestRender:r,primaryScrollView:void 0},s=bf(o,e,0,0,i,a,{x:0,y:0,width:i,height:a}),c=Array.from({length:a},()=>``);return wf(s,c,i),{root:s,width:i,height:a,lines:c,...o.primaryScrollView===void 0?{}:{primaryScrollView:o.primaryScrollView}}}function Ef(e,t,n){return t>=e.x&&t=e.y&&n{if(Ef(e.clip,t,n)){r.push({box:e,depth:a});for(let t of e.children)i(t,a+1)}};return i(e.root,0),r.sort((e,t)=>t.box.layer-e.box.layer||t.depth-e.depth),r.map(({box:e})=>e)}function Of(e,t){let n=e=>{if(e.scrollView===t)return e;for(let t of e.children){let e=n(t);if(e)return e}};return n(e.root)}function kf(e,t,n){let r=[],i=(e,a)=>{if(Ef(e.clip,t,n)){e.scrollView&&Ef(e.rect,t,n)&&r.push({scrollView:e.scrollView,depth:a});for(let t of e.children)i(t,a+1)}};return i(e.root,0),r.sort((e,t)=>t.depth-e.depth),r.map(e=>e.scrollView)}var Af=`\x1B[?1049h`,jf=`\x1B[?1049l`,Mf=`\x1B[?7l`,Nf=`\x1B[?7h`,Pf=`\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h`,Ff=`\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h`,If=`\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l`,Lf=`\x1B[I`,Rf=`\x1B[O`,zf=`\x1B[?2026h`,Bf=`\x1B[?2026l`,Vf=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,Hf=/^\x1b\]133;A(?:\x07|\x1b\\)/,Uf=4,Wf=5,Gf=16,Kf=33554432,qf=67108864,Jf=500,Yf=new Set([`/`,`-`]),Xf=Vu(),Zf=class extends Ld{mode=`fullscreen`;[Id]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity=`character`;selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScrollLines;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(e,t,n,r={}){super(e,t,n),this.implicitDocument={render:e=>super.render(e),handleMouse:e=>super.handleMouse(e),invalidate:()=>{for(let e of this.children)e.invalidate()}},this.implicitScrollView=new rf(this.implicitDocument,{follow:`end`,primary:!0}),this.flashes=new ef(()=>this.requestRender()),this.wheelScrollLines=Math.max(1,Math.floor(r.wheelScrollLines??1)),this.mouseEnabled=r.mouse??!0,this.searchMatchStyle=r.searchMatchStyle??(e=>`\x1b[4m${e}\x1b[24m`),this.searchCurrentMatchStyle=r.searchCurrentMatchStyle??(e=>`\x1b[1;7m${e}\x1b[22;27m`),this.searchNavigationButtonStyle=r.searchNavigationButtonStyle??(e=>e),this.scrollToEndIndicator=r.scrollToEndIndicator,this.openUrl=r.openUrl,this.onRightClickPaste=r.onRightClickPaste,this.copyOnSelect=r.copyOnSelect??!0,this.copySelection=r.copySelection,this.addInputListener(e=>this.handleViewportInput(e))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(e){this.copyOnSelect=e}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}setLayoutRoot(e){this.layoutRoot!==e&&(this.layoutRoot=e,this.currentLayout=void 0,this.requestRender())}render(e){return this.layoutRoot?.render(e)??super.render(e)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let e=hu();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images===`iterm2`&&(this.savedCapabilities=e,gu({...e,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity=`character`,this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let t=wl.env.TERM?.toLowerCase()??``,n=wl.env.TMUX!==void 0||wl.env.ZELLIJ!==void 0||wl.env.STY!==void 0||t.startsWith(`tmux`)||t.startsWith(`screen`)?Pf:Ff;this.terminal.write(`${Af}${Mf}${this.mouseEnabled?n:``}\x1b[2J\x1b[H\x1b[?25l`)}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${zf}${this.deleteKittyImages()}${this.mouseEnabled?If:``}${Nf}${Bf}`),this.uploadedKittyImages.clear())}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=!1,e.preserveScreen)this.terminal.write(`${zf}${jf}\x1b[?25h${Bf}`);else{let e=Math.max(1,this.terminal.columns),t=this.render(e).map(e=>e.replace(Vf,``));this.lastDocument=this.applyLineResets(t.map(e=>e.replaceAll(jd,``))).map(t=>_u(t)||X(t)<=e?t:wd(t,0,e,!0));let n=`${zf}${jf}${Mf}`;for(let e=0;e0&&(n+=`\r `),n+=`\r\x1b[2K${this.lastDocument[e]??``}`;n+=`\x1b[0m${Nf}\r\n\x1b[?25h${Bf}`,this.terminal.write(n)}this.savedCapabilities&&=(gu(this.savedCapabilities),void 0)}}deleteKittyImages(){return this.imageProtocol===`kitty`?Su():``}prepareKittyScreen(e){let t=new Set,n=e.map(e=>{let n=vu(e);if(!n)return e;t.add(n.imageId);let r=this.uploadedKittyImages.get(n.imageId),i={transmissionGeneration:n.transmissionGeneration,transmissionBytes:n.transmissionBytes,estimatedDecodedBytes:n.estimatedDecodedBytes};return r&&this.uploadedKittyImages.delete(n.imageId),this.uploadedKittyImages.set(n.imageId,i),r?.transmissionGeneration===n.transmissionGeneration?n.replacementLine:e}),r=0,i=0,a=0;for(let[e,n]of this.uploadedKittyImages)t.has(e)||(r+=1,i+=n.transmissionBytes,a+=n.estimatedDecodedBytes);let o=``;for(let[e,n]of this.uploadedKittyImages){if(r<=Gf&&i<=Kf&&a<=qf)break;t.has(e)||(o+=xu(e),this.uploadedKittyImages.delete(e),--r,i-=n.transmissionBytes,a-=n.estimatedDecodedBytes)}return{lines:n,evictedImageDeletion:o}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(e){this.getPrimaryScrollView().scrollBy(e),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(e){if(!this.currentLayout)return;let t=this.getPrimaryScrollView(),n=Of(this.currentLayout,t)?.scrollContentLines;if(n){for(let r=t.scrollTop+e;r>=0&&rthis.updateSearchQuery(e),this.searchNavigationButtonStyle),t={component:e,index:new Xd,query:``,matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:`query`};this.activeSearch=t,t.overlay=this.showOverlay(e,{anchor:`top-right`,width:`40%`,minWidth:32,margin:1})}closeSearch(){let e=this.activeSearch;e&&(this.activeSearch=void 0,e.overlay?.hide(),this.requestRender())}updateSearchQuery(e){let t=this.activeSearch;t&&e!==t.query&&(t.anchorRow=t.matches[t.selectedIndex]?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,t.query=e,t.selectionMode=`query`,t.component.setResult(-1,0),this.requestRender())}navigateSearch(e){let t=this.activeSearch;t?.query&&(t.selectionMode=e<0?`previous`:`next`,this.requestRender())}getSearchNavigationDirectionAt(e,t){let n=this.activeSearch,r=n?.overlay?.getBounds();if(n&&r&&!(e=r.col+r.width||t=r.row+r.height))return n.component.getNavigationDirectionAt(t-r.row,e-r.col)}handleSearchMouseEvent(e){let t=this.activeSearch;if(!t)return!1;let n=this.getSearchNavigationDirectionAt(e.x,e.y);return t.component.setHoveredNavigationDirection(n)&&this.requestRender(),n===void 0||e.release||e.button&32||e.button&3?!1:(this.navigateSearch(n),!0)}refreshSearch(e){let t=this.activeSearch;if(!t)return!1;let n=e.primaryScrollView??this.implicitScrollView,r=Of(e,n),i=r?.scrollContentLines;if(!i||!t.query.trim())return t.matches=[],t.selectedIndex=-1,t.selectedKey=void 0,t.selectionMode=`retain`,t.component.setResult(-1,0),!1;let a=t.selectionMode!==`retain`,o=t.index.search(i,t.query),s=o.matches;if(t.matches=s,!o.changed&&t.selectionMode===`retain`)return!1;let c=o.changed?t.selectedKey?s.findIndex(e=>Zd(e)===t.selectedKey):-1:t.selectedIndex,l=-1;if(s.length>0){if(t.selectionMode===`query`){let e=0,n=s.length;for(;e=0?c:Math.min(t.selectedIndex,s.length-1);l=e<0?0:(e+1)%s.length}else if(t.selectionMode===`previous`){let e=c>=0?c:Math.min(t.selectedIndex,s.length-1);l=e<0?s.length-1:(e-1+s.length)%s.length}else l=c>=0?c:Math.min(Math.max(0,t.selectedIndex),s.length-1)}if(t.selectedIndex=l,t.selectedKey=l>=0?Zd(s[l]):void 0,t.selectionMode=`retain`,t.component.setResult(l,s.length),!a)return!1;let u=s[l],d=u?.segments[0],f=u?.segments[u.segments.length-1];if(!r||!d||!f||n.viewportHeight<=0)return!1;let p=n.scrollTop,m=p+n.viewportHeight-1,h=p;return(d.rowm)&&(h=d.row-Math.floor(n.viewportHeight/3)),n.scrollTo(h,{disableFollow:!0}),n.scrollTop!==p}flash(e,t){this.flashes.flash(e,t)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(e){if(e===Rf){let e=this.selectionPressActive,t=e&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,e&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity=`character`,this.selectionInitialRange=void 0,t&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(e===Lf)return{consume:!0};let t=this.parseWheelEvent(e);if(t){let e=this.createMouseEvent(`wheel`,t.button,t.x,t.y,{wheelDelta:t.direction*this.getWheelScrollLines(t.button)}),n=this.dispatchMouseToOverlay(e),r=n.result??(n.hit?void 0:this.dispatchMouseToLayout(e));return r?(this.applyMouseDispatchResult(e,r)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(t),{consume:!0})}let n=this.parseSgrMouseEvent(e);if(n)return this.handleMouseEvent(n),{consume:!0};if(this.isMouseSequence(e))return{consume:!0};let r=au(),i=Ll(e);if(r.matches(e,`tui.altScreen.search`))return i||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(r.matches(e,`tui.altScreen.searchNext`))return i||this.navigateSearch(1),{consume:!0};if(r.matches(e,`tui.altScreen.searchPrevious`))return i||this.navigateSearch(-1),{consume:!0};if(r.matches(e,`tui.altScreen.searchClose`))return i||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(r.matches(e,`tui.altScreen.pageUp`))return i||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-Uf)),{consume:!0};if(r.matches(e,`tui.altScreen.pageDown`))return i||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-Uf)),{consume:!0};if(r.matches(e,`tui.altScreen.halfPageUp`))return i||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(r.matches(e,`tui.altScreen.halfPageDown`))return i||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(r.matches(e,`tui.altScreen.lineUp`))return i||this.scrollBy(-1),{consume:!0};if(r.matches(e,`tui.altScreen.lineDown`))return i||this.scrollBy(1),{consume:!0};if(r.matches(e,`tui.altScreen.previousPrompt`))return i||this.scrollToPrompt(-1),{consume:!0};if(r.matches(e,`tui.altScreen.nextPrompt`))return i||this.scrollToPrompt(1),{consume:!0};if(r.matches(e,`tui.altScreen.top`))return i||this.scrollToTop(),{consume:!0};if(r.matches(e,`tui.altScreen.bottom`))return i||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(e){switch(e&3){case 0:return`left`;case 1:return`middle`;case 2:return`right`;default:return`none`}}createMouseEvent(e,t,n,r,i={}){return{type:e,button:e===`wheel`?`none`:this.decodeMouseButton(t),x:n,y:r,screenX:n,screenY:r,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:!!(t&4),alt:!!(t&8),ctrl:!!(t&16),...i.wheelDelta===void 0?{}:{wheelDelta:i.wheelDelta},...i.clickCount===void 0?{}:{clickCount:i.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let t=new Set,n=Df(this.currentLayout,e.screenX,e.screenY);for(let r of n){if(t.has(r.component)||nf(r.component)&&r.component.handleMouse===Nd.prototype.handleMouse)continue;t.add(r.component);let n=Od(r.component,{...e,x:e.screenX-r.rect.x,y:e.screenY-r.rect.y,width:r.rect.width,height:r.rect.height});if(n)return n}}applyMouseDispatchResult(e,t){let n=this.resolveMouseFocusTarget(t.focusTarget??t.target.component),r=t.focus===!0&&this.getFocusedComponent()!==n;return t.focus&&this.setFocus(n),t.capture&&(this.mouseCapture=t.target),t.render??(r||e.type===`press`||e.type===`click`||e.type===`drag`||e.type===`wheel`)}dispatchMouseToTarget(e,t){return Od(t.component,kd(e,t))}getComponentClickCount(e,t,n){let r=Date.now(),i=this.lastComponentClick,a=i&&r-i.timestamp<=Jf&&i.component===e.component&&i.x===t&&i.y===n?i.count%3+1:1;return this.lastComponentClick={timestamp:r,count:a,component:e.component,x:t,y:n},a}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity=`character`,this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(e){let t=!!(e.button&32),n=e.release?`release`:t?this.decodeMouseButton(e.button)===`none`?`move`:`drag`:`press`,r=this.createMouseEvent(n,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let t=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let n=!1,i=this.dispatchMouseToTarget(r,t);if(i&&(n=this.applyMouseDispatchResult(r,i)),e.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===e.x&&this.mousePressPoint.y===e.y){let r=this.createMouseEvent(`click`,e.button,e.x,e.y,{clickCount:this.getComponentClickCount(t,e.x,e.y)}),i=this.dispatchMouseToTarget(r,t);i&&(n=this.applyMouseDispatchResult(r,i)||n)}this.clearComponentMouseGesture()}n&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let i=this.dispatchMouseToOverlay(r);if(i.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(e))return;let t=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),t)return}let a=i.result??(i.hit?void 0:this.dispatchMouseToLayout(r));if(a){let t=this.applyMouseDispatchResult(r,a);n===`press`&&(this.clearTextSelection(),this.mousePressTarget=a.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=!1),t&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e)}parseWheelEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(t){let e=Number.parseInt(t[1],10);if(!(e&64))return;let n=e&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,button:e}}if(e.length===6&&e.startsWith(`\x1B[M`)){let t=e.charCodeAt(3)-32;if(!(t&64))return;let n=t&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:t}}}getWheelScrollLines(e){return e&8?this.wheelScrollLines*Wf:this.wheelScrollLines}routeWheel(e){let t=e.direction*this.getWheelScrollLines(e.button),n=new Set;for(let r of this.currentLayout?kf(this.currentLayout,e.x,e.y):[])if(n.add(r),t=r.scrollBy(t),t===0||r.overscroll===`contain`)break;let r=this.getPrimaryScrollView();t!==0&&!n.has(r)&&r.scrollBy(t),this.updateScrollbarHover(e.x,e.y),this.requestRender()}parseSgrMouseEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(t)return{button:Number.parseInt(t[1],10),x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,release:t[4]===`m`}}handleRightClickPaste(e){if(!this.onRightClickPaste||wl.platform!==`win32`||wl.env.TERM_PROGRAM?.toLowerCase()===`vscode`||e.release||e.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(e){let t=this.scrollToEndIndicatorRect;return!t||e.release||e.button&32||e.button&3||e.y!==t.row||e.x=t.column+t.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(e,t,n=!1){if(!this.hasOverlay()&&this.currentLayout)for(let r of kf(this.currentLayout,e,t)){let i=Of(this.currentLayout,r),a=i?Sf(i,n):void 0;if(a&&e===a.column&&t>=a.trackTop&&t=t.geometry.thumbTop&&e.ye.col>=t.start&&e.cole.selectable&&t.selectable&&(e.joiner||t.joiner),o=n[i].start,s=n[i].end;for(let e=i;e>0&&a(n[e-1],n[e]);e--)o=n[e-1].start;for(let e=i;e=i),this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref?.())}autoScrollSelection(){let e=this.selectionAnchor?.scrollView,t=this.selectionDragPointer,n=this.selectionAutoScrollDirection;if(!e||!t||n===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(n)===n){this.stopSelectionAutoScroll();return}let r=this.getScrollSelectionPoint(e,t.x,t.y);r&&this.updateSelectionFocus(r),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&=(clearInterval(this.selectionAutoScrollTimer),void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(e){let t=e.button&3;if(t!==0&&!(e.release&&t===3))return;let n=this.selectionAnchor?.scrollView,r=this.getSelectionPoint(e,n);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(r);let t=!this.selectionDragged&&this.selectionAnchor.scrollView===r.scrollView&&this.selectionAnchor.row===r.row&&this.selectionAnchor.col===r.col,n=t?this.pressedUrl:void 0;if(this.pressedUrl=void 0,n&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(n)}catch{}this.requestRender();return}if(t){let t=this.createMouseEvent(`click`,e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),n=this.dispatchMouseToOverlay(t),r=n.result??(n.hit?void 0:this.dispatchMouseToLayout(t));if(r){let e=this.applyMouseDispatchResult(t,r);this.clearTextSelection(),e&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if(e.button&32){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(r),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let i=!this.hasOverlay()&&this.currentLayout?kf(this.currentLayout,e.x,e.y)[0]:void 0,a=this.getSelectionPoint(e,i),o=this.getWordSelection(a),s=this.getClickCount(a,o),c=s===2?o:s===3?this.getLineSelection(a):void 0;this.selectionGranularity=c?s===2?`word`:`line`:`character`,this.selectionInitialRange=c,this.selectionAnchor=c?.start??a,this.selectionFocus=c?.end??a,this.selectionDragged=!1,this.pressedUrl=c?void 0:id(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,e.y))]??``,Math.max(0,Math.min(this.terminal.columns-1,e.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let e=this.selectionAnchor.rowi&&(r+=n(e.slice(i,a))),r+=t.code,a+=t.length,i=a}return if)break;for(let o of t.segments){let t=i.rect.y+o.row-r.scrollTop;if(t=c)continue;let d=Math.max(l,i.rect.x+o.startCol),f=Math.min(u,i.rect.x+o.endCol);if(f<=d)continue;let p=a.get(t)??[];p.push({startCol:d,endCol:f,current:e===n.selectedIndex}),a.set(t,p)}}let h=[...e];for(let[e,t]of a){let n=h[e]??``;if(_u(n))continue;let r=X(n);for(let e of t.sort((e,t)=>t.startCol-e.startCol)){let t=Math.min(e.startCol,r),i=Math.min(e.endCol,r);if(i<=t)continue;let a=wd(n,0,t,!0),o=wd(n,t,i-t,!0),s=wd(n,i,Math.max(0,r-i),!0);n=`${a}${this.applySearchTextHighlight(o,e.current)}${s}`}h[e]=n}return h}applySelectionHighlight(e){let t=`\x1B[7m`,n=0;for(;n{if(ta||tr.end.row||_u(e))return e;let n=X(e),c=this.getSelectionColumns(e,t,r,o,s);if(c.end<=c.start)return e;let l=wd(e,0,c.start,!0),u=wd(e,c.start,c.end-c.start,!0),d=wd(e,c.end,Math.max(0,n-c.end),!0);return`${l}${this.applySelectionHighlight(u)}${d}`})}isMouseSequence(e){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith(`\x1B[M`)}compositeScrollToEndIndicator(e,t,n){this.scrollToEndIndicatorRect=void 0;let r=t.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!r.followEnd||r.isFollowingEnd)return e;let i=Of(t,r),a=i?.clip;if(!a||a.width<=0||a.height<=0)return e;let o=a.y+a.height-1;if(o>=e.length||_u(e[o]??``))return e;let s=i?Sf(i)?.column:void 0,c=Math.max(0,(s??a.x+a.width)-a.x),l=Cd(this.scrollToEndIndicator(),c,``),u=X(l);if(u===0)return e;let d=a.x+Math.floor((c-u)/2),f=[...e];return f[o]=Fd(f[o]??``,l,d,u,n),this.scrollToEndIndicatorRect={row:o,column:d,width:u},f}compositeFlashes(e,t,n){let r=this.flashes.render(t).slice(-n);if(r.length===0)return e;let i=[...e];for(;i.lengththis.requestRender());this.refreshSearch(r)&&(r=Tf(n,e,t,()=>this.requestRender()));let i=r.lines.map(e=>e.replace(Vf,``));i=this.applySearchHighlights(i,r),i=this.compositeScrollToEndIndicator(i,r,e),i=this.compositeOverlays(i,e,t),i.length>t&&(i=i.slice(i.length-t)),i=this.applySelection(i,r),i=this.compositeFlashes(i,e,t);let a=this.extractCursorPosition(i,t);i=this.applyLineResets(i).map(t=>_u(t)||X(t)<=e?t:wd(t,0,e,!0));let o=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==t,s=i.some((e,t)=>e!==this.previousScreen[t]&&(_u(e)||_u(this.previousScreen[t]??``))),c=o||s,l=this.uploadedKittyImages.size>0,u=c&&this.imageProtocol===`kitty`?this.prepareKittyScreen(i):{lines:i,evictedImageDeletion:``},d=zf;if(o){this.fullRedrawCount+=1;let e=this.imageProtocol===`kitty`&&l?Cu():this.deleteKittyImages();d+=`${e}\x1b[2J`}else s&&(this.imageProtocol===`iterm2`?d+=`\x1B[2J`:this.imageProtocol===`kitty`&&(d+=Cu()));d+=u.evictedImageDeletion;for(let e=0;ee.replace(/[\r\n]+/g,` `).trim(),np=(e,t,n)=>Math.max(t,Math.min(e,n)),rp=class{items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(e,t,n,r={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.layout=r}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(` No matching commands`)),t;let n=this.getPrimaryColumnWidth(),{startIndex:r,endIndex:i}=this.getVisibleRange();for(let a=r;a0||i=n)){if(e.type===`press`)return this.mousePressedIndex=r,this.selectedIndex!==r&&(this.selectedIndex=r,this.notifySelectionChange()),{handled:!0,focus:!0};if(e.type===`click`){let e=this.mousePressedIndex??r;this.mousePressedIndex=void 0;let t=this.selectedIndex!==e;this.selectedIndex=e,t&&this.notifySelectionChange();let n=this.filteredItems[this.selectedIndex];return n&&this.onSelect?.(n),{handled:!0}}}}handleInput(e){let t=au();if(t.matches(e,`tui.select.up`))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,`tui.select.down`))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(t.matches(e,`tui.select.confirm`)){let e=this.filteredItems[this.selectedIndex];e&&this.onSelect&&this.onSelect(e)}else t.matches(e,`tui.select.cancel`)&&this.onCancel&&this.onCancel()}getVisibleRange(){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex:e,endIndex:Math.min(e+this.maxVisible,this.filteredItems.length)}}renderItem(e,t,n,r,i){let a=t?`→ `:` `,o=X(a);if(r&&n>40){let s=Math.max(1,Math.min(i,n-o-4)),c=Math.max(1,s-$f),l=this.truncatePrimary(e,t,c,s),u=X(l),d=` `.repeat(Math.max(1,s-u)),f=n-(o+u+d.length)-2;if(f>ep){let e=Cd(r,f,``);if(t)return this.theme.selectedText(`${a}${l}${d}${e}`);let n=this.theme.description(d+e);return a+l+n}}let s=n-o-2,c=this.truncatePrimary(e,t,s,s);return t?this.theme.selectedText(`${a}${c}`):a+c}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds();return np(this.filteredItems.reduce((e,t)=>Math.max(e,X(this.getDisplayValue(t))+$f),0),e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??Qf,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??Qf;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,n,r){let i=this.getDisplayValue(e);return Cd(this.layout.truncatePrimary?this.layout.truncatePrimary({text:i,maxWidth:n,columnWidth:r,item:e,isSelected:t}):Cd(i,n,``),n,``)}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}},ip=Bu(),ap=Vu(),op=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,sp=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function cp(e){return e.length>=10&&sp.test(e)}function lp(e,t,n){if(n.size===0||!e.includes(`[paste #`))return t.segment(e);let r=[];for(let t of e.matchAll(op)){let e=Number.parseInt(t[1],10);n.has(e)&&r.push({start:t.index,end:t.index+t[0].length})}if(r.length===0)return t.segment(e);let i=t.segment(e),a=[],o=0;for(let t of i){for(;o=n.start&&t.indext&&(s>=0&&a-c+d<=t?(r.push({text:e.slice(o,s),startIndex:o,endIndex:s}),o=s,a-=c):ot){let e=up(u,t);for(let t=0;te!==`@`).map(mp);return RegExp(`(?:^|[ \\t])(?:@(?:"[^"]*|[^\\s]*)|[${t.join(``)}][^\\s]*)$`)}function _p(e,t,n){let r=Math.max(0,n),i=` ${e} ${t} more `,a=X(i);if(a+2<=r){let e=Math.floor((r-a)/2);return`─`.repeat(e)+i+`─`.repeat(r-e-a)}let o=`─── ${e} ${t} more `,s=r-X(o);if(s>=0)return o+`─`.repeat(s);let c=`...`.slice(0,r);return wd(o,0,r-X(c),!0)+c}var vp=class{state={lines:[``],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...pp];autocompleteTriggerPattern=hp(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=gp(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix=``;autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer=``;isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new ou;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new Rd;onSubmit;onChange;disableSubmit=!1;constructor(e,t,n={}){this.tui=e,this.theme=t,this.borderColor=t.borderColor;let r=n.paddingX??0;this.paddingX=Number.isFinite(r)?Math.max(0,Math.floor(r)):0;let i=n.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(i)?Math.max(3,Math.min(20,Math.floor(i))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e,t){return lp(e,t===`word`?ap:ip,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e,this.setAutocompleteTriggerCharacters(e.triggerCharacters??[])}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===``}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;if(!(t<-1||t>=this.history.length)){if(this.historyIndex===-1&&t>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=t,this.historyIndex===-1){let e=this.historyDraft;this.historyDraft=null,e?(this.state=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal(``)}else this.setTextInternal(this.history[this.historyIndex]||``,e===-1?`start`:`end`)}}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(e,t=`end`){let n=e.split(` `);this.state.lines=n.length===0?[``]:n,this.state.cursorLine=t===`start`?0:this.state.lines.length-1,this.setCursorCol(t===`start`?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(e,t){let n=t>0?_p(`↑`,t,e):`─`.repeat(e);return this.borderColor(n)}renderBottomBorder(e,t){let n=t>0?_p(`↓`,t,e):`─`.repeat(e);return this.borderColor(n)}render(e){let t=Math.max(0,Math.floor((e-1)/2)),n=Math.min(this.paddingX,t),r=Math.max(1,e-n*2),i=Math.max(1,r-+!n);this.lastWidth=i;let a=this.layoutText(i),o=this.tui.terminal.rows,s=Math.max(5,Math.floor(o*.3)),c=a.findIndex(e=>e.hasCursor);c===-1&&(c=0),c=this.scrollOffset+s&&(this.scrollOffset=c-s+1);let l=Math.max(0,a.length-s);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,l));let u=a.slice(this.scrollOffset,this.scrollOffset+s);this.renderedVisibleLineCount=u.length;let d=[],f=` `.repeat(n),p=f;d.push(this.renderTopBorder(e,this.scrollOffset));let m=this.focused;for(let e of u){let t=e.text,i=X(e.text),a=!1;if(e.hasCursor&&e.cursorPos!==void 0){let o=t.slice(0,e.cursorPos),s=t.slice(e.cursorPos),c=m?jd:``;if(s.length>0){let e=[...this.segment(s,`grapheme`)][0]?.segment||``,n=s.slice(e.length),r=`\x1b[7m${e}\x1b[0m`;t=o+c+r+n}else t=o+c+`\x1B[7m \x1B[0m`,i+=1,i>r&&n>0&&(a=!0)}let o=` `.repeat(Math.max(0,r-i)),s=a?p.slice(1):p;d.push(`${f}${t}${o}${s}`)}let h=a.length-(this.scrollOffset+u.length);if(d.push(this.renderBottomBorder(e,h)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let e=this.autocompleteList.render(r);this.renderedAutocompleteHeight=e.length;for(let t of e){let e=X(t),n=` `.repeat(Math.max(0,r-e));d.push(`${f}${t}${n}${p}`)}}return d}handleMouse(e){let t=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&e.y>=t&&e.ythis.renderedVisibleLineCount)return{handled:!0,focus:!0};let n=this.buildVisualLineMap(this.lastWidth),r=this.scrollOffset+e.y-1,i=n[r];if(!i)return{handled:!0,focus:!0};let a=this.state.lines[i.logicalLine]??``,o=i.startCol+i.length,s=a.slice(i.startCol,o),c=Math.max(0,Math.floor((e.width-1)/2)),l=Math.min(this.paddingX,c),u=Math.max(0,e.x-l),d=0,f=s.length,p=0;for(let e of this.segment(s,`grapheme`)){let t=d+X(e.segment);if(p=e.index,u0&&(f=p),this.state.cursorLine=i.logicalLine,this.setCursorCol(i.startCol+f),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(e){let t=au();if(this.jumpMode!==null){if(t.matches(e,`tui.editor.jumpForward`)||t.matches(e,`tui.editor.jumpBackward`)){this.jumpMode=null;return}let n=$l(e)??(e.charCodeAt(0)>=32?e:void 0);if(n!==void 0){let e=this.jumpMode;this.jumpMode=null,this.jumpToChar(n,e);return}this.jumpMode=null}if(e.includes(`\x1B[200~`)&&(this.isInPaste=!0,this.pasteBuffer=``,e=e.replace(`\x1B[200~`,``)),this.isInPaste){this.pasteBuffer+=e;let t=this.pasteBuffer.indexOf(`\x1B[201~`);if(t!==-1){let e=this.pasteBuffer.substring(0,t);e.length>0&&this.handlePaste(e),this.isInPaste=!1;let n=this.pasteBuffer.substring(t+6);this.pasteBuffer=``,n.length>0&&this.handleInput(n);return}return}if(t.matches(e,`tui.input.copy`))return;if(t.matches(e,`tui.editor.undo`)){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(t.matches(e,`tui.select.cancel`)){this.cancelAutocomplete();return}if(t.matches(e,`tui.select.up`)||t.matches(e,`tui.select.down`)){this.autocompleteList.handleInput(e);return}if(t.matches(e,`tui.input.tab`)){let e=this.autocompleteList.getSelectedItem();if(e&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(t.matches(e,`tui.select.confirm`)){let e=this.autocompleteList.getSelectedItem();if(e&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);if(this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.autocompletePrefix.startsWith(`/`))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(t.matches(e,`tui.input.tab`)&&!this.autocompleteState){this.handleTabCompletion();return}if(t.matches(e,`tui.editor.deleteToLineEnd`)){this.deleteToEndOfLine();return}if(t.matches(e,`tui.editor.deleteToLineStart`)){this.deleteToStartOfLine();return}if(t.matches(e,`tui.editor.deleteWordBackward`)){this.deleteWordBackwards();return}if(t.matches(e,`tui.editor.deleteWordForward`)){this.deleteWordForward();return}if(t.matches(e,`tui.editor.deleteCharBackward`)||Jl(e,`shift+backspace`)){this.handleBackspace();return}if(t.matches(e,`tui.editor.deleteCharForward`)||Jl(e,`shift+delete`)){this.handleForwardDelete();return}if(t.matches(e,`tui.editor.yank`)){this.yank();return}if(t.matches(e,`tui.editor.yankPop`)){this.yankPop();return}if(t.matches(e,`tui.editor.historyPrevious`)){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(t.matches(e,`tui.editor.historyNext`)){this.cancelAutocomplete(),this.navigateHistory(1);return}if(t.matches(e,`tui.editor.cursorLineStart`)){this.moveToLineStart();return}if(t.matches(e,`tui.editor.cursorLineEnd`)){this.moveToLineEnd();return}if(t.matches(e,`tui.editor.cursorWordLeft`)){this.moveWordBackwards();return}if(t.matches(e,`tui.editor.cursorWordRight`)){this.moveWordForwards();return}if(t.matches(e,`tui.input.newLine`)||e.charCodeAt(0)===10&&e.length>1||e===`\x1B\r`||e===`\x1B[13;2~`||e.length>1&&e.includes(`\x1B`)&&e.includes(`\r`)||e===` `&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,`tui.input.submit`)){if(this.disableSubmit)return;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>0&&e[this.state.cursorCol-1]===`\\`){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,`tui.editor.cursorUp`)){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(t.matches(e,`tui.editor.cursorDown`)){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,`tui.editor.cursorRight`)){this.moveCursor(0,1);return}if(t.matches(e,`tui.editor.cursorLeft`)){this.moveCursor(0,-1);return}if(t.matches(e,`tui.editor.pageUp`)){this.pageScroll(-1);return}if(t.matches(e,`tui.editor.pageDown`)){this.pageScroll(1);return}if(t.matches(e,`tui.editor.jumpForward`)){this.jumpMode=`forward`;return}if(t.matches(e,`tui.editor.jumpBackward`)){this.jumpMode=`backward`;return}if(Jl(e,`shift+space`)){this.insertCharacter(` `);return}let n=$l(e);if(n!==void 0){this.insertCharacter(n);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let t=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]===``)return t.push({text:``,hasCursor:!0,cursorPos:0}),t;for(let n=0;n=r.startIndex,c=a-r.startIndex):(s=a>=r.startIndex&&ar.text.length&&(c=r.text.length)))),s?t.push({text:r.text,hasCursor:!0,cursorPos:c}):t.push({text:r.text,hasCursor:!1})}}}return t}getText(){return this.state.lines.join(` `)}expandPasteMarkers(e){let t=e;for(let[e,n]of this.pastes){let r=RegExp(`\\[paste #${e}( (\\+\\d+ lines|\\d+ chars))?\\]`,`g`);t=t.replace(r,()=>n)}return t}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(` `))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let t=this.normalizeText(e);this.getText()!==t&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(t)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,` `).replace(/\r/g,` `).replace(/\t/g,` `)}insertTextAtCursorInternal(e){if(!e)return;let t=this.normalizeText(e),n=t.split(` `),r=this.state.lines[this.state.cursorLine]||``,i=r.slice(0,this.state.cursorCol),a=r.slice(this.state.cursorCol);n.length===1?(this.state.lines[this.state.cursorLine]=i+t+a,this.setCursorCol(this.state.cursorCol+t.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),i+n[0],...n.slice(1,-1),n[n.length-1]+a,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=n.length-1,this.setCursorCol((n[n.length-1]||``).length)),this.onChange&&this.onChange(this.getText())}insertCharacter(e,t){this.exitHistoryBrowsing(),t||((bd(e)||this.lastAction!==`type-word`)&&this.pushUndoSnapshot(),this.lastAction=`type-word`);let n=this.state.lines[this.state.cursorLine]||``,r=n.slice(0,this.state.cursorCol),i=n.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=r+e+i,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e===`/`&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(e)){let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol),t=e[e.length-2];(e.length===1||t===` `||t===` `)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)){let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);(this.isInSlashCommandContext(e)||this.autocompleteTriggerPattern.test(e))&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let t=e.replace(/\x1b\[(\d+);5u/g,(e,t)=>{let n=Number(t);return n>=97&&n<=122?String.fromCharCode(n-96):n>=65&&n<=90?String.fromCharCode(n-64):e}),n=this.normalizeText(t).split(``).filter(e=>e===` `||e.charCodeAt(0)>=32).join(``);if(/^[/~.]/.test(n)){let e=this.state.lines[this.state.cursorLine]||``,t=this.state.cursorCol>0?e[this.state.cursorCol-1]:``;t&&/\w/.test(t)&&(n=` ${n}`)}let r=n.split(` `),i=n.length;if(r.length>10||i>1e3){this.pasteCounter++;let e=this.pasteCounter;this.pastes.set(e,n);let t=r.length>10?`[paste #${e} +${r.length} lines]`:`[paste #${e} ${i} chars]`;this.insertTextAtCursorInternal(t);return}if(r.length===1){this.insertTextAtCursorInternal(n);return}this.insertTextAtCursorInternal(n)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=e.slice(0,this.state.cursorCol),n=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=t,this.state.lines.splice(this.state.cursorLine+1,0,n),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,t){if(this.disableSubmit||!Jl(e,`enter`))return!1;let n=t.getKeys(`tui.input.submit`);if(!(n.includes(`shift+enter`)||n.includes(`shift+return`)))return!1;let r=this.state.lines[this.state.cursorLine]||``;return this.state.cursorCol>0&&r[this.state.cursorCol-1]===`\\`}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(` `)).trim();this.state={lines:[``],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(``),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=e.slice(0,this.state.cursorCol),n=[...this.segment(t,`grapheme`)],r=n[n.length-1],i=r?r.segment.length:1,a=sp.exec(r.segment);if(a){let e=Number(a[1]);this.pastes.delete(e),this.pasteCounter--;let t=[...this.pastes.keys()].filter(t=>t>e).sort((e,t)=>e-t);for(let e of t)this.pastes.set(e-1,this.pastes.get(e)),this.pastes.delete(e);this.state.lines=this.state.lines.map(t=>t.replace(op,(t,n,r)=>{let i=Number(n);return i<=e?t:`[paste #${i-1}${r}]`}))}e=this.state.lines[this.state.cursorLine]||``;let o=e.slice(0,this.state.cursorCol-i),s=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=o+s,this.setCursorCol(this.state.cursorCol-i)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);(this.isInSlashCommandContext(e)||this.autocompleteTriggerPattern.test(e))&&this.tryTriggerAutocomplete()}}setCursorCol(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,t,n){let r=e[t],i=e[n];if(!(r&&i))return;let a;if(this.snappedFromCursorCol!==null){let t=this.findVisualLineAt(e,r.logicalLine,this.snappedFromCursorCol);a=this.snappedFromCursorCol-e[t].startCol}else a=this.state.cursorCol-r.startCol;let o=t===e.length-1||e[t+1]?.logicalLine!==r.logicalLine?r.length:Math.max(0,r.length-1),s=n===e.length-1||e[n+1]?.logicalLine!==i.logicalLine?i.length:Math.max(0,i.length-1),c=this.computeVerticalMoveColumn(a,o,s);this.state.cursorLine=i.logicalLine;let l=i.startCol+c,u=this.state.lines[i.logicalLine]||``;this.state.cursorCol=Math.min(l,u.length);let d=[...this.segment(u,`grapheme`)];for(let r of d){if(r.index>this.state.cursorCol)break;if(!(r.segment.length<=1)&&this.state.cursorColt){let a=r.index+r.segment.length,o=n+1;for(;o0){this.pushUndoSnapshot();let t=e.slice(0,this.state.cursorCol);this.killRing.push(t,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(` `,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol0){this.pushUndoSnapshot(),this.killRing.push(` `,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}}else{this.pushUndoSnapshot();let t=this.lastAction===`kill`,n=this.state.cursorCol;this.moveWordBackwards();let r=this.state.cursorCol;this.setCursorCol(n);let i=e.slice(r,this.state.cursorCol);this.killRing.push(i,{prepend:!0,accumulate:t}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(0,r)+e.slice(this.state.cursorCol),this.setCursorCol(r)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>=e.length){if(this.state.cursorLine=0&&(a=0&&t0){if(this.state.cursorCol0){let t=e.slice(0,this.state.cursorCol),n=[...this.segment(t,`grapheme`)],r=n[n.length-1];this.setCursorCol(this.state.cursorCol-(r?r.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||``;this.setCursorCol(e.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(e){this.lastAction=null;let t=this.tui.terminal.rows,n=Math.max(5,Math.floor(t*.3)),r=this.buildVisualLineMap(this.lastWidth),i=this.findCurrentVisualLine(r),a=Math.max(0,Math.min(r.length-1,i+e*n));this.moveToVisualLine(r,i,a)}moveWordBackwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||``;this.setCursorCol(e.length)}return}this.setCursorCol(Bd(e,this.state.cursorCol,{segment:e=>this.segment(e,`word`),isAtomicSegment:cp}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction=`yank`}yankPop(){if(this.lastAction!==`yank`||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction=`yank`}insertYankedText(e){this.exitHistoryBrowsing();let t=e.split(` `);if(t.length===1){let t=this.state.lines[this.state.cursorLine]||``,n=t.slice(0,this.state.cursorCol),r=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+e+r,this.setCursorCol(this.state.cursorCol+e.length)}else{let e=this.state.lines[this.state.cursorLine]||``,n=e.slice(0,this.state.cursorCol),r=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+(t[0]||``);for(let e=1;e=e.length){this.state.cursorLinethis.segment(e,`word`),isAtomicSegment:cp}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);return e.trim()===``||e.trim()===`/`}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith(`/`)}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let n=-1;for(let r=0;r{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},r}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}handleTabCompletion(){if(!this.autocompleteProvider)return;let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);this.isInSlashCommandContext(e)&&!e.trimStart().includes(` `)?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&this.autocompleteProvider.shouldTriggerFileCompletion&&!this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,n=this.getAutocompleteDebounceMs(e);if(n>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},n);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let n=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await n,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let r=new AbortController;this.autocompleteAbort=r;let i=++this.autocompleteRequestId,a=this.getText(),o=this.state.cursorLine,s=this.state.cursorCol;await this.runAutocompleteRequest(i,r,a,o,s,t)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(e){let t=[...pp];for(let n of e)n.length!==1||n===`/`||bd(n)||t.includes(n)||t.push(n);this.autocompleteTriggerCharacters=t,this.autocompleteTriggerPattern=hp(t),this.autocompleteDebouncePattern=gp(t)}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let t=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(t)?fp:0}async runAutocompleteRequest(e,t,n,r,i,a){if(!this.autocompleteProvider)return;let o=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:a.force});if(this.isAutocompleteRequestCurrent(e,t,n,r,i)){if(this.autocompleteAbort=void 0,!o||!Array.isArray(o.items)||o.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(a.force&&a.explicitTab&&o.items.length===1){let e=o.items[0];this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,o.prefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(o,a.force?`force`:`regular`),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,n,r,i){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===n&&this.state.cursorLine===r&&this.state.cursorCol===i}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let n=this.getBestAutocompleteMatchIndex(e.items,e.prefix);n>=0&&this.autocompleteList.setSelectedIndex(n),this.autocompleteState=t}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&=(clearTimeout(this.autocompleteDebounceTimer),void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=``}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){this.autocompleteState&&this.autocompleteProvider&&this.requestAutocomplete({force:this.autocompleteState===`force`,explicitTab:!1})}},yp=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(e=``,t=1,n=1,r){this.text=e,this.paddingX=t,this.paddingY=n,this.customBgFn=r}setText(e){this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===``){let t=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=t,t}let t=this.text.replace(/\t/g,` `),n=Math.min(this.paddingX,Math.max(0,Math.floor((e-1)/2))),r=_d(t,Math.max(1,e-n*2)),i=` `.repeat(n),a=` `.repeat(n),o=[];for(let t of r){let n=i+t+a;if(this.customBgFn)o.push(Sd(n,e,this.customBgFn));else{let t=X(n),r=Math.max(0,e-t);o.push(n+` `.repeat(r))}}let s=` `.repeat(e),c=[];for(let t=0;t0?l:[``]}},bp=class{text;paddingX;paddingY;constructor(e,t=0,n=0){this.text=e,this.paddingX=t,this.paddingY=n}invalidate(){}render(e){let t=[],n=` `.repeat(e);for(let e=0;enull};function Tp(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function Z(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Dp.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Ep=((e=``)=>{try{return!!RegExp(`(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Tp(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Tp(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Tp(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Tp(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Tp(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Tp(e=>RegExp(`^ {0,${e}}>`))},Op=/^(?:[ \t]*(?:\n|$))+/,kp=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ap=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,jp=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Mp=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Np=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Pp=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Fp=Z(Pp).replace(/bull/g,Np).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),Ip=Z(Pp).replace(/bull/g,Np).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Lp=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Rp=/^[^\n]+/,zp=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Bp=Z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,zp).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Vp=Z(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Np).getRegex(),Hp=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,Up=/|$))/,Wp=Z(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,Up).replace(`tag`,Hp).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Gp=Z(Lp).replace(`hr`,jp).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Hp).getRegex(),Kp={blockquote:Z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Gp).getRegex(),code:kp,def:Bp,fences:Ap,heading:Mp,hr:jp,html:Wp,lheading:Fp,list:Vp,newline:Op,paragraph:Gp,table:wp,text:Rp},qp=Z(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,jp).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Hp).getRegex(),Jp={...Kp,lheading:Ip,table:qp,paragraph:Z(Lp).replace(`hr`,jp).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,qp).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Hp).getRegex()},Yp={...Kp,html:Z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Up).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:wp,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Z(Lp).replace(`hr`,jp).replace(`heading`,` *#{1,6} *[^ ]`).replace(`lheading`,Fp).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Xp=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Zp=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Qp=/^( {2,}|\\)\n(?!\s*$)/,$p=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Ep?"(?`+)[^`]+\k(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),cm=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,lm=Z(cm,`u`).replace(/punct/g,em).getRegex(),um=Z(cm,`u`).replace(/punct/g,im).getRegex(),dm=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,fm=Z(dm,`gu`).replace(/notPunctSpace/g,nm).replace(/punctSpace/g,tm).replace(/punct/g,em).getRegex(),pm=Z(dm,`gu`).replace(/notPunctSpace/g,om).replace(/punctSpace/g,am).replace(/punct/g,im).getRegex(),mm=Z(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,nm).replace(/punctSpace/g,tm).replace(/punct/g,em).getRegex(),hm=Z(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,em).getRegex(),gm=Z(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,nm).replace(/punctSpace/g,tm).replace(/punct/g,em).getRegex(),_m=Z(/\\(punct)/,`gu`).replace(/punct/g,em).getRegex(),vm=Z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ym=Z(Up).replace(`(?:-->|$)`,`-->`).getRegex(),bm=Z(`^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^`).replace(`comment`,ym).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),xm=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Sm=Z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,xm).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Cm=Z(/^!?\[(label)\]\[(ref)\]/).replace(`label`,xm).replace(`ref`,zp).getRegex(),wm=Z(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,zp).getRegex(),Tm=Z(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Cm).replace(`nolink`,wm).getRegex(),Em=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Dm={_backpedal:wp,anyPunctuation:_m,autolink:vm,blockSkip:sm,br:Qp,code:Zp,del:wp,delLDelim:wp,delRDelim:wp,emStrongLDelim:lm,emStrongRDelimAst:fm,emStrongRDelimUnd:mm,escape:Xp,link:Sm,nolink:wm,punctuation:rm,reflink:Cm,reflinkSearch:Tm,tag:bm,text:$p,url:wp},Om={...Dm,link:Z(/^!?\[(label)\]\((.*?)\)/).replace(`label`,xm).getRegex(),reflink:Z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,xm).getRegex()},km={...Dm,emStrongRDelimAst:pm,emStrongLDelim:um,delLDelim:hm,delRDelim:gm,url:Z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Em).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Z(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":`>`,'"':`"`,"'":`'`},Pm=e=>Nm[e];function Fm(e,t){if(t){if(Dp.escapeTest.test(e))return e.replace(Dp.escapeReplace,Pm)}else if(Dp.escapeTestNoEncode.test(e))return e.replace(Dp.escapeReplaceNoEncode,Pm);return e}function Im(e){try{e=encodeURI(e).replace(Dp.percentDecode,`%`)}catch{return null}return e}function Lm(e,t){let n=e.replace(Dp.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Dp.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length=0&&Dp.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(` `)}function Bm(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r0?-2:-1}function Vm(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Hm(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Um(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(` `).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(` `)}var Wm=class{options;rules;lexer;constructor(e){this.options=e||Sp}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:zm(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Um(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Rm(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Rm(t[0],` `),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Rm(t[0],` `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Rm(t[0],` `).split(` `),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o=0;for(;o1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=Vm(t[2].split(` `,1)[0],t[1].length),l=e.split(` `,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+` `,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(` `,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=` `+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=` `+l}u=!l.trim(),r+=p+` `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=zm(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:Rm(t[0],` `),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Lm(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(` `):[],a={type:`table`,raw:Rm(t[0],` `),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:Rm(t[0],` `),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===` `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Rm(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Bm(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Hm(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Hm(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},Gm=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Sp,this.options.tokenizer=this.options.tokenizer||new Wm,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:Dp,block:jm.normal,inline:Mm.normal};this.options.pedantic?(t.block=jm.pedantic,t.inline=Mm.pedantic):this.options.gfm&&(t.block=jm.gfm,t.inline=this.options.breaks?Mm.breaks:Mm.gfm),this.tokenizer.rules=t}static get rules(){return{block:jm,inline:Mm}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Dp.carriageReturn,` `),this.blockTokens(e,this.tokens);for(let e=0;e(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=` `:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(` `)?``:` `)+i.raw,n.text+=` `+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(` `)?``:` `)+i.raw,n.text+=` `+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(` `)?``:` `)+i.raw,r.text+=` `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(` `)?``:` `)+i.raw,n.text+=` `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},Km=class{options;parser;constructor(e){this.options=e||Sp}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Dp.notSpaceStart)?.[0],i=e.replace(Dp.endingNewline,``)+` `;return r?`
`+(n?i:Fm(i,!0))+`
`:`
`+(n?i:Fm(i,!0))+`
`}blockquote({tokens:e}){return`
${this.parser.parse(e)}
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} `}hr(e){return`
`}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t `+r+` `}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • `}checkbox({checked:e}){return` `}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    `}table(e){let t=``,n=``;for(let t=0;t${r}`,` `+t+` `+r+`
    `}tablerow({text:e}){return` ${e} `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` `}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${Fm(e,!0)}`}br(e){return`
    `}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Im(e);if(i===null)return r;e=i;let a=`
    `+r+``,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Im(e);if(i===null)return Fm(n);e=i;let a=`${Fm(n)}`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Fm(e.text)}},qm=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},Jm=class e{options;renderer;textRenderer;constructor(e){this.options=e||Sp,this.options.renderer=this.options.renderer||new Km,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new qm}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Km(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Wm(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Ym;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=Ym.passThroughHooks.has(n)?e=>{if(this.defaults.async&&Ym.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Gm.lex(e,t??this.defaults)}parser(e,t){return Jm.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Gm.lex:Gm.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?Jm.parse:Jm.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Gm.lex:Gm.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?Jm.parse:Jm.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=` Please report this to https://github.com/markedjs/marked.`,e){let e=`

    An error occurred:

    `+Fm(n.message+``,!0)+`
    `;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Zm=new Xm;function Qm(e,t){return Zm.parse(e,t)}Qm.options=Qm.setOptions=function(e){return Zm.setOptions(e),Qm.defaults=Zm.defaults,Cp(Qm.defaults),Qm},Qm.getDefaults=xp,Qm.defaults=Sp,Qm.use=function(...e){return Zm.use(...e),Qm.defaults=Zm.defaults,Cp(Qm.defaults),Qm},Qm.walkTokens=function(e,t){return Zm.walkTokens(e,t)},Qm.parseInline=Zm.parseInline,Qm.Parser=Jm,Qm.parser=Jm.parse,Qm.Renderer=Km,Qm.TextRenderer=qm,Qm.Lexer=Gm,Qm.lexer=Gm.lex,Qm.Tokenizer=Wm,Qm.Hooks=Ym,Qm.parse=Qm,Qm.options,Qm.setOptions,Qm.use,Qm.walkTokens,Qm.parseInline,Jm.parse,Gm.lex;var $m={alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ϵ`,varepsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,vartheta:`ϑ`,iota:`ι`,kappa:`κ`,varkappa:`ϰ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,pi:`π`,varpi:`ϖ`,rho:`ρ`,varrho:`ϱ`,sigma:`σ`,varsigma:`ς`,tau:`τ`,upsilon:`υ`,phi:`ϕ`,varphi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,Gamma:`Γ`,Delta:`Δ`,Theta:`Θ`,Lambda:`Λ`,Xi:`Ξ`,Pi:`Π`,Sigma:`Σ`,Upsilon:`Υ`,Phi:`Φ`,Psi:`Ψ`,Omega:`Ω`,pm:`±`,mp:`∓`,times:`×`,div:`÷`,cdot:`·`,ast:`∗`,star:`⋆`,circ:`∘`,bullet:`•`,oplus:`⊕`,ominus:`⊖`,otimes:`⊗`,oslash:`⊘`,odot:`⊙`,bigcirc:`○`,dagger:`†`,ddagger:`‡`,amalg:`⨿`,uplus:`⊎`,sqcap:`⊓`,sqcup:`⊔`,bowtie:`⋈`,Join:`⋈`,ltimes:`⋉`,rtimes:`⋊`,leftouterjoin:`⟕`,rightouterjoin:`⟖`,fullouterjoin:`⟗`,triangleleft:`◁`,triangleright:`▷`,wr:`≀`,cap:`∩`,cup:`∪`,bigcap:`⋂`,bigcup:`⋃`,bigwedge:`⋀`,bigvee:`⋁`,bigsqcup:`⨆`,biguplus:`⨄`,bigoplus:`⨁`,bigotimes:`⨂`,bigodot:`⨀`,setminus:`∖`,in:`∈`,notin:`∉`,ni:`∋`,subset:`⊂`,supset:`⊃`,subseteq:`⊆`,supseteq:`⊇`,sqsubset:`⊏`,sqsupset:`⊐`,sqsubseteq:`⊑`,sqsupseteq:`⊒`,prec:`≺`,preceq:`≼`,succ:`≻`,succeq:`≽`,ll:`≪`,gg:`≫`,le:`≤`,leq:`≤`,leqslant:`≤`,ge:`≥`,geq:`≥`,geqslant:`≥`,ne:`≠`,neq:`≠`,equiv:`≡`,approx:`≈`,sim:`∼`,simeq:`≃`,cong:`≅`,asymp:`≍`,doteq:`≐`,propto:`∝`,parallel:`∥`,perp:`⊥`,mid:`∣`,vdash:`⊢`,dashv:`⊣`,models:`⊨`,Vdash:`⊩`,Vvdash:`⊪`,nvdash:`⊬`,nvDash:`⊭`,forall:`∀`,exists:`∃`,nexists:`∄`,neg:`¬`,land:`∧`,wedge:`∧`,lor:`∨`,vee:`∨`,to:`→`,rightarrow:`→`,longrightarrow:`→`,leftarrow:`←`,longleftarrow:`←`,gets:`←`,leftrightarrow:`↔`,longleftrightarrow:`↔`,hookleftarrow:`↩`,hookrightarrow:`↪`,twoheadleftarrow:`↞`,twoheadrightarrow:`↠`,leftharpoonup:`↼`,leftharpoondown:`↽`,rightharpoonup:`⇀`,rightharpoondown:`⇁`,rightleftharpoons:`⇌`,leftrightharpoons:`⇋`,nearrow:`↗`,searrow:`↘`,swarrow:`↙`,nwarrow:`↖`,rightsquigarrow:`⇝`,leadsto:`⇝`,Rightarrow:`⇒`,Longrightarrow:`⇒`,Leftarrow:`⇐`,Longleftarrow:`⇐`,Leftrightarrow:`⇔`,Longleftrightarrow:`⇔`,implies:`⇒`,iff:`⇔`,mapsto:`↦`,longmapsto:`↦`,uparrow:`↑`,downarrow:`↓`,partial:`∂`,nabla:`∇`,int:`∫`,iint:`∬`,iiint:`∭`,oint:`∮`,sum:`∑`,prod:`∏`,coprod:`∐`,infty:`∞`,emptyset:`∅`,varnothing:`∅`,angle:`∠`,therefore:`∴`,because:`∵`,aleph:`ℵ`,beth:`ℶ`,gimel:`ℷ`,daleth:`ℸ`,top:`⊤`,bot:`⊥`,triangle:`△`,square:`□`,lozenge:`◊`,checkmark:`✓`,complement:`∁`,wp:`℘`,prime:`′`,ldots:`…`,dots:`…`,cdots:`⋯`,vdots:`⋮`,ddots:`⋱`,ell:`ℓ`,hbar:`ℏ`,Im:`ℑ`,Re:`ℜ`,langle:`⟨`,rangle:`⟩`,vert:`|`,lvert:`|`,rvert:`|`,Vert:`‖`,lVert:`‖`,rVert:`‖`,lbrace:`{`,rbrace:`}`,backslash:`\\`,lfloor:`⌊`,rfloor:`⌋`,lceil:`⌈`,rceil:`⌉`,colon:`:`},eh=new Set(`arccos.arcsin.arctan.arg.cos.cosh.cot.coth.csc.deg.det.dim.exp.gcd.hom.inf.ker.lg.lim.liminf.limsup.ln.log.max.min.Pr.sec.sin.sinh.sup.tan.tanh`.split(`.`)),th=new Set([`argmax`,`argmin`,`inf`,`injlim`,`lim`,`liminf`,`limsup`,`max`,`min`,`projlim`,`sup`]),nh=new Set([`bigcap`,`bigcup`,`bigodot`,`bigoplus`,`bigotimes`,`bigsqcup`,`biguplus`,`bigvee`,`bigwedge`,`coprod`,`int`,`iint`,`iiint`,`oint`,`prod`,`sum`]),rh=new Set(`Leftarrow.Leftrightarrow.Longleftarrow.Longleftrightarrow.Longrightarrow.Rightarrow.Join.Vdash.Vvdash.approx.asymp.bowtie.cong.dashv.fullouterjoin.doteq.downarrow.equiv.ge.geq.geqslant.gets.gg.hookleftarrow.hookrightarrow.iff.implies.in.leadsto.le.leftarrow.leftharpoondown.leftharpoonup.leftrightarrow.leftrightharpoons.leftouterjoin.leq.leqslant.ll.longleftarrow.longleftrightarrow.longmapsto.longrightarrow.ltimes.mapsto.mid.models.ne.nearrow.neq.ni.notin.nvdash.nvDash.nwarrow.parallel.perp.prec.preceq.propto.rightharpoondown.rightharpoonup.rightleftharpoons.rightouterjoin.rightarrow.rightsquigarrow.rtimes.searrow.sim.simeq.sqsubset.sqsubseteq.sqsupset.sqsupseteq.subset.subseteq.succ.succeq.supset.supseteq.swarrow.to.triangleleft.triangleright.twoheadleftarrow.twoheadrightarrow.uparrow.vdash`.split(`.`)),ih={"<":`≮`,">":`≯`,"=":`≠`,"∈":`∉`,"∋":`∌`,"∣":`∤`,"∥":`∦`,"∼":`≁`,"≃":`≄`,"≅":`≇`,"≈":`≉`,"≡":`≢`,"≤":`≰`,"≥":`≱`,"≺":`⊀`,"≻":`⊁`,"⊂":`⊄`,"⊃":`⊅`,"⊆":`⊈`,"⊇":`⊉`,"⊢":`⊬`,"⊨":`⊭`,"↔":`↮`,"←":`↚`,"→":`↛`,"⇒":`⇏`,"⇐":`⇍`,"⇔":`⇎`,"≼":`⋠`,"≽":`⋡`},ah={C:`ℂ`,H:`ℍ`,N:`ℕ`,P:`ℙ`,Q:`ℚ`,R:`ℝ`,Z:`ℤ`},oh={0:`⁰`,1:`¹`,2:`²`,3:`³`,4:`⁴`,5:`⁵`,6:`⁶`,7:`⁷`,8:`⁸`,9:`⁹`,"+":`⁺`,"-":`⁻`,"=":`⁼`,"(":`⁽`,")":`⁾`,a:`ᵃ`,b:`ᵇ`,c:`ᶜ`,d:`ᵈ`,e:`ᵉ`,f:`ᶠ`,g:`ᵍ`,h:`ʰ`,i:`ⁱ`,j:`ʲ`,k:`ᵏ`,l:`ˡ`,m:`ᵐ`,n:`ⁿ`,o:`ᵒ`,p:`ᵖ`,r:`ʳ`,s:`ˢ`,t:`ᵗ`,u:`ᵘ`,v:`ᵛ`,w:`ʷ`,x:`ˣ`,y:`ʸ`,z:`ᶻ`},sh={0:`₀`,1:`₁`,2:`₂`,3:`₃`,4:`₄`,5:`₅`,6:`₆`,7:`₇`,8:`₈`,9:`₉`,"+":`₊`,"-":`₋`,"=":`₌`,"(":`₍`,")":`₎`,a:`ₐ`,e:`ₑ`,h:`ₕ`,i:`ᵢ`,j:`ⱼ`,k:`ₖ`,l:`ₗ`,m:`ₘ`,n:`ₙ`,o:`ₒ`,p:`ₚ`,r:`ᵣ`,s:`ₛ`,t:`ₜ`,u:`ᵤ`,v:`ᵥ`,x:`ₓ`},ch=new Set([`,`,`:`,`;`,` `,`>`,`enspace`,`enskip`,`medspace`,`quad`,`qquad`,`thickspace`,`thinspace`]),lh=new Set([`!`,`negmedspace`,`negthickspace`,`negthinspace`]),uh=`\0`,dh=new Set([`displaystyle`,`limits`,`nolimits`,`scriptstyle`,`scriptscriptstyle`,`textstyle`]),fh=new Set([`big`,`Big`,`bigg`,`Bigg`,`bigl`,`Bigl`,`biggl`,`Biggl`,`bigr`,`Bigr`,`biggr`,`Biggr`]),ph=new Set(`emph.mathcal.mathbf.mathfrak.mathit.mathrm.mathnormal.mathscr.mathsf.mathtt.mathup.mbox.overbrace.pmb.smash.substack.text.textbf.textit.textmd.textnormal.textrm.textsc.textsf.textsl.texttt.textup.underbrace.bm.boldsymbol`.split(`.`)),mh={acute:`́`,bar:`̅`,breve:`̆`,check:`̌`,ddot:`̈`,dot:`̇`,grave:`̀`,hat:`̂`,mathring:`̊`,overleftarrow:`⃖`,overleftrightarrow:`⃡`,overline:`̅`,overrightarrow:`⃗`,tilde:`̃`,underline:`̲`,vec:`⃗`,widehat:`̂`,widetilde:`̃`};function hh(e,t){let n=``;for(let r of e){let e=t[r];if(e===void 0)return;n+=e}return n}function gh(e,t){e=e.trim();let n=t===`sub`?sh:oh,r=hh(e.replace(/\s*([=+-])\s*/g,`$1`),n);if(r!==void 0)return r;let i=t===`sub`?`_`:`^`;return Array.from(e).length===1||t===`sub`&&/^[A-Za-z]+$/.test(e)?`${i}${e}`:`${i}(${e})`}function _h(e,t){e=e.trim(),t=t.trim();let n=/^[\p{L}\p{N}.]+$/u.test(e),r=/^[\p{N}.]+$/u.test(t)||Array.from(t).length===1;return`${n?e:`(${e})`}/${r?t:`(${t})`}`}function vh(e,t=`√`){return e=e.trim(),/^[\p{L}\p{N}.]+$/u.test(e)?`${t}${e}`:`${t}(${e})`}var yh=`󰀄`,bh=`󰀅`,xh=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,Sh=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function Ch(e){return e.replace(xh,` `).replaceAll(yh,``).replace(Sh,` `).replaceAll(bh,``).split(` `).map(e=>e.replace(/[ \t]+/g,` `).trim()).filter((e,t,n)=>e.length>0||t>0&&te.baseline)),n=Math.max(...e.map(e=>e.lines.length-e.baseline-1)),r=[];for(let i=0;i<=t+n;i++){let n=``;for(let r of e){let e=i-t+r.baseline;n+=e>=0&&ee+t.width,0),baseline:t}}function jh(e,t){let n=[],r=0;for(let i of e.split(` `)){let e=[],a=0,o;for(let n of i.matchAll(Eh)){let r=n.index,s=t[Number(n[1])];if(s){if(r>a){let t=i.slice(a,r),n=(o?t.trimStart():t).trimEnd(),c=o?.type===`matrix`&&/^\s/.test(t),l=s.type===`matrix`&&/\s$/.test(t),u=n?`${c?` `:``}${n}${l?` `:``}`:c||l?` `:``;e.push({lines:[u],width:X(u),baseline:0})}if(s.type===`fraction`){let n=jh(s.numerator,t),r=jh(s.denominator,t),i=Math.max(n.width,r.width,1),a=i+2;e.push({lines:[...n.lines.map(e=>kh(e,a,!0)),` ${`─`.repeat(i)} `,...r.lines.map(e=>kh(e,a,!0))],width:a,baseline:n.lines.length})}else if(s.type===`operator`){let t=Math.max(X(s.operator),s.lower===void 0?0:X(s.lower),s.upper===void 0?0:X(s.upper)),n=[];s.upper!==void 0&&n.push(`${kh(s.upper,t,!0)} `),n.push(`${kh(s.operator,t,!0)} `),s.lower!==void 0&&n.push(`${kh(s.lower,t,!0)} `),e.push({lines:n,width:t+1,baseline:s.upper===void 0?0:1})}else{let t=Math.max(0,...s.lines.map(e=>X(e)));e.push({lines:s.lines.map(e=>kh(e,t)),width:t,baseline:s.baseline})}a=r+n[0].length,o=s}}if(aX(e))),baseline:r}}var Mh=class e{source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;constructor(e,t,n){this.source=e,this.layoutNodes=t,this.display=n}render(){let e=this.parseSequence();if(this.supported&&this.position===this.source.length)return Ch(e)}parseSequence(e){let t=``;for(;this.position`){t=`${t.trimEnd()} ${n} `,this.position++;continue}if(n===`&`){this.position++;continue}if(n===`~`){this.position++,t+=` `;continue}if(n===`.`){let e=Dh.exec(t),r=e?this.layoutNodes[Number(e[1])]:void 0;if(r?.type===`matrix`){let e=r.lines.length-1;r.lines[e]=`${r.lines[e]??``}${n}`,this.position++;continue}}t+=n,this.position++}return e&&(this.supported=!1),t}parseWhitespace(){for(;this.position=this.source.length)return this.supported=!1,``;let e=``,t=this.source[this.position]??``;if(t===` `||t===`\r`)return this.position++,t===`\r`&&this.source[this.position]===` `&&this.position++,` `;if(/[A-Za-z]/.test(t)){let t=this.position;for(;this.positionah[e]??e).join(``)}if(e===`operatorname`){let e=this.source[this.position]===`*`;e&&this.position++;let t=Ch(this.parseRequiredArgument()).trim();return this.parseOperator(t,`bracket`,e,!0)}if(e===`mod`||e===`bmod`)return` mod `;if(e===`pmod`||e===`pod`){let t=this.parseRequiredArgument().trim();return e===`pmod`?` (mod ${t})`:` (${t})`}if(e===`overset`||e===`stackrel`){let e=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${gh(e,`sup`)}`}if(e===`underset`){let e=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${gh(e,`sub`)}`}if(ph.has(e)){let t=this.parseRequiredArgument();return e.startsWith(`text`)||e===`mbox`?t:t.trim()}return e===`begin`?this.parseEnvironment():e===`end`?(this.supported=!1,``):(this.supported=!1,`\\${e}`)}parseOperator(e,t,n,r=!1){let i=n,a=this.position;for(;a=this.source.length)return this.supported=!1,``;if(this.source[this.position]===`{`)return this.position++,this.parseSequence(`}`);if(this.source[this.position]===`\\`)return this.parseCommand();let e=this.source[this.position]??``;return this.position++,e}parseOptionalArgument(){for(;this.position{let n=e.split(`&`),r=t?Array.from({length:Math.ceil(n.length/2)},(e,t)=>n.slice(t*2,t*2+2).join(``)).join(` `):n.join(``);return this.renderNested(r).trim()}).filter(Boolean).join(` `)}if(e===`cases`||e===`cases*`){let e=this.splitEnvironmentRows(r).map(e=>e.split(`&`).map(e=>this.renderNested(e,!1).trim())).filter(e=>e.some(Boolean));return e.map((t,n)=>{let r=(t[0]??``).replace(/,\s*$/,``),i=t[1]??``,a=n===0?`⎧`:n===e.length-1?`⎩`:`⎨`,o=/^(?:if|when|for|otherwise)\b/i.test(i)?` `:` if `;return`${a} ${r}${i?`${o}${i}`:``}`}).join(` `)}if([`array`,`matrix`,`smallmatrix`,`pmatrix`,`bmatrix`,`Bmatrix`,`vmatrix`,`Vmatrix`].includes(e)){let t=e===`array`?r.replace(/^\s*\{[^}]*\}/,``):r;return this.renderMatrix(e,t)}return this.supported=!1,r}renderMatrix(e,t){let n=this.splitEnvironmentRows(t).map(e=>e.split(`&`).map(e=>this.renderNested(e,!1).trim())).filter(e=>e.some(Boolean)),r=Math.max(0,...n.map(e=>e.length)),i=Array.from({length:r},(e,t)=>Math.max(0,...n.map(e=>X(e[t]??``)))),a=n.map(e=>Array.from({length:r},(t,n)=>{let r=e[n]??``;return`${r}${Oh.repeat(Math.max(0,(i[n]??0)-X(r)))}`}).join(` │ `)),o;if(e===`array`||e===`matrix`||e===`smallmatrix`)o=a;else{let t={pmatrix:[`⎛`,`⎞`,`⎜`,`⎟`,`⎝`,`⎠`],bmatrix:[`⎡`,`⎤`,`⎢`,`⎥`,`⎣`,`⎦`],Bmatrix:[`⎧`,`⎫`,`⎨`,`⎬`,`⎩`,`⎭`],vmatrix:[`│`,`│`,`│`,`│`,`│`,`│`],Vmatrix:[`║`,`║`,`║`,`║`,`║`,`║`]}[e];if(!t)return this.supported=!1,a.join(` `);o=a.map((e,n)=>`${n===0?t[0]:n===a.length-1?t[4]:t[2]} ${e} ${n===0?t[1]:n===a.length-1?t[5]:t[3]}`)}return o.length<=1?o[0]??``:`${wh}${this.layoutNodes.push({type:`matrix`,lines:o,baseline:0})-1}${Th}`}renderNested(t,n=!0){let r=new e(t,this.layoutNodes,this.display&&n).render();return r===void 0?(this.supported=!1,t):r}};function Nh(e,t={}){let n=[],r=new Mh(e,n,t.display===!0).render();if(r===void 0)return;if(n.length===0)return r.replaceAll(Oh,` `);let i=jh(r,n).lines,a=Math.min(...i.filter(e=>e.trim()).map(e=>e.length-e.trimStart().length));return i.map(e=>e.slice(a).trimEnd()).join(` `).trimEnd().replaceAll(Oh,` `)}var Ph=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,Fh=class extends Wm{del(e){let t=Ph.exec(e);if(!t)return;let n=t[2];return{type:`del`,raw:t[0],text:n,tokens:this.lexer.inlineTokens(n)}}};function Ih(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;r--)n++;return n%2==1}function Lh(e,t,n){let r=e.indexOf(t,n);for(;r>=0&&Ih(e,r);)r=e.indexOf(t,r+t.length);return r}function Rh(e){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(e)}function zh(e){let t=``,n=``;if(e.startsWith(`$$`))t=`$$`,n=`$$`;else if(e.startsWith(`\\(`))t=`\\(`,n=`\\)`;else if(e.startsWith(`\\[`))t=`\\[`,n=`\\]`;else if(e.startsWith(`$`)&&!/^\$\s/.test(e))t=`$`,n=`$`;else return;let r=Lh(e,n,t.length);if(r>=0&&t===`$`&&(/\s$/.test(e.slice(t.length,r))||/^\d/.test(e.slice(r+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(e.slice(t.length,r))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(e.slice(r+1))||e.slice(t.length,r).includes("`")))return;if(r<0){let n=e.slice(t.length);return t.startsWith(`\\`)||Rh(n)?{type:`latex`,raw:e,text:n,pending:!0}:void 0}let i=e.slice(t.length,r);if(i&&!i.includes(` `))return{type:`latex`,raw:e.slice(0,r+n.length),text:i}}function Bh(e){let t=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(e);if(t?.[1])return{type:`latexBlock`,raw:t[0],text:t[1].trim()};let n=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(e);if(n?.[1])return{type:`latexBlock`,raw:n[0],text:n[1].trim()};let r=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(r)return{type:`latexBlock`,raw:r[0],text:r[1],pending:!0};let i=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(i?.[1]&&Rh(i[1]))return{type:`latexBlock`,raw:i[0],text:i[1],pending:!0}}var Vh=[{name:`latexBlock`,level:`block`,start(e){let t=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(e);return t?t.index+ +!!t[0].startsWith(` `):void 0},tokenizer:Bh},{name:`latex`,level:`inline`,start(e){let t=[e.indexOf(`$`),e.indexOf(`\\(`),e.indexOf(`\\[`)].filter(e=>e>=0);return t.length>0?Math.min(...t):void 0},tokenizer:zh}];function Hh(e){let t=e[e.length-1];if(t?.type===`list`){Hh(t.items[t.items.length-1]?.tokens??[]);return}if(t?.type===`blockquote`){Hh(t.tokens??[]);return}if(t?.type!==`code`)return;let n=/^(`{3,}|~{3,})/.exec(t.raw)?.[1],r=t.raw.split(` `).pop();!n||!r||r.length>=n.length||r!==n[0]?.repeat(r.length)||(t.text=t.text.slice(0,-r.length).replace(/\n$/,``))}var Uh=new Xm;Uh.setOptions({tokenizer:new Fh}),Uh.use({extensions:[...Vh]});var Wh=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;constructor(e,t,n,r,i,a){this.text=e,this.paddingX=t,this.paddingY=n,this.theme=r,this.defaultTextStyle=i,this.options=a?{...a}:{}}setText(e){this.text=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2),n=this.options.transform?.(this.text,t)??this.text;if(!n||n.trim()===``){let t=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=t,t}let r=n.replace(/\t/g,` `),i=Uh.lexer(r);Hh(i);let a=[];for(let e=0;e0?p:[``]}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return``;if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e=`\0`;this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e));let t=e.indexOf(`\0`);return this.defaultStylePrefix=t>=0?e.slice(0,t):``,this.defaultStylePrefix}getStylePrefix(e){let t=e(`\0`),n=t.indexOf(`\0`);return n>=0?t.slice(0,n):``}getDefaultInlineStyleContext(){return{applyText:e=>this.applyDefaultStyle(e),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,n,r){let i=[];switch(e.type){case`heading`:{let t=e.depth,r=`${`#`.repeat(t)} `,a;a=t===1?e=>this.theme.heading(this.theme.bold(this.theme.underline(e))):e=>this.theme.heading(this.theme.bold(e));let o={applyText:a,stylePrefix:this.getStylePrefix(a)},s=this.renderInlineTokens(e.tokens||[],o),c=t>=3?a(r)+s:s;i.push(c),n&&n!==`space`&&i.push(``);break}case`paragraph`:{let t=this.renderInlineTokens(e.tokens||[],r);i.push(t),n&&n!==`list`&&n!==`space`&&i.push(``);break}case`text`:i.push(this.renderInlineTokens([e],r));break;case`latexBlock`:{let t=e,r=!t.pending&&this.options.renderLatex!==!1?Nh(t.text,{display:!0})??t.raw.trim():t.raw.trim();for(let e of r.split(` `))i.push(this.applyDefaultStyle(e));n&&n!==`space`&&i.push(``);break}case`code`:{let t=this.theme.codeBlockIndent??` `;if(i.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||``}`)),this.theme.highlightCode){let n=this.theme.highlightCode(e.text,e.lang);for(let e of n)i.push(`${t}${e}`)}else{let n=e.text.split(` `);for(let e of n)i.push(`${t}${this.theme.codeBlock(e)}`)}i.push(this.theme.codeBlockBorder("```")),n&&n!==`space`&&i.push(``);break}case`list`:{let n=this.renderList(e,0,t,r);i.push(...n);break}case`table`:{let a=this.renderTable(e,t,n,r);i.push(...a);break}case`blockquote`:{let r=e=>this.theme.quote(this.theme.italic(e)),a=this.getStylePrefix(r),o=e=>{if(!a)return r(e);let t=e.replace(/\x1b\[0m/g,`\x1b[0m${a}`);return r(t)},s=Math.max(1,t-2),c={applyText:e=>e,stylePrefix:a},l=e.tokens||[],u=[];for(let e=0;e0&&u[u.length-1]===``;)u.pop();for(let e of u){let t=_d(o(e),s);for(let e of t)i.push(this.theme.quoteBorder(`│ `)+e)}n&&n!==`space`&&i.push(``);break}case`hr`:i.push(this.theme.hr(`─`.repeat(Math.min(t,80)))),n&&n!==`space`&&i.push(``);break;case`html`:`raw`in e&&typeof e.raw==`string`&&i.push(this.applyDefaultStyle(e.raw.trim()));break;case`space`:i.push(``);break;default:`text`in e&&typeof e.text==`string`&&i.push(e.text)}return i}renderInlineTokens(e,t){let n=``,r=t??this.getDefaultInlineStyleContext(),{applyText:i,stylePrefix:a}=r,o=e=>e.split(` `).map(e=>i(e)).join(` `);for(let t of e)switch(t.type){case`latex`:{let e=t,r=!e.pending&&this.options.renderLatex!==!1?Nh(e.text)??e.raw:e.raw;n+=o(r);break}case`escape`:n+=o(this.options.preserveBackslashEscapes?t.raw:t.text);break;case`text`:t.tokens&&t.tokens.length>0?n+=this.renderInlineTokens(t.tokens,r):n+=o(t.text);break;case`paragraph`:n+=this.renderInlineTokens(t.tokens||[],r);break;case`strong`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.bold(e)+a;break}case`em`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.italic(e)+a;break}case`codespan`:n+=this.theme.code(t.text)+a;break;case`link`:{let e=this.renderInlineTokens(t.tokens||[],r),i=this.theme.link(this.theme.underline(e));if(hu().hyperlinks)n+=wu(i,t.href)+a;else{let e=t.href.startsWith(`mailto:`)?t.href.slice(7):t.href;t.text===t.href||t.text===e?n+=i+a:n+=i+this.theme.linkUrl(` (${t.href})`)+a}break}case`br`:n+=` `;break;case`del`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.strikethrough(e)+a;break}case`html`:`raw`in t&&typeof t.raw==`string`&&(n+=o(t.raw));break;default:`text`in t&&typeof t.text==`string`&&(n+=o(t.text))}for(;a&&n.endsWith(a);)n=n.slice(0,-a.length);return n}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}getUnorderedListMarker(e){let t=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,n,r){let i=[],a=` `.repeat(t),o=typeof e.start==`number`?e.start:1;for(let s=0;se.length>0),r=0;for(let e of n)r=Math.max(r,X(e));return t===void 0?r:Math.min(r,t)}wrapCellText(e,t,n=``){let r=_d(e,Math.max(1,t));return r.map((e,t)=>`${e}${te+t,0);if(d>s){u=Array(a).fill(1);let e=s-a;if(e>0){let t=l.reduce((e,t)=>e+Math.max(0,t-1),0),n=l.map(n=>{let r=Math.max(0,n-1);return t>0?Math.floor(r/t*e):0});for(let e=0;ee+t,0);for(let e=0;r>0&&ee+t,0)}let f=c.reduce((e,t)=>e+t,0)+o,p;if(f<=t)p=c.map((e,t)=>Math.max(e,u[t]));else{let e=c.reduce((e,t,n)=>e+Math.max(0,t-u[n]),0),t=Math.max(0,s-d);p=u.map((n,r)=>{let i=c[r],a=Math.max(0,i-n),o=0;return e>0&&(o=Math.floor(a/e*t)),n+o});let n=s-p.reduce((e,t)=>e+t,0);for(;n>0;){let e=!1;for(let t=0;t0;t++)p[t]`─`.repeat(e));i.push(`┌─${m.join(`─┬─`)}─┐`);let h=e.header.map((e,t)=>{let n=this.renderInlineTokens(e.tokens||[],r);return this.wrapCellText(n,p[t],r?.stylePrefix)}),g=Math.max(...h.map(e=>e.length));for(let e=0;e{let r=t[e]||``,i=r+` `.repeat(Math.max(0,p[n]-X(r)));return this.theme.bold(i)});i.push(`│ ${t.join(` │ `)} │`)}let _=`├─${p.map(e=>`─`.repeat(e)).join(`─┼─`)}─┤`;i.push(_);for(let t=0;t{let n=this.renderInlineTokens(e.tokens||[],r);return this.wrapCellText(n,p[t],r?.stylePrefix)}),a=Math.max(...n.map(e=>e.length));for(let e=0;e{let r=t[e]||``;return r+` `.repeat(Math.max(0,p[n]-X(r)))});i.push(`│ ${t.join(` │ `)} │`)}t`─`.repeat(e));return i.push(`└─${v.join(`─┴─`)}─┘`),n&&n!==`space`&&i.push(``),i}},Gh=class{children=[];paddingX;paddingY;bgFn;cache;mouseLayout;constructor(e=1,t=1,n){this.paddingX=e,this.paddingY=t,this.bgFn=n}addChild(e){this.children.push(e),this.invalidateCache()}removeChild(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(e){this.bgFn=e}invalidateCache(){this.cache=void 0}matchCache(e,t,n){let r=this.cache;return!!r&&r.width===e&&r.bgSample===n&&r.childLines.length===t.length&&r.childLines.every((e,n)=>e===t[n])}invalidate(){this.invalidateCache();for(let e of this.children)e.invalidate?.()}handleMouse(e){let t=Math.max(1,e.width-this.paddingX*2),n=e.y-this.paddingY,r=e.x-this.paddingX;if(n<0||r<0||r>=t)return;let i=this.mouseLayout?.width===t?this.mouseLayout.children:this.children.map(e=>({component:e,height:e.render(t).length})),a=0;for(let{component:o,height:s}of i){if(n>=a&&ne.component.render(t.width)),i=df(n,r.map(e=>e.length),void 0,this.gap),a=[];for(let e=0;e0)for(let e=0;e{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r=6?`complete`:`incomplete`:ng(e):t.startsWith(`]`)?rg(e):t.startsWith(`P`)?ig(e):t.startsWith(`_`)?ag(e):t.startsWith(`O`)?t.length>=2?`complete`:`incomplete`:(t.length,`complete`)}function ng(e){if(!e.startsWith(`${Xh}[`))return`complete`;if(e.length<3)return`incomplete`;let t=e.slice(2),n=t[t.length-1],r=n.charCodeAt(0);if(r>=64&&r<=126){if(t.startsWith(`<`)){if(/^<\d+;\d+;\d+[Mm]$/.test(t))return`complete`;if(n===`M`||n===`m`){let e=t.slice(1,-1).split(`;`);if(e.length===3&&e.every(e=>/^\d+$/.test(e)))return`complete`}return`incomplete`}return`complete`}return`incomplete`}function rg(e){return!e.startsWith(`${Xh}]`)||e.endsWith(`${Xh}\\`)||e.endsWith(`\x07`)?`complete`:`incomplete`}function ig(e){return!e.startsWith(`${Xh}P`)||e.endsWith(`${Xh}\\`)?`complete`:`incomplete`}function ag(e){return!e.startsWith(`${Xh}_`)||e.endsWith(`${Xh}\\`)?`complete`:`incomplete`}function og(e){let t=e.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!t)return;let n=parseInt(t[1],10);return n>=32?n:void 0}function sg(e){let t=[],n=0;for(;nr.length)return{sequences:t,remainder:r}}else t.push(r[0]),n++}return{sequences:t,remainder:``}}var cg=class extends Yh.EventEmitter{buffer=``;timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer=``;pendingKittyPrintableCodepoint;constructor(e={}){super(),this.timeoutMs=e.timeout??Zh,this.escapeTimeoutMs=e.escapeTimeout??Qh}process(e){this.timeout&&=(clearTimeout(this.timeout),null);let t;if(Sl.Buffer.isBuffer(e)){if(e.length===1&&e[0]>127){let n=e[0]-128;t=`\x1b${String.fromCharCode(n)}`}else t=e.toString()}else t=e;if(t.length===0&&this.buffer.length===0){this.emitDataSequence(``);return}if(this.buffer+=t,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer=``;let e=this.pasteBuffer.indexOf(eg);if(e!==-1){let t=this.pasteBuffer.slice(0,e),n=this.pasteBuffer.slice(e+6);this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0,this.emit(`paste`,t),n.length>0&&this.process(n)}return}let n=this.buffer.indexOf($h);if(n!==-1){if(n>0){let e=sg(this.buffer.slice(0,n));for(let t of e.sequences)this.emitDataSequence(t)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(n+6),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer=``;let e=this.pasteBuffer.indexOf(eg);if(e!==-1){let t=this.pasteBuffer.slice(0,e),n=this.pasteBuffer.slice(e+6);this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0,this.emit(`paste`,t),n.length>0&&this.process(n)}return}let r=sg(this.buffer);this.buffer=r.remainder;for(let e of r.sequences)this.emitDataSequence(e);if(this.buffer.length>0){let e=this.buffer===Xh?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let e=this.flush();for(let t of e)this.emitDataSequence(t)},e)}}emitDataSequence(e){let t=e.length===1?e.codePointAt(0):void 0;if(t!==void 0&&t===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=og(e),this.emit(`data`,e)}flush(){if(this.timeout&&=(clearTimeout(this.timeout),null),this.buffer.length===0)return[];let e=[this.buffer];return this.buffer=``,this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&=(clearTimeout(this.timeout),null),this.buffer=``,this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}},lg=class extends vp{keybindings;workingStatusIndicator;embedWorkingStatus;actionHandlers=new Map;onEscape;onCtrlD;onPasteImage;onExtensionShortcut;constructor(e,t,n,r){super(e,t,r),this.keybindings=n,this.embedWorkingStatus=r?.embedWorkingStatus??!1}setWorkingStatusIndicator(e){this.workingStatusIndicator=e}renderTopBorder(e,t){if(!this.embedWorkingStatus||!this.workingStatusIndicator||e<=0)return super.renderTopBorder(e,t);let n=this.workingStatusIndicator.renderInBorder(Math.max(1,e-5)),r=X(n);if(r===0)return super.renderTopBorder(e,t);let i=t>0?` ↑ ${t} more `:void 0,a=i?X(i):0,o=Math.floor((e-a)/2),s=()=>i!==void 0&&a+2<=e&&o-(3+r+1)>=1;if(i&&!s()&&(n=this.workingStatusIndicator.renderSpinnerInBorder(e),r=X(n)),s()){let t=3+r+1;return this.borderColor(`── `)+n+this.borderColor(` ${`─`.repeat(o-t)}${i}${`─`.repeat(e-o-a)}`)}if(e>=r+5)return this.borderColor(`── `)+n+this.borderColor(` ${`─`.repeat(e-r-4)}`);n=this.workingStatusIndicator.renderSpinnerInBorder(e),r=X(n);let c=Math.min(3,Math.max(0,e-r));return this.borderColor(`─`.repeat(c))+n+this.borderColor(`─`.repeat(Math.max(0,e-c-r)))}onAction(e,t){this.actionHandlers.set(e,t)}handleInput(e){if(!this.onExtensionShortcut?.(e)){if(this.keybindings.matches(e,`app.clipboard.pasteImage`)){this.onPasteImage?.();return}if(this.keybindings.matches(e,`app.interrupt`)){if(!this.isShowingAutocomplete()){let e=this.onEscape??this.actionHandlers.get(`app.interrupt`);if(e){e();return}}super.handleInput(e);return}if(this.keybindings.matches(e,`app.exit`)&&this.getText().length===0){let e=this.onCtrlD??this.actionHandlers.get(`app.exit`);e&&e();return}if(this.keybindings.matches(e,`tui.editor.historyPrevious`)||this.keybindings.matches(e,`tui.editor.historyNext`)){super.handleInput(e);return}for(let[t,n]of this.actionHandlers)if(t!==`app.interrupt`&&t!==`app.exit`&&this.keybindings.matches(e,t)){n();return}super.handleInput(e)}}},ug={$schema:`https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json`,name:`dark`,vars:{cyan:`#00d7ff`,blue:`#5f87ff`,green:`#b5bd68`,red:`#cc6666`,yellow:`#ffff00`,text:`#d4d4d4`,gray:`#808080`,dimGray:`#666666`,darkGray:`#505050`,accent:`#8abeb7`,selectedBg:`#3a3a4a`,userMsgBg:`#343541`,toolPendingBg:`#282832`,toolSuccessBg:`#283228`,toolErrorBg:`#3c2828`,customMsgBg:`#2d2838`},colors:{accent:`accent`,border:`blue`,borderAccent:`cyan`,borderMuted:`darkGray`,success:`green`,error:`red`,warning:`yellow`,muted:`gray`,dim:`dimGray`,text:`text`,thinkingText:`gray`,selectedBg:`selectedBg`,scrollbarTrack:`darkGray`,scrollbarThumb:`text`,searchMatchBg:`selectedBg`,searchMatchText:`text`,userMessageBg:`userMsgBg`,userMessageText:`text`,customMessageBg:`customMsgBg`,customMessageText:`text`,customMessageLabel:`#9575cd`,toolPendingBg:`toolPendingBg`,toolSuccessBg:`toolSuccessBg`,toolErrorBg:`toolErrorBg`,toolTitle:`text`,toolOutput:`gray`,mdHeading:`#f0c674`,mdLink:`#81a2be`,mdLinkUrl:`dimGray`,mdCode:`accent`,mdCodeBlock:`green`,mdCodeBlockBorder:`gray`,mdQuote:`gray`,mdQuoteBorder:`gray`,mdHr:`gray`,mdListBullet:`accent`,toolDiffAdded:`green`,toolDiffRemoved:`red`,toolDiffContext:`gray`,syntaxComment:`#6A9955`,syntaxKeyword:`#569CD6`,syntaxFunction:`#DCDCAA`,syntaxVariable:`#9CDCFE`,syntaxString:`#CE9178`,syntaxNumber:`#B5CEA8`,syntaxType:`#4EC9B0`,syntaxOperator:`#D4D4D4`,syntaxPunctuation:`#D4D4D4`,thinkingOff:`darkGray`,thinkingMinimal:`#6e6e6e`,thinkingLow:`#5f87af`,thinkingMedium:`#81a2be`,thinkingHigh:`#b294bb`,thinkingXhigh:`#d183e8`,thinkingMax:`#ff5fff`,bashMode:`green`},export:{pageBg:`#18181e`,cardBg:`#1e1e24`,infoBg:`#3c3728`}},dg={muted:`#b0b0bd`,toolOutput:`#b0b0bd`,thinkingText:`#b0b0bd`,dim:`#aaaab7`,mdLinkUrl:`#aaaab7`,mdCodeBlockBorder:`#aaaab7`,mdQuote:`#b0b0bd`};function fg(e,t,n=!1){let r=(dg[e]??ug.vars[ug.colors[e]]??ug.colors[e]??ug.vars.text).slice(1).match(/../g).map(e=>parseInt(e,16)).join(`;`),i=`\x1b[${n?48:38};2;${r}m`,a=`\x1b[${n?49:39}m`;return i+String(t).replaceAll(a,i)+a}var pg={background:ug.export.pageBg,foreground:ug.vars.text,cursor:ug.vars.accent,cursorAccent:ug.export.pageBg,selectionBackground:ug.vars.selectedBg,selectionForeground:ug.vars.text,black:`#18181e`,brightBlack:`#9696a4`,white:`#d4d4d4`,brightWhite:`#f2f2f4`},Q={fg:(e,t)=>fg(e,t),bg:(e,t)=>fg(e,t,!0),bold:e=>`\x1b[1m${e}\x1b[22m`,italic:e=>`\x1b[3m${e}\x1b[23m`,underline:e=>`\x1b[4m${e}\x1b[24m`};function mg(){return{...Object.fromEntries(Object.entries({heading:`mdHeading`,link:`mdLink`,linkUrl:`mdLinkUrl`,code:`mdCode`,codeBlock:`mdCodeBlock`,codeBlockBorder:`mdCodeBlockBorder`,quote:`mdQuote`,quoteBorder:`mdQuoteBorder`,hr:`mdHr`,listBullet:`mdListBullet`}).map(([e,t])=>[e,e=>Q.fg(t,e)])),bold:Q.bold,italic:Q.italic,underline:Q.underline,strikethrough:e=>`\x1b[9m${e}\x1b[29m`,highlightCode:e=>e.split(` `).map(e=>Q.fg(`mdCodeBlock`,e))}}function hg(){return{borderColor:e=>Q.fg(`borderMuted`,e),selectList:{selectedPrefix:e=>Q.fg(`accent`,e),selectedText:e=>Q.fg(`accent`,e),description:e=>Q.fg(`muted`,e),scrollInfo:e=>Q.fg(`muted`,e),noMatch:e=>Q.fg(`muted`,e)}}}function gg(e,t,n){return(r,i)=>_g(r,{messageType:e,isStreaming:t,availableWidth:i},n)}function _g(e,t,n){let r=e;for(let e of n)try{let n=e(r,t);typeof n==`string`&&(r=n)}catch{}return r}var vg=`\x1B]133;A\x07`,yg=class extends Nd{text;markdownTheme;outputPad;markdownTransformers;constructor(e,t=mg(),n=1,r=[]){super(),this.text=e,this.markdownTheme=t,this.outputPad=n,this.markdownTransformers=r,this.rebuild()}setOutputPad(e){this.outputPad=e,this.rebuild()}rebuild(){this.clear();let e=new Gh(this.outputPad,1,e=>Q.bg(`userMessageBg`,e));e.addChild(new Wh(this.text,0,0,this.markdownTheme,{color:e=>Q.fg(`userMessageText`,e)},{preserveOrderedListMarkers:!0,preserveBackslashEscapes:!0,transform:gg(`user`,!1,this.markdownTransformers)})),this.addChild(e)}render(e){let t=super.render(e);return t.length===0?t:(t[0]=vg+t[0],t[t.length-1]=`\x1B]133;B\x07\x1B]133;C\x07`+t[t.length-1],t)}},bg=`\x1B]133;A\x07`,xg=class extends Nd{contentContainer;hideThinkingBlock;markdownTheme;hiddenThinkingLabel;outputPad;markdownTransformers;lastMessage;hasToolCalls=!1;isStreaming=!1;thinkingVisibilityOverrides=new Map;constructor(e,t=!1,n=mg(),r=`Thinking...`,i=1,a=[]){super(),this.hideThinkingBlock=t,this.markdownTheme=n,this.hiddenThinkingLabel=r,this.outputPad=i,this.markdownTransformers=a,this.contentContainer=new Nd,this.addChild(this.contentContainer),e&&this.updateContent(e)}invalidate(){super.invalidate(),this.lastMessage&&this.updateContent(this.lastMessage)}setHideThinkingBlock(e){this.hideThinkingBlock=e,this.thinkingVisibilityOverrides.clear(),this.lastMessage&&this.updateContent(this.lastMessage)}setHiddenThinkingLabel(e){this.hiddenThinkingLabel=e,this.lastMessage&&this.updateContent(this.lastMessage)}setOutputPad(e){this.outputPad=e,this.lastMessage&&this.updateContent(this.lastMessage)}render(e){let t=super.render(e);return this.hasToolCalls||t.length===0?t:(t[0]=bg+t[0],t[t.length-1]=`\x1B]133;B\x07\x1B]133;C\x07`+t[t.length-1],t)}updateContent(e,t=this.isStreaming){this.lastMessage=e,this.isStreaming=t,this.contentContainer.clear(),e.content.some(e=>e.type===`text`&&e.text.trim()||e.type===`thinking`&&e.thinking.trim())&&this.contentContainer.addChild(new Kh(1));let n=0;for(let t=0;te.type===`text`&&e.text.trim()||e.type===`thinking`&&e.thinking.trim()),a=n++,o=this.thinkingVisibilityOverrides.get(a)??this.hideThinkingBlock,s=o?new yp(Q.italic(Q.fg(`thinkingText`,this.hiddenThinkingLabel)),this.outputPad,0):new Wh(r.join(` `),this.outputPad,0,this.markdownTheme,{color:e=>Q.fg(`thinkingText`,e),italic:!0},{transform:gg(`assistant-thinking`,this.isStreaming,this.markdownTransformers)});this.contentContainer.addChild(new qh(s,e=>{if(e.type===`click`&&e.button===`left`)return this.thinkingVisibilityOverrides.set(a,!o),this.lastMessage&&this.updateContent(this.lastMessage),{handled:!0}})),i&&this.contentContainer.addChild(new Kh(1))}}let r=e.content.some(e=>e.type===`toolCall`);if(this.hasToolCalls=r,e.stopReason===`length`)this.contentContainer.addChild(new Kh(1)),this.contentContainer.addChild(new yp(Q.fg(`error`,`Response was truncated before completion.`),this.outputPad,0));else if(!r){if(e.stopReason===`aborted`){let t=e.errorMessage&&e.errorMessage!==`Request was aborted`?e.errorMessage:`Operation aborted`;this.contentContainer.addChild(new Kh(1)),this.contentContainer.addChild(new yp(Q.fg(`error`,t),this.outputPad,0))}else if(e.stopReason===`error`){let t=e.errorMessage||`Unknown error`;this.contentContainer.addChild(new Kh(1)),this.contentContainer.addChild(new yp(Q.fg(`error`,`Error: ${t}`),this.outputPad,0))}}}},Sg=class{constructor(e){this.xterm=e,this.subscriptions=[]}start(e,t){this.input=new cg,this.input.on(`data`,e),this.input.on(`paste`,t=>e(`\x1b[200~${t}\x1b[201~`)),this.subscriptions.push(this.xterm.onData(e=>this.input.process(e)),this.xterm.onResize(t)),this.write(`\x1B[?2004h`)}stop(){this.subscriptions.forEach(e=>e.dispose()),this.subscriptions=[],this.input?.destroy(),this.write(`\x1B[?2004l`)}async drainInput(){}write(e){this.xterm.write(e)}get columns(){return this.xterm.cols}get rows(){return this.xterm.rows}get kittyProtocolActive(){return!1}moveBy(e){e&&this.write(`\x1b[${Math.abs(e)}${e>0?`B`:`A`}`)}hideCursor(){this.write(`\x1B[?25l`)}showCursor(){this.write(`\x1B[?25h`)}clearLine(){this.write(`\x1B[K`)}clearFromCursor(){this.write(`\x1B[J`)}clearScreen(){this.write(`\x1B[2J\x1B[H`)}setTitle(e){this.xterm.element?.setAttribute(`aria-label`,e)}setProgress(e){this.xterm.element?.setAttribute(`aria-busy`,String(e))}inputData(e){this.input?.process(e)}},Cg=o((e=>{function t(e,t,n){if(n===void 0&&(n=Array.prototype),e&&typeof n.find==`function`)return n.find.call(e,t);for(var i=0;i-1}var _=n({HTML:`http://www.w3.org/1999/xhtml`,SVG:`http://www.w3.org/2000/svg`,XML:`http://www.w3.org/XML/1998/namespace`,XMLNS:`http://www.w3.org/2000/xmlns/`});e.assign=i,e.find=t,e.freeze=n,e.HTML_BOOLEAN_ATTRIBUTES=a,e.HTML_RAW_TEXT_ELEMENTS=l,e.HTML_VOID_ELEMENTS=s,e.hasDefaultHTMLNamespace=p,e.hasOwn=r,e.isHTMLBooleanAttribute=o,e.isHTMLRawTextElement=u,e.isHTMLEscapableRawTextElement=d,e.isHTMLMimeType=f,e.isHTMLVoidElement=c,e.isValidMimeType=g,e.MIME_TYPE=m,e.NAMESPACE=_})),wg=o((e=>{var t=Cg();function n(e,t){e.prototype=Object.create(Error.prototype,{constructor:{value:e},name:{value:e.name,enumerable:!0,writable:t}})}var r=t.freeze({Error:`Error`,IndexSizeError:`IndexSizeError`,DomstringSizeError:`DomstringSizeError`,HierarchyRequestError:`HierarchyRequestError`,WrongDocumentError:`WrongDocumentError`,InvalidCharacterError:`InvalidCharacterError`,NoDataAllowedError:`NoDataAllowedError`,NoModificationAllowedError:`NoModificationAllowedError`,NotFoundError:`NotFoundError`,NotSupportedError:`NotSupportedError`,InUseAttributeError:`InUseAttributeError`,InvalidStateError:`InvalidStateError`,SyntaxError:`SyntaxError`,InvalidModificationError:`InvalidModificationError`,NamespaceError:`NamespaceError`,InvalidAccessError:`InvalidAccessError`,ValidationError:`ValidationError`,TypeMismatchError:`TypeMismatchError`,SecurityError:`SecurityError`,NetworkError:`NetworkError`,AbortError:`AbortError`,URLMismatchError:`URLMismatchError`,QuotaExceededError:`QuotaExceededError`,TimeoutError:`TimeoutError`,InvalidNodeTypeError:`InvalidNodeTypeError`,DataCloneError:`DataCloneError`,EncodingError:`EncodingError`,NotReadableError:`NotReadableError`,UnknownError:`UnknownError`,ConstraintError:`ConstraintError`,DataError:`DataError`,TransactionInactiveError:`TransactionInactiveError`,ReadOnlyError:`ReadOnlyError`,VersionError:`VersionError`,OperationError:`OperationError`,NotAllowedError:`NotAllowedError`,OptOutError:`OptOutError`}),i=Object.keys(r);function a(e){return typeof e==`number`&&e>=1&&e<=25}function o(e){return typeof e==`string`&&e.substring(e.length-r.Error.length)===r.Error}function s(e,t){a(e)?(this.name=i[e],this.message=t||``):(this.message=e,this.name=o(t)?t:r.Error),Error.captureStackTrace&&Error.captureStackTrace(this,s)}n(s,!0),Object.defineProperties(s.prototype,{code:{enumerable:!0,get:function(){var e=i.indexOf(this.name);return a(e)?e:0}}});for(var c={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25},l=Object.entries(c),u=0;u{function t(e){try{typeof e!=`function`&&(e=RegExp);var t=new e(`𝌆`,`u`).exec(`𝌆`);return!!t&&t[0].length===2}catch{}return!1}var n=t();function r(e){if(e.source[0]!==`[`)throw Error(e+` can not be used with chars`);return e.source.slice(1,e.source.lastIndexOf(`]`))}function i(e,t){if(e.source[0]!==`[`)throw Error(`/`+e.source+`/ can not be used with chars_without`);if(!t||typeof t!=`string`)throw Error(JSON.stringify(t)+` is not a valid search`);if(e.source.indexOf(t)===-1)throw Error(`"`+t+`" is not is /`+e.source+`/`);if(t===`-`&&e.source.indexOf(t)!==1)throw Error(`"`+t+`" is not at the first postion of /`+e.source+`/`);return new RegExp(e.source.replace(t,``),n?`u`:``)}function a(e){var t=this;return new RegExp(Array.prototype.slice.call(arguments).map(function(e){var n=typeof e==`string`;if(n&&t===void 0&&e===`|`)throw Error("use regg instead of reg to wrap expressions with `|`!");return n?e:e.source}).join(``),n?`u`:``)}function o(e){if(arguments.length===0)throw Error(`no parameters provided`);return a.apply(o,[`(?:`].concat(Array.prototype.slice.call(arguments),[`)`]))}var s=`�`,c=/[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/;n&&(c=a(`[`,r(c),`\\u{10000}-\\u{10FFFF}`,`]`));var l=RegExp(`[^`+r(c)+`]`,n?`u`:``),u=/[\x20\x09\x0D\x0A]/,d=r(u),f=a(u,`+`),p=a(u,`*`),m=/[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;n&&(m=a(`[`,r(m),`\\u{10000}-\\u{10FFFF}`,`]`));var h=a(`[`,r(m),r(/[-.0-9\xB7]/),r(/[\u0300-\u036F\u203F-\u2040]/),`]`),g=a(m,h,`*`),_=a(`^`,g,`$`),v=a(h,`+`),y=o(a(`&`,g,`;`),`|`,o(/&#[0-9]+;|&#x[0-9a-fA-F]+;/)),b=a(`%`,g,`;`),x=o(a(`"`,o(/[^%&"]/,`|`,b,`|`,y),`*`,`"`),`|`,a(`'`,o(/[^%&']/,`|`,b,`|`,y),`*`,`'`)),S=o(`"`,o(/[^<&"]/,`|`,y),`*`,`"`,`|`,`'`,o(/[^<&']/,`|`,y),`*`,`'`),C=a(i(m,`:`),i(h,`:`),`*`),w=a(`^`,C,`$`),T=a(C,o(`:`,C),`?`),E=a(`^`,T,`$`),D=a(`(`,T,`)`),O=o(/"[^"]*"|'[^']*'/),k=a(/^<\?/,`(`,g,`)`,o(f,`(?!`,u,`)(`,c,`*?)`),`?`,/\?>/),ee=/[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/,te=o(`"`,ee,`*"`,`|`,`'`,i(ee,`'`),`*'`),ne=``,re=a(ne,o(i(c,`-`),`|`,a(`-`,i(c,`-`))),`*`,A),j=`#PCDATA`,M=o(`EMPTY`,`|`,`ANY`,`|`,o(a(/\(/,p,j,o(p,/\|/,p,T),`*`,p,/\)\*/),`|`,a(/\(/,p,j,p,/\)/)),`|`,a(/\([^>]+\)/,/[?*+]?/)),N=a(``),P=a(``),ie=`about:legacy-compat`,F=o(`"`+ie+`"`,`|`,`'`+ie+`'`),I=`SYSTEM`,L=`PUBLIC`,R=o(o(I,f,O),`|`,o(L,f,te,f,O)),ae=a(`^`,o(o(I,f,`(?`,O,`)`),`|`,o(L,f,`(?`,te,`)`,f,`(?`,O,`)`))),oe=a(`^`,te,`$`),z=a(`^`,O,`$`),se=o(x,`|`,o(R,o(f,`NDATA`,f,g),`?`)),ce=``),`|`,a(ce,f,`%`,f,g,f,o(x,`|`,R),p,`>`)),ue=a(``),de=a(p,`=`,p),fe=/1[.]\d+/,B=a(f,`version`,de,o(`'`,fe,`'`,`|`,`"`,fe,`"`)),pe=/[A-Za-z][-A-Za-z0-9._]*/,me=a(/^<\?xml/,B,o(f,`encoding`,de,o(`"`,pe,`"`,`|`,`'`,pe,`'`)),`?`,o(f,`standalone`,de,o(`'`,o(`yes`,`|`,`no`),`'`,`|`,`"`,o(`yes`,`|`,`no`),`"`)),`?`,p,/\?>/),he=``,ve=a(//));e.chars=r,e.chars_without=i,e.detectUnicodeSupport=t,e.reg=a,e.regg=o,e.ABOUT_LEGACY_COMPAT=ie,e.ABOUT_LEGACY_COMPAT_SystemLiteral=F,e.AttlistDecl=P,e.CDATA_START=ge,e.CDATA_END=_e,e.CDSect=ve,e.Char=c,e.Comment=re,e.COMMENT_START=ne,e.COMMENT_END=A,e.DOCTYPE_DECL_START=he,e.elementdecl=N,e.EntityDecl=le,e.EntityValue=x,e.ExternalID=R,e.ExternalID_match=ae,e.Name=g,e.Name_exact=_,e.NCName_exact=w,e.NotationDecl=ue,e.Reference=y,e.PEReference=b,e.PI=k,e.PUBLIC=L,e.PubidLiteral=te,e.PubidLiteral_match=oe,e.QName=T,e.QName_exact=E,e.QName_group=D,e.S=f,e.SChar_s=d,e.S_OPT=p,e.SYSTEM=I,e.SystemLiteral=O,e.SystemLiteral_match=z,e.InvalidChar=l,e.UNICODE_REPLACEMENT_CHARACTER=s,e.UNICODE_SUPPORT=n,e.XMLDecl=me})),Eg=o((e=>{var t=Cg(),n=t.find,r=t.hasDefaultHTMLNamespace,i=t.hasOwn,a=t.isHTMLMimeType,o=t.isHTMLRawTextElement,s=t.isHTMLVoidElement,c=t.MIME_TYPE,l=t.NAMESPACE,u=Symbol(),d=wg(),f=d.DOMException,p=d.DOMExceptionName,m=Tg();function h(e){if(e!==u)throw TypeError(`Illegal constructor`)}function g(e){return e!==``}function _(e){return e?e.split(/[\t\n\f\r ]+/).filter(g):[]}function v(e,t){return i(e,t)||(e[t]=!0),e}function y(e){if(!e)return[];var t=_(e);return Object.keys(t.reduce(v,{}))}function b(e){return function(t){return e&&e.indexOf(t)!==-1}}function x(e){if(!m.QName_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`invalid character in qualified name "`+e+`"`)}function S(e,n){x(n),e||=null;var r=null,i=n;if(n.indexOf(`:`)>=0){var a=n.split(`:`);r=a[0],i=a[1]}if(r!==null&&e===null)throw new f(f.NAMESPACE_ERR,`prefix is non-null and namespace is null`);if(r===`xml`&&e!==t.NAMESPACE.XML)throw new f(f.NAMESPACE_ERR,`prefix is "xml" and namespace is not the XML namespace`);if((r===`xmlns`||n===`xmlns`)&&e!==t.NAMESPACE.XMLNS)throw new f(f.NAMESPACE_ERR,`either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace`);if(e===t.NAMESPACE.XMLNS&&r!==`xmlns`&&n!==`xmlns`)throw new f(f.NAMESPACE_ERR,`namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"`);return[e,r,i]}function C(e,t){for(var n in e)i(e,n)&&(t[n]=e[n])}function w(e,t){var n=e.prototype;if(!(n instanceof t)){function r(){}r.prototype=t.prototype,r=new r,C(n,r),e.prototype=n=r}n.constructor!=e&&(typeof e!=`function`&&console.error(`unknown Class:`+e),n.constructor=e)}var T={},E=T.ELEMENT_NODE=1,D=T.ATTRIBUTE_NODE=2,O=T.TEXT_NODE=3,k=T.CDATA_SECTION_NODE=4,ee=T.ENTITY_REFERENCE_NODE=5,te=T.ENTITY_NODE=6,ne=T.PROCESSING_INSTRUCTION_NODE=7,A=T.COMMENT_NODE=8,re=T.DOCUMENT_NODE=9,j=T.DOCUMENT_TYPE_NODE=10,M=T.DOCUMENT_FRAGMENT_NODE=11,N=T.NOTATION_NODE=12,P=t.freeze({DOCUMENT_POSITION_DISCONNECTED:1,DOCUMENT_POSITION_PRECEDING:2,DOCUMENT_POSITION_FOLLOWING:4,DOCUMENT_POSITION_CONTAINS:8,DOCUMENT_POSITION_CONTAINED_BY:16,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:32});function ie(e,t){if(t.length=0&&e=0){for(var i=t.length-1;r<=i;)t[r]=t[++r];if(t.length=i,le(t,n),e){var a=e.ownerDocument;a&&ve(a,e,n),n.ownerElement=null}}}ae.prototype={length:0,item:I.prototype.item,getNamedItem:function(e){this._ownerElement&&this._ownerElement._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());for(var t=0;t0;){var n=t.pop(),r=n.node,i=n.other;if(r.nodeType!==i.nodeType)return!1;switch(r.nodeType){case r.DOCUMENT_TYPE_NODE:if(r.name!==i.name||r.publicId!==i.publicId||r.systemId!==i.systemId)return!1;break;case r.ELEMENT_NODE:if(r.namespaceURI!==i.namespaceURI||r.prefix!==i.prefix||r.localName!==i.localName||r.attributes.length!==i.attributes.length)return!1;for(var a=0;a=0;a--)t.push({node:r.childNodes[a],other:i.childNodes[a]})}return!0},isSameNode:function(e){return this===e},insertBefore:function(e,t){return je(this,e,t)},replaceChild:function(e,t){je(this,e,t,Ae),t&&this.removeChild(t)},removeChild:function(e){return be(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return Ye(this.ownerDocument||this,this,e)},normalize:function(){he(this,null,{enter:function(e){for(var t=e.firstChild;t;){var n=t.nextSibling;if(n!==null&&n.nodeType===O&&t.nodeType===O){for(var r=[],i=n;i!==null&&i.nodeType===O;)r.push(i.data),i=i.nextSibling;for(var a=t.nextSibling;a!==i;){var o=a.nextSibling;a.parentNode=null,a.previousSibling=null,a.nextSibling=null,a=o}t.nextSibling=i,i===null?e.lastChild=t:i.previousSibling=t,t.appendData(r.join(``)),ye(e.ownerDocument,e),t=i}else t=n}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},lookupPrefix:function(e){for(var t=this;t;){var n=t._nsMap;if(n){for(var r in n)if(i(n,r)&&n[r]===e)return r}t=t.nodeType==D?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&i(n,e))return n[e];t=t.nodeType==D?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){return this.lookupPrefix(e)==null},compareDocumentPosition:function(e){if(this===e)return 0;var t=e,n=this,r=null,i=null;if(t instanceof Ne&&(r=t,t=r.ownerElement),n instanceof Ne&&(i=n,n=i.ownerElement,r&&t&&n===t))for(var a=0,o;o=n.attributes[a];a++){if(o===r)return P.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+P.DOCUMENT_POSITION_PRECEDING;if(o===i)return P.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+P.DOCUMENT_POSITION_FOLLOWING}if(!t||!n||n.ownerDocument!==t.ownerDocument)return P.DOCUMENT_POSITION_DISCONNECTED+P.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+(F(n.ownerDocument)>F(t.ownerDocument)?P.DOCUMENT_POSITION_FOLLOWING:P.DOCUMENT_POSITION_PRECEDING);if(i&&t===n)return P.DOCUMENT_POSITION_CONTAINS+P.DOCUMENT_POSITION_PRECEDING;if(r&&t===n)return P.DOCUMENT_POSITION_CONTAINED_BY+P.DOCUMENT_POSITION_FOLLOWING;for(var s=[],c=t.parentNode;c;){if(!i&&c===n)return P.DOCUMENT_POSITION_CONTAINED_BY+P.DOCUMENT_POSITION_FOLLOWING;s.push(c),c=c.parentNode}s.reverse();for(var l=[],u=n.parentNode;u;){if(!r&&u===t)return P.DOCUMENT_POSITION_CONTAINS+P.DOCUMENT_POSITION_PRECEDING;l.push(u),u=u.parentNode}l.reverse();var d=ie(s,l);for(var f in d.childNodes){var p=d.childNodes[f];if(p===n)return P.DOCUMENT_POSITION_FOLLOWING;if(p===t)return P.DOCUMENT_POSITION_PRECEDING;if(l.indexOf(p)>=0)return P.DOCUMENT_POSITION_FOLLOWING;if(s.indexOf(p)>=0)return P.DOCUMENT_POSITION_PRECEDING}return 0}};function pe(e){return e==`<`&&`<`||e==`>`&&`>`||e==`&`&&`&`||e==`"`&&`"`||`&#`+e.charCodeAt()+`;`}C(T,B),C(T,B.prototype),C(P,B),C(P,B.prototype);function me(e,t){he(e,null,{enter:function(e){return!t(e)||he.STOP}})}function he(e,t,n){for(var r=[{node:e,context:t,phase:he.ENTER}];r.length>0;){var i=r.pop();if(i.phase===he.ENTER){var a=n.enter(i.node,i.context);if(a===he.STOP)return he.STOP;if(r.push({node:i.node,context:a,phase:he.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)r.push({node:o,context:a,phase:he.ENTER}),o=o.previousSibling}else n.exit&&n.exit(i.node,i.context)}}he.STOP=Symbol(`walkDOM.STOP`),he.ENTER=0,he.EXIT=1;function ge(e,t){h(e);var n=t||{};this.ownerDocument=this,this.contentType=n.contentType||c.XML_APPLICATION,this.type=a(this.contentType)?`html`:`xml`}function _e(e,t,n){e&&e._inc++,n.namespaceURI===l.XMLNS&&(t._nsMap[n.prefix?n.localName:``]=n.value)}function ve(e,t,n,r){e&&e._inc++,n.namespaceURI===l.XMLNS&&delete t._nsMap[n.prefix?n.localName:``]}function ye(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n&&!n.nextSibling)r[r.length++]=n;else{for(var i=t.firstChild,a=0;i;)r[a++]=i,i=i.nextSibling;r.length=a,delete r[r.length]}}}function be(e,t){if(e!==t.parentNode)throw new f(f.NOT_FOUND_ERR,`child's parent is not parent`);var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,ye(e.ownerDocument,e),t.parentNode=null,t.previousSibling=null,t.nextSibling=null,t}function xe(e){return e&&(e.nodeType===B.DOCUMENT_NODE||e.nodeType===B.DOCUMENT_FRAGMENT_NODE||e.nodeType===B.ELEMENT_NODE)}function Se(e){return e&&(e.nodeType===B.CDATA_SECTION_NODE||e.nodeType===B.COMMENT_NODE||e.nodeType===B.DOCUMENT_FRAGMENT_NODE||e.nodeType===B.DOCUMENT_TYPE_NODE||e.nodeType===B.ELEMENT_NODE||e.nodeType===B.PROCESSING_INSTRUCTION_NODE||e.nodeType===B.TEXT_NODE)}function Ce(e){return e&&e.nodeType===B.DOCUMENT_TYPE_NODE}function we(e){return e&&e.nodeType===B.ELEMENT_NODE}function Te(e){return e&&e.nodeType===B.TEXT_NODE}function Ee(e,t){var r=e.childNodes||[];if(n(r,we)||Ce(t))return!1;var i=n(r,Ce);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function De(e,t){var r=e.childNodes||[];function i(e){return we(e)&&e!==t}if(n(r,i))return!1;var a=n(r,Ce);return!(t&&a&&r.indexOf(a)>r.indexOf(t))}function Oe(e,t,n){if(!xe(e))throw new f(f.HIERARCHY_REQUEST_ERR,`Unexpected parent node type `+e.nodeType);if(n&&n.parentNode!==e)throw new f(f.NOT_FOUND_ERR,`child not in parent`);if(!Se(t)||Ce(t)&&e.nodeType!==B.DOCUMENT_NODE)throw new f(f.HIERARCHY_REQUEST_ERR,`Unexpected node type `+t.nodeType+` for parent node type `+e.nodeType)}function ke(e,t,r){var i=e.childNodes||[],a=t.childNodes||[];if(t.nodeType===B.DOCUMENT_FRAGMENT_NODE){var o=a.filter(we);if(o.length>1||n(a,Te))throw new f(f.HIERARCHY_REQUEST_ERR,`More than one element or text in fragment`);if(o.length===1&&!Ee(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Element in fragment can not be inserted before doctype`)}if(we(t)&&!Ee(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one element can be added and only after doctype`);if(Ce(t)){if(n(i,Ce))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one doctype is allowed`);var s=n(i,we);if(r&&i.indexOf(s)1||n(a,Te))throw new f(f.HIERARCHY_REQUEST_ERR,`More than one element or text in fragment`);if(o.length===1&&!De(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Element in fragment can not be inserted before doctype`)}if(we(t)&&!De(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one element can be added and only after doctype`);if(Ce(t)){function e(e){return Ce(e)&&e!==r}if(n(i,e))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one doctype is allowed`);var s=n(i,we);if(r&&i.indexOf(s)`)!==-1)throw new f(f.INVALID_CHARACTER_ERR,`data contains "]]>"`);var t=new Le(u);return t.ownerDocument=this,t.childNodes=new I,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new He(u);return n.ownerDocument=this,n.childNodes=new I,n.nodeName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){if(!m.QName_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`invalid character in name "`+e+`"`);return this.type===`html`&&(e=e.toLowerCase()),this._createAttribute(e)},_createAttribute:function(e){var t=new Ne(u);return t.ownerDocument=this,t.childNodes=new I,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!m.Name_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`not a valid xml name "`+e+`"`);if(this.type===`html`)throw new f(`document is an html document`,p.NotSupportedError);var t=new Ve(u);return t.ownerDocument=this,t.childNodes=new I,t.nodeName=e,t},createElementNS:function(e,t){var n=S(e,t),r=new Me(u),i=r.attributes=new ae;return r.childNodes=new I,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],i._ownerElement=r,r},createAttributeNS:function(e,t){var n=S(e,t),r=new Ne(u);return r.ownerDocument=this,r.childNodes=new I,r.nodeName=t,r.name=t,r.specified=!0,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],r}},w(ge,B);function Me(e){h(e),this._nsMap=Object.create(null)}Me.prototype={nodeType:E,attributes:null,getQualifiedName:function(){return this.prefix?this.prefix+`:`+this.localName:this.localName},_isInHTMLDocumentAndNamespace:function(){return this.ownerDocument.type===`html`&&this.namespaceURI===l.HTML},hasAttributes:function(){return!!(this.attributes&&this.attributes.length)},hasAttribute:function(e){return!!this.getAttributeNode(e)},getAttribute:function(e){var t=this.getAttributeNode(e);return t?t.value:null},getAttributeNode:function(e){return this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase()),this.attributes.getNamedItem(e)},setAttribute:function(e,t){this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());var n=this.getAttributeNode(e);n?n.value=n.nodeValue=``+t:(n=this.ownerDocument._createAttribute(e),n.value=n.nodeValue=``+t,this.setAttributeNode(n))},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n?n.value:null},setAttributeNS:function(e,t,n){var r=S(e,t)[2],i=this.getAttributeNodeNS(e,r);i?i.value=i.nodeValue=``+n:(i=this.ownerDocument.createAttributeNS(e,t),i.value=i.nodeValue=``+n,this.setAttributeNode(i))},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByClassName:function(e){var t=y(e);return new L(this,function(n){var r=[];return t.length>0&&me(n,function(i){if(i!==n&&i.nodeType===E){var a=i.getAttribute(`class`);if(a){var o=e===a;if(!o){var s=y(a);o=t.every(b(s))}o&&r.push(i)}}}),r})},getElementsByTagName:function(e){var t=(this.nodeType===re?this:this.ownerDocument).type===`html`,n=e.toLowerCase();return new L(this,function(r){var i=[];return me(r,function(a){a!==r&&a.nodeType===E&&(e===`*`||a.getQualifiedName()===(t&&a.namespaceURI===l.HTML?n:e))&&i.push(a)}),i})},getElementsByTagNameNS:function(e,t){return new L(this,function(n){var r=[];return me(n,function(i){i!==n&&i.nodeType===E&&(e===`*`||i.namespaceURI===e)&&(t===`*`||i.localName==t)&&r.push(i)}),r})}},ge.prototype.getElementsByClassName=Me.prototype.getElementsByClassName,ge.prototype.getElementsByTagName=Me.prototype.getElementsByTagName,ge.prototype.getElementsByTagNameNS=Me.prototype.getElementsByTagNameNS,w(Me,B);function Ne(e){h(e),this.namespaceURI=null,this.prefix=null,this.ownerElement=null}Ne.prototype.nodeType=D,w(Ne,B);function Pe(e){h(e)}Pe.prototype={data:``,substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},deleteData:function(e,t){this.replaceData(e,t,``)},replaceData:function(e,t,n){var r=this.data.substring(0,e),i=this.data.substring(e+t);n=r+n+i,this.nodeValue=this.data=n,this.length=n.length}},w(Pe,B);function Fe(e){h(e)}Fe.prototype={nodeName:`#text`,nodeType:O,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}},w(Fe,Pe);function Ie(e){h(e)}Ie.prototype={nodeName:`#comment`,nodeType:A},w(Ie,Pe);function Le(e){h(e)}Le.prototype={nodeName:`#cdata-section`,nodeType:k},w(Le,Fe);function Re(e){h(e)}Re.prototype.nodeType=j,w(Re,B);function ze(e){h(e)}ze.prototype.nodeType=N,w(ze,B);function Be(e){h(e)}Be.prototype.nodeType=te,w(Be,B);function Ve(e){h(e)}Ve.prototype.nodeType=ee,w(Ve,B);function V(e){h(e)}V.prototype.nodeName=`#document-fragment`,V.prototype.nodeType=M,w(V,B);function He(e){h(e)}He.prototype.nodeType=ne,w(He,Pe);function Ue(){}Ue.prototype.serializeToString=function(e,t){return We.call(e,t)},B.prototype.toString=We;function We(e){var t=typeof e==`function`?{requireWellFormed:!1,splitCDATASections:!0,nodeFilter:e}:e==null?{requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null}:{requireWellFormed:!!e.requireWellFormed,splitCDATASections:e.splitCDATASections!==!1,nodeFilter:e.nodeFilter||null},n=[],r=this.nodeType===re&&this.documentElement||this,i=r.prefix,a=r.namespaceURI;if(a&&i==null){var i=r.lookupPrefix(a);if(i==null)var o=[{namespace:a,prefix:null}]}return qe(this,n,o,t),n.join(``)}function Ge(e,t,n){var r=e.prefix||``,i=e.namespaceURI;if(!i||r===`xml`&&i===l.XML||i===l.XMLNS)return!1;for(var a=n.length;a--;){var o=n[a];if(o.prefix===r)return o.namespace!==i}return!0}function Ke(e,t,n,r){if(r&&!m.QName_exact.test(t))throw new f(`The attribute name "`+t+`" is not a valid XML QName`,p.InvalidStateError);e.push(` `,t,`="`,n.replace(/[<>&"\t\n\r]/g,pe),`"`)}function qe(e,t,n,r){n||=[];var i=r.nodeFilter,a=r.requireWellFormed,c=r.splitCDATASections,u=(e.nodeType===re?e:e.ownerDocument).type===`html`;he(e,{ns:n},{enter:function(e,n){var d=n.ns;if(i){if(e=i(e),e){if(typeof e==`string`)return t.push(e),null}else return null}switch(e.nodeType){case E:var h=e.attributes,g=h.length,_=e.tagName,v=_;if(!u&&!e.prefix&&e.namespaceURI){for(var y,b=0;b=0;x--){var S=d[x];if(S.prefix===``&&S.namespace===e.namespaceURI){y=S.namespace;break}}if(y!==e.namespaceURI)for(var x=d.length-1;x>=0;x--){var S=d[x];if(S.namespace===e.namespaceURI){S.prefix&&(v=S.prefix+`:`+_);break}}}if(a&&!m.QName_exact.test(v))throw new f(`The element name "`+v+`" is not a valid XML QName`,p.InvalidStateError);t.push(`<`,v);for(var C=d.slice(),w=0;w`),null;if(t.push(`>`),u&&o(_)){for(var I=e.firstChild;I;)I.data?t.push(I.data):qe(I,t,C.slice(),r),I=I.nextSibling;return t.push(``),null}return{ns:C,tag:v};case re:case M:if(a&&e.nodeType===re&&e.documentElement==null)throw new f(`The Document has no documentElement`,p.InvalidStateError);return{ns:d};case D:return Ke(t,e.name,e.value,a),null;case O:if(a&&m.InvalidChar.test(e.data))throw new f(`The Text node data contains characters outside the XML Char production`,p.InvalidStateError);return t.push(e.data.replace(/[<&>]/g,pe)),null;case k:if(a&&e.data.indexOf(`]]>`)!==-1)throw new f(`The CDATASection data contains "]]>"`,p.InvalidStateError);return c?t.push(m.CDATA_START,e.data.replace(/]]>/g,`]]]]>`),m.CDATA_END):t.push(m.CDATA_START,e.data,m.CDATA_END),null;case A:if(a){if(m.InvalidChar.test(e.data))throw new f(`The comment node data contains characters outside the XML Char production`,p.InvalidStateError);if(e.data.indexOf(`--`)!==-1||e.data[e.data.length-1]===`-`)throw new f(`The comment node data contains "--" or ends with "-"`,p.InvalidStateError)}return t.push(m.COMMENT_START,e.data,m.COMMENT_END),null;case j:var L=e.publicId,R=e.systemId;if(a){if(!m.Name_exact.test(e.name))throw new f(`The doctype name "`+e.name+`" is not a valid XML Name`,p.InvalidStateError);if(L&&!m.PubidLiteral_match.test(L))throw new f(`DocumentType publicId is not a valid PubidLiteral`,p.InvalidStateError);if(R&&R!==`.`&&!m.SystemLiteral_match.test(R))throw new f(`DocumentType systemId is not a valid SystemLiteral`,p.InvalidStateError);if(e.internalSubset&&e.internalSubset.indexOf(`]>`)!==-1)throw new f(`DocumentType internalSubset contains "]>"`,p.InvalidStateError)}return t.push(m.DOCTYPE_DECL_START,` `,e.name),L?(t.push(` `,m.PUBLIC,` `,L),R&&R!==`.`&&t.push(` `,R)):R&&R!==`.`&&t.push(` `,m.SYSTEM,` `,R),e.internalSubset&&t.push(` [`,e.internalSubset,`]`),t.push(`>`),null;case ne:if(a){if(!m.NCName_exact.test(e.target)||e.target.toLowerCase()===`xml`)throw new f(`The processing instruction target "`+e.target+`" is not a valid XML NCName or is reserved`,p.InvalidStateError);if(m.InvalidChar.test(e.data))throw new f(`The ProcessingInstruction data contains characters outside the XML Char production`,p.InvalidStateError);if(e.data.indexOf(`?>`)!==-1)throw new f(`The ProcessingInstruction data contains "?>"`,p.InvalidStateError)}return t.push(``),null;case ee:if(a&&!m.Name_exact.test(e.nodeName))throw new f(`The entity reference name "`+e.nodeName+`" is not a valid XML Name`,p.InvalidStateError);return t.push(`&`,e.nodeName,`;`),null;default:return t.push(`??`,e.nodeName),null}},exit:function(e,n){n&&n.tag&&t.push(``)}})}function Je(e,t,n){var r;return he(t,null,{enter:function(t,i){var a=t.cloneNode(!1);return a.ownerDocument=e,a.parentNode=null,i===null?r=a:i.appendChild(a),t.nodeType===D||n?a:null}}),r}function Ye(e,t,n){var r;return he(t,null,{enter:function(t,a){var o=new t.constructor(u);for(var s in t)if(i(t,s)){var c=t[s];typeof c!=`object`&&c!=o[s]&&(o[s]=c)}t.childNodes&&(o.childNodes=new I),o.ownerDocument=e;var l=n;switch(o.nodeType){case E:var d=t.attributes,f=o.attributes=new ae,p=d.length;f._ownerElement=o;for(var m=0;m{var t=Cg().freeze;e.XML_ENTITIES=t({amp:`&`,apos:`'`,gt:`>`,lt:`<`,quot:`"`}),e.HTML_ENTITIES=t({Aacute:`Á`,aacute:`á`,Abreve:`Ă`,abreve:`ă`,ac:`∾`,acd:`∿`,acE:`∾̳`,Acirc:`Â`,acirc:`â`,acute:`´`,Acy:`А`,acy:`а`,AElig:`Æ`,aelig:`æ`,af:`⁡`,Afr:`𝔄`,afr:`𝔞`,Agrave:`À`,agrave:`à`,alefsym:`ℵ`,aleph:`ℵ`,Alpha:`Α`,alpha:`α`,Amacr:`Ā`,amacr:`ā`,amalg:`⨿`,AMP:`&`,amp:`&`,And:`⩓`,and:`∧`,andand:`⩕`,andd:`⩜`,andslope:`⩘`,andv:`⩚`,ang:`∠`,ange:`⦤`,angle:`∠`,angmsd:`∡`,angmsdaa:`⦨`,angmsdab:`⦩`,angmsdac:`⦪`,angmsdad:`⦫`,angmsdae:`⦬`,angmsdaf:`⦭`,angmsdag:`⦮`,angmsdah:`⦯`,angrt:`∟`,angrtvb:`⊾`,angrtvbd:`⦝`,angsph:`∢`,angst:`Å`,angzarr:`⍼`,Aogon:`Ą`,aogon:`ą`,Aopf:`𝔸`,aopf:`𝕒`,ap:`≈`,apacir:`⩯`,apE:`⩰`,ape:`≊`,apid:`≋`,apos:`'`,ApplyFunction:`⁡`,approx:`≈`,approxeq:`≊`,Aring:`Å`,aring:`å`,Ascr:`𝒜`,ascr:`𝒶`,Assign:`≔`,ast:`*`,asymp:`≈`,asympeq:`≍`,Atilde:`Ã`,atilde:`ã`,Auml:`Ä`,auml:`ä`,awconint:`∳`,awint:`⨑`,backcong:`≌`,backepsilon:`϶`,backprime:`‵`,backsim:`∽`,backsimeq:`⋍`,Backslash:`∖`,Barv:`⫧`,barvee:`⊽`,Barwed:`⌆`,barwed:`⌅`,barwedge:`⌅`,bbrk:`⎵`,bbrktbrk:`⎶`,bcong:`≌`,Bcy:`Б`,bcy:`б`,bdquo:`„`,becaus:`∵`,Because:`∵`,because:`∵`,bemptyv:`⦰`,bepsi:`϶`,bernou:`ℬ`,Bernoullis:`ℬ`,Beta:`Β`,beta:`β`,beth:`ℶ`,between:`≬`,Bfr:`𝔅`,bfr:`𝔟`,bigcap:`⋂`,bigcirc:`◯`,bigcup:`⋃`,bigodot:`⨀`,bigoplus:`⨁`,bigotimes:`⨂`,bigsqcup:`⨆`,bigstar:`★`,bigtriangledown:`▽`,bigtriangleup:`△`,biguplus:`⨄`,bigvee:`⋁`,bigwedge:`⋀`,bkarow:`⤍`,blacklozenge:`⧫`,blacksquare:`▪`,blacktriangle:`▴`,blacktriangledown:`▾`,blacktriangleleft:`◂`,blacktriangleright:`▸`,blank:`␣`,blk12:`▒`,blk14:`░`,blk34:`▓`,block:`█`,bne:`=⃥`,bnequiv:`≡⃥`,bNot:`⫭`,bnot:`⌐`,Bopf:`𝔹`,bopf:`𝕓`,bot:`⊥`,bottom:`⊥`,bowtie:`⋈`,boxbox:`⧉`,boxDL:`╗`,boxDl:`╖`,boxdL:`╕`,boxdl:`┐`,boxDR:`╔`,boxDr:`╓`,boxdR:`╒`,boxdr:`┌`,boxH:`═`,boxh:`─`,boxHD:`╦`,boxHd:`╤`,boxhD:`╥`,boxhd:`┬`,boxHU:`╩`,boxHu:`╧`,boxhU:`╨`,boxhu:`┴`,boxminus:`⊟`,boxplus:`⊞`,boxtimes:`⊠`,boxUL:`╝`,boxUl:`╜`,boxuL:`╛`,boxul:`┘`,boxUR:`╚`,boxUr:`╙`,boxuR:`╘`,boxur:`└`,boxV:`║`,boxv:`│`,boxVH:`╬`,boxVh:`╫`,boxvH:`╪`,boxvh:`┼`,boxVL:`╣`,boxVl:`╢`,boxvL:`╡`,boxvl:`┤`,boxVR:`╠`,boxVr:`╟`,boxvR:`╞`,boxvr:`├`,bprime:`‵`,Breve:`˘`,breve:`˘`,brvbar:`¦`,Bscr:`ℬ`,bscr:`𝒷`,bsemi:`⁏`,bsim:`∽`,bsime:`⋍`,bsol:`\\`,bsolb:`⧅`,bsolhsub:`⟈`,bull:`•`,bullet:`•`,bump:`≎`,bumpE:`⪮`,bumpe:`≏`,Bumpeq:`≎`,bumpeq:`≏`,Cacute:`Ć`,cacute:`ć`,Cap:`⋒`,cap:`∩`,capand:`⩄`,capbrcup:`⩉`,capcap:`⩋`,capcup:`⩇`,capdot:`⩀`,CapitalDifferentialD:`ⅅ`,caps:`∩︀`,caret:`⁁`,caron:`ˇ`,Cayleys:`ℭ`,ccaps:`⩍`,Ccaron:`Č`,ccaron:`č`,Ccedil:`Ç`,ccedil:`ç`,Ccirc:`Ĉ`,ccirc:`ĉ`,Cconint:`∰`,ccups:`⩌`,ccupssm:`⩐`,Cdot:`Ċ`,cdot:`ċ`,cedil:`¸`,Cedilla:`¸`,cemptyv:`⦲`,cent:`¢`,CenterDot:`·`,centerdot:`·`,Cfr:`ℭ`,cfr:`𝔠`,CHcy:`Ч`,chcy:`ч`,check:`✓`,checkmark:`✓`,Chi:`Χ`,chi:`χ`,cir:`○`,circ:`ˆ`,circeq:`≗`,circlearrowleft:`↺`,circlearrowright:`↻`,circledast:`⊛`,circledcirc:`⊚`,circleddash:`⊝`,CircleDot:`⊙`,circledR:`®`,circledS:`Ⓢ`,CircleMinus:`⊖`,CirclePlus:`⊕`,CircleTimes:`⊗`,cirE:`⧃`,cire:`≗`,cirfnint:`⨐`,cirmid:`⫯`,cirscir:`⧂`,ClockwiseContourIntegral:`∲`,CloseCurlyDoubleQuote:`”`,CloseCurlyQuote:`’`,clubs:`♣`,clubsuit:`♣`,Colon:`∷`,colon:`:`,Colone:`⩴`,colone:`≔`,coloneq:`≔`,comma:`,`,commat:`@`,comp:`∁`,compfn:`∘`,complement:`∁`,complexes:`ℂ`,cong:`≅`,congdot:`⩭`,Congruent:`≡`,Conint:`∯`,conint:`∮`,ContourIntegral:`∮`,Copf:`ℂ`,copf:`𝕔`,coprod:`∐`,Coproduct:`∐`,COPY:`©`,copy:`©`,copysr:`℗`,CounterClockwiseContourIntegral:`∳`,crarr:`↵`,Cross:`⨯`,cross:`✗`,Cscr:`𝒞`,cscr:`𝒸`,csub:`⫏`,csube:`⫑`,csup:`⫐`,csupe:`⫒`,ctdot:`⋯`,cudarrl:`⤸`,cudarrr:`⤵`,cuepr:`⋞`,cuesc:`⋟`,cularr:`↶`,cularrp:`⤽`,Cup:`⋓`,cup:`∪`,cupbrcap:`⩈`,CupCap:`≍`,cupcap:`⩆`,cupcup:`⩊`,cupdot:`⊍`,cupor:`⩅`,cups:`∪︀`,curarr:`↷`,curarrm:`⤼`,curlyeqprec:`⋞`,curlyeqsucc:`⋟`,curlyvee:`⋎`,curlywedge:`⋏`,curren:`¤`,curvearrowleft:`↶`,curvearrowright:`↷`,cuvee:`⋎`,cuwed:`⋏`,cwconint:`∲`,cwint:`∱`,cylcty:`⌭`,Dagger:`‡`,dagger:`†`,daleth:`ℸ`,Darr:`↡`,dArr:`⇓`,darr:`↓`,dash:`‐`,Dashv:`⫤`,dashv:`⊣`,dbkarow:`⤏`,dblac:`˝`,Dcaron:`Ď`,dcaron:`ď`,Dcy:`Д`,dcy:`д`,DD:`ⅅ`,dd:`ⅆ`,ddagger:`‡`,ddarr:`⇊`,DDotrahd:`⤑`,ddotseq:`⩷`,deg:`°`,Del:`∇`,Delta:`Δ`,delta:`δ`,demptyv:`⦱`,dfisht:`⥿`,Dfr:`𝔇`,dfr:`𝔡`,dHar:`⥥`,dharl:`⇃`,dharr:`⇂`,DiacriticalAcute:`´`,DiacriticalDot:`˙`,DiacriticalDoubleAcute:`˝`,DiacriticalGrave:"`",DiacriticalTilde:`˜`,diam:`⋄`,Diamond:`⋄`,diamond:`⋄`,diamondsuit:`♦`,diams:`♦`,die:`¨`,DifferentialD:`ⅆ`,digamma:`ϝ`,disin:`⋲`,div:`÷`,divide:`÷`,divideontimes:`⋇`,divonx:`⋇`,DJcy:`Ђ`,djcy:`ђ`,dlcorn:`⌞`,dlcrop:`⌍`,dollar:`$`,Dopf:`𝔻`,dopf:`𝕕`,Dot:`¨`,dot:`˙`,DotDot:`⃜`,doteq:`≐`,doteqdot:`≑`,DotEqual:`≐`,dotminus:`∸`,dotplus:`∔`,dotsquare:`⊡`,doublebarwedge:`⌆`,DoubleContourIntegral:`∯`,DoubleDot:`¨`,DoubleDownArrow:`⇓`,DoubleLeftArrow:`⇐`,DoubleLeftRightArrow:`⇔`,DoubleLeftTee:`⫤`,DoubleLongLeftArrow:`⟸`,DoubleLongLeftRightArrow:`⟺`,DoubleLongRightArrow:`⟹`,DoubleRightArrow:`⇒`,DoubleRightTee:`⊨`,DoubleUpArrow:`⇑`,DoubleUpDownArrow:`⇕`,DoubleVerticalBar:`∥`,DownArrow:`↓`,Downarrow:`⇓`,downarrow:`↓`,DownArrowBar:`⤓`,DownArrowUpArrow:`⇵`,DownBreve:`̑`,downdownarrows:`⇊`,downharpoonleft:`⇃`,downharpoonright:`⇂`,DownLeftRightVector:`⥐`,DownLeftTeeVector:`⥞`,DownLeftVector:`↽`,DownLeftVectorBar:`⥖`,DownRightTeeVector:`⥟`,DownRightVector:`⇁`,DownRightVectorBar:`⥗`,DownTee:`⊤`,DownTeeArrow:`↧`,drbkarow:`⤐`,drcorn:`⌟`,drcrop:`⌌`,Dscr:`𝒟`,dscr:`𝒹`,DScy:`Ѕ`,dscy:`ѕ`,dsol:`⧶`,Dstrok:`Đ`,dstrok:`đ`,dtdot:`⋱`,dtri:`▿`,dtrif:`▾`,duarr:`⇵`,duhar:`⥯`,dwangle:`⦦`,DZcy:`Џ`,dzcy:`џ`,dzigrarr:`⟿`,Eacute:`É`,eacute:`é`,easter:`⩮`,Ecaron:`Ě`,ecaron:`ě`,ecir:`≖`,Ecirc:`Ê`,ecirc:`ê`,ecolon:`≕`,Ecy:`Э`,ecy:`э`,eDDot:`⩷`,Edot:`Ė`,eDot:`≑`,edot:`ė`,ee:`ⅇ`,efDot:`≒`,Efr:`𝔈`,efr:`𝔢`,eg:`⪚`,Egrave:`È`,egrave:`è`,egs:`⪖`,egsdot:`⪘`,el:`⪙`,Element:`∈`,elinters:`⏧`,ell:`ℓ`,els:`⪕`,elsdot:`⪗`,Emacr:`Ē`,emacr:`ē`,empty:`∅`,emptyset:`∅`,EmptySmallSquare:`◻`,emptyv:`∅`,EmptyVerySmallSquare:`▫`,emsp:` `,emsp13:` `,emsp14:` `,ENG:`Ŋ`,eng:`ŋ`,ensp:` `,Eogon:`Ę`,eogon:`ę`,Eopf:`𝔼`,eopf:`𝕖`,epar:`⋕`,eparsl:`⧣`,eplus:`⩱`,epsi:`ε`,Epsilon:`Ε`,epsilon:`ε`,epsiv:`ϵ`,eqcirc:`≖`,eqcolon:`≕`,eqsim:`≂`,eqslantgtr:`⪖`,eqslantless:`⪕`,Equal:`⩵`,equals:`=`,EqualTilde:`≂`,equest:`≟`,Equilibrium:`⇌`,equiv:`≡`,equivDD:`⩸`,eqvparsl:`⧥`,erarr:`⥱`,erDot:`≓`,Escr:`ℰ`,escr:`ℯ`,esdot:`≐`,Esim:`⩳`,esim:`≂`,Eta:`Η`,eta:`η`,ETH:`Ð`,eth:`ð`,Euml:`Ë`,euml:`ë`,euro:`€`,excl:`!`,exist:`∃`,Exists:`∃`,expectation:`ℰ`,ExponentialE:`ⅇ`,exponentiale:`ⅇ`,fallingdotseq:`≒`,Fcy:`Ф`,fcy:`ф`,female:`♀`,ffilig:`ffi`,fflig:`ff`,ffllig:`ffl`,Ffr:`𝔉`,ffr:`𝔣`,filig:`fi`,FilledSmallSquare:`◼`,FilledVerySmallSquare:`▪`,fjlig:`fj`,flat:`♭`,fllig:`fl`,fltns:`▱`,fnof:`ƒ`,Fopf:`𝔽`,fopf:`𝕗`,ForAll:`∀`,forall:`∀`,fork:`⋔`,forkv:`⫙`,Fouriertrf:`ℱ`,fpartint:`⨍`,frac12:`½`,frac13:`⅓`,frac14:`¼`,frac15:`⅕`,frac16:`⅙`,frac18:`⅛`,frac23:`⅔`,frac25:`⅖`,frac34:`¾`,frac35:`⅗`,frac38:`⅜`,frac45:`⅘`,frac56:`⅚`,frac58:`⅝`,frac78:`⅞`,frasl:`⁄`,frown:`⌢`,Fscr:`ℱ`,fscr:`𝒻`,gacute:`ǵ`,Gamma:`Γ`,gamma:`γ`,Gammad:`Ϝ`,gammad:`ϝ`,gap:`⪆`,Gbreve:`Ğ`,gbreve:`ğ`,Gcedil:`Ģ`,Gcirc:`Ĝ`,gcirc:`ĝ`,Gcy:`Г`,gcy:`г`,Gdot:`Ġ`,gdot:`ġ`,gE:`≧`,ge:`≥`,gEl:`⪌`,gel:`⋛`,geq:`≥`,geqq:`≧`,geqslant:`⩾`,ges:`⩾`,gescc:`⪩`,gesdot:`⪀`,gesdoto:`⪂`,gesdotol:`⪄`,gesl:`⋛︀`,gesles:`⪔`,Gfr:`𝔊`,gfr:`𝔤`,Gg:`⋙`,gg:`≫`,ggg:`⋙`,gimel:`ℷ`,GJcy:`Ѓ`,gjcy:`ѓ`,gl:`≷`,gla:`⪥`,glE:`⪒`,glj:`⪤`,gnap:`⪊`,gnapprox:`⪊`,gnE:`≩`,gne:`⪈`,gneq:`⪈`,gneqq:`≩`,gnsim:`⋧`,Gopf:`𝔾`,gopf:`𝕘`,grave:"`",GreaterEqual:`≥`,GreaterEqualLess:`⋛`,GreaterFullEqual:`≧`,GreaterGreater:`⪢`,GreaterLess:`≷`,GreaterSlantEqual:`⩾`,GreaterTilde:`≳`,Gscr:`𝒢`,gscr:`ℊ`,gsim:`≳`,gsime:`⪎`,gsiml:`⪐`,Gt:`≫`,GT:`>`,gt:`>`,gtcc:`⪧`,gtcir:`⩺`,gtdot:`⋗`,gtlPar:`⦕`,gtquest:`⩼`,gtrapprox:`⪆`,gtrarr:`⥸`,gtrdot:`⋗`,gtreqless:`⋛`,gtreqqless:`⪌`,gtrless:`≷`,gtrsim:`≳`,gvertneqq:`≩︀`,gvnE:`≩︀`,Hacek:`ˇ`,hairsp:` `,half:`½`,hamilt:`ℋ`,HARDcy:`Ъ`,hardcy:`ъ`,hArr:`⇔`,harr:`↔`,harrcir:`⥈`,harrw:`↭`,Hat:`^`,hbar:`ℏ`,Hcirc:`Ĥ`,hcirc:`ĥ`,hearts:`♥`,heartsuit:`♥`,hellip:`…`,hercon:`⊹`,Hfr:`ℌ`,hfr:`𝔥`,HilbertSpace:`ℋ`,hksearow:`⤥`,hkswarow:`⤦`,hoarr:`⇿`,homtht:`∻`,hookleftarrow:`↩`,hookrightarrow:`↪`,Hopf:`ℍ`,hopf:`𝕙`,horbar:`―`,HorizontalLine:`─`,Hscr:`ℋ`,hscr:`𝒽`,hslash:`ℏ`,Hstrok:`Ħ`,hstrok:`ħ`,HumpDownHump:`≎`,HumpEqual:`≏`,hybull:`⁃`,hyphen:`‐`,Iacute:`Í`,iacute:`í`,ic:`⁣`,Icirc:`Î`,icirc:`î`,Icy:`И`,icy:`и`,Idot:`İ`,IEcy:`Е`,iecy:`е`,iexcl:`¡`,iff:`⇔`,Ifr:`ℑ`,ifr:`𝔦`,Igrave:`Ì`,igrave:`ì`,ii:`ⅈ`,iiiint:`⨌`,iiint:`∭`,iinfin:`⧜`,iiota:`℩`,IJlig:`IJ`,ijlig:`ij`,Im:`ℑ`,Imacr:`Ī`,imacr:`ī`,image:`ℑ`,ImaginaryI:`ⅈ`,imagline:`ℐ`,imagpart:`ℑ`,imath:`ı`,imof:`⊷`,imped:`Ƶ`,Implies:`⇒`,in:`∈`,incare:`℅`,infin:`∞`,infintie:`⧝`,inodot:`ı`,Int:`∬`,int:`∫`,intcal:`⊺`,integers:`ℤ`,Integral:`∫`,intercal:`⊺`,Intersection:`⋂`,intlarhk:`⨗`,intprod:`⨼`,InvisibleComma:`⁣`,InvisibleTimes:`⁢`,IOcy:`Ё`,iocy:`ё`,Iogon:`Į`,iogon:`į`,Iopf:`𝕀`,iopf:`𝕚`,Iota:`Ι`,iota:`ι`,iprod:`⨼`,iquest:`¿`,Iscr:`ℐ`,iscr:`𝒾`,isin:`∈`,isindot:`⋵`,isinE:`⋹`,isins:`⋴`,isinsv:`⋳`,isinv:`∈`,it:`⁢`,Itilde:`Ĩ`,itilde:`ĩ`,Iukcy:`І`,iukcy:`і`,Iuml:`Ï`,iuml:`ï`,Jcirc:`Ĵ`,jcirc:`ĵ`,Jcy:`Й`,jcy:`й`,Jfr:`𝔍`,jfr:`𝔧`,jmath:`ȷ`,Jopf:`𝕁`,jopf:`𝕛`,Jscr:`𝒥`,jscr:`𝒿`,Jsercy:`Ј`,jsercy:`ј`,Jukcy:`Є`,jukcy:`є`,Kappa:`Κ`,kappa:`κ`,kappav:`ϰ`,Kcedil:`Ķ`,kcedil:`ķ`,Kcy:`К`,kcy:`к`,Kfr:`𝔎`,kfr:`𝔨`,kgreen:`ĸ`,KHcy:`Х`,khcy:`х`,KJcy:`Ќ`,kjcy:`ќ`,Kopf:`𝕂`,kopf:`𝕜`,Kscr:`𝒦`,kscr:`𝓀`,lAarr:`⇚`,Lacute:`Ĺ`,lacute:`ĺ`,laemptyv:`⦴`,lagran:`ℒ`,Lambda:`Λ`,lambda:`λ`,Lang:`⟪`,lang:`⟨`,langd:`⦑`,langle:`⟨`,lap:`⪅`,Laplacetrf:`ℒ`,laquo:`«`,Larr:`↞`,lArr:`⇐`,larr:`←`,larrb:`⇤`,larrbfs:`⤟`,larrfs:`⤝`,larrhk:`↩`,larrlp:`↫`,larrpl:`⤹`,larrsim:`⥳`,larrtl:`↢`,lat:`⪫`,lAtail:`⤛`,latail:`⤙`,late:`⪭`,lates:`⪭︀`,lBarr:`⤎`,lbarr:`⤌`,lbbrk:`❲`,lbrace:`{`,lbrack:`[`,lbrke:`⦋`,lbrksld:`⦏`,lbrkslu:`⦍`,Lcaron:`Ľ`,lcaron:`ľ`,Lcedil:`Ļ`,lcedil:`ļ`,lceil:`⌈`,lcub:`{`,Lcy:`Л`,lcy:`л`,ldca:`⤶`,ldquo:`“`,ldquor:`„`,ldrdhar:`⥧`,ldrushar:`⥋`,ldsh:`↲`,lE:`≦`,le:`≤`,LeftAngleBracket:`⟨`,LeftArrow:`←`,Leftarrow:`⇐`,leftarrow:`←`,LeftArrowBar:`⇤`,LeftArrowRightArrow:`⇆`,leftarrowtail:`↢`,LeftCeiling:`⌈`,LeftDoubleBracket:`⟦`,LeftDownTeeVector:`⥡`,LeftDownVector:`⇃`,LeftDownVectorBar:`⥙`,LeftFloor:`⌊`,leftharpoondown:`↽`,leftharpoonup:`↼`,leftleftarrows:`⇇`,LeftRightArrow:`↔`,Leftrightarrow:`⇔`,leftrightarrow:`↔`,leftrightarrows:`⇆`,leftrightharpoons:`⇋`,leftrightsquigarrow:`↭`,LeftRightVector:`⥎`,LeftTee:`⊣`,LeftTeeArrow:`↤`,LeftTeeVector:`⥚`,leftthreetimes:`⋋`,LeftTriangle:`⊲`,LeftTriangleBar:`⧏`,LeftTriangleEqual:`⊴`,LeftUpDownVector:`⥑`,LeftUpTeeVector:`⥠`,LeftUpVector:`↿`,LeftUpVectorBar:`⥘`,LeftVector:`↼`,LeftVectorBar:`⥒`,lEg:`⪋`,leg:`⋚`,leq:`≤`,leqq:`≦`,leqslant:`⩽`,les:`⩽`,lescc:`⪨`,lesdot:`⩿`,lesdoto:`⪁`,lesdotor:`⪃`,lesg:`⋚︀`,lesges:`⪓`,lessapprox:`⪅`,lessdot:`⋖`,lesseqgtr:`⋚`,lesseqqgtr:`⪋`,LessEqualGreater:`⋚`,LessFullEqual:`≦`,LessGreater:`≶`,lessgtr:`≶`,LessLess:`⪡`,lesssim:`≲`,LessSlantEqual:`⩽`,LessTilde:`≲`,lfisht:`⥼`,lfloor:`⌊`,Lfr:`𝔏`,lfr:`𝔩`,lg:`≶`,lgE:`⪑`,lHar:`⥢`,lhard:`↽`,lharu:`↼`,lharul:`⥪`,lhblk:`▄`,LJcy:`Љ`,ljcy:`љ`,Ll:`⋘`,ll:`≪`,llarr:`⇇`,llcorner:`⌞`,Lleftarrow:`⇚`,llhard:`⥫`,lltri:`◺`,Lmidot:`Ŀ`,lmidot:`ŀ`,lmoust:`⎰`,lmoustache:`⎰`,lnap:`⪉`,lnapprox:`⪉`,lnE:`≨`,lne:`⪇`,lneq:`⪇`,lneqq:`≨`,lnsim:`⋦`,loang:`⟬`,loarr:`⇽`,lobrk:`⟦`,LongLeftArrow:`⟵`,Longleftarrow:`⟸`,longleftarrow:`⟵`,LongLeftRightArrow:`⟷`,Longleftrightarrow:`⟺`,longleftrightarrow:`⟷`,longmapsto:`⟼`,LongRightArrow:`⟶`,Longrightarrow:`⟹`,longrightarrow:`⟶`,looparrowleft:`↫`,looparrowright:`↬`,lopar:`⦅`,Lopf:`𝕃`,lopf:`𝕝`,loplus:`⨭`,lotimes:`⨴`,lowast:`∗`,lowbar:`_`,LowerLeftArrow:`↙`,LowerRightArrow:`↘`,loz:`◊`,lozenge:`◊`,lozf:`⧫`,lpar:`(`,lparlt:`⦓`,lrarr:`⇆`,lrcorner:`⌟`,lrhar:`⇋`,lrhard:`⥭`,lrm:`‎`,lrtri:`⊿`,lsaquo:`‹`,Lscr:`ℒ`,lscr:`𝓁`,Lsh:`↰`,lsh:`↰`,lsim:`≲`,lsime:`⪍`,lsimg:`⪏`,lsqb:`[`,lsquo:`‘`,lsquor:`‚`,Lstrok:`Ł`,lstrok:`ł`,Lt:`≪`,LT:`<`,lt:`<`,ltcc:`⪦`,ltcir:`⩹`,ltdot:`⋖`,lthree:`⋋`,ltimes:`⋉`,ltlarr:`⥶`,ltquest:`⩻`,ltri:`◃`,ltrie:`⊴`,ltrif:`◂`,ltrPar:`⦖`,lurdshar:`⥊`,luruhar:`⥦`,lvertneqq:`≨︀`,lvnE:`≨︀`,macr:`¯`,male:`♂`,malt:`✠`,maltese:`✠`,Map:`⤅`,map:`↦`,mapsto:`↦`,mapstodown:`↧`,mapstoleft:`↤`,mapstoup:`↥`,marker:`▮`,mcomma:`⨩`,Mcy:`М`,mcy:`м`,mdash:`—`,mDDot:`∺`,measuredangle:`∡`,MediumSpace:` `,Mellintrf:`ℳ`,Mfr:`𝔐`,mfr:`𝔪`,mho:`℧`,micro:`µ`,mid:`∣`,midast:`*`,midcir:`⫰`,middot:`·`,minus:`−`,minusb:`⊟`,minusd:`∸`,minusdu:`⨪`,MinusPlus:`∓`,mlcp:`⫛`,mldr:`…`,mnplus:`∓`,models:`⊧`,Mopf:`𝕄`,mopf:`𝕞`,mp:`∓`,Mscr:`ℳ`,mscr:`𝓂`,mstpos:`∾`,Mu:`Μ`,mu:`μ`,multimap:`⊸`,mumap:`⊸`,nabla:`∇`,Nacute:`Ń`,nacute:`ń`,nang:`∠⃒`,nap:`≉`,napE:`⩰̸`,napid:`≋̸`,napos:`ʼn`,napprox:`≉`,natur:`♮`,natural:`♮`,naturals:`ℕ`,nbsp:`\xA0`,nbump:`≎̸`,nbumpe:`≏̸`,ncap:`⩃`,Ncaron:`Ň`,ncaron:`ň`,Ncedil:`Ņ`,ncedil:`ņ`,ncong:`≇`,ncongdot:`⩭̸`,ncup:`⩂`,Ncy:`Н`,ncy:`н`,ndash:`–`,ne:`≠`,nearhk:`⤤`,neArr:`⇗`,nearr:`↗`,nearrow:`↗`,nedot:`≐̸`,NegativeMediumSpace:`​`,NegativeThickSpace:`​`,NegativeThinSpace:`​`,NegativeVeryThinSpace:`​`,nequiv:`≢`,nesear:`⤨`,nesim:`≂̸`,NestedGreaterGreater:`≫`,NestedLessLess:`≪`,NewLine:` `,nexist:`∄`,nexists:`∄`,Nfr:`𝔑`,nfr:`𝔫`,ngE:`≧̸`,nge:`≱`,ngeq:`≱`,ngeqq:`≧̸`,ngeqslant:`⩾̸`,nges:`⩾̸`,nGg:`⋙̸`,ngsim:`≵`,nGt:`≫⃒`,ngt:`≯`,ngtr:`≯`,nGtv:`≫̸`,nhArr:`⇎`,nharr:`↮`,nhpar:`⫲`,ni:`∋`,nis:`⋼`,nisd:`⋺`,niv:`∋`,NJcy:`Њ`,njcy:`њ`,nlArr:`⇍`,nlarr:`↚`,nldr:`‥`,nlE:`≦̸`,nle:`≰`,nLeftarrow:`⇍`,nleftarrow:`↚`,nLeftrightarrow:`⇎`,nleftrightarrow:`↮`,nleq:`≰`,nleqq:`≦̸`,nleqslant:`⩽̸`,nles:`⩽̸`,nless:`≮`,nLl:`⋘̸`,nlsim:`≴`,nLt:`≪⃒`,nlt:`≮`,nltri:`⋪`,nltrie:`⋬`,nLtv:`≪̸`,nmid:`∤`,NoBreak:`⁠`,NonBreakingSpace:`\xA0`,Nopf:`ℕ`,nopf:`𝕟`,Not:`⫬`,not:`¬`,NotCongruent:`≢`,NotCupCap:`≭`,NotDoubleVerticalBar:`∦`,NotElement:`∉`,NotEqual:`≠`,NotEqualTilde:`≂̸`,NotExists:`∄`,NotGreater:`≯`,NotGreaterEqual:`≱`,NotGreaterFullEqual:`≧̸`,NotGreaterGreater:`≫̸`,NotGreaterLess:`≹`,NotGreaterSlantEqual:`⩾̸`,NotGreaterTilde:`≵`,NotHumpDownHump:`≎̸`,NotHumpEqual:`≏̸`,notin:`∉`,notindot:`⋵̸`,notinE:`⋹̸`,notinva:`∉`,notinvb:`⋷`,notinvc:`⋶`,NotLeftTriangle:`⋪`,NotLeftTriangleBar:`⧏̸`,NotLeftTriangleEqual:`⋬`,NotLess:`≮`,NotLessEqual:`≰`,NotLessGreater:`≸`,NotLessLess:`≪̸`,NotLessSlantEqual:`⩽̸`,NotLessTilde:`≴`,NotNestedGreaterGreater:`⪢̸`,NotNestedLessLess:`⪡̸`,notni:`∌`,notniva:`∌`,notnivb:`⋾`,notnivc:`⋽`,NotPrecedes:`⊀`,NotPrecedesEqual:`⪯̸`,NotPrecedesSlantEqual:`⋠`,NotReverseElement:`∌`,NotRightTriangle:`⋫`,NotRightTriangleBar:`⧐̸`,NotRightTriangleEqual:`⋭`,NotSquareSubset:`⊏̸`,NotSquareSubsetEqual:`⋢`,NotSquareSuperset:`⊐̸`,NotSquareSupersetEqual:`⋣`,NotSubset:`⊂⃒`,NotSubsetEqual:`⊈`,NotSucceeds:`⊁`,NotSucceedsEqual:`⪰̸`,NotSucceedsSlantEqual:`⋡`,NotSucceedsTilde:`≿̸`,NotSuperset:`⊃⃒`,NotSupersetEqual:`⊉`,NotTilde:`≁`,NotTildeEqual:`≄`,NotTildeFullEqual:`≇`,NotTildeTilde:`≉`,NotVerticalBar:`∤`,npar:`∦`,nparallel:`∦`,nparsl:`⫽⃥`,npart:`∂̸`,npolint:`⨔`,npr:`⊀`,nprcue:`⋠`,npre:`⪯̸`,nprec:`⊀`,npreceq:`⪯̸`,nrArr:`⇏`,nrarr:`↛`,nrarrc:`⤳̸`,nrarrw:`↝̸`,nRightarrow:`⇏`,nrightarrow:`↛`,nrtri:`⋫`,nrtrie:`⋭`,nsc:`⊁`,nsccue:`⋡`,nsce:`⪰̸`,Nscr:`𝒩`,nscr:`𝓃`,nshortmid:`∤`,nshortparallel:`∦`,nsim:`≁`,nsime:`≄`,nsimeq:`≄`,nsmid:`∤`,nspar:`∦`,nsqsube:`⋢`,nsqsupe:`⋣`,nsub:`⊄`,nsubE:`⫅̸`,nsube:`⊈`,nsubset:`⊂⃒`,nsubseteq:`⊈`,nsubseteqq:`⫅̸`,nsucc:`⊁`,nsucceq:`⪰̸`,nsup:`⊅`,nsupE:`⫆̸`,nsupe:`⊉`,nsupset:`⊃⃒`,nsupseteq:`⊉`,nsupseteqq:`⫆̸`,ntgl:`≹`,Ntilde:`Ñ`,ntilde:`ñ`,ntlg:`≸`,ntriangleleft:`⋪`,ntrianglelefteq:`⋬`,ntriangleright:`⋫`,ntrianglerighteq:`⋭`,Nu:`Ν`,nu:`ν`,num:`#`,numero:`№`,numsp:` `,nvap:`≍⃒`,nVDash:`⊯`,nVdash:`⊮`,nvDash:`⊭`,nvdash:`⊬`,nvge:`≥⃒`,nvgt:`>⃒`,nvHarr:`⤄`,nvinfin:`⧞`,nvlArr:`⤂`,nvle:`≤⃒`,nvlt:`<⃒`,nvltrie:`⊴⃒`,nvrArr:`⤃`,nvrtrie:`⊵⃒`,nvsim:`∼⃒`,nwarhk:`⤣`,nwArr:`⇖`,nwarr:`↖`,nwarrow:`↖`,nwnear:`⤧`,Oacute:`Ó`,oacute:`ó`,oast:`⊛`,ocir:`⊚`,Ocirc:`Ô`,ocirc:`ô`,Ocy:`О`,ocy:`о`,odash:`⊝`,Odblac:`Ő`,odblac:`ő`,odiv:`⨸`,odot:`⊙`,odsold:`⦼`,OElig:`Œ`,oelig:`œ`,ofcir:`⦿`,Ofr:`𝔒`,ofr:`𝔬`,ogon:`˛`,Ograve:`Ò`,ograve:`ò`,ogt:`⧁`,ohbar:`⦵`,ohm:`Ω`,oint:`∮`,olarr:`↺`,olcir:`⦾`,olcross:`⦻`,oline:`‾`,olt:`⧀`,Omacr:`Ō`,omacr:`ō`,Omega:`Ω`,omega:`ω`,Omicron:`Ο`,omicron:`ο`,omid:`⦶`,ominus:`⊖`,Oopf:`𝕆`,oopf:`𝕠`,opar:`⦷`,OpenCurlyDoubleQuote:`“`,OpenCurlyQuote:`‘`,operp:`⦹`,oplus:`⊕`,Or:`⩔`,or:`∨`,orarr:`↻`,ord:`⩝`,order:`ℴ`,orderof:`ℴ`,ordf:`ª`,ordm:`º`,origof:`⊶`,oror:`⩖`,orslope:`⩗`,orv:`⩛`,oS:`Ⓢ`,Oscr:`𝒪`,oscr:`ℴ`,Oslash:`Ø`,oslash:`ø`,osol:`⊘`,Otilde:`Õ`,otilde:`õ`,Otimes:`⨷`,otimes:`⊗`,otimesas:`⨶`,Ouml:`Ö`,ouml:`ö`,ovbar:`⌽`,OverBar:`‾`,OverBrace:`⏞`,OverBracket:`⎴`,OverParenthesis:`⏜`,par:`∥`,para:`¶`,parallel:`∥`,parsim:`⫳`,parsl:`⫽`,part:`∂`,PartialD:`∂`,Pcy:`П`,pcy:`п`,percnt:`%`,period:`.`,permil:`‰`,perp:`⊥`,pertenk:`‱`,Pfr:`𝔓`,pfr:`𝔭`,Phi:`Φ`,phi:`φ`,phiv:`ϕ`,phmmat:`ℳ`,phone:`☎`,Pi:`Π`,pi:`π`,pitchfork:`⋔`,piv:`ϖ`,planck:`ℏ`,planckh:`ℎ`,plankv:`ℏ`,plus:`+`,plusacir:`⨣`,plusb:`⊞`,pluscir:`⨢`,plusdo:`∔`,plusdu:`⨥`,pluse:`⩲`,PlusMinus:`±`,plusmn:`±`,plussim:`⨦`,plustwo:`⨧`,pm:`±`,Poincareplane:`ℌ`,pointint:`⨕`,Popf:`ℙ`,popf:`𝕡`,pound:`£`,Pr:`⪻`,pr:`≺`,prap:`⪷`,prcue:`≼`,prE:`⪳`,pre:`⪯`,prec:`≺`,precapprox:`⪷`,preccurlyeq:`≼`,Precedes:`≺`,PrecedesEqual:`⪯`,PrecedesSlantEqual:`≼`,PrecedesTilde:`≾`,preceq:`⪯`,precnapprox:`⪹`,precneqq:`⪵`,precnsim:`⋨`,precsim:`≾`,Prime:`″`,prime:`′`,primes:`ℙ`,prnap:`⪹`,prnE:`⪵`,prnsim:`⋨`,prod:`∏`,Product:`∏`,profalar:`⌮`,profline:`⌒`,profsurf:`⌓`,prop:`∝`,Proportion:`∷`,Proportional:`∝`,propto:`∝`,prsim:`≾`,prurel:`⊰`,Pscr:`𝒫`,pscr:`𝓅`,Psi:`Ψ`,psi:`ψ`,puncsp:` `,Qfr:`𝔔`,qfr:`𝔮`,qint:`⨌`,Qopf:`ℚ`,qopf:`𝕢`,qprime:`⁗`,Qscr:`𝒬`,qscr:`𝓆`,quaternions:`ℍ`,quatint:`⨖`,quest:`?`,questeq:`≟`,QUOT:`"`,quot:`"`,rAarr:`⇛`,race:`∽̱`,Racute:`Ŕ`,racute:`ŕ`,radic:`√`,raemptyv:`⦳`,Rang:`⟫`,rang:`⟩`,rangd:`⦒`,range:`⦥`,rangle:`⟩`,raquo:`»`,Rarr:`↠`,rArr:`⇒`,rarr:`→`,rarrap:`⥵`,rarrb:`⇥`,rarrbfs:`⤠`,rarrc:`⤳`,rarrfs:`⤞`,rarrhk:`↪`,rarrlp:`↬`,rarrpl:`⥅`,rarrsim:`⥴`,Rarrtl:`⤖`,rarrtl:`↣`,rarrw:`↝`,rAtail:`⤜`,ratail:`⤚`,ratio:`∶`,rationals:`ℚ`,RBarr:`⤐`,rBarr:`⤏`,rbarr:`⤍`,rbbrk:`❳`,rbrace:`}`,rbrack:`]`,rbrke:`⦌`,rbrksld:`⦎`,rbrkslu:`⦐`,Rcaron:`Ř`,rcaron:`ř`,Rcedil:`Ŗ`,rcedil:`ŗ`,rceil:`⌉`,rcub:`}`,Rcy:`Р`,rcy:`р`,rdca:`⤷`,rdldhar:`⥩`,rdquo:`”`,rdquor:`”`,rdsh:`↳`,Re:`ℜ`,real:`ℜ`,realine:`ℛ`,realpart:`ℜ`,reals:`ℝ`,rect:`▭`,REG:`®`,reg:`®`,ReverseElement:`∋`,ReverseEquilibrium:`⇋`,ReverseUpEquilibrium:`⥯`,rfisht:`⥽`,rfloor:`⌋`,Rfr:`ℜ`,rfr:`𝔯`,rHar:`⥤`,rhard:`⇁`,rharu:`⇀`,rharul:`⥬`,Rho:`Ρ`,rho:`ρ`,rhov:`ϱ`,RightAngleBracket:`⟩`,RightArrow:`→`,Rightarrow:`⇒`,rightarrow:`→`,RightArrowBar:`⇥`,RightArrowLeftArrow:`⇄`,rightarrowtail:`↣`,RightCeiling:`⌉`,RightDoubleBracket:`⟧`,RightDownTeeVector:`⥝`,RightDownVector:`⇂`,RightDownVectorBar:`⥕`,RightFloor:`⌋`,rightharpoondown:`⇁`,rightharpoonup:`⇀`,rightleftarrows:`⇄`,rightleftharpoons:`⇌`,rightrightarrows:`⇉`,rightsquigarrow:`↝`,RightTee:`⊢`,RightTeeArrow:`↦`,RightTeeVector:`⥛`,rightthreetimes:`⋌`,RightTriangle:`⊳`,RightTriangleBar:`⧐`,RightTriangleEqual:`⊵`,RightUpDownVector:`⥏`,RightUpTeeVector:`⥜`,RightUpVector:`↾`,RightUpVectorBar:`⥔`,RightVector:`⇀`,RightVectorBar:`⥓`,ring:`˚`,risingdotseq:`≓`,rlarr:`⇄`,rlhar:`⇌`,rlm:`‏`,rmoust:`⎱`,rmoustache:`⎱`,rnmid:`⫮`,roang:`⟭`,roarr:`⇾`,robrk:`⟧`,ropar:`⦆`,Ropf:`ℝ`,ropf:`𝕣`,roplus:`⨮`,rotimes:`⨵`,RoundImplies:`⥰`,rpar:`)`,rpargt:`⦔`,rppolint:`⨒`,rrarr:`⇉`,Rrightarrow:`⇛`,rsaquo:`›`,Rscr:`ℛ`,rscr:`𝓇`,Rsh:`↱`,rsh:`↱`,rsqb:`]`,rsquo:`’`,rsquor:`’`,rthree:`⋌`,rtimes:`⋊`,rtri:`▹`,rtrie:`⊵`,rtrif:`▸`,rtriltri:`⧎`,RuleDelayed:`⧴`,ruluhar:`⥨`,rx:`℞`,Sacute:`Ś`,sacute:`ś`,sbquo:`‚`,Sc:`⪼`,sc:`≻`,scap:`⪸`,Scaron:`Š`,scaron:`š`,sccue:`≽`,scE:`⪴`,sce:`⪰`,Scedil:`Ş`,scedil:`ş`,Scirc:`Ŝ`,scirc:`ŝ`,scnap:`⪺`,scnE:`⪶`,scnsim:`⋩`,scpolint:`⨓`,scsim:`≿`,Scy:`С`,scy:`с`,sdot:`⋅`,sdotb:`⊡`,sdote:`⩦`,searhk:`⤥`,seArr:`⇘`,searr:`↘`,searrow:`↘`,sect:`§`,semi:`;`,seswar:`⤩`,setminus:`∖`,setmn:`∖`,sext:`✶`,Sfr:`𝔖`,sfr:`𝔰`,sfrown:`⌢`,sharp:`♯`,SHCHcy:`Щ`,shchcy:`щ`,SHcy:`Ш`,shcy:`ш`,ShortDownArrow:`↓`,ShortLeftArrow:`←`,shortmid:`∣`,shortparallel:`∥`,ShortRightArrow:`→`,ShortUpArrow:`↑`,shy:`­`,Sigma:`Σ`,sigma:`σ`,sigmaf:`ς`,sigmav:`ς`,sim:`∼`,simdot:`⩪`,sime:`≃`,simeq:`≃`,simg:`⪞`,simgE:`⪠`,siml:`⪝`,simlE:`⪟`,simne:`≆`,simplus:`⨤`,simrarr:`⥲`,slarr:`←`,SmallCircle:`∘`,smallsetminus:`∖`,smashp:`⨳`,smeparsl:`⧤`,smid:`∣`,smile:`⌣`,smt:`⪪`,smte:`⪬`,smtes:`⪬︀`,SOFTcy:`Ь`,softcy:`ь`,sol:`/`,solb:`⧄`,solbar:`⌿`,Sopf:`𝕊`,sopf:`𝕤`,spades:`♠`,spadesuit:`♠`,spar:`∥`,sqcap:`⊓`,sqcaps:`⊓︀`,sqcup:`⊔`,sqcups:`⊔︀`,Sqrt:`√`,sqsub:`⊏`,sqsube:`⊑`,sqsubset:`⊏`,sqsubseteq:`⊑`,sqsup:`⊐`,sqsupe:`⊒`,sqsupset:`⊐`,sqsupseteq:`⊒`,squ:`□`,Square:`□`,square:`□`,SquareIntersection:`⊓`,SquareSubset:`⊏`,SquareSubsetEqual:`⊑`,SquareSuperset:`⊐`,SquareSupersetEqual:`⊒`,SquareUnion:`⊔`,squarf:`▪`,squf:`▪`,srarr:`→`,Sscr:`𝒮`,sscr:`𝓈`,ssetmn:`∖`,ssmile:`⌣`,sstarf:`⋆`,Star:`⋆`,star:`☆`,starf:`★`,straightepsilon:`ϵ`,straightphi:`ϕ`,strns:`¯`,Sub:`⋐`,sub:`⊂`,subdot:`⪽`,subE:`⫅`,sube:`⊆`,subedot:`⫃`,submult:`⫁`,subnE:`⫋`,subne:`⊊`,subplus:`⪿`,subrarr:`⥹`,Subset:`⋐`,subset:`⊂`,subseteq:`⊆`,subseteqq:`⫅`,SubsetEqual:`⊆`,subsetneq:`⊊`,subsetneqq:`⫋`,subsim:`⫇`,subsub:`⫕`,subsup:`⫓`,succ:`≻`,succapprox:`⪸`,succcurlyeq:`≽`,Succeeds:`≻`,SucceedsEqual:`⪰`,SucceedsSlantEqual:`≽`,SucceedsTilde:`≿`,succeq:`⪰`,succnapprox:`⪺`,succneqq:`⪶`,succnsim:`⋩`,succsim:`≿`,SuchThat:`∋`,Sum:`∑`,sum:`∑`,sung:`♪`,Sup:`⋑`,sup:`⊃`,sup1:`¹`,sup2:`²`,sup3:`³`,supdot:`⪾`,supdsub:`⫘`,supE:`⫆`,supe:`⊇`,supedot:`⫄`,Superset:`⊃`,SupersetEqual:`⊇`,suphsol:`⟉`,suphsub:`⫗`,suplarr:`⥻`,supmult:`⫂`,supnE:`⫌`,supne:`⊋`,supplus:`⫀`,Supset:`⋑`,supset:`⊃`,supseteq:`⊇`,supseteqq:`⫆`,supsetneq:`⊋`,supsetneqq:`⫌`,supsim:`⫈`,supsub:`⫔`,supsup:`⫖`,swarhk:`⤦`,swArr:`⇙`,swarr:`↙`,swarrow:`↙`,swnwar:`⤪`,szlig:`ß`,Tab:` `,target:`⌖`,Tau:`Τ`,tau:`τ`,tbrk:`⎴`,Tcaron:`Ť`,tcaron:`ť`,Tcedil:`Ţ`,tcedil:`ţ`,Tcy:`Т`,tcy:`т`,tdot:`⃛`,telrec:`⌕`,Tfr:`𝔗`,tfr:`𝔱`,there4:`∴`,Therefore:`∴`,therefore:`∴`,Theta:`Θ`,theta:`θ`,thetasym:`ϑ`,thetav:`ϑ`,thickapprox:`≈`,thicksim:`∼`,ThickSpace:`  `,thinsp:` `,ThinSpace:` `,thkap:`≈`,thksim:`∼`,THORN:`Þ`,thorn:`þ`,Tilde:`∼`,tilde:`˜`,TildeEqual:`≃`,TildeFullEqual:`≅`,TildeTilde:`≈`,times:`×`,timesb:`⊠`,timesbar:`⨱`,timesd:`⨰`,tint:`∭`,toea:`⤨`,top:`⊤`,topbot:`⌶`,topcir:`⫱`,Topf:`𝕋`,topf:`𝕥`,topfork:`⫚`,tosa:`⤩`,tprime:`‴`,TRADE:`™`,trade:`™`,triangle:`▵`,triangledown:`▿`,triangleleft:`◃`,trianglelefteq:`⊴`,triangleq:`≜`,triangleright:`▹`,trianglerighteq:`⊵`,tridot:`◬`,trie:`≜`,triminus:`⨺`,TripleDot:`⃛`,triplus:`⨹`,trisb:`⧍`,tritime:`⨻`,trpezium:`⏢`,Tscr:`𝒯`,tscr:`𝓉`,TScy:`Ц`,tscy:`ц`,TSHcy:`Ћ`,tshcy:`ћ`,Tstrok:`Ŧ`,tstrok:`ŧ`,twixt:`≬`,twoheadleftarrow:`↞`,twoheadrightarrow:`↠`,Uacute:`Ú`,uacute:`ú`,Uarr:`↟`,uArr:`⇑`,uarr:`↑`,Uarrocir:`⥉`,Ubrcy:`Ў`,ubrcy:`ў`,Ubreve:`Ŭ`,ubreve:`ŭ`,Ucirc:`Û`,ucirc:`û`,Ucy:`У`,ucy:`у`,udarr:`⇅`,Udblac:`Ű`,udblac:`ű`,udhar:`⥮`,ufisht:`⥾`,Ufr:`𝔘`,ufr:`𝔲`,Ugrave:`Ù`,ugrave:`ù`,uHar:`⥣`,uharl:`↿`,uharr:`↾`,uhblk:`▀`,ulcorn:`⌜`,ulcorner:`⌜`,ulcrop:`⌏`,ultri:`◸`,Umacr:`Ū`,umacr:`ū`,uml:`¨`,UnderBar:`_`,UnderBrace:`⏟`,UnderBracket:`⎵`,UnderParenthesis:`⏝`,Union:`⋃`,UnionPlus:`⊎`,Uogon:`Ų`,uogon:`ų`,Uopf:`𝕌`,uopf:`𝕦`,UpArrow:`↑`,Uparrow:`⇑`,uparrow:`↑`,UpArrowBar:`⤒`,UpArrowDownArrow:`⇅`,UpDownArrow:`↕`,Updownarrow:`⇕`,updownarrow:`↕`,UpEquilibrium:`⥮`,upharpoonleft:`↿`,upharpoonright:`↾`,uplus:`⊎`,UpperLeftArrow:`↖`,UpperRightArrow:`↗`,Upsi:`ϒ`,upsi:`υ`,upsih:`ϒ`,Upsilon:`Υ`,upsilon:`υ`,UpTee:`⊥`,UpTeeArrow:`↥`,upuparrows:`⇈`,urcorn:`⌝`,urcorner:`⌝`,urcrop:`⌎`,Uring:`Ů`,uring:`ů`,urtri:`◹`,Uscr:`𝒰`,uscr:`𝓊`,utdot:`⋰`,Utilde:`Ũ`,utilde:`ũ`,utri:`▵`,utrif:`▴`,uuarr:`⇈`,Uuml:`Ü`,uuml:`ü`,uwangle:`⦧`,vangrt:`⦜`,varepsilon:`ϵ`,varkappa:`ϰ`,varnothing:`∅`,varphi:`ϕ`,varpi:`ϖ`,varpropto:`∝`,vArr:`⇕`,varr:`↕`,varrho:`ϱ`,varsigma:`ς`,varsubsetneq:`⊊︀`,varsubsetneqq:`⫋︀`,varsupsetneq:`⊋︀`,varsupsetneqq:`⫌︀`,vartheta:`ϑ`,vartriangleleft:`⊲`,vartriangleright:`⊳`,Vbar:`⫫`,vBar:`⫨`,vBarv:`⫩`,Vcy:`В`,vcy:`в`,VDash:`⊫`,Vdash:`⊩`,vDash:`⊨`,vdash:`⊢`,Vdashl:`⫦`,Vee:`⋁`,vee:`∨`,veebar:`⊻`,veeeq:`≚`,vellip:`⋮`,Verbar:`‖`,verbar:`|`,Vert:`‖`,vert:`|`,VerticalBar:`∣`,VerticalLine:`|`,VerticalSeparator:`❘`,VerticalTilde:`≀`,VeryThinSpace:` `,Vfr:`𝔙`,vfr:`𝔳`,vltri:`⊲`,vnsub:`⊂⃒`,vnsup:`⊃⃒`,Vopf:`𝕍`,vopf:`𝕧`,vprop:`∝`,vrtri:`⊳`,Vscr:`𝒱`,vscr:`𝓋`,vsubnE:`⫋︀`,vsubne:`⊊︀`,vsupnE:`⫌︀`,vsupne:`⊋︀`,Vvdash:`⊪`,vzigzag:`⦚`,Wcirc:`Ŵ`,wcirc:`ŵ`,wedbar:`⩟`,Wedge:`⋀`,wedge:`∧`,wedgeq:`≙`,weierp:`℘`,Wfr:`𝔚`,wfr:`𝔴`,Wopf:`𝕎`,wopf:`𝕨`,wp:`℘`,wr:`≀`,wreath:`≀`,Wscr:`𝒲`,wscr:`𝓌`,xcap:`⋂`,xcirc:`◯`,xcup:`⋃`,xdtri:`▽`,Xfr:`𝔛`,xfr:`𝔵`,xhArr:`⟺`,xharr:`⟷`,Xi:`Ξ`,xi:`ξ`,xlArr:`⟸`,xlarr:`⟵`,xmap:`⟼`,xnis:`⋻`,xodot:`⨀`,Xopf:`𝕏`,xopf:`𝕩`,xoplus:`⨁`,xotime:`⨂`,xrArr:`⟹`,xrarr:`⟶`,Xscr:`𝒳`,xscr:`𝓍`,xsqcup:`⨆`,xuplus:`⨄`,xutri:`△`,xvee:`⋁`,xwedge:`⋀`,Yacute:`Ý`,yacute:`ý`,YAcy:`Я`,yacy:`я`,Ycirc:`Ŷ`,ycirc:`ŷ`,Ycy:`Ы`,ycy:`ы`,yen:`¥`,Yfr:`𝔜`,yfr:`𝔶`,YIcy:`Ї`,yicy:`ї`,Yopf:`𝕐`,yopf:`𝕪`,Yscr:`𝒴`,yscr:`𝓎`,YUcy:`Ю`,yucy:`ю`,Yuml:`Ÿ`,yuml:`ÿ`,Zacute:`Ź`,zacute:`ź`,Zcaron:`Ž`,zcaron:`ž`,Zcy:`З`,zcy:`з`,Zdot:`Ż`,zdot:`ż`,zeetrf:`ℨ`,ZeroWidthSpace:`​`,Zeta:`Ζ`,zeta:`ζ`,Zfr:`ℨ`,zfr:`𝔷`,ZHcy:`Ж`,zhcy:`ж`,zigrarr:`⇝`,Zopf:`ℤ`,zopf:`𝕫`,Zscr:`𝒵`,zscr:`𝓏`,zwj:`‍`,zwnj:`‌`}),e.entityMap=e.HTML_ENTITIES})),Og=o((e=>{var t=Cg(),n=Tg(),r=wg(),i=t.isHTMLEscapableRawTextElement,a=t.isHTMLMimeType,o=t.isHTMLRawTextElement,s=t.hasOwn,c=t.NAMESPACE,l=r.ParseError,u=r.DOMException,d=0,f=1,p=2,m=3,h=4,g=5,_=6,v=7;function y(){}y.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),E(t,t=Object.create(null)),x(e,t,n,r,this.errorHandler),r.endDocument()}};var b=/&#?\w+;?/g;function x(e,r,i,o,c){var d=a(o.mimeType);e.indexOf(n.UNICODE_REPLACEMENT_CHARACTER)>=0&&c.warning(`Unicode replacement character detected, source encoding issues?`);function f(e){if(e>65535){e-=65536;var t=55296+(e>>10),n=56320+(e&1023);return String.fromCharCode(t,n)}return String.fromCharCode(e)}function p(e){var t=e[e.length-1]===`;`?e:e+`;`;if(!d&&t!==e)return c.error(`EntityRef: expecting ;`),e;var r=n.Reference.exec(t);if(!r||r[0].length!==t.length)return c.error(`entity not matching Reference production: `+e),e;var a=t.slice(1,-1);return s(i,a)?i[a]:a.charAt(0)===`#`?f(parseInt(a.substring(1).replace(`x`,`0x`))):(c.error(`entity not found:`+e),e)}function m(t){if(t>D){var n=e.substring(D,t).replace(b,p);v&&y(D),o.characters(n,0,t-D),D=t}}var h=0,g=0,_=/\r\n?|\n|$/g,v=o.locator;function y(t,n){for(;t>=g&&(n=_.exec(e));)h=g,g=n.index+n[0].length,v.lineNumber++;v.columnNumber=t-h+1}for(var x=[{currentNSMap:r}],E=[],D=0;;){try{var O=e.indexOf(`<`,D);if(O<0){if(!d&&E.length>0)return c.fatalError(`unclosed xml tag(s): `+E.join(`, `));if(!e.substring(D).match(/^\s*$/)){var ne=o.doc,A=ne.createTextNode(e.substring(D));if(ne.documentElement)return c.error(`Extra content at the end of the document`);ne.appendChild(A),o.currentElement=A}return}if(O>D){var re=e.substring(D,O);!d&&E.length===0&&(re=re.replace(new RegExp(n.S_OPT.source,`g`),``),re&&c.error(`Unexpected content outside root element: '`+re+`'`)),m(O)}switch(e.charAt(O+1)){case`/`:var j=e.indexOf(`>`,O+2),M=e.substring(O+2,j>0?j:void 0);if(!M)return c.fatalError(`end tag name missing`);var N=n.reg(`^`,n.QName_group,n.S_OPT,`$`),P=j>0&&N.exec(M);if(!P){var ie=j>0&&n.reg(`^`,n.QName_group).exec(M);if(d&&ie)c.warning(`end tag name contains invalid trailing characters: "`+M+`"`),P=ie;else if(ie&&new RegExp(N.source,N.flags+`m`).test(M))c.error(`end tag name is followed by a line break and trailing content: "`+M+`"`),P=ie;else return c.fatalError(`end tag name contains invalid characters: "`+M+`"`)}if(!o.currentElement&&!o.doc.documentElement)return;var F=E[E.length-1]||o.currentElement.tagName||o.doc.documentElement.tagName||``;if(F!==P[1]){var I=P[1].toLowerCase();if(!d||F.toLowerCase()!==I)return c.fatalError(`Opening and ending tag mismatch: "`+F+`" != "`+M+`"`)}var L=x.pop();E.pop();var R=L.localNSMap;if(o.endElement(L.uri,L.localName,F),R)for(var ae in R)s(R,ae)&&o.endPrefixMapping(ae);j++;break;case`?`:v&&y(O),j=ee(e,O,o,c);break;case`!`:v&&y(O),j=k(e,O,o,c,d);break;default:v&&y(O);var oe=new te,z=x[x.length-1].currentNSMap,j=C(e,O,oe,z,p,c,d),se=oe.length;if(oe.closed||(d&&t.isHTMLVoidElement(oe.tagName)?oe.closed=!0:E.push(oe.tagName)),v&&se){for(var ce=S(v,{}),le=0;leD?D=j:m(Math.max(O,D)+1)}}function S(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function C(e,t,n,r,i,a,o){function c(e,t,r){if(s(n.attributeNames,e))return a.fatalError(`Attribute `+e+` redefined`);if(!o&&t.indexOf(`<`)>=0)return a.fatalError(`Unescaped '<' not allowed in attributes values`);n.addValue(e,t.replace(/[\t\n\r]/g,` `).replace(b,i),r)}for(var l,u,y=++t,x=d;;){var S=e.charAt(y);if(x===d&&S===`<`)throw Error(`unexpected < in tag name: `+e.slice(t,y));switch(S){case`=`:if(x===f)l=e.slice(t,y),x=m;else if(x===p)x=m;else throw Error(`attribute equal must after attrName`);break;case`'`:case`"`:if(x===m||x===f){if(x===f&&(a.warning(`attribute value must after "="`),l=e.slice(t,y)),t=y+1,y=e.indexOf(S,t),y>0)u=e.slice(t,y),c(l,u,t-1),x=g;else throw Error(`attribute value no end '`+S+`' match`)}else if(x==h)u=e.slice(t,y),c(l,u,t),a.warning(`attribute "`+l+`" missed start quot(`+S+`)!!`),t=y+1,x=g;else throw Error(`attribute value must after "="`);break;case`/`:switch(x){case d:n.setTagName(e.slice(t,y));case g:case _:case v:x=v,n.closed=!0;case h:case f:break;case p:n.closed=!0;break;default:throw Error(`attribute invalid close char('/')`)}break;case``:return a.error(`unexpected end of input`),x==d&&n.setTagName(e.slice(t,y)),y;case`>`:switch(x){case d:n.setTagName(e.slice(t,y));case g:case _:case v:break;case h:case f:u=e.slice(t,y),u.slice(-1)===`/`&&(n.closed=!0,u=u.slice(0,-1));case p:x===p&&(u=l),x==h?(a.warning(`attribute "`+u+`" missed quot(")!`),c(l,u,t)):(o||a.warning(`attribute "`+u+`" missed value!! "`+u+`" instead!!`),c(u,u,t));break;case m:if(!o)return a.fatalError(`AttValue: ' or " expected`)}return y;case`€`:S=` `;default:if(S<=` `)switch(x){case d:n.setTagName(e.slice(t,y)),x=_;break;case f:l=e.slice(t,y),x=p;break;case h:var u=e.slice(t,y);a.warning(`attribute "`+u+`" missed quot(")!!`),c(l,u,t);case g:x=_}else switch(x){case p:o||a.warning(`attribute "`+l+`" missed value!! "`+l+`" instead2!!`),c(l,l,t),t=y,x=f;break;case g:a.warning(`attribute space is required"`+l+`"!!`);case _:x=f,t=y;break;case m:x=h,t=y;break;case v:throw Error(`elements closed character '/' and '>' must be connected to`)}}y++}}function w(e,t,n){for(var r=e.tagName,i=null,a=e.length;a--;){var o=e[a],l=o.qName,u=o.value,d=l.indexOf(`:`);if(d>0)var f=o.prefix=l.slice(0,d),p=l.slice(d+1),m=f===`xmlns`&&p;else p=l,f=null,m=l===`xmlns`&&``;o.localName=p,m!==!1&&(i??(i=Object.create(null),n=Object.create(n)),n[m]=i[m]=u,o.uri=c.XMLNS,t.startPrefixMapping(m,u))}for(var a=e.length;a--;)o=e[a],o.prefix&&(o.prefix===`xml`&&(o.uri=c.XML),o.prefix!==`xmlns`&&(o.uri=n[o.prefix]));var d=r.indexOf(`:`);d>0?(f=e.prefix=r.slice(0,d),p=e.localName=r.slice(d+1)):(f=null,p=e.localName=r);var h=e.uri=n[f||``];if(t.startElement(h,p,r,e),e.closed){if(t.endElement(h,p,r),i)for(f in i)s(i,f)&&t.endPrefixMapping(f)}else return e.currentNSMap=n,e.localNSMap=i,!0}function T(e,t,n,r,a){var s=i(n);if(s||o(n)){var c=RegExp(``,`ig`);c.lastIndex=t;var l=c.exec(e),u=l?l.index:-1;if(u<0)return t+1;var d=e.substring(t+1,u);return s&&(d=d.replace(b,r)),a.characters(d,0,d.length),u}return t+1}function E(e,t){for(var n in e)s(e,n)&&(t[n]=e[n])}function D(e,t){var r=t;function i(t){return t||=0,e.charAt(r+t)}function a(e){e||=1,r+=e}function o(){for(var t=0;r`?(o.skip(1),r.startDTD(l.name,l.publicId,l.systemId,l.internalSubset),r.endDTD(),o.getIndex()):i.fatalError(`doctype not terminated with > at position `+o.getIndex());default:return i.fatalError(`Not well-formed XML starting with "0)return i.fatalError(`processing instruction at position `+t+` is an xml declaration which is only at the start of the document`);if(!n.XMLDecl.test(e.substring(t)))return i.fatalError(`xml declaration is not well-formed`)}return r.processingInstruction(a[1],a[2]),t+a[0].length}function te(){this.attributeNames=Object.create(null)}te.prototype={setTagName:function(e){if(!n.QName_exact.test(e))throw Error(`invalid tagName:`+e);this.tagName=e},addValue:function(e,t,r){if(!n.QName_exact.test(e))throw Error(`invalid attribute:`+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},e.XMLReader=y,e.parseUtils=D,e.parseDoctypeCommentOrCData=k})),kg=o((e=>{var t=Cg(),n=Eg(),r=wg(),i=Dg(),a=Og(),o=n.DOMImplementation,s=t.hasDefaultHTMLNamespace,c=t.isHTMLMimeType,l=t.isValidMimeType,u=t.MIME_TYPE,d=t.NAMESPACE,f=r.ParseError,p=a.XMLReader;function m(e){return e.replace(/\r[\n\u0085]/g,` `).replace(/[\r\u0085\u2028\u2029]/g,` `)}function h(e){if(e||={},e.locator===void 0&&(e.locator=!0),this.assign=e.assign||t.assign,this.domHandler=e.domHandler||g,this.onError=e.onError||e.errorHandler,e.errorHandler&&typeof e.errorHandler!=`function`)throw TypeError(`errorHandler object is no longer supported, switch to onError!`);e.errorHandler&&e.errorHandler(`warning`,"The `errorHandler` option has been deprecated, use `onError` instead!",this),this.normalizeLineEndings=e.normalizeLineEndings||m,this.locator=!!e.locator,this.xmlns=this.assign(Object.create(null),e.xmlns)}h.prototype.parseFromString=function(e,n){if(!l(n))throw TypeError(`DOMParser.parseFromString: the provided mimeType "`+n+`" is not valid.`);var r=this.assign(Object.create(null),this.xmlns),a=i.XML_ENTITIES,o=r[``]||null;s(n)?(a=i.HTML_ENTITIES,o=d.HTML):n===u.XML_SVG_IMAGE&&(o=d.SVG),r[``]=o,r.xml=r.xml||d.XML;var c=new this.domHandler({mimeType:n,defaultNamespace:o,onError:this.onError}),f=this.locator?{}:void 0;this.locator&&c.setDocumentLocator(f);var m=new p;return m.errorHandler=c,m.domBuilder=c,!t.isHTMLMimeType(n)&&typeof e!=`string`&&m.errorHandler.fatalError(`source is not a string`),m.parse(this.normalizeLineEndings(String(e)),r,a),c.doc.documentElement||m.errorHandler.fatalError(`missing root element`),c.doc};function g(e){var t=e||{};this.mimeType=t.mimeType||u.XML_APPLICATION,this.defaultNamespace=t.defaultNamespace||null,this.cdata=!1,this.currentElement=void 0,this.doc=void 0,this.locator=void 0,this.onError=t.onError}function _(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}g.prototype={startDocument:function(){var e=new o;this.doc=c(this.mimeType)?e.createHTMLDocument(!1):e.createDocument(this.defaultNamespace,``)},startElement:function(e,t,n,r){var i=this.doc,a=i.createElementNS(e,n||t),o=r.length;b(this,a),this.currentElement=a,this.locator&&_(this.locator,a);for(var s=0;s=t+n||t?new java.lang.String(e,t,n)+``:e}`endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl`.replace(/\w+/g,function(e){g.prototype[e]=function(){return null}});function b(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}function x(e){if(e===`error`)throw`onErrorStopParsing`}function S(){throw`onWarningStopParsing`}e.__DOMHandler=g,e.DOMParser=h,e.normalizeLineEndings=m,e.onErrorStopParsing=x,e.onWarningStopParsing=S}));o((e=>{var t=Cg();e.assign=t.assign,e.hasDefaultHTMLNamespace=t.hasDefaultHTMLNamespace,e.isHTMLMimeType=t.isHTMLMimeType,e.isValidMimeType=t.isValidMimeType,e.MIME_TYPE=t.MIME_TYPE,e.NAMESPACE=t.NAMESPACE;var n=wg();e.DOMException=n.DOMException,e.DOMExceptionName=n.DOMExceptionName,e.ExceptionCode=n.ExceptionCode,e.ParseError=n.ParseError;var r=Eg();e.Attr=r.Attr,e.CDATASection=r.CDATASection,e.CharacterData=r.CharacterData,e.Comment=r.Comment,e.Document=r.Document,e.DocumentFragment=r.DocumentFragment,e.DocumentType=r.DocumentType,e.DOMImplementation=r.DOMImplementation,e.Element=r.Element,e.Entity=r.Entity,e.EntityReference=r.EntityReference,e.LiveNodeList=r.LiveNodeList,e.NamedNodeMap=r.NamedNodeMap,e.Node=r.Node,e.NodeList=r.NodeList,e.Notation=r.Notation,e.ProcessingInstruction=r.ProcessingInstruction,e.Text=r.Text,e.XMLSerializer=r.XMLSerializer;var i=kg();e.DOMParser=i.DOMParser,e.normalizeLineEndings=i.normalizeLineEndings,e.onErrorStopParsing=i.onErrorStopParsing,e.onWarningStopParsing=i.onWarningStopParsing}))();var Ag=e=>typeof e==`string`?e:(e??[]).filter(e=>e.type===`text`).map(e=>e.text).join(` `),jg=8192;function Mg(e){let t=e.findLast(e=>e.role===`assistant`&&e.usage?.input>0);return t?{inputTokens:t.usage.input,outputTokens:t.usage.output??0}:e.length?null:{inputTokens:0,outputTokens:0}}function Ng(e){if(!e)return`—/${jg.toLocaleString(`en-US`)} context`;let t=e.inputTokens+e.outputTokens,n=Math.max(0,jg-t);return`${t.toLocaleString(`en-US`)}/${jg.toLocaleString(`en-US`)} context · ${n.toLocaleString(`en-US`)} free`}var Pg=new Audio(new URL(``+new URL(`../cat-meow-v1.mp3`,import.meta.url).href,``+import.meta.url).href);Pg.preload=`auto`,Pg.volume=.65;function Fg(){try{Pg.currentTime=0,Pg.play().catch(()=>{})}catch{}}function Ig(e,t){let n=document.createElement(`canvas`).getContext(`2d`),r=document.createElement(`span`);r.style.cssText=`display:inline-block;width:0;height:0;padding:0;border:0;vertical-align:baseline`;let i=document.createElement(`div`);i.className=`empty-mascot`,i.hidden=!0,i.style.visibility=`hidden`;let a=document.createElement(`button`);a.type=`button`,a.className=`mascot-suggestion`;let o=document.createElement(`div`);o.className=`mascot-cat`,o.setAttribute(`aria-hidden`,`true`);let s=document.createElement(`img`);s.width=s.height=104,s.alt=``,s.draggable=!1;let c=document.createElement(`span`);c.className=`mascot-eyelids`,c.setAttribute(`aria-hidden`,`true`),o.append(s,c),i.append(a,o),e.append(i);let l=``,u=!1,d=!1,f=0,p=0,m=new Set,h=matchMedia(`(prefers-reduced-motion: reduce)`);function g(e,t,n){for(let e of m)e.id===n.id&&(e.cancel(),m.delete(e));let r=e.animate(t,n);m.add(r),r.onfinish=()=>m.delete(r)}function _(){clearTimeout(f),f=0,!(i.hidden||document.hidden||h.matches||!u)&&(d=!0,g(o,[{transform:`translate3d(0, 0, 0)`,easing:`ease-out`},{transform:`translate3d(0, -4px, 0)`,offset:.4,easing:`ease-in`},{transform:`translate3d(0, 0, 0)`}],{id:`mascot-bump`,duration:420}))}o.onclick=()=>{Fg(),_()},o.onpointerdown=e=>e.preventDefault(),o.onmousedown=e=>e.preventDefault();function v(){clearTimeout(f),clearTimeout(p),f=p=0;for(let e of m)e.cancel();m.clear()}function y(){if(i.hidden||document.hidden||h.matches||!u){v();return}!d&&!f&&(f=setTimeout(_,1800)),p||=setTimeout(()=>{p=0,g(c,[{opacity:0,easing:`steps(1, end)`},{opacity:1,offset:.15},{opacity:1,offset:.8,easing:`steps(1, end)`},{opacity:0}],{id:`mascot-blink`,duration:180}),y()},5e3+Math.random()*4e3)}function b(){i.hidden=!0,v()}async function x(){try{await s.decode()}catch{return}i.isConnected&&(u=!0,i.style.visibility=``,y())}return s.addEventListener(`load`,x),document.addEventListener(`visibilitychange`,y),h.addEventListener(`change`,y),a.onclick=()=>t(l),{hide:b,get statusInset(){return i.hidden?0:o.offsetWidth+20},update({screen:t,rows:c,viewportRows:u,contentRows:d,draft:f,hasSales:p,hasProducts:m}){if(!t||!c){b();return}let h=t.getBoundingClientRect(),g=e.getBoundingClientRect(),_=h.height/c,v=(u-d)*_-16;if(v<48){b();return}s.hasAttribute(`src`)||(s.src=new URL(``+new URL(`../empty-cat-v1.png`,import.meta.url).href,``+import.meta.url).href);let x=!f.trim()&&v>=180;a.hidden=!x,a.textContent=p&&m?`Ask me to calculate our total sales.`:`Ask me to explore your files.`,l=p&&m?`What's our total sales revenue?`:`Explore the workspace files and summarize what is here.`,a.setAttribute(`aria-label`,`Use suggested prompt: ${l}`);let S=Math.min(104,Math.floor(x?v-76:v));o.style.width=o.style.height=`${S}px`,i.hidden=!1;let C=h.top+(u+1.5)*_,w=t.querySelector(`.xterm-rows`)?.children[u+1]?.firstElementChild,T=devicePixelRatio||1;if(w&&n){let e=getComputedStyle(w);w.parentElement.append(r);let t=r.getBoundingClientRect().top;r.remove(),n.font=`${e.fontWeight} ${parseFloat(e.fontSize)*T}px ${e.fontFamily}`;let i=n.measureText(`─`);C=t-(i.actualBoundingBoxAscent-i.actualBoundingBoxDescent)/2/T}C=Math.floor(C*T+1e-4)/T;let E=Math.round(S*1156/1250*T)/T;i.style.top=`${C-g.top+S-E-i.getBoundingClientRect().height}px`,y()},dispose(){b(),s.removeEventListener(`load`,x),document.removeEventListener(`visibilitychange`,y),h.removeEventListener(`change`,y),i.remove()}}}var Lg=7e3,Rg=6500;function zg(e,t){let n=document.createElement(`div`);n.className=`terminal-paws`,n.hidden=!0,n.setAttribute(`aria-hidden`,`true`);for(let e=0;e<6;e++)n.append(document.createElement(`i`));e.append(n);let r=matchMedia(`(prefers-reduced-motion: reduce)`),i=new AbortController,a=!1,o=!1,s=!1,c=0,l=0,u=0,d=0;function f(){return a&&o&&!s&&!document.hidden&&document.hasFocus()&&!r.matches&&!document.querySelector(`dialog[open]`)}function p(){clearTimeout(l),l=0,n.hidden||=!0}function m(){if(!f()){clearTimeout(c),c=0;return}c&&u<=d||(clearTimeout(c),u=d,c=setTimeout(g,Math.max(0,d-Date.now())))}function h(){p(),d=Date.now()+Lg,m()}function g(){if(c=0,!f())return;if(Date.now()=220&&e.height>=180&&(Object.assign(n.style,{left:`${e.left}px`,top:`${e.top}px`,width:`${e.width}px`,height:`${e.height}px`}),n.style.setProperty(`--trail-shift`,`${Math.random()*10}%`),n.hidden=!1,l=setTimeout(p,Rg)),d=Date.now()+Rg+45e3+Math.random()*15e3,m()}let _={passive:!0,capture:!0,signal:i.signal};for(let e of[`pointerdown`,`keydown`,`input`,`wheel`,`scroll`,`touchstart`,`touchmove`,`focusin`])document.addEventListener(e,h,_);document.addEventListener(`visibilitychange`,h,_),window.addEventListener(`blur`,h,_),window.addEventListener(`focus`,h,_),r.addEventListener(`change`,h,_);let v=new MutationObserver(h);for(let e of document.querySelectorAll(`dialog`))v.observe(e,{attributes:!0,attributeFilter:[`open`]});let y=new IntersectionObserver(([e])=>{o=e.isIntersecting,h()});return y.observe(e),{reset:h,setEnabled(e){e!==a&&(a=e,h())},dispose(){s=!0,p(),clearTimeout(c),i.abort(),v.disconnect(),y.disconnect(),n.remove()}}}var Bg=e=>nd(String(e??``)).replace(/\r\n?/g,` `).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,``),Vg=[{value:`/help`,label:`/help`,description:`Browser terminal commands`},{value:`/load`,label:`/load`,description:`Load MiniCPM on this device`},{value:`/new`,label:`/new`,description:`Start a new conversation; keep files`},{value:`/clear`,label:`/clear`,description:`Same as /new`}];function Hg(e,t){let n=new _s({fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13,lineHeight:1.3,theme:pg,cursorBlink:!1,scrollback:0,screenReaderMode:!0,allowProposedApi:!0});n.loadAddon(new yl);let r=document.createElement(`div`);r.className=`pi-terminal-mount`,e.append(r);let i=new bs;n.loadAddon(i),n.open(r);let a=new Sg(n),o=new Zf(a,!0,void 0,{copyOnSelect:!1,copySelection:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}},openUrl:e=>{/^https?:\/\//i.test(e)&&window.open(e,`_blank`,`noopener,noreferrer`)},scrollToEndIndicator:()=>Q.fg(`accent`,` ↓ Latest `),searchMatchStyle:e=>Q.bg(`selectedBg`,Q.fg(`text`,e)),searchCurrentMatchStyle:e=>Q.bg(`accent`,Q.fg(`userMessageBg`,Q.bold(e)))}),s=new nu({...eu,"app.interrupt":{defaultKeys:[`escape`,`ctrl+c`]},"app.exit":{defaultKeys:`ctrl+d`},"app.tools.expand":{defaultKeys:`ctrl+o`},"tui.editor.historyPrevious":{defaultKeys:`ctrl+p`},"tui.editor.historyNext":{defaultKeys:`ctrl+n`}});iu(s);let c=new lg(o,hg(),s,{paddingX:0}),l=new Nd,u=new rf(l,{follow:`end`,primary:!0,scrollbar:`auto`,scrollbarTrackStyle:e=>Q.fg(`borderMuted`,e),scrollbarThumbStyle:e=>Q.fg(`muted`,e)}),d=new bp(``,0,0),f=0,p=d.render.bind(d);d.render=e=>{let t=Math.min(f,Math.max(0,e-1)),n=p(e-t).map(e=>e+` `.repeat(t));return m.busy?[``,...n]:n},o.setLayoutRoot(new Jh([{component:u,basis:0,grow:1,minSize:0},{component:new Jh([d,c,{invalidate(){},render(e){let t=`/workspace · MiniCPM5-2B`,n=Ng(m.contextUsage),r=`${t} · ${n}`;return(r.length<=e-2?[r]:[t,n]).flatMap(t=>new bp(Q.fg(`dim`,t),1,0).render(e))}}]),basis:`auto`,shrink:0}])),o.setFocus(c);let m={loaded:!1,busy:!1,activity:``,contextUsage:Mg([])},h=[],g=[],_=!1,v=!1,y,b=!1,x=zg(e,()=>{let t=r.querySelector(`.xterm-screen`)?.getBoundingClientRect();if(!t||!n.rows)return;let i=e.getBoundingClientRect();return{left:t.left-i.left,top:t.top-i.top,width:t.width,height:t.height*u.viewportHeight/n.rows}}),S=Ig(e,e=>{m.busy||v||c.getText().trim()||(c.setText(e),n.focus(),o.requestRender())});function C(){x.setEnabled(b&&!m.busy&&!v&&!y);let e=r.querySelector(`.xterm-screen`);!b||g.some(e=>e.role===`user`)||m.busy||v?S.hide():S.update({screen:e,rows:n.rows,viewportRows:u.viewportHeight,contentRows:l.render(n.cols).length,draft:c.getText(),hasSales:h.includes(`sales.csv`),hasProducts:h.includes(`products.json`)||h.includes(`products.csv`)});let t=e?.getBoundingClientRect().width/n.cols,i=t>0?Math.ceil(S.statusInset/t):0;i!==f&&(f=i,o.requestRender())}let w=n.onRender(C),T=new Map,E=[],D=new Set,O=new Nd;O.addChild(new yp(Q.fg(`accent`,Q.bold(`π Pi`))+Q.fg(`muted`,` browser workspace`),1,1)),O.addChild(new yp(`Ask Pi to work with your files. /load load MiniCPM /help show commands !ls run a workspace command`,1,0)),O.addChild(new Kh(1));let k=new yp(Q.fg(`accent`,Q.bold(`π Pi`))+Q.fg(`muted`,` browser workspace`)+` Ask Pi to work with your files.`,1,0),ee=O.render.bind(O);O.render=e=>n.rows<30?k.render(e):ee(e);function te(e,t=!1){E.push({at:g.length,component:new yp(Q.fg(t?`error`:`muted`,Bg(e)),1,1)}),re(),o.scrollToBottom()}function ne(e){e&&!D.has(e)&&(D.add(e),c.addToHistory(e))}function A(e,t){let n=new Nd;n.addChild(new Kh(1));let r=new Gh(1,1,e=>Q.bg(t?t.isError?`toolErrorBg`:`toolSuccessBg`:`toolPendingBg`,e)),i=Q.fg(`toolTitle`,Q.bold(Bg(e.name)))+` `+Q.fg(`accent`,Bg(e.arguments?.path??e.arguments?.command??``));r.addChild(new yp(i,0,0));let a=Bg(JSON.stringify(e.arguments,null,2)),o=Bg(t?Ag(t.content):`Running…`).replace(/\n+$/,``),s=o.split(` `);return r.addChild(new yp(Q.fg(`toolOutput`,_?a+` `+o:s.slice(0,10).join(` `)),0,0)),!_&&s.length>10&&r.addChild(new yp(Q.fg(`dim`,`… ${s.length-10} more lines · Ctrl+O to expand`),0,0)),n.addChild(r),n}function re(){l.clear(),l.addChild(O);let e=new Map(g.filter(e=>e.role===`toolResult`).map(e=>[e.toolCallId,e])),t=new Set;for(let n=0;n<=g.length;n++){for(let e of E)e.at===n&&l.addChild(e.component);let r=g[n];if(!r||r.role===`toolResult`)continue;let i=r.role+`:`+r.timestamp+`:`+n;t.add(i);let a=T.get(i);if(a||(a={component:r.role===`user`?new yg(Bg(Ag(r.content))):new xg(void 0,!0)},T.set(i,a)),r.role===`user`&&ne(Ag(r.content)),r.role===`assistant`&&a.message!==r){let e={...r,content:r.content.map(e=>e.type===`text`?{...e,text:Bg(e.text)}:e.type===`thinking`?{...e,thinking:Bg(e.thinking)}:e),errorMessage:r.errorMessage?Bg(r.errorMessage):void 0};a.component.setHiddenThinkingLabel(r.stopReason?`Thoughts · click to expand`:`Thinking…`),a.component.updateContent(e,!r.stopReason)}r.role===`user`&&(n>0||E.length)&&l.addChild(new Kh(1)),a.message=r,l.addChild(a.component);for(let n of Array.isArray(r.content)?r.content:[]){if(n.type!==`toolCall`)continue;let r=e.get(n.id),i=`tool:`+n.id;t.add(i);let a=JSON.stringify([n,r,_]),o=T.get(i);o?.signature!==a&&(o={signature:a,component:A(n,r)},T.set(i,o)),l.addChild(o.component)}}for(let e of T.keys())t.has(e)||T.delete(e);y&&(l.addChild(new Kh(1)),l.addChild(y),l.addChild(new yp(Q.fg(`muted`,`Queued · sends when the model is ready`),1,0))),C(),o.requestRender()}function j(){d.text=Q.fg(m.busy?`accent`:`muted`,Bg(m.activity||(m.busy?``:m.loaded?`Ready`:`Send a message to get started · /help`))),c.disableSubmit=m.busy||v,c.borderColor=e=>Q.fg(m.busy?`accent`:`borderMuted`,e),t.onInput?.(c.getText()),o.requestRender(),C()}async function M(e){if(!(!e.trim()||m.busy||v)){v=!0,j(),ne(e),o.scrollToBottom();try{let n=e.trim();if(n===`/help`)te(`/load Load MiniCPM on this device /new Clear the conversation; keep workspace files !cmd Run cmd with just-bash Enter: send · Shift+Enter: newline ↑/↓: edit/history · Ctrl+P/N: history Esc or Ctrl+C: stop · Ctrl+O: expand tools Ctrl+Shift+F: search transcript Pi’s original terminal UI and agent core run here. Node CLI extensions, npm, Python and native binaries are unavailable.`);else if(n===`/load`)await t.load();else if(n===`/new`||n===`/clear`)await t.newChat(),E.length=0,re();else if(n.startsWith(`/`))throw Error(`Unknown browser command. Type /help for available commands.`);else if(n.startsWith(`!`)){let e=n.slice(1).trim();if(!e)throw Error(`Enter a shell command after !.`);let r=await t.shell(e);te(`$ ${e}\n${r.stdout}${r.stderr}\n[exit ${r.exitCode}]`,r.exitCode!==0)}else await t.prompt(e)}catch(t){t.name!==`AbortError`&&te(t.message,!0),c.getText()||c.setText(e)}finally{v=!1,j()}}}c.onSubmit=e=>{M(e)},c.onChange=()=>{t.onInput?.(c.getText()),o.requestRender()},c.onEscape=()=>{m.busy&&t.stop().catch(e=>te(e.message,!0))},c.onCtrlD=()=>te(`This terminal lives in your browser. Close the tab to leave.`),c.onAction(`app.tools.expand`,()=>{_=!_,re()}),c.setAutocompleteProvider({getSuggestions(e,t,n){let r=e[t].slice(0,n),i=r.match(/\S*$/)?.[0]??``;if(!i)return null;let a=(r.startsWith(`/`)?Vg:h.map(e=>({value:e,label:e,description:`workspace file`}))).filter(e=>e.value.startsWith(i)&&e.value!==i);return a.length?{items:a,prefix:i}:null},applyCompletion(e,t,n,r,i){let a=[...e];return a[t]=e[t].slice(0,n-i.length)+r.value+` `+e[t].slice(n),{lines:a,cursorLine:t,cursorCol:n-i.length+r.value.length+1}}}),n.attachCustomKeyEventHandler(e=>e.type!==`keydown`||e.isComposing?!0:(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`v`?!1:e.ctrlKey&&e.shiftKey&&e.code===`KeyF`?(e.preventDefault(),a.inputData(`\x1B[102;6u`),!1):e.key===`Enter`&&e.shiftKey?(e.preventDefault(),a.inputData(`\x1B\r`),!1):(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`c`&&(n.hasSelection()||o.hasActiveSelection())?(o.hasActiveSelection()&&(e.preventDefault(),o.copyActiveSelectionToClipboard()),!1):!0);let N;e.addEventListener(`touchstart`,e=>{e.touches.length===1&&(N=e.touches[0].clientY)},{passive:!0}),e.addEventListener(`touchmove`,e=>{if(N===void 0||e.touches.length!==1)return;let t=e.touches[0].clientY,n=Math.trunc((N-t)/18);n&&(o.scrollBy(n),N=t,e.preventDefault())},{passive:!1}),e.addEventListener(`touchend`,()=>{N=void 0},{passive:!0});function P(){x.reset(),e.clientWidth>0&&e.clientHeight>0&&(i.fit(),o.requestRender())}let ie=new ResizeObserver(P);return ie.observe(e),P(),o.start(),re(),j(),document.fonts.ready.then(P),n.textarea.setAttribute(`aria-label`,`Message Pi`),n.textarea.setAttribute(`autocapitalize`,`off`),n.textarea.setAttribute(`spellcheck`,`false`),{setMessages(e,{reset:t=!1}={}){b=!0,g=e,t&&(E.length=0,T.clear()),re()},setFiles(e){h=Object.keys(e).map(e=>e.replace(/^\/workspace\//,``)),C()},setState(e){m={...m,...e},j()},setQueuedPrompt(e){(e||y)&&(y=e?new yg(Bg(e)):void 0,re(),o.scrollToBottom())},submit(){let e=c.getExpandedText();if(!c.disableSubmit&&e.trim())return c.setText(``),M(e)},focus(){n.focus()},newline(){a.inputData(`\x1B\r`),n.focus()},get text(){return c.getExpandedText()},get cols(){return n.cols},get rows(){return n.rows},get viewportTop(){return o.viewportTop},readScreen(){return Array.from({length:n.buffer.active.length},(e,t)=>n.buffer.active.getLine(t)?.translateToString(!0)??``).join(` `)},readDocument(){return u.render(n.cols).map(e=>nd(e).trimEnd())},readCells(){return Array.from({length:n.rows},(e,t)=>Array.from({length:n.cols},(e,r)=>{let i=n.buffer.active.getLine(t)?.getCell(r);return i?{text:i.getChars(),width:i.getWidth(),fg:i.isFgDefault()?pg.foreground:i.getFgColor(),bg:i.isBgDefault()?pg.background:i.getBgColor()}:null}))},dispose(){ie.disconnect(),w.dispose(),S.dispose(),x.dispose(),o.stop({preserveScreen:!0}),n.dispose()}}}function Ug(e,{onClose:t}){let n=t=>e.querySelector(t),r=n(`#model-confirm`),i=n(`#model-cancel`),a=n(`#model-error`),o=n(`.setup-cat img`),s=o.parentElement,c=n(`.setup-cat-tail`),l=matchMedia(`(prefers-reduced-motion: reduce)`),u;function d(){u?.cancel(),u=void 0}s.onpointerdown=e=>e.preventDefault(),s.onmousedown=e=>e.preventDefault(),s.onclick=()=>{if(Fg(),!e.open||document.hidden||l.matches||!s.classList.contains(`is-ready`))return;let t=getComputedStyle(c).transform;d();let n=c.getAnimations().find(e=>e.animationName===`setup-tail-swish`);n&&(n.currentTime=0),u=c.animate([{transform:t},{transform:`rotate(-7deg)`,offset:.3},{transform:`rotate(4deg)`,offset:.6},{transform:`rotate(-1deg)`,offset:.82},{transform:`rotate(0deg)`}],{id:`cat-tail-reaction`,duration:1200,easing:`ease-in-out`}),u.onfinish=()=>{u=void 0}},e.addEventListener(`close`,d),o.decode().then(()=>{o.parentElement.style.setProperty(`--cat-sprite`,`url("${o.currentSrc||o.src}")`),o.parentElement.classList.add(`is-ready`)}).catch(()=>{});let f=()=>{e.style.setProperty(`--cat-play-state`,document.hidden?`paused`:`running`),(document.hidden||l.matches)&&d()};document.addEventListener(`visibilitychange`,f),l.addEventListener(`change`,f),f();let p;function m(n){if(!p)return;d();let r=p;p=void 0,e.close(),t(),r(n)}return i.onclick=()=>m(!1),e.addEventListener(`cancel`,e=>{e.preventDefault(),m(!1)}),r.onclick=()=>m(!0),{request(t,{errorMessage:i}={}){if(p)throw Error(`Finish the current model setup before sending another message.`);r.textContent=i?`Try again`:`Load model & send`,n(`#model-title`).textContent=i?`Load model`:`Download model weights`,n(`#model-preview`).textContent=t,a.textContent=i??``,a.hidden=!i;let o=document.querySelector(`#open-tab`);n(`#model-open-tab`).hidden=!i||o.hidden,n(`#model-open-tab`).href=o.href;let s=new Promise(e=>{p=e});return e.showModal(),n(`.setup-body`).scrollTop=0,r.focus(),s}}}var Wg=c(o(((e,t)=>{var n=function(e){var t=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,n=0,r={},i={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(t){return t instanceof a?new a(t.type,e(t.content),t.alias):Array.isArray(t)?t.map(e):t.replace(/&/g,`&`).replace(/`u`)return null;if(document.currentScript&&document.currentScript.tagName===`SCRIPT`)return document.currentScript;try{throw Error()}catch(r){var e=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack)||[])[1];if(e){var t=document.getElementsByTagName(`script`);for(var n in t)if(t[n].src==e)return t[n]}return null}},isActive:function(e,t,n){for(var r=`no-`+t;e;){var i=e.classList;if(i.contains(t))return!0;if(i.contains(r))return!1;e=e.parentElement}return!!n}},languages:{plain:r,plaintext:r,text:r,txt:r,extend:function(e,t){var n=i.util.clone(i.languages[e]);for(var r in t)n[r]=t[r];return n},insertBefore:function(e,t,n,r){r||=i.languages;var a=r[e],o={};for(var s in a)if(a.hasOwnProperty(s)){if(s==t)for(var c in n)n.hasOwnProperty(c)&&(o[c]=n[c]);n.hasOwnProperty(s)||(o[s]=a[s])}var l=r[e];return r[e]=o,i.languages.DFS(i.languages,function(t,n){n===l&&t!=e&&(this[t]=o)}),o},DFS:function e(t,n,r,a){a||={};var o=i.util.objId;for(var s in t)if(t.hasOwnProperty(s)){n.call(t,s,t[s],r||s);var c=t[s],l=i.util.type(c);l===`Object`&&!a[o(c)]?(a[o(c)]=!0,e(c,n,null,a)):l===`Array`&&!a[o(c)]&&(a[o(c)]=!0,e(c,n,s,a))}}},plugins:{},highlightAll:function(e,t){i.highlightAllUnder(document,e,t)},highlightAllUnder:function(e,t,n){var r={callback:n,container:e,selector:`code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code`};i.hooks.run(`before-highlightall`,r),r.elements=Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)),i.hooks.run(`before-all-elements-highlight`,r);for(var a=0,o;o=r.elements[a++];)i.highlightElement(o,t===!0,r.callback)},highlightElement:function(t,n,r){var a=i.util.getLanguage(t),o=i.languages[a];i.util.setLanguage(t,a);var s=t.parentElement;s&&s.nodeName.toLowerCase()===`pre`&&i.util.setLanguage(s,a);var c={element:t,language:a,grammar:o,code:t.textContent};function l(e){c.highlightedCode=e,i.hooks.run(`before-insert`,c),c.element.innerHTML=c.highlightedCode,i.hooks.run(`after-highlight`,c),i.hooks.run(`complete`,c),r&&r.call(c.element)}if(i.hooks.run(`before-sanity-check`,c),s=c.element.parentElement,s&&s.nodeName.toLowerCase()===`pre`&&!s.hasAttribute(`tabindex`)&&s.setAttribute(`tabindex`,`0`),!c.code){i.hooks.run(`complete`,c),r&&r.call(c.element);return}if(i.hooks.run(`before-highlight`,c),!c.grammar){l(i.util.encode(c.code));return}if(n&&e.Worker){var u=new Worker(i.filename);u.onmessage=function(e){l(e.data)},u.postMessage(JSON.stringify({language:c.language,code:c.code,immediateClose:!0}))}else l(i.highlight(c.code,c.grammar,c.language))},highlight:function(e,t,n){var r={code:e,grammar:t,language:n};if(i.hooks.run(`before-tokenize`,r),!r.grammar)throw Error(`The language "`+r.language+`" has no grammar.`);return r.tokens=i.tokenize(r.code,r.grammar),i.hooks.run(`after-tokenize`,r),a.stringify(i.util.encode(r.tokens),r.language)},tokenize:function(e,t){var n=t.rest;if(n){for(var r in n)t[r]=n[r];delete t.rest}var i=new c;return l(i,i.head,e),s(e,i,t,i.head,0),d(i)},hooks:{all:{},add:function(e,t){var n=i.hooks.all;n[e]=n[e]||[],n[e].push(t)},run:function(e,t){var n=i.hooks.all[e];if(n&&n.length)for(var r=0,a;a=n[r++];)a(t)}},Token:a};e.Prism=i;function a(e,t,n,r){this.type=e,this.content=t,this.alias=n,this.length=(r||``).length|0}a.stringify=function e(t,n){if(typeof t==`string`)return t;if(Array.isArray(t)){var r=``;return t.forEach(function(t){r+=e(t,n)}),r}var a={type:t.type,content:e(t.content,n),tag:`span`,classes:[`token`,t.type],attributes:{},language:n},o=t.alias;o&&(Array.isArray(o)?Array.prototype.push.apply(a.classes,o):a.classes.push(o)),i.hooks.run(`wrap`,a);var s=``;for(var c in a.attributes)s+=` `+c+`="`+(a.attributes[c]||``).replace(/"/g,`"`)+`"`;return`<`+a.tag+` class="`+a.classes.join(` `)+`"`+s+`>`+a.content+``};function o(e,t,n,r){e.lastIndex=t;var i=e.exec(n);if(i&&r&&i[1]){var a=i[1].length;i.index+=a,i[0]=i[0].slice(a)}return i}function s(e,t,n,r,c,d){for(var f in n)if(n.hasOwnProperty(f)&&n[f]){var p=n[f];p=Array.isArray(p)?p:[p];for(var m=0;m=d.reach);C+=S.value.length,S=S.next){var w=S.value;if(t.length>e.length)return;if(!(w instanceof a)){var T=1,E;if(v){if(E=o(x,C,e,_),!E||E.index>=e.length)break;var D=E.index,O=E.index+E[0].length,k=C;for(k+=S.value.length;D>=k;)S=S.next,k+=S.value.length;if(k-=S.value.length,C=k,S.value instanceof a)continue;for(var ee=S;ee!==t.tail&&(kd.reach&&(d.reach=re);var j=S.prev;ne&&(j=l(t,j,ne),C+=ne.length),u(t,j,T);var M=new a(f,g?i.tokenize(te,g):te,y,te);if(S=l(t,j,M),A&&l(t,S,A),T>1){var N={cause:f+`,`+m,reach:re};s(e,t,n,S.prev,C,N),d&&N.reach>d.reach&&(d.reach=N.reach)}}}}}}function c(){var e={value:null,prev:null,next:null},t={value:null,prev:e,next:null};e.next=t,this.head=e,this.tail=t,this.length=0}function l(e,t,n){var r=t.next,i={value:n,prev:t,next:r};return t.next=i,r.prev=i,e.length++,i}function u(e,t,n){for(var r=t.next,i=0;i>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp(`(\\{)`+t),lookbehind:!0,alias:`constant`}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:`important`},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:`function`},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:`function`}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:`variable`,lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp(`(^|[\\s;|&]|[<>]\\()`+t),lookbehind:!0,alias:`constant`}},alias:`variable`,lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:`variable`,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:r},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:n}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:r},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:r.entity}}],environment:{pattern:RegExp(`\\$?`+t),alias:`constant`},variable:r.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:`class-name`},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:`important`},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:`important`}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},n.inside=e.languages.bash;for(var i=[`comment`,`function-name`,`for-or-select`,`assign-left`,`parameter`,`string`,`environment`,`function`,`keyword`,`builtin`,`boolean`,`file-descriptor`,`operator`,`punctuation`,`number`],a=r.variable[1].inside,o=0;ond(String(e??``)).replace(/\r\n?/g,` `).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,``),Kg=24e3;function qg(e){return e=Gg(e),e.length>Kg?e.slice(0,Kg)+` … output truncated; use head or grep to narrow it down.`:e}function Jg(e){let t=document.createDocumentFragment();function n(e,t){if(typeof t==`string`){e.append(document.createTextNode(t));return}if(Array.isArray(t)){t.forEach(t=>n(e,t));return}let r=document.createElement(`span`);r.className=[`token`,t.type,...[t.alias??[]].flat()].join(` `),n(r,t.content),e.append(r)}return n(t,e.length>8192?e:Wg.default.tokenize(e,Wg.default.languages.bash)),t}function Yg(e,{run:t}){let n=t=>e.querySelector(t),r=n(`#command`),i=n(`#command-highlight`),a=n(`#terminal-output`),o=n(`#shell-form`),s=n(`#shell-run`),c=n(`#shell-clear`),l=a.firstElementChild.cloneNode(!0),u=[],d=[],f=0,p=``,m=!1,h=!1,g=()=>a.scrollHeight-a.scrollTop-a.clientHeight<24,_=()=>{a.scrollTop=a.scrollHeight};function v(){s.disabled=m||h||!r.value.trim(),s.textContent=m?`Running…`:`Run`,c.disabled=m||d.length===0}function y(){i.replaceChildren(Jg(r.value),document.createTextNode(` `)),r.style.height=`auto`,r.style.height=Math.min(104,Math.max(32,r.scrollHeight))+`px`,i.scrollTop=r.scrollTop,i.scrollLeft=r.scrollLeft,v()}function b(e){r.value=e,y(),r.setSelectionRange(e.length,e.length)}function x(){m||(d.length=0,a.replaceChildren(l.cloneNode(!0)),v())}function S(e,t,n){if(!t)return;let r=document.createElement(`pre`);r.className=n,r.textContent=qg(t),e.append(r)}o.onsubmit=async e=>{e.preventDefault();let n=r.value;if(m||h||!n.trim())return;m=!0,u.at(-1)!==n&&u.push(n),u.length>50&&u.shift(),f=u.length,p=``,b(``),r.focus(),d.length||a.replaceChildren();let i=document.createElement(`section`);i.className=`shell-entry`;let o=document.createElement(`div`);o.className=`shell-entry-heading`;let s=document.createElement(`span`);s.className=`shell-prompt`,s.textContent=`$`;let c=document.createElement(`pre`);c.className=`shell-code`,c.append(Jg(qg(n)));let l=document.createElement(`span`);l.className=`shell-status`,l.textContent=`Running…`,o.append(s,c,l),i.append(o),a.append(i),d.push(i),_();try{let e=await t(n),r=g();S(i,e.stdout,`shell-stdout`),S(i,e.stderr,`shell-stderr`),l.classList.add(e.exitCode===0?`success`:`error`),l.textContent=`[exit ${e.exitCode}]`,r&&_()}catch(e){let t=g();S(i,e.message,`shell-stderr`),l.classList.add(`error`),l.textContent=`[error]`,r.value||b(n),t&&_()}finally{for(;d.length>1&&(d.length>40||a.textContent.length>48e3);)d.shift().remove();m=!1,v()}},r.addEventListener(`input`,()=>{f=u.length,p=r.value,y()}),r.addEventListener(`scroll`,()=>{i.scrollTop=r.scrollTop,i.scrollLeft=r.scrollLeft}),r.addEventListener(`keydown`,e=>{if(e.isComposing||e.keyCode===229)return;if(e.key===`Enter`&&!e.shiftKey){e.preventDefault(),o.requestSubmit();return}if(e.ctrlKey&&e.key.toLowerCase()===`l`){e.preventDefault(),x();return}if(e.ctrlKey||e.altKey||e.metaKey||e.shiftKey||r.selectionStart!==r.selectionEnd)return;let t=!r.value.slice(0,r.selectionStart).includes(` `),n=!r.value.slice(r.selectionEnd).includes(` `);e.key===`ArrowUp`&&t&&f>0?(e.preventDefault(),f===u.length&&(p=r.value),b(u[--f])):e.key===`ArrowDown`&&n&&f{x(),r.focus()};let C=0;return new ResizeObserver(([e])=>{e.contentRect.width!==C&&(C=e.contentRect.width,y())}).observe(r.parentElement),y(),{setBusy(e){h=e,v()}}}function Xg(e){let t=e.querySelector(`.runtime-value`),n=e.querySelector(`.runtime-sparkline`),r=e.querySelector(`.runtime-bars`),i=e.querySelector(`[role="status"]`),a=e.querySelector(`.runtime-engine`),o=e.querySelector(`.runtime-content`);new ResizeObserver(([t])=>{e.style.width=`calc(${Math.ceil(t.contentRect.width)}px + 2 * var(--runtime-padding))`}).observe(o);let s=!1,c,l=[],u;function d(o,s,d){clearTimeout(u),o!==c&&(i.textContent=d??`${s} in this browser.`),c=o,a.textContent=c===`tool`?`JavaScript`:`WebGPU`,e.dataset.state=c,t.textContent=s,n.setAttribute(`hidden`,``),e.title=d??`${s} in this browser.`,c!==`generating`&&(l=[],r.replaceChildren())}function f(){d(`idle`,s?`Ready`:`Idle`,s?`Model ready. Inference and tools run in this browser.`:`Model loads when you send a message. Inference and tools run in this browser.`)}function p(e){if(!Number.isFinite(e)||e<0){d(`generating`,`Generating…`);return}d(`generating`,`${e<10?e.toFixed(1):Math.round(e)} tok/s`,`Live token generation speed, including thinking tokens. Prompt-processing time is excluded.`),l.push(e),l.length>12&&l.shift();let t=Math.max(40,...l),i=[...Array(12-l.length).fill(null),...l];r.replaceChildren(...i.map((e,n)=>{if(e===null||e===0){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);return t.setAttribute(`cx`,String(n*4+1)),t.setAttribute(`cy`,`17`),t.setAttribute(`r`,`1`),t.setAttribute(`opacity`,e===null?`.35`:`.6`),t}let r=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`),i=Math.max(2,Math.min(16,e/t*16));return r.setAttribute(`x`,String(n*4)),r.setAttribute(`y`,(18-i).toFixed(2)),r.setAttribute(`width`,`2`),r.setAttribute(`height`,i.toFixed(2)),r.setAttribute(`rx`,`1`),r})),n.removeAttribute(`hidden`),u=setTimeout(()=>{d(`generating`,`Generating…`),l=[],r.replaceChildren()},2e3)}return f(),{update(e){e.type===`loaded`?(s=!0,f()):e.type===`idle`||e.type===`initialized`?f():e.type===`fatal`?(s=!1,d(`error`,`Unavailable`)):e.type===`busy`?e.action===`load`?d(`loading`,`Loading…`,e.cachedOnly?`Loading local model…`:void 0):e.action===`prompt`?d(`prefill`,`Reading prompt…`):e.action===`shell`?d(`tool`,`Running bash…`):e.action===`read`?d(`tool`,`Reading file…`):e.action===`write`?d(`tool`,`Writing file…`):d(`working`,`Working…`):e.type===`load_progress`?d(`loading`,e.phase===`download`&&e.loaded2e5)return!1;let t=1;for(let n=0;n5e3)return!1;return!0}function i_(e){let t=e.querySelector(`#editor`),n=e.querySelector(`#editor-highlight`),r=``,i=0,a,o,s,c=!1,l=!1,u;function d(){n.style.width=t.clientWidth+`px`,n.style.height=t.clientHeight+`px`,n.scrollTop=t.scrollTop,n.scrollLeft=t.scrollLeft}function f(){e.classList.remove(`is-highlighted`)}function p(){clearTimeout(o),s?.terminate(),s=void 0,c=!1}function m(){if(c||!u)return;let t=u;u=void 0;try{s||(s=new Worker(new URL(new URL(`editor-highlight.worker-oPpFVFqT.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),s.onmessage=({data:t})=>{clearTimeout(o),c=!1,t.id===i&&t.html!==null&&(n.innerHTML=t.html+` `,d(),e.classList.add(`is-highlighted`)),m()},s.onerror=()=>{p(),u=void 0}),c=!0,s.postMessage(t),o=setTimeout(()=>{p(),m()},1500)}catch{p()}}function h(n=0){i++,clearTimeout(a),u=void 0,f();let o=n_(r),s=t.value;if(e.dataset.language=o??`plain`,l||!s||!o||!r_(s))return;let c=i;a=setTimeout(()=>{u={id:c,text:s,language:o},m()},n)}t.addEventListener(`input`,()=>h(80)),t.addEventListener(`compositionstart`,()=>{l=!0,h()}),t.addEventListener(`compositionend`,()=>{l=!1,h(80)}),t.addEventListener(`scroll`,d,{passive:!0});let g=new ResizeObserver(d);return g.observe(t),{setFile(e,n){if(r===e&&t.value===n)return;let i=r!==e;r=e,t.value!==n&&(t.value=n),i&&(t.scrollTop=0,t.scrollLeft=0),h()},dispose(){clearTimeout(a),p(),g.disconnect()}}}var a_=`pi-column-ratio`,o_=1/1.83;function s_(e,t){let n=matchMedia(`(min-width: 851px)`),r=getComputedStyle(e),i=parseFloat(r.getPropertyValue(`--conversation-min`)),a=parseFloat(r.getPropertyValue(`--workspace-min`)),o=o_,s,c=0;try{let e=Number(localStorage.getItem(a_));Number.isFinite(e)&&e>0&&e<1&&(o=e)}catch{}function l(){if(!n.matches)return;let r=e.getBoundingClientRect().width;if(!r)return;let s=Math.max(i,Math.min(r-a,r*o));e.style.setProperty(`--conversation-width`,`${s}px`);let c=Math.round(s/r*100);t.setAttribute(`aria-valuemin`,String(Math.round(i/r*100))),t.setAttribute(`aria-valuemax`,String(Math.round((r-a)/r*100))),t.setAttribute(`aria-valuenow`,String(c)),t.setAttribute(`aria-valuetext`,`Chat ${c}%, workspace ${100-c}%`)}function u(){try{localStorage.setItem(a_,String(o))}catch{}}function d(t){let n=e.getBoundingClientRect().width;o=Math.max(i,Math.min(n-a,t))/n,l()}function f(){cancelAnimationFrame(c),c=0,s&&d(s.x-e.getBoundingClientRect().left-s.offset)}function p(e){if(!s)return;e?f():(cancelAnimationFrame(c),c=0,o=s.initialRatio);let n=s.pointer;s=void 0,t.hasPointerCapture(n)&&t.releasePointerCapture(n),document.documentElement.classList.remove(`is-resizing-columns`),l(),e&&u()}function m(){p(!1),o=o_,l(),u()}t.addEventListener(`pointerdown`,r=>{if(!n.matches||r.button!==0||!r.isPrimary||s)return;r.preventDefault(),t.focus({preventScroll:!0});let i=e.querySelector(`.conversation`).getBoundingClientRect().right;s={pointer:r.pointerId,initialRatio:o,x:r.clientX,offset:r.clientX-i},t.setPointerCapture(r.pointerId),document.documentElement.classList.add(`is-resizing-columns`)}),t.addEventListener(`pointermove`,e=>{s&&e.pointerId===s.pointer&&(s.x=e.clientX,c||=requestAnimationFrame(f))}),t.addEventListener(`pointerup`,e=>{s&&e.pointerId===s.pointer&&(s.x=e.clientX,p(!0))}),t.addEventListener(`pointercancel`,()=>p(!1)),t.addEventListener(`lostpointercapture`,()=>p(!1)),t.addEventListener(`dblclick`,m),t.addEventListener(`keydown`,t=>{if(!n.matches)return;if(t.key===`Escape`&&s){t.preventDefault(),p(!1);return}if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`,`Enter`].includes(t.key))return;if(t.preventDefault(),t.key===`Enter`){m();return}p(!1);let r=e.querySelector(`.conversation`).getBoundingClientRect().width,i=t.shiftKey?48:16;d(t.key===`Home`?0:t.key===`End`?1/0:r+(t.key===`ArrowLeft`?-i:i)),u()}),window.addEventListener(`blur`,()=>p(!1)),n.addEventListener(`change`,()=>{p(!1),l()}),new ResizeObserver(l).observe(e),l()}var $=e=>document.querySelector(e);s_($(`main`),$(`#column-resizer`));var c_=new Worker(new URL(new URL(`agent.worker-CS8jL-AS.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),l_=new Map,u_=1,d_=!1,f_=!1,p_,m_=!1,h_={},g_=[],__,v_,y_=new Promise(e=>{__=e}),b_={events:[],generations:[],runtimeSamples:[],device:null,contextUsage:Mg([])},x_=Xg($(`#runtime-meter`)),S_=i_($(`.editor-input`)),C_=Hg($(`#pi-terminal`),{onInput:e=>$(`#send`).classList.toggle(`has-input`,!!e.trim()),load:()=>y_.then(I_),prompt:e=>y_.then(()=>L_(e)),newChat:()=>y_.then(R_),stop:()=>E_(`stop`),shell:e=>{if(m_)throw Error(`Save your file edits before running commands.`);return E_(`shell`,{command:e})}}),w_=Ug($(`#model-dialog`),{onClose:()=>C_.focus()}),T_=Yg($(`.workspace > .terminal`),{run:async e=>{if(await y_,m_)throw Error(`Save your file edits before running commands.`);if(d_)throw Error(`Wait for Pi to finish or stop the current task first.`);return E_(`shell`,{command:e})}});function E_(e,t){return new Promise((n,r)=>{let i=u_++;l_.set(i,{resolve:n,reject:r}),c_.postMessage({id:i,action:e,args:t})})}function D_(e){$(`#notice`).textContent=e,$(`#notice`).hidden=!e}function O_(e){return window.self===window.top||!/denied|storage directory access/i.test(e)?e:($(`#open-tab`).href=location.href,$(`#open-tab`).hidden=!1,`Your browser blocked storage in this embedded app. Open the workspace in a new tab to load the model and save files.`)}function k_(){$(`#load`).disabled=d_||f_,$(`#load`).classList.toggle(`is-loaded`,f_),f_?$(`#load`).textContent=`Loaded`:d_||($(`#load`).textContent=`Load model`),$(`#load`).title=$(`#load-status`).textContent+` `+$(`#load-detail`).textContent,$(`#send`).disabled=d_,$(`#newline`).disabled=d_,C_.setState({busy:d_,loaded:f_,activity:$(`#activity`).textContent}),$(`#stop`).hidden=!d_;for(let e of[`#new-chat`,`#add-file`,`#upload`])$(e).disabled=d_;T_.setBusy(d_),$(`#save`).disabled=d_||!p_||!m_,$(`#editor`).disabled=d_||!p_}function A_(){C_.setFiles(h_),$(`#files`).replaceChildren();for(let e of Object.keys(h_).sort()){let t=document.createElement(`button`),n=document.createElement(`span`);n.className=`file-name`,n.textContent=e.replace(/^\/workspace\//,``),t.append(e_(e),n),t.title=e,t.classList.toggle(`selected`,e===p_),t.onclick=()=>j_(e),$(`#files`).append(t)}p_&&!m_&&S_.setFile(p_,h_[p_]??``)}function j_(e){if(v_=void 0,m_){D_(`Save the open file before selecting another file.`);return}p_=e,$(`#filename`).textContent=e,$(`#filetype`).replaceChildren(e_(e)),A_(),k_()}function M_(){if(m_){v_=void 0;return}if(!v_||!Object.hasOwn(h_,v_))return;let e=v_,t=e!==p_;j_(e),t&&($(`#editor`).scrollTop=0,$(`#editor`).scrollLeft=0);let n=[...$(`#files`).children].find(t=>t.title===e);if(n){let e=n.getBoundingClientRect(),t=$(`#files`).getBoundingClientRect();e.topt.bottom&&($(`#files`).scrollTop+=e.bottom-t.bottom)}}function N_(){C_.setMessages(g_)}function P_(e){b_.contextUsage=e,C_.setState({contextUsage:e})}c_.onmessage=({data:e})=>{if(x_.update(e),e.type===`inference_activity`&&(b_.runtimeSamples.push(e),b_.runtimeSamples.length>160&&b_.runtimeSamples.shift()),e.type===`reply`){let t=l_.get(e.id);l_.delete(e.id),e.error?t?.reject(Object.assign(Error(e.error),{name:e.errorName||`Error`,code:e.errorCode})):t?.resolve(e.value)}else if(e.type===`initialized`)h_=e.files,g_=e.messages,A_(),N_(),P_(Mg(g_)),h_[`/workspace/README.md`]&&j_(`/workspace/README.md`),document.activeElement===document.body&&C_.focus(),__();else if(e.type===`busy`)e.action===`load`&&($(`#load`).textContent=`Loading…`),d_=!0,$(`#activity`).textContent=e.action===`prompt`?`Pi is working…`:e.action===`load`?e.cachedOnly?`Loading local model…`:`Loading model…`:`Working…`,k_();else if(e.type===`idle`)d_=!1,$(`#progress`).hidden=!0,$(`#activity`).textContent=f_?`Ready · running on your device`:`Files and chat are saved on this device.`,k_();else if(e.type===`workspace`)h_=e.files,A_(),M_();else if(e.type===`device`)b_.device=e.device;else if(e.type===`load_progress`)$(`#progress`).hidden=!1,e.phase===`download`?($(`#progress`).hidden=!1,$(`#progress`).value=e.loaded/e.total*100,$(`#load-status`).textContent=e.loaded===e.total?`Download verified. Preparing model…`:`Downloading model weights from Hugging Face…`,$(`#load-detail`).textContent=`${(e.loaded/1e9).toFixed(2)} / ${(e.total/1e9).toFixed(2)} GB · ${Math.round(e.loaded/e.total*100)}%${e.cached?` · ${(e.cached/1e9).toFixed(2)} GB cached`:``}`,$(`#load`).textContent=`Loading ${Math.round(e.loaded/e.total*100)}%`):($(`#load-status`).textContent=e.phase===`compile`?`Preparing WebGPU session…`:`Warming up GPU shaders…`,$(`#load-detail`).textContent=``,$(`#progress`).removeAttribute(`value`),$(`#load`).textContent=e.phase===`compile`?`Preparing…`:`Almost ready…`),$(`#load`).title=$(`#load-status`).textContent+` `+$(`#load-detail`).textContent;else if(e.type===`loaded`)f_=!0,b_.device=e.device,$(`#progress`).hidden=!0,$(`#load`).textContent=`Loaded`,$(`#load-status`).textContent=`Ready. Model inference and tools run entirely in this browser.`,$(`#load-detail`).textContent=e.cachedBytes?`Verified model restored from browser storage.`:`SHA-256 verified · model cached for next time.`,k_();else if(e.type===`agent_event`){let t=e.event;if(b_.events.push(t.type),b_.events.length>500&&b_.events.shift(),t.message){let e=g_.findIndex(e=>e.timestamp===t.message.timestamp&&e.role===t.message.role&&e.toolCallId===t.message.toolCallId);e<0?g_.push(t.message):g_[e]=t.message,N_()}t.type===`tool_execution_start`&&($(`#activity`).textContent=`Running ${t.toolName}…`),t.type===`tool_execution_end`&&t.toolName===`read`&&!t.isError&&typeof t.result?.details?.path==`string`&&(v_=t.result.details.path,M_()),t.type===`turn_start`&&($(`#activity`).textContent=`Pi is thinking…`),C_.setState({activity:$(`#activity`).textContent})}else e.type===`context_usage`?P_({inputTokens:e.inputTokens,outputTokens:e.outputTokens}):e.type===`generation`?(b_.generations.push(e),b_.generations.length>100&&b_.generations.shift()):e.type===`context_trim`?D_(`Older turns were left out of the model context. Your full chat remains saved.`):e.type===`notice`?D_(e.text):e.type===`persistence_error`?D_(O_(e.error)):e.type===`fatal`&&(f_=!1,D_(e.error),k_())},c_.onerror=e=>{x_.update({type:`fatal`});let t=Error(e.message||`The worker stopped. Reload to restore your saved workspace.`);D_(t.message);for(let e of l_.values())e.reject(t);l_.clear(),d_=!1,f_=!1,$(`#progress`).hidden=!0,k_()};var F_=e=>async t=>{t?.preventDefault();try{await y_,await e(t)}catch(e){D_(e.message)}};async function I_({cachedOnly:e=!1}={}){if(d_)throw Error(`Wait for the current operation or stop it first.`);D_(``);let t=new URLSearchParams(location.search);d_=!0,$(`#load`).textContent=`Loading…`,$(`#activity`).textContent=e?`Loading local model…`:`Loading model…`,$(`#load-status`).textContent=e?`Loading local model…`:`Checking your browser and saved model…`,$(`#load-detail`).textContent=``,$(`#progress`).hidden=!1,$(`#progress`).removeAttribute(`value`),x_.update({type:`busy`,action:`load`,cachedOnly:e}),k_();try{return await E_(`load`,{runtimeURL:new URL(`./runtime/`,location.href).href,local:t.get(`source`)===`local`,origin:location.origin,limit128:t.has(`limit128`),cachedOnly:e})}catch(e){throw e.message=O_(e.message),$(`#load-status`).textContent=e.message,$(`#progress`).hidden=!0,e}}async function L_(e){if(e.trim()){if(m_)throw Error(`Save your file edits before asking Pi to work on them.`);try{if(!f_){let t;if(await E_(`cache_status`))try{C_.setQueuedPrompt(e),await I_({cachedOnly:!0})}catch(e){if(e.name===`AbortError`)throw e;e.code!==`MODEL_CACHE_MISS`&&(t=e.message)}for(;!f_;){if(C_.setQueuedPrompt(``),!await w_.request(e,{errorMessage:t}))throw new DOMException(`Message kept for later.`,`AbortError`);C_.setQueuedPrompt(e);try{await I_()}catch(e){if(e.name===`AbortError`)throw e;t=e.message}}}C_.setQueuedPrompt(``),D_(``);let t=await E_(`prompt`,{text:e});return g_=t.messages,N_(),t}finally{C_.setQueuedPrompt(``)}}}$(`#load`).onclick=F_(I_),$(`#send`).onclick=()=>{C_.submit(),C_.focus()},$(`#newline`).onclick=()=>C_.newline(),$(`#stop`).onclick=F_(()=>E_(`stop`)),$(`.terminal-panel`).addEventListener(`click`,e=>{!e.defaultPrevented&&e.button===0&&e.target instanceof Element&&(e.target.closest(`#pi-terminal, button, a, input, textarea, select, label, summary, [role="button"], [contenteditable]`)||window.getSelection()?.isCollapsed!==!1&&C_.focus())});async function R_(){v_=void 0,g_=(await E_(`new_chat`)).messages,P_(Mg(g_)),C_.setMessages(g_,{reset:!0}),D_(``),C_.focus()}$(`#new-chat`).onclick=F_(R_),$(`#editor`).oninput=()=>{m_=!0,k_()},$(`#save`).onclick=F_(async()=>{await E_(`write`,{path:p_,content:$(`#editor`).value}),m_=!1,A_(),k_(),D_(``)}),$(`#add-file`).onclick=F_(async()=>{if(m_)throw Error(`Save the open file first.`);let e=window.prompt(`File path, relative to /workspace:`);if(!e?.trim())return;let t=e.startsWith(`/`)?e:`/workspace/`+e;if(Object.hasOwn(h_,t))throw Error(`That file already exists.`);await E_(`write`,{path:t,content:``}),j_(t)}),$(`#upload`).onchange=F_(async()=>{if(m_)throw Error(`Save the open file first.`);for(let e of $(`#upload`).files){if(e.size>1024**2)throw Error(`Import text files of 1 MiB or less.`);let t=await e.text();if(t.includes(`\0`))throw Error(`Import supports text files only.`);let n=`/workspace/`+e.name;if(Object.hasOwn(h_,n))throw Error(e.name+` already exists. Rename it before importing.`);await E_(`write`,{path:n,content:t}),j_(n)}$(`#upload`).value=``}),$(`#export`).onclick=F_(async()=>{let e=await E_(`snapshot`),t=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:`application/json`})),n=document.createElement(`a`);n.href=t,n.download=`pi-workspace.json`,n.click(),setTimeout(()=>URL.revokeObjectURL(t),1e3)}),window.browserPi={ready:y_,load:I_,prompt:L_,rpc:E_,diagnostics:b_,terminal:C_,runtimeMeter:x_,get loaded(){return f_},get busy(){return d_}},k_();