brsh 2.8.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/release.yml +3 -1
- package/CHANGELOG.md +32 -0
- package/POSIX-CHECKLIST.md +3 -3
- package/Readme.md +138 -223
- package/bin/Readme.md +70 -24
- package/bin/brsh-shell.js +16 -131
- package/bin/exportFileSystem.js +4 -0
- package/bin/zsh-server.js +261 -0
- package/dist/brsh.css +1 -1
- package/dist/shell.es.js +1020 -648
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +34 -19
- package/dist/shell.min.js.map +1 -1
- package/dist/terminal.cjs.js +77 -100
- package/dist/terminal.cjs.js.map +1 -1
- package/dist/terminal.es.js +1382 -603
- package/dist/terminal.es.js.map +1 -1
- package/dist/terminal.min.js +77 -100
- package/dist/terminal.min.js.map +1 -1
- package/dist/wbt.es.js +410 -238
- package/dist/wbt.es.js.map +1 -1
- package/dist/wbt.min.js +10 -8
- package/dist/wbt.min.js.map +1 -1
- package/index.js +472 -0
- package/lib/Command.js +30 -0
- package/lib/InteractiveCommand.js +28 -0
- package/lib/Readme.md +111 -12
- package/lib/ReplCommand.js +15 -0
- package/lib/Terminal.js +769 -510
- package/lib/TtyStream.js +181 -0
- package/lib/WasmCommand.js +26 -5
- package/lib/builtins/cat.js +2 -2
- package/lib/builtins/grep.js +2 -2
- package/lib/local/clear.js +3 -0
- package/lib/terminal/DomRenderer.js +325 -0
- package/lib/terminal/PtyBridge.js +169 -0
- package/lib/terminal/ScreenBuffer.js +594 -0
- package/lib/terminal/VtParser.js +728 -0
- package/lib/wbt/index.js +3 -2
- package/lib/wbt/registry.js +15 -1
- package/package.json +4 -2
- package/styles/terminal.css +33 -4
- package/test/terminal.test.js +762 -40
- package/test/wbt.test.js +92 -0
package/dist/terminal.cjs.js
CHANGED
|
@@ -1,101 +1,78 @@
|
|
|
1
|
-
"use strict";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;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require("brsh");l=c(l);var u=c(o((e=>{(function(t,n){if(typeof define==`function`&&define.amd)define([`exports`],n);else if(typeof e==`object`&&typeof e.nodeName!=`string`)n(e);else{var r={};n(r),t.AnsiUp=r.default}})(e,function(e){var t=this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},n;(function(e){e[e.EOS=0]=`EOS`,e[e.Text=1]=`Text`,e[e.Incomplete=2]=`Incomplete`,e[e.ESC=3]=`ESC`,e[e.Unknown=4]=`Unknown`,e[e.SGR=5]=`SGR`,e[e.OSCURL=6]=`OSCURL`})(n||={});var r=function(){function e(){this.VERSION=`5.0.1`,this.setup_palettes(),this._use_classes=!1,this.bold=!1,this.underline=!1,this.italic=!1,this.fg=this.bg=null,this._buffer=``,this._url_whitelist={http:1,https:1}}return Object.defineProperty(e.prototype,"use_classes",{get:function(){return this._use_classes},set:function(e){this._use_classes=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"url_whitelist",{get:function(){return this._url_whitelist},set:function(e){this._url_whitelist=e},enumerable:!1,configurable:!0}),e.prototype.setup_palettes=function(){var e=this;this.ansi_colors=[[{rgb:[0,0,0],class_name:`ansi-black`},{rgb:[187,0,0],class_name:`ansi-red`},{rgb:[0,187,0],class_name:`ansi-green`},{rgb:[187,187,0],class_name:`ansi-yellow`},{rgb:[0,0,187],class_name:`ansi-blue`},{rgb:[187,0,187],class_name:`ansi-magenta`},{rgb:[0,187,187],class_name:`ansi-cyan`},{rgb:[255,255,255],class_name:`ansi-white`}],[{rgb:[85,85,85],class_name:`ansi-bright-black`},{rgb:[255,85,85],class_name:`ansi-bright-red`},{rgb:[0,255,0],class_name:`ansi-bright-green`},{rgb:[255,255,85],class_name:`ansi-bright-yellow`},{rgb:[85,85,255],class_name:`ansi-bright-blue`},{rgb:[255,85,255],class_name:`ansi-bright-magenta`},{rgb:[85,255,255],class_name:`ansi-bright-cyan`},{rgb:[255,255,255],class_name:`ansi-bright-white`}]],this.palette_256=[],this.ansi_colors.forEach(function(t){t.forEach(function(t){e.palette_256.push(t)})});for(var t=[0,95,135,175,215,255],n=0;n<6;++n)for(var r=0;r<6;++r)for(var i=0;i<6;++i){var a={rgb:[t[n],t[r],t[i]],class_name:`truecolor`};this.palette_256.push(a)}for(var o=8,s=0;s<24;++s,o+=10){var c={rgb:[o,o,o],class_name:`truecolor`};this.palette_256.push(c)}},e.prototype.escape_txt_for_html=function(e){return e.replace(/[&<>"']/gm,function(e){if(e===`&`)return`&`;if(e===`<`)return`<`;if(e===`>`)return`>`;if(e===`"`)return`"`;if(e===`'`)return`'`})},e.prototype.append_buffer=function(e){var t=this._buffer+e;this._buffer=t},e.prototype.get_next_packet=function(e){e===void 0&&(e=this);var r={kind:n.EOS,text:``,url:``},o=e._buffer.length;if(o==0)return r;var s=e._buffer.indexOf(`\x1B`);if(s==-1)return r.kind=n.Text,r.text=e._buffer,e._buffer=``,r;if(s>0)return r.kind=n.Text,r.text=e._buffer.slice(0,s),e._buffer=e._buffer.slice(s),r;if(s==0){if(o==1)return r.kind=n.Incomplete,r;var c=e._buffer.charAt(1);if(c!=`[`&&c!=`]`)return r.kind=n.ESC,r.text=e._buffer.slice(0,1),e._buffer=e._buffer.slice(1),r;if(c==`[`){this._csi_regex||=i(t([`
|
|
2
|
-
|
|
3
|
-
#
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
(
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
)
|
|
79
|
-
`],[`
|
|
80
|
-
^ # beginning of line
|
|
81
|
-
#
|
|
82
|
-
\\x1b\\]8; # OSC Hyperlink
|
|
83
|
-
[\\x20-\\x3a\\x3c-\\x7e]* # params (excluding ;)
|
|
84
|
-
; # end of params
|
|
85
|
-
([\\x21-\\x7e]{0,512}) # URL capture
|
|
86
|
-
(?: # ST
|
|
87
|
-
(?:\\x1b\\\\) # ESC \\
|
|
88
|
-
| # alternate
|
|
89
|
-
(?:\\x07) # BEL (what xterm did)
|
|
90
|
-
)
|
|
91
|
-
([^\\x07]+?) # TEXT capture
|
|
92
|
-
\\x1b\\]8;; # OSC Hyperlink End
|
|
93
|
-
(?: # ST
|
|
94
|
-
(?:\\x1b\\\\) # ESC \\
|
|
95
|
-
| # alternate
|
|
96
|
-
(?:\\x07) # BEL (what xterm did)
|
|
97
|
-
)
|
|
98
|
-
`]));var l=e._buffer.match(this._osc_regex);if(l===null)return r.kind=n.ESC,r.text=e._buffer.slice(0,1),e._buffer=e._buffer.slice(1),r;r.kind=n.OSCURL,r.url=l[1],r.text=l[2];var u=l[0].length;return e._buffer=e._buffer.slice(u),r}}},e.prototype.ansi_to_html=function(e){return this.append_buffer(e),this.loop_over_packets()},e.prototype.loop_over_packets=function(e){e===void 0&&(e=this);for(var t=[];;){var r=this.get_next_packet(e);if(r.kind==n.EOS||r.kind==n.Incomplete)break;r.kind==n.ESC||r.kind==n.Unknown||(r.kind==n.Text?t.push(this.transform_to_html(this.with_state(r))):r.kind==n.SGR?this.process_ansi(r):r.kind==n.OSCURL&&t.push(this.process_hyperlink(r)))}return t.join(``)},e.prototype.with_state=function(e){return{bold:this.bold,underline:this.underline,italic:this.italic,fg:this.fg,bg:this.bg,text:e.text}},e.prototype.process_ansi=function(e){for(var t=e.text.split(`;`);t.length>0;){var n=t.shift(),r=parseInt(n,10);if(isNaN(r)||r===0)this.fg=this.bg=null,this.bold=!1,this.italic=!1,this.underline=!1;else if(r===1)this.bold=!0;else if(r===22)this.bold=!1;else if(r===4)this.underline=!0;else if(r===24)this.underline=!1;else if(r===3)this.italic=!0;else if(r===3)this.italic=!1;else if(r===39)this.fg=null;else if(r===49)this.bg=null;else if(r>=30&&r<38)this.fg=this.ansi_colors[0][r-30];else if(r>=40&&r<48)this.bg=this.ansi_colors[0][r-40];else if(r>=90&&r<98)this.fg=this.ansi_colors[1][r-90];else if(r>=100&&r<108)this.bg=this.ansi_colors[1][r-100];else if((r===38||r===48)&&t.length>0){var i=r===38,a=t.shift();if(a===`5`&&t.length>0){var o=parseInt(t.shift(),10);o>=0&&o<=255&&(i?this.fg=this.palette_256[o]:this.bg=this.palette_256[o])}if(a===`2`&&t.length>2){var s=parseInt(t.shift(),10),c=parseInt(t.shift(),10),l=parseInt(t.shift(),10);if(s>=0&&s<=255&&c>=0&&c<=255&&l>=0&&l<=255){var u={rgb:[s,c,l],class_name:`truecolor`};i?this.fg=u:this.bg=u}}}}},e.prototype.transform_to_html=function(e){var t=e.text;if(t.length===0||(t=this.escape_txt_for_html(t),!e.bold&&!e.underline&&!e.italic&&e.fg===null&&e.bg===null))return t;var n=[],r=[],i=e.fg,a=e.bg;e.bold&&n.push(`font-weight:bold`),e.underline&&n.push(`text-decoration:underline`),e.italic&&n.push(`font-style:italic`),this._use_classes?(i&&(i.class_name===`truecolor`?n.push(`color:rgb(`+i.rgb.join(`,`)+`)`):r.push(i.class_name+`-fg`)),a&&(a.class_name===`truecolor`?n.push(`background-color:rgb(`+a.rgb.join(`,`)+`)`):r.push(a.class_name+`-bg`))):(i&&n.push(`color:rgb(`+i.rgb.join(`,`)+`)`),a&&n.push(`background-color:rgb(`+a.rgb+`)`));var o=``,s=``;return r.length&&(o=` class="`+r.join(` `)+`"`),n.length&&(s=` style="`+n.join(`;`)+`"`),`<span`+s+o+`>`+t+`</span>`},e.prototype.process_hyperlink=function(e){var t=e.url.split(`:`);return t.length<1||!this._url_whitelist[t[0]]?``:`<a href="`+this.escape_txt_for_html(e.url)+`">`+this.sub_string_to_html(e.text)+`</a>`},e.prototype.sub_string_to_html=function(e){var t={_buffer:e+``};return this.loop_over_packets(t)},e}();function i(e){var t=e.raw[0].replace(/^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm,``);return new RegExp(t)}function a(e){var t=e.raw[0].replace(/^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm,``);return new RegExp(t,`g`)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=r})}))()),d=l.default?.default??l.default,f=u.default?.default??u.default,p=`/.brsh_history`,m=class{constructor(e){let{el:t,font:n=`Roboto Mono`,cursor:r=`none`,outputAnimation:i=`none`,animateSpeed:a=1,onExit:o=null,mobileInput:s=`click`,lineWrap:c=!1,command:l=null}=e;if(!t)throw Error("you must set `el` option");if(![`none`,`block`,`blink`].includes(r))throw Error(`cursor value must be one of: 'none', 'block', 'blink'`);if(![`none`,`type`].includes(i))throw Error(`outputAnimation value must be one of: 'none', 'type'`);if(!Number.isInteger(a)||a<1||a>20)throw Error(`animateSpeed value must be between 1 and 20`);this._exitFn=o,this._cursor=r,this._outputAnimation=i,this._animateSpeed=a,this._lineWrap=c,this._working=!0,this._pendingCommands=[];let u=null;if(e.Shell!==!1&&e.Shell!==null&&(u=e.Shell||typeof globalThis<`u`&&(globalThis.Shell||globalThis.shell)||(typeof d==`function`?d:null)),this.cli=e.cli||e.shell,!this.cli){if(!u)throw Error(`Shell is required by Terminal. Please import Shell from "brsh" or include shell.min.js before terminal.min.js.`);this.cli=new u(Object.assign({},e,{command:void 0}))}this._buffer=[],this._cursorPos=0,this._history=[],this._historyPos=null,this._savedInput=null,this._historyLoaded=!1,this._el=t,this._ansi=new f,this._ansi.use_classes=!0,this._ansi.url_whitelist={http:!0,https:!0,tel:!0,mailto:!0},this._setupDom(this._el,n),this._attachShellListeners(),l&&this.onCommand(l),s===`click`&&this._mobileInput()}sendKey(e,t={}){let{alt:n=!1,ctrl:r=!1}=t,i=this._setCurrentLine.bind(this);[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Home`,`End`,`Delete`].includes(e)||r&&[`a`,`e`,`u`,`k`].includes(e.toLowerCase())?this._navKeyEvent(i,{key:e,altKey:n,ctrlKey:r}):this._keyEvent(i,e)}onCommand(e){if(!this._currentLine){this.cli&&this.cli.suppressMotd(),this._pendingCommands.push(e);return}let t=this._setCurrentLine.bind(this);this._cursorPos=e.length,t(Array.from(e)),this.cli.onCommand(e)}_mobileInput(){let e=document.createElement(`input`);e.type=`text`,e.style.position=`absolute`,e.style.left=`-9999999px`,this._el.appendChild(e),this._mobileInputBuffer=``,this._el.addEventListener(`click`,()=>{e.focus()}),e.addEventListener(`keypress`,t=>{t.key===`Enter`&&(e.value=``,this._mobileInputBuffer=e.value)});let t=this._setCurrentLine.bind(this);e.addEventListener(`keyup`,n=>{if(n.key===`Unidentified`){if(e.value.length<this._mobileInputBuffer.length)this._keyEvent(t,`Backspace`);else if(e.value.length>this._mobileInputBuffer.length){let n=e.value[e.value.length-1];this._keyEvent(t,n.toLowerCase())}this._mobileInputBuffer=e.value}})}_setupDom(e,t=`Roboto Mono`){let n=document.createElement(`link`);n.href=`https://fonts.googleapis.com/css?family=${encodeURIComponent(t)}:ital,wght@0,400;0,700;1,400;1,700&display=swap`,n.rel=`stylesheet`,document.head.appendChild(n),this._cmdList=document.createElement(`ul`),this._cmdList.style.fontFamily=`'${t}', monospace`,this._cmdList.style.listStyle=`none`,this._cmdList.style.padding=`0`,this._lineWrap&&this._cmdList.classList.add(`terminal--wrap`),e.appendChild(this._cmdList),this._screen=document.createElement(`pre`),this._screen.className=`terminal__screen`,this._screen.style.fontFamily=`'${t}', monospace`,e.appendChild(this._screen),this._charMeasure=document.createElement(`span`),this._charMeasure.className=`terminal__char-measure`,this._charMeasure.style.fontFamily=`'${t}', monospace`,this._charMeasure.textContent=`X`,this._charMeasure.setAttribute(`aria-hidden`,`true`),e.appendChild(this._charMeasure),setTimeout(()=>this._measureAndSetSize(),0),document.fonts&&document.fonts.ready.then(()=>this._measureAndSetSize()),typeof ResizeObserver<`u`&&new ResizeObserver(()=>this._measureAndSetSize()).observe(e)}_newPrompt(e){typeof document>`u`||!this._cmdList||(this._progressLine=null,this._clearCursor(),this._currentLine=document.createElement(`li`),this._cmdList.appendChild(this._currentLine),e&&e(),this._autoScroll())}_print(e,t=`out`){if(typeof e==`string`&&e.startsWith(`\r`)){let n=e.slice(1);if(this._progressLine&&this._progressLine.parentNode===this._cmdList){this._progressLine.innerHTML=this._ansi.ansi_to_html(n),this._autoScroll();return}let r=document.createElement(`li`);r.classList.add(`terminal__line`),r.classList.add(t),r.innerHTML=this._ansi.ansi_to_html(n),this._cmdList.appendChild(r),this._progressLine=r,this._autoScroll();return}if(this._progressLine=null,this._outputAnimation===`none`){let n=document.createElement(`li`);n.classList.add(`terminal__line`),n.classList.add(t),n.innerHTML=this._ansi.ansi_to_html(e),this._cmdList.appendChild(n),this._autoScroll()}else this._animateType(e,t)}_autoScroll(){this._el.scrollTop+this._el.offsetHeight>=this._el.scrollHeight-50&&this._el.scrollTo(0,this._el.scrollHeight)}_animateType(e,t){if(this._animating)return requestAnimationFrame(this._animateType.bind(this,e,t));let n=document.createElement(`li`);n.classList.add(`terminal__line`),n.classList.add(t),this._cmdList.appendChild(n);let r;try{r=this._ansi.ansi_to_html(e)}catch{r=e}this._animating=n;let i=0,a=setInterval(()=>{r.charAt(i)===`<`&&(i=r.indexOf(`>`,i)),n.innerHTML=r.substr(0,i);let e=0;for(;e<this._animateSpeed;)i++,r.charAt(i)===`<`&&(i=r.indexOf(`>`,i)),e++;i>=r.length-1&&(n.innerHTML=r,clearInterval(a),delete this._animating),this._autoScroll()},10)}_clearOutput(){this._cmdList.querySelectorAll(`li`).forEach(e=>this._cmdList.removeChild(e))}_clearLine(e){this._cmdList.querySelectorAll(`li.terminal__line.${e}`).forEach(e=>this._cmdList.removeChild(e))}_setCurrentLine(e){let t=Math.min(this._cursorPos,e.length);for(;this._currentLine.firstChild;)this._currentLine.removeChild(this._currentLine.firstChild);let n=`${this.cli.getPrompt()} `;if(this._cursor!==`none`){let r=e.slice(0,t).join(``),i=t<e.length?e[t]:`\xA0`,a=e.slice(t+1).join(``);this._currentLine.appendChild(document.createTextNode(n+r));let o=document.createElement(`span`);o.textContent=i,o.classList.add(`terminal__cursor`),o.classList.add(this._cursor),this._currentLine.appendChild(o),a&&this._currentLine.appendChild(document.createTextNode(a))}else this._currentLine.innerText=`${n}${e.join(``)}`}_clearCursor(){if(this._cursor!==`none`){let e=document.querySelectorAll(`.terminal__cursor`);e.length&&e.forEach(e=>e.parentElement.removeChild(e))}}_statusCheck(e){if(e===(this.cli?.constructor?.STATUS_READY||d?.STATUS_READY||globalThis.Shell?.STATUS_READY||globalThis.shell?.STATUS_READY||`READY`)){if(this._interactive&&this._exitInteractiveMode(),this._working=!1,this._historyLoaded||=(this._loadHistory(),!0),this._animating)return requestAnimationFrame(this._statusCheck.bind(this,e));if(this._newPrompt(this._setCurrentLine.bind(this,this._buffer)),this._pendingCommands&&this._pendingCommands.length>0){let e=this._pendingCommands.shift();if(this._pendingCommands.length===0&&this.cli){let e=this.cli.context.getVar(`-`);e.includes(`c`)&&this.cli.context.setVar(`-`,e.replace(/c/g,``))}this.onCommand(e)}}else this._clearCursor(),this._working=!0}_loadHistory(){try{let e=this.cli.context.fs._getFileRaw(p);e&&typeof e==`string`&&e.length>0&&(this._history=e.split(`
|
|
99
|
-
`).filter(e=>e.length>0))}catch{}}_saveHistory(){try{this.cli.context.fs._setFileRaw(p,this._history.join(`
|
|
100
|
-
`),!0)}catch{}}_navigateHistory(e,t){if(this._history.length!==0){if(e===-1){if(this._historyPos===null)this._savedInput=[...this._buffer],this._historyPos=this._history.length-1;else if(this._historyPos>0)this._historyPos--;else return;this._buffer=Array.from(this._history[this._historyPos])}else{if(this._historyPos===null)return;this._historyPos<this._history.length-1?(this._historyPos++,this._buffer=Array.from(this._history[this._historyPos])):(this._historyPos=null,this._buffer=this._savedInput?[...this._savedInput]:[],this._savedInput=null)}this._cursorPos=this._buffer.length,t(this._buffer)}}_attachShellListeners(){this.cli.on(`status`,this._statusCheck.bind(this)),this.cli.on(`stdOut`,e=>{this._interactive?this._renderInteractiveScreen(e):this._print(e,`out`)}),this.cli.on(`stdErr`,e=>{this._interactive||this._print(e,`err`)}),this.cli.on(`clear`,()=>{this._clearOutput()}),this.cli.on(`interactive`,()=>{this._enterInteractiveMode()}),this.cli.on(`exit`,e=>{delete this.cli,typeof this._exitFn==`function`&&this._exitFn(e)}),this._listenForKeyEvents(this._setCurrentLine.bind(this),window)}_listenForKeyEvents(e,t){window.addEventListener(`keydown`,t=>{if(this._interactive){t.preventDefault();let e=this._buildInteractiveKey(t);e&&this.cli.onInput(e);return}if(t.keyCode===9&&t.preventDefault(),[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Home`,`End`,`Delete`].includes(t.key)){t.preventDefault(),this._navKeyEvent(e,t);return}t.ctrlKey&&[`a`,`e`,`u`,`k`].includes(t.key.toLowerCase())&&(t.preventDefault(),this._navKeyEvent(e,t))}),t.addEventListener(`keyup`,t=>{this._interactive||this._keyEvent(e,t.key)}),window.addEventListener(`paste`,t=>{if(t.preventDefault(),this._interactive)return;let n=(t.clipboardData||window.clipboardData).getData(`text`);if(!n)return;let r=n.split(/\r?\n/);r.forEach((t,n)=>{let i=t.split(``);this._buffer.splice(this._cursorPos,0,...i),this._cursorPos+=i.length,n<r.length-1&&this._keyEvent(e,`Enter`)}),e(this._buffer)})}_buildInteractiveKey(e){let t=e.key;return[`Control`,`Alt`,`Shift`,`Meta`].includes(t)?null:e.ctrlKey&&t.length===1?`^`+t.toUpperCase():t}_wordLeft(){let e=this._cursorPos;for(;e>0&&this._buffer[e-1]===` `;)e--;for(;e>0&&this._buffer[e-1]!==` `;)e--;return e}_wordRight(){let e=this._cursorPos,t=this._buffer.length;for(;e<t&&this._buffer[e]===` `;)e++;for(;e<t&&this._buffer[e]!==` `;)e++;return e}_navKeyEvent(e,t){if(this._working||this._animating)return;let n=t.key;n===`ArrowLeft`?(t.altKey?this._cursorPos=this._wordLeft():this._cursorPos>0&&this._cursorPos--,e(this._buffer)):n===`ArrowRight`?(t.altKey?this._cursorPos=this._wordRight():this._cursorPos<this._buffer.length&&this._cursorPos++,e(this._buffer)):n===`Home`||t.ctrlKey&&n.toLowerCase()===`a`?(this._cursorPos=0,e(this._buffer)):n===`End`||t.ctrlKey&&n.toLowerCase()===`e`?(this._cursorPos=this._buffer.length,e(this._buffer)):n===`Delete`?this._cursorPos<this._buffer.length&&(this._buffer.splice(this._cursorPos,1),e(this._buffer)):t.ctrlKey&&n.toLowerCase()===`u`?(this._buffer.splice(0,this._cursorPos),this._cursorPos=0,e(this._buffer)):t.ctrlKey&&n.toLowerCase()===`k`?(this._buffer.splice(this._cursorPos),e(this._buffer)):n===`ArrowUp`?this._navigateHistory(-1,e):n===`ArrowDown`&&this._navigateHistory(1,e)}_keyEvent(e,t){if(this._clearLine(`autoComplete`),!this.cli.onInput(t)){if(t.length===1)this._buffer.splice(this._cursorPos,0,t),this._cursorPos++,!this._working&&!this._animating&&e(this._buffer);else if(t===`Enter`&&!this._working){let e=this._buffer.join(``);this._buffer=[],this._cursorPos=0,this._historyPos=null,this._savedInput=null,e.trim()&&(this._history[this._history.length-1]!==e&&this._history.push(e),this._saveHistory()),this.cli.onCommand(e)}else if(t===`Backspace`)this._cursorPos>0&&(this._buffer.splice(this._cursorPos-1,1),this._cursorPos--,!this._working&&!this._animating&&e(this._buffer));else if(t===`Tab`&&!this._working&&!this._animating){let t=this._buffer.join(``).split(` `),n=t.pop(),r=this.cli.tabCompletion(n);if(r){let{options:n,path:i}=r;n.length===1?(t.push(`${i==null?``:i.concat(`/`)}${n[0]}`),this._buffer=t.join(` `).split(``)):this._print(n.join(` `),`autoComplete`),this._cursorPos=this._buffer.length,e(this._buffer)}}}}_enterInteractiveMode(){this._interactive=!0,this._cmdList.style.display=`none`,this._screen.style.display=`block`,this._clearCursor()}_exitInteractiveMode(){this._interactive=!1,this._screen.style.display=`none`,this._screen.innerHTML=``,this._cmdList.style.display=``}_renderInteractiveScreen(e){let t=e.replace(/\x1b\[\d*J/g,``).replace(/\x1b\[\d+;\d+H/g,``).replace(/\x1b\[H/g,``);try{this._screen.innerHTML=this._ansi.ansi_to_html(t)}catch{this._screen.textContent=t}}_measureAndSetSize(){if(!this._charMeasure||!this.cli)return;let e=this._charMeasure.getBoundingClientRect(),t=this._el.getBoundingClientRect();if(!e.width||!e.height||!t.width)return;let n=Math.max(1,Math.floor(t.width/e.width)),r=Math.max(1,Math.floor(t.height/e.height));(n!==this._lastCols||r!==this._lastRows)&&(this._lastCols=n,this._lastRows=r,this.cli.setTerminalSize(n,r))}};m.Terminal=m,typeof globalThis<`u`&&(globalThis.Terminal=m),module.exports=m;
|
|
1
|
+
"use strict";var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("brsh");c=s(c);function l(e=` `,t=null,n=null,r=0,i=null){return{ch:e,fg:t,bg:n,flags:r,link:i}}function u(e){return{ch:e.ch,fg:e.fg,bg:e.bg,flags:e.flags,link:e.link}}var d=class{constructor(e=80,t=24,n={}){this.cols=Math.max(1,e),this.rows=Math.max(1,t),this.maxScrollback=n.maxScrollback??1e3,this.convertEol=n.convertEol!==!1,this.scrollback=[],this.viewportOffset=0,this.primaryGrid=this._createGrid(this.cols,this.rows),this.altGrid=this._createGrid(this.cols,this.rows),this.isAltScreen=!1,this.cursorRow=0,this.cursorCol=0,this.pendingWrap=!1,this.cursorVisible=!0,this.autoWrap=!0,this.originMode=!1,this.scrollTop=0,this.scrollBottom=this.rows-1,this.curFg=null,this.curBg=null,this.curFlags=0,this.curLink=null,this._savedPrimary=null,this._savedCursorPrimary=null,this._savedCursorAlt=null,this.dirtyRows=new Set,this.fullRedrawNeeded=!0,this._markAllDirty()}get grid(){return this.isAltScreen?this.altGrid:this.primaryGrid}_createRow(e=this.cols,t=!1){let n=t?this.curFg:null,r=t?this.curBg:null,i=t?this.curFlags:0,a=Array(e);for(let t=0;t<e;t++)a[t]=l(` `,n,r,i,null);return a}_createGrid(e,t){let n=Array(t);for(let r=0;r<t;r++)n[r]=this._createRow(e,!1);return n}_markRowDirty(e){e>=0&&e<this.rows&&this.dirtyRows.add(e)}_markRangeDirty(e,t){let n=Math.max(0,e),r=Math.min(this.rows-1,t);for(let e=n;e<=r;e++)this.dirtyRows.add(e)}_markAllDirty(){this.fullRedrawNeeded=!0;for(let e=0;e<this.rows;e++)this.dirtyRows.add(e)}reset(){this.scrollback=[],this.viewportOffset=0,this.primaryGrid=this._createGrid(this.cols,this.rows),this.altGrid=this._createGrid(this.cols,this.rows),this.isAltScreen=!1,this.cursorRow=0,this.cursorCol=0,this.pendingWrap=!1,this.cursorVisible=!0,this.autoWrap=!0,this.originMode=!1,this.scrollTop=0,this.scrollBottom=this.rows-1,this.curFg=null,this.curBg=null,this.curFlags=0,this.curLink=null,this._savedPrimary=null,this._savedCursorPrimary=null,this._savedCursorAlt=null,this._markAllDirty()}resetAttributes(){this.curFg=null,this.curBg=null,this.curFlags=0}saveCursor(){let e={row:this.cursorRow,col:this.cursorCol,pendingWrap:this.pendingWrap,fg:this.curFg,bg:this.curBg,flags:this.curFlags,originMode:this.originMode,autoWrap:this.autoWrap};this.isAltScreen?this._savedCursorAlt=e:this._savedCursorPrimary=e}restoreCursor(){let e=this.isAltScreen?this._savedCursorAlt:this._savedCursorPrimary;e&&(this._markRowDirty(this.cursorRow),this.cursorRow=Math.min(this.rows-1,Math.max(0,e.row)),this.cursorCol=Math.min(this.cols-1,Math.max(0,e.col)),this.pendingWrap=!!e.pendingWrap,this.curFg=e.fg,this.curBg=e.bg,this.curFlags=e.flags,this.originMode=e.originMode,this.autoWrap=e.autoWrap,this._markRowDirty(this.cursorRow))}enterAltScreen(e=!0){this.isAltScreen||(this._savedPrimary={cursorRow:this.cursorRow,cursorCol:this.cursorCol,pendingWrap:this.pendingWrap,fg:this.curFg,bg:this.curBg,flags:this.curFlags,scrollTop:this.scrollTop,scrollBottom:this.scrollBottom,originMode:this.originMode,autoWrap:this.autoWrap},this.isAltScreen=!0,this.viewportOffset=0,this.scrollTop=0,this.scrollBottom=this.rows-1),e&&(this.altGrid=this._createGrid(this.cols,this.rows),this.cursorRow=0,this.cursorCol=0,this.pendingWrap=!1),this._markAllDirty()}exitAltScreen(){this.isAltScreen&&(this.isAltScreen=!1,this._savedPrimary?(this.cursorRow=Math.min(this.rows-1,Math.max(0,this._savedPrimary.cursorRow)),this.cursorCol=Math.min(this.cols-1,Math.max(0,this._savedPrimary.cursorCol)),this.pendingWrap=this._savedPrimary.pendingWrap,this.curFg=this._savedPrimary.fg,this.curBg=this._savedPrimary.bg,this.curFlags=this._savedPrimary.flags,this.scrollTop=Math.min(this.rows-1,this._savedPrimary.scrollTop),this.scrollBottom=Math.min(this.rows-1,Math.max(this.scrollTop,this._savedPrimary.scrollBottom)),this.originMode=this._savedPrimary.originMode,this.autoWrap=this._savedPrimary.autoWrap,this._savedPrimary=null):(this.scrollTop=0,this.scrollBottom=this.rows-1),this._markAllDirty())}setScrollRegion(e,t){let n=Math.max(1,e||1)-1,r=t?Math.min(this.rows,t)-1:this.rows-1;n<r&&n>=0&&r<this.rows?(this.scrollTop=n,this.scrollBottom=r):(this.scrollTop=0,this.scrollBottom=this.rows-1),this.setCursor(0,0)}setCursor(e,t){this._markRowDirty(this.cursorRow);let n=this.originMode?this.scrollTop:0,r=this.originMode?this.scrollBottom:this.rows-1,i=(this.originMode?this.scrollTop:0)+e;this.cursorRow=Math.max(n,Math.min(r,i)),this.cursorCol=Math.max(0,Math.min(this.cols-1,t)),this.pendingWrap=!1,this._markRowDirty(this.cursorRow)}moveCursorRelative(e,t){if(this._markRowDirty(this.cursorRow),e!==0){let t=this.cursorRow>=this.scrollTop&&this.cursorRow<=this.scrollBottom&&e<0?this.scrollTop:0,n=this.cursorRow>=this.scrollTop&&this.cursorRow<=this.scrollBottom&&e>0?this.scrollBottom:this.rows-1;this.cursorRow=Math.max(t,Math.min(n,this.cursorRow+e))}t!==0&&(this.cursorCol=Math.max(0,Math.min(this.cols-1,this.cursorCol+t))),this.pendingWrap=!1,this._markRowDirty(this.cursorRow)}putChar(e){this.pendingWrap&&(this.autoWrap?(this.cursorCol=0,this.pendingWrap=!1,this._indexDown()):this.pendingWrap=!1);let t=this.grid[this.cursorRow];if(t&&this.cursorCol>=0&&this.cursorCol<this.cols){let n=t[this.cursorCol];n.ch=e,n.fg=this.curFg,n.bg=this.curBg,n.flags=this.curFlags,n.link=this.curLink,this._markRowDirty(this.cursorRow)}this.cursorCol<this.cols-1?this.cursorCol++:this.pendingWrap=!0}carriageReturn(){this._markRowDirty(this.cursorRow),this.cursorCol=0,this.pendingWrap=!1}lineFeed(){this._markRowDirty(this.cursorRow),this.convertEol&&(this.cursorCol=0),this.pendingWrap=!1,this._indexDown(),this._markRowDirty(this.cursorRow)}index(){this._markRowDirty(this.cursorRow),this.pendingWrap=!1,this._indexDown(),this._markRowDirty(this.cursorRow)}nextLine(){this._markRowDirty(this.cursorRow),this.cursorCol=0,this.pendingWrap=!1,this._indexDown(),this._markRowDirty(this.cursorRow)}reverseIndex(){this._markRowDirty(this.cursorRow),this.pendingWrap=!1,this.cursorRow===this.scrollTop?this.scrollDown(1):this.cursorRow>0&&this.cursorRow--,this._markRowDirty(this.cursorRow)}backspace(){this._markRowDirty(this.cursorRow),this.pendingWrap?this.pendingWrap=!1:this.cursorCol>0&&this.cursorCol--,this._markRowDirty(this.cursorRow)}tab(){this._markRowDirty(this.cursorRow);let e=Math.min(this.cols-1,(Math.floor(this.cursorCol/8)+1)*8);this.cursorCol=e,this.pendingWrap=!1,this._markRowDirty(this.cursorRow)}_indexDown(){this.cursorRow===this.scrollBottom?this.scrollUp(1):this.cursorRow<this.rows-1&&this.cursorRow++}scrollUp(e=1,t=this.scrollTop,n=this.scrollBottom){let r=this.grid,i=Math.min(e,n-t+1);for(let e=0;e<i;e++){let e=r[t];!this.isAltScreen&&t===0&&this.maxScrollback>0&&(this.scrollback.push(e.map(u)),this.scrollback.length>this.maxScrollback&&this.scrollback.shift());for(let e=t;e<n;e++)r[e]=r[e+1];r[n]=this._createRow(this.cols,!0)}this._markRangeDirty(t,n)}scrollDown(e=1,t=this.scrollTop,n=this.scrollBottom){let r=this.grid,i=Math.min(e,n-t+1);for(let e=0;e<i;e++){for(let e=n;e>t;e--)r[e]=r[e-1];r[t]=this._createRow(this.cols,!0)}this._markRangeDirty(t,n)}eraseInLine(e=0){let t=this.grid[this.cursorRow];if(!t)return;let n=0,r=this.cols-1;if(e===0)n=this.cursorCol;else if(e===1)r=this.cursorCol;else if(e!==2)return;for(let e=n;e<=r;e++)t[e]=l(` `,this.curFg,this.curBg,this.curFlags,null);this.pendingWrap=!1,this._markRowDirty(this.cursorRow)}eraseInDisplay(e=0){let t=this.grid;if(e===0){this.eraseInLine(0);for(let e=this.cursorRow+1;e<this.rows;e++)t[e]=this._createRow(this.cols,!0);this._markRangeDirty(this.cursorRow,this.rows-1)}else if(e===1){for(let e=0;e<this.cursorRow;e++)t[e]=this._createRow(this.cols,!0);this.eraseInLine(1),this._markRangeDirty(0,this.cursorRow)}else if(e===2||e===3){for(let e=0;e<this.rows;e++)t[e]=this._createRow(this.cols,!0);e===3&&!this.isAltScreen&&(this.scrollback=[],this.viewportOffset=0),this.pendingWrap=!1,this._markAllDirty()}}eraseChars(e=1){let t=this.grid[this.cursorRow];if(!t)return;let n=Math.min(this.cols,this.cursorCol+Math.max(1,e));for(let e=this.cursorCol;e<n;e++)t[e]=l(` `,this.curFg,this.curBg,this.curFlags,null);this.pendingWrap=!1,this._markRowDirty(this.cursorRow)}insertChars(e=1){let t=this.grid[this.cursorRow];if(!t)return;let n=Math.min(this.cols-this.cursorCol,Math.max(1,e));for(let e=this.cols-1;e>=this.cursorCol+n;e--)t[e]=t[e-n];for(let e=this.cursorCol;e<this.cursorCol+n;e++)t[e]=l(` `,this.curFg,this.curBg,this.curFlags,null);this.pendingWrap=!1,this._markRowDirty(this.cursorRow)}deleteChars(e=1){let t=this.grid[this.cursorRow];if(!t)return;let n=Math.min(this.cols-this.cursorCol,Math.max(1,e));for(let e=this.cursorCol;e<this.cols-n;e++)t[e]=t[e+n];for(let e=this.cols-n;e<this.cols;e++)t[e]=l(` `,this.curFg,this.curBg,this.curFlags,null);this.pendingWrap=!1,this._markRowDirty(this.cursorRow)}insertLines(e=1){this.cursorRow<this.scrollTop||this.cursorRow>this.scrollBottom||(this.scrollDown(Math.max(1,e),this.cursorRow,this.scrollBottom),this.cursorCol=0,this.pendingWrap=!1)}deleteLines(e=1){this.cursorRow<this.scrollTop||this.cursorRow>this.scrollBottom||(this.scrollUp(Math.max(1,e),this.cursorRow,this.scrollBottom),this.cursorCol=0,this.pendingWrap=!1)}resize(e,t){let n=Math.max(1,e),r=Math.max(1,t);if(n===this.cols&&r===this.rows)return;let i=e=>{let t=Array(r);for(let i=0;i<r;i++){let r=Array(n),a=i<e.length?e[i]:null;for(let e=0;e<n;e++)r[e]=a&&e<a.length?a[e]:l(` `,null,null,0,null);t[i]=r}return t};this.primaryGrid=i(this.primaryGrid),this.altGrid=i(this.altGrid),this.cols=n,this.rows=r,this.scrollTop=0,this.scrollBottom=r-1,this.cursorRow=Math.min(r-1,this.cursorRow),this.cursorCol=Math.min(n-1,this.cursorCol),this.pendingWrap=!1,this._markAllDirty()}scrollViewport(e){if(this.isAltScreen)return;let t=this.scrollback.length,n=Math.max(0,Math.min(t,this.viewportOffset+e));n!==this.viewportOffset&&(this.viewportOffset=n,this._markAllDirty())}getVisibleRow(e){if(this.isAltScreen||this.viewportOffset===0)return this.grid[e];let t=this.scrollback.length,n=t-this.viewportOffset+e;return n<t?this.scrollback[n]:this.grid[n-t]}getLineText(e,t=!0){let n=this.grid[e];if(!n)return``;let r=``;for(let e=0;e<n.length;e++)r+=n[e].ch;return t?r.replace(/\s+$/,``):r}getScreenText(e={}){let t=e.trimRight!==!1,n=[];for(let e=0;e<this.rows;e++)n.push(this.getLineText(e,t));return n.join(`
|
|
2
|
+
`)}getScrollbackAndScreenText(e={}){let t=e.trimRight!==!1,n=[];if(!this.isAltScreen)for(let e of this.scrollback){let r=``;for(let t=0;t<e.length;t++)r+=e[t].ch;n.push(t?r.replace(/\s+$/,``):r)}for(let e=0;e<this.rows;e++)n.push(this.getLineText(e,t));return n.join(`
|
|
3
|
+
`)}},f=0,p=1,m=2,h=3,g=4,_=5,v={"`":`◆`,a:`▒`,f:`°`,g:`±`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},y={http:!0,https:!0,tel:!0,mailto:!0};function b(e,t=y){if(!e||typeof e!=`string`)return null;let n=e.trim(),r=n.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);return!r||!t[r[1].toLowerCase()]?null:n}var x=class{constructor(e,t={}){this.screen=e,this.onResponse=t.onResponse||null,this.onTitle=t.onTitle||null,this.onBell=t.onBell||null,this.urlWhitelist=t.urlWhitelist||y,this.state=f,this._csiPrefix=``,this._csiParams=``,this._csiIntermediate=``,this._escIntermediate=``,this._oscBuffer=``,this._oscEscSeen=!1,this._dcsEscSeen=!1,this._lastPrintedChar=` `,this.charsetG0=`B`,this.charsetG1=`B`,this.activeCharset=0,this.applicationCursorKeys=!1,this.applicationKeypad=!1,this.bracketedPasteMode=!1,this.mouseTrackingMode=0,this.mouseProtocol=`x10`,this.alternateScrollMode=!1}reset(){this.state=f,this._csiPrefix=``,this._csiParams=``,this._csiIntermediate=``,this._escIntermediate=``,this._oscBuffer=``,this._oscEscSeen=!1,this._dcsEscSeen=!1,this._lastPrintedChar=` `,this.charsetG0=`B`,this.charsetG1=`B`,this.activeCharset=0,this.applicationCursorKeys=!1,this.applicationKeypad=!1,this.bracketedPasteMode=!1,this.mouseTrackingMode=0,this.mouseProtocol=`x10`,this.alternateScrollMode=!1,this.screen.reset()}write(e){if(e==null)return;let t=typeof e==`string`?e:e instanceof Uint8Array||Buffer.isBuffer(e)?new TextDecoder().decode(e):String(e);for(let e=0;e<t.length;e++){let n=t[e],r=t.charCodeAt(e);switch(this.state){case f:this._handleGround(n,r);break;case p:this._handleEsc(n,r);break;case m:this._handleEscIntermediate(n,r);break;case h:this._handleCsi(n,r);break;case g:this._handleOsc(n,r);break;case _:this._handleDcs(n,r);break}}}_handleGround(e,t){if(t===27){this.state=p,this._escIntermediate=``;return}if(t===13){this.screen.carriageReturn();return}if(t===10||t===11||t===12){this.screen.lineFeed();return}if(t===8){this.screen.backspace();return}if(t===9){this.screen.tab();return}if(t===7){this.onBell&&this.onBell();return}if(t===14){this.activeCharset=1;return}if(t===15){this.activeCharset=0;return}if(t<32||t===127)return;let n=(this.activeCharset===0?this.charsetG0:this.charsetG1)===`0`&&v[e]?v[e]:e;this._lastPrintedChar=n,this.screen.putChar(n)}_handleEsc(e,t){if(e===`[`){this.state=h,this._csiPrefix=``,this._csiParams=``,this._csiIntermediate=``;return}if(e===`]`){this.state=g,this._oscBuffer=``,this._oscEscSeen=!1;return}if(e===`P`||e===`X`||e===`^`||e===`_`){this.state=_,this._dcsEscSeen=!1;return}if(e===`(`||e===`)`||e===`*`||e===`+`||e===`#`){this.state=m,this._escIntermediate=e;return}if(e===`7`){this.screen.saveCursor(),this.state=f;return}if(e===`8`){this.screen.restoreCursor(),this.state=f;return}if(e===`D`){this.screen.index(),this.state=f;return}if(e===`M`){this.screen.reverseIndex(),this.state=f;return}if(e===`E`){this.screen.nextLine(),this.state=f;return}if(e===`c`){this.reset();return}if(e===`=`){this.applicationKeypad=!0,this.state=f;return}if(e===`>`){this.applicationKeypad=!1,this.state=f;return}t!==27&&(this.state=f)}_handleEscIntermediate(e){if(this._escIntermediate===`(`)this.charsetG0=e===`0`?`0`:`B`;else if(this._escIntermediate===`)`)this.charsetG1=e===`0`?`0`:`B`;else if(this._escIntermediate===`#`&&e===`8`){for(let e=0;e<this.screen.rows;e++)for(let t=0;t<this.screen.cols;t++)this.screen.grid[e][t].ch=`E`;this.screen._markAllDirty()}this.state=f}_handleCsi(e,t){if(t===13){this.screen.carriageReturn();return}if(t===10||t===11||t===12){this.screen.lineFeed();return}if(t===8){this.screen.backspace();return}if(t===27){this.state=p;return}if(this._csiParams.length===0&&this._csiPrefix.length===0&&(e===`?`||e===`>`||e===`<`||e===`=`)){this._csiPrefix=e;return}if(t>=48&&t<=57||e===`;`||e===`:`){this._csiParams+=e;return}if(t>=32&&t<=47){this._csiIntermediate+=e;return}t>=64&&t<=126&&(this._dispatchCsi(this._csiPrefix,this._csiParams,this._csiIntermediate,e),this.state=f)}_handleOsc(e,t){if(t===7){this._dispatchOsc(this._oscBuffer),this.state=f;return}if(this._oscEscSeen){if(this._oscEscSeen=!1,e===`\\`){this._dispatchOsc(this._oscBuffer),this.state=f;return}this._oscBuffer+=`\x1B`+e;return}if(t===27){this._oscEscSeen=!0;return}this._oscBuffer+=e}_handleDcs(e,t){if(t===7){this.state=f;return}if(this._dcsEscSeen&&(this._dcsEscSeen=!1,e===`\\`)){this.state=f;return}t===27&&(this._dcsEscSeen=!0)}_dispatchOsc(e){let t=e.indexOf(`;`);if(t===-1)return;let n=e.slice(0,t),r=e.slice(t+1);if(n===`0`||n===`2`)this.onTitle&&this.onTitle(r);else if(n===`8`){let e=r.indexOf(`;`);if(e!==-1){let t=r.slice(e+1);this.screen.curLink=t?b(t,this.urlWhitelist):null}}}_parseParams(e){return e?e.split(`;`).map(e=>e.includes(`:`)?e.split(`:`).map(e=>e===``?0:parseInt(e,10)||0):e===``?0:parseInt(e,10)||0):[]}_dispatchCsi(e,t,n,r){let i=this._parseParams(t),a=typeof i[0]==`number`?i[0]:0,o=typeof i[1]==`number`?i[1]:0;if(e===`?`){this._dispatchDecPrivate(i,r);return}if(e===`>`){r===`c`&&this.onResponse&&this.onResponse(`\x1B[>0;276;0c`);return}switch(r){case`A`:this.screen.moveCursorRelative(-Math.max(1,a),0);break;case`B`:case`e`:this.screen.moveCursorRelative(Math.max(1,a),0);break;case`C`:case`a`:this.screen.moveCursorRelative(0,Math.max(1,a));break;case`D`:this.screen.moveCursorRelative(0,-Math.max(1,a));break;case`E`:this.screen.moveCursorRelative(Math.max(1,a),0),this.screen.carriageReturn();break;case`F`:this.screen.moveCursorRelative(-Math.max(1,a),0),this.screen.carriageReturn();break;case`G`:case"`":this.screen.setCursor(this.screen.cursorRow,Math.max(1,a)-1);break;case`H`:case`f`:this.screen.setCursor(Math.max(1,a)-1,Math.max(1,o)-1);break;case`d`:this.screen.setCursor(Math.max(1,a)-1,this.screen.cursorCol);break;case`J`:this.screen.eraseInDisplay(a);break;case`K`:this.screen.eraseInLine(a);break;case`X`:this.screen.eraseChars(Math.max(1,a));break;case`@`:this.screen.insertChars(Math.max(1,a));break;case`P`:this.screen.deleteChars(Math.max(1,a));break;case`L`:this.screen.insertLines(Math.max(1,a));break;case`M`:this.screen.deleteLines(Math.max(1,a));break;case`S`:this.screen.scrollUp(Math.max(1,a));break;case`T`:this.screen.scrollDown(Math.max(1,a));break;case`r`:this.screen.setScrollRegion(a||1,o||this.screen.rows);break;case`s`:this.screen.saveCursor();break;case`u`:this.screen.restoreCursor();break;case`b`:{let e=Math.min(this.screen.cols*this.screen.rows,Math.max(1,a));for(let t=0;t<e;t++)this.screen.putChar(this._lastPrintedChar);break}case`m`:this._handleSgr(i);break;case`h`:case`l`:a===20&&(this.screen.convertEol=r===`h`);break;case`n`:this.onResponse&&(a===5?this.onResponse(`\x1B[0n`):a===6&&this.onResponse(`\x1b[${this.screen.cursorRow+1};${this.screen.cursorCol+1}R`));break;case`c`:this.onResponse&&this.onResponse(`\x1B[?1;2c`);break;case`t`:a===18&&this.onResponse&&this.onResponse(`\x1b[8;${this.screen.rows};${this.screen.cols}t`);break}}_dispatchDecPrivate(e,t){if(t===`c`&&this.onResponse){this.onResponse(`\x1B[?1;2c`);return}if(t!==`h`&&t!==`l`)return;let n=t===`h`;for(let t of e){let e=typeof t==`number`?t:0;switch(e){case 1:this.applicationCursorKeys=n;break;case 6:this.screen.originMode=n,this.screen.setCursor(0,0);break;case 7:this.screen.autoWrap=n;break;case 25:this.screen.cursorVisible=n,this.screen._markRowDirty(this.screen.cursorRow);break;case 47:case 1047:n?this.screen.enterAltScreen(e===1047):this.screen.exitAltScreen();break;case 1048:n?this.screen.saveCursor():this.screen.restoreCursor();break;case 1049:n?(this.screen.saveCursor(),this.screen.enterAltScreen(!0)):(this.screen.exitAltScreen(),this.screen.restoreCursor());break;case 1e3:case 1002:case 1003:n?this.mouseTrackingMode=e:this.mouseTrackingMode===e&&(this.mouseTrackingMode=0);break;case 1005:this.mouseProtocol=n?`utf8`:`x10`;break;case 1006:this.mouseProtocol=n?`sgr`:`x10`;break;case 1007:this.alternateScrollMode=n;break;case 2004:this.bracketedPasteMode=n;break}}}_handleSgr(e){if(e.length===0){this.screen.resetAttributes();return}let t=0;for(;t<e.length;){let n=e[t];if(Array.isArray(n)){let e=n[0];if(e===38||e===48){let t=e===38;if(n[1]===5&&n.length>=3)t?this.screen.curFg=n[2]:this.screen.curBg=n[2];else if(n[1]===2&&n.length>=5){let e=n.length>=6?3:2,r=`rgb(${n[e]||0}, ${n[e+1]||0}, ${n[e+2]||0})`;t?this.screen.curFg=r:this.screen.curBg=r}}t++;continue}switch(n){case 0:this.screen.resetAttributes();break;case 1:this.screen.curFlags|=1;break;case 2:this.screen.curFlags|=2;break;case 3:this.screen.curFlags|=4;break;case 4:this.screen.curFlags|=8;break;case 5:case 6:this.screen.curFlags|=16;break;case 7:this.screen.curFlags|=32;break;case 8:this.screen.curFlags|=64;break;case 9:this.screen.curFlags|=128;break;case 21:case 22:this.screen.curFlags&=-4;break;case 23:this.screen.curFlags&=-5;break;case 24:this.screen.curFlags&=-9;break;case 25:this.screen.curFlags&=-17;break;case 27:this.screen.curFlags&=-33;break;case 28:this.screen.curFlags&=-65;break;case 29:this.screen.curFlags&=-129;break;case 38:case 48:{let r=n===38,i=e[t+1];if(i===5&&t+2<e.length){let n=Number(e[t+2])||0;r?this.screen.curFg=n:this.screen.curBg=n,t+=2}else if(i===2&&t+4<e.length){let n=`rgb(${Number(e[t+2])||0}, ${Number(e[t+3])||0}, ${Number(e[t+4])||0})`;r?this.screen.curFg=n:this.screen.curBg=n,t+=4}break}case 39:this.screen.curFg=null;break;case 49:this.screen.curBg=null;break;default:n>=30&&n<=37?this.screen.curFg=n-30:n>=40&&n<=47?this.screen.curBg=n-40:n>=90&&n<=97?this.screen.curFg=n-90+8:n>=100&&n<=107&&(this.screen.curBg=n-100+8);break}t++}}},S=[`ansi-black`,`ansi-red`,`ansi-green`,`ansi-yellow`,`ansi-blue`,`ansi-magenta`,`ansi-cyan`,`ansi-white`,`ansi-bright-black`,`ansi-bright-red`,`ansi-bright-green`,`ansi-bright-yellow`,`ansi-bright-blue`,`ansi-bright-magenta`,`ansi-bright-cyan`,`ansi-bright-white`],C=[0,95,135,175,215,255];function w(e){if(typeof e==`string`)return e;if(typeof e!=`number`||e<16||e>255)return null;if(e>=232){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}let t=e-16;return`rgb(${C[Math.floor(t/36)%6]}, ${C[Math.floor(t/6)%6]}, ${C[t%6]})`}function T(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var E=/(?:https?:\/\/|mailto:|tel:)[^\s<>"'`]+/g;function D(e){let t=e.length;for(;t>0;){let n=e[t-1];if(`.!?,;:`.includes(n))t--;else if(n===`)`){let n=e.slice(0,t),r=(n.match(/\(/g)||[]).length;if((n.match(/\)/g)||[]).length>r)t--;else break}else if(n===`]`){let n=e.slice(0,t),r=(n.match(/\[/g)||[]).length;if((n.match(/\]/g)||[]).length>r)t--;else break}else break}return e.slice(0,t)}function O(e,t=y){let n=``;for(let t=0;t<e.length;t++)n+=e[t].ch||` `;let r=Array(e.length).fill(null);for(let t=0;t<e.length;t++)e[t].link&&(r[t]=e[t].link);E.lastIndex=0;let i;for(;(i=E.exec(n))!==null;){let e=D(i[0]),n=b(e,t);if(!n)continue;let a=i.index,o=a+e.length;for(let e=a;e<o&&e<r.length;e++)r[e]||(r[e]=n)}return r}var k=class{constructor(e,t,n={}){this.container=e,this.screen=t,this.cursorStyle=n.cursor||`none`,this.urlWhitelist=n.urlWhitelist||y,this._rowElements=[],this._rafId=null,this._lastCursorRow=-1,this._lastCursorCol=-1,this._lastCursorVisible=!1}scheduleRender(){this._rafId===null&&(typeof requestAnimationFrame==`function`?this._rafId=requestAnimationFrame(()=>{this._rafId=null,this.flushRender()}):this.flushRender())}flushRender(){if(this._rafId!==null&&typeof cancelAnimationFrame==`function`&&(cancelAnimationFrame(this._rafId),this._rafId=null),!this.container||typeof document>`u`)return;let e=this.screen.rows;this._ensureRowElements(e);let t=this.cursorStyle!==`none`&&this.screen.cursorVisible&&this.screen.viewportOffset===0,n=t?this.screen.cursorRow:-1,r=t?this.screen.cursorCol:-1;(this._lastCursorRow!==n||this._lastCursorCol!==r||this._lastCursorVisible!==t)&&(this._lastCursorRow>=0&&this._lastCursorRow<e&&this.screen.dirtyRows.add(this._lastCursorRow),n>=0&&n<e&&this.screen.dirtyRows.add(n),this._lastCursorRow=n,this._lastCursorCol=r,this._lastCursorVisible=t);for(let t of this.screen.dirtyRows)t>=0&&t<e&&this._renderRow(t,t===n?r:-1);this.screen.dirtyRows.clear(),this.screen.fullRedrawNeeded=!1}_ensureRowElements(e){for(;this._rowElements.length<e;){let e=document.createElement(`li`);e.classList&&(e.classList.add(`terminal__line`),e.classList.add(`terminal__row`)),this.container.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>e;){let e=this._rowElements.pop();e&&e.parentNode===this.container&&this.container.removeChild&&this.container.removeChild(e)}}_renderRow(e,t){let n=this._rowElements[e],r=this.screen.getVisibleRow(e);if(!n||!r)return;let i=O(r,this.urlWhitelist),a=this.screen.isAltScreen?r.length-1:-1;if(!this.screen.isAltScreen){for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.ch!==` `||t.fg!==null||t.bg!==null||t.flags!==0||i[e]!==null){a=e;break}}t>a&&(a=t)}if(a<0){n.innerHTML=``;return}let o=``,s=``,c=null,l=null,u=null,d=!1,f=()=>{s&&=(o+=this._formatRun(s,l,u,d),``)};for(let e=0;e<=a;e++){let n=r[e],a=i[e],o=e===t,p=`${n.fg??``}|${n.bg??``}|${n.flags}|${a??``}|${+!!o}`;p!==c&&(f(),c=p,l=n,u=a,d=o),s+=n.ch||` `}f(),n.innerHTML=o}_formatRun(e,t,n,r){let i=[],a=[],o=t.flags||0,s=(o&32)!=0,c=s?t.bg:t.fg,l=s?t.fg:t.bg;if(s&&t.fg===null&&t.bg===null&&i.push(`terminal__inverse`),typeof c==`number`&&c>=0&&c<16)i.push(`${S[c]}-fg`);else if(c!==null){let e=w(c);e&&a.push(`color:${e}`)}if(typeof l==`number`&&l>=0&&l<16)i.push(`${S[l]}-bg`);else if(l!==null){let e=w(l);e&&a.push(`background-color:${e}`)}o&1&&a.push(`font-weight:bold`),o&2&&a.push(`opacity:0.65`),o&4&&a.push(`font-style:italic`),o&8&&o&128?a.push(`text-decoration:underline line-through`):o&8?a.push(`text-decoration:underline`):o&128&&a.push(`text-decoration:line-through`),o&16&&i.push(`terminal__blink`),o&64&&a.push(`visibility:hidden`),r&&(i.push(`terminal__cursor`),i.push(this.cursorStyle));let u=T(e),d=u;return(i.length>0||a.length>0)&&(d=`<span${i.length>0?` class="${i.join(` `)}"`:``}${a.length>0?` style="${a.join(`;`)}"`:``}>${u}</span>`),n?`<a href="${T(n)}" target="_blank" rel="noopener noreferrer" class="terminal__link">${d}</a>`:d}},A=`
|
|
4
|
+
import os, sys, pty, select, fcntl, termios, struct, signal, json
|
|
5
|
+
|
|
6
|
+
cmd = sys.argv[1]
|
|
7
|
+
args = json.loads(sys.argv[2])
|
|
8
|
+
cols = int(sys.argv[3])
|
|
9
|
+
rows = int(sys.argv[4])
|
|
10
|
+
cwd = sys.argv[5]
|
|
11
|
+
|
|
12
|
+
pid, fd = pty.fork()
|
|
13
|
+
if pid == 0:
|
|
14
|
+
if cwd:
|
|
15
|
+
try: os.chdir(cwd)
|
|
16
|
+
except Exception: pass
|
|
17
|
+
os.execvp(cmd, [cmd] + args)
|
|
18
|
+
|
|
19
|
+
def set_winsize(c, r):
|
|
20
|
+
try:
|
|
21
|
+
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", r, c, 0, 0))
|
|
22
|
+
os.kill(pid, signal.SIGWINCH)
|
|
23
|
+
except Exception:
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
set_winsize(cols, rows)
|
|
27
|
+
stdin_fd = sys.stdin.fileno()
|
|
28
|
+
stdout_fd = sys.stdout.fileno()
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
while True:
|
|
32
|
+
rlist, _, _ = select.select([fd, stdin_fd], [], [])
|
|
33
|
+
if fd in rlist:
|
|
34
|
+
try:
|
|
35
|
+
data = os.read(fd, 8192)
|
|
36
|
+
if not data:
|
|
37
|
+
break
|
|
38
|
+
os.write(stdout_fd, data)
|
|
39
|
+
except OSError:
|
|
40
|
+
break
|
|
41
|
+
if stdin_fd in rlist:
|
|
42
|
+
try:
|
|
43
|
+
chunk = os.read(stdin_fd, 8192)
|
|
44
|
+
if not chunk:
|
|
45
|
+
break
|
|
46
|
+
# Check for inline resize control packet: \\x1b]9999;cols;rows\\x07
|
|
47
|
+
while b"\\x1b]9999;" in chunk:
|
|
48
|
+
start = chunk.find(b"\\x1b]9999;")
|
|
49
|
+
end = chunk.find(b"\\x07", start)
|
|
50
|
+
if end == -1:
|
|
51
|
+
break
|
|
52
|
+
packet = chunk[start+7:end].decode("ascii", "ignore")
|
|
53
|
+
parts = packet.split(";")
|
|
54
|
+
if len(parts) == 2:
|
|
55
|
+
set_winsize(int(parts[0]), int(parts[1]))
|
|
56
|
+
chunk = chunk[:start] + chunk[end+1:]
|
|
57
|
+
if chunk:
|
|
58
|
+
os.write(fd, chunk)
|
|
59
|
+
except OSError:
|
|
60
|
+
break
|
|
61
|
+
finally:
|
|
62
|
+
try:
|
|
63
|
+
os.close(fd)
|
|
64
|
+
except Exception:
|
|
65
|
+
pass
|
|
66
|
+
try:
|
|
67
|
+
_, status = os.waitpid(pid, 0)
|
|
68
|
+
sys.exit(os.waitstatus_to_exitcode(status) if hasattr(os, "waitstatus_to_exitcode") else 0)
|
|
69
|
+
except Exception:
|
|
70
|
+
sys.exit(0)
|
|
71
|
+
`;function j(e){if(typeof process<`u`&&process.env&&process.env.SHELL)return process.env.SHELL;try{let t=e?e(`fs`):null;if(t){for(let e of[`/bin/zsh`,`/usr/bin/zsh`,`/bin/bash`,`/usr/bin/bash`,`/bin/sh`])if(t.existsSync(e))return e}}catch{}return`/bin/sh`}function M(e,t=[],n={}){let r=typeof require==`function`?require:typeof globalThis<`u`&&globalThis.process&&globalThis.process.getBuiltinModule?e=>globalThis.process.getBuiltinModule(e):null;if(!r)throw Error(`spawnPty is only available in a Node.js environment`);let i=e||j(r),{spawn:a}=r(`child_process`),o=n.cols||80,s=n.rows||24,c=n.cwd||(typeof process<`u`?process.cwd():``),l=Object.assign({},typeof process<`u`?process.env:{},{TERM:`xterm-256color`,COLORTERM:`truecolor`,COLUMNS:String(o),LINES:String(s)},n.env||{}),u=a(`python3`,[`-u`,`-c`,A,i,JSON.stringify(t),String(o),String(s),c],{env:l,stdio:[`pipe`,`pipe`,`pipe`]}),d=new Map,f=(e,...t)=>{let n=d.get(e);if(n)for(let e of[...n])e(...t)};return u.stdout.on(`data`,e=>f(`data`,e)),u.on(`exit`,(e,t)=>f(`exit`,e,t)),u.on(`close`,e=>f(`close`,e)),u.on(`error`,e=>f(`error`,e)),{pid:u.pid,process:u,write(e){u.stdin&&!u.stdin.destroyed&&u.stdin.write(e)},resize(e,t){u.stdin&&!u.stdin.destroyed&&u.stdin.write(`\x1b]9999;${Math.max(1,e)};${Math.max(1,t)}\x07`)},on(e,t){return d.has(e)||d.set(e,[]),d.get(e).push(t),this},removeListener(e,t){let n=d.get(e);if(!n)return this;let r=n.indexOf(t);return r!==-1&&n.splice(r,1),this},kill(e=`SIGTERM`){try{u.kill(e)}catch{}}}}var N=c.default?.default??c.default,P=class{constructor(){this._listeners=new Map,this.readable=!0,this.writable=!0,this.isTTY=!0}on(e,t){return this._listeners.has(e)||this._listeners.set(e,[]),this._listeners.get(e).push(t),this}addListener(e,t){return this.on(e,t)}once(e,t){let n=(...r)=>{this.removeListener(e,n),t(...r)};return this.on(e,n)}removeListener(e,t){let n=this._listeners.get(e);if(!n)return this;let r=n.indexOf(t);return r!==-1&&n.splice(r,1),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}listeners(e){return[...this._listeners.get(e)||[]]}emit(e,...t){let n=this._listeners.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}setRawMode(e){return this.isRaw=!!e,this}resume(){return this}pause(){return this}setEncoding(e){return this._encoding=e,this}pipe(e){return this.on(`data`,t=>e.write(t)),e}unpipe(){return this}destroy(){this.removeAllListeners()}},F=class{constructor(e={}){let{el:t,font:n=`Roboto Mono`,cursor:r=`none`,outputAnimation:i=`none`,animateSpeed:a=1,onExit:o=null,mobileInput:s=`click`,lineWrap:c=!1,command:l=null,cols:u=80,rows:f=24,maxScrollback:p=1e3,stream:m=null}=e;if(!t)throw Error("you must set `el` option");if(![`none`,`block`,`blink`].includes(r))throw Error(`cursor value must be one of: 'none', 'block', 'blink'`);if(![`none`,`type`].includes(i))throw Error(`outputAnimation value must be one of: 'none', 'type'`);if(!Number.isInteger(a)||a<1||a>20)throw Error(`animateSpeed value must be between 1 and 20`);if(this._exitFn=o,this._cursor=r,this._outputAnimation=i,this._animateSpeed=a,this._lineWrap=c,this._el=t,this._dataListeners=[],this._resizeListeners=[],this._titleListeners=[],this._mouseButtonDown=null,this._typeQueue=``,this._typeTimer=null,this._isHandlingInput=!1,this._suppressAnimationUntil=0,this.screen=new d(u,f,{maxScrollback:p}),this.parser=new x(this.screen,{urlWhitelist:y,onResponse:e=>this._emitInput(e),onTitle:e=>{this.title=e;for(let t of this._titleListeners)t(e)}}),this.cli=e.cli||e.shell||null,!this.cli&&!m&&e.Shell!==!1){let t=e.Shell===null?null:e.Shell||typeof globalThis<`u`&&(globalThis.Shell||globalThis.shell)||(typeof N==`function`?N:null);if(!t)throw Error(`Shell is required by Terminal. Please import Shell from "brsh" or include shell.min.js before terminal.min.js.`);this.cli=new t(Object.assign({},e,{command:void 0}))}this._setupDom(this._el,n),this.renderer=new k(this._cmdList,this.screen,{cursor:this._cursor,urlWhitelist:y}),this._listenForEvents(),this.cli&&(this.attach(this.cli),typeof this.cli.on==`function`&&this.cli.on(`exit`,e=>{delete this.cli,typeof this._exitFn==`function`&&this._exitFn(e)}),l&&this.onCommand(l)),m&&(this.attach(m),l&&this.onCommand(l)),s===`click`&&this._mobileInput(),this.renderer.flushRender()}get cols(){return this.screen.cols}get rows(){return this.screen.rows}write(e){if(e==null||e===``)return;let t=typeof e==`string`?e:e instanceof Uint8Array||typeof Buffer<`u`&&Buffer.isBuffer(e)?new TextDecoder().decode(e):String(e);if(this._outputAnimation===`type`){if(this._isUserInputActive()||this._isFullScreenWrite(t)){this._flushTypeQueue(),this.parser.write(t),this.renderer.flushRender(),this._autoScroll();return}if((this._isLineRewrite(t)||!/[^\r\n]/.test(t))&&(!this._typeQueue||!this._typeQueue.includes(`
|
|
72
|
+
`))){this._flushTypeQueue(),this.parser.write(t),this.renderer.flushRender(),this._autoScroll();return}this._enqueueTypeAnimation(t);return}this.parser.write(t),this.renderer.flushRender(),this._autoScroll()}writeln(e=``){this.write(String(e)+`\r
|
|
73
|
+
`)}clear(){this.write(`\x1B[2J\x1B[3J\x1B[H`)}reset(){this._flushTypeQueue(),this.parser.reset(),this.renderer.flushRender()}onData(e){return typeof e==`function`?(this._dataListeners.push(e),()=>{let t=this._dataListeners.indexOf(e);t!==-1&&this._dataListeners.splice(t,1)}):()=>{}}onResize(e){return typeof e==`function`?(this._resizeListeners.push(e),()=>{let t=this._resizeListeners.indexOf(e);t!==-1&&this._resizeListeners.splice(t,1)}):()=>{}}onTitleChange(e){return typeof e==`function`?(this._titleListeners.push(e),()=>{let t=this._titleListeners.indexOf(e);t!==-1&&this._titleListeners.splice(t,1)}):()=>{}}resize(e,t){let n=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t));if(!(n===this.screen.cols&&r===this.screen.rows&&this._lastCols===n&&this._lastRows===r)){this._lastCols=n,this._lastRows=r,this.screen.resize(n,r),this.cli&&typeof this.cli.setTerminalSize==`function`&&this.cli.setTerminalSize(n,r);for(let e of this._resizeListeners)e({cols:n,rows:r});this.renderer.flushRender()}}attach(e){if(!e)return()=>{};this._attachedStream=e;let t=e=>{this.write(e)};typeof e.on==`function`?e.on(`data`,t):typeof e.addEventListener==`function`&&e.addEventListener(`message`,e=>this.write(e.data??e));let n=this.onData(t=>{typeof e.write==`function`?e.write(t):typeof e.send==`function`&&e.send(t)}),r=this.onResize(({cols:t,rows:n})=>{typeof e.resize==`function`&&e.resize(t,n)});return typeof e.resize==`function`&&e.resize(this.cols,this.rows),()=>{n(),r(),typeof e.removeListener==`function`&&e.removeListener(`data`,t),this._attachedStream===e&&(this._attachedStream=null)}}spawn(e,t=[],n={}){let r=M(e,t,Object.assign({cols:this.cols,rows:this.rows},n)),i=this.attach(r);return r.on(`exit`,e=>{typeof this._exitFn==`function`&&this._exitFn(e)}),{pty:r,detach:i}}createTty(e={}){let t=new P,n=new P;e.interceptShell,n.columns=this.cols,n.rows=this.rows,n.getWindowSize=()=>[n.columns,n.rows],n.write=(e,t,n)=>(this.write(e),typeof t==`function`?t():typeof n==`function`&&n(),!0);let r=this.onData(e=>{let n=t._encoding?e:typeof Buffer<`u`?Buffer.from(e,`utf8`):e;t.emit(`data`,n)}),i=this.onResize(({cols:e,rows:t})=>{n.columns=e,n.rows=t,n.emit(`resize`)});return{stdin:t,stdout:n,dispose:()=>{r(),i(),t.destroy(),n.destroy()}}}sendKey(e,t={}){let n=this._encodeKey(e,t);n&&this._emitInput(n)}sendMouse(e,{button:t=0,col:n=1,row:r=1,shift:i=!1,alt:a=!1,ctrl:o=!1,deltaY:s=0}={}){let c=this.parser.mouseTrackingMode,l=Math.max(1,Math.min(this.cols,n)),u=Math.max(1,Math.min(this.rows,r));if(c===0||i){if(e===`wheel`)if(this.screen.isAltScreen&&this.parser.alternateScrollMode){let e=s<0?`ArrowUp`:`ArrowDown`;this.sendKey(e)}else this.screen.isAltScreen||(this.screen.scrollViewport(s<0?3:-3),this.renderer.flushRender());return!1}let d=t;if(e===`wheel`)d=s<0?64:65;else if(e===`mousemove`){if(c===1e3||c===1002&&this._mouseButtonDown===null)return!1;d=(this._mouseButtonDown??0)+32}else e===`mousedown`?this._mouseButtonDown=t:e===`mouseup`&&(this._mouseButtonDown=null,this.parser.mouseProtocol!==`sgr`&&(d=3));if(i&&(d+=4),a&&(d+=8),o&&(d+=16),this.parser.mouseProtocol===`sgr`){let t=e===`mouseup`?`m`:`M`;return this._emitInput(`\x1b[<${d};${l};${u}${t}`),!0}let f=this.parser.mouseProtocol===`utf8`?2015:223,p=Math.min(f,l),m=Math.min(f,u);return this._emitInput(`\x1B[M`+String.fromCharCode(32+d)+String.fromCharCode(32+p)+String.fromCharCode(32+m)),!0}onCommand(e){this.cli&&typeof this.cli.sendCommand==`function`?this.cli.sendCommand(e):this._emitInput(String(e)+`\r`)}getScreenText(e){return this.renderer.flushRender(),this.screen.getScreenText(e)}getLineText(e,t=!0){return this.renderer.flushRender(),this.screen.getLineText(e,t)}_emitInput(e){if(!e)return;this.screen.viewportOffset>0&&(this.screen.viewportOffset=0,this.screen._markAllDirty(),this.renderer.flushRender()),(this._typeQueue||this._typeTimer!==null)&&(this._flushTypeQueue(),this.renderer.flushRender(),this._autoScroll());let t=e===`\r`||e===`
|
|
74
|
+
`||e===`\r
|
|
75
|
+
`;this._suppressAnimationUntil=t?0:Date.now()+80,this._isHandlingInput=!t;try{for(let t of this._dataListeners)t(e)}finally{this._isHandlingInput=!1}}_flushTypeQueue(){if(this._typeTimer!==null&&(clearInterval(this._typeTimer),this._typeTimer=null),this._typeQueue){let e=this._typeQueue;this._typeQueue=``,this.parser.write(e)}}_isUserInputActive(){return!!(this._isHandlingInput||this._suppressAnimationUntil&&Date.now()<this._suppressAnimationUntil)}_isFullScreenWrite(e){if(this.screen.isAltScreen)return!0;if(this.cli&&this.cli.runningCommand){let e=this.cli.runningCommand;if(e.interactive||e._inAltScreen||e.stdinStream&&e.stdinStream.isRaw)return!0}return!!(this._attachedStream&&this._attachedStream.isRaw||/\x1b\[\?(?:1049|1047|47)[hl]/.test(e)||/\x1b\[(?:\d*J|(?:\d+;\d+)?[Hf]|\d*[ABLM]|\d*;\d*r)/.test(e))}_isLineRewrite(e){return!!(/\r(?!\n)/.test(e)||/\x1b\[\d*[KCDG@P]/.test(e)||/[\x08\x7f]/.test(e))}_encodeKey(e,t={}){let{alt:n=!1,ctrl:r=!1,shift:i=!1,meta:a=!1}=t;if(!e||[`Control`,`Alt`,`Shift`,`Meta`,`CapsLock`].includes(e)||a)return null;let o=this.parser.applicationCursorKeys;if(e===`ArrowUp`)return n?`\x1B[1;3A`:r?`\x1B[1;5A`:o?`\x1BOA`:`\x1B[A`;if(e===`ArrowDown`)return n?`\x1B[1;3B`:r?`\x1B[1;5B`:o?`\x1BOB`:`\x1B[B`;if(e===`ArrowRight`)return n?`\x1B[1;3C`:r?`\x1B[1;5C`:o?`\x1BOC`:`\x1B[C`;if(e===`ArrowLeft`)return n?`\x1B[1;3D`:r?`\x1B[1;5D`:o?`\x1BOD`:`\x1B[D`;if(e===`Home`)return o?`\x1BOH`:`\x1B[H`;if(e===`End`)return o?`\x1BOF`:`\x1B[F`;if(e===`Delete`)return`\x1B[3~`;if(e===`Insert`)return`\x1B[2~`;if(e===`PageUp`)return`\x1B[5~`;if(e===`PageDown`)return`\x1B[6~`;if(e===`Enter`)return`\r`;if(e===`Backspace`)return n?`\x1B`:``;if(e===`Tab`)return i?`\x1B[Z`:` `;if(e===`Escape`)return`\x1B`;let s=e.match(/^F(\d{1,2})$/);if(s)return{1:`\x1BOP`,2:`\x1BOQ`,3:`\x1BOR`,4:`\x1BOS`,5:`\x1B[15~`,6:`\x1B[17~`,7:`\x1B[18~`,8:`\x1B[19~`,9:`\x1B[20~`,10:`\x1B[21~`,11:`\x1B[23~`,12:`\x1B[24~`}[Number(s[1])]||null;if(r&&e.length===1){let t=e.toUpperCase().charCodeAt(0);if(t>=64&&t<=95){let e=String.fromCharCode(t-64);return n?`\x1B`+e:e}}return e.length===1?n?`\x1B`+e:e:null}_enqueueTypeAnimation(e){this._typeQueue+=e,this._typeTimer===null&&(this._typeTimer=setInterval(()=>{if(!this._typeQueue){clearInterval(this._typeTimer),this._typeTimer=null;return}if(this._isFullScreenWrite(this._typeQueue)){this._flushTypeQueue(),this.renderer.flushRender(),this._autoScroll();return}let e=0,t=0,n=this._typeQueue.indexOf(`
|
|
76
|
+
`),r=n===-1?this._typeQueue.length:n+1,i=this._typeQueue.slice(0,r);if(this._isLineRewrite(i))t=r;else for(;t<this._typeQueue.length&&e<this._animateSpeed;)if(this._typeQueue.charCodeAt(t)===27)if(t++,this._typeQueue[t]===`[`){for(t++;t<this._typeQueue.length&&this._typeQueue.charCodeAt(t)<64;)t++;t<this._typeQueue.length&&t++}else if(this._typeQueue[t]===`]`){for(t++;t<this._typeQueue.length&&this._typeQueue.charCodeAt(t)!==7;){if(this._typeQueue.charCodeAt(t)===27&&this._typeQueue[t+1]===`\\`){t+=2;break}t++}t<this._typeQueue.length&&this._typeQueue.charCodeAt(t)===7&&t++}else t<this._typeQueue.length&&t++;else t++,e++;let a=this._typeQueue.slice(t);a&&!a.includes(`
|
|
77
|
+
`)&&this._isLineRewrite(a)&&(t=this._typeQueue.length);let o=this._typeQueue.slice(0,t);this._typeQueue=this._typeQueue.slice(t),this.parser.write(o),this.renderer.flushRender(),this._autoScroll()},10))}_setupDom(e,t=`Roboto Mono`){if(typeof document>`u`)return;let n=document.createElement(`link`);n.href=`https://fonts.googleapis.com/css?family=${encodeURIComponent(t)}:ital,wght@0,400;0,700;1,400;1,700&display=swap`,n.rel=`stylesheet`,document.head&&document.head.appendChild&&document.head.appendChild(n),this._cmdList=document.createElement(`ul`),this._cmdList.style.fontFamily=`'${t}', monospace`,this._cmdList.style.listStyle=`none`,this._cmdList.style.padding=`0`,this._cmdList.style.margin=`0`,this._lineWrap&&this._cmdList.classList.add(`terminal--wrap`),e.appendChild(this._cmdList),this._charMeasure=document.createElement(`span`),this._charMeasure.className=`terminal__char-measure`,this._charMeasure.style.fontFamily=`'${t}', monospace`,this._charMeasure.textContent=`X`,this._charMeasure.setAttribute(`aria-hidden`,`true`),e.appendChild(this._charMeasure),setTimeout(()=>this._measureAndSetSize(),0),document.fonts&&document.fonts.ready&&document.fonts.ready.then(()=>this._measureAndSetSize()),typeof ResizeObserver<`u`&&new ResizeObserver(()=>this._measureAndSetSize()).observe(e)}_listenForEvents(){if(!(typeof window>`u`)&&(this._onKeyDown=e=>{if(e.metaKey)return;let t=this._encodeKey(e.key,{alt:!!e.altKey,ctrl:!!e.ctrlKey,shift:!!e.shiftKey,meta:!!e.metaKey});t&&(e.preventDefault&&e.preventDefault(),this._emitInput(t))},this._onPaste=e=>{let t=e.clipboardData||typeof window<`u`&&window.clipboardData;if(!t||typeof t.getData!=`function`)return;let n=t.getData(`text`);if(!n)return;e.preventDefault&&e.preventDefault();let r=n.replace(/\r?\n/g,`\r`);this.parser.bracketedPasteMode?this._emitInput(`\x1b[200~${r}\x1b[201~`):this._emitInput(r)},window.addEventListener(`keydown`,this._onKeyDown),window.addEventListener(`paste`,this._onPaste),this._el&&typeof this._el.addEventListener==`function`)){let e=e=>{if(!this._charMeasure||!this._el.getBoundingClientRect)return{col:1,row:1};let t=this._charMeasure.getBoundingClientRect(),n=this._el.getBoundingClientRect(),r=t.width||8,i=t.height||16;return{col:Math.max(1,Math.min(this.cols,Math.floor(((e.clientX||0)-n.left)/r)+1)),row:Math.max(1,Math.min(this.rows,Math.floor(((e.clientY||0)-n.top)/i)+1))}};this._el.addEventListener(`mousedown`,t=>{let n=t.target;if(n&&n.tagName===`A`&&(this.parser.mouseTrackingMode===0||t.metaKey||t.ctrlKey))return;let{col:r,row:i}=e(t);this.sendMouse(`mousedown`,{button:t.button||0,col:r,row:i,shift:!!t.shiftKey,alt:!!t.altKey,ctrl:!!t.ctrlKey})&&t.preventDefault&&t.preventDefault()}),this._el.addEventListener(`mouseup`,t=>{let{col:n,row:r}=e(t);this.sendMouse(`mouseup`,{button:t.button||0,col:n,row:r,shift:!!t.shiftKey,alt:!!t.altKey,ctrl:!!t.ctrlKey})&&t.preventDefault&&t.preventDefault()}),this._el.addEventListener(`mousemove`,t=>{if(this.parser.mouseTrackingMode===0)return;let{col:n,row:r}=e(t);this.sendMouse(`mousemove`,{button:t.button||0,col:n,row:r,shift:!!t.shiftKey,alt:!!t.altKey,ctrl:!!t.ctrlKey})}),this._el.addEventListener(`wheel`,t=>{let{col:n,row:r}=e(t);this.sendMouse(`wheel`,{col:n,row:r,deltaY:t.deltaY||0,shift:!!t.shiftKey,alt:!!t.altKey,ctrl:!!t.ctrlKey})&&t.preventDefault&&t.preventDefault()})}}_mobileInput(){if(typeof document>`u`||!this._el)return;let e=document.createElement(`input`);e.type=`text`,e.style.position=`absolute`,e.style.left=`-9999999px`,this._el.appendChild(e),this._mobileInputBuffer=``,this._el.addEventListener(`click`,()=>{typeof e.focus==`function`&&e.focus()}),e.addEventListener(`keypress`,t=>{t.key===`Enter`&&(e.value=``,this._mobileInputBuffer=e.value)}),e.addEventListener(`keyup`,t=>{if(t.key===`Unidentified`){if(e.value.length<this._mobileInputBuffer.length)this.sendKey(`Backspace`);else if(e.value.length>this._mobileInputBuffer.length){let t=e.value[e.value.length-1];this.sendKey(t)}this._mobileInputBuffer=e.value}})}_autoScroll(){!this._el||typeof this._el.scrollTo!=`function`||this._el.scrollTop+this._el.offsetHeight>=this._el.scrollHeight-50&&this._el.scrollTo(0,this._el.scrollHeight)}_measureAndSetSize(){if(!this._charMeasure||!this._el||typeof this._el.getBoundingClientRect!=`function`)return;let e=this._charMeasure.getBoundingClientRect(),t=this._el.getBoundingClientRect();if(!e||!t||!e.width||!e.height||!t.width||e.width>=t.width&&e.height>=t.height)return;let n=Math.max(1,Math.floor(t.width/e.width)),r=Math.max(1,Math.floor((t.height||e.height*24)/e.height));(n!==this._lastCols||r!==this._lastRows)&&this.resize(n,r)}destroy(){this._typeTimer!==null&&(clearInterval(this._typeTimer),this._typeTimer=null),typeof window<`u`&&window.removeEventListener&&(this._onKeyDown&&window.removeEventListener(`keydown`,this._onKeyDown),this._onPaste&&window.removeEventListener(`paste`,this._onPaste)),this._dataListeners=[],this._resizeListeners=[],this._titleListeners=[]}};F.Terminal=F,F.spawnPty=M,typeof globalThis<`u`&&(globalThis.Terminal=F),module.exports=F;
|
|
101
78
|
//# sourceMappingURL=terminal.cjs.js.map
|