UNPKG

@jupyterlite/terminal

Version:
34 lines (29 loc) 94.2 kB
(()=>{var e,t,i,r,s,n,a,o={581(e,t,i){"use strict";i.d(t,{H:()=>td});var r,s,n,a,o,l,h,u,c,d,m,f,p,_,g,w,y,b={};function C(e,t){return e=e.replace(/\/+$/,""),t=t.replace(/^\/+/,""),`${e}/${t}`}function x(e){return e.replace(/\s+$/,"")}function v(e){let t=[],i=e.length;for(let r=0;r<i;r+=1e4)t.push(String.fromCharCode(...e.slice(r,r+1e4)));return t.join("")}i.r(b),i.d(b,{AliasCommand:()=>e_,BuiltinCommand:()=>en,CdCommand:()=>ev,ClearCommand:()=>eE,CockleConfigCommand:()=>eT,ExitCommand:()=>eM,ExportCommand:()=>eD,FalseCommand:()=>eC,HelpCommand:()=>eF,HistoryCommand:()=>eU,TrueCommand:()=>eb,UnsetCommand:()=>ej,WhichCommand:()=>ez}),(r=c||(c={}))[r.ASYNC=0]="ASYNC",r[r.SYNC=1]="SYNC";class S{browsingContextId;shellId;constructor(e,t,i){this.browsingContextId=t,this.shellId=i,this._url=C(e,"api/stdin/terminal")}getStdin(e){try{let{xhr:t,msg:i}=this._prepareStdinRequest(e,c.SYNC);return t.send(i),this._processStdinReply(t.responseText)}catch(e){return console.error(`Failed to request stdin via service worker: ${e}`),""}}async getStdinAsync(e,t=!1){try{let{xhr:i,msg:r}=this._prepareStdinRequest(e,c.ASYNC,t),s=new Promise((e,t)=>{i.onload=()=>e(i.responseText),i.onerror=()=>t("XHR error")});return i.send(r),this._processStdinReply(await s)}catch(e){return console.error(`Failed to request stdin via service worker: ${e}`),""}}_prepareStdinRequest(e,t,i=!1){let r=new XMLHttpRequest;r.open("POST",this._url,t===c.ASYNC);let s={shellId:this.shellId,timeoutMs:e};return i&&(s.test=!0),{xhr:r,msg:JSON.stringify({browsingContextId:this.browsingContextId,data:s})}}_processStdinReply(e){let t=JSON.parse(e);if("error"in t)throw Error(t.error);if(void 0!==t.text)return t.text??"";throw Error(`Invalid stdin response: ${t}`)}_url}var E=i(899);let O=/\x1b\[[^m]*m/g,I="\x1b[?1049h",k="\x1b[?1049l",N=(e=1)=>e>0?"\x1b["+e+"C":"",A=(e=1)=>e>0?"\x1b["+e+"D":"",T="\x1b[H",R="\x1b[2J",P="\x1b[3J",M="\x1b[K",L="\x1b[1K",D=e=>e.replace(O,""),B="\x1b[1;0m",F="\x1b[1;31m",W="\x1b[1;32m",U="\x1b[0;91m",$="\x1b[0;94m",j="\x1b[0;95m",H="\x1b[0;31m",z="\x1b[0;32m",V="\x1b[0;33m";!function(e){var t,i,r,s;let n,a,o;(t=n=e.InputFlag||(e.InputFlag={}))[t.ISTRIP=32]="ISTRIP",t[t.INLCR=64]="INLCR",t[t.IGNCR=128]="IGNCR",t[t.ICRNL=256]="ICRNL",t[t.IUCLC=512]="IUCLC",t[t.IXON=1024]="IXON",t[t.IXANY=2048]="IXANY",t[t.IMAXBEL=8192]="IMAXBEL",t[t.IUTF8=16384]="IUTF8",(i=a=e.OutputFlag||(e.OutputFlag={}))[i.OPOST=1]="OPOST",i[i.OLCUC=2]="OLCUC",i[i.ONLCR=4]="ONLCR",i[i.OCRNL=8]="OCRNL",i[i.ONOCR=16]="ONOCR",i[i.ONLRET=32]="ONLRET",i[i.TABDLY=6144]="TABDLY",(r=o=e.LocalFlag||(e.LocalFlag={}))[r.ISIG=1]="ISIG",r[r.ICANON=2]="ICANON",r[r.ECHO=8]="ECHO",r[r.ECHOE=16]="ECHOE",r[r.ECHOK=32]="ECHOK",r[r.ECHONL=64]="ECHONL",r[r.NOFLSH=128]="NOFLSH",r[r.ECHOCTL=512]="ECHOCTL",r[r.ECHOPRT=1024]="ECHOPRT",r[r.ECHOKE=2048]="ECHOKE",r[r.IEXTEN=32768]="IEXTEN",(s=e.ControlCharacter||(e.ControlCharacter={}))[s.VINTR=0]="VINTR",s[s.VQUIT=1]="VQUIT",s[s.VERASE=2]="VERASE",s[s.VKILL=3]="VKILL",s[s.VEOF=4]="VEOF",s[s.VTIME=5]="VTIME",s[s.VMIN=6]="VMIN",s[s.VSWTCH=7]="VSWTCH",s[s.VSTART=8]="VSTART",s[s.VSTOP=9]="VSTOP",s[s.VSUSP=10]="VSUSP",s[s.VEOL=11]="VEOL",s[s.VREPRINT=12]="VREPRINT",s[s.VDISCARD=13]="VDISCARD",s[s.VWERASE=14]="VWERASE",s[s.VLNEXT=15]="VLNEXT",s[s.VEOL2=16]="VEOL2",e.cloneFlags=function(e){return{c_iflag:e.c_iflag,c_oflag:e.c_oflag,c_cflag:e.c_cflag,c_lflag:e.c_lflag,c_cc:[...e.c_cc]}};class l{c_iflag=0;c_oflag=0;c_cflag=0;c_lflag=0;c_cc=[]}e.Flags=l;class h{constructor(){this.setDefaultShell()}get(){return this._flags}log(e){let t=(e,t,i)=>{let r=[];for(let[t,s]of Object.entries(e).filter(([e,t])=>e[0].match(/\D/)))(i&s)>0&&r.push(t);return` ${t} = ${i} 0x${i.toString(16)} = ${r.join(" ")}`},i=["Cockle "+e+":"],r=this._flags;i.push(t(n,"c_iflag",r.c_iflag)),i.push(t(a,"c_oflag",r.c_oflag)),i.push(` c_cflag = ${r.c_cflag} 0x${r.c_cflag.toString(16)}`),i.push(t(o,"c_lflag",r.c_lflag)),i.push(` c_cc = ${r.c_cc}`),console.debug(i.join("\n"))}set(e){this._flags=e,this.log("Termios set")}setDefaultShell(){this.setDefaultWasm(),this._flags.c_oflag|=a.ONOCR}setDefaultWasm(){let e=this._flags;e.c_iflag=n.IUTF8|n.IMAXBEL|n.IXON|n.ICRNL,e.c_oflag=a.OPOST|a.ONLCR,e.c_cflag=191,e.c_lflag=o.IEXTEN|o.ECHOKE|o.ECHOCTL|o.ECHOK|o.ECHOE|o.ECHO|o.ICANON|o.ISIG,e.c_cc=[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}setRawMode(){let e=this._flags;e.c_iflag&=~(n.ISTRIP|n.INLCR|n.IGNCR|n.ICRNL|n.IXON),e.c_oflag&=~a.OPOST,e.c_lflag&=~(o.ECHO|o.ECHONL|o.ICANON|o.ISIG|o.IEXTEN)}_flags=new l}e.Termios=h}(d||(d={}));class q{outputCallback;termios;constructor(e,t){this.outputCallback=e,this.termios=t}async canEnable(){await this._available?.promise}async disable(){this._enabled&&(this._enabled=!1,this._available?.resolve())}async enable(){this._enabled=!0,this._available=new E.PromiseDelegate}get enabled(){return this._enabled}pollInput(e){if(!this._enabled)throw Error("WorkerIO.pollInput when disabled");let t=this._readBuffer.length>0;if(!t&&0!==e){let i=this._getStdin(e);this._postRead(i),t=this._readBuffer.length>0}return t}read(e){if(!this._enabled)throw Error("WorkerIO.read when disabled");if(null!==e&&e<=0)return[];if(this._readBuffer.length>0&&this._canReturnNow())return this._readFromBuffer(e);for(;!this._canReturnNow();){let e=this._getStdin(-1);this._postRead(e)}return this._readFromBuffer(e)}async readAsync(e,t){if(!this._enabled)throw Error("WorkerIO.readAsync when disabled");if(null!==e&&e<=0)return[];if(this._readBuffer.length>0&&this._canReturnNow())return this._readFromBuffer(e);for(;!this._canReturnNow();){let e=await this._getStdinAsync(t);if(this._postRead(e),""===e&&t>=0)break}return this._readFromBuffer(e)}utf8ArrayToString(e){return void 0===this._utf8Decoder&&(this._utf8Decoder=new TextDecoder("utf8")),this._utf8Decoder.decode(e)}write(e){let t=[];t="string"==typeof e?this._processWriteChars(e.split("").map(e=>e.charCodeAt(0))):this._processWriteChars(e),this.outputCallback(v(t))}_canReturnNow(){if(this._isLineBuffering()){let e=this._readBuffer.at(-1);return 10===e||4===e}return this._readBuffer.length>0}_isLineBuffering(){return(this.termios.get().c_lflag&d.LocalFlag.ICANON)>0}_maybeEchoToOutput(e){let t=this.termios.get(),i=(t.c_lflag&d.LocalFlag.ECHO)>0,r=(t.c_lflag&d.LocalFlag.ECHONL)>0;if(!i&&!r)return;let s=[];for(let r of e)switch(r){case 10:t.c_oflag&d.OutputFlag.ONLCR?s.push(13,10):s.push(10);break;case 4:break;case 127:s.push(8,32,8);break;default:i&&s.push(r)}s.length>0&&this.write(s)}_postRead(e){let t=e.split("").map(e=>e.charCodeAt(0));this._processReadChars(t)}_processReadChars(e){let t=this.termios.get(),i=[];for(let r of e)switch(r){case 13:(t.c_iflag&d.InputFlag.IGNCR)==0&&((t.c_iflag&d.InputFlag.ICRNL)>0?(i.push(10),this._readBuffer.push(10)):(i.push(13),this._readBuffer.push(13)));break;case 10:(t.c_iflag&d.InputFlag.INLCR)>0?(i.push(13),this._readBuffer.push(13)):(i.push(10),this._readBuffer.push(10));break;case 127:(t.c_lflag&d.LocalFlag.ICANON)==0?(i.push(127),this._readBuffer.push(127)):this._readBuffer.length>0&&(i.push(127),this._readBuffer.pop());break;default:i.push(r),this._readBuffer.push(r)}this._maybeEchoToOutput(i)}_processWriteChars(e){let{c_oflag:t}=this.termios.get(),i=[];for(let r=0;r<e.length;r++){let s=e[r];if(27===s){let t=e.at(r+1);if(91===t||93===t){let t=91===e[r+1],s=e.slice(r+2).findIndex(e=>t?e>=65&&e<=90||e>=97&&e<=122:7===e||27===e);if(s>=0){let t=e.slice(r,r+s+3);i.push(...t),r+=s+2;let n=v(t);this._inAlternativeBuffer?n===k&&(this._inAlternativeBuffer=!1):n===I?this._inAlternativeBuffer=!0:n===T&&(this._writeColumn=0);continue}}else if(void 0!==t){let t=e.slice(r,r+2);i.push(...t),r+=1;continue}}switch(s){case 13:13!==i.at(-1)&&i.push(13);break;case 10:if(0===this._writeColumn&&(t&d.OutputFlag.ONOCR)>0)break;this._writeColumn=0,(t&d.OutputFlag.ONLCR)>0&&13!==i.at(-1)&&i.push(13),i.push(10);break;default:!this._inAlternativeBuffer&&s>=32&&this._writeColumn++,i.push(s)}}return i}_readFromBuffer(e){if(null===e){let e=this._readBuffer;return this._readBuffer=[],e}{let t=this._readBuffer.slice(0,e);return this._readBuffer.splice(0,t.length),t}}_available;_enabled=!1;_inAlternativeBuffer=!1;_utf8Decoder;_writeColumn=0;_readBuffer=[]}class Q extends q{constructor(e,t,i,r,s){super(e,t),this._utils=new S(i,r,s)}_getStdin(e){return this._utils.getStdin(e)}async _getStdinAsync(e){return this._utils.getStdinAsync(e)}_utils}(s=m||(m={})).REQUEST_INDEX=0,s.TIMEOUT_INDEX=1,s.LENGTH_INDEX=2,s.START_INDEX=3,s.NO_REQUEST_VALUE=0,s.REQUEST_VALUE=1,s.MORE_TO_FOLLOW_VALUE=2,s.ABORT_VALUE=3,s.maxChars=1e3,s.encodeTimeout=function(e){return e<0||e>=1e5?1e5:Math.round(e)},s.decodeTimeout=function(e){return e>=1e5?-1:e};class X extends q{constructor(e,t,i){super(e,t);const r=m.maxChars+4;this._sharedArrayBuffer=i,this._intArray=new Int32Array(this._sharedArrayBuffer,0,r)}_getStdin(e){Atomics.load(this._intArray,m.REQUEST_INDEX)!==m.NO_REQUEST_VALUE&&console.error("SharedArrayBuffer stdin request already pending"),Atomics.store(this._intArray,m.TIMEOUT_INDEX,m.encodeTimeout(e));let t="",i=!0;for(;i;){Atomics.store(this._intArray,m.REQUEST_INDEX,m.REQUEST_VALUE),Atomics.notify(this._intArray,m.REQUEST_INDEX,1),Atomics.wait(this._intArray,m.REQUEST_INDEX,m.REQUEST_VALUE),i=Atomics.load(this._intArray,m.REQUEST_INDEX)===m.MORE_TO_FOLLOW_VALUE;let e=Atomics.load(this._intArray,m.LENGTH_INDEX);for(let i=0;i<e;i++)t+=String.fromCharCode(Atomics.load(this._intArray,m.START_INDEX+i))}return t}async _getStdinAsync(e){Atomics.load(this._intArray,m.REQUEST_INDEX)!==m.NO_REQUEST_VALUE&&console.error("SharedArrayBuffer stdin request already pending"),Atomics.store(this._intArray,m.TIMEOUT_INDEX,m.encodeTimeout(e));let t="",i=!0;for(;i;){Atomics.store(this._intArray,m.REQUEST_INDEX,m.REQUEST_VALUE),Atomics.notify(this._intArray,m.REQUEST_INDEX,1);let{async:e,value:r}=Atomics.waitAsync(this._intArray,m.REQUEST_INDEX,m.REQUEST_VALUE);e&&await r,i=Atomics.load(this._intArray,m.REQUEST_INDEX)===m.MORE_TO_FOLLOW_VALUE;let s=Atomics.load(this._intArray,m.LENGTH_INDEX);for(let e=0;e<s;e++)t+=String.fromCharCode(Atomics.load(this._intArray,m.START_INDEX+e))}return t}_intArray;_sharedArrayBuffer}class J{setMainIO;setWorkerIO;constructor(e,t){this.setMainIO=e,this.setWorkerIO=t,this._map.set("sab",{longName:"shared array buffer",available:!1}),this._map.set("sw",{longName:"service worker",available:!1})}available(e){return this._getByShortName(e).available}get enabled(){return this._enabled}get shortNames(){return Array(...this._map.keys())}longName(e){return this._getByShortName(e).longName}setAvailable(e,t){this._getByShortName(e).available=t}setEnabled(e){if(this._map.has(e))return void this._enable(e);let t=Object.entries(this._map).find(([t,i])=>i.longName===e);if(void 0!==t)this._enable(t[0]);else throw Error(`Unknown StdinContext name '${e}'`)}_enable(e){if(e!==this._enabled){if(!this._getByShortName(e).available)throw Error(`StdinContext '${e}' is not available`);this._enabled=e,this._initialised?(this.setWorkerIO(e),this.setMainIO(e)):this._initialised=!0}}_getByShortName(e){let t=this._map.get(e);if(void 0===t)throw Error(`Unknown shortName '${e}' passed to StdinContext`);return t}_map=new Map;_enabled="";_initialised=!1}class G extends Map{constructor(){super()}getRecursive(e){let t=this.get(e);for(;void 0!==t;){let i=t.split(" ")[0];if(i===e)break;let r=this.get(i);if(void 0===r)break;t=r+t.slice(i.length),e=i}return t}match(e){return[...this.keys()].filter(t=>t.startsWith(e))}}class Y{get(e,t){let i=this.key(e,t);return this._cache.get(i)??void 0}has(e,t){let i=this.key(e,t);return this._cache.has(i)}key(e,t){return[e,t].join("/")}set(e,t,i){let r=this.key(e,t);this._cache.set(r,i)}_cache=new Map}class K{wasmBaseUrl;wasmUrlQueryParamsCallback;downloadModuleCallback;constructor(e,t,i){this.wasmBaseUrl=e,this.wasmUrlQueryParamsCallback=t,this.downloadModuleCallback=i}async getJavaScriptModule(e,t){let i=await this._getModule(e,t,!1);return void 0!==i?i:void 0}async getWasmModule(e,t){let i=await this._getModule(e,t,!0);return void 0!==i?i:void 0}async _getModule(e,t,i){let r=this.cache.get(e,t);if(void 0===r){let s=this.cache.key(e,t)+".js",n=await this.wasmUrlQueryParamsCallback(s),a=C(this.wasmBaseUrl,s+n);console.log(`Cockle loading ${i?"WebAssembly":"JavaScript"} module from ${a}`),this.downloadModuleCallback(e,t,!0);try{importScripts(a),r=self.Module}finally{this.downloadModuleCallback(e,t,!1)}void 0!==r&&this.cache.set(e,t,r)}return r}cache=new Y}(n=f||(f={}))[n.None=0]="None",n[n.Unknown=1]="Unknown",n[n.Builtin=2]="Builtin",n[n.External=4]="External",n[n.JavaScript=8]="JavaScript",n[n.Wasm=16]="Wasm",n[n.All=31]="All";class Z extends Error{exitCode;constructor(e,t){super(t),this.exitCode=e}}class ee extends Z{constructor(e){super(127,`'${e}': command not found`)}}class et extends Z{constructor(e){super(127,`'${e}': cannot load command`)}}class ei extends Z{constructor(e){super(1,e)}}class er extends Z{constructor(e){super(126,`'${e}': cannot run command`)}}class es{name;callExternalCommand;callExternalTabComplete;constructor(e,t,i){this.name=e,this.callExternalCommand=t,this.callExternalTabComplete=i}get commandType(){return f.External}get moduleName(){return"<external>"}names(){return[this.name]}get packageName(){return""}async run(e){let{name:t,args:i,environment:r,stdin:s,stdout:n,stderr:a}=e;if(t!==this.name)throw new ee(t);let{exitCode:o,environmentChanges:l}=await this.callExternalCommand(t,i,Object.fromEntries(r),s.isTerminal(),n.isTerminal(),a.isTerminal(),e.termios.get());return void 0!==l&&Object.entries(l).forEach(([e,t])=>{void 0===t?r.delete(e):r.set(e,t)}),o}async tabComplete(e){if(void 0!==this.callExternalTabComplete){let{name:t,args:i}=e;return await this.callExternalTabComplete(t,i)}return{}}}class en{get commandType(){return f.Builtin}get moduleName(){return"<builtin>"}get packageName(){return""}names(){return[this.name]}run(e){let{name:t}=e;if(t!==this.name)throw new ee(t);return this._run(e)}}class ea{shortName;longName;description;constructor(e,t,i){if(this.shortName=e,this.longName=t,this.description=i,0!==e.length&&1!==e.length)throw new ei(`Argument shortName ${e} must be a string of length 1`);if(!(0===t.length||t.length>1))throw new ei(`Argument longName ${t} must be a string of length greater than 1`)}get isSet(){return this._isSet}parse(e,t){return this.set(),t}set(){this._isSet=!0}_isSet=!1}class eo extends ea{constructor(e,t,i){super(e,t,i)}}class el extends ea{options;constructor(e={}){super("","",""),this.options=e;const{max:t,min:i}=e;if(void 0!==i){if(i<0)throw new ei("Negative min for positional arguments");if(void 0!==t&&t<i)throw new ei("max must be greater than min for positional arguments")}}get length(){return this._strings.length}parse(e,t){for(let i of(this._strings.push(e),this.set(),t)){if(i.startsWith("-"))throw new ei("Cannot have named argument after positional arguments");this._strings.push(i)}return[]}get strings(){return this._strings}_strings=[]}class eh extends el{options;constructor(e={}){super(e),this.options=e}}(a=p||(p={}))[a.TOP=0]="TOP",a[a.MIDDLE=1]="MIDDLE",a[a.BOTTOM=2]="BOTTOM",(o=_||(_={}))[o.LEFT=0]="LEFT",o[o.INNER=1]="INNER",o[o.RIGHT=2]="RIGHT";class eu{options;constructor(e){this.options=e}addHeaderRow(e){this._headerRows.push(e),this._updateColumnWidths(e)}addRow(e){this._rows.push(e),this._updateColumnWidths(e)}static defaultColorByColumn(){return new Map([[1,$],[2,j],[3,z],[4,V]])}*lines(e="",t=""){let{sortByColumn:i}=this.options;if(void 0!==i){let e=(t,r,s)=>{let n=i[t];return r[n]<s[n]?-1:r[n]>s[n]?1:i.length>t+1?e(t+1,r,s):0};this._rows.sort((t,i)=>e(0,t,i))}let r=this._columnWidths.length,s=this.horizontalSpacer(p.TOP);for(let i of(void 0!==s&&(yield e+x(s)+t),this._headerRows)){let s="";for(let e=0;e<r;e++){s+=this.verticalSpacer(0===e?_.LEFT:_.INNER);let t=i[e]??"";s+=t+" ".repeat(this._columnWidths[e]-this._cleanString(t).length)}s+=this.verticalSpacer(_.RIGHT),yield e+x(s)+t}if(this._headerRows.length>0){let i=this.horizontalSpacer(p.MIDDLE);void 0!==i&&(yield e+x(i)+t)}for(let i of this._rows){let s="";for(let e=0;e<r;e++){s+=this.verticalSpacer(0===e?_.LEFT:_.INNER);let t=i[e]??"";if(t){let i=this.options.colorByColumn?.get(e);s+=void 0!==i?i+t+B:t}s+=" ".repeat(this._columnWidths[e]-this._cleanString(t).length)}s+=this.verticalSpacer(_.RIGHT),yield e+x(s)+t}let n=this.horizontalSpacer(p.BOTTOM);void 0!==n&&(yield e+x(n)+t)}get rowCount(){return this._rows.length}write(e,t="",i="\n"){for(let r of this.lines(t,i))e.write(r)}_cleanString(e){return D(e)}_updateColumnWidths(e){let t=e.map(e=>this._cleanString(e).length),i=Math.min(this._columnWidths.length,t.length);for(let e=0;e<i;e++)this._columnWidths[e]=Math.max(this._columnWidths[e],t[e]);t.length>i&&this._columnWidths.push(...t.slice(i))}_columnWidths=[];_headerRows=[];_rows=[]}class ec extends eu{constructor(e={}){super(e);const t=e.spacerSize??2;this._spacer=" ".repeat(t),this._spacersAtEnds=e.spacersAtEnds??!1}horizontalSpacer(e){if(e===p.MIDDLE){let e=this._columnWidths.reduce((e,t)=>e+t)+this._totalSeparatorSize();return"─".repeat(e)}}verticalSpacer(e){return e===_.INNER||this._spacersAtEnds?this._spacer:""}_totalSeparatorSize(){let e=this._columnWidths.length-1;return this._spacersAtEnds&&(e+=2),e*this._spacer.length}_spacer;_spacersAtEnds}class ed extends eu{constructor(e={}){super(e)}horizontalSpacer(e){let t=(e=>{switch(e){case p.TOP:return"╭┬╮";case p.MIDDLE:return"├┼┤";case p.BOTTOM:return"╰┴╯"}})(e);return t[0]+this._columnWidths.map(e=>"─".repeat(e+2)).join(t[1])+t[2]}verticalSpacer(e){return e===_.LEFT?"│ ":e===_.RIGHT?" │":" │ "}}(l=g||(g={}))[l.Any=0]="Any",l[l.Directory=1]="Directory",l[l.File=2]="File";class em{parse(e){return this._parseToRun(e.slice()),this}async tabComplete(e){let t={...e,args:e.args.slice()},i=await this._parseToTabComplete(t);return i.possibles&&(i.possibles=i.possibles.filter(t=>t.startsWith(e.args.at(-1)))),i}writeHelp(e){for(let t of this._help())e.write(`${t} `)}_findByLongName(e){let t=this._longNameArguments;if(e in t)return t[e];throw new ei(`No such longName argument '${e}'`)}_findByShortName(e){let t=this._shortNameArguments;if(e in t)return t[e];throw new ei(`No such shortName argument '${e}'`)}*_help(){this.description&&(yield this.description);let e=new ec({spacerSize:3});for(let t of Object.values(this))if(t instanceof ea){let{longName:i,shortName:r}=t;if(i||r){let s=r?`-${r}`:" ";i&&(s+=(r?", ":" ")+`--${i}`),e.addRow([s,t.description])}}if(e.rowCount>0&&(yield"",yield"options:",yield*e.lines(" ")),void 0!==this.subcommands){let e=new ec({spacerSize:3});for(let t of Object.values(this.subcommands))e.addRow([t.name,t.description]);e.rowCount>0&&(yield"",yield"subcommands:",yield*e.lines(" "))}}get _longNameArguments(){return Object.fromEntries(Object.values(this).filter(e=>e instanceof ea&&"longName"in e&&e.longName.length>0).map(e=>[e.longName,e]))}_parseToRun(e){let{positional:t}=this,i=!1,r=this.subcommands??{},s=!0;for(;e.length>0;){let n=e.shift();if(s&&n in r){let t=r[n];t.set(),t.parse(e);break}if(n.startsWith("-")&&n.length>1){if(i)throw new ei("Cannot have named argument after positional arguments");if(n.startsWith("--")){let t=n.slice(2);e=this._findByLongName(t).parse(n,e)}else for(let t of n.slice(1).split(""))e=this._findByShortName(t).parse(n,e)}else if(void 0!==t)i=!0,e=t.parse(n,e);else throw new ei(`Unrecognised argument: '${n}'`);s=!1}if(void 0!==t){let{min:e,max:i}=t.options;if(void 0!==e&&t.length<e)throw new ei("Insufficient positional arguments");if(void 0!==i&&t.length>i)throw new ei("Too many positional arguments")}}async _parseToTabComplete(e){let{args:t}=e,{positional:i}=this,r=this.subcommands??{},s=!0;for(;t.length>0;){let n=t.shift(),a=0===t.length;if(s&&r){if(a){let e=Object.keys(r).filter(e=>e.startsWith(n));if(e.length>0)return{possibles:e}}if(n in r){let t=r[n];return t.set(),await t.tabComplete(e)}}if(n.startsWith("-"))if(a){let e=Object.keys(this._longNameArguments).map(e=>"--"+e);if(n.startsWith("--"))return{possibles:e};if(n.length>2)return{};return{possibles:Object.keys(this._shortNameArguments).map(e=>"-"+e).concat(e)}}else if(n.startsWith("--")){let e=n.slice(2);t=this._findByLongName(e).parse(n,t)}else for(let e of n.slice(1).split(""))t=this._findByShortName(e).parse(n,t);else if(void 0!==i)if(i instanceof eh)return{pathType:i.options.pathType??g.Any};else{let r=i.options.tabComplete;if(void 0!==r)return await r({...e,args:[n,...t]})}s=!1}return{}}get _shortNameArguments(){return Object.fromEntries(Object.values(this).filter(e=>e instanceof ea&&"shortName"in e&&e.shortName.length>0).map(e=>[e.shortName,e]))}positional;subcommands;description}class ef extends em{name;description;constructor(e,t){super(),this.name=e,this.description=t}get isSet(){return this._isSet}set(){this._isSet=!0}_isSet=!1}class ep extends em{description=`Without arguments, 'alias' prints the list of aliases in the reusable form 'alias NAME=VALUE' on standard output. Otherwise, an alias is defined for each NAME whose VALUE is given. A trailing space in VALUE causes the next word to be checked for alias substitution when the alias is expanded.`;positional=new el;help=new eo("h","help","display this help and exit")}class e_ extends en{get name(){return"alias"}async tabComplete(e){return await new ep().tabComplete(e)}async _run(e){let{aliases:t,stdout:i}=e,r=new ep().parse(e.args);if(r.help.isSet)return r.writeHelp(i),0;if(r.positional.isSet)for(let e of r.positional.strings){let r=e.indexOf("=");-1===r?i.write(`${e}='${t.get(e)}' `):t.set(e.slice(0,r),e.slice(r+1))}else for(let[e,r]of t.entries())i.write(`${e}='${r}' `);return 0}}class eg extends em{help=new eo("h","help","display this help and exit")}class ew extends eg{description="Always succeeds; Return a successful result."}class ey extends eg{description="Always fails; Return an unsuccessful result."}class eb extends en{get name(){return"true"}async tabComplete(e){return await new ew().tabComplete(e)}async _run(e){let t=new ew().parse(e.args);return t.help.isSet&&t.writeHelp(e.stdout),0}}class eC extends en{get name(){return"false"}async tabComplete(e){return await new ey().tabComplete(e)}async _run(e){let t=new ey().parse(e.args);return t.help.isSet?(t.writeHelp(e.stdout),0):1}}class ex extends em{description=`Change the shell working directory. Change the current directory to DIR. If DIR is "-", it is converted to $OLDPWD.`;positional=new eh({pathType:g.Directory});help=new eo("h","help","display this help and exit")}class ev extends en{get name(){return"cd"}async tabComplete(e){return await new ex().tabComplete(e)}async _run(e){let t=new ex().parse(e.args);if(t.help.isSet)return t.writeHelp(e.stdout),0;let i=t.positional.strings;if(i.length<1)return 0;if(i.length>1)throw new ei("cd: too many arguments");let r=i[0];if("-"===r){let t=e.environment.get("OLDPWD");if(void 0===t)throw new ei("cd: OLDPWD not set");r=t,e.stdout.write(`${r} `)}let{FS:s}=e.fileSystem,n=s.cwd();try{s.chdir(r)}catch(s){let{errno:t}=s,{ERRNO_CODES:i}=e.fileSystem;return t===i.ENOENT?e.stderr.write(`cd: ${r}: No such file or directory `):t===i.ENOTDIR?e.stderr.write(`cd: ${r}: Not a directory `):e.stderr.write(`cd: ${r}: Unable to cd `),1}return e.environment.set("OLDPWD",n),e.environment.set("PWD",s.cwd()),0}}class eS extends em{description="Clear the terminal screen if ANSI escapes are supported.";help=new eo("h","help","display this help and exit")}class eE extends en{get name(){return"clear"}async tabComplete(e){return await new eS().tabComplete(e)}async _run(e){let{stdout:t}=e,i=new eS().parse(e.args);return i.help.isSet?i.writeHelp(t):t.isTerminal()&&t.write(R+P+T),0}}class eO extends ef{help=new eo("h","help","display this help and exit");builtin=new eo("b","builtin","display only builtin commands");external=new eo("e","external","display only external commands");javascript=new eo("j","javascript","display only javascript commands");wasm=new eo("w","wasm","display only wasm commands");positional=new el({tabComplete:async e=>({possibles:e.commandRegistry?.match(e.args.at(-1)||"",eR(this))??[]})})}class eI extends ef{positional=new el({tabComplete:async e=>({possibles:e.commandRegistry?.allModules().map(e=>e.name)??[]})})}class ek extends ef{positional=new el({tabComplete:async e=>({possibles:e.commandRegistry?[...e.commandRegistry.commandPackageMap.keys()]:[]})})}class eN extends ef{positional=new el({max:1,tabComplete:async e=>({possibles:e.stdinContext?.shortNames??[]})})}class eA extends em{description="Inspect and optionally modify Cockle configuration. Without arguments prints all sections. Use subcommands to target specific areas.";version=new eo("v","version","show cockle version");worker=new eo("w","worker","show web worker type");help=new eo("h","help","display this help and exit");subcommands={command:new eO("command","Show information about one or more commands."),module:new eI("module","Show information about one or more modules."),package:new ek("package","Show information about one or more packages."),stdin:new eN("stdin","Configure or show synchronous stdin settings.")}}class eT extends en{get name(){return"cockle-config"}async tabComplete(e){return await new eA().tabComplete(e)}async _run(e){let{environment:t,stdout:i}=e,r=new eA().parse(e.args),{subcommands:s}=r;if(r.help.isSet)return r.writeHelp(i),0;let n=i.isTerminal()&&t.color?ed.defaultColorByColumn():void 0,a=0===e.args.length;if((a||r.version.isSet)&&this._writeVersion(e),(a||s.stdin.isSet)&&this._writeOrSetSyncStdinConfig(e,n,s.stdin.positional.strings.at(0)),(a||s.package.isSet)&&this._writePackageConfig(e,n,s.package.positional.strings),(a||s.module.isSet)&&this._writeModuleConfig(e,n,s.module.positional.strings),s.command.isSet){let{command:t}=s;if(t.help.isSet)return t.writeHelp(i),0;this._writeCommandConfig(e,n,t)}return r.worker.isSet&&this._writeWorker(e),0}_writeCommandConfig(e,t,i){let{commandRegistry:r,stdout:s}=e,n=i.positional.strings,a=r.commandNames(eR(i));if(n.length>0){let e=n.filter(e=>!a.includes(e));if(e.length>0)throw new ei(`Unknown command(s): ${e.sort().join(" ")}`);a=n.sort()}let o=new ed({colorByColumn:t,sortByColumn:[0]});for(let e of(o.addHeaderRow(["command","module"]),a)){let t=r.get(e);if(null===t)throw new ei(`Unknown command '${e}'`);o.addRow([e,t.moduleName])}o.write(s)}_writeModuleConfig(e,t,i){let{commandRegistry:r,commandModuleCache:s,stdout:n}=e,a=r.allModules(),o=a.map(e=>e.name);if(i.length>0){let e=i.filter(e=>!o.includes(e));if(e.length>0)throw new ei(`Unknown module(s): ${e.sort().join(" ")}`);a=a.filter(e=>i.includes(e.name))}let l=new ed({colorByColumn:t,sortByColumn:[0,1]});for(let e of(l.addHeaderRow(["module","package","cached"]),a))l.addRow([e.name,e.packageName,s.has(e.packageName,e.name)?"yes":""]);l.write(n)}_writeOrSetSyncStdinConfig(e,t,i){let{stdinContext:r,stdout:s}=e;void 0!==i&&r.setEnabled(i);let n=new ed({colorByColumn:t});n.addHeaderRow(["synchronous stdin","short name","available","enabled"]);let{enabled:a,shortNames:o}=r;for(let e of o)n.addRow([r.longName(e),e,r.available(e)?"yes":"",a===e?"yes":""]);n.write(s)}_writePackageConfig(e,t,i){let{commandRegistry:r,stdout:s}=e,n=[...r.commandPackageMap.keys()];if(i.length>0){let e=i.filter(e=>!n.includes(e));if(e.length>0)throw new ei(`Unknown package(s): ${e.sort().join(" ")}`);n=i.sort()}let a=new ed({colorByColumn:t,sortByColumn:[0]});for(let e of(a.addHeaderRow(["package","type","version","build string","source"]),n)){let t=r.commandPackageMap.get(e);a.addRow([t.name,t.wasm?"wasm":"js",t.version,t.build_string,t.channel])}a.write(s)}_writeVersion(e){let{stdout:t}=e;t.write(`cockle 1.7.0 `)}_writeWorker(e){let{stdout:t,workerType:i}=e;t.write(`${i} worker `)}}function eR(e){let t=f.None;return e.builtin.isSet&&(t|=f.Builtin),e.external.isSet&&(t|=f.External),e.javascript.isSet&&(t|=f.JavaScript),e.wasm.isSet&&(t|=f.Wasm),t===f.None&&(t=f.All),t}class eP extends em{description="Exit the shell";help=new eo("h","help","display this help and exit")}class eM extends en{get name(){return"exit"}async tabComplete(e){return await new eP().tabComplete(e)}async _run(e){let{stdout:t,terminate:i}=e,r=new eP().parse(e.args);return r.help.isSet?r.writeHelp(t):(t.write("Terminating shell...\n"),t.flush(),i()),0}}class eL extends em{description=`Set export attribute for shell variables. Marks each NAME for automatic export to the environment of subsequently executed commands. If VALUE is supplied, assign VALUE before exporting.`;positional=new el;help=new eo("h","help","display this help and exit")}class eD extends en{get name(){return"export"}async tabComplete(e){return await new eL().tabComplete(e)}async _run(e){let{environment:t,stdout:i}=e,r=new eL().parse(e.args);if(r.help.isSet)return r.writeHelp(i),0;if(r.positional.isSet)for(let e of r.positional.strings){let i=e.indexOf("=");if(i>0){let r=e.slice(0,i),s=e.slice(i+1);t.set(r,s)}}return 0}}class eB extends em{description="Show help for built-in commands. With no arguments, lists available builtins. With names, shows each command's help (equivalent to '<cmd> --help').";help=new eo("h","help","display this help and exit");positional=new el({tabComplete:async e=>({possibles:e.commandRegistry?.commandNames(f.Builtin)??[]})})}class eF extends en{get name(){return"help"}async tabComplete(e){return await new eB().tabComplete(e)}async _run(e){let{args:t,stdout:i,stderr:r,commandRegistry:s}=e,n=new eB().parse(t);if(n.help.isSet)return n.writeHelp(i),0;let a=n.positional.strings,o=s?s.commandNames(f.Builtin):[];if(0===a.length){for(let e of(i.write("Built-in commands:\n"),o))i.write(` ${e} `);return i.write("\n"),i.write("For detailed help, type <command-name> --help (e.g., `history --help` or `alias -h`)."),0}let l=0;for(let t of a){if(!o.includes(t)){r.write(`help: unknown built-in: ${t} `),l=1;continue}let n=s.get(t);if(null===n){r.write(`help: failed to get command '${t}' `),l=1;continue}let a={...e,name:t,args:["--help"]};i.write(` === help for ${t} === `),await n.run(a)}return l}}class eW extends em{description=` Display or manipulate the history list. Display the history list with line numbers, prefixing each modified entry with a '*'`;clear=new eo("c","","clear the history by deleting all of the entries");help=new eo("h","help","display this help and exit")}class eU extends en{get name(){return"history"}async tabComplete(e){return await new eW().tabComplete(e)}async _run(e){let{history:t,stdout:i}=e,r=new eW().parse(e.args);return r.help.isSet?r.writeHelp(i):r.clear.isSet?t.clear():t.write(i),0}}class e$ extends em{description=`Unset shell variables. For each NAME, remove the correpsonding environment variable. Ignores NAMEs that are not set.`;positional=new el({tabComplete:async e=>({possibles:e.environment?e.environment.names():[]})});help=new eo("h","help","display this help and exit")}class ej extends en{get name(){return"unset"}async tabComplete(e){return await new e$().tabComplete(e)}async _run(e){let{environment:t,stdout:i}=e,r=new e$().parse(e.args);if(r.help.isSet)return r.writeHelp(i),0;if(r.positional.isSet)for(let e of r.positional.strings)t.delete(e);return 0}}class eH extends em{description="Locate built-in commands by name. Prints each given command if it exists, otherwise an error message.";help=new eo("h","help","display this help and exit");positional=new el({tabComplete:async e=>({possibles:e.commandRegistry?.commandNames()??[]})})}class ez extends en{get name(){return"which"}async tabComplete(e){return await new eH().tabComplete(e)}async _run(e){let{args:t,stdout:i}=e,r=new Set(e.commandRegistry?.commandNames()),s=new eH().parse(e.args);if(s.help.isSet)return s.writeHelp(i),0;if(0===s.positional.strings.length)return i.write("which: missing operand\n"),s.writeHelp(i),1;let n=0;for(let i of t)r.has(i)?e.stdout.write(`${i} `):(e.stdout.write(`which: no ${i} command `),n=1);return n}}class eV{callExternalCommand;callExternalTabComplete;constructor(e,t){this.callExternalCommand=e,this.callExternalTabComplete=t,this.registerBuiltinCommands(b)}allModules(){let e=[];for(let t of this.commandPackageMap.values())e.push(...t.modules);return e.sort((e,t)=>e.name<t.name?-1:1),e}commandNames(e=f.All){return e===f.None?[]:e===f.All?Array.from(this._map.keys()).sort():Array.from(this._map).filter(([t,i])=>(i.commandType&e)>0).map(([e,t])=>e).sort()}get(e){return this._map.get(e)??null}match(e,t=f.All){return this.commandNames(t).filter(t=>t.startsWith(e))}registerBuiltinCommands(e){for(let[t,i]of Object.entries(e))if(!(!t.endsWith("Command")||t.startsWith("Builtin")))try{let e=new i;e instanceof en&&this._register(e)}catch{}}registerCommandPackage(e){for(let t of(this.commandPackageMap.set(e.name,e),e.modules))this._register(t.runner)}registerExternalCommand(e,t){this._validName(e)&&this._map.set(e,new es(e,this.callExternalCommand,t?this.callExternalTabComplete:void 0))}_register(e){for(let t of e.names())this._validName(t)&&this._map.set(t,e)}_validName(e){let t=null!==e.match(/^[\w-]+$/);return t||console.warn(`${e} is not a valid command name`),t}_map=new Map;commandPackageMap=new Map}class eq{module;constructor(e){this.module=e}get moduleName(){return this.module.moduleName}names(){return this.module.names}get packageName(){return this.module.packageName}}class eQ{input;constructor(e){this.input=e}isTerminal(){return this.input.isTerminal()}async readAsync(e){return v(await this.input.readAsync(e))}}class eX extends eq{module;constructor(e){super(e),this.module=e}get commandType(){return f.JavaScript}async run(e){let{name:t}=e,i=await this.module.loader.getJavaScriptModule(this.packageName,this.moduleName);if(void 0===i)throw new ee(t);if(!Object.prototype.hasOwnProperty.call(i,"run"))throw new et(t);let{args:r,environment:s,fileSystem:n,shellId:a,stdout:o,stderr:l,termios:h,size:u}=e,c=new eQ(e.stdin);try{return await i.run({name:t,args:r,environment:s,fileSystem:n,shellId:a,stdin:c,stdout:o,stderr:l,size:u,termios:h})}catch(e){throw console.error(`JavascriptCommandRunner: ${e}`),new er(t)}}async tabComplete(e){let t=await this.module.loader.getJavaScriptModule(this.packageName,this.moduleName);if(void 0!==t&&Object.prototype.hasOwnProperty.call(t,"tabComplete")&&void 0!==t.tabComplete){let{name:i,args:r,shellId:s}=e;try{return await t.tabComplete({name:i,args:r,shellId:s})}catch(e){}}return{}}}class eJ extends eq{module;constructor(e){super(e),this.module=e}get commandType(){return f.Wasm}async run(e){let t,{name:i,args:r,workerIO:s,fileSystem:n,stdin:a,stdout:o,stderr:l,termios:h,size:u}=e,{wasmBaseUrl:c}=this.module.loader,d="less"===i,m=performance.now(),f=await this.module.loader.getWasmModule(this.packageName,this.moduleName);if(void 0===f)throw new ee(i);function p(e){return h.get()}function _(e,t,i){return h.set(i),0}function g(e){let{rows:t,columns:i}=u();return[t,i]}function w(e,t){return d&&t<0&&(t=0),4|!!(a.finished?s.pollInput(t):a.poll(t))}function y(e,t,i,r,n){if(0===r)return 0;let o=a.finished?s.read(r):a.read(r);return 1===o.length&&4===o[0]&&(o=[]),t.set(o,i),o.length}function b(e,t,i,r,n){if(0===r)return 0;let a=t.slice(i,i+r),h=s.utf8ArrayToString(a);return("/dev/tty1"===e.path?l:o).write(h),r}function x(e){void 0===t&&(t=e)}let v=await f({thisProgram:i,arguments:r,locateFile:e=>C(c,this.packageName+"/"+e),onExit:e=>x(e),quit:(e,t)=>x(e),preRun:[t=>{let{ENV:i,FS:r,TTY:s}=t;if(void 0!==r){let e=t.FS,{mountpoint:i}=n;e.mkdir(i,511),e.mount(t.PROXYFS??n.PROXYFS,{root:i,fs:n.FS},i),e.chdir(n.FS.cwd())}if(void 0!==i&&e.environment.copyIntoCommand(t.ENV),void 0!==s){let{default_tty_ops:e,default_tty1_ops:i,stream_ops:r}=t.TTY;e.ioctl_tcgets=p,e.ioctl_tcsets=_,e.ioctl_tiocgwinsz=g,i.ioctl_tcgets=p,i.ioctl_tcsets=_,i.ioctl_tiocgwinsz=g,r.poll=w,r.read=y,r.write=b}}],stdin:this._inputHandler(a),stderr:this._outputHandler(l),stdout:this._outputHandler(o)});if(void 0===t)t=126;else if(Object.prototype.hasOwnProperty.call(v,"FS")){let e=v.FS;for(let t of[e.streams[1],e.streams[2]])null===t||e.isClosed(t)||e.close(t)}let S=performance.now();return console.debug(`Cockle ${i} load and run time ${(S-m).toFixed(1)} ms`),t}_inputHandler(e){if(!e.isTerminal())return()=>{let t=e.read(1);return t.length>0?t[0]:null}}_outputHandler(e){if(!e.isTerminal())return t=>e.write(String.fromCharCode(t))}}class eG{commandModuleLoader;name;commands;packageName;wasm;constructor(e,t,i,r,s){this.commandModuleLoader=e,this.name=t,this.commands=i,this.packageName=r,this.wasm=s}get loader(){return this.commandModuleLoader}get runner(){return void 0===this._runner&&(this._runner=this.wasm?new eJ(this):new eX(this)),this._runner}get moduleName(){return this.name}get names(){return this.commands}_runner}class eY{name;version;build_string;channel;platform;wasm;modules;constructor(e,t,i,r,s,n,a){this.name=e,this.version=t,this.build_string=i,this.channel=r,this.platform=s,this.wasm=n,this.modules=a}}class eK extends Map{constructor(e,t,i){super(),t&&this.set("COCKLE_SHELL_ID",t),i&&this.set("COCKLE_BROWSING_CONTEXT_ID",i),e?(this.set("PS1",z+"js-shell:"+B+" "),this.set("TERM","xterm-256color"),this.set("TERMINFO","/usr/local/share/terminfo")):this.set("PS1","js-shell: ")}copyIntoCommand(e){for(let[t,i]of this.entries())e[t]=i}getNumber(e){let t=this.get(e);if(null===t)return null;let i=Number(t);return isNaN(i)?null:i}getPrompt(){return this.get("PS1")??"$ "}get color(){return this.has("TERM")}names(){let e=/^[A-Za-z_]/;return Array.from(this.keys()).filter(t=>e.test(t))}setSize(e){let{rows:t,columns:i}=e;if(t>=1){let e=t.toString();this.set("LINES",e)}else this.delete("LINES");if(i>=1){let e=i.toString();this.set("COLUMNS",e)}else this.delete("COLUMNS")}}class eZ{add(e){this._current=null,!e.trim()||this._ignoreInitialWhitespace&&e.startsWith(" ")||this._ignoreDuplicates&&e===this.at(-1)||(this._history.length>=this._maxSize&&this._history.shift(),this._history.push(e))}at(e){return this._history.at(e)??null}clear(){this._current=null,this._history=[]}scrollCurrent(e){return e?this._current=null===this._current?null:this._current+1:this._current=null===this._current?this._history.length-1:this._current-1,null!==this._current&&(this._current<0?this._current=0:this._current>=this._history.length&&(this._current=null)),null===this._current?null:this.at(this._current)}setMaxSize(e){this._maxSize=Math.max(e,0),this._history.length>this._maxSize&&(this._current=null,this._history=this._history.slice(this._maxSize))}write(e){for(let t=0;t<this._history.length;t++){let i=String(t).padStart(5," ");e.write(`${i} ${this._history[t]} `)}}_history=[];_current=null;_ignoreInitialWhitespace=!0;_ignoreDuplicates=!0;_maxSize=1e3}class e0{outputCallback;constructor(e,t,i){this.outputCallback=e,this.prefix=t,this.suffix=i}flush(){}isTerminal(){return!0}supportsAnsiEscapes(){return!0}write(e){e.length<1||(void 0!==this.prefix&&(e=this.prefix+e),void 0!==this.suffix&&(e+=this.suffix),this.outputCallback(e))}prefix;suffix}class e1{pollCallback;stdinCallback;stdinAsyncCallback;constructor(e,t,i){this.pollCallback=e,this.stdinCallback=t,this.stdinAsyncCallback=i}get finished(){return!1}isTerminal(){return!0}poll(e){return this.pollCallback(e)}async readAsync(e){return await this.stdinAsyncCallback(e)}read(e){return this.stdinCallback(e)}}class e2{get allContent(){return this.data.join("")}clear(){this.data=[]}isTerminal(){return!1}supportsAnsiEscapes(){return!1}write(e){this.data.push(e)}data=[]}class e3{get finished(){return this._index>=this.buffer.length}isTerminal(){return!1}poll(e){return!this.finished}async readAsync(e){return this.read(e)}read(e){let{buffer:t}=this;if(!(this._index<t.length))return[];{let e=t[this._index++],i=[];for(let t=0;t<e.length;t++)i.push(e.charCodeAt(t));return i}}get buffer(){return void 0===this._buffer&&(this._buffer=this.readAll(),this._index=0),this._buffer}_buffer;_index=0}class e8 extends e3{pipe;constructor(e){super(),this.pipe=e}readAll(){let e=this.pipe.allContent;return this.pipe.clear(),e}}class e5 extends e2{flush(){}get input(){return new e8(this)}}class e6 extends e2{fileSystem;path;append;constructor(e,t,i){super(),this.fileSystem=e,this.path=t,this.append=i}flush(){let{FS:e}=this.fileSystem,t=this.allContent;if(this.append)try{t=e.readFile(this.path,{encoding:"utf8"})+t}catch(e){}e.writeFile(this.path,t,{mode:436}),this.clear()}}class e4 extends e3{fileSystem;path;constructor(e,t){super(),this.fileSystem=e,this.path=t}readAll(){let{FS:e}=this.fileSystem;return e.readFile(this.path,{encoding:"utf8"})}}class e9{get finished(){return!1}isTerminal(){return!1}poll(e){return!1}async readAsync(e){return[]}read(e){return[]}}class e7{flush(){}isTerminal(){return!1}supportsAnsiEscapes(){return!1}write(e){}}(h=w||(w={}))[h.None=0]="None",h[h.Delimiter=1]="Delimiter",h[h.DoubleQuote=2]="DoubleQuote",h[h.SingleQuote=3]="SingleQuote",h[h.Whitespace=4]="Whitespace",h[h.Other=5]="Other";class te{throwErrors;aliases;constructor(e,t,i){this.throwErrors=t,this.aliases=i,this._source=e,this._tokens=[]}run(){for(;this._index<=this._source.length;)this._next();if(this.throwErrors&&""!==this._endQuote)throw new ei("Tokenize error, expected end quote "+this._endQuote)}get tokens(){return this._tokens}_addToken(){let e=this._offset,t=this._value;if(void 0!==this.aliases&&e!==this._aliasOffset&&(0===this._tokens.length||";&|".includes(this._tokens.at(-1).value.at(-1)))){let i=this.aliases.getRecursive(t);if(void 0!==i){let r=t.length;return this._offset=-1,this._index=e-1,this._aliasOffset=e,this._source=this._source.slice(0,e)+i+this._source.slice(e+r),this._prevChar="",this._prevCharType=w.None,this._value="",this._endQuote="",!1}}return this._tokens.push({offset:e,value:t}),this._endQuote="",!0}_getCharType(e){return" ".includes(e)?w.Whitespace:";&|><".includes(e)?w.Delimiter:"'"===e?w.SingleQuote:'"'===e?w.DoubleQuote:w.Other}_endQuoteFromCharType(e){return e===w.DoubleQuote?'"':e===w.SingleQuote?"'":""}_next(){let e=++this._index,t=e<this._source.length?this._source[e]:" ",i=this._getCharType(t),r=this._endQuoteFromCharType(i);this._offset>=0?this._endQuote?t!==this._endQuote?this._value+=t:(this._endQuote="",i=w.Other):r?this._endQuote=r:i===w.Whitespace?this._addToken()&&(this._offset=-1):i!==this._prevCharType||i===w.Delimiter&&t!==this._prevChar?"2"===this._value&&">"===t?this._value+=t:this._addToken()&&(this._offset=e,this._value=t):this._value+=t:i!==w.Whitespace&&(this._offset=e,this._endQuote=this._endQuoteFromCharType(i),this._value=""===this._endQuote?t:""),this._prevChar=t,this._prevCharType=i}_source;_tokens;_prevChar="";_prevCharType=w.None;_index=-1;_offset=-1;_aliasOffset=-1;_value="";_endQuote=""}class tt{}class ti extends tt{name;suffix;redirects;constructor(e,t,i){super(),this.name=e,this.suffix=t,this.redirects=i}lastToken(){return this.redirects&&this.redirects.length>0?this.redirects[this.redirects.length-1].lastToken():this.suffix.length>0?[this.suffix[this.suffix.length-1],!1]:[this.name,!0]}}class tr extends tt{commands;constructor(e){super(),this.commands=e}lastToken(){return this.commands.length>0?this.commands[this.commands.length-1].lastToken():[null,!1]}}class ts extends tt{token;target;constructor(e,t){super(),this.token=e,this.target=t}lastToken(){return[this.target,!1]}}function tn(e,t=!0,i){let r=function(e,t=!0,i){let r=new te(e,t,i);return r.run(),r.tokens}(e,t,i),s=[],n=[],a=-1,o=r.length;function l(){1===n.length?s.push(n[0]):n.length>1&&s.push(new tr([...n])),n.length=0}for(let e=0;e<o;e++){let t=r[e];a>=0?";&".includes(t.value)?(n.push(ta(r.slice(a,e))),l(),a=-1):"|"===t.value&&(n.push(ta(r.slice(a,e))),a=-1):";&".includes(t.value)||(a=e)}return a>=0&&n.push(ta(r.slice(a,o))),l(),s}function ta(e){let t,i=e.slice(1),r=i.findIndex(e=>to(e.value));return r>=0&&(t=function(e){let t=[];for(;e.length>0;){let i=e.shift();if(!to(i.value))throw new ei(`Expected redirect token not '${i.value}'`);if(e.length<1)throw new ei(`Redirect '${i.value}' should be followed by a file to redirect to`);let r=e.shift();t.push(new ts(i,r))}return t}(i.slice(r)),i=i.slice(0,r)),new ti(e[0],i,t)}function to(e){return e.startsWith(">")||e.startsWith("2>")||e.startsWith("<")}class tl{context;enableBufferedStdinCallback;termios;constructor(e,t,i){this.context=e,this.enableBufferedStdinCallback=t,this.termios=i}async complete(e){let t=e.text.slice(0,e.cursorIndex),i=e.text.slice(e.cursorIndex),r=tn(t,!1).at(-1),[s,n]=t.endsWith(" ")?[null,!1]:void 0!==r?r.lastToken():[null,!0],a=s?.value??"",o={pathType:g.Any};if(n)o={possibles:this._getPossibleCompletionsCommand(a)};else if(r instanceof ti){let e=r.name.value,t=this.context.commandRegistry.get(e);if(null!==t&&void 0!==t.tabComplete){let i=r.suffix.map(e=>e.value);a||i.push("");let{commandRegistry:s,environment:n,stdinContext:l}=this.context;o=await t.tabComplete({name:e,args:i,commandRegistry:s,environment:n,shellId:this.context.shellId,stdinContext:l})}}let l=o.possibles??[];if(void 0!==o.pathType){let t=[];[e,a,t]=this._getPossibleCompletionsFileSystem(e,a,o.pathType),l.push(...t)}if(0===l.length)return e;if(l.sort(),1===l.length){let t=l[0].slice(a.length);return t.endsWith("/")||(t+=" "),e.text=e.text.slice(0,e.cursorIndex)+t+i,e.cursorIndex+=t.length,this.context.workerIO.write(t+i+A(i.length)),e}let h=function(e,t=0){if(e.length<1)return"";let i=Math.min(...e.map(e=>e.length)),r=e[0],s=t;for(;s<i&&e.every(e=>e[s]===r[s]);)s++;return r.slice(0,s)}(l,a.length);if(h.length>a.length){let t=h.slice(a.length);return e.text=e.text.slice(0,e.cursorIndex)+t+i,e.cursorIndex+=t.length,this.context.workerIO.write(t+i+A(i.length)),e}return await this._showPossibleCompletions(e,i,l),e}_getPossibleCompletionsCommand(e){return[...new Set([...this.context.commandRegistry.match(e),...this.context.aliases.match(e)])]}_getPossibleCompletionsFileSystem(e,t,i){let{FS:r,PATH:s}=this.context.fileSystem;t||(t="./");let n=t.endsWith("/"),a=[void 0,"/"],o=t.endsWith("..")&&a.includes(t.at(-3)),l=!o&&t.endsWith(".")&&a.includes(t.at(-2)),h=l||o;o&&(t=t.slice(0,-1));let u=r.analyzePath(t,!0),c=n||h?u.path:u.parentPath,d=h?l?".":"..":n?"":u.name,m=r.readdir(c);n&&(m=m.filter(e=>!e.startsWith("."))),m=m.filter(e=>e.startsWith(d));let f=new th(r);return i===g.Directory?m=m.filter(e=>f.isDir(s.join(c,e))):i===g.File&&(m=m.filter(e=>f.isFile(s.join(c,e)))),i!==g.File&&(m=m.map(e=>f.isDir(s.join(c,e))?e+"/":e)),[e,d,m]}async _showPossibleCompletions(e,t,i){let{environment:r}=this.context,s=function(e,t){if(e.length<1)return[];if(t<1)return[e.join(" ")];let i=e.length,r=Math.max(...e.map(e=>e.length)),s=Math.min(Math.floor(t/(r+2)),i),n=Math.ceil(i/s),a=[];for(let t=0;t<n;++t){let o="";for(let a=0;a<s;++a){let s=a*n+t;if(s>=i)continue;let l=e[s];o+=l,s+n<i&&(o+=" ".repeat(r+2-l.length))}a.push(o)}return a}(i,r.getNumber("COLUMNS")??0),n=r.getNumber("LINES"),a=!0;(i.length>99||null!==n&&s.length>n-2)&&(a=await this._yesNoPrompt(`Display all ${i.length} possibilities (y or n)?`));let o="\n";a&&(o+=s.join("\n")+"\n"),this.context.workerIO.write(o+r.getPrompt()+e.text+A(t.length))}async _yesNoPrompt(e){let{workerIO:t}=this.context;t.write("\n"+e),await this.enableBufferedStdinCallback(!0),this.termios.setRawMode();let i=!1,r=!1;for(;!r;){let e=await t.readAsync(1,-1);if(e.length>0){let t=e[0];121===t?(i=!0,r=!0):[3,4,110].includes(t)&&(r=!0)}}return this.termios.setDefaultShell(),await this.enableBufferedStdinCallback(!1),i}}class th{FS;constructor(e){this.FS=e}isDir(e){return this.FS.isDir(this._stat(e).mode)}isFile(e){return this.FS.isFile(this._stat(e).mode)}_stat(e){let t=this._statCache.get(e);return void 0===t&&(t=this.FS.stat(e,!1),this._statCache.set(e,t)),t}_statCache=new Map}class tu{constructor(e){this._options=e,this._commandModuleLoader=new K(e.wasmBaseUrl,this._wasmUrlQueryParams.bind(this),e.downloadModuleCallback),this._fileSystem={FS:void 0,PATH:void 0,ERRNO_CODES:void 0,PROXYFS:void 0,mountpoint:e.mountpoint??"/drive"};const{shellId:t,stdinContext:i,termios:r,workerIO:s,workerType:n}=e;this._runContext={name:"",args:[],fileSystem:this._fileSystem,aliases:new G,commandRegistry:new eV(this.callExternalCommand.bind(this),e.callExternalTabComplete),environment:new eK(e.color,e.shellId,e.browsingContextId),history:new eZ,shellId:t,terminate:this.terminate.bind(this),stdin:this._dummyInput,stdout:this._dummyOutput,stderr:this._dummyOutput,size:()=>this.size,termios:r,workerIO:s,workerType:n,commandModuleCache:this._commandModuleLoader.cache,stdinContext:i},e.externalCommandConfigs.forEach(e=>this._runContext.commandRegistry.registerExternalCommand(e.name,e.hasTabComplete)),this._stderr=new e0(this.output.bind(this),this._options.color?H:void 0,this._options.color?B:void 0),this._tabCompleter=new tl(this._runContext,this._options.enableBufferedStdinCallback,this._options.termios)}get aliases(){return this._runContext.aliases}async callExternalCommand(e,t,i,r,s,n,a){this._options.callExternalCommand(e,t,i,r,s,n,a);let o=new E.PromiseDelegate;return void 0!==this._externalCommandPromise&&this._externalCommandPromise.reject("Previous external command did not exit properly"),this._externalCommandPromise=o,await o.promise}get environment(){return this._runContext.environment}exitCode(){return this._exitCode}exitExternalCommand(e){void 0!==this._externalCommandPromise&&(this._externalCommandPromise.resolve(e),this._externalCommandPromise=void 0)}async externalInput(e){return v(await this._runContext.stdin.readAsync(e))}externalOutput(e,t){(t?this._runContext.stderr:this._runContext.stdout).write(e)}get history(){return this._runContext.history}async initialize(){await this._initWasmPackages(),Object.entries(this._options.aliases).forEach(([e,t])=>this._runContext.aliases.set(e,t)),Object.entries(this._options.environment).forEach(([e,t])=>{void 0===t?this._runContext.environment.delete(e):this._runContext.environment.set(e,t)}),await this._initFileSystem()}async input(e){if(!this._isRunning)return;let t=e.length;for(let i=0;i<t;++i){let t=e[i];switch(t.charCodeAt(0)){case 13:{this.output("