just-binary 3.3.0 → 3.3.1
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/dist/bin/just-bash.js +279 -279
- package/dist/bin/shell/shell.js +270 -270
- package/dist/bundle/browser.js +390 -390
- package/dist/bundle/index.js +286 -286
- package/dist/interpreter/redirections.d.ts +11 -0
- package/dist/process/process-table.d.ts +14 -4
- package/dist/sandbox/Command.d.ts +7 -0
- package/package.json +1 -1
package/dist/bin/shell/shell.js
CHANGED
|
@@ -1,149 +1,151 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{$ as vr,A as Fs,B as Kt,C as cr,D as Vs,E as ur,F as be,G as He,H as fr,I as dr,J as zs,K as js,L as Fe,M as hr,N as pr,O as De,P as Bs,R as mr,S as gr,T as Se,U as tt,V as ue,W as Ie,X as Yt,Y as yr,Z as z,_ as wr,a as or,aa as Ve,b as Ls,ba as br,c as ar,ca as Sr,d as lr,da as ot,e as Zt,ea as Q,f as le,g as Z,h as Le,i as Jt,j as et,k as Ms,l as Ws,m as Me,n as kt,o as Pt,p as U,q as _e,r as K,s as _t,t as Y,u as ee,v as Ze,w as te,x as pe,y as We,z as Je}from"./chunks/chunk-73X3QWRT.js";import{a as Ct}from"./chunks/chunk-JGKR7YR7.js";import{a as ir}from"./chunks/chunk-RUESYAVK.js";import{a as qe,b as Pe}from"./chunks/chunk-CAXM2HMK.js";import{a as At}from"./chunks/chunk-N7YAMUQG.js";import{a as Ae,b as Ce,c as we,d as ke,e as sr,f as q,g as Xe,h as $t,i as Gt,j as nr,k as oe,l as rr,m as me,n as Qe,o as Be,p as qt,q as ve}from"./chunks/chunk-A257OMG4.js";import"./chunks/chunk-OBH7XN5N.js";import{a as Oe}from"./chunks/chunk-4VDEBYW7.js";import{a as St,b as E,d as he,e as Et,f as V,g as ie,h as tr,i as it,j as Ut}from"./chunks/chunk-6VQWCKYE.js";import{a as Ht,g as L,h as F,i as H,j as er,k as bt,l as x,m as y}from"./chunks/chunk-463VWH7H.js";import*as eo from"node:fs";import*as to from"node:readline";var at=[{name:"echo",load:async()=>(await import("./chunks/echo-DHVSEP57.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-UO3ZDQHP.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-CVEJOTYB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-LBW3TTPI.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-UUOVKGHS.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-NJCSEPRP.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-4ZSEFYEW.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-UMIY7ESO.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-YSXTOMBS.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-7VY5OVAU.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-2OLFXJYU.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-GYXHDITN.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-6OLMY3MQ.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-T4CDCG4Z.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-HT46A7YT.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-LOVA3SKT.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-TDIG4RIU.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-J5TUE4U5.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-PQP4HTR3.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-BZW7POX3.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-FB5MXVFV.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-TO3IPXI2.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-I2KNCRR6.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-WKYJTISA.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-2MSOLU4C.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-Q23K6FU7.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-ARR7JBLN.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-O3PQMT23.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-34JIXDXD.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-OVU7UR2E.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-L4NT2YFK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-B4WHWJHL.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-TDUSHGAB.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-JXCUP73P.js")).split},{name:"column",load:async()=>(await import("./chunks/column-UCIEGSHJ.js")).column},{name:"join",load:async()=>(await import("./chunks/join-6M3ARIFB.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-SREYEKO6.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-B6JV4QSG.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-ZFBDKUVW.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-XXQNLCA4.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7Y7H64VI.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-IKBAW7PG.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-A43LGO53.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-A43LGO53.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-WO6CMWMT.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-6K57XYD6.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-FZZM6QD2.js")).clearCommand},{name:"yes",load:async()=>(await import("./chunks/yes-7ZGUE2PX.js")).yesCommand},{name:"bash",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-HP7VLWBL.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-NGAPXZAM.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-4PEKV4XS.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-5LA42436.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-HDMKKRCV.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-XBYZ5LW5.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-GS6SIFPK.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-3FRPQG5E.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-BGBONRHV.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-GAWU76ZU.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-AOZWHFTU.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-EXJTAPU4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-DZRWWDPH.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-34LV4LFQ.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-AOETY73Q.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-QMZ276XE.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-QXOHN3J4.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-4O6NEPL2.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-XYB47VCX.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-IGVFBAFH.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(at.push({name:"tar",load:async()=>(await import("./chunks/tar-BAKR5OJO.js")).tarCommand}),at.push({name:"yq",load:async()=>(await import("./chunks/yq-ZHYSTGN3.js")).yqCommand}),at.push({name:"xan",load:async()=>(await import("./chunks/xan-STBKXZ5W.js")).xanCommand}),at.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-K7LHCU76.js")).sqlite3Command}));var Hs=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Hs.push({name:"python3",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).python3Command}),Hs.push({name:"python",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).pythonCommand}));var io=[{name:"curl",load:async()=>(await import("./chunks/curl-YFYJ2XNC.js")).curlCommand}],Er=new Map;function Us(e){return{name:e.name,async execute(t,s){let n=Er.get(e.name);if(n||(n=await e.load(),Er.set(e.name,n)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:r}=await import("./chunks/flag-coverage-FTS7XXHM.js"),{decodeArgs:i}=await import("./chunks/bytes-C34BYEMS.js");r(s.coverage,e.name,i(t))}return n.execute(t,s)}}}function $r(e){return(e?at.filter(s=>e.includes(s.name)):at).map(Us)}function Ar(){return io.map(Us)}function Cr(){return Hs.map(Us)}function kr(e){return"load"in e&&typeof e.load=="function"}function Pr(e){let t=null;return{name:e.name,async execute(s,n){return t||(t=await e.load()),t.execute(s,n)}}}var oo=new TextEncoder;function ao(e){return typeof e=="object"&&e!==null&&typeof e.getReader=="function"}function lo(e,t){if(e instanceof Uint8Array)return e;if(t==="base64")return Uint8Array.from(atob(e),s=>s.charCodeAt(0));if(t==="hex"){let s=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)s[n/2]=parseInt(e.slice(n,n+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,r=>r.charCodeAt(0));let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}return oo.encode(e)}function Tr(e){if(e.length===0)return[];if(e.length<=St)return[e];let t=[];for(let s=0;s<e.length;s+=St)t.push(e.subarray(s,Math.min(s+St,e.length)));return t}function lt(e,t){let s=lo(e,t);return{chunks:Tr(s),size:s.length}}async function ct(e,t){if(ao(e)){let s=[],n=0;for await(let r of Ut(e))if(r.length<=St)s.push(r),n+=r.length;else for(let i of Tr(r))s.push(i),n+=i.length;return{chunks:s,size:n}}return lt(e,t)}function Xt(e,t){if(t==="base64")return btoa(ir(_r(e)));if(t==="hex"){let r="";for(let i of e)for(let a=0;a<i.length;a++)r+=i[a].toString(16).padStart(2,"0");return r}if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(_r(e)).toString(t);let r=65536,i="";for(let a of e)if(a.length<=r)i+=String.fromCharCode(...a);else for(let o=0;o<a.length;o+=r){let l=a.subarray(o,o+r);i+=String.fromCharCode(...l)}return i}let s=new TextDecoder,n="";for(let r of e)r.length>0&&(n+=s.decode(r,{stream:!0}));return n+=s.decode(),n}function _r(e){let t=0;for(let r of e)t+=r.length;if(t===0)return new Uint8Array(0);if(e.length===1)return e[0];let s=new Uint8Array(t),n=0;for(let r of e)s.set(r,n),n+=r.length;return s}function Ue(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}function Qt(e,t){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw new Error(`EINVAL: invalid offset (must be a non-negative integer): ${e}`);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`EINVAL: invalid length (must be a non-negative integer): ${t}`)}function es(e,t,s,n){if(s>=t||n===0)return new Uint8Array(0);let r=Math.min(s+n,t),i=r-s,a=new Uint8Array(i),o=0,l=0;for(let u of e){if(o>=i)break;let c=l+u.length;if(c>s&&l<r){let f=Math.max(0,s-l),d=Math.min(u.length,r-l),p=u.subarray(f,d);a.set(p,o),o+=p.length}l=c}return a}function co(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&!(e instanceof ReadableStream)&&"content"in e}function ce(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Tt=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,n]of Object.entries(t))if(co(n)){if(n.content instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n.content,void 0,{mode:n.mode,mtime:n.mtime})}else{if(n instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(t);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,s,n,r){ce(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let a=Ue(n),{chunks:o,size:l}=lt(s,a);this.data.set(i,{type:"file",chunks:o,size:l,mode:r?.mode??420,mtime:r?.mtime??new Date})}async readFile(t){ce(t,"open");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return Et(n.chunks)}async readRange(t,s,n){Qt(s,n),ce(t,"open");let r=this.resolvePathWithSymlinks(t),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return es(i.chunks,i.size,s,n)}async readFileText(t,s){ce(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);let i=Ue(s);return Xt(r.chunks,i)}async writeFile(t,s,n){ce(t,"write");let r=this.normalizePath(t);this.ensureParentDirs(r);let i=Ue(n),{chunks:a,size:o}=await ct(s,i);this.data.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date})}async appendFile(t,s,n){ce(t,"append");let r=this.normalizePath(t),i=this.data.get(r);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=Ue(n),{chunks:o,size:l}=await ct(s,a);i?.type==="file"?this.data.set(r,{type:"file",chunks:[...i.chunks,...o],size:i.size+l,mode:i.mode,mtime:new Date}):(this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:o,size:l,mode:420,mtime:new Date}))}async exists(t){if(t.includes("\0"))return!1;try{let s=this.resolvePathWithSymlinks(t);return this.data.has(s)}catch{return!1}}async stat(t){ce(t,"stat");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(t){ce(t,"lstat");let s=this.resolveIntermediateSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/");if(n.length<=1)return s;let r="",i=new Set;for(let a=0;a<n.length-1;a++){let o=n[a];r=`${r}/${o}`;let l=this.data.get(r),u=0,c=40;for(;l&&l.type==="symlink"&&u<c;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(r),r=this.resolveSymlink(r,l.target),l=this.data.get(r),u++}if(u>=c)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/"),r="",i=new Set;for(let a of n){r=`${r}/${a}`;let o=this.data.get(r),l=0,u=40;for(;o&&o.type==="symlink"&&l<u;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(r),r=this.resolveSymlink(r,o.target),o=this.data.get(r),l++}if(l>=u)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return r}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){ce(t,"mkdir");let n=this.normalizePath(t);if(this.data.has(n)){if(this.data.get(n)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let r=this.dirname(n);if(r!=="/"&&!this.data.has(r))if(s?.recursive)this.mkdirSync(r,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(n=>n.name)}async readdirWithFileTypes(t){ce(t,"scandir");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Set;for(;n&&n.type==="symlink";){if(r.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==s&&o.startsWith(i)){let u=o.slice(i.length),c=u.split("/")[0];c&&!u.includes("/",c.length)&&!a.has(c)&&a.set(c,{name:c,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(a.values()).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0)}async rm(t,s){ce(t,"rm");let n=this.normalizePath(t),r=this.data.get(n);if(!r){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(r.type==="directory"){let i=await this.readdir(n);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=n==="/"?`/${a}`:`${n}/${a}`;await this.rm(o,s)}}}this.data.delete(n)}async cp(t,s,n){ce(t,"cp"),ce(s,"cp");let r=this.normalizePath(t),i=this.normalizePath(s),a=this.data.get(r);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")this.ensureParentDirs(i),this.data.set(i,{type:"file",chunks:[...a.chunks],size:a.size,mode:a.mode,mtime:a.mtime});else if(a.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(r);for(let l of o){let u=r==="/"?`/${l}`:`${r}/${l}`,c=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(u,c,n)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}async chmod(t,s){ce(t,"chmod");let n=this.normalizePath(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);r.mode=s}async symlink(t,s){ce(s,"symlink");let n=this.normalizePath(s);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){ce(t,"link"),ce(s,"link");let n=this.normalizePath(t),r=this.normalizePath(s),i=this.data.get(n);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(r))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:[...i.chunks],size:i.size,mode:i.mode,mtime:i.mtime})}async readlink(t){ce(t,"readlink");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}async realpath(t){ce(t,"realpath");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,n){ce(t,"utimes");let r=this.normalizePath(t),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=n}};function uo(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function fo(e,t){e.mkdirSync("/bin",{recursive:!0}),e.mkdirSync("/usr/bin",{recursive:!0}),t&&(e.mkdirSync("/home/user",{recursive:!0}),e.mkdirSync("/tmp",{recursive:!0}))}function ho(e){e.mkdirSync("/dev",{recursive:!0}),e.writeFileSync("/dev/null",""),e.writeFileSync("/dev/zero",new Uint8Array(0)),e.writeFileSync("/dev/stdin",""),e.writeFileSync("/dev/stdout",""),e.writeFileSync("/dev/stderr","")}function po(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${or}
|
|
2
|
+
import{$ as vr,A as Fs,B as Kt,C as cr,D as Vs,E as ur,F as be,G as He,H as fr,I as dr,J as zs,K as js,L as Fe,M as hr,N as pr,O as Ie,P as Bs,R as mr,S as gr,T as Se,U as tt,V as ue,W as De,X as Yt,Y as yr,Z as z,_ as wr,a as or,aa as Ve,b as Ls,ba as br,c as ar,ca as Sr,d as lr,da as ot,e as Jt,ea as Q,f as le,g as Z,h as Le,i as Xt,j as et,k as Ms,l as Ws,m as Me,n as kt,o as Pt,p as U,q as _e,r as K,s as _t,t as Y,u as ee,v as Ze,w as te,x as pe,y as We,z as Je}from"./chunks/chunk-73X3QWRT.js";import{a as Ct}from"./chunks/chunk-JGKR7YR7.js";import{a as ir}from"./chunks/chunk-RUESYAVK.js";import{a as qe,b as Pe}from"./chunks/chunk-CAXM2HMK.js";import{a as At}from"./chunks/chunk-N7YAMUQG.js";import{a as Ae,b as Ce,c as we,d as ke,e as sr,f as q,g as Ye,h as $t,i as qt,j as nr,k as oe,l as rr,m as me,n as Qe,o as Be,p as Zt,q as ve}from"./chunks/chunk-A257OMG4.js";import"./chunks/chunk-OBH7XN5N.js";import{a as Oe}from"./chunks/chunk-4VDEBYW7.js";import{a as St,b as A,d as he,e as Et,f as V,g as ie,h as tr,i as it,j as Gt}from"./chunks/chunk-6VQWCKYE.js";import{a as Ut,g as R,h as F,i as H,j as er,k as bt,l as x,m as y}from"./chunks/chunk-463VWH7H.js";import*as eo from"node:fs";import*as to from"node:readline";var at=[{name:"echo",load:async()=>(await import("./chunks/echo-DHVSEP57.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-UO3ZDQHP.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-CVEJOTYB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-LBW3TTPI.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-UUOVKGHS.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-NJCSEPRP.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-4ZSEFYEW.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-UMIY7ESO.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-YSXTOMBS.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-7VY5OVAU.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-2OLFXJYU.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-GYXHDITN.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-6OLMY3MQ.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-T4CDCG4Z.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-HT46A7YT.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-LOVA3SKT.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-TDIG4RIU.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-J5TUE4U5.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-PQP4HTR3.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-BZW7POX3.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-FB5MXVFV.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-TO3IPXI2.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-I2KNCRR6.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-WKYJTISA.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-2MSOLU4C.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-Q23K6FU7.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-ARR7JBLN.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-O3PQMT23.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-34JIXDXD.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-OVU7UR2E.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-L4NT2YFK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-B4WHWJHL.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-TDUSHGAB.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-JXCUP73P.js")).split},{name:"column",load:async()=>(await import("./chunks/column-UCIEGSHJ.js")).column},{name:"join",load:async()=>(await import("./chunks/join-6M3ARIFB.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-SREYEKO6.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-B6JV4QSG.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-ZFBDKUVW.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-XXQNLCA4.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7Y7H64VI.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-IKBAW7PG.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-A43LGO53.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-A43LGO53.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-WO6CMWMT.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-6K57XYD6.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-FZZM6QD2.js")).clearCommand},{name:"yes",load:async()=>(await import("./chunks/yes-7ZGUE2PX.js")).yesCommand},{name:"bash",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-HP7VLWBL.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-NGAPXZAM.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-4PEKV4XS.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-5LA42436.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-HDMKKRCV.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-XBYZ5LW5.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-GS6SIFPK.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-3FRPQG5E.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-BGBONRHV.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-GAWU76ZU.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-AOZWHFTU.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-EXJTAPU4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-DZRWWDPH.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-34LV4LFQ.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-AOETY73Q.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-QMZ276XE.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-QXOHN3J4.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-4O6NEPL2.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-XYB47VCX.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-IGVFBAFH.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(at.push({name:"tar",load:async()=>(await import("./chunks/tar-BAKR5OJO.js")).tarCommand}),at.push({name:"yq",load:async()=>(await import("./chunks/yq-ZHYSTGN3.js")).yqCommand}),at.push({name:"xan",load:async()=>(await import("./chunks/xan-STBKXZ5W.js")).xanCommand}),at.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-K7LHCU76.js")).sqlite3Command}));var Hs=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Hs.push({name:"python3",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).python3Command}),Hs.push({name:"python",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).pythonCommand}));var io=[{name:"curl",load:async()=>(await import("./chunks/curl-YFYJ2XNC.js")).curlCommand}],Er=new Map;function Us(e){return{name:e.name,async execute(t,s){let n=Er.get(e.name);if(n||(n=await e.load(),Er.set(e.name,n)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:r}=await import("./chunks/flag-coverage-FTS7XXHM.js"),{decodeArgs:i}=await import("./chunks/bytes-C34BYEMS.js");r(s.coverage,e.name,i(t))}return n.execute(t,s)}}}function $r(e){return(e?at.filter(s=>e.includes(s.name)):at).map(Us)}function Ar(){return io.map(Us)}function Cr(){return Hs.map(Us)}function kr(e){return"load"in e&&typeof e.load=="function"}function Pr(e){let t=null;return{name:e.name,async execute(s,n){return t||(t=await e.load()),t.execute(s,n)}}}var oo=new TextEncoder;function ao(e){return typeof e=="object"&&e!==null&&typeof e.getReader=="function"}function lo(e,t){if(e instanceof Uint8Array)return e;if(t==="base64")return Uint8Array.from(atob(e),s=>s.charCodeAt(0));if(t==="hex"){let s=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)s[n/2]=parseInt(e.slice(n,n+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,r=>r.charCodeAt(0));let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}return oo.encode(e)}function Tr(e){if(e.length===0)return[];if(e.length<=St)return[e];let t=[];for(let s=0;s<e.length;s+=St)t.push(e.subarray(s,Math.min(s+St,e.length)));return t}function lt(e,t){let s=lo(e,t);return{chunks:Tr(s),size:s.length}}async function ct(e,t){if(ao(e)){let s=[],n=0;for await(let r of Gt(e))if(r.length<=St)s.push(r),n+=r.length;else for(let i of Tr(r))s.push(i),n+=i.length;return{chunks:s,size:n}}return lt(e,t)}function Qt(e,t){if(t==="base64")return btoa(ir(_r(e)));if(t==="hex"){let r="";for(let i of e)for(let a=0;a<i.length;a++)r+=i[a].toString(16).padStart(2,"0");return r}if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(_r(e)).toString(t);let r=65536,i="";for(let a of e)if(a.length<=r)i+=String.fromCharCode(...a);else for(let o=0;o<a.length;o+=r){let l=a.subarray(o,o+r);i+=String.fromCharCode(...l)}return i}let s=new TextDecoder,n="";for(let r of e)r.length>0&&(n+=s.decode(r,{stream:!0}));return n+=s.decode(),n}function _r(e){let t=0;for(let r of e)t+=r.length;if(t===0)return new Uint8Array(0);if(e.length===1)return e[0];let s=new Uint8Array(t),n=0;for(let r of e)s.set(r,n),n+=r.length;return s}function Ue(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}function es(e,t){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw new Error(`EINVAL: invalid offset (must be a non-negative integer): ${e}`);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`EINVAL: invalid length (must be a non-negative integer): ${t}`)}function ts(e,t,s,n){if(s>=t||n===0)return new Uint8Array(0);let r=Math.min(s+n,t),i=r-s,a=new Uint8Array(i),o=0,l=0;for(let c of e){if(o>=i)break;let u=l+c.length;if(u>s&&l<r){let f=Math.max(0,s-l),d=Math.min(c.length,r-l),p=c.subarray(f,d);a.set(p,o),o+=p.length}l=u}return a}function co(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&!(e instanceof ReadableStream)&&"content"in e}function ce(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Tt=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,n]of Object.entries(t))if(co(n)){if(n.content instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n.content,void 0,{mode:n.mode,mtime:n.mtime})}else{if(n instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(t);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,s,n,r){ce(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let a=Ue(n),{chunks:o,size:l}=lt(s,a);this.data.set(i,{type:"file",chunks:o,size:l,mode:r?.mode??420,mtime:r?.mtime??new Date})}async readFile(t){ce(t,"open");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return Et(n.chunks)}async readRange(t,s,n){es(s,n),ce(t,"open");let r=this.resolvePathWithSymlinks(t),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return ts(i.chunks,i.size,s,n)}async readFileText(t,s){ce(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);let i=Ue(s);return Qt(r.chunks,i)}async writeFile(t,s,n){ce(t,"write");let r=this.normalizePath(t);this.ensureParentDirs(r);let i=Ue(n),{chunks:a,size:o}=await ct(s,i);this.data.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date})}async appendFile(t,s,n){ce(t,"append");let r=this.normalizePath(t),i=this.data.get(r);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=Ue(n),{chunks:o,size:l}=await ct(s,a);i?.type==="file"?this.data.set(r,{type:"file",chunks:[...i.chunks,...o],size:i.size+l,mode:i.mode,mtime:new Date}):(this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:o,size:l,mode:420,mtime:new Date}))}async exists(t){if(t.includes("\0"))return!1;try{let s=this.resolvePathWithSymlinks(t);return this.data.has(s)}catch{return!1}}async stat(t){ce(t,"stat");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(t){ce(t,"lstat");let s=this.resolveIntermediateSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/");if(n.length<=1)return s;let r="",i=new Set;for(let a=0;a<n.length-1;a++){let o=n[a];r=`${r}/${o}`;let l=this.data.get(r),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(r),r=this.resolveSymlink(r,l.target),l=this.data.get(r),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/"),r="",i=new Set;for(let a of n){r=`${r}/${a}`;let o=this.data.get(r),l=0,c=40;for(;o&&o.type==="symlink"&&l<c;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(r),r=this.resolveSymlink(r,o.target),o=this.data.get(r),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return r}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){ce(t,"mkdir");let n=this.normalizePath(t);if(this.data.has(n)){if(this.data.get(n)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let r=this.dirname(n);if(r!=="/"&&!this.data.has(r))if(s?.recursive)this.mkdirSync(r,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(n=>n.name)}async readdirWithFileTypes(t){ce(t,"scandir");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Set;for(;n&&n.type==="symlink";){if(r.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!a.has(u)&&a.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(a.values()).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0)}async rm(t,s){ce(t,"rm");let n=this.normalizePath(t),r=this.data.get(n);if(!r){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(r.type==="directory"){let i=await this.readdir(n);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=n==="/"?`/${a}`:`${n}/${a}`;await this.rm(o,s)}}}this.data.delete(n)}async cp(t,s,n){ce(t,"cp"),ce(s,"cp");let r=this.normalizePath(t),i=this.normalizePath(s),a=this.data.get(r);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")this.ensureParentDirs(i),this.data.set(i,{type:"file",chunks:[...a.chunks],size:a.size,mode:a.mode,mtime:a.mtime});else if(a.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(r);for(let l of o){let c=r==="/"?`/${l}`:`${r}/${l}`,u=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(c,u,n)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}async chmod(t,s){ce(t,"chmod");let n=this.normalizePath(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);r.mode=s}async symlink(t,s){ce(s,"symlink");let n=this.normalizePath(s);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){ce(t,"link"),ce(s,"link");let n=this.normalizePath(t),r=this.normalizePath(s),i=this.data.get(n);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(r))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:[...i.chunks],size:i.size,mode:i.mode,mtime:i.mtime})}async readlink(t){ce(t,"readlink");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}async realpath(t){ce(t,"realpath");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,n){ce(t,"utimes");let r=this.normalizePath(t),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=n}};function uo(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function fo(e,t){e.mkdirSync("/bin",{recursive:!0}),e.mkdirSync("/usr/bin",{recursive:!0}),t&&(e.mkdirSync("/home/user",{recursive:!0}),e.mkdirSync("/tmp",{recursive:!0}))}function ho(e){e.mkdirSync("/dev",{recursive:!0}),e.writeFileSync("/dev/null",""),e.writeFileSync("/dev/zero",new Uint8Array(0)),e.writeFileSync("/dev/stdin",""),e.writeFileSync("/dev/stdout",""),e.writeFileSync("/dev/stderr","")}function po(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${or}
|
|
3
3
|
`),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
|
|
4
|
-
`),e.writeFileSync("/proc/self/status",ar()),e.writeFileSync("/proc/self/fd/0","/dev/stdin"),e.writeFileSync("/proc/self/fd/1","/dev/stdout"),e.writeFileSync("/proc/self/fd/2","/dev/stderr")}function
|
|
4
|
+
`),e.writeFileSync("/proc/self/status",ar()),e.writeFileSync("/proc/self/fd/0","/dev/stdin"),e.writeFileSync("/proc/self/fd/1","/dev/stdout"),e.writeFileSync("/proc/self/fd/2","/dev/stderr")}function Nr(e,t){uo(e)&&(fo(e,t),ho(e),po(e))}var mo=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],go=["braceexpand","hashall","interactive-comments"];function Gs(e){let t=[],s=[...go.map(n=>({name:n,enabled:!0})),...mo.map(n=>({name:n,enabled:e[n]}))].sort((n,r)=>n.name.localeCompare(r.name));for(let n of s)n.enabled&&t.push(n.name);return t.join(":")}function ut(e){y(e.state.env,"SHELLOPTS",Gs(e.state.options))}var yo=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function qs(e){let t=[];for(let s of yo)e[s]&&t.push(s);return t.join(":")}function Zs(e){y(e.state.env,"BASHOPTS",qs(e.state.shoptOptions))}var wo="BASH_ALIAS_";function xr(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Or(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Ir(e,t){let s=e.env.get(`${wo}${t}`);return s!==void 0?H(s):void 0}function Js(e,t,s){if(!t.name||!xr(t.name))return t;let n=Or(t.name);if(!n)return t;let r=Ir(e,n);if(!r||s.has(n))return t;try{s.add(n);let i=new Z,a=r,o=r.endsWith(" ");if(!o)for(let f of t.args){let d=Rr(f);a+=` ${d}`}let l;try{l=i.parse(a)}catch(f){if(f instanceof Jt)throw f;return t}if(l.statements.length!==1||l.statements[0].pipelines.length!==1||l.statements[0].pipelines[0].commands.length!==1)return Dr(t,r);let c=l.statements[0].pipelines[0].commands[0];if(c.type!=="SimpleCommand")return Dr(t,r);let u={...c,assignments:[...t.assignments,...c.assignments],redirections:[...c.redirections,...t.redirections],line:t.line};if(o&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let f=u.args[0];if(xr(f)){let d=Or(f);if(d&&Ir(e,d)){let p={type:"SimpleCommand",name:f,args:u.args.slice(1),assignments:[],redirections:[]},m=Js(e,p,s);m!==p&&(u={...u,name:m.name,args:[...m.args]})}}}return u}catch(i){throw s.delete(n),i}}function Dr(e,t){let s=t;for(let a of e.args){let o=Rr(a);s+=` ${o}`}let n=new Z,r=n.parseWordFromString("eval",!1,!1),i=n.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:r,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Rr(e){let t="";for(let s of e.parts)switch(s.type){case"Literal":t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,"\\$1");break;case"SingleQuoted":t+=`'${s.value}'`;break;case"DoubleQuoted":t+=`"${s.parts.map(n=>n.type==="Literal"?n.value:`$${n.type}`).join("")}"`;break;case"ParameterExpansion":t+=`\${${s.parameter}}`;break;case"CommandSubstitution":t+="$(...)";break;case"ArithmeticExpansion":t+=`$((${s.expression}))`;break;case"Glob":t+=s.pattern;break;default:break}return t}async function Lr(e,t){let s=t.parts.map(u=>u.type==="Literal"?u.value:"\0").join(""),n=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!n||!s.endsWith(")"))return null;let r=n[1],i=[],a=!1,o="",l=!1;for(let u of t.parts)if(u.type==="Literal"){let f=u.value;if(!a){let d=f.indexOf("=(");d!==-1&&(a=!0,f=f.slice(d+2))}if(a){f.endsWith(")")&&(f=f.slice(0,-1));let d=f.split(/(\s+)/);for(let p of d)/^\s+$/.test(p)?(o||l)&&(i.push(o),o="",l=!1):p&&(o+=p)}}else if(a)if(u.type==="BraceExpansion")if(/^\[.+\]=/.test(o))o+=Kt({type:"Word",parts:[u]});else{(o||l)&&(i.push(o),o="",l=!1);let d=await Ve(e,{type:"Word",parts:[u]});i.push(...d.values)}else{(u.type==="SingleQuoted"||u.type==="DoubleQuoted"||u.type==="Escaped")&&(l=!0);let f=await z(e,{type:"Word",parts:[u]});o+=f}(o||l)&&i.push(o);let c=i.map(u=>/^\[.+\]=/.test(u)?u:u===""?"''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(u)&&!u.startsWith("'")&&!u.startsWith('"')?`'${u.replace(/'/g,"'\\''")}'`:u);return`${r}=(${c.join(" ")})`}async function Mr(e,t){let s=-1,n=-1,r=!1;for(let h=0;h<t.parts.length;h++){let v=t.parts[h];if(v.type==="Literal"){let S=v.value.indexOf("+=");if(S!==-1){let b=v.value.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){s=h,n=S,r=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){s=h,n=S,r=!0;break}}let E=v.value.indexOf("=");if(E!==-1&&(E===0||v.value[E-1]!=="+")){let b=v.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){s=h,n=E;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),a=t.parts[s];if(a.type!=="Literal")return null;let o=r?2:1,l=a.value.slice(0,n),c=a.value.slice(n+o),u=t.parts.slice(s+1),f="";for(let h of i)f+=await z(e,{type:"Word",parts:[h]});f+=l;let d={type:"Word",parts:c!==""?[{type:"Literal",value:c},...u]:u},p=d.parts.length>0?await z(e,d):"";return`${f}${r?"+=":"="}${p}`}var vo=["tar","yq","xan","sqlite3","python3","python"];function Wr(e){return vo.includes(e)}function B(){return{stdout:A(),stderr:A(),exitCode:0}}var ft={get stdout(){return A()},get stderr(){return A()},exitCode:0};function Te(e=A()){return{stdout:e,stderr:A(),exitCode:0}}function G(e){return{stdout:V(e),stderr:A(),exitCode:0}}function C(e,t=1){return{stdout:A(),stderr:V(e),exitCode:t}}function W(e,t,s){return{stdout:e instanceof Uint8Array?he(e):e,stderr:t instanceof Uint8Array?he(t):t,exitCode:s}}function ae(e){return{stdout:A(),stderr:A(),exitCode:e?0:1}}function Re(e,t){throw new oe(e,t)}async function Xs(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Be;return B()}if(t.length>1)throw await U(e,2,`bash: break: too many arguments
|
|
5
5
|
`,!0),new q(1);let s=1;if(t.length>0){let n=Number.parseInt(t[0],10);if(Number.isNaN(n)||n<1)throw await U(e,2,`bash: break: ${t[0]}: numeric argument required
|
|
6
|
-
`,!0),new q(128);s=n}throw new Ae(s)}async function
|
|
7
|
-
`)}catch{return
|
|
8
|
-
`)}}let c
|
|
9
|
-
`):Te()}function
|
|
6
|
+
`,!0),new q(128);s=n}throw new Ae(s)}async function Ks(e,t){let s,n=!1,r=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")r=!1,i++;else if(t[i]==="-P")r=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let a=t.slice(i);if(a.length===0?s=x(e.state.env,"HOME","/"):a[0]==="~"?s=x(e.state.env,"HOME","/"):a[0]==="-"?(s=e.state.previousDir,n=!0):s=a[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let f=e.state.env.get("CDPATH");if(f){let d=H(f??R).split(":").filter(p=>p);for(let p of d){let m=p.startsWith("/")?`${p}/${s}`:`${e.state.cwd}/${p}/${s}`;try{if((await e.fs.stat(m)).isDirectory){s=m,n=!0;break}}catch{}}}}let l=(s.startsWith("/")?s:`${e.state.cwd}/${s}`).split("/").filter(f=>f&&f!=="."),c="";for(let f of l)if(f==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await e.fs.stat(c)).isDirectory)return C(`bash: cd: ${s}: Not a directory
|
|
7
|
+
`)}catch{return C(`bash: cd: ${s}: No such file or directory
|
|
8
|
+
`)}}let u=c||"/";if(r)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,y(e.state.env,"PWD",e.state.cwd),y(e.state.env,"OLDPWD",e.state.previousDir),n?G(`${u}
|
|
9
|
+
`):Te()}function Ys(e,t){return e.fs.resolvePath(e.state.cwd,t)}var bo=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function ss(e){return bo.includes(e)}async function ns(e,t,s){let n=Ys(e,s);switch(t){case"-e":case"-a":return e.fs.exists(n);case"-f":return await e.fs.exists(n)?(await e.fs.stat(n)).isFile:!1;case"-d":return await e.fs.exists(n)?(await e.fs.stat(n)).isDirectory:!1;case"-r":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&256)!==0:!1;case"-w":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&128)!==0:!1;case"-x":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&64)!==0:!1;case"-s":return await e.fs.exists(n)?(await e.fs.stat(n)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(n)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&512)!==0:!1;case"-g":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(n);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].some(i=>n===i||n.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(n);default:return!1}}var So=["-nt","-ot","-ef"];function rs(e){return So.includes(e)}async function is(e,t,s,n){let r=Ys(e,s),i=Ys(e,n);switch(t){case"-nt":try{let a=await e.fs.stat(r),o=await e.fs.stat(i);return a.mtime>o.mtime}catch{return!1}case"-ot":try{let a=await e.fs.stat(r),o=await e.fs.stat(i);return a.mtime<o.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(r)||!await e.fs.exists(i))return!1;let a=e.fs.resolvePath(e.state.cwd,r),o=e.fs.resolvePath(e.state.cwd,i);return a===o}catch{return!1}default:return!1}}var Eo=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function os(e){return Eo.has(e)}function as(e,t,s){switch(e){case"-eq":return t===s;case"-ne":return t!==s;case"-lt":return t<s;case"-le":return t<=s;case"-gt":return t>s;case"-ge":return t>=s}}function Nt(e){return e==="="||e==="=="||e==="!="}function ls(e,t,s,n=!1,r=!1,i=!1){if(n){let o=dt(t,s,r,i);return e==="!="?!o:o}if(r){let o=t.toLowerCase()===s.toLowerCase();return e==="!="?!o:o}let a=t===s;return e==="!="?!a:a}var $o=new Set(["-z","-n"]);function cs(e){return $o.has(e)}function us(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function fs(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let n=s[1],r=s[2];if(e.state.associativeArrays?.has(n)){let o=r;return(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1)),o=o.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,c)=>x(e.state.env,c)),e.state.env.has(`${n}_${o}`)}let a;try{let o=new Z,l=le(o,r);a=await Q(e,l.expression)}catch{if(/^-?\d+$/.test(r))a=Number.parseInt(r,10);else{let o=x(e.state.env,r);a=o?Number.parseInt(o,10):0}}if(a<0){let o=pe(e,n),l=e.state.currentLine;if(o.length===0)return await U(e,2,`bash: line ${l}: ${n}: bad array subscript
|
|
10
10
|
`),!1;if(a=Math.max(...o)+1+a,a<0)return await U(e,2,`bash: line ${l}: ${n}: bad array subscript
|
|
11
|
-
`),!1}return e.state.env.has(`${n}_${a}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Je(e,t).length>0:pe(e,t).length>0}async function
|
|
12
|
-
`,2):
|
|
13
|
-
`,2):W(
|
|
14
|
-
`,2):ae(s.value)}async function jr(e,t,s){return Ao(e,t,s)}async function Ao(e,t,s){let{value:n,pos:r}=await Fr(e,t,s);for(;t[r]==="-o";){let i=await Fr(e,t,r+1);n=n||i.value,r=i.pos}return{value:n,pos:r}}async function Fr(e,t,s){let{value:n,pos:r}=await Qs(e,t,s);for(;t[r]==="-a";){let i=await Qs(e,t,r+1);n=n&&i.value,r=i.pos}return{value:n,pos:r}}async function Qs(e,t,s){if(t[s]==="!"){let{value:n,pos:r}=await Qs(e,t,s+1);return{value:!n,pos:r}}return Co(e,t,s)}async function Co(e,t,s){let n=t[s];if(n==="("){let{value:i,pos:a}=await jr(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let r=t[s+1];if(
|
|
15
|
-
`)&&!n&&!r){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function
|
|
11
|
+
`),!1}return e.state.env.has(`${n}_${a}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Je(e,t).length>0:pe(e,t).length>0}async function Xe(e,t){switch(t.type){case"CondBinary":{let s=await z(e,t.left),n=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),r;if(t.operator==="=~")if(n){let i=await z(e,t.right);r=gr(i)}else r=await wr(e,t.right);else Nt(t.operator)&&!n?r=await vr(e,t.right):r=await z(e,t.right);if(Nt(t.operator)){let i=e.state.shoptOptions.nocasematch;return ls(t.operator,s,r,!n,i,!0)}if(os(t.operator))return as(t.operator,await Vr(e,s),await Vr(e,r));if(rs(t.operator))return is(e,t.operator,s,r);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,a=Po(r),l=At(a,i?"i":"").match(s);if(We(e,"BASH_REMATCH"),l)for(let c=0;c<l.length;c++)y(e.state.env,`BASH_REMATCH_${c}`,l[c]||"");return l!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<r;case">":return s>r;default:return!1}}case"CondUnary":{let s=await z(e,t.operand);return ss(t.operator)?ns(e,t.operator,s):cs(t.operator)?us(t.operator,s):t.operator==="-v"?await fs(e,s):t.operator==="-o"?en(e,s):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await z(e,t.operand.expression.word)})`!=="":!await Xe(e,t.operand);case"CondAnd":return await Xe(e,t.left)?await Xe(e,t.right):!1;case"CondOr":return await Xe(e,t.left)?!0:await Xe(e,t.right);case"CondGroup":return await Xe(e,t.expression);case"CondWord":return await z(e,t.word)!=="";default:return!1}}async function xt(e,t){if(t.length===0)return W(R,R,1);if(t.length===1)return ae(!!t[0]);if(t.length===2){let n=t[0],r=t[1];return n==="("?C(`test: '(' without matching ')'
|
|
12
|
+
`,2):ss(n)?ae(await ns(e,n,r)):cs(n)?ae(us(n,r)):n==="!"?ae(!r):n==="-v"?ae(await fs(e,r)):n==="-o"?ae(en(e,r)):n==="="||n==="=="||n==="!="||n==="<"||n===">"||n==="-eq"||n==="-ne"||n==="-lt"||n==="-le"||n==="-gt"||n==="-ge"||n==="-nt"||n==="-ot"||n==="-ef"?C(`test: ${n}: unary operator expected
|
|
13
|
+
`,2):W(R,R,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(Nt(r))return ae(ls(r,n,i));if(os(r)){let a=ds(n),o=ds(i);return!a.valid||!o.valid?W(R,R,2):ae(as(r,a.value,o.value))}if(rs(r))return ae(await is(e,r,n,i));switch(r){case"-a":return ae(n!==""&&i!=="");case"-o":return ae(n!==""||i!=="");case">":return ae(n>i);case"<":return ae(n<i)}if(n==="!"){let a=await xt(e,[r,i]);return W(R,a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(n==="("&&i===")")return ae(r!=="")}if(t.length===4){if(t[0]==="!"){let n=await xt(e,t.slice(1));return W(R,n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(t[0]==="("&&t[3]===")")return xt(e,[t[1],t[2]])}let s=await jr(e,t,0);return s.pos<t.length?C(`test: too many arguments
|
|
14
|
+
`,2):ae(s.value)}async function jr(e,t,s){return Ao(e,t,s)}async function Ao(e,t,s){let{value:n,pos:r}=await Fr(e,t,s);for(;t[r]==="-o";){let i=await Fr(e,t,r+1);n=n||i.value,r=i.pos}return{value:n,pos:r}}async function Fr(e,t,s){let{value:n,pos:r}=await Qs(e,t,s);for(;t[r]==="-a";){let i=await Qs(e,t,r+1);n=n&&i.value,r=i.pos}return{value:n,pos:r}}async function Qs(e,t,s){if(t[s]==="!"){let{value:n,pos:r}=await Qs(e,t,s+1);return{value:!n,pos:r}}return Co(e,t,s)}async function Co(e,t,s){let n=t[s];if(n==="("){let{value:i,pos:a}=await jr(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let r=t[s+1];if(Nt(r)){let i=n,a=t[s+2]??"";return{value:ls(r,i,a),pos:s+3}}if(os(r)){let i=ds(n),a=ds(t[s+2]??"0");return!i.valid||!a.valid?{value:!1,pos:s+3}:{value:as(r,i.value,a.value),pos:s+3}}if(rs(r)){let i=n,a=t[s+2]??"";return{value:await is(e,r,i,a),pos:s+3}}if(ss(n)){let i=t[s+1]??"";return{value:await ns(e,n,i),pos:s+2}}if(cs(n)){let i=t[s+1]??"";return{value:us(n,i),pos:s+2}}if(n==="-v"){let i=t[s+1]??"";return{value:await fs(e,i),pos:s+2}}if(n==="-o"){let i=t[s+1]??"";return{value:en(e,i),pos:s+2}}return{value:n!==void 0&&n!=="",pos:s+1}}function dt(e,t,s=!1,n=!1){let r=`^${Br(t,n)}$`;return At(r,s?"is":"s").test(e)}function Br(e,t){let s="";for(let n=0;n<e.length;n++){let r=e[n];if(t&&(r==="@"||r==="*"||r==="+"||r==="?"||r==="!")&&n+1<e.length&&e[n+1]==="("){let i=Hr(e,n+1);if(i!==-1){let a=e.slice(n+2,i),o=Ur(a),l=o.map(u=>Br(u,t)),c=l.length>0?l.join("|"):"(?:)";if(r==="@")s+=`(?:${c})`;else if(r==="*")s+=`(?:${c})*`;else if(r==="+")s+=`(?:${c})+`;else if(r==="?")s+=`(?:${c})?`;else if(r==="!")if(i<e.length-1){let f=o.map(p=>Gr(p,t));if(f.every(p=>p!==null)&&f.every(p=>p===f[0])&&f[0]!==null){let p=f[0];if(p===0)s+="(?:.+)";else{let m=[];p>0&&m.push(`.{0,${p-1}}`),m.push(`.{${p+1},}`),m.push(`(?!(?:${c})).{${p}}`),s+=`(?:${m.join("|")})`}}else s+=`(?:(?!(?:${c})).)*?`}else s+=`(?!(?:${c})$).*`;n=i;continue}}if(r==="\\")if(n+1<e.length){let i=e[n+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,n++}else s+="\\\\";else if(r==="*")s+=".*";else if(r==="?")s+=".";else if(r==="["){let i=e.indexOf("]",n+1);i!==-1?(s+=e.slice(n,i+1),n=i):s+="\\["}else/[\\^$.|+(){}]/.test(r)?s+=`\\${r}`:s+=r}return s}function Hr(e,t){let s=1,n=t+1;for(;n<e.length&&s>0;){let r=e[n];if(r==="\\"){n+=2;continue}if(r==="(")s++;else if(r===")"&&(s--,s===0))return n;n++}return-1}function Ur(e){let t=[],s="",n=0,r=0;for(;r<e.length;){let i=e[r];if(i==="\\"){s+=i,r+1<e.length?(s+=e[r+1],r+=2):r++;continue}i==="("?(n++,s+=i):i===")"?(n--,s+=i):i==="|"&&n===0?(t.push(s),s=""):s+=i,r++}return t.push(s),t}function Gr(e,t){let s=0,n=0;for(;n<e.length;){let r=e[n];if(t&&(r==="@"||r==="*"||r==="+"||r==="?"||r==="!")&&n+1<e.length&&e[n+1]==="("){let i=Hr(e,n+1);if(i!==-1){if(r==="@"){let a=e.slice(n+2,i),l=Ur(a).map(c=>Gr(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===l[0])){s+=l[0],n=i+1;continue}return null}return null}}if(r==="*")return null;if(r==="?"){s+=1,n++;continue}if(r==="["){let i=e.indexOf("]",n+1);if(i!==-1){s+=1,n=i+1;continue}s+=1,n++;continue}if(r==="\\"){s+=1,n+=2;continue}s+=1,n++}return s}function en(e,t){let n=new Map([["errexit",()=>e.state.options.errexit===!0],["nounset",()=>e.state.options.nounset===!0],["pipefail",()=>e.state.options.pipefail===!0],["xtrace",()=>e.state.options.xtrace===!0],["e",()=>e.state.options.errexit===!0],["u",()=>e.state.options.nounset===!0],["x",()=>e.state.options.xtrace===!0]]).get(t);return n?n():!1}async function Vr(e,t){if(t=t.trim(),t==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return zr(t);try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{return zr(t)}}function ko(e,t){let s=0;for(let n of e){let r;if(n>="0"&&n<="9")r=n.charCodeAt(0)-48;else if(n>="a"&&n<="z")r=n.charCodeAt(0)-97+10;else if(n>="A"&&n<="Z")r=n.charCodeAt(0)-65+36;else if(n==="@")r=62;else if(n==="_")r=63;else return Number.NaN;if(r>=t)return Number.NaN;s=s*t+r}return s}function zr(e){if(e=e.trim(),e==="")return 0;let t=!1;e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1));let s,n=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(n){let r=Number.parseInt(n[1],10);r>=2&&r<=64?s=ko(n[2],r):s=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?s=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?s=Number.parseInt(e,8):s=Number.parseInt(e,10);return Number.isNaN(s)&&(s=0),t?-s:s}function ds(e){if(e=e.trim(),e==="")return{value:0,valid:!0};let t=!1;if(e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let s=Number.parseInt(e,10);return Number.isNaN(s)?{value:0,valid:!1}:{value:t?-s:s,valid:!0}}function Po(e){let t="",s=0;for(;s<e.length;)if(e[s]==="\\"&&s+1<e.length)t+=e[s]+e[s+1],s+=2;else if(e[s]==="["){let n=_o(e,s);t+=n.converted,s=n.endIndex}else t+=e[s],s++;return t}function _o(e,t){let s=t+1,n="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(n+="^",s++);let r=!1;s<e.length&&e[s]==="]"&&(r=!0,s++);let i=!1;s<e.length&&e[s]==="["&&s+1<e.length&&e[s+1]!==":"&&(i=!0,s++);let a="",o=!1;for(;s<e.length;){let l=e[s];if(l==="]"){o=!0,s++;break}if(l==="["&&s+1<e.length&&e[s+1]===":"){let c=e.indexOf(":]",s+2);if(c!==-1){let u=e.slice(s+2,c);a+=To(u),s=c+2;continue}}if(l==="["&&s+1<e.length){let c=e[s+1];if(c==="."||c==="="){let u=`${c}]`,f=e.indexOf(u,s+2);if(f!==-1){let d=e.slice(s+2,f);a+=d,s=f+2;continue}}}if(l==="\\"&&s+1<e.length){a+=l+e[s+1],s+=2;continue}a+=l,s++}return o?(r&&(n+="\\]"),i&&(n+="\\["),n+=a,n+="]",{converted:n,endIndex:s}):{converted:"\\[",endIndex:t+1}}function To(e){return new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]).get(e)??""}function ze(e){let t=[],s="",n=!1,r=!1,i=!1,a=!1;for(let o of e){if(i){s+=o,i=!1,a=!0;continue}if(o==="\\"){i=!0;continue}if(o==="'"&&!r){n||(a=!0),n=!n;continue}if(o==='"'&&!n){r||(a=!0),r=!r;continue}if((o===" "||o===" "||o===`
|
|
15
|
+
`)&&!n&&!r){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function hs(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!=="["){s++;continue}s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)n+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)r+=e[s],s++;t.push([n,r])}return t}function qr(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:ze(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes("=")){let n=e.indexOf("=");return{name:e.slice(0,n),isArray:!1,value:e.slice(n+1)}}return{name:e,isArray:!1}}async function No(e,t){try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function Zr(e,t,s={}){let{name:n,isArray:r,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=s;if(c){let u=await ue(e,n);if(u)return u}if(r&&i){for(let u=0;u<i.length;u++)y(e.state.env,`${n}_${u}`,i[u]);y(e.state.env,`${n}__length`,String(i.length))}else if(o!==void 0&&a!==void 0){let u=await No(e,o);y(e.state.env,`${n}_${u}`,a);let f=parseInt(x(e.state.env,`${n}__length`,"0"),10);u>=f&&y(e.state.env,`${n}__length`,String(u+1))}else a!==void 0&&y(e.state.env,n,a);return l&&Se(e,n),null}function Ke(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function ht(e,t){return e.state.localVarDepth?.get(t)}function ps(e,t){e.state.localVarDepth?.delete(t)}function Jr(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let n=e.state.localVarStack.get(t)||[];n.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,n)}function ms(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function Xr(e,t){if(e.state.localVarStack)for(let[s,n]of e.state.localVarStack.entries()){for(;n.length>0&&n[n.length-1].scopeIndex===t;)n.pop();n.length===0&&e.state.localVarStack.delete(s)}}var tn=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function Kr(e){return tn.has(e)}var sn=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),Ge=new Set([":","true","false","cd","export","unset","exit","local","set","break","continue","return","eval","shift","getopts","compgen","complete","compopt","pushd","popd","dirs","source",".","read","mapfile","readarray","declare","typeset","readonly","let","command","shopt","exec","test","[","echo","printf","pwd","alias","unalias","type","hash","ulimit","umask","trap","times","wait","kill","jobs","fg","bg","disown","suspend","fc","history","help","enable","builtin","caller"]);function Ot(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function gs(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let n=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(n)||n<0)return null;let r=s+1,i=t.slice(r,r+n),a=r+n+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let c=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=o.slice(l+1);return{path:i,position:c,content:u}}async function Yr(e,t,s,n){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
|
|
16
16
|
`;if(n.checkNoclobber&&e.state.options.noclobber&&!n.isClobber&&s!=="/dev/null")return`bash: ${s}: cannot overwrite existing file
|
|
17
|
-
`}catch{}return null}async function
|
|
17
|
+
`}catch{}return null}async function ys(e,t){if(t.target.type==="HereDoc")throw new Error("Here-document targets are not words");return t.operator===">&"||t.operator==="<&"?br(e,t.target)?{error:`bash: $@: ambiguous redirect
|
|
18
18
|
`}:{target:await z(e,t.target)}:Sr(e,t.target)}function nn(e){return e.includes("\0")?`bash: ${e.replace(/\0/g,"")}: No such file or directory
|
|
19
19
|
`:null}function je(e){return`bash: ${e}: Bad file descriptor
|
|
20
|
-
`}
|
|
21
|
-
`
|
|
22
|
-
`)
|
|
23
|
-
`);
|
|
24
|
-
`)
|
|
25
|
-
`)
|
|
26
|
-
`);
|
|
27
|
-
|
|
20
|
+
`}async function It(e,t){try{if((await e.fs.stat(e.fs.resolvePath(e.state.cwd,t))).isDirectory)return`bash: ${t}: Is a directory
|
|
21
|
+
`}catch{}return`bash: ${t}: No such file or directory
|
|
22
|
+
`}function rn(e,t=()=>!1){for(e.state.nextFd===void 0&&(e.state.nextFd=10);t(e.state.nextFd);)e.state.nextFd++;return e.state.nextFd++}async function pt(e,t,s){for(let n of t){if(!n.fdVariable)continue;e.state.fileDescriptors||(e.state.fileDescriptors=new Map);let r;if((n.operator===">&"||n.operator==="<&")&&n.target.type==="Word"&&(r=await z(e,n.target),r==="-")){if(e.state.env.has(n.fdVariable)){let a=Number.parseInt(x(e.state.env,n.fdVariable),10);Number.isNaN(a)||e.state.fileDescriptors.delete(a)}continue}let i=rn(e,s);if(y(e.state.env,n.fdVariable,String(i)),n.target.type==="Word"){let a=r??await z(e,n.target);if(n.operator===">&"||n.operator==="<&"){let o=Number.parseInt(a,10);if(!Number.isNaN(o)){let l=e.state.fileDescriptors.get(o);if(l!==void 0)e.state.fileDescriptors.set(i,l);else return W(A(),V(je(o)),1);continue}}if(n.operator===">"||n.operator===">>"||n.operator===">|"||n.operator==="&>"||n.operator==="&>>"){let o=e.fs.resolvePath(e.state.cwd,a);(n.operator===">"||n.operator===">|"||n.operator==="&>")&&await e.fs.writeFile(o,""),e.state.fileDescriptors.set(i,`__file__:${o}`)}else if(n.operator==="<<<")e.state.fileDescriptors.set(i,`${a}
|
|
23
|
+
`);else if(n.operator==="<"||n.operator==="<>")try{let o=e.fs.resolvePath(e.state.cwd,a),l=await e.fs.readFileText(o);e.state.fileDescriptors.set(i,l)}catch{return W(A(),V(`bash: ${a}: No such file or directory
|
|
24
|
+
`),1)}}}return null}var xo={write(){}},Oo={write(){let e=new Error(`bash: echo: write error: No space left on device
|
|
25
|
+
`);return e.code="ENOSPC",Promise.reject(e)}};function Io(e){return e.target.type==="HereDoc"||e.operator==="<"||e.operator==="<>"||e.operator==="<<<"||e.operator==="<<"||e.operator==="<<-"}function on(e,t){return{...e,target:{type:"Word",parts:[{type:"Literal",value:t}]}}}function vs(e,t){let s=Promise.resolve();return{write(n){let r=s.then(()=>e.fs.appendFile(t,n));return s=r.catch(()=>{}),r}}}function ei(e,t,s,n=new Set){let r=t.bindings.get(s),i=r?.sink;if(i)return i;if(n.has(s))return;n.add(s);let a=r?.descriptor,o;if(a?.startsWith("__file__:"))o=vs(e,a.slice(9));else if(a?.startsWith("__file_append__:"))o=vs(e,a.slice(16));else if(a?.startsWith("__rw__:")){let l=gs(a);l&&(o=vs(e,l.path))}else if(a?.startsWith("__dupout__:")){let l=Number.parseInt(a.slice(11),10);Number.isNaN(l)||(o=ei(e,t,l,n))}return o&&t.bindings.set(s,{...r,sink:o}),o}async function Qr(e,t,s,n,r=!1){if(s==="/dev/null")return{sink:xo,descriptor:"__file__:/dev/null"};if(s==="/dev/full")return{sink:Oo,descriptor:"__file__:/dev/full"};if(s==="/dev/stdout"||s==="/dev/stderr"){let o=s==="/dev/stdout"?1:2,l=t.bindings.get(o),c=l?.sink;return c?{sink:c,descriptor:l.descriptor??`__dupout__:${o}`}:{error:je(o)}}let i=e.fs.resolvePath(e.state.cwd,s),a=await Yr(e,i,s,{checkNoclobber:n==="truncate",isClobber:r});return a?{error:a}:(n==="truncate"?await e.fs.writeFile(i,""):await e.fs.appendFile(i,new Uint8Array),{sink:vs(e,i),descriptor:n==="append"?`__file_append__:${i}`:`__file__:${i}`})}function st(e,t,s){e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,s)}function Do(e,t){return e.bindings.get(t)?.descriptor??`__dupout__:${t}`}function an(e,t,s,n,r){if(!(!r&&!t.fdVariable)){if(t.fdVariable&&n.startsWith("__file_append__:")){st(e,s,`__file__:${n.slice(16)}`);return}st(e,s,n)}}function ws(e,t,s,n,r,i=!0){let a=e.state.fileDescriptors?.get(s),o=r?.startsWith("__file_append__:")?`__file__:${r.slice(16)}`:r;(n||t.fdVariable)&&i&&a!==void 0&&a===o&&e.state.fileDescriptors?.delete(s)}function Ne(e,t,s){return{channels:e,legacyRedirections:t,error:C(s)}}async function xe(e,t,s,n={}){let r={bindings:new Map(t.bindings),parent:t,overrides:new Set};for(let[o,l]of e.state.fileDescriptors??[]){let c=r.bindings.get(o);c?.descriptor===void 0&&r.bindings.set(o,{...c,descriptor:l})}let i=[],a=n.persistent===!0;for(let o of s){let l;if(o.operator==="<&"&&o.target.type==="Word"){let S=await ys(e,o);if("error"in S)return Ne(r,i,S.error);l=S.target;let E=l.startsWith("&")?l.slice(1):l,b=/^\d+-?$/.test(E);if(l!=="-"&&!b)return Ne(r,i,`bash: ${l}: ambiguous redirect
|
|
26
|
+
`);if(!o.fdVariable&&(o.fd??0)===0){i.push(on(o,l));continue}}if(o.operator==="<"&&!o.fdVariable&&o.target.type==="Word"){let S=await ys(e,o);if("error"in S)return Ne(r,i,S.error);let E=nn(S.target);if(E)return Ne(r,i,E);try{let b=e.fs.resolvePath(e.state.cwd,S.target),g=await e.fs.stat(b)}catch{return Ne(r,i,`bash: ${S.target}: No such file or directory
|
|
27
|
+
`)}i.push(on(o,S.target));continue}if(Io(o)){if(o.fdVariable&&o.target.type==="Word"){let S=await pt(e,[o],g=>Ws(r,g));if(S)return{channels:r,legacyRedirections:i,error:S};let E=Number.parseInt(x(e.state.env,o.fdVariable),10),b=e.state.fileDescriptors?.get(E);if(!Number.isNaN(E)&&b!==void 0){let g=r.bindings.get(E);r.bindings.set(E,{...g,descriptor:b})}}else i.push(o);continue}let c;if(l!==void 0)c=l;else{let S=await ys(e,o);if("error"in S)return Ne(r,i,S.error);c=S.target}let u=nn(c);if(u)return Ne(r,i,u);if((o.operator===">&"||o.operator==="<&")&&c==="-"&&o.fdVariable){if(e.state.env.has(o.fdVariable)){let S=Number.parseInt(x(e.state.env,o.fdVariable),10);if(!Number.isNaN(S)){let E=r.bindings.get(S)?.descriptor,b=Pt(r,S);ws(e,o,S,a,E,b)}}continue}let f=o.fdVariable?rn(e,S=>Ws(r,S)):o.fd??(o.operator==="<&"?0:1);if(o.fdVariable&&y(e.state.env,o.fdVariable,String(f)),!Number.isInteger(f)||f<0)return Ne(r,i,je(f));if(o.operator===">"||o.operator===">|"||o.operator===">>"||o.operator==="&>"||o.operator==="&>>"){let S=o.operator===">>"||o.operator==="&>>",E=await Qr(e,r,c,S?"append":"truncate",o.operator===">|");if("error"in E)return Ne(r,i,E.error);o.operator==="&>"||o.operator==="&>>"?(r.bindings.set(1,{sink:E.sink,descriptor:E.descriptor}),r.bindings.set(2,{sink:E.sink,descriptor:E.descriptor}),r.overrides?.add(1),r.overrides?.add(2),a&&(st(e,1,E.descriptor),st(e,2,E.descriptor))):(o.fdVariable?kt(r,f,E.sink,E.descriptor):(r.bindings.set(f,{sink:E.sink,descriptor:E.descriptor}),r.overrides?.add(f)),an(e,o,f,E.descriptor,a));continue}if(o.operator!==">&"&&o.operator!=="<&"){i.push(o);continue}if(c==="-"){let S=r.bindings.get(f)?.descriptor;r.overrides?.add(f),r.bindings.set(f,{descriptor:Xt}),ws(e,o,f,a,S);continue}let d=c.endsWith("-"),p=d?c.slice(0,-1):c,m=p.startsWith("&")?p.slice(1):p,h=/^\d+$/.test(m)?Number.parseInt(m,10):Number.NaN;if(!Number.isNaN(h)){let S=ei(e,r,h);if(!S){let b=r.bindings.get(h)?.descriptor;if(b===Xt)return Ne(r,i,je(h));if(o.operator==="<&"&&o.fdVariable&&b!==void 0){if(r.bindings.set(f,{descriptor:b}),st(e,f,b),d){let g=Pt(r,h);ws(e,o,h,a,b,g)}continue}if(o.operator==="<&"&&!o.fdVariable){i.push(on(o,c));continue}return Ne(r,i,je(h))}let E=Do(r,h);if(o.fdVariable?kt(r,f,S,E):r.bindings.set(f,{sink:S,descriptor:E}),an(e,o,f,E,a),d){let b=!0;o.fdVariable?b=Pt(r,h):(r.overrides?.add(h),r.bindings.set(h,{descriptor:Xt}),n.persistMovedSource&&r.parent&&(b=Pt(r.parent,h))),ws(e,o,h,a||n.persistMovedSource===!0,E,b)}o.fdVariable||r.overrides?.add(f);continue}if(o.operator==="<&")return Ne(r,i,`bash: ${c}: ambiguous redirect
|
|
28
|
+
`);let v=await Qr(e,r,c,"truncate");if("error"in v)return Ne(r,i,v.error);o.fd==null&&!o.fdVariable?(r.bindings.set(1,{sink:v.sink,descriptor:v.descriptor}),r.bindings.set(2,{sink:v.sink,descriptor:v.descriptor}),r.overrides?.add(1),r.overrides?.add(2),a&&(st(e,1,v.descriptor),st(e,2,v.descriptor))):(o.fdVariable?kt(r,f,v.sink,v.descriptor):(r.bindings.set(f,{sink:v.sink,descriptor:v.descriptor}),r.overrides?.add(f)),an(e,o,f,v.descriptor,a))}return{channels:r,legacyRedirections:i}}async function ti(e,t){let s=e.outputChannels,n=await xe(e,s,t,{persistent:!0});if(n.error)return n;for(let r of n.channels.overrides??[]){let i=n.channels.bindings.get(r);i?.descriptor!==void 0&&kt(s,r,i.sink,i.descriptor)}return{...n,channels:s}}async function si(e,t){if(e.state.options.posix&&tn.has(t.name)){let n=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
|
|
29
|
+
`;throw await U(e,2,n,!0),new q(2)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),B()}async function Ro(e,t){let s=A(),n=!1;for(let r of t)if(!r.fdVariable){if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let i=r.target,a=await z(e,i.content);i.stripTabs&&(a=a.split(`
|
|
28
30
|
`).map(l=>l.replace(/^\t+/,"")).join(`
|
|
29
31
|
`)),(r.fd??0)===0&&(s=V(a),n=!0)}else if(r.operator==="<<<"&&r.target.type==="Word")s=V(`${await z(e,r.target)}
|
|
30
|
-
`),n=!0;else if(r.operator==="<"&&r.target.type==="Word"){let i=await z(e,r.target),a=e.fs.resolvePath(e.state.cwd,i);try{s=await e.fs.readFile(a),n=!0}catch{}}}return s}async function
|
|
31
|
-
`,2);let N=t[
|
|
32
|
-
`,2);s.push(N)}else if(
|
|
33
|
-
`,2);n=t[
|
|
34
|
-
`,2);r=t[
|
|
35
|
-
`,2);i=t[
|
|
36
|
-
`,2);let N=t[
|
|
37
|
-
`,2)}else if(
|
|
38
|
-
`,2);f=t[
|
|
39
|
-
`,2);d=t[
|
|
40
|
-
`,2);
|
|
41
|
-
`,2)}else if(
|
|
42
|
-
`);for(let O of k)O.length>0&&h.push(O)}}catch(
|
|
43
|
-
`,2);throw
|
|
44
|
-
`),
|
|
45
|
-
`:"");return G(
|
|
46
|
-
`);if(s.length===0)return[t];let n=new Set(s.split("")),r=[],i="",a=0;for(;a<t.length;){let o=t[a];if(o==="\\"&&a+1<t.length){let l=t[a+1];i+=l,a+=2}else n.has(o)?(i.length>0&&(r.push(i),i=""),a++):(i+=o,a++)}return i.length>0&&r.push(i),r}function mt(e,t){for(let[s,n]of t)n===void 0?e.state.env.delete(s):y(e.state.env,s,n)}function
|
|
47
|
-
`,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return
|
|
48
|
-
`,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return
|
|
49
|
-
`,2);let p=t[f];if(!
|
|
50
|
-
`,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return
|
|
51
|
-
`,2);
|
|
52
|
-
`,2);o=t[f]}else if(d==="-G"){if(f++,f>=t.length)return
|
|
53
|
-
`,2)}else if(d==="-P"){if(f++,f>=t.length)return
|
|
54
|
-
`,2)}else if(d==="-S"){if(f++,f>=t.length)return
|
|
55
|
-
`,2)}else if(d==="-X"){if(f++,f>=t.length)return
|
|
56
|
-
`,2)}else if(d==="--"){
|
|
57
|
-
`,2);if(r){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),a!==void 0&&(f.function=a),o!==void 0&&(f.command=o),l.length>0&&(f.options=l),
|
|
58
|
-
`;return W(
|
|
32
|
+
`),n=!0;else if(r.operator==="<"&&r.target.type==="Word"){let i=await z(e,r.target),a=e.fs.resolvePath(e.state.cwd,i);try{s=await e.fs.readFile(a),n=!0}catch{}}}return s}async function bs(e,t,s,n=A(),r){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Re(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(r??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??"main"),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let i=new Map;for(let o=0;o<s.length;o++)i.set(String(o+1),x(e.state.env,String(o+1))),y(e.state.env,String(o+1),s[o]);i.set("@",x(e.state.env,"@")),i.set("#",x(e.state.env,"#")),y(e.state.env,"@",s.join(" ")),y(e.state.env,"#",String(s.length));let a=()=>{let o=e.state.localScopes.length-1,l=e.state.localScopes.pop();if(l)for(let[c,u]of l)u===void 0?e.state.env.delete(c):e.state.env.set(c,u);if(Xr(e,o),e.state.fullyUnsetLocals)for(let[c,u]of e.state.fullyUnsetLocals.entries())u===o&&e.state.fullyUnsetLocals.delete(c);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let c=e.state.localExportedVars.pop();if(c)for(let u of c)e.state.exportedVars?.delete(u)}for(let[c,u]of i)u===void 0?e.state.env.delete(c):y(e.state.env,c,u);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--};try{let o=await xe(e,e.outputChannels,t.redirections);return o.error?await K(e,o.channels,()=>te(e,()=>Promise.resolve(o.error))):await K(e,o.channels,async()=>{try{let l=await pt(e,o.legacyRedirections);if(l)return await te(e,()=>Promise.resolve(l));let c=await ie(n),u=c.length>0?he(c):await Ro(e,o.legacyRedirections),f=await e.executeCommand(t.body,u);return await te(e,()=>Promise.resolve(f))}catch(l){let{writeFailure:c}=await Ze(e,l);if(c)return c;if(l instanceof we)return W(A(),A(),l.exitCode);throw l}})}catch(o){throw await ee(e,o),o}finally{a()}}var ri=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],cn=[".",":","[","alias","bg","bind","break","builtin","caller","cd","command","compgen","complete","compopt","continue","declare","dirs","disown","echo","enable","eval","exec","exit","export","false","fc","fg","getopts","hash","help","history","jobs","kill","let","local","logout","mapfile","popd","printf","pushd","pwd","read","readarray","readonly","return","set","shift","shopt","source","suspend","test","times","trap","true","type","typeset","ulimit","umask","unalias","unset","wait"],Lo=["autocd","assoc_expand_once","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","dotglob","execfail","expand_aliases","extdebug","extglob","extquote","failglob","force_fignore","globasciiranges","globstar","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lastpipe","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","nocaseglob","nocasematch","nullglob","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath","xpg_echo"],Mo=cn;async function un(e,t){let s=[],n=null,r="",i="",a=null,o=!1,l=!1,c=!1,u=null,f=null,d=null,p=[],m=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let g=0;g<t.length;g++){let P=t[g];if(P==="-v")s.push("variable");else if(P==="-e")s.push("export");else if(P==="-f")s.push("file");else if(P==="-d")s.push("directory");else if(P==="-k")s.push("keyword");else if(P==="-A"){if(g++,g>=t.length)return C(`compgen: -A: option requires an argument
|
|
33
|
+
`,2);let N=t[g];if(!m.includes(N))return C(`compgen: ${N}: invalid action name
|
|
34
|
+
`,2);s.push(N)}else if(P==="-W"){if(g++,g>=t.length)return C(`compgen: -W: option requires an argument
|
|
35
|
+
`,2);n=t[g]}else if(P==="-P"){if(g++,g>=t.length)return C(`compgen: -P: option requires an argument
|
|
36
|
+
`,2);r=t[g]}else if(P==="-S"){if(g++,g>=t.length)return C(`compgen: -S: option requires an argument
|
|
37
|
+
`,2);i=t[g]}else if(P==="-o"){if(g++,g>=t.length)return C(`compgen: -o: option requires an argument
|
|
38
|
+
`,2);let N=t[g];if(N==="plusdirs")o=!0;else if(N==="dirnames")l=!0;else if(N==="default")c=!0;else if(!(N==="filenames"||N==="nospace"||N==="bashdefault"||N==="noquote"))return C(`compgen: ${N}: invalid option name
|
|
39
|
+
`,2)}else if(P==="-F"){if(g++,g>=t.length)return C(`compgen: -F: option requires an argument
|
|
40
|
+
`,2);f=t[g]}else if(P==="-C"){if(g++,g>=t.length)return C(`compgen: -C: option requires an argument
|
|
41
|
+
`,2);d=t[g]}else if(P==="-X"){if(g++,g>=t.length)return C(`compgen: -X: option requires an argument
|
|
42
|
+
`,2);u=t[g]}else if(P==="-G"){if(g++,g>=t.length)return C(`compgen: -G: option requires an argument
|
|
43
|
+
`,2)}else if(P==="--"){p.push(...t.slice(g+1));break}else P.startsWith("-")||p.push(P)}a=p[0]??null;let h=[];if(l){let g=await ln(e,a);h.push(...g)}if(c){let g=await ni(e,a);h.push(...g)}for(let g of s)if(g==="variable"){let P=Wo(e,a);h.push(...P)}else if(g==="export"){let P=Fo(e,a);h.push(...P)}else if(g==="function"){let P=Vo(e,a);h.push(...P)}else if(g==="builtin"){let P=zo(a);h.push(...P)}else if(g==="keyword"){let P=jo(a);h.push(...P)}else if(g==="alias"){let P=Bo(e,a);h.push(...P)}else if(g==="shopt"){let P=Ho(a);h.push(...P)}else if(g==="helptopic"){let P=Uo(a);h.push(...P)}else if(g==="directory"){let P=await ln(e,a);h.push(...P)}else if(g==="file"){let P=await ni(e,a);h.push(...P)}else if(g==="user"){let P=Go(a);h.push(...P)}else if(g==="command"){let P=await qo(e,a);h.push(...P)}if(n!==null)try{let g=await Zo(e,n),P=Jo(e,g);for(let N of P)(a===null||N.startsWith(a))&&h.push(N)}catch{return W(R,R,1)}if(o){let g=await ln(e,a);for(let P of g)h.includes(P)||h.push(P)}let v="";if(f!==null){let g=e.state.functions.get(f);if(g){let P=new Map;P.set("COMP_WORDS__length",x(e.state.env,"COMP_WORDS__length")),y(e.state.env,"COMP_WORDS__length","0"),P.set("COMP_CWORD",x(e.state.env,"COMP_CWORD")),y(e.state.env,"COMP_CWORD","-1"),P.set("COMP_LINE",x(e.state.env,"COMP_LINE")),y(e.state.env,"COMP_LINE",""),P.set("COMP_POINT",x(e.state.env,"COMP_POINT")),y(e.state.env,"COMP_POINT","0");let N=new Map;for(let $ of e.state.env.keys())($==="COMPREPLY"||$.startsWith("COMPREPLY_")||$==="COMPREPLY__length")&&(N.set($,x(e.state.env,$)),e.state.env.delete($));let M=["compgen",p[0]??"",""];try{let $=_e(),k=_e(),O=await K(e,{bindings:new Map([[1,{sink:$}],[2,{sink:k}]])},()=>bs(e,g,M,A()));if(await _t(e,O.stderr,k),O.exitCode!==0)return mt(e,P),mt(e,N),W(R,k.stream(),1);await _t(e,O.stdout,$),v=H(await ie($.stream()));let D=Xo(e);h.push(...D)}catch{return mt(e,P),mt(e,N),W(R,R,1)}mt(e,P),mt(e,N)}}if(d!==null)try{let g=Le(d),P=_e(),N=_e(),M=await K(e,{bindings:new Map([[1,{sink:P}],[2,{sink:N}]])},()=>e.executeScript(g));if(await _t(e,M.stderr,N),M.exitCode!==0)return W(R,N.stream(),M.exitCode);await _t(e,M.stdout,P);let $=await ie(P.stream());if($.length>0){let k=H($).split(`
|
|
44
|
+
`);for(let O of k)O.length>0&&h.push(O)}}catch(g){if(g.name==="ParseException")return C(`compgen: -C: ${g.message}
|
|
45
|
+
`,2);throw g}let S=h;if(u!==null){let g=u.startsWith("!"),P=g?u.slice(1):u;S=h.filter(N=>{let M=dt(N,P,!1,!0);return g?M:!M})}if(S.length===0&&a!==null)return W(F(v),R,1);let E=S.map(g=>`${r}${g}${i}`).join(`
|
|
46
|
+
`),b=v+(E?`${E}
|
|
47
|
+
`:"");return G(b)}function Wo(e,t){let s=new Set;for(let r of e.state.env.keys()){if(r.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(r)||r.endsWith("__length"))continue;let i=r.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)?s.add(r):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let n=Array.from(s);return t!==null&&(n=n.filter(r=>r.startsWith(t))),n.sort()}function Fo(e,t){let s=e.state.exportedVars??new Set,n=Array.from(s);return t!==null&&(n=n.filter(r=>r.startsWith(t))),n=n.filter(r=>r.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(r)||r.endsWith("__length")?!1:e.state.env.has(r)),n.sort()}function Vo(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(n=>n.startsWith(t))),s.sort()}function zo(e){let t=[...cn];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function jo(e){let t=[...ri];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Bo(e,t){let s=[];for(let r of e.state.env.keys())if(r.startsWith("BASH_ALIAS_")){let i=r.slice(11);s.push(i)}let n=s;return t!==null&&(n=n.filter(r=>r.startsWith(t))),n.sort()}function Ho(e){let t=[...Lo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Uo(e){let t=[...Mo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function ln(e,t){let s=[];try{let n=e.state.cwd,r=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";r=t.slice(a+1),o.startsWith("/")?n=o:n=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(n);for(let a of i){let o=`${n}/${a}`;try{if((await e.fs.stat(o)).isDirectory&&(!r||a.startsWith(r)))if(t?.includes("/")){let c=t.lastIndexOf("/"),u=t.slice(0,c+1);s.push(u+a)}else s.push(a)}catch{}}}catch{}return s.sort()}async function ni(e,t){let s=[];try{let n=e.state.cwd,r=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";r=t.slice(a+1),o.startsWith("/")?n=o:n=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(n);for(let a of i)if(!r||a.startsWith(r))if(t?.includes("/")){let o=t.lastIndexOf("/"),l=t.slice(0,o+1);s.push(l+a)}else s.push(a)}catch{}return s.sort()}function Go(e){return["root","nobody"]}async function qo(e,t){let s=new Set;for(let i of cn)s.add(i);for(let i of e.state.functions.keys())s.add(i);for(let i of e.state.env.keys())i.startsWith("BASH_ALIAS_")&&s.add(i.slice(11));for(let i of ri)s.add(i);let n=x(e.state.env,"PATH","/usr/bin:/bin");for(let i of n.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let o of a)s.add(o)}catch{}let r=Array.from(s);return t!==null&&(r=r.filter(i=>i.startsWith(t))),r.sort()}async function Zo(e,t){let n=new Z().parseWordFromString(t,!1,!1);return await z(e,n)}function Jo(e,t){let s=x(e.state.env,"IFS",`
|
|
48
|
+
`);if(s.length===0)return[t];let n=new Set(s.split("")),r=[],i="",a=0;for(;a<t.length;){let o=t[a];if(o==="\\"&&a+1<t.length){let l=t[a+1];i+=l,a+=2}else n.has(o)?(i.length>0&&(r.push(i),i=""),a++):(i+=o,a++)}return i.length>0&&r.push(i),r}function mt(e,t){for(let[s,n]of t)n===void 0?e.state.env.delete(s):y(e.state.env,s,n)}function Xo(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let r=Ie(e,"COMPREPLY");for(let[,i]of r)t.push(i)}else e.state.env.has("COMPREPLY")&&t.push(x(e.state.env,"COMPREPLY"));return t}var Ko=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function dn(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,n=!1,r=!1,i,a,o,l=[],c=[],u=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")s=!0;else if(d==="-r")n=!0;else if(d==="-D")r=!0;else if(d==="-W"){if(f++,f>=t.length)return C(`complete: -W: option requires an argument
|
|
49
|
+
`,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return C(`complete: -F: option requires an argument
|
|
50
|
+
`,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return C(`complete: -o: option requires an argument
|
|
51
|
+
`,2);let p=t[f];if(!Ko.includes(p))return C(`complete: ${p}: invalid option name
|
|
52
|
+
`,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return C(`complete: -A: option requires an argument
|
|
53
|
+
`,2);c.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return C(`complete: -C: option requires an argument
|
|
54
|
+
`,2);o=t[f]}else if(d==="-G"){if(f++,f>=t.length)return C(`complete: -G: option requires an argument
|
|
55
|
+
`,2)}else if(d==="-P"){if(f++,f>=t.length)return C(`complete: -P: option requires an argument
|
|
56
|
+
`,2)}else if(d==="-S"){if(f++,f>=t.length)return C(`complete: -S: option requires an argument
|
|
57
|
+
`,2)}else if(d==="-X"){if(f++,f>=t.length)return C(`complete: -X: option requires an argument
|
|
58
|
+
`,2)}else if(d==="--"){u.push(...t.slice(f+1));break}else d.startsWith("-")||u.push(d)}if(n){if(u.length===0)return e.state.completionSpecs.clear(),Te();for(let f of u)e.state.completionSpecs.delete(f);return Te()}if(s)return u.length===0?fn(e):fn(e,u);if(t.length===0||u.length===0&&!i&&!a&&!o&&l.length===0&&c.length===0&&!r)return fn(e);if(a&&u.length===0&&!r)return C(`complete: -F: option requires a command name
|
|
59
|
+
`,2);if(r){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),a!==void 0&&(f.function=a),o!==void 0&&(f.command=o),l.length>0&&(f.options=l),c.length>0&&(f.actions=c),e.state.completionSpecs.set("__default__",f),Te()}for(let f of u){let d=Object.create(null);i!==void 0&&(d.wordlist=i),a!==void 0&&(d.function=a),o!==void 0&&(d.command=o),l.length>0&&(d.options=l),c.length>0&&(d.actions=c),e.state.completionSpecs.set(f,d)}return Te()}function fn(e,t){let s=e.state.completionSpecs;if(!s||s.size===0){if(t&&t.length>0){let i="";for(let a of t)i+=`complete: ${a}: no completion specification
|
|
60
|
+
`;return W(R,F(i),1)}return Te()}let n=[],r=t||Array.from(s.keys());for(let i of r){if(i==="__default__")continue;let a=s.get(i);if(!a){if(t)return W(F(n.join(`
|
|
59
61
|
`)+(n.length>0?`
|
|
60
62
|
`:"")),F(`complete: ${i}: no completion specification
|
|
61
63
|
`),1);continue}let o="complete";if(a.options)for(let l of a.options)o+=` -o ${l}`;if(a.actions)for(let l of a.actions)o+=` -A ${l}`;a.wordlist!==void 0&&(a.wordlist.includes(" ")||a.wordlist.includes("'")?o+=` -W '${a.wordlist}'`:o+=` -W ${a.wordlist}`),a.function!==void 0&&(o+=` -F ${a.function}`),a.isDefault&&(o+=" -D"),o+=` ${i}`,n.push(o)}return n.length===0?Te():G(`${n.join(`
|
|
62
64
|
`)}
|
|
63
|
-
`)}var ii=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function hn(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,n=!1,r=[],i=[],a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-D")s=!0;else if(l==="-E")n=!0;else if(l==="-o"){if(o++,o>=t.length)return
|
|
64
|
-
`,2);let
|
|
65
|
-
`,2);r.push(
|
|
66
|
-
`,2);let
|
|
67
|
-
`,2);i.push(
|
|
65
|
+
`)}var ii=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function hn(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,n=!1,r=[],i=[],a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-D")s=!0;else if(l==="-E")n=!0;else if(l==="-o"){if(o++,o>=t.length)return C(`compopt: -o: option requires an argument
|
|
66
|
+
`,2);let c=t[o];if(!ii.includes(c))return C(`compopt: ${c}: invalid option name
|
|
67
|
+
`,2);r.push(c)}else if(l==="+o"){if(o++,o>=t.length)return C(`compopt: +o: option requires an argument
|
|
68
|
+
`,2);let c=t[o];if(!ii.includes(c))return C(`compopt: ${c}: invalid option name
|
|
69
|
+
`,2);i.push(c)}else if(l==="--"){a.push(...t.slice(o+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&a.push(l)}if(s){let o=e.state.completionSpecs.get("__default__")??{isDefault:!0},l=new Set(o.options??[]);for(let c of r)l.add(c);for(let c of i)l.delete(c);return o.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__default__",o),Te()}if(n){let o=e.state.completionSpecs.get("__empty__")??{},l=new Set(o.options??[]);for(let c of r)l.add(c);for(let c of i)l.delete(c);return o.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__empty__",o),Te()}if(a.length>0){for(let o of a){let l=e.state.completionSpecs.get(o)??{},c=new Set(l.options??[]);for(let u of r)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set(o,l)}return Te()}return C(`compopt: not currently executing completion function
|
|
68
70
|
`,1)}async function pn(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Be;return B()}if(t.length>1)throw await U(e,2,`bash: continue: too many arguments
|
|
69
71
|
`,!0),new q(1);let s=1;if(t.length>0){let n=Number.parseInt(t[0],10);if(Number.isNaN(n)||n<1)throw await U(e,2,`bash: continue: ${t[0]}: numeric argument required
|
|
70
|
-
`,!0),new q(1);s=n}throw new Ce(s)}function se(e,t){let s=x(e.state.env,"HOME","/home/user");return t.split(":").map(i=>i==="~"?s:i==="~root"?"/root":i.startsWith("~/")?s+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function mn(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function gn(e){let t="$'";for(let s=0;s<e.length;s++){let n=e[s],r=e.charCodeAt(s);r===7?t+="\\a":r===8?t+="\\b":r===9?t+="\\t":r===10?t+="\\n":r===11?t+="\\v":r===12?t+="\\f":r===13?t+="\\r":r===27?t+="\\e":r===39?t+="\\'":r===92?t+="\\\\":r<32||r===127?t+=`\\${r.toString(8).padStart(3,"0")}`:t+=n}return t+="'",t}function
|
|
71
|
-
`;else{let c
|
|
72
|
-
`}continue}let l=pe(e,i);if(l.length>0){let
|
|
72
|
+
`,!0),new q(1);s=n}throw new Ce(s)}function se(e,t){let s=x(e.state.env,"HOME","/home/user");return t.split(":").map(i=>i==="~"?s:i==="~root"?"/root":i.startsWith("~/")?s+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function mn(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function gn(e){let t="$'";for(let s=0;s<e.length;s++){let n=e[s],r=e.charCodeAt(s);r===7?t+="\\a":r===8?t+="\\b":r===9?t+="\\t":r===10?t+="\\n":r===11?t+="\\v":r===12?t+="\\f":r===13?t+="\\r":r===27?t+="\\e":r===39?t+="\\'":r===92?t+="\\\\":r<32||r===127?t+=`\\${r.toString(8).padStart(3,"0")}`:t+=n}return t+="'",t}function Ss(e){return mn(e)?gn(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function nt(e){return mn(e)?gn(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function yn(e){return mn(e)?gn(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function oi(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),be(e,t)&&(s+="n"),e.state.readonlyVars?.has(t)&&(s+="r"),e.state.uppercaseVars?.has(t)&&(s+="u"),e.state.exportedVars?.has(t)&&(s+="x"),s===""?"--":`-${s}`}function wn(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function ai(e,t){let s="",n="",r=!1;for(let i of t){let a=oi(e,i);if(e.state.associativeArrays?.has(i)){let c=Je(e,i);if(c.length===0)s+=`declare -A ${i}=()
|
|
73
|
+
`;else{let u=c.map(f=>{let d=x(e.state.env,`${i}_${f}`,""),p=wn(d);return`['${f}']=${p}`});s+=`declare -A ${i}=(${u.join(" ")})
|
|
74
|
+
`}continue}let l=pe(e,i);if(l.length>0){let c=l.map(u=>{let f=x(e.state.env,`${i}_${u}`,"");return`[${u}]=${nt(f)}`});s+=`declare -a ${i}=(${c.join(" ")})
|
|
73
75
|
`;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=()
|
|
74
|
-
`;continue}if(e.state.env.has(i)){let
|
|
75
|
-
`}else{let
|
|
76
|
+
`;continue}if(e.state.env.has(i)){let c=x(e.state.env,i);s+=`declare ${a} ${i}=${yn(c)}
|
|
77
|
+
`}else{let c=e.state.declaredVars?.has(i),u=e.state.localVarDepth?.has(i);c||u?s+=`declare ${a} ${i}
|
|
76
78
|
`:(n+=`bash: declare: ${i}: not found
|
|
77
|
-
`,r=!0)}}return W(F(s),F(n),r?1:0)}function li(e,t){let{filterExport:s,filterReadonly:n,filterNameref:r,filterIndexedArray:i,filterAssocArray:a}=t,o=s||n||r||i||a,l="",
|
|
78
|
-
`;else{let S=
|
|
79
|
-
`}continue}if(m.length>0){let
|
|
79
|
+
`,r=!0)}}return W(F(s),F(n),r?1:0)}function li(e,t){let{filterExport:s,filterReadonly:n,filterNameref:r,filterIndexedArray:i,filterAssocArray:a}=t,o=s||n||r||i||a,l="",c=new Set;for(let f of e.state.env.keys()){if(f.startsWith("BASH_"))continue;if(f.endsWith("__length")){let p=f.slice(0,-8);c.add(p);continue}let d=f.lastIndexOf("_");if(d>0){let p=f.slice(0,d),m=f.slice(d+1);if(/^\d+$/.test(m)||e.state.associativeArrays?.has(p)){c.add(p);continue}}c.add(f)}if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())c.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)c.add(f);let u=Array.from(c).sort();for(let f of u){let d=oi(e,f),p=e.state.associativeArrays?.has(f),m=pe(e,f),h=!p&&(m.length>0||e.state.env.has(`${f}__length`));if(!(o&&(a&&!p||i&&!h||s&&!e.state.exportedVars?.has(f)||n&&!e.state.readonlyVars?.has(f)||r&&!be(e,f)))){if(p){let v=Je(e,f);if(v.length===0)l+=`declare -A ${f}=()
|
|
80
|
+
`;else{let S=v.map(E=>{let b=x(e.state.env,`${f}_${E}`,""),g=wn(b);return`['${E}']=${g}`});l+=`declare -A ${f}=(${S.join(" ")})
|
|
81
|
+
`}continue}if(m.length>0){let v=m.map(S=>{let E=x(e.state.env,`${f}_${S}`,"");return`[${S}]=${nt(E)}`});l+=`declare -a ${f}=(${v.join(" ")})
|
|
80
82
|
`;continue}if(e.state.env.has(`${f}__length`)){l+=`declare -a ${f}=()
|
|
81
|
-
`;continue}if(e.state.env.has(f)){let
|
|
83
|
+
`;continue}if(e.state.env.has(f)){let v=x(e.state.env,f);l+=`declare ${d} ${f}=${yn(v)}
|
|
82
84
|
`}}}return G(l)}function ci(e){let t="",s=Array.from(e.state.associativeArrays??[]).sort();for(let n of s){let r=Je(e,n);if(r.length===0)t+=`declare -A ${n}=()
|
|
83
85
|
`;else{let i=r.map(a=>{let o=x(e.state.env,`${n}_${a}`,""),l=wn(o);return`['${a}']=${l}`});t+=`declare -A ${n}=(${i.join(" ")})
|
|
84
86
|
`}}return G(t)}function ui(e){let t="",s=new Set;for(let r of e.state.env.keys()){if(r.startsWith("BASH_"))continue;if(r.endsWith("__length")){let a=r.slice(0,-8);e.state.associativeArrays?.has(a)||s.add(a);continue}let i=r.lastIndexOf("_");if(i>0){let a=r.slice(0,i),o=r.slice(i+1);/^\d+$/.test(o)&&(e.state.associativeArrays?.has(a)||s.add(a))}}let n=Array.from(s).sort();for(let r of n){let i=pe(e,r);if(i.length===0)t+=`declare -a ${r}=()
|
|
85
87
|
`;else{let a=i.map(o=>{let l=x(e.state.env,`${r}_${o}`,"");return`[${o}]=${nt(l)}`});t+=`declare -a ${r}=(${a.join(" ")})
|
|
86
|
-
`}}return G(t)}function fi(e){let t="",s=new Set;for(let r of e.state.env.keys()){if(r.startsWith("BASH_"))continue;if(r.endsWith("__length")){let a=r.slice(0,-8);s.add(a);continue}let i=r.lastIndexOf("_");if(i>0){let a=r.slice(0,i),o=r.slice(i+1);if(/^\d+$/.test(o)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(r)}let n=Array.from(s).sort();for(let r of n)e.state.associativeArrays?.has(r)||pe(e,r).length>0||e.state.env.has(`${r}__length`)||e.state.env.has(r)&&(t+=`${r}=${
|
|
87
|
-
`);return G(t)}function vn(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Dt(e,t){return e.state.integerVars?.has(t)??!1}function bn(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function
|
|
88
|
-
`),2)}}}else if(O==="-i")f=!0;else if(O==="-l")d=!0;else if(O==="-u")p=!0;else if(O==="-f")m=!0;else if(O==="-F")h=!0;else if(O==="-g")
|
|
89
|
-
`),2);else S.push(O)}let
|
|
90
|
-
`;return G(_)}let k=!0,O="";for(let
|
|
91
|
-
`:k=!1;return W(F(O),
|
|
88
|
+
`}}return G(t)}function fi(e){let t="",s=new Set;for(let r of e.state.env.keys()){if(r.startsWith("BASH_"))continue;if(r.endsWith("__length")){let a=r.slice(0,-8);s.add(a);continue}let i=r.lastIndexOf("_");if(i>0){let a=r.slice(0,i),o=r.slice(i+1);if(/^\d+$/.test(o)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(r)}let n=Array.from(s).sort();for(let r of n)e.state.associativeArrays?.has(r)||pe(e,r).length>0||e.state.env.has(`${r}__length`)||e.state.env.has(r)&&(t+=`${r}=${Ss(x(e.state.env,r))}
|
|
89
|
+
`);return G(t)}function vn(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Dt(e,t){return e.state.integerVars?.has(t)??!1}function bn(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Yo(e,t){return e.state.lowercaseVars?.has(t)??!1}function Sn(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Qo(e,t){return e.state.uppercaseVars?.has(t)??!1}function gt(e,t,s){return Yo(e,t)?s.toLowerCase():Qo(e,t)?s.toUpperCase():s}async function di(e,t){try{let s=new Z,n=le(s,t),r=await Q(e,n.expression);return String(r)}catch{return"0"}}function ea(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],n=s.length;if(e[n]!=="[")return null;let r=0,i=n+1;for(;n<e.length;n++)if(e[n]==="[")r++;else if(e[n]==="]"&&(r--,r===0))break;if(r!==0)return null;let a=e.slice(i,n);if(n++,e[n]!=="=")return null;n++;let o=e.slice(n);return{name:s,indexExpr:a,value:o}}async function En(e,t){let s=!1,n=!1,r=!1,i=!1,a=!1,o=!1,l=!1,c=!1,u=!1,f=!1,d=!1,p=!1,m=!1,h=!1,v=!1,S=[];for(let k=0;k<t.length;k++){let O=t[k];if(O==="-a")s=!0;else if(O==="-A")n=!0;else if(O==="-r")r=!0;else if(O==="-x")i=!0;else if(O==="-p")a=!0;else if(O==="-n")o=!0;else if(O==="+n")l=!0;else if(O==="+a")c=!0;else if(O==="+x")u=!0;else if(O==="--"){S.push(...t.slice(k+1));break}else if(O.startsWith("+")){for(let D of O.slice(1))if(D==="n")l=!0;else if(D==="a")c=!0;else if(D==="x")u=!0;else if(D!=="r"){if(D!=="i"){if(!(D==="f"||D==="F"))return W(R,F(`bash: typeset: +${D}: invalid option
|
|
90
|
+
`),2)}}}else if(O==="-i")f=!0;else if(O==="-l")d=!0;else if(O==="-u")p=!0;else if(O==="-f")m=!0;else if(O==="-F")h=!0;else if(O==="-g")v=!0;else if(O.startsWith("-"))for(let D of O.slice(1))if(D==="a")s=!0;else if(D==="A")n=!0;else if(D==="r")r=!0;else if(D==="x")i=!0;else if(D==="p")a=!0;else if(D==="n")o=!0;else if(D==="i")f=!0;else if(D==="l")d=!0;else if(D==="u")p=!0;else if(D==="f")m=!0;else if(D==="F")h=!0;else if(D==="g")v=!0;else return W(R,F(`bash: typeset: -${D}: invalid option
|
|
91
|
+
`),2);else S.push(O)}let b=e.state.localScopes.length>0&&!v,g=k=>{if(!b)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(k)||O.set(k,e.state.env.get(k))},P=k=>{if(!b)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(k)||O.set(k,e.state.env.get(k));let D=`${k}_`;for(let T of e.state.env.keys())T.startsWith(D)&&!T.includes("__")&&(O.has(T)||O.set(T,e.state.env.get(T)));let _=`${k}__length`;e.state.env.has(_)&&!O.has(_)&&O.set(_,e.state.env.get(_))},N=k=>{b&&Ke(e,k)};if(h){if(S.length===0){let D=Array.from(e.state.functions.keys()).sort(),_="";for(let T of D)_+=`declare -f ${T}
|
|
92
|
+
`;return G(_)}let k=!0,O="";for(let D of S)e.state.functions.has(D)?O+=`${D}
|
|
93
|
+
`:k=!1;return W(F(O),R,k?0:1)}if(m){if(S.length===0){let O="",D=Array.from(e.state.functions.keys()).sort();for(let _ of D)O+=`${_} ()
|
|
92
94
|
{
|
|
93
95
|
# function body
|
|
94
96
|
}
|
|
95
|
-
`;return G(O)}let k=!0;for(let O of S)e.state.functions.has(O)||(k=!1);return W(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
`}}return G(a)}for(let a of i){let o=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(o){let f=o[1],d=o[2],p=await ue(e,f);if(p)return p;let m=ze(d);if(e.state.associativeArrays?.has(f)){let h=
|
|
103
|
-
`,2);n=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return
|
|
104
|
-
`,2);if(n!==void 0)return
|
|
105
|
-
`,2);n=l}}if(n===void 0){if(s.length<2)return
|
|
106
|
-
`,1);let o=s[0];s[0]=s[1],s[1]=o,n=s[0]}let r;if(n.startsWith("/"))r=n;else if(n===".."){let o=e.state.cwd.split("/").filter(l=>l);o.pop(),r=`/${o.join("/")}`}else n==="."?r=e.state.cwd:n.startsWith("~")?r=x(e.state.env,"HOME","/")+n.slice(1):r=`${e.state.cwd}/${n}`;r=ta(r);try{if(!(await e.fs.stat(r)).isDirectory)return
|
|
107
|
-
`,1)}catch{return
|
|
108
|
-
`,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=r,y(e.state.env,"PWD",r),y(e.state.env,"OLDPWD",e.state.previousDir);let i=x(e.state.env,"HOME",""),a=`${[r,...s].map(o=>
|
|
109
|
-
`;return G(a)}function kn(e,t){let s=An(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?
|
|
110
|
-
`,2):
|
|
111
|
-
`,2);if(s.length===0)return
|
|
112
|
-
`,1);let n=s.shift();if(!n)return
|
|
113
|
-
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=n,y(e.state.env,"PWD",n),y(e.state.env,"OLDPWD",e.state.previousDir);let r=x(e.state.env,"HOME",""),i=`${[n,...s].map(a=>
|
|
114
|
-
`;return G(i)}function Pn(e,t){let s=An(e),n=!1,r=!1,i=!1,a=!1;for(let
|
|
115
|
-
`,2);else return
|
|
116
|
-
`,1);if(n)return e.state.directoryStack=[],ft;let o=[e.state.cwd,...s],l=x(e.state.env,"HOME",""),
|
|
117
|
-
`),
|
|
118
|
-
`):i?
|
|
97
|
+
`;return G(O)}let k=!0;for(let O of S)e.state.functions.has(O)||(k=!1);return W(R,R,k?0:1)}if(a&&S.length>0)return ai(e,S);if(a&&S.length===0)return li(e,{filterExport:i,filterReadonly:r,filterNameref:o,filterIndexedArray:s,filterAssocArray:n});if(S.length===0&&n&&!a)return ci(e);if(S.length===0&&s&&!a)return ui(e);if(S.length===0&&!a)return fi(e);let M="",$=0;for(let k of S){let O=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(O&&!c){let w=O[1],I=O[2];if(n&&pe(e,w).length>0){M+=`bash: declare: ${w}: cannot convert indexed to associative array
|
|
98
|
+
`,$=1;continue}if((s||!n&&!s)&&e.state.associativeArrays?.has(w)){M+=`bash: declare: ${w}: cannot convert associative to indexed array
|
|
99
|
+
`,$=1;continue}if(P(w),n&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)),We(e,w),e.state.env.delete(w),e.state.env.delete(`${w}__length`),n&&I.includes("[")){let L=hs(I);for(let[J,j]of L){let X=se(e,j);y(e.state.env,`${w}_${J}`,X)}}else if(n){let L=ze(I);for(let J=0;J<L.length;J+=2){let j=L[J],X=J+1<L.length?se(e,L[J+1]):"";y(e.state.env,`${w}_${j}`,X)}}else{let L=ze(I);if(L.some(j=>/^\[[^\]]+\]=/.test(j))){let j=0;for(let X of L){let re=X.match(/^\[([^\]]+)\]=(.*)$/);if(re){let $e=re[1],rt=re[2],so=se(e,rt),vt;if(/^-?\d+$/.test($e))vt=Number.parseInt($e,10);else try{let no=new Z,ro=le(no,$e);vt=await Q(e,ro.expression)}catch{vt=0}y(e.state.env,`${w}_${vt}`,so),j=vt+1}else{let $e=se(e,X);y(e.state.env,`${w}_${j}`,$e),j++}}}else{for(let j=0;j<L.length;j++)y(e.state.env,`${w}_${j}`,L[j]);y(e.state.env,`${w}__length`,String(L.length))}}N(w),r&&Se(e,w),i&&De(e,w);continue}if(l){let w=k.includes("=")?k.slice(0,k.indexOf("=")):k;if(fr(e,w),!k.includes("="))continue}if(u){let w=k.includes("=")?k.slice(0,k.indexOf("=")):k;if(Yt(e,w),!k.includes("="))continue}let D=ea(k);if(D){let{name:w,indexExpr:I,value:L}=D,J=await ue(e,w);if(J)return J;P(w);let j;try{let re=new Z,$e=le(re,I);j=await Q(e,$e.expression)}catch{let re=parseInt(I,10);j=Number.isNaN(re)?0:re}y(e.state.env,`${w}_${j}`,L);let X=parseInt(x(e.state.env,`${w}__length`,"0"),10);j>=X&&y(e.state.env,`${w}__length`,String(j+1)),N(w),r&&Se(e,w),i&&De(e,w);continue}let _=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(_&&!c){let w=_[1],I=_[2],L=await ue(e,w);if(L)return L;P(w);let J=ze(I);if(e.state.associativeArrays?.has(w)){let j=hs(I);for(let[X,re]of j){let $e=se(e,re);y(e.state.env,`${w}_${X}`,$e)}}else{let j=pe(e,w),X=0,re=e.state.env.get(w);j.length===0&&re!==void 0?(e.state.env.set(`${w}_0`,re),e.state.env.delete(w),X=1):j.length>0&&(X=Math.max(...j)+1);for(let rt=0;rt<J.length;rt++)y(e.state.env,`${w}_${X+rt}`,se(e,J[rt]));let $e=X+J.length;y(e.state.env,`${w}__length`,String($e))}N(w),r&&Se(e,w),i&&De(e,w);continue}let T=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(T){let w=T[1],I=se(e,T[2]),L=await ue(e,w);if(L)return L;g(w),f&&vn(e,w),d&&bn(e,w),p&&Sn(e,w);let j=pe(e,w).length>0||e.state.associativeArrays?.has(w);if(Dt(e,w)){let X=x(e.state.env,w,"0"),re=parseInt(X,10)||0,$e=parseInt(await di(e,I),10)||0;I=String(re+$e),y(e.state.env,w,I)}else if(j){I=gt(e,w,I);let X=`${w}_0`,re=x(e.state.env,X);y(e.state.env,X,re+I)}else{I=gt(e,w,I);let X=x(e.state.env,w);y(e.state.env,w,X+I)}N(w),r&&Se(e,w),i&&De(e,w),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(w));continue}if(k.includes("=")){let w=k.indexOf("="),I=k.slice(0,w),L=k.slice(w+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(I)){M+=`bash: typeset: \`${I}': not a valid identifier
|
|
100
|
+
`,$=1;continue}let J=await ue(e,I);if(J)return J;if(g(I),o){if(L!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(L)){M+=`bash: declare: \`${L}': invalid variable name for name reference
|
|
101
|
+
`,$=1;continue}y(e.state.env,I,L),He(e,I),L!==""&&js(e,L)&&zs(e,I),N(I),r&&Se(e,I),i&&De(e,I);continue}if(f&&vn(e,I),d&&bn(e,I),p&&Sn(e,I),Dt(e,I)&&(L=await di(e,L)),L=gt(e,I,L),be(e,I)){let j=Fe(e,I);j&&j!==I?y(e.state.env,j,L):y(e.state.env,I,L)}else y(e.state.env,I,L);N(I),r&&Se(e,I),i&&De(e,I),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(I))}else{let w=k;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)){M+=`bash: typeset: \`${w}': not a valid identifier
|
|
102
|
+
`,$=1;continue}if(s||n?P(w):g(w),o){He(e,w);let L=x(e.state.env,w);L!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(L)?dr(e,w):L&&js(e,L)&&zs(e,w),N(w),r&&Se(e,w),i&&De(e,w);continue}if(f&&vn(e,w),d&&bn(e,w),p&&Sn(e,w),n){if(pe(e,w).length>0){M+=`bash: declare: ${w}: cannot convert indexed to associative array
|
|
103
|
+
`,$=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)}let I=Array.from(e.state.env.keys()).some(L=>L.startsWith(`${w}_`)&&!L.startsWith(`${w}__length`));!e.state.env.has(w)&&!I&&(s||n?y(e.state.env,`${w}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(w))),N(w),r&&Se(e,w),i&&De(e,w)}}return W(R,F(M),$)}async function $n(e,t){let s=!1,n=!1,r=!1,i=[];for(let a=0;a<t.length;a++){let o=t[a];if(o==="-a")s=!0;else if(o==="-A")n=!0;else if(o==="-p")r=!0;else if(o==="--"){i.push(...t.slice(a+1));break}else o.startsWith("-")||i.push(o)}if(i.length===0){let a="",o=Array.from(e.state.readonlyVars||[]).sort();for(let l of o){let c=e.state.env.get(l);if(c!==void 0){let u=H(c??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${l}="${u}"
|
|
104
|
+
`}}return G(a)}for(let a of i){let o=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(o){let f=o[1],d=o[2],p=await ue(e,f);if(p)return p;let m=ze(d);if(e.state.associativeArrays?.has(f)){let h=hs(d);for(let[v,S]of h){let E=se(e,S);y(e.state.env,`${f}_${v}`,E)}}else{let h=pe(e,f),v=0,S=e.state.env.get(f);h.length===0&&S!==void 0?(e.state.env.set(`${f}_0`,S),e.state.env.delete(f),v=1):h.length>0&&(v=Math.max(...h)+1);for(let b=0;b<m.length;b++)y(e.state.env,`${f}_${v+b}`,se(e,m[b]));let E=v+m.length;y(e.state.env,`${f}__length`,String(E))}Se(e,f);continue}let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=se(e,l[2]),p=await ue(e,f);if(p)return p;let m=x(e.state.env,f);y(e.state.env,f,m+d),Se(e,f);continue}let c=qr(a);if(c.value===void 0&&!c.isArray){Se(e,c.name);continue}let u=await Zr(e,c,{makeReadonly:!0});if(u)return u}return ft}function An(e){return e.state.directoryStack??=[],e.state.directoryStack}function Rt(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function ta(e){let t=e.split("/").filter(n=>n&&n!=="."),s=[];for(let n of t)n===".."?s.pop():s.push(n);return`/${s.join("/")}`}async function Cn(e,t){let s=An(e),n;for(let o=0;o<t.length;o++){let l=t[o];if(l==="--"){if(o+1<t.length){if(n!==void 0)return C(`bash: pushd: too many arguments
|
|
105
|
+
`,2);n=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return C(`bash: pushd: ${l}: invalid option
|
|
106
|
+
`,2);if(n!==void 0)return C(`bash: pushd: too many arguments
|
|
107
|
+
`,2);n=l}}if(n===void 0){if(s.length<2)return C(`bash: pushd: no other directory
|
|
108
|
+
`,1);let o=s[0];s[0]=s[1],s[1]=o,n=s[0]}let r;if(n.startsWith("/"))r=n;else if(n===".."){let o=e.state.cwd.split("/").filter(l=>l);o.pop(),r=`/${o.join("/")}`}else n==="."?r=e.state.cwd:n.startsWith("~")?r=x(e.state.env,"HOME","/")+n.slice(1):r=`${e.state.cwd}/${n}`;r=ta(r);try{if(!(await e.fs.stat(r)).isDirectory)return C(`bash: pushd: ${n}: Not a directory
|
|
109
|
+
`,1)}catch{return C(`bash: pushd: ${n}: No such file or directory
|
|
110
|
+
`,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=r,y(e.state.env,"PWD",r),y(e.state.env,"OLDPWD",e.state.previousDir);let i=x(e.state.env,"HOME",""),a=`${[r,...s].map(o=>Rt(o,i)).join(" ")}
|
|
111
|
+
`;return G(a)}function kn(e,t){let s=An(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?C(`bash: popd: ${a}: invalid option
|
|
112
|
+
`,2):C(`bash: popd: too many arguments
|
|
113
|
+
`,2);if(s.length===0)return C(`bash: popd: directory stack empty
|
|
114
|
+
`,1);let n=s.shift();if(!n)return C(`bash: popd: directory stack empty
|
|
115
|
+
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=n,y(e.state.env,"PWD",n),y(e.state.env,"OLDPWD",e.state.previousDir);let r=x(e.state.env,"HOME",""),i=`${[n,...s].map(a=>Rt(a,r)).join(" ")}
|
|
116
|
+
`;return G(i)}function Pn(e,t){let s=An(e),n=!1,r=!1,i=!1,a=!1;for(let u of t)if(u!=="--")if(u.startsWith("-"))for(let f of u.slice(1))if(f==="c")n=!0;else if(f==="l")r=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,a=!0;else return C(`bash: dirs: -${f}: invalid option
|
|
117
|
+
`,2);else return C(`bash: dirs: too many arguments
|
|
118
|
+
`,1);if(n)return e.state.directoryStack=[],ft;let o=[e.state.cwd,...s],l=x(e.state.env,"HOME",""),c;return a?(c=o.map((u,f)=>{let d=r?u:Rt(u,l);return` ${f} ${d}`}).join(`
|
|
119
|
+
`),c+=`
|
|
120
|
+
`):i?c=o.map(u=>r?u:Rt(u,l)).join(`
|
|
119
121
|
`)+`
|
|
120
|
-
`:
|
|
121
|
-
`,G(
|
|
122
|
+
`:c=o.map(u=>r?u:Rt(u,l)).join(" ")+`
|
|
123
|
+
`,G(c)}async function Es(e,t,s){let n=t;if(n.length>0){let o=n[0];if(o==="--")n=n.slice(1);else if(o.startsWith("-")&&o!=="-"&&o.length>1)return C(`bash: eval: ${o}: invalid option
|
|
122
124
|
eval: usage: eval [arg ...]
|
|
123
|
-
`,2)}if(n.length===0)return B();let r=n.join(" ");if(r.trim()==="")return B();let i=e.state.groupStdin,a=s??e.state.groupStdin;a!==void 0&&(e.state.groupStdin=a);try{let o=Le(r),l=await e.executeScript(o);return await Y(e,l)}catch(o){if(await ee(e,o),o instanceof Ae||o instanceof Ce||o instanceof we||o instanceof q)throw o;if(o.name==="ParseException")return
|
|
125
|
+
`,2)}if(n.length===0)return B();let r=n.join(" ");if(r.trim()==="")return B();let i=e.state.groupStdin,a=s??e.state.groupStdin;a!==void 0&&(e.state.groupStdin=a);try{let o=Le(r),l=await e.executeScript(o);return await Y(e,l)}catch(o){if(await ee(e,o),o instanceof Ae||o instanceof Ce||o instanceof we||o instanceof q)throw o;if(o.name==="ParseException")return C(`bash: eval: ${o.message}
|
|
124
126
|
`);throw o}finally{e.state.groupStdin=i}}async function _n(e,t){let s,n;if(t.length===0)s=e.state.lastExitCode;else{let r=t[0],i=Number.parseInt(r,10);r===""||Number.isNaN(i)||!/^-?\d+$/.test(r)?(n=`bash: exit: ${r}: numeric argument required
|
|
125
|
-
`,s=2):s=(i%256+256)%256}throw n&&await U(e,2,n,!0),new q(s)}function Tn(e,t){let s=!1,n=[];for(let a of t)a==="-n"?s=!0:a==="-p"||a==="--"||n.push(a);if(n.length===0&&!s){let a="",o=e.state.exportedVars??new Set,l=Array.from(o).sort();for(let
|
|
126
|
-
`}}return G(a)}if(s){for(let a of n){let o,l;if(a.includes("=")){let
|
|
127
|
-
`,i=1;continue}if(l!==void 0)if(
|
|
128
|
-
`);let s=t[0],n=t[1],r=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n),i=s.startsWith(":"),a=i?s.slice(1):s,o;if(t.length>2)o=t.slice(2);else{let h=Number.parseInt(x(e.state.env,"#","0"),10);o=[];for(let
|
|
129
|
-
`,r||y(e.state.env,n,"?"),f+1<
|
|
130
|
-
`,r||y(e.state.env,n,"?")),y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:r?2:0,stdout:
|
|
131
|
-
`,1);o=t[
|
|
132
|
-
`,1):
|
|
133
|
-
`,1);
|
|
134
|
-
`,1);let m=!1,h="";for(let
|
|
135
|
-
`,m=!0);return m?
|
|
136
|
-
`,1);let m="",h=!1,
|
|
137
|
-
`:m+=`${
|
|
138
|
-
`:(
|
|
139
|
-
`,h=!0)}return h?{exitCode:1,stdout:V(m),stderr:V(
|
|
127
|
+
`,s=2):s=(i%256+256)%256}throw n&&await U(e,2,n,!0),new q(s)}function Tn(e,t){let s=!1,n=[];for(let a of t)a==="-n"?s=!0:a==="-p"||a==="--"||n.push(a);if(n.length===0&&!s){let a="",o=e.state.exportedVars??new Set,l=Array.from(o).sort();for(let c of l){let u=e.state.env.get(c);if(u!==void 0){let f=H(u??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -x ${c}="${f}"
|
|
128
|
+
`}}return G(a)}if(s){for(let a of n){let o,l;if(a.includes("=")){let c=a.indexOf("=");o=a.slice(0,c),l=se(e,a.slice(c+1)),y(e.state.env,o,l)}else o=a;Yt(e,o)}return ft}let r="",i=0;for(let a of n){let o,l,c=!1,u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)o=u[1],l=se(e,u[2]),c=!0;else if(a.includes("=")){let f=a.indexOf("=");o=a.slice(0,f),l=se(e,a.slice(f+1))}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){r+=`bash: export: \`${a}': not a valid identifier
|
|
129
|
+
`,i=1;continue}if(l!==void 0)if(c){let f=x(e.state.env,o);y(e.state.env,o,f+l)}else y(e.state.env,o,l);else e.state.env.has(o)||y(e.state.env,o,"");De(e,o)}return W(R,F(r),i)}function $s(e,t){if(t.length<2)return C(`bash: getopts: usage: getopts optstring name [arg ...]
|
|
130
|
+
`);let s=t[0],n=t[1],r=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n),i=s.startsWith(":"),a=i?s.slice(1):s,o;if(t.length>2)o=t.slice(2);else{let h=Number.parseInt(x(e.state.env,"#","0"),10);o=[];for(let v=1;v<=h;v++)o.push(x(e.state.env,String(v))||"")}let l=Number.parseInt(x(e.state.env,"OPTIND","1"),10);l<1&&(l=1);let c=Number.parseInt(x(e.state.env,"__GETOPTS_CHARINDEX","0"),10);if(y(e.state.env,"OPTARG",""),l>o.length)return r||y(e.state.env,n,"?"),y(e.state.env,"OPTIND",String(o.length+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:r?2:1,stdout:A(),stderr:A()};let u=o[l-1];if(!u||u==="-"||!u.startsWith("-"))return r||y(e.state.env,n,"?"),{exitCode:r?2:1,stdout:A(),stderr:A()};if(u==="--")return y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),r||y(e.state.env,n,"?"),{exitCode:r?2:1,stdout:A(),stderr:A()};let f=c===0?1:c,d=u[f];if(!d)return y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),$s(e,t);let p=a.indexOf(d);if(p===-1){let h="";return i?y(e.state.env,"OPTARG",d):h=`bash: illegal option -- ${d}
|
|
131
|
+
`,r||y(e.state.env,n,"?"),f+1<u.length?(y(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),y(e.state.env,"OPTIND",String(l))):(y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0")),{exitCode:r?2:0,stdout:A(),stderr:V(h)}}if(p+1<a.length&&a[p+1]===":")if(f+1<u.length)y(e.state.env,"OPTARG",u.slice(f+1)),y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0");else{if(l>=o.length){let h="";return i?(y(e.state.env,"OPTARG",d),r||y(e.state.env,n,":")):(h=`bash: option requires an argument -- ${d}
|
|
132
|
+
`,r||y(e.state.env,n,"?")),y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:r?2:0,stdout:A(),stderr:V(h)}}y(e.state.env,"OPTARG",o[l]),y(e.state.env,"OPTIND",String(l+2)),y(e.state.env,"__GETOPTS_CHARINDEX","0")}else f+1<u.length?(y(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),y(e.state.env,"OPTIND",String(l))):(y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"));return r||y(e.state.env,n,d),{exitCode:r?2:0,stdout:A(),stderr:A()}}async function Nn(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,n=!1,r=!1,i=!1,a=!1,o="",l=[],c=0;for(;c<t.length;){let m=t[c];if(m==="--"){c++,l.push(...t.slice(c));break}if(m==="-r")s=!0,c++;else if(m==="-d")n=!0,c++;else if(m==="-l")r=!0,c++;else if(m==="-t")a=!0,c++;else if(m==="-p"){if(i=!0,c++,c>=t.length)return C(`bash: hash: -p: option requires an argument
|
|
133
|
+
`,1);o=t[c],c++}else if(m.startsWith("-")&&m.length>1){for(let h of m.slice(1))if(h==="r")s=!0;else if(h==="d")n=!0;else if(h==="l")r=!0;else if(h==="t")a=!0;else return h==="p"?C(`bash: hash: -p: option requires an argument
|
|
134
|
+
`,1):C(`bash: hash: -${h}: invalid option
|
|
135
|
+
`,1);c++}else l.push(m),c++}if(s)return e.state.hashTable.clear(),B();if(n){if(l.length===0)return C(`bash: hash: -d: option requires an argument
|
|
136
|
+
`,1);let m=!1,h="";for(let v of l)e.state.hashTable.has(v)?e.state.hashTable.delete(v):(h+=`bash: hash: ${v}: not found
|
|
137
|
+
`,m=!0);return m?C(h,1):B()}if(a){if(l.length===0)return C(`bash: hash: -t: option requires an argument
|
|
138
|
+
`,1);let m="",h=!1,v="";for(let S of l){let E=e.state.hashTable.get(S);E?l.length>1?m+=`${S} ${E}
|
|
139
|
+
`:m+=`${E}
|
|
140
|
+
`:(v+=`bash: hash: ${S}: not found
|
|
141
|
+
`,h=!0)}return h?{exitCode:1,stdout:V(m),stderr:V(v)}:G(m)}if(i){if(l.length===0)return C(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
|
|
140
142
|
`,1);let m=l[0];return e.state.hashTable.set(m,o),B()}if(l.length===0){if(e.state.hashTable.size===0)return G(`hash: hash table empty
|
|
141
|
-
`);let m="";if(r)for(let[h,
|
|
143
|
+
`);let m="";if(r)for(let[h,v]of e.state.hashTable)m+=`builtin hash -p ${v} ${h}
|
|
142
144
|
`;else{m=`hits command
|
|
143
145
|
`;for(let[,h]of e.state.hashTable)m+=` 1 ${h}
|
|
144
|
-
`}return G(m)}let
|
|
145
|
-
`,
|
|
146
|
-
`,
|
|
146
|
+
`}return G(m)}let u=!1,f="",p=x(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let m of l){if(m.includes("/")){f+=`bash: hash: ${m}: cannot use / in name
|
|
147
|
+
`,u=!0;continue}let h=!1;for(let v of p){if(!v)continue;let S=`${v}/${m}`;if(await e.fs.exists(S)){e.state.hashTable.set(m,S),h=!0;break}}h||(f+=`bash: hash: ${m}: not found
|
|
148
|
+
`,u=!0)}return u?C(f,1):B()}var hi=new Map([[":",[": [arguments]",`Null command.
|
|
147
149
|
No effect; the command does nothing.
|
|
148
150
|
Exit Status:
|
|
149
151
|
Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
|
|
@@ -488,46 +490,47 @@ eval: usage: eval [arg ...]
|
|
|
488
490
|
job specification. With no ID, waits for all known jobs.
|
|
489
491
|
Exit Status:
|
|
490
492
|
Returns the status of the last ID; fails if ID is invalid or an invalid
|
|
491
|
-
option is given.`]]]),pi=[...hi.keys()].sort();function
|
|
492
|
-
`,2)}r++}else n.push(l),r++}if(n.length===0)return na();let i="",a=!1,o="";for(let l of n){let
|
|
493
|
-
`,a=!0;continue}for(let
|
|
494
|
-
`:i+=`${
|
|
493
|
+
option is given.`]]]),pi=[...hi.keys()].sort();function xn(e,t){let s=!1,n=[],r=0;for(;r<t.length;){let l=t[r];if(l==="--"){for(r++;r<t.length;)n.push(t[r]),r++;break}if(l.startsWith("-")&&l.length>1){for(let c=1;c<l.length;c++){let u=l[c];if(u==="s")s=!0;else return C(`bash: help: -${u}: invalid option
|
|
494
|
+
`,2)}r++}else n.push(l),r++}if(n.length===0)return na();let i="",a=!1,o="";for(let l of n){let c=sa(l);if(c.length===0){o+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
|
|
495
|
+
`,a=!0;continue}for(let u of c){let f=hi.get(u);if(!f)continue;let[d,p]=f;s?i+=`${u}: ${d}
|
|
496
|
+
`:i+=`${u}: ${d}
|
|
495
497
|
${p}
|
|
496
498
|
`}}return{exitCode:a?1:0,stdout:V(i),stderr:V(o)}}function sa(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=At(`^${t}$`);return pi.filter(n=>s.test(n))}function na(){let e=[];e.push("just-bash shell builtins"),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push("");let t=36,s=pi.slice(),n=Math.ceil(s.length/2);for(let r=0;r<n;r++){let i=s[r]||"",a=s[r+n]||"",o=i.padEnd(t);e.push(a?`${o}${a}`:i)}return G(`${e.join(`
|
|
497
499
|
`)}
|
|
498
500
|
`)}var ra=`jobs: usage: jobs [-lnprs] [jobspec ...] or jobs -x command [args]
|
|
499
|
-
`;function ia(e){return{stdout:
|
|
500
|
-
${ra}`),exitCode:2}}async function On(e,t,s){if(t[0]==="-x"){let
|
|
501
|
-
`),exitCode:1};let
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
`)
|
|
508
|
-
`)
|
|
501
|
+
`;function ia(e){return{stdout:A(),stderr:V(`bash: jobs: ${e}: invalid option
|
|
502
|
+
${ra}`),exitCode:2}}async function On(e,t,s){if(t[0]==="-x"){let d=t[1];if(!d)return{stdout:A(),stderr:A(),exitCode:0};if(!s)return{stdout:A(),stderr:V(`bash: jobs: -x: command execution unavailable
|
|
503
|
+
`),exitCode:1};let p=[];for(let m of t.slice(2)){if(!m.startsWith("%")){p.push(m);continue}let h=e.processes.resolveJobSpec(m);p.push(h===void 0?m:String(h))}return s(d,p)}let n={long:!1,pidsOnly:!1,runningOnly:!1,stoppedOnly:!1,changedOnly:!1},r=0;for(;r<t.length;r++){let d=t[r];if(d==="--"){r++;break}if(!d.startsWith("-")||d==="-")break;for(let p of d.slice(1))if(p==="l")n.long=!0;else if(p==="n")n.changedOnly=!0;else if(p==="p")n.pidsOnly=!0;else if(p==="r")n.runningOnly=!0;else if(p==="s")n.stoppedOnly=!0;else return ia(`-${p}`)}let i=t.slice(r),a=d=>{let p=e.processes.resolveJobSpec(d);return p!==void 0&&e.processes.get(p)?p:void 0},o=i.length===0?void 0:new Set(i.map(a).filter(d=>d!==void 0)),l="",c="",u=0;for(let d of i)a(d)===void 0&&(c+=`bash: jobs: ${d}: no such job
|
|
504
|
+
`,u=1);let f=e.processes.listJobs(o,{changedOnly:n.changedOnly,runningOnly:n.runningOnly,stoppedOnly:n.stoppedOnly});for(let d of f){if(n.pidsOnly){l+=`${d.pid}
|
|
505
|
+
`;continue}let p=d.state==="running"?"Running ":"Done ",m=n.long?`[${d.jobNumber}]${d.marker} ${d.pid} `:`[${d.jobNumber}]${d.marker} `;l+=`${m}${p}${d.command}
|
|
506
|
+
`}return{stdout:V(l),stderr:V(c),exitCode:u}}var mi=`kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
|
|
507
|
+
`,oa=typeof process<"u"&&process.platform==="darwin",aa=oa?["HUP","INT","QUIT","ILL","TRAP","ABRT","EMT","FPE","KILL","BUS","SEGV","SYS","PIPE","ALRM","TERM","URG","STOP","TSTP","CONT","CHLD","TTIN","TTOU","IO","XCPU","XFSZ","VTALRM","PROF","WINCH","INFO","USR1","USR2"]:["HUP","INT","QUIT","ILL","TRAP","ABRT","BUS","FPE","KILL","USR1","SEGV","USR2","PIPE","ALRM","TERM","STKFLT","CHLD","CONT","STOP","TSTP","TTIN","TTOU","URG","XCPU","XFSZ","VTALRM","PROF","WINCH","IO","PWR","SYS"],la=new Set(["STOP","TSTP","TTIN","TTOU","CONT","CHLD","URG","WINCH","INFO"]);function ca(e){if(!la.has(e))return e==="KILL"?"SIGKILL":e==="INT"?"SIGINT":"SIGTERM"}var In=aa.map((e,t)=>({name:e,number:t+1,delivery:ca(e)})),ua={name:"0",number:0};function As(e){let t=e.toUpperCase().replace(/^SIG/,"");if(/^\d+$/.test(t)){let s=Number.parseInt(t,10);return s===0?ua:In.find(n=>n.number===s)}return In.find(s=>s.name===t)}function Dn(e){return{stdout:A(),stderr:V(`bash: kill: ${e.replace(/^-/,"")}: invalid signal specification
|
|
508
|
+
`),exitCode:1}}function fa(e){if(e.length===0){let s="";for(let n of In)s+=`${String(n.number).padStart(2)}) SIG${n.name} `,n.number%4===0&&(s=`${s.slice(0,-1)}
|
|
509
|
+
`);return{stdout:V(s.endsWith(`
|
|
510
|
+
`)?s:`${s}
|
|
511
|
+
`),stderr:A(),exitCode:0}}let t="";for(let s of e){let n=/^\d+$/.test(s)?String(Number.parseInt(s,10)-(Number(s)>128?128:0)):s,r=As(n);if(!r)return Dn(s);t+=/^\d+$/.test(s)?`${r.name}
|
|
509
512
|
`:`${r.number}
|
|
510
|
-
`}return{stdout:V(t),stderr:
|
|
511
|
-
`,
|
|
512
|
-
`,
|
|
513
|
-
`,
|
|
514
|
-
`);let s=
|
|
515
|
-
`)}return W(
|
|
516
|
-
`);let s=e.state.localScopes[e.state.localScopes.length-1],n="",r=0,i=!1,a=!1,o=!1,l=[];for(let
|
|
517
|
-
`}}return W(F(
|
|
518
|
-
`,r=1;continue}if(await ue(e,
|
|
519
|
-
`,r=1;continue}let
|
|
520
|
-
`,r=1;continue}y(e.state.env,
|
|
521
|
-
`,i=0,a=0,o=0,l=!1,
|
|
522
|
-
`,
|
|
523
|
-
`),1);let N=p,
|
|
524
|
-
`),1);d.push(
|
|
525
|
-
`,o="",l=-1,
|
|
526
|
-
`){T+=2,
|
|
527
|
-
`){_+=2;continue}if(w
|
|
528
|
-
`&&
|
|
529
|
-
`)&&(
|
|
530
|
-
`),1);We(e,
|
|
513
|
+
`}return{stdout:V(t),stderr:A(),exitCode:0}}function Rn(e,t){let s=As("TERM"),n=0;if(t[0]==="-l")return fa(t.slice(1));if(t[0]==="-s"||t[0]==="-n"){let l=t[1];if(!l)return{stdout:A(),stderr:V(mi),exitCode:2};let c=As(l);if(!c)return Dn(l);s=c,n=2}else if(t[0]?.startsWith("-")&&t[0]!=="--"){let l=t[0].slice(1),c=As(l);if(!c)return Dn(l);s=c,n=1}else t[0]==="--"&&(n=1);let r=t.slice(n);if(r.length===0)return{stdout:A(),stderr:V(mi),exitCode:1};let i="",a=0,o=0;for(let l of r){let c;if(l.startsWith("%")){if(c=e.processes.resolveJobSpec(l),c===void 0){i+=`bash: kill: ${l}: no such job
|
|
514
|
+
`,o++;continue}}else if(/^\d+$/.test(l)){let f=Number(l);Number.isSafeInteger(f)&&f>0&&(c=f)}if(c===void 0){i+=`bash: kill: ${l}: arguments must be process or job IDs
|
|
515
|
+
`,o++;continue}(s.number===0||s.delivery===void 0?e.processes.get(c)!==void 0:e.processes.kill(c,s.delivery,s.number))?a++:(i+=`bash: kill: (${c}) - No such process
|
|
516
|
+
`,o++)}return{stdout:A(),stderr:V(i),exitCode:a>0||o===0?0:1}}function da(e){let t=[],s="",n=0;for(let r of e){for(let i of r)i==="("?n++:i===")"&&n--;s?s+=` ${r}`:s=r,n===0&&(t.push(s),s="")}return s&&t.push(s),t}async function Ln(e,t){if(t.length===0)return C(`bash: let: expression expected
|
|
517
|
+
`);let s=da(t),n=0;for(let r of s)try{let a=Le(`(( ${r} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(n=await Q(e,o.expression.expression))}}catch(i){return C(`bash: let: ${r}: ${i.message}
|
|
518
|
+
`)}return W(R,R,n===0?1:0)}async function Mn(e,t){if(e.state.localScopes.length===0)return C(`bash: local: can only be used in a function
|
|
519
|
+
`);let s=e.state.localScopes[e.state.localScopes.length-1],n="",r=0,i=!1,a=!1,o=!1,l=[];for(let c of t)if(c==="-n")i=!0;else if(c==="-a")a=!0;else if(c==="-p")o=!0;else if(c.startsWith("-")&&!c.includes("="))for(let u of c.slice(1))u==="n"?i=!0:u==="a"?a=!0:u==="p"&&(o=!0);else l.push(c);if(l.length===0){let c="",u=Array.from(s.keys()).filter(f=>!f.includes("_")||!f.match(/_\d+$/)).filter(f=>!f.includes("__length")).sort();for(let f of u){let d=e.state.env.get(f);if(d!==void 0){let p=H(d);c+=`${f}=${p}
|
|
520
|
+
`}}return W(F(c),R,0)}for(let c of l){let u,f,d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(d){u=d[1];let S=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){n+=`bash: local: \`${c}': not a valid identifier
|
|
521
|
+
`,r=1;continue}if(await ue(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let g=`${u}_`;for(let P of e.state.env.keys())P.startsWith(g)&&!P.includes("__")&&(s.has(P)||s.set(P,e.state.env.get(P)))}let E=`${u}_`;for(let g of e.state.env.keys())g.startsWith(E)&&!g.includes("__")&&e.state.env.delete(g);let b=ze(S);for(let g=0;g<b.length;g++)y(e.state.env,`${u}_${g}`,b[g]);y(e.state.env,`${u}__length`,String(b.length)),Ke(e,u),i&&He(e,u);continue}let p=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(p){u=p[1];let S=p[2];if(await ue(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let M=`${u}_`;for(let k of e.state.env.keys())k.startsWith(M)&&!k.includes("__")&&(s.has(k)||s.set(k,e.state.env.get(k)));let $=`${u}__length`;e.state.env.has($)&&!s.has($)&&s.set($,e.state.env.get($))}let E=ze(S),b=pe(e,u),g=0,P=e.state.env.get(u);b.length===0&&P!==void 0?(e.state.env.set(`${u}_0`,P),e.state.env.delete(u),g=1):b.length>0&&(g=Math.max(...b)+1);for(let M=0;M<E.length;M++)y(e.state.env,`${u}_${g+M}`,se(e,E[M]));let N=g+E.length;y(e.state.env,`${u}__length`,String(N)),Ke(e,u),i&&He(e,u);continue}let m=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){u=m[1];let S=se(e,m[2]);await ue(e,u,"bash"),s.has(u)||s.set(u,e.state.env.get(u));let E=x(e.state.env,u);y(e.state.env,u,E+S),Ke(e,u),i&&He(e,u);continue}let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(h){u=h[1];let S=h[2],E=se(e,h[3]);if(await ue(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let P=`${u}_`;for(let M of e.state.env.keys())M.startsWith(P)&&!M.includes("__")&&(s.has(M)||s.set(M,e.state.env.get(M)));let N=`${u}__length`;e.state.env.has(N)&&!s.has(N)&&s.set(N,e.state.env.get(N))}let b;try{let P=new Z,N=le(P,S);b=await Q(e,N.expression)}catch{let P=parseInt(S,10);b=Number.isNaN(P)?0:P}y(e.state.env,`${u}_${b}`,E);let g=parseInt(x(e.state.env,`${u}__length`,"0"),10);b>=g&&y(e.state.env,`${u}__length`,String(b+1)),Ke(e,u),i&&He(e,u);continue}if(c.includes("=")){let S=c.indexOf("=");u=c.slice(0,S),f=se(e,c.slice(S+1))}else u=c;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){n+=`bash: local: \`${c}': not a valid identifier
|
|
522
|
+
`,r=1;continue}let v=s.has(u);if(f!==void 0){let S=e.state.env.get(u);if(e.state.tempEnvBindings){let E=e.state.accessedTempEnvVars?.has(u),b=e.state.mutatedTempEnvVars?.has(u);if(!E&&!b)for(let g=e.state.tempEnvBindings.length-1;g>=0;g--){let P=e.state.tempEnvBindings[g];if(P.has(u)){S=P.get(u);break}}}Jr(e,u,S)}if(!v){let S=e.state.env.get(u);if(e.state.tempEnvBindings)for(let E=e.state.tempEnvBindings.length-1;E>=0;E--){let b=e.state.tempEnvBindings[E];if(b.has(u)){S=b.get(u);break}}if(s.set(u,S),a){let E=`${u}_`;for(let g of e.state.env.keys())g.startsWith(E)&&!g.includes("__")&&(s.has(g)||s.set(g,e.state.env.get(g)));let b=`${u}__length`;e.state.env.has(b)&&!s.has(b)&&s.set(b,e.state.env.get(b))}}if(a&&f===void 0){let S=`${u}_`;for(let E of e.state.env.keys())E.startsWith(S)&&!E.includes("__")&&e.state.env.delete(E);y(e.state.env,`${u}__length`,"0")}else if(f!==void 0){if(await ue(e,u,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){n+=`bash: local: \`${f}': invalid variable name for name reference
|
|
523
|
+
`,r=1;continue}y(e.state.env,u,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(u))}else{let S=e.state.tempEnvBindings?.some(E=>E.has(u));!v&&!S&&e.state.env.delete(u)}Ke(e,u),i&&He(e,u)}return W(R,F(n),r)}async function Wn(e,t,s){let n=H(s),r=`
|
|
524
|
+
`,i=0,a=0,o=0,l=!1,c="MAPFILE",u=0;for(;u<t.length;){let b=t[u];b==="-d"&&u+1<t.length?(r=t[u+1]===""?"\0":t[u+1]||`
|
|
525
|
+
`,u+=2):b==="-n"&&u+1<t.length?(i=Number.parseInt(t[u+1],10)||0,u+=2):b==="-O"&&u+1<t.length?(a=Number.parseInt(t[u+1],10)||0,u+=2):b==="-s"&&u+1<t.length?(o=Number.parseInt(t[u+1],10)||0,u+=2):b==="-t"?(l=!0,u++):b==="-u"||b==="-C"||b==="-c"?u+=2:(b.startsWith("-")||(c=b),u++)}let f=n;!f&&e.state.groupStdin!==void 0&&(f=H(await ie(e.state.groupStdin)));let d=[],p=f,m=0,h=0,v=e.limits?.maxArrayElements??1e5;for(;p.length>0;){let b=p.indexOf(r);if(b===-1){if(p.length>0){if(h<o)h++;else if(i===0||m<i){if(a+m>=v)return W(R,F(`mapfile: array element limit exceeded (${v})
|
|
526
|
+
`),1);let N=p,M=N.indexOf("\0");M!==-1&&(N=N.substring(0,M)),d.push(N),m++}}break}let g=p.substring(0,b),P=g.indexOf("\0");if(P!==-1&&(g=g.substring(0,P)),!l&&r!=="\0"&&(g+=r),p=p.substring(b+r.length),h<o){h++;continue}if(i>0&&m>=i)break;if(a+m>=v)return W(R,F(`mapfile: array element limit exceeded (${v})
|
|
527
|
+
`),1);d.push(g),m++}a===0&&We(e,c);for(let b=0;b<d.length;b++)y(e.state.env,`${c}_${a+b}`,d[b]);let S=parseInt(x(e.state.env,`${c}__length`,"0"),10),E=a+d.length;return y(e.state.env,`${c}__length`,String(Math.max(S,E))),e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=A()),W(R,R,0)}function ha(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let n=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(n)||n<0)return null;let r=s+1,i=t.slice(r,r+n),a=r+n+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let c=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=o.slice(l+1);return{path:i,position:c,content:u}}function pa(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}async function Fn(e,t,s,n=-1){let r=H(s),i=!1,a=`
|
|
528
|
+
`,o="",l=-1,c=-1,u=null,f=-1,d=-1,p=[],m=0,h=!1,v=(_,T)=>{let w=1;for(;w<_.length;){let I=_[w];if(I==="r")i=!0,w++;else if(I==="s")w++;else{if(I==="d")return w+1<_.length?(a=_.substring(w+1),{nextArgIndex:T+1}):T+1<t.length?(a=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(I==="n"){if(w+1<_.length){let L=_.substring(w+1);return l=Number.parseInt(L,10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:T+1}}else if(T+1<t.length)return l=Number.parseInt(t[T+1],10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(I==="N"){if(w+1<_.length){let L=_.substring(w+1);return c=Number.parseInt(L,10),(Number.isNaN(c)||c<0)&&(h=!0,c=0),{nextArgIndex:T+1}}else if(T+1<t.length)return c=Number.parseInt(t[T+1],10),(Number.isNaN(c)||c<0)&&(h=!0,c=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else{if(I==="a")return w+1<_.length?(u=_.substring(w+1),{nextArgIndex:T+1}):T+1<t.length?(u=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(I==="p")return w+1<_.length?(o=_.substring(w+1),{nextArgIndex:T+1}):T+1<t.length?(o=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(I==="u"){if(w+1<_.length){let L=_.substring(w+1);return f=Number.parseInt(L,10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:T+1}}else if(T+1<t.length)return f=Number.parseInt(t[T+1],10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(I==="t"){if(w+1<_.length){let L=_.substring(w+1);return d=Number.parseFloat(L),Number.isNaN(d)&&(d=0),{nextArgIndex:T+1}}else if(T+1<t.length)return d=Number.parseFloat(t[T+1]),Number.isNaN(d)&&(d=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(I==="e"||I==="i"||I==="P"){if(I==="i"&&T+1<t.length)return{nextArgIndex:T+2};w++}else w++}}}return{nextArgIndex:T+1}};for(;m<t.length;){let _=t[m];if(_.startsWith("-")&&_.length>1&&_!=="--"){let T=v(_,m);if(T.nextArgIndex===-1)return{stdout:A(),stderr:A(),exitCode:2};if(T.nextArgIndex===-2)return{stdout:A(),stderr:A(),exitCode:1};m=T.nextArgIndex}else if(_==="--")for(m++;m<t.length;)p.push(t[m]),m++;else p.push(_),m++}if(h)return W(R,R,1);if(p.length===0&&u===null&&p.push("REPLY"),d===0){if(u)We(e,u);else{for(let _ of p)y(e.state.env,_,"");p.length===0&&y(e.state.env,"REPLY","")}return W(R,R,0)}if(d<0&&d!==-1)return W(R,R,1);let S=r;f>=0?e.state.fileDescriptors?S=e.state.fileDescriptors.get(f)||"":S="":!S&&e.state.groupStdin!==void 0&&(S=H(await ie(e.state.groupStdin)));let E=a===""?"\0":a,b="",g=0,P=!0,N=_=>{if(f>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(f,S.substring(_));else if(n>=0&&e.state.fileDescriptors){let T=e.state.fileDescriptors.get(n);if(T?.startsWith("__rw__:")){let w=ha(T);if(w){let I=w.position+_;e.state.fileDescriptors.set(n,pa(w.path,I,w.content))}}}else e.state.groupStdin!==void 0&&!r&&(e.state.groupStdin=he(F(S.substring(_))))};if(c>=0){let _=Math.min(c,S.length);b=S.substring(0,_),g=_,P=_>=c,N(g);let T=p[0]||"REPLY";y(e.state.env,T,b);for(let w=1;w<p.length;w++)y(e.state.env,p[w],"");return W(R,R,P?0:1)}else if(l>=0){let _=0,T=0,w=!1;for(;T<S.length&&_<l;){let I=S[T];if(I===E){g=T+1,w=!0;break}if(!i&&I==="\\"&&T+1<S.length){let L=S[T+1];if(L===E&&E===`
|
|
529
|
+
`){T+=2,g=T;continue}if(L===E){T+=2,_++,b+=L,g=T;continue}b+=L,T+=2,_++,g=T}else b+=I,T++,_++,g=T}P=_>=l||w,N(g)}else{g=0;let _=0;for(;_<S.length;){let T=S[_];if(T===E){g=_+E.length,P=!0;break}if(!i&&T==="\\"&&_+1<S.length){let w=S[_+1];if(w===`
|
|
530
|
+
`){_+=2;continue}if(w===E){b+=w,_+=2;continue}b+=T,b+=w,_+=2;continue}b+=T,_++}if(_>=S.length&&(P=!1,g=_,b.length===0&&S.length===0)){for(let T of p)y(e.state.env,T,"");return u&&We(e,u),W(R,R,1)}N(g)}E===`
|
|
531
|
+
`&&b.endsWith(`
|
|
532
|
+
`)&&(b=b.slice(0,-1));let M=_=>i?_:_.replace(/\\(.)/g,"$1");if(p.length===1&&p[0]==="REPLY")return y(e.state.env,"REPLY",M(b)),W(R,R,P?0:1);let $=cr(e.state.env);if(u){let{words:_}=Vs(b,$,void 0,i),T=e.limits?.maxArrayElements??1e5;if(_.length>T)return W(R,F(`read: array element limit exceeded (${T})
|
|
533
|
+
`),1);We(e,u);for(let w=0;w<_.length;w++)y(e.state.env,`${u}_${w}`,M(_[w]));return W(R,R,P?0:1)}let k=p.length,{words:O,wordStarts:D}=Vs(b,$,k,i);for(let _=0;_<p.length;_++){let T=p[_];if(_<p.length-1)y(e.state.env,T,M(O[_]??""));else if(_<D.length){let w=b.substring(D[_]);w=ur(w,$,i),w=M(w),y(e.state.env,T,w)}else y(e.state.env,T,"")}return W(R,R,P?0:1)}function Vn(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return C("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let n=t[0],r=Number.parseInt(n,10);if(n===""||Number.isNaN(r)||!/^-?\d+$/.test(n))return C(`bash: return: ${n}: numeric argument required
|
|
531
534
|
`,2);s=(r%256+256)%256}throw new we(s)}var Cs=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
532
535
|
Options:
|
|
533
536
|
-e Exit immediately if a command exits with non-zero status
|
|
@@ -544,75 +547,75 @@ Options:
|
|
|
544
547
|
+o pipefail Disable pipefail
|
|
545
548
|
-o xtrace Same as -x
|
|
546
549
|
+o xtrace Disable xtrace
|
|
547
|
-
`,gi=new Map([["e","errexit"],["u","nounset"],["x","xtrace"],["v","verbose"],["f","noglob"],["C","noclobber"],["a","allexport"],["n","noexec"],["h",null],["b",null],["m",null],["B",null],["H",null],["P",null],["T",null],["E",null],["p",null]]),yi=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["noclobber","noclobber"],["noglob","noglob"],["allexport","allexport"],["noexec","noexec"],["posix","posix"],["vi","vi"],["emacs","emacs"],["notify",null],["monitor",null],["braceexpand",null],["histexpand",null],["physical",null],["functrace",null],["errtrace",null],["privileged",null],["hashall",null],["ignoreeof",null],["interactive-comments",null],["keyword",null],["onecmd",null]]),wi=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],vi=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function bi(e,t,s){t!==null&&(s&&(t==="vi"?e.state.options.emacs=!1:t==="emacs"&&(e.state.options.vi=!1)),e.state.options[t]=s,ut(e))}function
|
|
550
|
+
`,gi=new Map([["e","errexit"],["u","nounset"],["x","xtrace"],["v","verbose"],["f","noglob"],["C","noclobber"],["a","allexport"],["n","noexec"],["h",null],["b",null],["m",null],["B",null],["H",null],["P",null],["T",null],["E",null],["p",null]]),yi=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["noclobber","noclobber"],["noglob","noglob"],["allexport","allexport"],["noexec","noexec"],["posix","posix"],["vi","vi"],["emacs","emacs"],["notify",null],["monitor",null],["braceexpand",null],["histexpand",null],["physical",null],["functrace",null],["errtrace",null],["privileged",null],["hashall",null],["ignoreeof",null],["interactive-comments",null],["keyword",null],["onecmd",null]]),wi=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],vi=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function bi(e,t,s){t!==null&&(s&&(t==="vi"?e.state.options.emacs=!1:t==="emacs"&&(e.state.options.vi=!1)),e.state.options[t]=s,ut(e))}function ma(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function ga(e,t){let s=pe(e,t);if(s.length===0)return`${t}=()`;let n=s.map(r=>{let i=x(e.state.env,`${t}_${r}`,"");return`[${r}]=${nt(i)}`});return`${t}=(${n.join(" ")})`}function ya(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function wa(e,t){let s=Je(e,t);if(s.length===0)return`${t}=()`;let n=s.map(r=>{let i=x(e.state.env,`${t}_${r}`,"");return`[${ya(r)}]=${nt(i)}`});return`${t}=(${n.join(" ")} )`}function va(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let n of e.state.env.keys()){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(r){let i=r[1];s.has(i)||t.add(i)}}return t}function ba(e){return e.state.associativeArrays??new Set}async function jn(e,t){if(t.includes("--help"))return G(Cs);if(t.length===0){let n=va(e),r=ba(e),i=l=>{for(let c of r){let u=`${c}_`,f=`${c}__length`;if(l!==f&&l.startsWith(u)){if(l.slice(u.length).startsWith("_length"))continue;return!0}}return!1},a=[];for(let[l,c]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)||n.has(l)||r.has(l))continue;let u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(u&&n.has(u[1]))continue;let f=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&n.has(f[1])||i(l)||f&&r.has(f[1])||a.push([l,H(c)])}let o=[];for(let[l,c]of a.sort(([u],[f])=>u<f?-1:u>f?1:0))o.push(`${l}=${Ss(c)}`);for(let l of[...n].sort((c,u)=>c<u?-1:c>u?1:0))o.push(ga(e,l));for(let l of[...r].sort((c,u)=>c<u?-1:c>u?1:0))o.push(wa(e,l));return o.sort((l,c)=>{let u=l.split("=")[0],f=c.split("=")[0];return u<f?-1:u>f?1:0}),G(o.length>0?`${o.join(`
|
|
548
551
|
`)}
|
|
549
|
-
`:"")}let s=0;for(;s<t.length;){let n=t[s];if((n==="-o"||n==="+o")&&
|
|
550
|
-
${Cs}`;if(e.state.options.posix)throw await U(e,2,i,!0),new ve(1);return
|
|
552
|
+
`:"")}let s=0;for(;s<t.length;){let n=t[s];if((n==="-o"||n==="+o")&&ma(t,s)){let r=t[s+1];if(!yi.has(r)){let i=`bash: set: ${r}: invalid option name
|
|
553
|
+
${Cs}`;if(e.state.options.posix)throw await U(e,2,i,!0),new ve(1);return C(i)}bi(e,yi.get(r)??null,n==="-o"),s+=2;continue}if(n==="-o"){let r=wi.map(o=>`${o.padEnd(16)}${e.state.options[o]?"on":"off"}`),i=vi.map(o=>`${o.padEnd(16)}off`),a=[...r,...i].sort();return G(`${a.join(`
|
|
551
554
|
`)}
|
|
552
555
|
`)}if(n==="+o"){let r=wi.map(o=>`set ${e.state.options[o]?"-o":"+o"} ${o}`),i=vi.map(o=>`set +o ${o}`),a=[...r,...i].sort();return G(`${a.join(`
|
|
553
556
|
`)}
|
|
554
557
|
`)}if(n.length>1&&(n[0]==="-"||n[0]==="+")&&n[1]!=="-"){let r=n[0]==="-";for(let i=1;i<n.length;i++){let a=n[i];if(!gi.has(a)){let o=`bash: set: ${n[0]}${a}: invalid option
|
|
555
|
-
${Cs}`;if(e.state.options.posix)throw await U(e,2,o,!0),new ve(1);return
|
|
556
|
-
${Cs}`;if(e.state.options.posix)throw await U(e,2,r,!0),new ve(1);return
|
|
557
|
-
`;if(e.state.options.posix)throw await U(e,2,o,!0),new ve(1);return
|
|
558
|
-
`;if(e.state.options.posix)throw await U(e,2,a,!0),new ve(1);return
|
|
559
|
-
`),2);let n=s[0],r=null,i=null;if(n.includes("/")){let
|
|
560
|
-
`);let a=new Map;if(s.length>1){for(let
|
|
561
|
-
`);throw
|
|
562
|
-
`,r=1;continue}let
|
|
563
|
-
`,r=1;continue}if(
|
|
564
|
-
`,r=1;continue}let N=
|
|
565
|
-
`,r=1;continue}let
|
|
566
|
-
`,r=1;continue}let
|
|
567
|
-
`,r=1;continue}let f=ht(e,
|
|
568
|
-
`,r=1;continue}let m=await Ei(e,
|
|
569
|
-
`,r=1;continue}if(m===null)continue;if(m<0){let h=
|
|
570
|
-
`,r=1;continue}let
|
|
571
|
-
`,r=1;continue}let
|
|
572
|
-
`,r=1;continue}let o=i;if(be(e,i)){let
|
|
573
|
-
`,r=1;continue}let l=ht(e,o);if(l!==void 0&&l!==e.state.callDepth)$i(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(l!==void 0){let
|
|
574
|
-
`;async function qn(e,t){let s=t.find(
|
|
575
|
-
${
|
|
576
|
-
`:`bash: wait: pid ${
|
|
577
|
-
`,
|
|
578
|
-
`)}}}l++}else break}for(;l<t.length;)o.push(t[l]),l++;if(a)return
|
|
558
|
+
${Cs}`;if(e.state.options.posix)throw await U(e,2,o,!0),new ve(1);return C(o)}bi(e,gi.get(a)??null,r)}s++;continue}if(n==="--")return zn(e,t.slice(s+1)),B();if(n==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,ut(e),s+1<t.length)return zn(e,t.slice(s+1)),B();s++;continue}if(n==="+"){s++;continue}if(n.startsWith("-")||n.startsWith("+")){let r=`bash: set: ${n}: invalid option
|
|
559
|
+
${Cs}`;if(e.state.options.posix)throw await U(e,2,r,!0),new ve(1);return C(r)}return zn(e,t.slice(s)),B()}return B()}function zn(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let n=0;n<t.length;n++)y(e.state.env,String(n+1),t[n]);y(e.state.env,"#",String(t.length)),y(e.state.env,"@",t.join(" ")),y(e.state.env,"*",t.join(" "))}async function Bn(e,t){let s=1;if(t.length>0){let a=Number.parseInt(t[0],10);if(Number.isNaN(a)||a<0){let o=`bash: shift: ${t[0]}: numeric argument required
|
|
560
|
+
`;if(e.state.options.posix)throw await U(e,2,o,!0),new ve(1);return C(o)}s=a}let n=Number.parseInt(x(e.state.env,"#","0"),10);if(s>n){let a=`bash: shift: shift count out of range
|
|
561
|
+
`;if(e.state.options.posix)throw await U(e,2,a,!0),new ve(1);return C(a)}if(s===0)return B();let r=[];for(let a=1;a<=n;a++)r.push(x(e.state.env,String(a))||"");let i=r.slice(s);for(let a=1;a<=n;a++)e.state.env.delete(String(a));for(let a=0;a<i.length;a++)y(e.state.env,String(a+1),i[a]);return y(e.state.env,"#",String(i.length)),y(e.state.env,"@",i.join(" ")),B()}async function Hn(e,t){let s=t;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return W(R,F(`bash: source: filename argument required
|
|
562
|
+
`),2);let n=s[0],r=null,i=null;if(n.includes("/")){let c=e.fs.resolvePath(e.state.cwd,n);try{i=await e.fs.readFileText(c),r=c}catch{}}else{let u=x(e.state.env,"PATH","").split(":").filter(f=>f);for(let f of u){let d=e.fs.resolvePath(e.state.cwd,`${f}/${n}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFileText(d),r=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,n);try{i=await e.fs.readFileText(f),r=f}catch{}}}if(i===null)return C(`bash: ${n}: No such file or directory
|
|
563
|
+
`);let a=new Map;if(s.length>1){for(let u=1;u<=9;u++)a.set(String(u),x(e.state.env,String(u)));a.set("#",x(e.state.env,"#")),a.set("@",x(e.state.env,"@"));let c=s.slice(1);y(e.state.env,"#",String(c.length)),y(e.state.env,"@",c.join(" "));for(let u=0;u<c.length&&u<9;u++)y(e.state.env,String(u+1),c[u]);for(let u=c.length+1;u<=9;u++)e.state.env.delete(String(u))}let o=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=o,s.length>1)for(let[c,u]of a)u===void 0?e.state.env.delete(c):y(e.state.env,c,u)};e.state.sourceDepth++,e.state.currentSource=n;try{let c=Le(i),u=await e.executeScript(c),f=await Y(e,u);return l(),f}catch(c){if(l(),await ee(e,c),c instanceof q)throw c;if(c instanceof we)return W(R,R,c.exitCode);if(c.name==="ParseException")return C(`bash: ${n}: ${c.message}
|
|
564
|
+
`);throw c}}function Si(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Sa(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function Ei(e,t){if(Sa(t))return null;try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function $i(e,t){if(e.state.localVarStack?.has(t)){let n=ms(e,t);if(n){n.value===void 0?e.state.env.delete(t):e.state.env.set(t,n.value);let r=e.state.localVarStack?.get(t);if(!r||r.length===0)ps(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,n.scopeIndex),Un(e,t);else{let i=r[r.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,i.scopeIndex+1)}return!0}return e.state.env.delete(t),ps(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let n=e.state.localScopes.length-1;n>=0;n--){let r=e.state.localScopes[n];if(r.has(t)){let i=r.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),r.delete(t);let a=!1;for(let o=n-1;o>=0;o--)if(e.state.localScopes[o].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,o+1),a=!0;break}return a||ps(e,t),!0}}return!1}function Un(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let n=e.state.tempEnvBindings[s];if(n.has(t)){let r=n.get(t);return r===void 0?e.state.env.delete(t):e.state.env.set(t,r),n.delete(t),!0}}return!1}async function Ai(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),r=new Z().parseWordFromString(s,!0,!1);return z(e,r)}if(t.includes("$")){let n=new Z().parseWordFromString(t,!1,!1);return z(e,n)}return t}async function Gn(e,t){let s="both",n="",r=0;for(let i of t){if(i==="-v"){s="variable";continue}if(i==="-f"){s="function";continue}if(s==="function"){e.state.functions.delete(i);continue}if(s==="variable"){let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let d=c[1],p=c[2];if(p==="@"||p==="*"){let b=Ie(e,d);for(let[g]of b)e.state.env.delete(`${d}_${g}`);e.state.env.delete(d);continue}let m=e.state.associativeArrays?.has(d);if(m){let b=await Ai(e,p);e.state.env.delete(`${d}_${b}`);continue}let h=Bs(e,d),v=e.state.declaredVars?.has(d);if((e.state.env.has(d)||v)&&!h&&!m){n+=`bash: unset: ${d}: not an array variable
|
|
565
|
+
`,r=1;continue}let E=await Ei(e,p);if(E===null&&h){n+=`bash: unset: ${p}: not a valid identifier
|
|
566
|
+
`,r=1;continue}if(E===null)continue;if(E<0){let b=Ie(e,d),g=b.length,P=e.state.currentLine;if(g===0){n+=`bash: line ${P}: unset: [${E}]: bad array subscript
|
|
567
|
+
`,r=1;continue}let N=g+E;if(N<0){n+=`bash: line ${P}: unset: [${E}]: bad array subscript
|
|
568
|
+
`,r=1;continue}let M=b[N][0];e.state.env.delete(`${d}_${M}`);continue}e.state.env.delete(`${d}_${E}`);continue}if(!Si(i)){n+=`bash: unset: \`${i}': not a valid identifier
|
|
569
|
+
`,r=1;continue}let u=i;if(be(e,i)){let d=Fe(e,i);d&&d!==i&&(u=d)}if(tt(e,u)){n+=`bash: unset: ${u}: cannot unset: readonly variable
|
|
570
|
+
`,r=1;continue}let f=ht(e,u);if(f!==void 0&&f!==e.state.callDepth)$i(e,u);else if(e.state.fullyUnsetLocals?.has(u))e.state.env.delete(u);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(u),p=e.state.mutatedTempEnvVars?.has(u);if((d||p)&&e.state.localVarStack?.has(u)){let m=ms(e,u);m?m.value===void 0?e.state.env.delete(u):e.state.env.set(u,m.value):e.state.env.delete(u)}else e.state.env.delete(u)}else Un(e,u)||e.state.env.delete(u);e.state.exportedVars?.delete(u);continue}let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let c=a[1],u=a[2];if(u==="@"||u==="*"){let h=Ie(e,c);for(let[v]of h)e.state.env.delete(`${c}_${v}`);e.state.env.delete(c);continue}let f=e.state.associativeArrays?.has(c);if(f){let h=await Ai(e,u);e.state.env.delete(`${c}_${h}`);continue}let d=Bs(e,c);if(e.state.env.has(c)&&!d&&!f){n+=`bash: unset: ${c}: not an array variable
|
|
571
|
+
`,r=1;continue}let m=await Ei(e,u);if(m===null&&d){n+=`bash: unset: ${u}: not a valid identifier
|
|
572
|
+
`,r=1;continue}if(m===null)continue;if(m<0){let h=Ie(e,c),v=h.length,S=e.state.currentLine;if(v===0){n+=`bash: line ${S}: unset: [${m}]: bad array subscript
|
|
573
|
+
`,r=1;continue}let E=v+m;if(E<0){n+=`bash: line ${S}: unset: [${m}]: bad array subscript
|
|
574
|
+
`,r=1;continue}let b=h[E][0];e.state.env.delete(`${c}_${b}`);continue}e.state.env.delete(`${c}_${m}`);continue}if(!Si(i)){n+=`bash: unset: \`${i}': not a valid identifier
|
|
575
|
+
`,r=1;continue}let o=i;if(be(e,i)){let c=Fe(e,i);c&&c!==i&&(o=c)}if(tt(e,o)){n+=`bash: unset: ${o}: cannot unset: readonly variable
|
|
576
|
+
`,r=1;continue}let l=ht(e,o);if(l!==void 0&&l!==e.state.callDepth)$i(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(l!==void 0){let c=e.state.accessedTempEnvVars?.has(o),u=e.state.mutatedTempEnvVars?.has(o);if((c||u)&&e.state.localVarStack?.has(o)){let f=ms(e,o);f?f.value===void 0?e.state.env.delete(o):e.state.env.set(o,f.value):e.state.env.delete(o)}else e.state.env.delete(o)}else Un(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(i)}return W(R,F(n),r)}var Ea=`wait: usage: wait [id ...]
|
|
577
|
+
`;async function qn(e,t){let s=t.indexOf("--"),n=s===-1?t:t.slice(s+1),i=(s===-1?t:t.slice(0,s)).find(l=>l.startsWith("-"));if(i)return{stdout:A(),stderr:V(`bash: wait: ${i}: invalid option
|
|
578
|
+
${Ea}`),exitCode:2};if(t=n,Qe(e.signal),t.length===0){let l,c=new Promise((u,f)=>{l=()=>f(new me(e.signal?.reason)),e.signal?.addEventListener("abort",l,{once:!0})});try{let u=await(e.signal?Promise.race([e.processes.waitForLineage(e.lineageId),c]):e.processes.waitForLineage(e.lineageId));return{stdout:A(),stderr:A(),exitCode:u}}finally{l&&e.signal?.removeEventListener("abort",l)}}let a=0,o="";for(let l of t){Qe(e.signal);let c=l.startsWith("%")?e.processes.resolveJobSpec(l):/^\d+$/.test(l)?Number(l):void 0;if(c===void 0||!Number.isSafeInteger(c)||!e.processes.canWait(c)){o+=l.startsWith("%")?`bash: wait: ${l}: no such job
|
|
579
|
+
`:`bash: wait: pid ${l} is not a child of this shell
|
|
580
|
+
`,a=127;continue}let u,f=new Promise((d,p)=>{u=()=>p(new me(e.signal?.reason)),e.signal?.addEventListener("abort",u,{once:!0})});try{a=await(e.signal?Promise.race([e.processes.wait(c),f]):e.processes.wait(c))}finally{u&&e.signal?.removeEventListener("abort",u)}}return{stdout:A(),stderr:V(o),exitCode:a}}var Zn=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],$a=["autocd","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","execfail","extdebug","extquote","force_fignore","globasciiranges","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath"];function ks(e){return Zn.includes(e)}function Aa(e){return $a.includes(e)}function Ci(e,t){let s=!1,n=!1,r=!1,i=!1,a=!1,o=[],l=0;for(;l<t.length;){let d=t[l];if(d==="--"){l++;break}if(d.startsWith("-")&&d.length>1){for(let p=1;p<d.length;p++){let m=d[p];switch(m){case"s":s=!0;break;case"u":n=!0;break;case"p":r=!0;break;case"q":i=!0;break;case"o":a=!0;break;default:return{exitCode:2,stdout:A(),stderr:V(`shopt: -${m}: invalid option
|
|
581
|
+
`)}}}l++}else break}for(;l<t.length;)o.push(t[l]),l++;if(a)return Ca(e,o,s,n,r,i);if(s&&n)return{exitCode:1,stdout:A(),stderr:V(`shopt: cannot set and unset shell options simultaneously
|
|
579
582
|
`)};if(o.length===0){if(s||n){let p=[];for(let m of Zn){let h=e.state.shoptOptions[m];s&&h?p.push(r?`shopt -s ${m}`:`${m} on`):n&&!h&&p.push(r?`shopt -u ${m}`:`${m} off`)}return{exitCode:0,stdout:p.length>0?V(`${p.join(`
|
|
580
583
|
`)}
|
|
581
|
-
`):
|
|
584
|
+
`):A(),stderr:A()}}let d=[];for(let p of Zn){let m=e.state.shoptOptions[p];d.push(r?`shopt ${m?"-s":"-u"} ${p}`:`${p} ${m?"on":"off"}`)}return{exitCode:0,stdout:V(`${d.join(`
|
|
582
585
|
`)}
|
|
583
|
-
`),stderr:
|
|
584
|
-
`,
|
|
586
|
+
`),stderr:A()}}let c=!1,u="",f=[];for(let d of o){if(!ks(d)&&!Aa(d)){u+=`shopt: ${d}: invalid shell option name
|
|
587
|
+
`,c=!0;continue}if(s)ks(d)&&(e.state.shoptOptions[d]=!0,Zs(e));else if(n)ks(d)&&(e.state.shoptOptions[d]=!1,Zs(e));else if(ks(d)){let p=e.state.shoptOptions[d];i?p||(c=!0):r?(f.push(`shopt ${p?"-s":"-u"} ${d}`),p||(c=!0)):(f.push(`${d} ${p?"on":"off"}`),p||(c=!0))}else i?c=!0:r?(f.push(`shopt -u ${d}`),c=!0):(f.push(`${d} off`),c=!0)}return{exitCode:c?1:0,stdout:f.length>0?V(`${f.join(`
|
|
585
588
|
`)}
|
|
586
|
-
`):
|
|
589
|
+
`):A(),stderr:V(u)}}function Ca(e,t,s,n,r,i){let a=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),o=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],l=[...a.keys(),...o].sort();if(t.length===0){let d=[];for(let p of l){let m=o.includes(p),h=a.get(p),v=m||!h?!1:e.state.options[h];s&&!v||n&&v||d.push(r?`set ${v?"-o":"+o"} ${p}`:`${p} ${v?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?V(`${d.join(`
|
|
587
590
|
`)}
|
|
588
|
-
`):
|
|
589
|
-
`,
|
|
591
|
+
`):A(),stderr:A()}}let c=!1,u="",f=[];for(let d of t){let p=a.has(d),m=o.includes(d);if(!p&&!m){u+=`shopt: ${d}: invalid option name
|
|
592
|
+
`,c=!0;continue}if(m){s||n||(i?c=!0:r?(f.push(`set +o ${d}`),c=!0):(f.push(`${d} off`),c=!0));continue}let h=a.get(d);if(h)if(s)h==="vi"?e.state.options.emacs=!1:h==="emacs"&&(e.state.options.vi=!1),e.state.options[h]=!0,ut(e);else if(n)e.state.options[h]=!1,ut(e);else{let v=e.state.options[h];i?v||(c=!0):r?(f.push(`set ${v?"-o":"+o"} ${d}`),v||(c=!0)):(f.push(`${d} ${v?"on":"off"}`),v||(c=!0))}}return{exitCode:c?1:0,stdout:f.length>0?V(`${f.join(`
|
|
590
593
|
`)}
|
|
591
|
-
`):
|
|
592
|
-
`;p=!0,
|
|
593
|
-
`,p=!0,
|
|
594
|
-
`;else{let N=e.state.functions.get(h),
|
|
595
|
-
`;
|
|
596
|
-
`:
|
|
597
|
-
`),
|
|
598
|
-
`:
|
|
599
|
-
`),
|
|
600
|
-
`;else{let N=e.state.functions.get(h),
|
|
601
|
-
`;
|
|
602
|
-
`:
|
|
603
|
-
`),
|
|
604
|
-
`:r?
|
|
605
|
-
`:
|
|
606
|
-
`,p=!0,
|
|
607
|
-
`:r?
|
|
608
|
-
`:
|
|
609
|
-
`,p=!0,
|
|
610
|
-
`)}}}return i?d=m&&!p?1:0:d=m?1:0,W(F(
|
|
594
|
+
`):A(),stderr:V(u)}}async function ki(e,t,s){if(t.includes("/")){let a=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(a))return{error:"not_found",path:a};let o=a.split("/").pop()||t,l=e.commands.get(o);try{let c=await e.fs.stat(a);return c.isDirectory?{error:"permission_denied",path:a}:l?{cmd:l,path:a}:(c.mode&73)!==0?{script:!0,path:a}:{error:"permission_denied",path:a}}catch{return{error:"not_found",path:a}}}if(!s&&e.state.hashTable){let a=e.state.hashTable.get(t);if(a)if(await e.fs.exists(a)){let o=e.commands.get(t);if(o)return{cmd:o,path:a};try{let l=await e.fs.stat(a);if(!l.isDirectory&&(l.mode&73)!==0)return{script:!0,path:a}}catch{}}else e.state.hashTable.delete(t)}let r=(s??x(e.state.env,"PATH","/usr/bin:/bin")).split(":");for(let a of r){if(!a)continue;let l=`${a.startsWith("/")?a:e.fs.resolvePath(e.state.cwd,a)}/${t}`;if(await e.fs.exists(l))try{let c=await e.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=e.commands.get(t),d=a==="/bin"||a==="/usr/bin";if(f&&d)return{cmd:f,path:l};if(u){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await e.fs.exists("/usr/bin")){let a=e.commands.get(t);if(a)return{cmd:a,path:`/usr/bin/${t}`}}return null}async function Ps(e,t){let s=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let a=await e.fs.stat(i);a.isDirectory||(a.mode&73)!==0&&s.push(t)}catch{}return s}let r=x(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let i of r){if(!i)continue;let o=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(o)){try{if((await e.fs.stat(o)).isDirectory)continue}catch{continue}s.push(i.startsWith("/")?o:`${i}/${t}`)}}return s}async function Ni(e,t,s,n){let r=!1,i=!1,a=!1,o=!1,l=!1,c=[];for(let h of t)if(h.startsWith("-")&&h.length>1)for(let v of h.slice(1))v==="t"?r=!0:v==="p"?i=!0:v==="P"?a=!0:v==="a"?o=!0:v==="f"&&(l=!0);else c.push(h);let u="",f="",d=0,p=!1,m=!1;for(let h of c){let v=!1;if(a){if(o){let N=await n(h);if(N.length>0){for(let M of N)u+=`${M}
|
|
595
|
+
`;p=!0,v=!0}}else{let N=await s(h);N&&(u+=`${N}
|
|
596
|
+
`,p=!0,v=!0)}v||(m=!0);continue}let S=!l&&e.state.functions.has(h);if(o&&S){if(!i)if(r)u+=`function
|
|
597
|
+
`;else{let N=e.state.functions.get(h),M=N?Pi(h,N):`${h} is a function
|
|
598
|
+
`;u+=M}v=!0}let E=e.state.env.get(`BASH_ALIAS_${h}`);if(E!==void 0&&(o||!v)&&(i||(r?u+=`alias
|
|
599
|
+
`:u+=`${h} is aliased to \`${H(E)}'
|
|
600
|
+
`),v=!0,!o)||sn.has(h)&&(o||!v)&&(i||(r?u+=`keyword
|
|
601
|
+
`:u+=`${h} is a shell keyword
|
|
602
|
+
`),v=!0,!o))continue;if(!o&&S&&!v){if(!i)if(r)u+=`function
|
|
603
|
+
`;else{let N=e.state.functions.get(h),M=N?Pi(h,N):`${h} is a function
|
|
604
|
+
`;u+=M}v=!0;continue}if(!(Ge.has(h)&&(o||!v)&&(i||(r?u+=`builtin
|
|
605
|
+
`:u+=`${h} is a shell builtin
|
|
606
|
+
`),v=!0,!o))){if(o){let N=await n(h);for(let M of N)i?u+=`${M}
|
|
607
|
+
`:r?u+=`file
|
|
608
|
+
`:u+=`${h} is ${M}
|
|
609
|
+
`,p=!0,v=!0}else if(!v){let N=await s(h);N&&(i?u+=`${N}
|
|
610
|
+
`:r?u+=`file
|
|
611
|
+
`:u+=`${h} is ${N}
|
|
612
|
+
`,p=!0,v=!0)}if(!v&&(m=!0,!r&&!i)){let N=!0;if(h.includes("/")){let M=e.fs.resolvePath(e.state.cwd,h);await e.fs.exists(M)&&(N=!1)}N&&(f+=`bash: type: ${h}: not found
|
|
613
|
+
`)}}}return i?d=m&&!p?1:0:d=m?1:0,W(F(u),F(f),d)}function Pi(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(r=>Lt(r)).join("; "):s=Lt(t.body),`${e} is a function
|
|
611
614
|
${e} ()
|
|
612
615
|
{
|
|
613
616
|
${s}
|
|
614
617
|
}
|
|
615
|
-
`}function
|
|
618
|
+
`}function Lt(e){if(Array.isArray(e))return e.map(t=>Lt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let n=e.pipelines[s];t.push(ka(n)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(_i(t.name));for(let n of t.args)s.push(_i(n));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(n=>Lt(n)).join("; ")}; }`:"..."}function ka(e){let t=e.commands.map(s=>Lt(s));return(e.negated?"! ":"")+t.join(" | ")}function _i(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(n=>Ti(n)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=Ti(s);return t}function Ti(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function xi(e,t,s,n){let r="",i="",a=0;for(let o of t){if(!o){a=1;continue}let l=e.state.env.get(`BASH_ALIAS_${o}`);if(l!==void 0)n?r+=`${o} is an alias for "${H(l)}"
|
|
616
619
|
`:r+=`alias ${o}='${H(l)}'
|
|
617
620
|
`;else if(sn.has(o))n?r+=`${o} is a shell keyword
|
|
618
621
|
`:r+=`${o}
|
|
@@ -620,88 +623,85 @@ ${e} ()
|
|
|
620
623
|
`:r+=`${o}
|
|
621
624
|
`;else if(e.state.functions.has(o))n?r+=`${o} is a function
|
|
622
625
|
`:r+=`${o}
|
|
623
|
-
`;else if(o.includes("/")){let
|
|
626
|
+
`;else if(o.includes("/")){let c=e.fs.resolvePath(e.state.cwd,o),u=!1;if(await e.fs.exists(c))try{let f=await e.fs.stat(c);f.isDirectory||(f.mode&73)!==0&&(n?r+=`${o} is ${o}
|
|
624
627
|
`:r+=`${o}
|
|
625
|
-
`,
|
|
626
|
-
`),a=1)}else if(e.commands.has(o)){let
|
|
628
|
+
`,u=!0)}catch{}u||(n&&(i+=`${o}: not found
|
|
629
|
+
`),a=1)}else if(e.commands.has(o)){let u=x(e.state.env,"PATH","/usr/bin:/bin").split(":"),f=null;for(let d of u){if(!d)continue;let p=`${d}/${o}`;try{let m=await e.fs.stat(p);if(!m.isDirectory&&(m.mode&73)!==0){f=p;break}}catch{}}f||(f=`/usr/bin/${o}`),n?r+=`${o} is ${f}
|
|
627
630
|
`:r+=`${f}
|
|
628
631
|
`}else n&&(i+=`${o}: not found
|
|
629
|
-
`),a=1}return W(F(r),F(i),a)}async function Oi(e,t){if(t.includes("/")){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r)){try{let i=await e.fs.stat(r);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let n=x(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let r of n){if(!r)continue;let a=`${r.startsWith("/")?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let r of n)if(r==="/usr/bin"||r==="/bin")return`${r}/${t}`;return`/usr/bin/${t}`}return null}async function
|
|
630
|
-
`);let[,...a]=r;return n(i,a.map(o=>F(o)),[],s,!0,!1,-1)}async function
|
|
631
|
-
`,127):
|
|
632
|
-
`,127);if("error"in
|
|
633
|
-
`,126):
|
|
634
|
-
`,127);if("script"in
|
|
635
|
-
`)}}async function _s(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let n=0;try{for(let r of t){let i=await e.executeStatement(r);await Y(e,i),n=i.exitCode}}catch(r){throw await ee(e,r),r}finally{e.state.inCondition=s}return{stdout:
|
|
632
|
+
`),a=1}return W(F(r),F(i),a)}async function Oi(e,t){if(t.includes("/")){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r)){try{let i=await e.fs.stat(r);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let n=x(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let r of n){if(!r)continue;let a=`${r.startsWith("/")?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let r of n)if(r==="/usr/bin"||r==="/bin")return`${r}/${t}`;return`/usr/bin/${t}`}return null}async function Ii(e,t,s,n,r,i,a,o){let{ctx:l,runCommand:c}=e,u=bt(s);if(l.coverage&&Ge.has(t)&&l.coverage.hit(`bash:builtin:${t}`),t==="export")return Tn(l,u);if(t==="unset")return Gn(l,u);if(t==="exit")return _n(l,u);if(t==="local")return Mn(l,u);if(t==="set")return jn(l,u);if(t==="break")return Xs(l,u);if(t==="continue")return pn(l,u);if(t==="return")return Vn(l,u);if(t==="eval"&&l.state.options.posix)return Es(l,u,r);if(t==="shift")return Bn(l,u);if(t==="getopts")return $s(l,u);if(t==="compgen")return un(l,u);if(t==="complete")return dn(l,u);if(t==="compopt")return hn(l,u);if(t==="pushd")return await Cn(l,u);if(t==="popd")return kn(l,u);if(t==="dirs")return Pn(l,u);if(t==="source"||t===".")return Hn(l,u);if(t==="read")return await Fn(l,u,await ie(r),o);if(t==="mapfile"||t==="readarray")return await Wn(l,u,await ie(r));if(t==="declare"||t==="typeset")return En(l,u);if(t==="readonly")return $n(l,u);if(!i){let f=l.state.functions.get(t);if(f)return bs(l,f,u,r)}if(t==="eval")return Es(l,u,r);if(t==="cd")return await Ks(l,u);if(t===":"||t==="true")return B();if(t==="false")return ae(!1);if(t==="let")return Ln(l,u);if(t==="command")return Pa(e,u,r);if(t==="builtin")return _a(e,u,r);if(t==="shopt")return Ci(l,u);if(t==="exec"){if(s.length===0)return B();let[f,...d]=s;return c(H(f),d,[],r,!1,!1,-1)}if(t==="wait")return await qn(l,u);if(t==="jobs")return await On(l,u,(f,d)=>c(f,d.map(F),d.map(()=>!1),A()));if(t==="kill")return Rn(l,u);if(t==="type")return await Ni(l,u,f=>Oi(l,f),f=>Ps(l,f));if(t==="hash")return Nn(l,u);if(t==="help")return xn(l,u);if(t==="["||t==="test"){let f=u;if(t==="["){if(u[u.length-1]!=="]")return C("[: missing `]'\n",2);f=u.slice(0,-1)}return xt(l,f)}return null}async function Pa(e,t,s){let{ctx:n,runCommand:r}=e;if(t.length===0)return B();let i=!1,a=!1,o=!1,l=t;for(;l.length>0&&l[0].startsWith("-");){let f=l[0];if(f==="--"){l=l.slice(1);break}for(let d of f.slice(1))d==="p"?i=!0:d==="V"?a=!0:d==="v"&&(o=!0);l=l.slice(1)}if(l.length===0)return B();if(o||a)return await xi(n,l,o,a);let[c,...u]=l;return r(c,u.map(f=>F(f)),[],s,!0,i,-1)}async function _a(e,t,s){let{runCommand:n}=e;if(t.length===0)return B();let r=t;if(r[0]==="--"&&(r=r.slice(1),r.length===0))return B();let i=r[0];if(!Ge.has(i))return C(`bash: builtin: ${i}: not a shell builtin
|
|
633
|
+
`);let[,...a]=r;return n(i,a.map(o=>F(o)),[],s,!0,!1,-1)}async function Di(e,t,s,n,r){let{buildExportedEnv:i,ctx:a,executeUserScript:o}=e,c=await ki(a,t,r?"/usr/bin:/bin":void 0);if(!c)return Wr(t)?C(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
|
|
634
|
+
`,127):C(`bash: ${t}: command not found
|
|
635
|
+
`,127);if("error"in c)return c.error==="permission_denied"?C(`bash: ${t}: Permission denied
|
|
636
|
+
`,126):C(`bash: ${t}: No such file or directory
|
|
637
|
+
`,127);if("script"in c)return t.includes("/")||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,c.path)),await o(c.path,s,n);let{cmd:u,path:f}=c;t.includes("/")||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,f));let d,p=n.getReader(),m=await p.read();p.releaseLock(),m.done||!m.value||m.value.length===0?a.state.groupStdin?d=a.state.groupStdin:d=A():d=it(he(m.value),n);let h=i(),v={fs:a.fs,cwd:a.state.cwd,env:a.state.env,exportedEnv:h,stdin:d,limits:a.limits,exec:a.execFn,fetch:a.fetch,getRegisteredCommands:()=>Array.from(a.commands.keys()),sleep:a.sleep,trace:a.trace,fileDescriptors:a.state.fileDescriptors,xpgEcho:a.state.shoptOptions.xpg_echo,coverage:a.coverage,signal:a.signal};try{return await u.execute(s,v)}catch(S){if(S instanceof oe)throw S;return C(`${t}: ${Oe(S)}
|
|
638
|
+
`)}}async function _s(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let n=0;try{for(let r of t){let i=await e.executeStatement(r);await Y(e,i),n=i.exitCode}}catch(r){throw await ee(e,r),r}finally{e.state.inCondition=s}return{stdout:A(),stderr:A(),exitCode:n}}function Mt(e,t){return e instanceof Ae?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"break"}:e instanceof Ce?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"continue"}:e instanceof we||e instanceof ke||e instanceof q||e instanceof oe?{action:"rethrow",error:e}:{action:"error",exitCode:1,error:e}}async function Ts(e,t){let s=0;try{for(let n of t){let r=await e.executeStatement(n);await Y(e,r),s=r.exitCode}}catch(n){let r=await ee(e,n);if(Zt(n)||n instanceof ke||n instanceof q||n instanceof oe||n instanceof Be)throw n;if(!r){let i=Oe(n);await Y(e,C(i.endsWith(`
|
|
636
639
|
`)?i:`${i}
|
|
637
|
-
`))}return{stdout:
|
|
638
|
-
`);let r=n||
|
|
639
|
-
`),r=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(s||n||r||i){let l="";for(let
|
|
640
|
-
`?l+="\\n":
|
|
640
|
+
`))}return{stdout:A(),stderr:A(),exitCode:1}}return{stdout:A(),stderr:A(),exitCode:s}}var Ta="+ ";async function Ri(e){let t=e.state.env.get("PS4"),s=e.substitutionDepth??0;if(t===void 0)return`${"+".repeat(s+1)} `;let n=H(t);if(n==="")return"";try{let i=new Z().parseWordFromString(n,!1,!1),a=await z(e,i);return s>0&&a.length>0?`${a[0].repeat(s)}${a}`:a}catch{await U(e,2,`bash: ${n}: bad substitution
|
|
641
|
+
`);let r=n||Ta;return s>0&&r.length>0?`${r[0].repeat(s)}${r}`:r}}function Na(e){return e.map(t=>xa(t)).join(" ")}function xa(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),n=e.includes(`
|
|
642
|
+
`),r=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(s||n||r||i){let l="";for(let c of e){let u=c.charCodeAt(0);c===`
|
|
643
|
+
`?l+="\\n":c===" "?l+="\\t":c==="\\"?l+="\\\\":c==="'"?l+="'":c==='"'?l+='"':u<32||u===127?u<256?l+=`\\x${u.toString(16).padStart(2,"0")}`:l+=`\\u${u.toString(16).padStart(4,"0")}`:l+=c}return`$'${l}'`}return a?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function Ns(e,t,s){if(!e.state.options.xtrace)return"";let n=await Ri(e),r=[t,...s],i=Na(r);return`${n}${i}
|
|
641
644
|
`}async function Li(e,t,s){return e.state.options.xtrace?`${await Ri(e)}${t}=${s}
|
|
642
|
-
`:""}function
|
|
645
|
+
`:""}function Wt(e){let t=Oe(e);return t.endsWith(`
|
|
643
646
|
`)?t:`${t}
|
|
644
|
-
`}async function yt(e,t,s){let n=await
|
|
645
|
-
`)),1;let r=[];if(t.words===null)r=x(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length>0)try{for(let i of t.words){let a=await Ve(e,i);r.push(...a.values)}}catch(i){if(i instanceof
|
|
647
|
+
`}async function yt(e,t,s){let n=await xe(e,e.outputChannels,t);return n.error?K(e,n.channels,()=>Y(e,n.error)):K(e,n.channels,async()=>{try{let r=await s(n.legacyRedirections);return{stdout:A(),stderr:A(),exitCode:r}}catch(r){let i=await ee(e,r);if(r instanceof Error&&"code"in r&&r.code==="ENOSPC")return i?{stdout:A(),stderr:A(),exitCode:1}:await Y(e,C(Wt(r)));throw r}})}async function Mi(e,t){return yt(e,t.redirections,async()=>{for(let s of t.clauses)if((await _s(e,s.condition)).exitCode===0)return(await Ts(e,s.body)).exitCode;return t.elseBody?(await Ts(e,t.elseBody)).exitCode:0})}async function Wi(e,t){return yt(e,t.redirections,async()=>{let s=0,n=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return await Y(e,C(`bash: \`${t.variable}': not a valid identifier
|
|
648
|
+
`)),1;let r=[];if(t.words===null)r=x(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length>0)try{for(let i of t.words){let a=await Ve(e,i);r.push(...a.values)}}catch(i){if(i instanceof qt)return await ee(e,i),1;throw i}e.state.loopDepth++;try{for(let i of r){if(n++,e.signal?.aborted)throw new me(e.signal.reason);n>e.limits.maxLoopIterations&&Re(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),y(e.state.env,t.variable,i),e.state.options.xtrace&&await U(e,2,await Ns(e,"for",[t.variable,"in",...r]));try{for(let a of t.body){let o=await e.executeStatement(a);await Y(e,o),s=o.exitCode}}catch(a){let o=await ee(e,a),l=Mt(a,e.state.loopDepth);if(l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return o||await Y(e,C(Wt(l.error))),l.exitCode??1;throw l.error}}}finally{e.state.loopDepth--}return s})}async function Fi(e,t){return yt(e,t.redirections,async()=>{let s=t.line;s!==void 0&&(e.state.currentLine=s);let n=0,r=0;t.init&&await Q(e,t.init.expression),e.state.loopDepth++;try{for(;;){if(r++,e.signal?.aborted)throw new me(e.signal.reason);if(r>e.limits.maxLoopIterations&&Re(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),t.condition&&(s!==void 0&&(e.state.currentLine=s),await Q(e,t.condition.expression)===0))break;try{for(let i of t.body){let a=await e.executeStatement(i);await Y(e,a),n=a.exitCode}}catch(i){let a=await ee(e,i),o=Mt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue"){t.update&&await Q(e,t.update.expression);continue}if(o.action==="error")return a||await Y(e,C(Wt(o.error))),o.exitCode??1;throw o.error}t.update&&await Q(e,t.update.expression)}}finally{e.state.loopDepth--}return n})}async function Vi(e,t,s=A()){return yt(e,t.redirections,async n=>{let r=0,i=0,a=s,o=!1;for(let c of n)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let u=c.target,f=await z(e,u.content);u.stripTabs&&(f=f.split(`
|
|
646
649
|
`).map(d=>d.replace(/^\t+/,"")).join(`
|
|
647
|
-
`)),a=V(f),o=!0}else if(
|
|
648
|
-
`),o=!0;else if(
|
|
649
|
-
`)),1}}let l=e.state.groupStdin;if(o)e.state.groupStdin=a;else{let u=await ie(s);u.length>0&&(e.state.groupStdin=he(u))}e.state.loopDepth++;try{for(;;){if(i++,e.signal?.aborted)throw new me(e.signal.reason);i>e.limits.maxLoopIterations&&Re(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations");let u=0,c=!1,f=!1;try{u=(await _s(e,t.condition)).exitCode}catch(d){if(await ee(e,d),d instanceof Ae){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;c=!0}else if(d instanceof Ce){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;f=!0}else throw d}if(c)break;if(!f){if(u!==0)break;try{for(let d of t.body){let p=await e.executeStatement(d);await Y(e,p),r=p.exitCode}}catch(d){let p=await ee(e,d),m=Lt(d,e.state.loopDepth);if(m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return p||await Y(e,A(Mt(m.error))),m.exitCode??1;throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return r})}async function zi(e,t){return yt(e,t.redirections,async()=>{let s=0,n=0;e.state.loopDepth++;try{for(;;){if(n++,e.signal?.aborted)throw new me(e.signal.reason);if(n>e.limits.maxLoopIterations&&Re(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),(await _s(e,t.condition)).exitCode===0)break;try{for(let i of t.body){let a=await e.executeStatement(i);await Y(e,a),s=a.exitCode}}catch(i){let a=await ee(e,i),o=Lt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return a||await Y(e,A(Mt(o.error))),o.exitCode??1;throw o.error}}}finally{e.state.loopDepth--}return s})}async function ji(e,t){return yt(e,t.redirections,async()=>{let s=0,n=await z(e,t.word),r=!1;for(let i=0;i<t.items.length;i++){let a=t.items[i],o=r;if(!r)for(let l of a.patterns){let u=await z(e,l);yr(l)&&(u=mr(u));let c=e.state.shoptOptions.nocasematch,f=e.state.shoptOptions.extglob;if(dt(n,u,c,f)){o=!0;break}}if(o){if(s=(await Ts(e,a.body)).exitCode,a.terminator===";;")break;a.terminator===";&"?r=!0:r=!1}else r=!1}return s})}async function Pa(e,t,s){let n=_e(),r=s?_e():void 0,i=et(e.outputChannels);Ms(i,1,n),r&&Ms(i,2,r);try{let a=await K(e,i,t);return{...a,stdout:it(a.stdout,n.stream()),stderr:r?it(a.stderr,r.stream()):a.stderr}}catch(a){await K(e,i,()=>ee(e,a));let o=n.stream(),l=r?.stream()??E();if(a instanceof $t)return{stdout:o,stderr:l,exitCode:1};if(a instanceof q)return{stdout:o,stderr:l,exitCode:a.exitCode};if(a instanceof ke)return{stdout:o,stderr:l,exitCode:a.exitCode};throw await Y(e,{stdout:o,stderr:l,exitCode:1},!1),a}}async function Bi(e,t,s){let n=t.timed?performance.now():0,r=E(),i=B(),a=0,o=[],l=t.commands.length>1,u=e.state.lastArg;for(let d=0;d<t.commands.length;d++){let p=t.commands[d],m=d===t.commands.length-1,h=d===0,b=t.pipeStderr?.[d]??!1;l&&(e.state.lastArg=F(""),h||(e.state.groupStdin=void 0));let S=l&&(!m||!e.state.shoptOptions.lastpipe),$=S?new Map(e.state.env):null,g;try{if(m){let v=()=>s(p,r);g=S?await K(e,et(e.outputChannels),v):await v()}else g=await Pa(e,()=>s(p,r),b)}catch(v){if(await ee(e,v),v instanceof $t)g={stdout:E(),stderr:E(),exitCode:1};else if(v instanceof q&&t.commands.length>1)g={stdout:E(),stderr:E(),exitCode:v.exitCode};else if(v instanceof ke&&t.commands.length>1)g={stdout:E(),stderr:E(),exitCode:v.exitCode};else throw $&&(e.state.env=$),v}if($&&(e.state.env=$),e.signal?.aborted===!0&&g.exitCode===new me(e.signal.reason).exitCode)throw await Y(e,g,!1),new me(e.signal.reason);if(o.push(g.exitCode),g.exitCode!==0&&(a=g.exitCode),m)i=g;else if(b)r=it(g.stderr,g.stdout),i={stdout:E(),stderr:E(),exitCode:g.exitCode};else{let v=g.stdout;await Y(e,g,!0,[2]),r=v,i={stdout:E(),stderr:E(),exitCode:g.exitCode}}}e.state.options.pipefail&&a!==0&&(i={...i,exitCode:a}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0});let c=i.exitCode;if(i=await Y(e,i),i.exitCode!==c&&o.length>0&&(o[o.length-1]=i.exitCode),t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand"){for(let d of e.state.env.keys())d.startsWith("PIPESTATUS_")&&e.state.env.delete(d);for(let d=0;d<o.length;d++)y(e.state.env,`PIPESTATUS_${d}`,String(o[d]));y(e.state.env,"PIPESTATUS__length",String(o.length))}if(t.timed){let p=(performance.now()-n)/1e3,m=Math.floor(p/60),h=p%60,b;t.timePosix?b=`real ${p.toFixed(2)}
|
|
650
|
+
`)),a=V(f),o=!0}else if(c.operator==="<<<"&&c.target.type==="Word")a=V(`${await z(e,c.target)}
|
|
651
|
+
`),o=!0;else if(c.operator==="<"&&c.target.type==="Word"){let u=await z(e,c.target);try{let f=e.fs.resolvePath(e.state.cwd,u);a=await e.fs.readFile(f),o=!0}catch{return await Y(e,C(await It(e,u))),1}}let l=e.state.groupStdin;if(o)e.state.groupStdin=a;else{let c=await ie(s);c.length>0&&(e.state.groupStdin=he(c))}e.state.loopDepth++;try{for(;;){if(i++,e.signal?.aborted)throw new me(e.signal.reason);i>e.limits.maxLoopIterations&&Re(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations");let c=0,u=!1,f=!1;try{c=(await _s(e,t.condition)).exitCode}catch(d){if(await ee(e,d),d instanceof Ae){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;u=!0}else if(d instanceof Ce){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;f=!0}else throw d}if(u)break;if(!f){if(c!==0)break;try{for(let d of t.body){let p=await e.executeStatement(d);await Y(e,p),r=p.exitCode}}catch(d){let p=await ee(e,d),m=Mt(d,e.state.loopDepth);if(m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return p||await Y(e,C(Wt(m.error))),m.exitCode??1;throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return r})}async function zi(e,t){return yt(e,t.redirections,async()=>{let s=0,n=0;e.state.loopDepth++;try{for(;;){if(n++,e.signal?.aborted)throw new me(e.signal.reason);if(n>e.limits.maxLoopIterations&&Re(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),(await _s(e,t.condition)).exitCode===0)break;try{for(let i of t.body){let a=await e.executeStatement(i);await Y(e,a),s=a.exitCode}}catch(i){let a=await ee(e,i),o=Mt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return a||await Y(e,C(Wt(o.error))),o.exitCode??1;throw o.error}}}finally{e.state.loopDepth--}return s})}async function ji(e,t){return yt(e,t.redirections,async()=>{let s=0,n=await z(e,t.word),r=!1;for(let i=0;i<t.items.length;i++){let a=t.items[i],o=r;if(!r)for(let l of a.patterns){let c=await z(e,l);yr(l)&&(c=mr(c));let u=e.state.shoptOptions.nocasematch,f=e.state.shoptOptions.extglob;if(dt(n,c,u,f)){o=!0;break}}if(o){if(s=(await Ts(e,a.body)).exitCode,a.terminator===";;")break;a.terminator===";&"?r=!0:r=!1}else r=!1}return s})}async function Oa(e,t,s){let n=_e(),r=s?_e():void 0,i=et(e.outputChannels);Ms(i,1,n),r&&Ms(i,2,r);try{let a=await K(e,i,t);return{...a,stdout:it(a.stdout,n.stream()),stderr:r?it(a.stderr,r.stream()):a.stderr}}catch(a){await K(e,i,()=>ee(e,a));let o=n.stream(),l=r?.stream()??A();if(a instanceof $t)return{stdout:o,stderr:l,exitCode:1};if(a instanceof q)return{stdout:o,stderr:l,exitCode:a.exitCode};if(a instanceof ke)return{stdout:o,stderr:l,exitCode:a.exitCode};throw await Y(e,{stdout:o,stderr:l,exitCode:1},!1),a}}async function Bi(e,t,s){let n=t.timed?performance.now():0,r=A(),i=B(),a=0,o=[],l=t.commands.length>1,c=e.state.lastArg;for(let d=0;d<t.commands.length;d++){let p=t.commands[d],m=d===t.commands.length-1,h=d===0,v=t.pipeStderr?.[d]??!1;l&&(e.state.lastArg=F(""),h||(e.state.groupStdin=void 0));let S=l&&(!m||!e.state.shoptOptions.lastpipe),E=S?new Map(e.state.env):null,b;try{if(m){let g=()=>s(p,r);b=S?await K(e,et(e.outputChannels),g):await g()}else b=await Oa(e,()=>s(p,r),v)}catch(g){if(await ee(e,g),g instanceof $t)b={stdout:A(),stderr:A(),exitCode:1};else if(g instanceof q&&t.commands.length>1)b={stdout:A(),stderr:A(),exitCode:g.exitCode};else if(g instanceof ke&&t.commands.length>1)b={stdout:A(),stderr:A(),exitCode:g.exitCode};else throw E&&(e.state.env=E),g}if(E&&(e.state.env=E),e.signal?.aborted===!0&&b.exitCode===new me(e.signal.reason).exitCode)throw await Y(e,b,!1),new me(e.signal.reason);if(o.push(b.exitCode),b.exitCode!==0&&(a=b.exitCode),m)i=b;else if(v)r=it(b.stderr,b.stdout),i={stdout:A(),stderr:A(),exitCode:b.exitCode};else{let g=b.stdout;await Y(e,b,!0,[2]),r=g,i={stdout:A(),stderr:A(),exitCode:b.exitCode}}}e.state.options.pipefail&&a!==0&&(i={...i,exitCode:a}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0});let u=i.exitCode;if(i=await Y(e,i),i.exitCode!==u&&o.length>0&&(o[o.length-1]=i.exitCode),t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand"){for(let d of e.state.env.keys())d.startsWith("PIPESTATUS_")&&e.state.env.delete(d);for(let d=0;d<o.length;d++)y(e.state.env,`PIPESTATUS_${d}`,String(o[d]));y(e.state.env,"PIPESTATUS__length",String(o.length))}if(t.timed){let p=(performance.now()-n)/1e3,m=Math.floor(p/60),h=p%60,v;t.timePosix?v=`real ${p.toFixed(2)}
|
|
650
652
|
user 0.00
|
|
651
653
|
sys 0.00
|
|
652
|
-
`:
|
|
654
|
+
`:v=`
|
|
653
655
|
real ${`${m}m${h.toFixed(3)}s`}
|
|
654
656
|
user 0m0.000s
|
|
655
657
|
sys 0m0.000s
|
|
656
|
-
`,await U(e,2,
|
|
657
|
-
`)};let
|
|
658
|
-
`)};if(be(e,s)){let
|
|
658
|
+
`,await U(e,2,v)}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=c),i}async function Hi(e,t){let s=new Map,n="";for(let r of t.assignments){let i=r.name;if(r.array){let f=await Ia(e,t,i,r.array,r.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:f.error};if(n+=f.xtraceOutput,f.continueToNext)continue}let a=r.value?await ot(e,r.value):R,o=r.value?H(a):"";if(o.length>e.limits.maxStringLength&&Re(`word expansion: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"iterations"),i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:C(`bash: ${i}: bad array subscript
|
|
659
|
+
`)};let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let f=await Wa(e,t,c[1],c[2],o,r.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:f.error};if(f.continueToNext)continue}let u=await Va(e,t,i,o,r.append,s,a);if(u.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:u.error};n+=u.xtraceOutput,u.continueToNext}return{continueToNext:!1,xtraceOutput:n,tempAssignments:s}}async function Ia(e,t,s,n,r,i){let a="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:C(`bash: ${s}: cannot assign list to array member
|
|
660
|
+
`)};if(be(e,s)){let u=hr(e,s);if(u===void 0||u==="")throw new q(1);let f=Fe(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:C(`bash: ${s}: cannot assign list to array member
|
|
659
661
|
`)}}if(tt(e,s)){if(t.name)return a+=`bash: ${s}: readonly variable
|
|
660
|
-
`,{continueToNext:!0,xtraceOutput:a};let
|
|
661
|
-
`)}}async function
|
|
662
|
-
`)};o=f}}if(tt(e,o)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=await ue(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(o),
|
|
663
|
-
`;if(i.fatal)throw await U(e,2,l,!0),new q(1);return{index:0,error:
|
|
664
|
-
`)}}if(r=Math.max(...i.map(([o])=>typeof o=="number"?o:0))+1+r,r<0){let o=e.state.currentLine;return{index:0,error:
|
|
665
|
-
`)}}}return{index:r}}async function
|
|
666
|
-
`)};if(h===null)return{continueToNext:!0,xtraceOutput:""};l=h;let
|
|
667
|
-
`,{continueToNext:!0,xtraceOutput:o};let h=await ue(e,l);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let
|
|
668
|
-
`))),await
|
|
662
|
+
`,{continueToNext:!0,xtraceOutput:a};let u=await ue(e,s);if(u)return{continueToNext:!1,xtraceOutput:"",error:u}}let o=e.state.associativeArrays?.has(s),l=Da(n),c=()=>{let u=`${s}_`;for(let f of e.state.env.keys())f.startsWith(u)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(o&&l?await Ra(e,t,s,n,r,c,u=>{a+=u}):l?await La(e,s,n,r,c):await Ma(e,s,n,r,c),t.name){i.set(s,e.state.env.get(s));let f=`(${n.map(d=>Kt(d)).join(" ")})`;y(e.state.env,s,f)}return{continueToNext:!0,xtraceOutput:a}}function Da(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],n=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(t.parts.length<3)return!1;let r=t.parts[2];return r.type!=="Literal"?!1:r.value.startsWith("]=")||r.value.startsWith("]+=")}return n.type!=="Literal"?!1:n.value.startsWith("]")?n.value.startsWith("]=")||n.value.startsWith("]+="):s.pattern.endsWith("]")?n.value.startsWith("=")||n.value.startsWith("+="):!1}return!1})}async function Ra(e,t,s,n,r,i,a){let o=[];for(let l of n){let c=Fs(l);if(c){let{key:u,valueParts:f,append:d}=c,p;f.length>0?p=await z(e,{type:"Word",parts:f}):p="",p=se(e,p),o.push({type:"keyed",key:u,value:p,append:d})}else{let u=await z(e,l);o.push({type:"invalid",expandedValue:u})}}r||i();for(let l of o)if(l.type==="keyed")if(l.append){let c=x(e.state.env,`${s}_${l.key}`,"");y(e.state.env,`${s}_${l.key}`,c+l.value)}else y(e.state.env,`${s}_${l.key}`,l.value);else{let c=t.line??e.state.currentLine??1;a(`bash: line ${c}: ${s}: ${l.expandedValue}: must use subscript when assigning associative array
|
|
663
|
+
`)}}async function La(e,t,s,n,r){let i=[];for(let o of s){let l=Fs(o);if(l){let{key:c,valueParts:u,append:f}=l,d;u.length>0?d=await z(e,{type:"Word",parts:u}):d="",d=se(e,d),i.push({type:"keyed",indexExpr:c,value:d,append:f})}else{let c=await Ve(e,o);i.push({type:"non-keyed",values:c.values})}}n||r();let a=0;for(let o of i)if(o.type==="keyed"){let l;try{let c=new Z,u=le(c,o.indexExpr);l=await Q(e,u.expression,!1)}catch{if(/^-?\d+$/.test(o.indexExpr))l=Number.parseInt(o.indexExpr,10);else{let c=x(e.state.env,o.indexExpr);l=c?Number.parseInt(c,10):0,Number.isNaN(l)&&(l=0)}}if(o.append){let c=x(e.state.env,`${t}_${l}`,"");y(e.state.env,`${t}_${l}`,c+o.value)}else y(e.state.env,`${t}_${l}`,o.value);a=l+1}else for(let l of o.values)y(e.state.env,`${t}_${a++}`,l)}async function Ma(e,t,s,n,r){let i=[];for(let o of s){let l=await Ve(e,o);i.push(...l.values)}let a=0;if(n){let o=Ie(e,t);if(o.length>0)a=Math.max(...o.map(([c])=>typeof c=="number"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(e.state.env.set(`${t}_0`,l),e.state.env.delete(t),a=1)}}else r();for(let o=0;o<i.length;o++)y(e.state.env,`${t}_${a+o}`,i[o]);n||y(e.state.env,`${t}__length`,String(i.length))}async function Wa(e,t,s,n,r,i,a){let o=s;if(be(e,s)){let f=Fe(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:C(`bash: \`${f}': not a valid identifier
|
|
664
|
+
`)};o=f}}if(tt(e,o)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=await ue(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(o),c;if(l)c=await Ui(e,o,n);else{let f=await Fa(e,o,n);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};c=`${o}_${f.index}`}let u=i?x(e.state.env,c)+r:r;if(t.name)a.set(c,e.state.env.get(c)),y(e.state.env,c,u);else{let f=ht(e,o);if(f!==void 0&&f===e.state.callDepth&&e.state.localScopes.length>0){let d=e.state.localScopes[e.state.localScopes.length-1];d.has(c)||d.set(c,e.state.env.get(c))}y(e.state.env,c,u)}return{continueToNext:!0,xtraceOutput:""}}async function Ui(e,t,s){let n;if(s.startsWith("'")&&s.endsWith("'"))n=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let r=s.slice(1,-1),a=new Z().parseWordFromString(r,!0,!1);n=await z(e,a)}else if(s.includes("$")){let i=new Z().parseWordFromString(s,!1,!1);n=await z(e,i)}else n=s;return`${t}_${n}`}async function Fa(e,t,s){let n=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(n=s.slice(1,-1));let r;if(/^-?\d+$/.test(n))r=Number.parseInt(n,10);else{try{let i=new Z,a=le(i,n);r=await Q(e,a.expression,!1)}catch(i){if(i instanceof Ye){let l=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
|
|
665
|
+
`;if(i.fatal)throw await U(e,2,l,!0),new q(1);return{index:0,error:C(l)}}let a=x(e.state.env,s);r=a?Number.parseInt(a,10):0}Number.isNaN(r)&&(r=0)}if(r<0){let i=Ie(e,t);if(i.length===0){let o=e.state.currentLine;return{index:0,error:C(`bash: line ${o}: ${t}[${s}]: bad array subscript
|
|
666
|
+
`)}}if(r=Math.max(...i.map(([o])=>typeof o=="number"?o:0))+1+r,r<0){let o=e.state.currentLine;return{index:0,error:C(`bash: line ${o}: ${t}[${s}]: bad array subscript
|
|
667
|
+
`)}}}return{index:r}}async function Va(e,t,s,n,r,i,a){let o="",l=s,c=null;if(be(e,s)){let h=pr(e,s,n);if(h===void 0)return{continueToNext:!1,xtraceOutput:"",error:C(`bash: ${s}: circular name reference
|
|
668
|
+
`)};if(h===null)return{continueToNext:!0,xtraceOutput:""};l=h;let v=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);v&&(c={arrayName:v[1],subscriptExpr:v[2]},l=v[1])}if(tt(e,l)){if(t.name)return o+=`bash: ${l}: readonly variable
|
|
669
|
+
`,{continueToNext:!0,xtraceOutput:o};let h=await ue(e,l);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let u,f=!!a&&!r&&!c;if(Dt(e,l)){f=!1;try{let h=new Z;if(r){let S=`(${x(e.state.env,l,"0")}) + (${n})`,E=le(h,S);u=String(await Q(e,E.expression))}else{let v=le(h,n);u=String(await Q(e,v.expression))}}catch{u="0"}}else{let{isArray:h}=await import("./chunks/expansion-IB7ZIBIF.js"),v=h(e,l);v&&(f=!1);let S=v?`${l}_0`:l;u=r?x(e.state.env,S)+n:n}let d=gt(e,l,u);d!==u&&(f=!1),u=d,o+=await Li(e,l,u);let p=l;if(c)p=await za(e,c);else{let{isArray:h}=await import("./chunks/expansion-IB7ZIBIF.js");h(e,l)&&(p=`${l}_0`,f=!1)}let m=f?()=>e.state.env.set(p,a):()=>y(e.state.env,p,u);return t.name?(i.set(p,e.state.env.get(p)),m()):(m(),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(l)),e.state.tempEnvBindings?.some(h=>h.has(l))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(l))),{continueToNext:!1,xtraceOutput:o}}async function za(e,t){let{arrayName:s,subscriptExpr:n}=t;if(e.state.associativeArrays?.has(s))return Ui(e,s,n);let i;if(/^-?\d+$/.test(n))i=Number.parseInt(n,10);else{try{let a=new Z,o=le(a,n);i=await Q(e,o.expression,!1)}catch{let a=x(e.state.env,n);i=a?Number.parseInt(a,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let a=Ie(e,s);a.length>0&&(i=Math.max(...a.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function Gi(e,t,s,n){let r=et(e.outputChannels),i=new Map(e.state.env),a=e.state.cwd,o=e.state.fileDescriptors,l=e.state.nextFd;e.state.fileDescriptors=o?new Map(o):void 0;let c={...e.state.options},u=new Map(e.state.functions),f=e.state.localScopes,d=e.state.localVarStack,p=e.state.localVarDepth,m=e.state.fullyUnsetLocals;if(e.state.localScopes=f.map(N=>new Map(N)),d){e.state.localVarStack=new Map;for(let[N,M]of d.entries())e.state.localVarStack.set(N,M.map($=>({...$})))}p&&(e.state.localVarDepth=new Map(p)),m&&(e.state.fullyUnsetLocals=new Map(m));let h=e.state.loopDepth,v=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let S=e.state.lastArg,E=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let b=e.state.groupStdin,g=e.lineageId;e.lineageId=e.processes.createLineageId();let P=()=>{e.lineageId=g,e.state.env=i,e.state.cwd=a,e.state.fileDescriptors=o,e.state.nextFd=l,e.state.options=c,e.state.functions=u,e.state.localScopes=f,e.state.localVarStack=d,e.state.localVarDepth=p,e.state.fullyUnsetLocals=m,e.state.loopDepth=h,e.state.parentHasLoopContext=v,e.state.groupStdin=b,e.state.bashPid=E,e.state.lastArg=S};try{let N=t.redirections.length===0?{channels:r,legacyRedirections:[]}:await xe(e,r,t.redirections);return N.error?await K(e,N.channels,()=>te(e,()=>Promise.resolve(N.error))):await K(e,N.channels,async()=>{let M=$=>W(A(),A(),$);try{let $=await ie(s);$.length>0&&(e.state.groupStdin=he($));let k=0;for(let O of t.body){let D=await n(O);k=(await te(e,()=>Promise.resolve(D))).exitCode}return await M(k)}catch($){let{diagnosticWritten:k,writeFailure:O}=await Ze(e,$);if(O)return O;if($ instanceof oe)throw $;return $ instanceof Be||$ instanceof Ae||$ instanceof Ce?await M(0):$ instanceof q||$ instanceof we||$ instanceof ke||$ instanceof ve?await M($.exitCode):(k||await te(e,()=>Promise.resolve(C(`${Oe($)}
|
|
670
|
+
`))),await M(1))}})}catch(N){throw await K(e,r,()=>ee(e,N)),N}finally{P()}}async function qi(e,t,s,n){let r=t.redirections.length===0?{channels:e.outputChannels,legacyRedirections:[]}:await xe(e,e.outputChannels,t.redirections);return r.error?K(e,r.channels,()=>te(e,()=>Promise.resolve(r.error))):K(e,r.channels,async()=>{let i=e.state.groupStdin;try{let a=await pt(e,r.legacyRedirections);if(a)return await te(e,()=>Promise.resolve(a));let o=await ie(s),l=he(o),c=!1;for(let f of r.legacyRedirections)if(!f.fdVariable){if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,p=await z(e,d.content);d.stripTabs&&(p=p.split(`
|
|
669
671
|
`).map(h=>h.replace(/^\t+/,"")).join(`
|
|
670
|
-
`));let m=f.fd??0;m!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(m,p)):(l=V(p),
|
|
671
|
-
`),
|
|
672
|
-
`)))}}}(
|
|
673
|
-
`))),W(
|
|
674
|
-
`,127)}if(i.startsWith("#!")){let
|
|
675
|
-
`);
|
|
676
|
-
`);throw
|
|
672
|
+
`));let m=f.fd??0;m!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(m,p)):(l=V(p),c=!0)}else if(f.operator==="<<<"&&f.target.type==="Word")l=V(`${await z(e,f.target)}
|
|
673
|
+
`),c=!0;else if(f.operator==="<"&&f.target.type==="Word"){let d=await z(e,f.target);try{let p=e.fs.resolvePath(e.state.cwd,d);l=await e.fs.readFile(p),c=!0}catch{return await te(e,()=>Promise.resolve(C(`bash: ${d}: No such file or directory
|
|
674
|
+
`)))}}}(c||o.length>0)&&(e.state.groupStdin=l);let u=0;for(let f of t.body){let d=await n(f);u=(await te(e,()=>Promise.resolve(d))).exitCode}return W(A(),A(),u)}catch(a){let{diagnosticWritten:o,writeFailure:l}=await Ze(e,a);if(l)return l;if(Zt(a)||a instanceof ke||a instanceof q||a instanceof ve||a instanceof Be||a instanceof oe)throw a;return o||await te(e,()=>Promise.resolve(C(`${Oe(a)}
|
|
675
|
+
`))),W(A(),A(),1)}finally{e.state.groupStdin=i}})}async function Zi(e,t,s,n,r){let i;try{i=await e.fs.readFileText(t)}catch{return C(`bash: ${t}: No such file or directory
|
|
676
|
+
`,127)}if(i.startsWith("#!")){let v=i.indexOf(`
|
|
677
|
+
`);v!==-1&&(i=i.slice(v+1))}let a=new Map(e.state.env),o=e.state.cwd,l={...e.state.options},c=e.state.loopDepth,u=e.state.parentHasLoopContext,f=e.state.lastArg,d=e.state.bashPid,p=e.state.groupStdin,m=e.state.currentSource,h=()=>{e.state.env=a,e.state.cwd=o,e.state.options=l,e.state.loopDepth=c,e.state.parentHasLoopContext=u,e.state.lastArg=f,e.state.bashPid=d,e.state.groupStdin=p,e.state.currentSource=m};try{e.state.parentHasLoopContext=c>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;let v=await ie(n);v.length>0&&(e.state.groupStdin=he(v)),e.state.currentSource=t,y(e.state.env,"0",t),y(e.state.env,"#",String(s.length)),y(e.state.env,"@",s.join(" ")),y(e.state.env,"*",s.join(" "));for(let g=0;g<s.length&&g<9;g++)y(e.state.env,String(g+1),s[g]);for(let g=s.length+1;g<=9;g++)e.state.env.delete(String(g));let E=new Z().parse(i),b=await r(E);return await te(e,()=>Promise.resolve(b))}catch(v){let{writeFailure:S}=await Ze(e,v);if(S)return S;if(v instanceof q||v instanceof oe)throw v;if(v.name==="ParseException")return C(`bash: ${t}: ${v.message}
|
|
678
|
+
`);throw v}finally{h()}}function ja(e,t){for(let s of t.parts)switch(s.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"DoubleQuoted":for(let n of s.parts)switch(n.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"ParameterExpansion":if(n.operation||n.parameter==="@"||n.parameter==="*"||n.parameter.endsWith("[@]")||n.parameter.endsWith("[*]"))return!1;if(be(e,n.parameter)){let r=Fe(e,n.parameter);if(r&&(r.endsWith("[@]")||r.endsWith("[*]")))return!1}continue;case"CommandSubstitution":continue;default:return!1}continue;case"ParameterExpansion":return!1;default:return!1}return t.parts.length>0}var Ft=class e{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,processes:t.processes,lineageId:t.lineageId,outputChannels:t.outputChannels,reportedDiagnostics:new WeakSet,limits:t.limits,jobTracker:t.jobTracker,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,signal:t.signal}}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,n=new Set;if(t)for(let i of t)n.add(i);if(s)for(let i of s)n.add(i);if(n.size===0)return Object.create(null);let r=Object.create(null);for(let i of n)this.ctx.state.env.has(i)&&(r[i]=x(this.ctx.state.env,i));return r}async executeRootScript(t){let s=await this.executeScript(t);return Qe(this.ctx.signal),Y(this.ctx,s)}async executeScript(t){let s=0;for(let n of t.statements)try{let r=await this.executeStatement(n),i=this.ctx.signal?.aborted===!0&&r.exitCode===new me(this.ctx.signal.reason).exitCode;await Y(this.ctx,r,!i),s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s))}catch(r){if(await ee(this.ctx,r),r instanceof q)throw r;if(r instanceof ve)return s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:qe(this.ctx.state.env)};if(r instanceof oe)throw r;if(r instanceof ke)return s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:qe(this.ctx.state.env)};if(r instanceof sr)return s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:qe(this.ctx.state.env)};if(r instanceof $t)return s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:qe(this.ctx.state.env)};if(r instanceof Ye){s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s));continue}if(r instanceof nr){s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s));continue}if(r instanceof Ae||r instanceof Ce){if(this.ctx.state.loopDepth>0)throw r;continue}throw r instanceof we,r}return{stdout:A(),stderr:A(),exitCode:s,env:qe(this.ctx.state.env)}}async executeUserScript(t,s,n=A()){return Zi(this.ctx,t,bt(s),n,r=>this.executeScript(r))}async executeStatement(t){if(Qe(this.ctx.signal),this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Re(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),this.ctx.signal&&this.ctx.state.commandCount%1024===0&&(await new Promise(o=>setTimeout(o,0)),Qe(this.ctx.signal)),t.deferredError)throw new Jt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return B();if(this.ctx.state.errexitSafe=!1,this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&await U(this.ctx,2,`${t.sourceText}
|
|
677
679
|
`),t.background){if(this.ctx.processes.runningCount>=this.ctx.limits.maxConcurrentJobs)return this.ctx.jobTracker.limitExceeded=!0,await U(this.ctx,2,`bash: maximum concurrent jobs (${this.ctx.limits.maxConcurrentJobs}) exceeded
|
|
678
|
-
`),
|
|
679
|
-
`),
|
|
680
|
+
`),C("",oe.EXIT_CODE);let o=this.ctx.state,l={...o,env:new Map([...o.env].map(([h,v])=>[h,v.slice()])),functions:new Map(o.functions),localScopes:o.localScopes.map(h=>new Map([...h].map(([v,S])=>[v,S?.slice()]))),options:{...o.options},shoptOptions:{...o.shoptOptions},lastArg:o.lastArg.slice(),groupStdin:void 0,...o.fileDescriptors?{fileDescriptors:new Map(o.fileDescriptors)}:{},...o.readonlyVars?{readonlyVars:new Set(o.readonlyVars)}:{},...o.associativeArrays?{associativeArrays:new Set(o.associativeArrays)}:{},...o.namerefs?{namerefs:new Set(o.namerefs)}:{},...o.boundNamerefs?{boundNamerefs:new Set(o.boundNamerefs)}:{},...o.invalidNamerefs?{invalidNamerefs:new Set(o.invalidNamerefs)}:{},...o.integerVars?{integerVars:new Set(o.integerVars)}:{},...o.lowercaseVars?{lowercaseVars:new Set(o.lowercaseVars)}:{},...o.uppercaseVars?{uppercaseVars:new Set(o.uppercaseVars)}:{},...o.exportedVars?{exportedVars:new Set(o.exportedVars)}:{},...o.tempExportedVars?{tempExportedVars:new Set(o.tempExportedVars)}:{},...o.localExportedVars?{localExportedVars:o.localExportedVars.map(h=>new Set(h))}:{},...o.declaredVars?{declaredVars:new Set(o.declaredVars)}:{},...o.localVarDepth?{localVarDepth:new Map(o.localVarDepth)}:{},...o.localVarStack?{localVarStack:new Map([...o.localVarStack].map(([h,v])=>[h,v.map(S=>({...S,value:S.value?.slice()}))]))}:{},...o.fullyUnsetLocals?{fullyUnsetLocals:new Map(o.fullyUnsetLocals)}:{},...o.tempEnvBindings?{tempEnvBindings:o.tempEnvBindings.map(h=>new Map([...h].map(([v,S])=>[v,S?.slice()])))}:{},...o.mutatedTempEnvVars?{mutatedTempEnvVars:new Set(o.mutatedTempEnvVars)}:{},...o.accessedTempEnvVars?{accessedTempEnvVars:new Set(o.accessedTempEnvVars)}:{},...o.callLineStack?{callLineStack:[...o.callLineStack]}:{},...o.funcNameStack?{funcNameStack:[...o.funcNameStack]}:{},...o.sourceStack?{sourceStack:[...o.sourceStack]}:{},...o.completionSpecs?{completionSpecs:new Map(o.completionSpecs)}:{},...o.directoryStack?{directoryStack:[...o.directoryStack]}:{},...o.hashTable?{hashTable:new Map(o.hashTable)}:{}},c=this.ctx.processes,u=this.ctx.outputChannels,f=h=>et(u,(v,S)=>c.observesOutput?_e({write(E){return c.observeOutput(h,v,E),S.write(E)}},!1):S),d=t.sourceText?.trim()||"<background job>",p=c.createLineageId(),m;try{m=c.start(d,async(h,v)=>{let S=f(h);l.bashPid=h,l.nextVirtualPid=Math.max(l.nextVirtualPid,h+1);let E=Ct(this.ctx.signal,v),b=new e({fs:this.ctx.fs,commands:this.ctx.commands,processes:c,lineageId:p,outputChannels:S,limits:this.ctx.limits,jobTracker:this.ctx.jobTracker,exec:(g,P)=>this.ctx.execFn(g,{...P,signal:Ct(E,P?.signal)}),fetch:this.ctx.fetch,sleep:this.ctx.sleep,trace:this.ctx.trace,coverage:this.ctx.coverage,signal:E},l);try{return(await b.executeRootScript({type:"Script",statements:[{...t,background:!1,sourceText:void 0}]})).exitCode}catch(g){if(g instanceof me||g instanceof q)return g.exitCode;if(g instanceof oe)return this.ctx.jobTracker.limitExceeded=!0,oe.EXIT_CODE;throw g}},this.ctx.lineageId),this.ctx.jobTracker.started=!0}catch(h){return await U(this.ctx,2,`bash: ${h instanceof Error?h.message:String(h)}
|
|
681
|
+
`),C("",1)}return this.ctx.state.lastBackgroundPid=m,B()}let s=0,n=-1,r=!1;for(let o=0;o<t.pipelines.length;o++){let l=t.pipelines[o],c=o>0?t.operators[o-1]:null;if(c==="&&"&&s!==0||c==="||"&&s===0)continue;s=(await this.executePipeline(l)).exitCode,n=o,r=l.negated,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s))}let i=n<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=i||r||a,this.ctx.state.options.errexit&&s!==0&&n===t.pipelines.length-1&&!r&&!this.ctx.state.inCondition&&!a)throw new ke(s);return{stdout:A(),stderr:A(),exitCode:s}}async executePipeline(t){return Bi(this.ctx,t,(s,n)=>this.executeCommand(s,n))}async executeCommand(t,s){switch(this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,s);case"If":return Mi(this.ctx,t);case"For":return Wi(this.ctx,t);case"CStyleFor":return Fi(this.ctx,t);case"While":return Vi(this.ctx,t,s);case"Until":return zi(this.ctx,t);case"Case":return ji(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return si(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return B()}}async executeSimpleCommand(t,s){this.ctx.reportedDiagnostics=new WeakSet;try{return await this.executeSimpleCommandInner(t,s)}catch(n){if(n instanceof qt)return await ee(this.ctx,n),{stdout:A(),stderr:A(),exitCode:1};throw n}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let $=t,k=100;for(;k>0;){let O=this.expandAlias($);if(O===$)break;$=O,k--}this.aliasExpansionStack.clear(),$!==t&&(t=$)}let n=await Hi(this.ctx,t);if(n.error)return n.error;let r=n.tempAssignments,i=n.xtraceOutput;if(!t.name){if(await U(this.ctx,2,i),t.redirections.length>0){let $=this.ctx.outputChannels,k=await xe(this.ctx,$,t.redirections);if(k.error)return await K(this.ctx,k.channels,()=>te(this.ctx,()=>Promise.resolve(k.error)));let O={stdout:A(),stderr:A(),exitCode:0},D=[1,2].filter(_=>{let T=$.bindings.get(_),w=k.channels.bindings.get(_);return T?.sink!==w?.sink||Me($,_)!==Me(k.channels,_)});return await K(this.ctx,k.channels,()=>te(this.ctx,()=>Promise.resolve(O),D))}return this.ctx.state.lastArg=F(""),{stdout:A(),stderr:A(),exitCode:this.ctx.state.lastExitCode}}let a=t.name&&Ot(t.name,["local","declare","typeset","export","readonly"]),o=Array.from(r.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let $ of o)this.ctx.state.tempExportedVars.add($)}let l=-1,c=Ot(t.name,["exec"])&&(t.args.length===0||t.args.length===1&&Ot(t.args[0],["--"])),u=await z(this.ctx,t.name),f=[],d=[];if(Ot(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let $ of t.args){let k=await Lr(this.ctx,$);if(k)f.push(F(k)),d.push(!0);else{let O=await Mr(this.ctx,$);if(O!==null)f.push(F(O)),d.push(!0);else{let D=await Ve(this.ctx,$);for(let _ of D.values)f.push(F(_)),d.push(D.quoted)}}}else for(let $ of t.args)if(ja(this.ctx,$))f.push(await ot(this.ctx,$)),d.push(!0);else{let k=await Ve(this.ctx,$);for(let O of k.values)f.push(F(O)),d.push(k.quoted)}let m=this.ctx.outputChannels,h=!c&&t.redirections.length>0?await xe(this.ctx,m,t.redirections,{persistMovedSource:Ge.has(u)}):void 0;if(h?.error){await U(this.ctx,2,i);for(let[$,k]of r)k===void 0?this.ctx.state.env.delete($):this.ctx.state.env.set($,k);return await K(this.ctx,h.channels,()=>te(this.ctx,()=>Promise.resolve(h.error)))}let v=t.redirections.some($=>{if(c&&($.operator==="<"||$.operator==="<&")||$.fdVariable)return!1;if($.operator==="<<"||$.operator==="<<-"||$.operator==="<<<")return!0;let k=$.fd??0;return($.operator==="<"||$.operator==="<&")&&k===0}),S=null,E=R;v?E=await ie(s):S=s;let b=h?.legacyRedirections??t.redirections;for(let $ of b)if(!($.fdVariable||c&&($.operator==="<"||$.operator==="<&"))){if(($.operator==="<<"||$.operator==="<<-")&&$.target.type==="HereDoc"){let k=$.target,O=$.fd??0;if(O===0&&!k.stripTabs)E=await ot(this.ctx,k.content);else{let D=await z(this.ctx,k.content);k.stripTabs&&(D=D.split(`
|
|
680
682
|
`).map(_=>_.replace(/^\t+/,"")).join(`
|
|
681
|
-
`)),O!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set(O,
|
|
682
|
-
`));continue}if(
|
|
683
|
-
`)}if(
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
`)
|
|
687
|
-
`)),h&&I.length>0&&(C=await K(this.ctx,h.channels,()=>te(this.ctx,()=>Promise.resolve(C),I))),N)throw N;if(f.length>0){let P=H(f[f.length-1]);if((c==="declare"||c==="local"||c==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(P)){let k=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);k&&(P=k[1])}this.ctx.state.lastArg=F(P)}else this.ctx.state.lastArg=F(c)}finally{let P=Yr(c)&&c!=="unset"&&c!=="eval";if(!this.ctx.state.options.posix||!P)for(let[O,R]of r)this.ctx.state.fullyUnsetLocals?.has(O)||(R===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,R));if(this.ctx.state.tempExportedVars)for(let O of r.keys())this.ctx.state.tempExportedVars.delete(O);r.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop()}return C}async runCommand(t,s,n,r,i=!1,a=!1,o=-1){let l={ctx:this.ctx,runCommand:(c,f,d,p,m,h,b)=>this.runCommand(c,f,d,p,m,h,b),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(c,f,d)=>this.executeUserScript(c,f,d??E())},u=await Di(l,t,s,n,r,i,a,o);return u!==null?u:Ii(l,t,s,r,a)}aliasExpansionStack=new Set;expandAlias(t){return Js(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Ps(this.ctx,t)}async executeSubshell(t,s=E()){return Gi(this.ctx,t,s,n=>this.executeStatement(n))}async executeGroup(t,s=E()){return qi(this.ctx,t,s,n=>this.executeStatement(n))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,n=await Ne(this.ctx,s,t.redirections);if(n.error)return K(this.ctx,n.channels,()=>te(this.ctx,()=>Promise.resolve(n.error)));let r=[1,2].filter(i=>{let a=s.bindings.get(i),o=n.channels.bindings.get(i);return a?.sink!==o?.sink||Me(s,i)!==Me(n.channels,i)});return K(this.ctx,n.channels,async()=>{let i;try{let a=await Q(this.ctx,t.expression.expression);i=ae(a!==0)}catch(a){i=A(`bash: arithmetic expression: ${a.message}
|
|
688
|
-
|
|
689
|
-
`,o)}return r.length>0?te(this.ctx,()=>Promise.resolve(i),r):i})}};var ye={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:3e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxConcurrentJobs:128};function Ji(e){return e?{maxCallDepth:e.maxCallDepth??ye.maxCallDepth,maxCommandCount:e.maxCommandCount??ye.maxCommandCount,maxLoopIterations:e.maxLoopIterations??ye.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??ye.maxAwkIterations,maxSedIterations:e.maxSedIterations??ye.maxSedIterations,maxJqIterations:e.maxJqIterations??ye.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??ye.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??ye.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??ye.maxGlobOperations,maxStringLength:e.maxStringLength??ye.maxStringLength,maxArrayElements:e.maxArrayElements??ye.maxArrayElements,maxHeredocSize:e.maxHeredocSize??ye.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??ye.maxSubstitutionDepth,maxConcurrentJobs:e.maxConcurrentJobs??ye.maxConcurrentJobs}:{...ye}}function Ki(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Wa(e){let t=Ki(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Fa(e,t){let s=Ki(e);if(!s)return!1;let n=Wa(t);return!n||s.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:s.pathname.startsWith(n.pathPrefix)}function Jn(e,t){return!t||t.length===0?!1:t.some(s=>Fa(e,s))}var Ft=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},Vt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},zt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Ns=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},jt=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Va=20,za=3e4,ja=10485760,Ba=["GET","HEAD"],Ha=new Set(["GET","HEAD","OPTIONS"]),Ua=new Set([301,302,303,307,308]);function Kn(e){let t=e.maxRedirects??Va,s=e.timeoutMs??za,n=e.maxResponseSize??ja,r=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??Ba;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!Jn(l,e.allowedUrlPrefixes??[]))throw new Ft(l)}function a(l){if(e.dangerouslyAllowFullInternetAccess)return;let u=l.toUpperCase();if(!r.includes(u))throw new Ns(u,r)}async function o(l,u={}){let c=u.method?.toUpperCase()??"GET";i(l),a(c);let f=l,d=0,p=u.followRedirects??!0,m=u.timeoutMs!==void 0?Math.min(u.timeoutMs,s):s;for(;;){let h=new AbortController,b=setTimeout(()=>h.abort(),m);try{let S={method:c,headers:u.headers,signal:h.signal,redirect:"manual"};u.body&&!Ha.has(c)&&(S.body=u.body);let $=await fetch(f,S);if(Ua.has($.status)&&p){let g=$.headers.get("location");if(!g)return await Yi($,f,n);let v=new URL(g,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!Jn(v,e.allowedUrlPrefixes??[]))throw new zt(v);if(d++,d>t)throw new Vt(t);f=v;continue}return await Yi($,f,n)}finally{clearTimeout(b)}}}return o}async function Yi(e,t,s){let n=Object.create(null);if(e.headers.forEach((i,a)=>{n[a.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let a=parseInt(i,10);if(!Number.isNaN(a)&&a>s)throw new jt(s)}}let r;if(s>0&&e.body){let i=e.body.getReader(),a=new TextDecoder,o=[],l=0;for(;;){let{done:u,value:c}=await i.read();if(u)break;if(l+=c.byteLength,l>s)throw i.cancel(),new jt(s);o.push(a.decode(c,{stream:!0}))}o.push(a.decode()),r=o.join("")}else r=await e.text();return{status:e.status,statusText:e.statusText,headers:n,body:r,url:t}}var Ga=1e3,qa=64,Za=globalThis.setTimeout.bind(globalThis),Ja=globalThis.clearTimeout.bind(globalThis),Os=class{jobs=new Map;reapedWaitStatuses=new Map;reapedWaitLineages=new Map;options;nextPid=Ga;nextLineageId=1;highestJobNumber=0;runningJobs=0;disposed=!1;disposePromise;constructor(t={}){this.options=t}start(t,s,n){if(this.disposed)throw new Error("Cannot start a job on a disposed ProcessTable");let r=this.nextPid++,i=new AbortController,a=this.highestJobNumber+1,o={info:{pid:r,command:t,startedAt:Date.now(),state:"running"},jobNumber:a,lineageId:n,controller:i,promise:Promise.resolve(0)};return this.jobs.set(r,o),this.highestJobNumber=a,this.runningJobs++,o.promise=Promise.resolve().then(()=>s(r,i.signal)).catch(()=>i.signal.aborted?rr(i.signal.reason):1).then(l=>{this.jobs.get(r)===o&&this.runningJobs--,o.info={...o.info,state:"done",exitCode:l},o.controller=void 0,o.promise=void 0;try{Promise.resolve(this.options.onJobExit?.(r,l)).catch(()=>{})}catch{}return l}),r}list(){return[...this.jobs.values()].sort((t,s)=>t.jobNumber-s.jobNumber).map(t=>({...t.info}))}listJobs(t,s={}){let n=[...this.jobs.values()].sort((l,u)=>l.jobNumber-u.jobNumber),r=n.at(-1)?.info.pid,i=n.at(-2)?.info.pid,a=[],o=[];for(let l of n)t&&!t.has(l.info.pid)||s.runningOnly&&l.info.state!=="running"||s.stoppedOnly||s.changedOnly&&l.changedStateReported===l.info.state||(o.push({...l.info,jobNumber:l.jobNumber,marker:l.info.pid===r?"+":l.info.pid===i?"-":" "}),s.changedOnly&&(l.changedStateReported=l.info.state),l.info.state==="done"&&(a.push(l.info.pid),this.rememberWaitStatus(l.info.pid,l.info.exitCode??1,l.lineageId)));return this.deleteJobs(a),o}get(t){let s=this.jobs.get(t)?.info;return s?{...s}:void 0}kill(t,s,n){let r=this.jobs.get(t);return!r||r.info.state==="done"?!1:(s!=="SIGSTOP"&&s!=="SIGCONT"&&r.controller?.abort(n??s),!0)}async wait(t){if(t!==void 0){let r=this.jobs.get(t);if(!r)return this.reapedWaitStatuses.get(t)??127;let i=r.info.state==="done"?r.info.exitCode??1:await(r.promise??Promise.resolve(1));return this.jobs.get(t)===r&&(this.rememberWaitStatus(t,i,r.lineageId),this.deleteJobs([t])),i}let s=[...this.jobs.values()],n=new Set([...this.reapedWaitStatuses.keys(),...s.map(r=>r.info.pid)]);s.length>0&&(await Promise.all(s.map(r=>r.promise??Promise.resolve(r.info.exitCode??1))),this.deleteJobs(s.map(r=>r.info.pid)));for(let r of n)this.reapedWaitStatuses.delete(r),this.reapedWaitLineages.delete(r);return 0}async waitForLineage(t){let s=[...this.jobs.values()].filter(r=>r.lineageId===t),n=[...this.reapedWaitLineages.entries()].flatMap(([r,i])=>i===t?[r]:[]);s.length>0&&(await Promise.all(s.map(r=>r.promise??Promise.resolve(r.info.exitCode??1))),this.deleteJobs(s.map(r=>r.info.pid)));for(let r of[...n,...s.map(i=>i.info.pid)])this.reapedWaitStatuses.delete(r),this.reapedWaitLineages.delete(r);return 0}createLineageId(){return this.nextLineageId++}abortAll(t="SIGTERM"){for(let s of this.jobs.values())s.info.state==="running"&&s.controller?.abort(t)}dispose(){if(this.disposePromise)return this.disposePromise;this.disposed=!0;let t=[...this.jobs.values()],s=()=>{};this.disposePromise=new Promise(r=>{s=r}),this.abortAll("SIGKILL"),this.jobs.clear(),this.reapedWaitStatuses.clear(),this.reapedWaitLineages.clear(),this.highestJobNumber=0,this.runningJobs=0;let n=Za(s,this.options.disposeTimeoutMs??1e3);return Promise.allSettled(t.flatMap(r=>r.promise?[r.promise]:[])).then(()=>{Ja(n),s()}),this.disposePromise}get runningCount(){return this.runningJobs}getJobNumber(t){return this.jobs.get(t)?.jobNumber}canWait(t){return this.jobs.has(t)||this.reapedWaitStatuses.has(t)}resolveJobSpec(t){let s=[...this.jobs.values()].sort((i,a)=>i.jobNumber-a.jobNumber);if(t==="%+"||t==="%%")return s.at(-1)?.info.pid;if(t==="%-")return s.at(-2)?.info.pid;let n=/^%(\d+)$/.exec(t);if(!n)return;let r=Number.parseInt(n[1],10);return s.find(i=>i.jobNumber===r)?.info.pid}get observesOutput(){return this.options.onJobOutput!==void 0}observeOutput(t,s,n){try{Promise.resolve(this.options.onJobOutput?.(t,s,n)).catch(()=>{})}catch{}}rememberWaitStatus(t,s,n){if(this.reapedWaitStatuses.delete(t),this.reapedWaitLineages.delete(t),this.reapedWaitStatuses.set(t,s),this.reapedWaitLineages.set(t,n),this.reapedWaitStatuses.size>qa){let r=this.reapedWaitStatuses.keys().next().value;r!==void 0&&(this.reapedWaitStatuses.delete(r),this.reapedWaitLineages.delete(r))}}deleteJobs(t){let s=!1;for(let n of t){let r=this.jobs.get(n);r&&(this.jobs.delete(n),s||=r.jobNumber===this.highestJobNumber)}if(s){this.highestJobNumber=0;for(let n of this.jobs.values())this.highestJobNumber=Math.max(this.highestJobNumber,n.jobNumber)}}};function Xi(){let e=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables"},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"}];try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let t=Object.getPrototypeOf(async function*(){}).constructor;t&&t!==Function&&t!==Object.getPrototypeOf(async()=>{}).constructor&&e.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}return e.filter(t=>{try{return t.target[t.prop]!==void 0}catch{return!1}})}var Bt=typeof __BROWSER__<"u"&&__BROWSER__;function Qi(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Xn=null;if(!Bt)try{let e="node:module",{createRequire:t}=await import(e);Xn=t(import.meta.url)("node:async_hooks").AsyncLocalStorage}catch(e){console.debug("[DefenseInDepthBox] AsyncLocalStorage not available, defense-in-depth disabled:",e instanceof Error?e.message:e)}var Ka=`
|
|
690
|
-
|
|
691
|
-
This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,ge=class extends Error{violation;constructor(t,s){super(t+Ka),this.violation=s,this.name="SecurityViolationError"}},Ee=!Bt&&Xn?new Xn:null,Ya=1e3,Yn={enabled:!0,auditMode:!1};function Xa(e){return e===void 0?{...Yn,enabled:!1}:typeof e=="boolean"?{...Yn,enabled:e}:{...Yn,...e}}var Ds=class e{static instance=null;config;refCount=0;originalDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(t){this.config=t}static getInstance(t){return e.instance||(e.instance=new e(Xa(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return Ee?Ee?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(Ee)return Ee?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Bt||!this.config.enabled){let s=Qi();return{run:n=>n(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=Qi();return{run:s=>Ee.run({sandboxActive:!0,executionId:t},s),deactivate:()=>{this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0)},executionId:t}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}clearViolations(){this.violations=[]}getPathForTarget(t,s){return t===globalThis?`globalThis.${s}`:t===process?`process.${s}`:t===Error?`Error.${s}`:t===Function.prototype?`Function.prototype.${s}`:t===Object.prototype?`Object.prototype.${s}`:`<object>.${s}`}shouldBlock(){return Bt||this.config.auditMode||!Ee?!1:Ee?.getStore()?.sandboxActive===!0}recordViolation(t,s,n){let r={timestamp:Date.now(),type:t,message:n,path:s,stack:new Error().stack,executionId:Ee?.getStore()?.executionId};if(this.violations.length<Ya&&this.violations.push(r),this.config.onViolation)try{this.config.onViolation(r)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return r}createBlockingProxy(t,s,n){let r=this;return new Proxy(t,{apply(i,a,o){if(r.shouldBlock()){let l=`${s} is blocked during script execution`,u=r.recordViolation(n,s,l);throw new ge(l,u)}return r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} called (audit mode)`),Reflect.apply(i,a,o)},construct(i,a,o){if(r.shouldBlock()){let l=`${s} constructor is blocked during script execution`,u=r.recordViolation(n,s,l);throw new ge(l,u)}return r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} constructor called (audit mode)`),Reflect.construct(i,a,o)}})}createBlockingObjectProxy(t,s,n){let r=this;return new Proxy(t,{get(i,a,o){if(r.shouldBlock()){let l=`${s}.${String(a)}`,u=`${l} is blocked during script execution`,c=r.recordViolation(n,l,u);throw new ge(u,c)}if(r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0){let l=`${s}.${String(a)}`;r.recordViolation(n,l,`${l} accessed (audit mode)`)}return Reflect.get(i,a,o)},set(i,a,o,l){if(r.shouldBlock()){let u=`${s}.${String(a)}`,c=`${u} modification is blocked during script execution`,f=r.recordViolation(n,u,c);throw new ge(c,f)}return Reflect.set(i,a,o,l)},ownKeys(i){if(r.shouldBlock()){let a=`${s} enumeration is blocked during script execution`,o=r.recordViolation(n,s,a);throw new ge(a,o)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} descriptor access is blocked during script execution`,u=r.recordViolation(n,o,l);throw new ge(l,u)}return Reflect.getOwnPropertyDescriptor(i,a)},has(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} existence check is blocked during script execution`,u=r.recordViolation(n,o,l);throw new ge(l,u)}return Reflect.has(i,a)}})}applyPatches(){let t=Xi();for(let s of t)this.applyPatch(s);this.protectConstructorChain(),this.protectErrorPrepareStackTrace(),this.protectModuleLoad(),this.protectProcessMainModule()}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(async function*(){}).constructor,s=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&t!==s&&this.patchPrototypeConstructor(t.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}}protectErrorPrepareStackTrace(){let t=this;try{let s=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:s});let n=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return n},set(r){if(t.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",a=t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new ge(i,a)}t.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),n=r},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,n){let r=this;try{let i=Object.getOwnPropertyDescriptor(t,"constructor");this.originalDescriptors.push({target:t,prop:"constructor",descriptor:i});let a=i?.value;Object.defineProperty(t,"constructor",{get(){if(r.shouldBlock()){let o=`${s} access is blocked during script execution`,l=r.recordViolation(n,s,o);throw new ge(o,l)}return r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} accessed (audit mode)`),a},set(o){if(r.shouldBlock()){let l=`${s} modification is blocked during script execution`,u=r.recordViolation(n,s,l);throw new ge(l,u)}Object.defineProperty(this,"constructor",{value:o,writable:!0,configurable:!0})},configurable:!0})}catch(i){console.debug(`[DefenseInDepthBox] Could not patch ${s}:`,i instanceof Error?i.message:i)}}protectProcessMainModule(){if(typeof process>"u")return;let t=this;try{let s=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:s});let n=s?.value;n!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let r="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",r);throw new ge(r,i)}return t.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),n},set(r){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",a=t.recordViolation("process_main_module","process.mainModule",i);throw new ge(i,a)}Object.defineProperty(process,"mainModule",{value:r,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Bt)try{let t=null;if(typeof process<"u"){let a=process.mainModule;a&&typeof a=="object"&&(t=a.constructor)}if(!t&&typeof Ht<"u"&&typeof Ht.main<"u"&&(t=Ht.main.constructor),!t||typeof t._load!="function")return;let s=t._load,n=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:n});let i=this.createBlockingProxy(s,"Module._load","module_load");Object.defineProperty(t,"_load",{value:i,writable:!0,configurable:!0})}catch(t){console.debug("[DefenseInDepthBox] Could not protect Module._load:",t instanceof Error?t.message:t)}}applyPatch(t){let{target:s,prop:n,violationType:r,strategy:i}=t;try{let a=s[n];if(a===void 0)return;let o=Object.getOwnPropertyDescriptor(s,n);if(this.originalDescriptors.push({target:s,prop:n,descriptor:o}),i==="freeze")typeof a=="object"&&a!==null&&Object.freeze(a);else{let l=this.getPathForTarget(s,n),u=typeof a=="function"?this.createBlockingProxy(a,l,r):this.createBlockingObjectProxy(a,l,r);Object.defineProperty(s,n,{value:u,writable:!0,configurable:!0})}}catch(a){let o=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not patch ${o}:`,a instanceof Error?a.message:a)}}restorePatches(){for(let t=this.originalDescriptors.length-1;t>=0;t--){let{target:s,prop:n,descriptor:r}=this.originalDescriptors[t];try{r?Object.defineProperty(s,n,r):delete s[n]}catch(i){let a=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not restore ${a}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var Qa=globalThis.setTimeout.bind(globalThis),Is=class{fs;processes;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Tt(t.files);this.fs=s,this.processes=t.processes??new Os,this.useDefaultLayout=!t.cwd&&!t.files;let n=t.cwd||(this.useDefaultLayout?"/home/user":"/"),r=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
692
|
-
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",n],["OLDPWD",n],["OPTIND","1"]];for(let[a,o]of i)y(r,a,o);for(let[a,o]of Object.entries(t.env??{}))y(r,a,o);if(this.limits=Ji({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.network&&(this.secureFetch=Kn(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth,this.coverageWriter=t.coverage,this.state={env:r,cwd:n,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:L,startTime:Date.now(),lastBackgroundPid:0,bashPid:Ls().pid,nextVirtualPid:Ls().pid+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},y(this.state.env,"SHELLOPTS",Gs(this.state.options)),y(this.state.env,"BASHOPTS",qs(this.state.shoptOptions)),xr(s,this.useDefaultLayout),n!=="/"&&s instanceof Tt)try{s.mkdirSync(n,{recursive:!0})}catch{}for(let a of $r(t.commands))this.registerCommand(a);if(t.network)for(let a of Ar())this.registerCommand(a);if(t.python)for(let a of Cr())this.registerCommand(a);if(t.customCommands)for(let a of t.customCommands)kr(a)?this.registerCommand(Pr(a)):this.registerCommand(a)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let n=`#!/bin/bash
|
|
683
|
+
`)),O!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set(O,D)):E=F(D)}continue}if($.operator==="<<<"&&$.target.type==="Word"){let k=await ot(this.ctx,$.target);E=er(k,F(`
|
|
684
|
+
`));continue}if($.operator==="<"&&$.target.type==="Word")try{let k=await z(this.ctx,$.target),O=this.ctx.fs.resolvePath(this.ctx.state.cwd,k);E=await ie(await this.ctx.fs.readFile(O))}catch{let k=await z(this.ctx,$.target);for(let[O,D]of r)D===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,D);return C(await It(this.ctx,k))}if($.operator==="<&"&&($.fd??0)===0&&$.target.type==="Word"){let k=await z(this.ctx,$.target),O=k.startsWith("&")?k.slice(1):k;if(O!=="-"&&!/^\d+-?$/.test(O)){for(let[_,T]of r)T===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,T);return C(`bash: ${k}: ambiguous redirect
|
|
685
|
+
`)}let D=Number.parseInt(O,10);if(!Number.isNaN(D)&&Me(this.ctx.outputChannels,D)){for(let[_,T]of r)T===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,T);return C(je(D))}if(!Number.isNaN(D)&&this.ctx.state.fileDescriptors){let _=this.ctx.state.fileDescriptors.get(D);if(_!==void 0)if(_.startsWith("__rw__:")){let T=gs(_);T&&(E=F(T.content.slice(T.position)),l=D)}else _.startsWith("__file__:")||_.startsWith("__file_append__:")||(E=F(_));else if(D>=3&&!this.ctx.outputChannels.bindings.get(D)?.sink){for(let[T,w]of r)w===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,w);return C(je(D))}}else if(!Number.isNaN(D)&&D>=3&&!this.ctx.outputChannels.bindings.get(D)?.sink){for(let[_,T]of r)T===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,T);return C(je(D))}}}if(!u){if(t.name.parts.every(k=>k.type==="CommandSubstitution"||k.type==="ParameterExpansion"||k.type==="ArithmeticExpansion")){if(f.length>0){let k=H(f.shift());return d.shift(),await this.runCommand(k,f,d,S??he(E),!1,!1,l)}return{stdout:A(),stderr:A(),exitCode:this.ctx.state.lastExitCode}}return C(`bash: : command not found
|
|
686
|
+
`,127)}await U(this.ctx,2,i);let g=await Ns(this.ctx,u,f.map($=>H($)));if(await U(this.ctx,2,g),u==="exec"&&(f.length===0||H(f[0])==="--")){let $=[],k=this.ctx.outputChannels;for(;k;)$.push([k,new Map(k.bindings)]),k=k.parent;let O=this.ctx.state.fileDescriptors?new Map(this.ctx.state.fileDescriptors):void 0,D=this.ctx.state.nextFd,_=new Map;for(let w of t.redirections)w.fdVariable&&!_.has(w.fdVariable)&&_.set(w.fdVariable,this.ctx.state.env.get(w.fdVariable));let T=await ti(this.ctx,t.redirections);if(T.error){let w;try{w=await K(this.ctx,T.channels,()=>te(this.ctx,()=>Promise.resolve(T.error)))}finally{for(let[I,L]of $)I.bindings=new Map(L);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=D;for(let[I,L]of _)L===void 0?this.ctx.state.env.delete(I):this.ctx.state.env.set(I,L)}return w}for(let w of T.legacyRedirections){if(w.target.type==="HereDoc"||w.fdVariable)continue;let I=await z(this.ctx,w.target),L=w.fd??(w.operator==="<"||w.operator==="<>"?0:1);if(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),w.operator==="<"){let J=this.ctx.fs.resolvePath(this.ctx.state.cwd,I);try{let j=await this.ctx.fs.readFileText(J);this.ctx.state.fileDescriptors.set(L,j)}catch{let j;try{let X=await It(this.ctx,I);j=await te(this.ctx,()=>Promise.resolve(C(X)))}finally{for(let[X,re]of $)X.bindings=new Map(re);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=D;for(let[X,re]of _)re===void 0?this.ctx.state.env.delete(X):this.ctx.state.env.set(X,re)}return j}}else if(w.operator==="<>"){let J=this.ctx.fs.resolvePath(this.ctx.state.cwd,I);try{let j=await this.ctx.fs.readFileText(J);this.ctx.state.fileDescriptors.set(L,`__rw__:${J.length}:${J}:0:${j}`)}catch{await this.ctx.fs.writeFile(J,"","utf8"),this.ctx.state.fileDescriptors.set(L,`__rw__:${J.length}:${J}:0:`)}}else if(w.operator==="<&")if(I==="-")this.ctx.state.fileDescriptors.delete(L);else{let J=I.endsWith("-"),j=Number.parseInt(J?I.slice(0,-1):I,10);if(!Number.isNaN(j)){let X=this.ctx.state.fileDescriptors.get(j)??`__dupin__:${j}`;this.ctx.state.fileDescriptors.set(L,X),J&&this.ctx.state.fileDescriptors.delete(j)}}}for(let[w,I]of r)I===void 0?this.ctx.state.env.delete(w):this.ctx.state.env.set(w,I);if(this.ctx.state.tempExportedVars)for(let w of r.keys())this.ctx.state.tempExportedVars.delete(w);return B()}r.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(r)));let P,N=null,M=h?[1,2].filter($=>{let k=m.bindings.get($),O=h.channels.bindings.get($);return k?.sink!==O?.sink||Me(m,$)!==Me(h.channels,$)}):[];try{try{let $=()=>this.runCommand(u,f,d,S??he(E),!1,!1,l);P=h?await K(this.ctx,h.channels,$):await $()}catch($){let k=null;if(h&&(k=(await K(this.ctx,h.channels,()=>Ze(this.ctx,$,M))).writeFailure,k&&(P=k)),!k)if($ instanceof Ae||$ instanceof Ce)N=$,P=B();else throw $}if(P.exitCode===127&&Ge.has(u)&&h?.channels.bindings.get(1)?.descriptor==="__file__:/dev/full"&&(P=G(`
|
|
687
|
+
`)),h&&M.length>0&&(P=await K(this.ctx,h.channels,()=>te(this.ctx,()=>Promise.resolve(P),M))),N)throw N;if(f.length>0){let $=H(f[f.length-1]);if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test($)){let k=$.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);k&&($=k[1])}this.ctx.state.lastArg=F($)}else this.ctx.state.lastArg=F(u)}finally{let $=Kr(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!$)for(let[O,D]of r)this.ctx.state.fullyUnsetLocals?.has(O)||(D===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,D));if(this.ctx.state.tempExportedVars)for(let O of r.keys())this.ctx.state.tempExportedVars.delete(O);r.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop()}return P}async runCommand(t,s,n,r,i=!1,a=!1,o=-1){let l={ctx:this.ctx,runCommand:(u,f,d,p,m,h,v)=>this.runCommand(u,f,d,p,m,h,v),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(u,f,d)=>this.executeUserScript(u,f,d??A())},c=await Ii(l,t,s,n,r,i,a,o);return c!==null?c:Di(l,t,s,r,a)}aliasExpansionStack=new Set;expandAlias(t){return Js(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Ps(this.ctx,t)}async executeSubshell(t,s=A()){return Gi(this.ctx,t,s,n=>this.executeStatement(n))}async executeGroup(t,s=A()){return qi(this.ctx,t,s,n=>this.executeStatement(n))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,n=await xe(this.ctx,s,t.redirections);if(n.error)return K(this.ctx,n.channels,()=>te(this.ctx,()=>Promise.resolve(n.error)));let r=[1,2].filter(i=>{let a=s.bindings.get(i),o=n.channels.bindings.get(i);return a?.sink!==o?.sink||Me(s,i)!==Me(n.channels,i)});return K(this.ctx,n.channels,async()=>{let i;try{let a=await Q(this.ctx,t.expression.expression);i=ae(a!==0)}catch(a){i=C(`bash: arithmetic expression: ${a.message}
|
|
688
|
+
`)}return r.length>0?te(this.ctx,()=>Promise.resolve(i),r):i})}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,n=await xe(this.ctx,s,t.redirections);if(n.error)return K(this.ctx,n.channels,()=>te(this.ctx,()=>Promise.resolve(n.error)));let r=[1,2].filter(i=>{let a=s.bindings.get(i),o=n.channels.bindings.get(i);return a?.sink!==o?.sink||Me(s,i)!==Me(n.channels,i)});return K(this.ctx,n.channels,async()=>{let i;try{let a=await Xe(this.ctx,t.expression);i=ae(a)}catch(a){let o=a instanceof Ye?1:2;i=C(`bash: conditional expression: ${a.message}
|
|
689
|
+
`,o)}return r.length>0?te(this.ctx,()=>Promise.resolve(i),r):i})}};var ye={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:3e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxConcurrentJobs:128};function Ji(e){return e?{maxCallDepth:e.maxCallDepth??ye.maxCallDepth,maxCommandCount:e.maxCommandCount??ye.maxCommandCount,maxLoopIterations:e.maxLoopIterations??ye.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??ye.maxAwkIterations,maxSedIterations:e.maxSedIterations??ye.maxSedIterations,maxJqIterations:e.maxJqIterations??ye.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??ye.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??ye.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??ye.maxGlobOperations,maxStringLength:e.maxStringLength??ye.maxStringLength,maxArrayElements:e.maxArrayElements??ye.maxArrayElements,maxHeredocSize:e.maxHeredocSize??ye.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??ye.maxSubstitutionDepth,maxConcurrentJobs:e.maxConcurrentJobs??ye.maxConcurrentJobs}:{...ye}}function Xi(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Ba(e){let t=Xi(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Ha(e,t){let s=Xi(e);if(!s)return!1;let n=Ba(t);return!n||s.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:s.pathname.startsWith(n.pathPrefix)}function Jn(e,t){return!t||t.length===0?!1:t.some(s=>Ha(e,s))}var Vt=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},zt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},jt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},xs=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},Bt=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Ua=20,Ga=3e4,qa=10485760,Za=["GET","HEAD"],Ja=new Set(["GET","HEAD","OPTIONS"]),Xa=new Set([301,302,303,307,308]);function Xn(e){let t=e.maxRedirects??Ua,s=e.timeoutMs??Ga,n=e.maxResponseSize??qa,r=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??Za;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!Jn(l,e.allowedUrlPrefixes??[]))throw new Vt(l)}function a(l){if(e.dangerouslyAllowFullInternetAccess)return;let c=l.toUpperCase();if(!r.includes(c))throw new xs(c,r)}async function o(l,c={}){let u=c.method?.toUpperCase()??"GET";i(l),a(u);let f=l,d=0,p=c.followRedirects??!0,m=c.timeoutMs!==void 0?Math.min(c.timeoutMs,s):s;for(;;){let h=new AbortController,v=setTimeout(()=>h.abort(),m);try{let S={method:u,headers:c.headers,signal:h.signal,redirect:"manual"};c.body&&!Ja.has(u)&&(S.body=c.body);let E=await fetch(f,S);if(Xa.has(E.status)&&p){let b=E.headers.get("location");if(!b)return await Ki(E,f,n);let g=new URL(b,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!Jn(g,e.allowedUrlPrefixes??[]))throw new jt(g);if(d++,d>t)throw new zt(t);f=g;continue}return await Ki(E,f,n)}finally{clearTimeout(v)}}}return o}async function Ki(e,t,s){let n=Object.create(null);if(e.headers.forEach((i,a)=>{n[a.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let a=parseInt(i,10);if(!Number.isNaN(a)&&a>s)throw new Bt(s)}}let r;if(s>0&&e.body){let i=e.body.getReader(),a=new TextDecoder,o=[],l=0;for(;;){let{done:c,value:u}=await i.read();if(c)break;if(l+=u.byteLength,l>s)throw i.cancel(),new Bt(s);o.push(a.decode(u,{stream:!0}))}o.push(a.decode()),r=o.join("")}else r=await e.text();return{status:e.status,statusText:e.statusText,headers:n,body:r,url:t}}var Ka=1e3,Ya=4096,Qa=globalThis.setTimeout.bind(globalThis),el=globalThis.clearTimeout.bind(globalThis),Os=class{jobs=new Map;reapedWaitStatuses=new Map;reapedWaitLineages=new Map;reapedJobNumbers=new Map;options;nextPid=Ka;nextLineageId=1;highestJobNumber=0;runningJobs=0;disposed=!1;disposePromise;constructor(t={}){this.options=t}start(t,s,n){if(this.disposed)throw new Error("Cannot start a job on a disposed ProcessTable");let r=this.nextPid++,i=new AbortController,a=this.highestJobNumber+1,o={info:{pid:r,command:t,startedAt:Date.now(),state:"running"},jobNumber:a,lineageId:n,controller:i,promise:Promise.resolve(0)};return this.jobs.set(r,o),this.highestJobNumber=a,this.runningJobs++,o.promise=Promise.resolve().then(()=>s(r,i.signal)).catch(()=>i.signal.aborted?rr(i.signal.reason):1).then(l=>{let c=this.jobs.get(r)===o;c&&this.runningJobs--,o.info={...o.info,state:"done",exitCode:l},o.controller=void 0,o.promise=void 0,c&&(this.rememberWaitStatus(r,l,o.lineageId,o.jobNumber),this.deleteJobs([r]));try{Promise.resolve(this.options.onJobExit?.(r,l)).catch(()=>{})}catch{}return l}),r}list(){return[...this.jobs.values()].sort((t,s)=>t.jobNumber-s.jobNumber).map(t=>({...t.info}))}listJobs(t,s={}){let n=[...this.jobs.values()].sort((o,l)=>o.jobNumber-l.jobNumber),r=n.at(-1)?.info.pid,i=n.at(-2)?.info.pid,a=[];for(let o of n)t&&!t.has(o.info.pid)||s.runningOnly&&o.info.state!=="running"||s.stoppedOnly||s.changedOnly&&o.changedStateReported===o.info.state||(a.push({...o.info,jobNumber:o.jobNumber,marker:o.info.pid===r?"+":o.info.pid===i?"-":" "}),s.changedOnly&&(o.changedStateReported=o.info.state));return a}get(t){let s=this.jobs.get(t)?.info;return s?{...s}:void 0}kill(t,s,n){let r=this.jobs.get(t);return!r||r.info.state==="done"?!1:(s!=="SIGSTOP"&&s!=="SIGCONT"&&r.controller?.abort(n??s),!0)}async wait(t){if(t!==void 0){let r=this.jobs.get(t);if(!r)return this.reapedWaitStatuses.get(t)??127;let i=r.info.state==="done"?r.info.exitCode??1:await(r.promise??Promise.resolve(1));return this.jobs.get(t)===r&&(this.rememberWaitStatus(t,i,r.lineageId),this.deleteJobs([t])),i}let s=[...this.jobs.values()],n=new Set([...this.reapedWaitStatuses.keys(),...s.map(r=>r.info.pid)]);s.length>0&&(await Promise.all(s.map(r=>r.promise??Promise.resolve(r.info.exitCode??1))),this.deleteJobs(s.map(r=>r.info.pid)));for(let r of n)this.forgetWaitStatus(r);return 0}async waitForLineage(t){let s=new Set;for(;;){let n=[...this.jobs.values()].filter(r=>r.lineageId===t);if(n.length===0)break;await Promise.all(n.map(r=>r.promise??Promise.resolve(r.info.exitCode??1)));for(let r of n)s.add(r.info.pid);this.deleteJobs(n.map(r=>r.info.pid))}for(let[n,r]of this.reapedWaitLineages)r===t&&s.add(n);for(let n of s)this.forgetWaitStatus(n);return 0}createLineageId(){return this.nextLineageId++}abortAll(t="SIGTERM"){for(let s of this.jobs.values())s.info.state==="running"&&s.controller?.abort(t)}dispose(){if(this.disposePromise)return this.disposePromise;this.disposed=!0;let t=[...this.jobs.values()],s=()=>{};this.disposePromise=new Promise(r=>{s=r}),this.abortAll("SIGKILL"),this.jobs.clear(),this.reapedWaitStatuses.clear(),this.reapedWaitLineages.clear(),this.reapedJobNumbers.clear(),this.highestJobNumber=0,this.runningJobs=0;let n=Qa(s,this.options.disposeTimeoutMs??1e3);return n.unref?.(),Promise.allSettled(t.flatMap(r=>r.promise?[r.promise]:[])).then(()=>{el(n),s()}),this.disposePromise}get runningCount(){return this.runningJobs}getJobNumber(t){return this.jobs.get(t)?.jobNumber}canWait(t){return this.jobs.has(t)||this.reapedWaitStatuses.has(t)}resolveJobSpec(t){let s=[...this.jobs.values()].sort((i,a)=>i.jobNumber-a.jobNumber);if(t==="%+"||t==="%%")return s.at(-1)?.info.pid;if(t==="%-")return(s.at(-2)??s.at(-1))?.info.pid;let n=/^%(\d+)$/.exec(t);if(!n)return;let r=Number.parseInt(n[1],10);return s.find(i=>i.jobNumber===r)?.info.pid??this.reapedJobNumbers.get(r)}get observesOutput(){return this.options.onJobOutput!==void 0}observeOutput(t,s,n){try{Promise.resolve(this.options.onJobOutput?.(t,s,n)).catch(()=>{})}catch{}}rememberWaitStatus(t,s,n,r){if(this.forgetWaitStatus(t),this.reapedWaitStatuses.set(t,s),this.reapedWaitLineages.set(t,n),r!==void 0&&this.reapedJobNumbers.set(r,t),this.reapedWaitStatuses.size>Ya){let i=this.reapedWaitStatuses.keys().next().value;i!==void 0&&this.forgetWaitStatus(i)}}forgetWaitStatus(t){this.reapedWaitStatuses.delete(t),this.reapedWaitLineages.delete(t);for(let[s,n]of this.reapedJobNumbers)n===t&&this.reapedJobNumbers.delete(s)}deleteJobs(t){let s=!1;for(let n of t){let r=this.jobs.get(n);r&&(this.jobs.delete(n),s||=r.jobNumber===this.highestJobNumber)}if(s){this.highestJobNumber=0;for(let n of this.jobs.values())this.highestJobNumber=Math.max(this.highestJobNumber,n.jobNumber)}}};function Yi(){let e=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables"},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"}];try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let t=Object.getPrototypeOf(async function*(){}).constructor;t&&t!==Function&&t!==Object.getPrototypeOf(async()=>{}).constructor&&e.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}return e.filter(t=>{try{return t.target[t.prop]!==void 0}catch{return!1}})}var Ht=typeof __BROWSER__<"u"&&__BROWSER__;function Qi(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Yn=null;if(!Ht)try{let e="node:module",{createRequire:t}=await import(e);Yn=t(import.meta.url)("node:async_hooks").AsyncLocalStorage}catch(e){console.debug("[DefenseInDepthBox] AsyncLocalStorage not available, defense-in-depth disabled:",e instanceof Error?e.message:e)}var tl=`
|
|
690
|
+
|
|
691
|
+
This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,ge=class extends Error{violation;constructor(t,s){super(t+tl),this.violation=s,this.name="SecurityViolationError"}},Ee=!Ht&&Yn?new Yn:null,sl=1e3,Kn={enabled:!0,auditMode:!1};function nl(e){return e===void 0?{...Kn,enabled:!1}:typeof e=="boolean"?{...Kn,enabled:e}:{...Kn,...e}}var Is=class e{static instance=null;config;refCount=0;originalDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(t){this.config=t}static getInstance(t){return e.instance||(e.instance=new e(nl(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return Ee?Ee?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(Ee)return Ee?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Ht||!this.config.enabled){let s=Qi();return{run:n=>n(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=Qi();return{run:s=>Ee.run({sandboxActive:!0,executionId:t},s),deactivate:()=>{this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0)},executionId:t}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}clearViolations(){this.violations=[]}getPathForTarget(t,s){return t===globalThis?`globalThis.${s}`:t===process?`process.${s}`:t===Error?`Error.${s}`:t===Function.prototype?`Function.prototype.${s}`:t===Object.prototype?`Object.prototype.${s}`:`<object>.${s}`}shouldBlock(){return Ht||this.config.auditMode||!Ee?!1:Ee?.getStore()?.sandboxActive===!0}recordViolation(t,s,n){let r={timestamp:Date.now(),type:t,message:n,path:s,stack:new Error().stack,executionId:Ee?.getStore()?.executionId};if(this.violations.length<sl&&this.violations.push(r),this.config.onViolation)try{this.config.onViolation(r)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return r}createBlockingProxy(t,s,n){let r=this;return new Proxy(t,{apply(i,a,o){if(r.shouldBlock()){let l=`${s} is blocked during script execution`,c=r.recordViolation(n,s,l);throw new ge(l,c)}return r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} called (audit mode)`),Reflect.apply(i,a,o)},construct(i,a,o){if(r.shouldBlock()){let l=`${s} constructor is blocked during script execution`,c=r.recordViolation(n,s,l);throw new ge(l,c)}return r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} constructor called (audit mode)`),Reflect.construct(i,a,o)}})}createBlockingObjectProxy(t,s,n){let r=this;return new Proxy(t,{get(i,a,o){if(r.shouldBlock()){let l=`${s}.${String(a)}`,c=`${l} is blocked during script execution`,u=r.recordViolation(n,l,c);throw new ge(c,u)}if(r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0){let l=`${s}.${String(a)}`;r.recordViolation(n,l,`${l} accessed (audit mode)`)}return Reflect.get(i,a,o)},set(i,a,o,l){if(r.shouldBlock()){let c=`${s}.${String(a)}`,u=`${c} modification is blocked during script execution`,f=r.recordViolation(n,c,u);throw new ge(u,f)}return Reflect.set(i,a,o,l)},ownKeys(i){if(r.shouldBlock()){let a=`${s} enumeration is blocked during script execution`,o=r.recordViolation(n,s,a);throw new ge(a,o)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} descriptor access is blocked during script execution`,c=r.recordViolation(n,o,l);throw new ge(l,c)}return Reflect.getOwnPropertyDescriptor(i,a)},has(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} existence check is blocked during script execution`,c=r.recordViolation(n,o,l);throw new ge(l,c)}return Reflect.has(i,a)}})}applyPatches(){let t=Yi();for(let s of t)this.applyPatch(s);this.protectConstructorChain(),this.protectErrorPrepareStackTrace(),this.protectModuleLoad(),this.protectProcessMainModule()}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(async function*(){}).constructor,s=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&t!==s&&this.patchPrototypeConstructor(t.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}}protectErrorPrepareStackTrace(){let t=this;try{let s=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:s});let n=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return n},set(r){if(t.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",a=t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new ge(i,a)}t.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),n=r},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,n){let r=this;try{let i=Object.getOwnPropertyDescriptor(t,"constructor");this.originalDescriptors.push({target:t,prop:"constructor",descriptor:i});let a=i?.value;Object.defineProperty(t,"constructor",{get(){if(r.shouldBlock()){let o=`${s} access is blocked during script execution`,l=r.recordViolation(n,s,o);throw new ge(o,l)}return r.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} accessed (audit mode)`),a},set(o){if(r.shouldBlock()){let l=`${s} modification is blocked during script execution`,c=r.recordViolation(n,s,l);throw new ge(l,c)}Object.defineProperty(this,"constructor",{value:o,writable:!0,configurable:!0})},configurable:!0})}catch(i){console.debug(`[DefenseInDepthBox] Could not patch ${s}:`,i instanceof Error?i.message:i)}}protectProcessMainModule(){if(typeof process>"u")return;let t=this;try{let s=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:s});let n=s?.value;n!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let r="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",r);throw new ge(r,i)}return t.config.auditMode&&Ee?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),n},set(r){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",a=t.recordViolation("process_main_module","process.mainModule",i);throw new ge(i,a)}Object.defineProperty(process,"mainModule",{value:r,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Ht)try{let t=null;if(typeof process<"u"){let a=process.mainModule;a&&typeof a=="object"&&(t=a.constructor)}if(!t&&typeof Ut<"u"&&typeof Ut.main<"u"&&(t=Ut.main.constructor),!t||typeof t._load!="function")return;let s=t._load,n=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:n});let i=this.createBlockingProxy(s,"Module._load","module_load");Object.defineProperty(t,"_load",{value:i,writable:!0,configurable:!0})}catch(t){console.debug("[DefenseInDepthBox] Could not protect Module._load:",t instanceof Error?t.message:t)}}applyPatch(t){let{target:s,prop:n,violationType:r,strategy:i}=t;try{let a=s[n];if(a===void 0)return;let o=Object.getOwnPropertyDescriptor(s,n);if(this.originalDescriptors.push({target:s,prop:n,descriptor:o}),i==="freeze")typeof a=="object"&&a!==null&&Object.freeze(a);else{let l=this.getPathForTarget(s,n),c=typeof a=="function"?this.createBlockingProxy(a,l,r):this.createBlockingObjectProxy(a,l,r);Object.defineProperty(s,n,{value:c,writable:!0,configurable:!0})}}catch(a){let o=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not patch ${o}:`,a instanceof Error?a.message:a)}}restorePatches(){for(let t=this.originalDescriptors.length-1;t>=0;t--){let{target:s,prop:n,descriptor:r}=this.originalDescriptors[t];try{r?Object.defineProperty(s,n,r):delete s[n]}catch(i){let a=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not restore ${a}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var rl=globalThis.setTimeout.bind(globalThis),Ds=class{fs;processes;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Tt(t.files);this.fs=s,this.processes=t.processes??new Os,this.useDefaultLayout=!t.cwd&&!t.files;let n=t.cwd||(this.useDefaultLayout?"/home/user":"/"),r=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
692
|
+
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",n],["OLDPWD",n],["OPTIND","1"]];for(let[a,o]of i)y(r,a,o);for(let[a,o]of Object.entries(t.env??{}))y(r,a,o);if(this.limits=Ji({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.network&&(this.secureFetch=Xn(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth,this.coverageWriter=t.coverage,this.state={env:r,cwd:n,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:R,startTime:Date.now(),lastBackgroundPid:0,bashPid:Ls().pid,nextVirtualPid:Ls().pid+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},y(this.state.env,"SHELLOPTS",Gs(this.state.options)),y(this.state.env,"BASHOPTS",qs(this.state.shoptOptions)),Nr(s,this.useDefaultLayout),n!=="/"&&s instanceof Tt)try{s.mkdirSync(n,{recursive:!0})}catch{}for(let a of $r(t.commands))this.registerCommand(a);if(t.network)for(let a of Ar())this.registerCommand(a);if(t.python)for(let a of Cr())this.registerCommand(a);if(t.customCommands)for(let a of t.customCommands)kr(a)?this.registerCommand(Pr(a)):this.registerCommand(a)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let n=`#!/bin/bash
|
|
693
693
|
# Built-in command: ${t.name}
|
|
694
|
-
`;try{s.writeFileSync(`/bin/${t.name}`,n)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,n)}catch{}}}logResult(t,s,n){try{let r=this.logger;if(r){let i=s.text(),a=n.text();i.length>0&&r.debug("stdout",{output:i}),a.length>0&&r.info("stderr",{output:a}),r.info("exit",{exitCode:t.exitCode})}return{...t,stdout:s.stream(),stderr:n.stream()}}finally{s.seal(),n.seal()}}async exec(t,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:
|
|
695
|
-
`),exitCode:1,env:Pe(this.state.env,s?.env)};if(!t.trim())return{stdout:
|
|
696
|
-
`)),this.logResult({exitCode:1,env:Pe(this.state.env,s?.env)},i,a);if(
|
|
697
|
-
`)),this.logResult({exitCode:1,env:Pe(this.state.env,s?.env)},i,a);if(
|
|
698
|
-
`)),this.logResult({exitCode:2,env:Pe(this.state.env,s?.env)},i,a);if(
|
|
699
|
-
`)),this.logResult({exitCode:2,env:Pe(this.state.env,s?.env)},i,a);if(
|
|
700
|
-
`)),this.logResult({exitCode:1,env:Pe(this.state.env,s?.env)},i,a);throw
|
|
701
|
-
`),s=[],n=[];for(let r=0;r<t.length;r++){let i=t[r];if(n.length>0){let l=n[n.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.delimiter){s.push(i.trimStart()),n.pop();continue}s.push(i);continue}let a=i.trimStart();s.push(a);let o=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let l of a.matchAll(o)){let
|
|
702
|
-
`)}import*as ne from"node:fs";import*as wt from"node:path";var tl="/home/user/project";function fe(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Rs=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=wt.resolve(t.root);let s=t.mountPoint??tl;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,!ne.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ne.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split("/").filter(Boolean),s="";for(let n of t)s+=`/${n}`,this.memory.has(s)||this.memory.set(s,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,s){let r=this.normalizePath(t).split("/").filter(Boolean),i="";for(let a of r)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let n=this.normalizePath(t),r=this.getDirname(n);r!=="/"&&this.mkdirSync(r);let{chunks:i,size:a}=lt(s);this.memory.set(n,{type:"file",chunks:i,size:a,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=this.normalizePath(t),n=this.getRelativeToMount(s);if(n===null)return null;let r=wt.join(this.root,n),i=wt.resolve(r);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(t);s!=="/"&&(this.memory.has(s)||(this.ensureParentDirs(s),this.memory.set(s,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(s))}async existsInOverlay(t){let s=this.normalizePath(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let n=this.toRealPath(s);if(!n)return!1;try{return await ne.promises.access(n),!0}catch{return!1}}async readFile(t){let s=await this.readFileChunks(t);return Et(s)}async readRange(t,s,n){Qt(s,n);let r=await this.resolveForRead(t);if(r.kind==="memory")return es(r.chunks,r.size,s,n);if(n===0||s>=r.size)return new Uint8Array(0);let i=Math.min(n,r.size-s),a=new Uint8Array(i),o=await ne.promises.open(r.realPath,"r");try{let{bytesRead:l}=await o.read(a,0,i,s);return l===i?a:a.subarray(0,l)}finally{await o.close()}}async resolveForRead(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.resolveForRead(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return{kind:"memory",chunks:r.chunks,size:r.size}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let o=await ne.promises.readlink(i),l=this.resolveSymlink(n,o);return this.resolveForRead(l,s)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);return{kind:"real",realPath:i,size:a.size}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async readFileText(t,s){let n=await this.readFileChunks(t),r=Ue(s);return Xt(n,r)}async readFileChunks(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.readFileChunks(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return r.chunks}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let c=await ne.promises.readlink(i),f=this.resolveSymlink(n,c);return this.readFileChunks(f,s)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);let o=await ne.promises.readFile(i),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),{chunks:u}=lt(l);return u}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async writeFile(t,s,n){fe(t,"write"),this.assertWritable(`write '${t}'`);let r=this.normalizePath(t);this.ensureParentDirs(r);let i=Ue(n),{chunks:a,size:o}=await ct(s,i);this.memory.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date}),this.deleted.delete(r)}async appendFile(t,s,n){fe(t,"append"),this.assertWritable(`append '${t}'`);let r=this.normalizePath(t),i=Ue(n),{chunks:a,size:o}=await ct(s,i),l=[],u=0;try{l=await this.readFileChunks(r);for(let c of l)u+=c.length}catch{}this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:[...l,...a],size:u+o,mode:420,mtime:new Date}),this.deleted.delete(r)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){fe(t,"stat");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let o=this.resolveSymlink(n,r.target);return this.stat(o,s)}let a=0;return r.type==="file"&&(a=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:a,mtime:r.mtime}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await ne.promises.stat(i);return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):a}}async lstat(t){fe(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let n=this.memory.get(s);if(n){if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime};let i=0;return n.type==="file"&&(i=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:i,mtime:n.mtime}}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ne.promises.lstat(r);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):i}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}async mkdir(t,s){fe(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let n=this.normalizePath(t);if(await this.existsInOverlay(n)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(n);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(n,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(n)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Map,r=new Set,i=s==="/"?"/":`${s}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),u=l.split("/")[0];u&&!l.includes("/",u.length)&&r.add(u)}for(let[o,l]of this.memory)if(o!==s&&o.startsWith(i)){let u=o.slice(i.length),c=u.split("/")[0];c&&!r.has(c)&&!u.includes("/",1)&&n.set(c,{name:c,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.toRealPath(s);if(a)try{let o=await ne.promises.readdir(a,{withFileTypes:!0});for(let l of o)!r.has(l.name)&&!n.has(l.name)&&n.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(o){if(o.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else if(o.code!=="ENOTDIR")throw o}return n}async resolveForReaddir(t,s=!1){let n=this.normalizePath(t),r=new Set,i=s,a=this.memory.get(n);for(;a&&a.type==="symlink";){if(r.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(n),i=!0,n=this.resolveSymlink(n,a.target),a=this.memory.get(n)}if(a)return{normalized:n,outsideOverlay:!1};if(this.getRelativeToMount(n)===null)return{normalized:n,outsideOverlay:!0};let l=this.toRealPath(n);if(!l)return{normalized:n,outsideOverlay:!0};try{if((await ne.promises.lstat(l)).isSymbolicLink()){let c=await ne.promises.readlink(l),f=this.resolveSymlink(n,c);return this.resolveForReaddir(f,!0)}return{normalized:n,outsideOverlay:!1}}catch{return i?{normalized:n,outsideOverlay:!0}:{normalized:n,outsideOverlay:!1}}}async readdir(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){fe(t,"rm"),this.assertWritable(`rm '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(n)).isDirectory){let a=await this.readdir(n);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=n==="/"?`/${o}`:`${n}/${o}`;await this.rm(l,s)}}}}catch{}this.deleted.add(n),this.memory.delete(n)}async cp(t,s,n){fe(t,"cp"),fe(s,"cp"),this.assertWritable(`cp '${s}'`);let r=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r);await this.writeFile(i,Et(l))}else if(o.isDirectory){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(r);for(let u of l){let c=r==="/"?`/${u}`:`${r}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(c,f,n)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let n=this.toRealPath(t);if(n)try{let r=ne.readdirSync(n);for(let i of r){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=wt.join(n,i);ne.statSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){fe(t,"chmod"),this.assertWritable(`chmod '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(n);if(i){i.mode=s;return}let a=await this.stat(n);if(a.isFile){let o=await this.readFileChunks(n),l=0;for(let u of o)l+=u.length;this.memory.set(n,{type:"file",chunks:o,size:l,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){fe(s,"symlink"),this.assertWritable(`symlink '${s}'`);let n=this.normalizePath(s);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.memory.set(n,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(n)}async link(t,s){fe(t,"link"),fe(s,"link"),this.assertWritable(`link '${s}'`);let n=this.normalizePath(t),r=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(n);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileChunks(n),u=0;for(let c of l)u+=c.length;this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:l,size:u,mode:a.mode,mtime:new Date}),this.deleted.delete(r)}async readlink(t){fe(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let n=this.memory.get(s);if(n){if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ne.promises.readlink(r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):i.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):i}}async realpath(t){fe(t,"realpath");let s=this.normalizePath(t),n=new Set,r=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),u="";for(let c of l){if(u=`${u}/${c}`,n.has(u))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(u))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(u),d=0,p=40;for(;f&&f.type==="symlink"&&d<p;){if(n.add(u),u=this.resolveSymlink(u,f.target),d++,n.has(u))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(u))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(u)}if(d>=p)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let m=this.toRealPath(u);if(m)try{if((await ne.promises.lstat(m)).isSymbolicLink()){let b=await ne.promises.readlink(m);return n.add(u),u=this.resolveSymlink(u,b),r(u)}}catch(h){throw h.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):h}}}return u||"/"},i=await r(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,n){fe(t,"utimes"),this.assertWritable(`utimes '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(r);if(a){a.mtime=n;return}let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r),u=0;for(let c of l)u+=c.length;this.memory.set(r,{type:"file",chunks:l,size:u,mode:o.mode,mtime:n})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:o.mode,mtime:n})}};var de={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"},Qn=class{env;rl;running=!0;history=[];isInteractive;constructor(t={}){let s=process.cwd(),n=new Rs({root:s,mountPoint:"/"});this.env=new Is({fs:n,cwd:t.cwd||"/",env:{HOME:"/",USER:"user",SHELL:"/bin/bash",TERM:"xterm-256color",...t.env},network:t.network!==!1?{dangerouslyAllowFullInternetAccess:!0}:void 0}),this.isInteractive=process.stdin.isTTY===!0,this.rl=to.createInterface({input:process.stdin,output:process.stdout,terminal:this.isInteractive}),this.rl.on("SIGINT",()=>{process.stdout.write(`^C
|
|
694
|
+
`;try{s.writeFileSync(`/bin/${t.name}`,n)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,n)}catch{}}}logResult(t,s,n){try{let r=this.logger;if(r){let i=s.text(),a=n.text();i.length>0&&r.debug("stdout",{output:i}),a.length>0&&r.info("stderr",{output:a}),r.info("exit",{exitCode:t.exitCode})}return{...t,stdout:s.stream(),stderr:n.stream()}}finally{s.seal(),n.seal()}}async exec(t,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:A(),stderr:V(`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
695
|
+
`),exitCode:1,env:Pe(this.state.env,s?.env)};if(!t.trim())return{stdout:A(),stderr:A(),exitCode:0,env:Pe(this.state.env,s?.env)};if(s?.signal?.aborted)return{stdout:A(),stderr:A(),exitCode:new me(s.signal.reason).exitCode,env:Pe(this.state.env,s?.env)};let n=new Set,r=b=>{if(b)return{async write(g){try{await b.write(g)}catch(P){throw n.add(P),P}}}},i=_e(r(s?.stdoutSink)),a=_e(r(s?.stderrSink)),o=s?.processes??this.processes,l=s?.lineageId??o.createLineageId(),c=s?.jobTracker??{started:!1,limitExceeded:!1};this.logger?.info("exec",{command:t});let u=s?.cwd??this.state.cwd,f,d=u;if(s?.cwd)if(s.env&&"PWD"in s.env)f=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{f=await this.fs.realpath(u),d=f}catch{f=u}else f=u;let p=new Map(this.state.env);if(s?.env)for(let[b,g]of Object.entries(s.env))y(p,b,g);f!==void 0&&y(p,"PWD",f);let m={...this.state,env:p,cwd:d,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},fileDescriptors:this.state.fileDescriptors?new Map(this.state.fileDescriptors):void 0,hashTable:this.state.hashTable,groupStdin:s?.stdin||void 0},h=t;s?.rawScript||(h=il(t));let S=(this.defenseInDepthConfig?Is.getInstance(this.defenseInDepthConfig):null)?.activate(),E=!1;try{let b=async()=>{let g=Le(h);E=!0;let P={fs:this.fs,commands:this.commands,outputChannels:{bindings:new Map([[1,{sink:i}],[2,{sink:a}]])},limits:this.limits,jobTracker:c,processes:o,lineageId:l,exec:($,k)=>this.exec($,{...k,jobTracker:c,processes:o,signal:Ct(s?.signal,k?.signal)}),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,signal:s?.signal},M=await new Ft(P,m).executeRootScript(g);return c.started&&(await new Promise($=>rl($,0)),c.limitExceeded&&(M={...M,exitCode:oe.EXIT_CODE})),this.logResult(M,i,a)};return S?await S.run(b):await b()}catch(b){if(n.has(b))throw b;if(b instanceof q)return this.logResult({exitCode:b.exitCode,env:Pe(this.state.env,s?.env)},i,a);if(b instanceof ve)return this.logResult({exitCode:b.exitCode,env:Pe(this.state.env,s?.env)},i,a);if(b instanceof Ye)return E||await a.write(F(`bash: ${b.message}
|
|
696
|
+
`)),this.logResult({exitCode:1,env:Pe(this.state.env,s?.env)},i,a);if(b instanceof me)return this.logResult({exitCode:b.exitCode,env:Pe(this.state.env,s?.env)},i,a);if(b instanceof oe)return this.logResult({exitCode:oe.EXIT_CODE,env:Pe(this.state.env,s?.env)},i,a);if(b instanceof ge)return await a.write(F(`bash: security violation: ${b.message}
|
|
697
|
+
`)),this.logResult({exitCode:1,env:Pe(this.state.env,s?.env)},i,a);if(b.name==="ParseException")return await a.write(F(`bash: syntax error: ${b.message}
|
|
698
|
+
`)),this.logResult({exitCode:2,env:Pe(this.state.env,s?.env)},i,a);if(b instanceof lr)return await a.write(F(`bash: ${b.message}
|
|
699
|
+
`)),this.logResult({exitCode:2,env:Pe(this.state.env,s?.env)},i,a);if(b instanceof RangeError)return await a.write(F(`bash: ${b.message}
|
|
700
|
+
`)),this.logResult({exitCode:1,env:Pe(this.state.env,s?.env)},i,a);throw b}finally{S?.deactivate()}}async readFile(t){return this.fs.readFileText(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,s){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),s)}getCwd(){return this.state.cwd}getEnv(){return qe(this.state.env)}};function il(e){let t=e.split(`
|
|
701
|
+
`),s=[],n=[];for(let r=0;r<t.length;r++){let i=t[r];if(n.length>0){let l=n[n.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.delimiter){s.push(i.trimStart()),n.pop();continue}s.push(i);continue}let a=i.trimStart();s.push(a);let o=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let l of a.matchAll(o)){let c=l[1]==="-",u=l[3];n.push({delimiter:u,stripTabs:c})}}return s.join(`
|
|
702
|
+
`)}import*as ne from"node:fs";import*as wt from"node:path";var ol="/home/user/project";function fe(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Rs=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=wt.resolve(t.root);let s=t.mountPoint??ol;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,!ne.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ne.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split("/").filter(Boolean),s="";for(let n of t)s+=`/${n}`,this.memory.has(s)||this.memory.set(s,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,s){let r=this.normalizePath(t).split("/").filter(Boolean),i="";for(let a of r)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let n=this.normalizePath(t),r=this.getDirname(n);r!=="/"&&this.mkdirSync(r);let{chunks:i,size:a}=lt(s);this.memory.set(n,{type:"file",chunks:i,size:a,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=this.normalizePath(t),n=this.getRelativeToMount(s);if(n===null)return null;let r=wt.join(this.root,n),i=wt.resolve(r);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(t);s!=="/"&&(this.memory.has(s)||(this.ensureParentDirs(s),this.memory.set(s,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(s))}async existsInOverlay(t){let s=this.normalizePath(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let n=this.toRealPath(s);if(!n)return!1;try{return await ne.promises.access(n),!0}catch{return!1}}async readFile(t){let s=await this.readFileChunks(t);return Et(s)}async readRange(t,s,n){es(s,n);let r=await this.resolveForRead(t);if(r.kind==="memory")return ts(r.chunks,r.size,s,n);if(n===0||s>=r.size)return new Uint8Array(0);let i=Math.min(n,r.size-s),a=new Uint8Array(i),o=await ne.promises.open(r.realPath,"r");try{let{bytesRead:l}=await o.read(a,0,i,s);return l===i?a:a.subarray(0,l)}finally{await o.close()}}async resolveForRead(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.resolveForRead(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return{kind:"memory",chunks:r.chunks,size:r.size}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let o=await ne.promises.readlink(i),l=this.resolveSymlink(n,o);return this.resolveForRead(l,s)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);return{kind:"real",realPath:i,size:a.size}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async readFileText(t,s){let n=await this.readFileChunks(t),r=Ue(s);return Qt(n,r)}async readFileChunks(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.readFileChunks(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return r.chunks}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let u=await ne.promises.readlink(i),f=this.resolveSymlink(n,u);return this.readFileChunks(f,s)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);let o=await ne.promises.readFile(i),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),{chunks:c}=lt(l);return c}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async writeFile(t,s,n){fe(t,"write"),this.assertWritable(`write '${t}'`);let r=this.normalizePath(t);this.ensureParentDirs(r);let i=Ue(n),{chunks:a,size:o}=await ct(s,i);this.memory.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date}),this.deleted.delete(r)}async appendFile(t,s,n){fe(t,"append"),this.assertWritable(`append '${t}'`);let r=this.normalizePath(t),i=Ue(n),{chunks:a,size:o}=await ct(s,i),l=[],c=0;try{l=await this.readFileChunks(r);for(let u of l)c+=u.length}catch{}this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:[...l,...a],size:c+o,mode:420,mtime:new Date}),this.deleted.delete(r)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){fe(t,"stat");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let o=this.resolveSymlink(n,r.target);return this.stat(o,s)}let a=0;return r.type==="file"&&(a=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:a,mtime:r.mtime}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await ne.promises.stat(i);return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):a}}async lstat(t){fe(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let n=this.memory.get(s);if(n){if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime};let i=0;return n.type==="file"&&(i=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:i,mtime:n.mtime}}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ne.promises.lstat(r);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):i}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}async mkdir(t,s){fe(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let n=this.normalizePath(t);if(await this.existsInOverlay(n)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(n);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(n,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(n)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Map,r=new Set,i=s==="/"?"/":`${s}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&r.add(c)}for(let[o,l]of this.memory)if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!r.has(u)&&!c.includes("/",1)&&n.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.toRealPath(s);if(a)try{let o=await ne.promises.readdir(a,{withFileTypes:!0});for(let l of o)!r.has(l.name)&&!n.has(l.name)&&n.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(o){if(o.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else if(o.code!=="ENOTDIR")throw o}return n}async resolveForReaddir(t,s=!1){let n=this.normalizePath(t),r=new Set,i=s,a=this.memory.get(n);for(;a&&a.type==="symlink";){if(r.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(n),i=!0,n=this.resolveSymlink(n,a.target),a=this.memory.get(n)}if(a)return{normalized:n,outsideOverlay:!1};if(this.getRelativeToMount(n)===null)return{normalized:n,outsideOverlay:!0};let l=this.toRealPath(n);if(!l)return{normalized:n,outsideOverlay:!0};try{if((await ne.promises.lstat(l)).isSymbolicLink()){let u=await ne.promises.readlink(l),f=this.resolveSymlink(n,u);return this.resolveForReaddir(f,!0)}return{normalized:n,outsideOverlay:!1}}catch{return i?{normalized:n,outsideOverlay:!0}:{normalized:n,outsideOverlay:!1}}}async readdir(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){fe(t,"rm"),this.assertWritable(`rm '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(n)).isDirectory){let a=await this.readdir(n);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=n==="/"?`/${o}`:`${n}/${o}`;await this.rm(l,s)}}}}catch{}this.deleted.add(n),this.memory.delete(n)}async cp(t,s,n){fe(t,"cp"),fe(s,"cp"),this.assertWritable(`cp '${s}'`);let r=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r);await this.writeFile(i,Et(l))}else if(o.isDirectory){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(r);for(let c of l){let u=r==="/"?`/${c}`:`${r}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,n)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let n=this.toRealPath(t);if(n)try{let r=ne.readdirSync(n);for(let i of r){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=wt.join(n,i);ne.statSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){fe(t,"chmod"),this.assertWritable(`chmod '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(n);if(i){i.mode=s;return}let a=await this.stat(n);if(a.isFile){let o=await this.readFileChunks(n),l=0;for(let c of o)l+=c.length;this.memory.set(n,{type:"file",chunks:o,size:l,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){fe(s,"symlink"),this.assertWritable(`symlink '${s}'`);let n=this.normalizePath(s);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.memory.set(n,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(n)}async link(t,s){fe(t,"link"),fe(s,"link"),this.assertWritable(`link '${s}'`);let n=this.normalizePath(t),r=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(n);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileChunks(n),c=0;for(let u of l)c+=u.length;this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:l,size:c,mode:a.mode,mtime:new Date}),this.deleted.delete(r)}async readlink(t){fe(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let n=this.memory.get(s);if(n){if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ne.promises.readlink(r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):i.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):i}}async realpath(t){fe(t,"realpath");let s=this.normalizePath(t),n=new Set,r=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,n.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,p=40;for(;f&&f.type==="symlink"&&d<p;){if(n.add(c),c=this.resolveSymlink(c,f.target),d++,n.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=p)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let m=this.toRealPath(c);if(m)try{if((await ne.promises.lstat(m)).isSymbolicLink()){let v=await ne.promises.readlink(m);return n.add(c),c=this.resolveSymlink(c,v),r(c)}}catch(h){throw h.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):h}}}return c||"/"},i=await r(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,n){fe(t,"utimes"),this.assertWritable(`utimes '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(r);if(a){a.mtime=n;return}let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r),c=0;for(let u of l)c+=u.length;this.memory.set(r,{type:"file",chunks:l,size:c,mode:o.mode,mtime:n})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:o.mode,mtime:n})}};var de={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"},Qn=class{env;rl;running=!0;history=[];isInteractive;constructor(t={}){let s=process.cwd(),n=new Rs({root:s,mountPoint:"/"});this.env=new Ds({fs:n,cwd:t.cwd||"/",env:{HOME:"/",USER:"user",SHELL:"/bin/bash",TERM:"xterm-256color",...t.env},network:t.network!==!1?{dangerouslyAllowFullInternetAccess:!0}:void 0}),this.isInteractive=process.stdin.isTTY===!0,this.rl=to.createInterface({input:process.stdin,output:process.stdout,terminal:this.isInteractive}),this.rl.on("SIGINT",()=>{process.stdout.write(`^C
|
|
703
703
|
`),this.prompt()}),process.stdin.isTTY&&this.rl.on("close",()=>{this.running=!1,console.log(`
|
|
704
|
-
Goodbye!`),process.exit(0)})}syncHistory(){let t=this.env.getEnv();t.BASH_HISTORY=JSON.stringify(this.history)}getPrompt(){let t=this.env.getCwd(),s=this.env.getEnv().HOME||"/home/user",n=t;return t===s?n="~":t.startsWith(`${s}/`)&&(n=`~${t.slice(s.length)}`),`${de.green}${de.bold}user@virtual${de.reset}:${de.blue}${de.bold}${n}${de.reset}$ `}async executeCommand(t){let s=t.trim();if(s){if(this.history.push(s),s==="exit"||s.startsWith("exit ")){let n=s.split(/\s+/),r=n[1]?parseInt(n[1],10):0;console.log("exit"),process.exit(r)}this.syncHistory();try{let n=await this.env.exec(s);for await(let i of
|
|
704
|
+
Goodbye!`),process.exit(0)})}syncHistory(){let t=this.env.getEnv();t.BASH_HISTORY=JSON.stringify(this.history)}getPrompt(){let t=this.env.getCwd(),s=this.env.getEnv().HOME||"/home/user",n=t;return t===s?n="~":t.startsWith(`${s}/`)&&(n=`~${t.slice(s.length)}`),`${de.green}${de.bold}user@virtual${de.reset}:${de.blue}${de.bold}${n}${de.reset}$ `}async executeCommand(t){let s=t.trim();if(s){if(this.history.push(s),s==="exit"||s.startsWith("exit ")){let n=s.split(/\s+/),r=n[1]?parseInt(n[1],10):0;console.log("exit"),process.exit(r)}this.syncHistory();try{let n=await this.env.exec(s);for await(let i of Gt(n.stdout))process.stdout.write(i);let r=await tr(n.stderr);r.length>0&&process.stderr.write(`${de.red}${r}${de.reset}`)}catch(n){console.error(`${de.red}Error: ${Oe(n)}${de.reset}`)}}}printWelcome(){console.log(`
|
|
705
705
|
${de.cyan}${de.bold}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
706
706
|
\u2551 Virtual Shell v1.0 \u2551
|
|
707
707
|
\u2551 A simulated bash environment in TypeScript \u2551
|
|
@@ -711,7 +711,7 @@ ${de.dim}Exploring: ${process.cwd()}${de.reset}
|
|
|
711
711
|
|
|
712
712
|
Type ${de.green}help${de.reset} for available commands, ${de.green}exit${de.reset} to quit.
|
|
713
713
|
Reads from real filesystem, writes stay in memory (OverlayFs).
|
|
714
|
-
`)}prompt(){this.rl.question(this.getPrompt(),async t=>{this.running&&(await this.executeCommand(t),this.prompt())})}async run(){if(this.isInteractive)this.printWelcome(),this.prompt();else{let t=[];this.rl.on("line",s=>{t.push(s)}),await new Promise(s=>{this.rl.on("close",s)});for(let s of t)await this.executeCommand(s)}}};function
|
|
714
|
+
`)}prompt(){this.rl.question(this.getPrompt(),async t=>{this.running&&(await this.executeCommand(t),this.prompt())})}async run(){if(this.isInteractive)this.printWelcome(),this.prompt();else{let t=[];this.rl.on("line",s=>{t.push(s)}),await new Promise(s=>{this.rl.on("close",s)});for(let s of t)await this.executeCommand(s)}}};function al(){let e=process.argv.slice(2),t={network:!0};for(let s=0;s<e.length;s++)if(e[s]==="--cwd"&&e[s+1])t.cwd=e[++s];else if(e[s]==="--files"&&e[s+1]){let n=e[++s];try{let r=eo.readFileSync(n,"utf-8");t.files=JSON.parse(r)}catch(r){console.error(`Error reading files from ${n}:`,r),process.exit(1)}}else e[s]==="--no-network"?t.network=!1:(e[s]==="--help"||e[s]==="-h")&&(console.log(`
|
|
715
715
|
Usage: pnpm shell [options]
|
|
716
716
|
|
|
717
717
|
Interactive shell using OverlayFs - reads from the current directory,
|
|
@@ -725,4 +725,4 @@ Options:
|
|
|
725
725
|
Example:
|
|
726
726
|
pnpm shell
|
|
727
727
|
pnpm shell --no-network
|
|
728
|
-
`),process.exit(0));return t}var
|
|
728
|
+
`),process.exit(0));return t}var ll=al(),cl=new Qn(ll);cl.run();
|