just-binary 2.9.8 → 2.9.9

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.
Files changed (33) hide show
  1. package/dist/bin/chunks/base64-XCZKQZ7Z.js +2 -0
  2. package/dist/bin/chunks/chunk-RUESYAVK.js +2 -0
  3. package/dist/bin/chunks/chunk-S23TISYL.js +6 -0
  4. package/dist/bin/{shell/chunks/chunk-CRHN4WNQ.js → chunks/chunk-ZD5OTNAU.js} +17 -17
  5. package/dist/bin/{shell/chunks/flag-coverage-DBKGNLJO.js → chunks/flag-coverage-RODPAQVH.js} +1 -1
  6. package/dist/bin/chunks/tar-IQNZQP7E.js +2 -0
  7. package/dist/bin/just-bash.js +97 -97
  8. package/dist/bin/shell/chunks/base64-XCZKQZ7Z.js +2 -0
  9. package/dist/bin/shell/chunks/chunk-RUESYAVK.js +2 -0
  10. package/dist/bin/shell/chunks/chunk-S23TISYL.js +6 -0
  11. package/dist/bin/{chunks/chunk-CRHN4WNQ.js → shell/chunks/chunk-ZD5OTNAU.js} +17 -17
  12. package/dist/bin/{chunks/flag-coverage-DBKGNLJO.js → shell/chunks/flag-coverage-RODPAQVH.js} +1 -1
  13. package/dist/bin/shell/chunks/tar-IQNZQP7E.js +2 -0
  14. package/dist/bin/shell/shell.js +97 -97
  15. package/dist/bundle/browser.js +426 -426
  16. package/dist/bundle/chunks/base64-5E5MPPWD.js +1 -0
  17. package/dist/bundle/chunks/chunk-DQTFPKDH.js +5 -0
  18. package/dist/bundle/chunks/chunk-MIFIRXNI.js +1 -0
  19. package/dist/bundle/chunks/{chunk-3OY3UJDR.js → chunk-ZCZOV2DS.js} +17 -17
  20. package/dist/bundle/chunks/{flag-coverage-FMTW4YWD.js → flag-coverage-LGRO7HFL.js} +1 -1
  21. package/dist/bundle/chunks/tar-K64VDNWF.js +1 -0
  22. package/dist/bundle/index.js +96 -96
  23. package/dist/utils/binary-string.d.ts +1 -0
  24. package/package.json +31 -29
  25. package/dist/bin/chunks/base64-DNX4WCIO.js +0 -2
  26. package/dist/bin/chunks/chunk-6CZOPIZD.js +0 -6
  27. package/dist/bin/chunks/tar-2UVSVD3P.js +0 -2
  28. package/dist/bin/shell/chunks/base64-DNX4WCIO.js +0 -2
  29. package/dist/bin/shell/chunks/chunk-6CZOPIZD.js +0 -6
  30. package/dist/bin/shell/chunks/tar-2UVSVD3P.js +0 -2
  31. package/dist/bundle/chunks/base64-RY5JPAQL.js +0 -1
  32. package/dist/bundle/chunks/chunk-N4GRDEVJ.js +0 -5
  33. package/dist/bundle/chunks/tar-7KN7KZ6S.js +0 -1
@@ -1,20 +1,20 @@
1
- import{A as fs,C as _r,D as kr,E as de,F as Be,G as se,H as Pe,I as Ct,J as Cr,K as L,L as xr,M as Nr,N as Ce,O as ds,P as xt,Q as Ye,R as Z,a as gr,b as os,c as wr,d as vr,e as _t,f as J,g as H,h as Ae,i as re,j as _e,k as Le,l as as,m as kt,n as br,o as ls,p as Er,q as fe,r as Oe,s as $r,t as Sr,u as cs,v as us,w as ke,x as Pr,y as Ar,z as Se}from"./chunks/chunk-Q3TLRYBC.js";import{a as Fe,b as $e}from"./chunks/chunk-QEKGAAIL.js";import{a as dt}from"./chunks/chunk-YNYSPYQ5.js";import{a as ye,b as ge,c as ue,d as ve,e as mr,f as G,g as Ve,h as St,i as Pt,j as yr,k as ae,l as Me,m as At,n as Ee}from"./chunks/chunk-PTELGM2J.js";import"./chunks/chunk-NUFRM6SI.js";import{a as Te}from"./chunks/chunk-44UOCSGV.js";import{a as ft,g as p,h as E,i as z,j as x,k as qe,l as Ze,m as N,n as w,o as pr}from"./chunks/chunk-O7N2RCS7.js";var je=[{name:"echo",load:async()=>(await import("./chunks/echo-TR3BM2AJ.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-WUR2OJUG.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-WOYMDX2I.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-6BM6G675.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-I3BZBLTZ.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-5HDB4IQ7.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-ATQADRUQ.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-JMWEKCU4.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-W5HXJH5J.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-76WRD5SE.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-BWYUCELO.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-LTQYKUUW.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-BE3B3ZPG.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-QI6K7ZZX.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-KBQT2JAC.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-YGDXZZGG.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-22EISCPD.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-DIMPSC6S.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-D6AI423Z.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-D6AI423Z.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-D6AI423Z.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-CNS6SD3V.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-CSUGXVBJ.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-UIH6CPHX.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-BIWEEIVX.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-XS6VGRO2.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-FPLN4BYY.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-VNFQFCA7.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-C6JKQOHO.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-QVFN4YWH.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-2FZQEIQG.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-77Q7V2GV.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-L4U6GS2N.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-ZVCJ72RF.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-2WTX7UPB.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-LECMRXOT.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-QUFGLTTX.js")).split},{name:"column",load:async()=>(await import("./chunks/column-S7P64XRJ.js")).column},{name:"join",load:async()=>(await import("./chunks/join-FTSZAZYU.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-J4MBDQJZ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-NAGPRRQ7.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-QT55QR7O.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-V7Z24BGZ.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-IY7WNFVF.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-QKRPQIMY.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-SVQBHVZF.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-SVQBHVZF.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T2KDAHDL.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T2KDAHDL.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-OKEAINJD.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-5MMN7C6P.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-AKKYE7WM.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-AKKYE7WM.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-NLKZY76S.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-BZZ6TUGW.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-BZZ6TUGW.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-TNIKCGGT.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-RY5JPAQL.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-RR5VJXIT.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-EDSSFONA.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-225KIGXI.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-UX2PSLYJ.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-CVS7ESWV.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-UP62NDEL.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-QRA5KFYV.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-ALFVDB3W.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-XXYTWQIW.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-GD6AFWG3.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-TORG4IVZ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-P2LSCPVF.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-F3TJS3LS.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-IWHCX6SW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-A6JKZKWL.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-AGIPNJOC.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-HCON4D7C.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-AA6TIC6A.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-4EFUBHN7.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-4EFUBHN7.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-4EFUBHN7.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(je.push({name:"tar",load:async()=>(await import("./chunks/tar-7KN7KZ6S.js")).tarCommand}),je.push({name:"yq",load:async()=>(await import("./chunks/yq-LQX5YIGM.js")).yqCommand}),je.push({name:"xan",load:async()=>(await import("./chunks/xan-XDECJHII.js")).xanCommand}),je.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-3ZFEGTQ7.js")).sqlite3Command}));var Nt=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Nt.push({name:"python3",load:async()=>(await import("./chunks/python3-QFUFNW7I.js")).python3Command}),Nt.push({name:"python",load:async()=>(await import("./chunks/python3-QFUFNW7I.js")).pythonCommand}));var Or=[{name:"curl",load:async()=>(await import("./chunks/curl-UFR6W4B6.js")).curlCommand}],Tr=new Map;function hs(e){return{name:e.name,async execute(t,s){let r=Tr.get(e.name);if(r||(r=await e.load(),Tr.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-FMTW4YWD.js"),{decodeArgs:i}=await import("./chunks/bytes-W6ESHQ7F.js");n(s.coverage,e.name,i(t))}return r.execute(t,s)}}}function fi(){return je.map(e=>e.name)}function di(){return Or.map(e=>e.name)}function Dr(e){return(e?je.filter(s=>e.includes(s.name)):je).map(hs)}function Ir(){return Or.map(hs)}function hi(){return Nt.map(e=>e.name)}function Rr(){return Nt.map(hs)}function Mr(e){return"load"in e&&typeof e.load=="function"}function pi(e,t){return{name:e,async execute(s,r){let n={...r,env:pr(r.env)},i=await t(Ze(s),n);return typeof i.stdout=="string"?{stdout:E(i.stdout),stderr:E(i.stderr),exitCode:i.exitCode}:i}}}function Fr(e){let t=null;return{name:e.name,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}var mi=new TextEncoder,yi=new TextDecoder;function De(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 r=0;r<e.length;r+=2)s[r/2]=parseInt(e.slice(r,r+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,n=>n.charCodeAt(0));let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}return mi.encode(e)}function Ke(e,t){if(t==="base64")return btoa(String.fromCharCode(...e));if(t==="hex")return Array.from(e).map(s=>s.toString(16).padStart(2,"0")).join("");if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(e).toString(t);let s=65536;if(e.length<=s)return String.fromCharCode(...e);let r="";for(let n=0;n<e.length;n+=s){let i=e.subarray(n,n+s);r+=String.fromCharCode(...i)}return r}return yi.decode(e)}function be(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}var Tt=new TextEncoder;function gi(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}function le(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Ie=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))gi(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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,r,n){le(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let o=be(r),a=De(s,o);this.data.set(i,{type:"file",content:a,mode:n?.mode??420,mtime:n?.mtime??new Date})}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Ke(r,n)}async readFileBuffer(t){le(t,"open");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);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}'`);return r.content instanceof Uint8Array?r.content:Tt.encode(r.content)}async writeFile(t,s,r){this.writeFileSync(t,s,r)}async appendFile(t,s,r){le(t,"append");let n=this.normalizePath(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let o=be(r),a=De(s,o);if(i?.type==="file"){let c=i.content instanceof Uint8Array?i.content:Tt.encode(i.content),u=new Uint8Array(c.length+a.length);u.set(c),u.set(a,c.length),this.data.set(n,{type:"file",content:u,mode:i.mode,mtime:new Date})}else this.writeFileSync(t,s,r)}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){le(t,"stat");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Tt.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){le(t,"lstat");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Tt.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];n=`${n}/${a}`;let c=this.data.get(n),u=0,l=40;for(;c&&c.type==="symlink"&&u<l;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=this.resolveSymlink(n,c.target),c=this.data.get(n),u++}if(u>=l)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let o of r){n=`${n}/${o}`;let a=this.data.get(n),c=0,u=40;for(;a&&a.type==="symlink"&&c<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=this.resolveSymlink(n,a.target),a=this.data.get(n),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){le(t,"mkdir");let r=this.normalizePath(t);if(this.data.has(r)){if(this.data.get(r)?.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 n=this.dirname(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){le(t,"scandir");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=this.resolveSymlink(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,o=new Map;for(let[a,c]of this.data.entries())if(a!==s&&a.startsWith(i)){let u=a.slice(i.length),l=u.split("/")[0];l&&!u.includes("/",l.length)&&!o.has(l)&&o.set(l,{name:l,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}return Array.from(o.values()).sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0)}async rm(t,s){le(t,"rm");let r=this.normalizePath(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of i){let a=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(a,s)}}}this.data.delete(r)}async cp(t,s,r){le(t,"cp"),le(s,"cp");let n=this.normalizePath(t),i=this.normalizePath(s),o=this.data.get(n);if(!o)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(o.type==="file")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(n);for(let c of a){let u=n==="/"?`/${c}`:`${n}/${c}`,l=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,l,r)}}}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 r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}async chmod(t,s){le(t,"chmod");let r=this.normalizePath(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){le(s,"symlink");let r=this.normalizePath(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){le(t,"link"),le(s,"link");let r=this.normalizePath(t),n=this.normalizePath(s),i=this.data.get(r);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(n))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"file",content:i.content,mode:i.mode,mtime:i.mtime})}async readlink(t){le(t,"readlink");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){le(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,r){le(t,"utimes");let n=this.normalizePath(t),i=this.resolvePathWithSymlinks(n),o=this.data.get(i);if(!o)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);o.mtime=r}};function wi(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function vi(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 bi(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 Ei(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${gr}
1
+ import{A as fs,C as kr,D as Cr,E as de,F as Be,G as se,H as Pe,I as Ct,J as xr,K as L,L as Nr,M as Tr,N as Ce,O as ds,P as xt,Q as Ye,R as Z,a as wr,b as os,c as vr,d as br,e as _t,f as J,g as H,h as Ae,i as re,j as _e,k as Le,l as as,m as kt,n as Er,o as ls,p as $r,q as fe,r as Oe,s as Sr,t as Pr,u as cs,v as us,w as ke,x as Ar,y as _r,z as Se}from"./chunks/chunk-Q3TLRYBC.js";import{a as gr}from"./chunks/chunk-MIFIRXNI.js";import{a as Fe,b as $e}from"./chunks/chunk-QEKGAAIL.js";import{a as dt}from"./chunks/chunk-YNYSPYQ5.js";import{a as ye,b as ge,c as ue,d as ve,e as mr,f as G,g as Ve,h as St,i as Pt,j as yr,k as ae,l as Me,m as At,n as Ee}from"./chunks/chunk-PTELGM2J.js";import"./chunks/chunk-NUFRM6SI.js";import{a as Te}from"./chunks/chunk-44UOCSGV.js";import{a as ft,g as p,h as E,i as z,j as x,k as qe,l as Ze,m as N,n as w,o as pr}from"./chunks/chunk-O7N2RCS7.js";var je=[{name:"echo",load:async()=>(await import("./chunks/echo-TR3BM2AJ.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-WUR2OJUG.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-WOYMDX2I.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-6BM6G675.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-I3BZBLTZ.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-5HDB4IQ7.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-ATQADRUQ.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-JMWEKCU4.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-W5HXJH5J.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-76WRD5SE.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-BWYUCELO.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-LTQYKUUW.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-BE3B3ZPG.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-QI6K7ZZX.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-KBQT2JAC.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-YGDXZZGG.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-22EISCPD.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-DIMPSC6S.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-D6AI423Z.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-D6AI423Z.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-D6AI423Z.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-CNS6SD3V.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-CSUGXVBJ.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-UIH6CPHX.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-BIWEEIVX.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-XS6VGRO2.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-FPLN4BYY.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-VNFQFCA7.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-C6JKQOHO.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-QVFN4YWH.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-2FZQEIQG.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-77Q7V2GV.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-L4U6GS2N.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-ZVCJ72RF.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-2WTX7UPB.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-LECMRXOT.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-QUFGLTTX.js")).split},{name:"column",load:async()=>(await import("./chunks/column-S7P64XRJ.js")).column},{name:"join",load:async()=>(await import("./chunks/join-FTSZAZYU.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-J4MBDQJZ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-NAGPRRQ7.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-QT55QR7O.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-V7Z24BGZ.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-IY7WNFVF.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-QKRPQIMY.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-SVQBHVZF.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-SVQBHVZF.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T2KDAHDL.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T2KDAHDL.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-OKEAINJD.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-5MMN7C6P.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-AKKYE7WM.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-AKKYE7WM.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-NLKZY76S.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-BZZ6TUGW.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-BZZ6TUGW.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-TNIKCGGT.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-5E5MPPWD.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-RR5VJXIT.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-EDSSFONA.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-225KIGXI.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-UX2PSLYJ.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-CVS7ESWV.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-UP62NDEL.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-QRA5KFYV.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-ALFVDB3W.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-XXYTWQIW.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-GD6AFWG3.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-TORG4IVZ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-P2LSCPVF.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-F3TJS3LS.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-IWHCX6SW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-A6JKZKWL.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-AGIPNJOC.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-HCON4D7C.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-AA6TIC6A.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-4EFUBHN7.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-4EFUBHN7.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-4EFUBHN7.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(je.push({name:"tar",load:async()=>(await import("./chunks/tar-K64VDNWF.js")).tarCommand}),je.push({name:"yq",load:async()=>(await import("./chunks/yq-LQX5YIGM.js")).yqCommand}),je.push({name:"xan",load:async()=>(await import("./chunks/xan-XDECJHII.js")).xanCommand}),je.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-3ZFEGTQ7.js")).sqlite3Command}));var Nt=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Nt.push({name:"python3",load:async()=>(await import("./chunks/python3-QFUFNW7I.js")).python3Command}),Nt.push({name:"python",load:async()=>(await import("./chunks/python3-QFUFNW7I.js")).pythonCommand}));var Dr=[{name:"curl",load:async()=>(await import("./chunks/curl-UFR6W4B6.js")).curlCommand}],Or=new Map;function hs(e){return{name:e.name,async execute(t,s){let r=Or.get(e.name);if(r||(r=await e.load(),Or.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-LGRO7HFL.js"),{decodeArgs:i}=await import("./chunks/bytes-W6ESHQ7F.js");n(s.coverage,e.name,i(t))}return r.execute(t,s)}}}function di(){return je.map(e=>e.name)}function hi(){return Dr.map(e=>e.name)}function Ir(e){return(e?je.filter(s=>e.includes(s.name)):je).map(hs)}function Rr(){return Dr.map(hs)}function pi(){return Nt.map(e=>e.name)}function Mr(){return Nt.map(hs)}function Fr(e){return"load"in e&&typeof e.load=="function"}function mi(e,t){return{name:e,async execute(s,r){let n={...r,env:pr(r.env)},i=await t(Ze(s),n);return typeof i.stdout=="string"?{stdout:E(i.stdout),stderr:E(i.stderr),exitCode:i.exitCode}:i}}}function Lr(e){let t=null;return{name:e.name,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}var yi=new TextEncoder,gi=new TextDecoder;function De(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 r=0;r<e.length;r+=2)s[r/2]=parseInt(e.slice(r,r+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,n=>n.charCodeAt(0));let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}return yi.encode(e)}function Ke(e,t){if(t==="base64")return btoa(gr(e));if(t==="hex")return Array.from(e).map(s=>s.toString(16).padStart(2,"0")).join("");if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(e).toString(t);let s=65536;if(e.length<=s)return String.fromCharCode(...e);let r="";for(let n=0;n<e.length;n+=s){let i=e.subarray(n,n+s);r+=String.fromCharCode(...i)}return r}return gi.decode(e)}function be(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}var Tt=new TextEncoder;function wi(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}function le(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Ie=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))wi(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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,r,n){le(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let o=be(r),a=De(s,o);this.data.set(i,{type:"file",content:a,mode:n?.mode??420,mtime:n?.mtime??new Date})}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Ke(r,n)}async readFileBuffer(t){le(t,"open");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);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}'`);return r.content instanceof Uint8Array?r.content:Tt.encode(r.content)}async writeFile(t,s,r){this.writeFileSync(t,s,r)}async appendFile(t,s,r){le(t,"append");let n=this.normalizePath(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let o=be(r),a=De(s,o);if(i?.type==="file"){let c=i.content instanceof Uint8Array?i.content:Tt.encode(i.content),u=new Uint8Array(c.length+a.length);u.set(c),u.set(a,c.length),this.data.set(n,{type:"file",content:u,mode:i.mode,mtime:new Date})}else this.writeFileSync(t,s,r)}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){le(t,"stat");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Tt.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){le(t,"lstat");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Tt.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];n=`${n}/${a}`;let c=this.data.get(n),u=0,l=40;for(;c&&c.type==="symlink"&&u<l;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=this.resolveSymlink(n,c.target),c=this.data.get(n),u++}if(u>=l)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let o of r){n=`${n}/${o}`;let a=this.data.get(n),c=0,u=40;for(;a&&a.type==="symlink"&&c<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=this.resolveSymlink(n,a.target),a=this.data.get(n),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){le(t,"mkdir");let r=this.normalizePath(t);if(this.data.has(r)){if(this.data.get(r)?.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 n=this.dirname(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){le(t,"scandir");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=this.resolveSymlink(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,o=new Map;for(let[a,c]of this.data.entries())if(a!==s&&a.startsWith(i)){let u=a.slice(i.length),l=u.split("/")[0];l&&!u.includes("/",l.length)&&!o.has(l)&&o.set(l,{name:l,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}return Array.from(o.values()).sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0)}async rm(t,s){le(t,"rm");let r=this.normalizePath(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of i){let a=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(a,s)}}}this.data.delete(r)}async cp(t,s,r){le(t,"cp"),le(s,"cp");let n=this.normalizePath(t),i=this.normalizePath(s),o=this.data.get(n);if(!o)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(o.type==="file")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(n);for(let c of a){let u=n==="/"?`/${c}`:`${n}/${c}`,l=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,l,r)}}}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 r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}async chmod(t,s){le(t,"chmod");let r=this.normalizePath(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){le(s,"symlink");let r=this.normalizePath(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){le(t,"link"),le(s,"link");let r=this.normalizePath(t),n=this.normalizePath(s),i=this.data.get(r);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(n))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"file",content:i.content,mode:i.mode,mtime:i.mtime})}async readlink(t){le(t,"readlink");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){le(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,r){le(t,"utimes");let n=this.normalizePath(t),i=this.resolvePathWithSymlinks(n),o=this.data.get(i);if(!o)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);o.mtime=r}};function vi(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function bi(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 Ei(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 $i(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${wr}
2
2
  `),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
3
- `),e.writeFileSync("/proc/self/status",wr()),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 Lr(e,t){wi(e)&&(vi(e,t),bi(e),Ei(e))}var $i=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],Si=["braceexpand","hashall","interactive-comments"];function ps(e){let t=[],s=[...Si.map(r=>({name:r,enabled:!0})),...$i.map(r=>({name:r,enabled:e[r]}))].sort((r,n)=>r.name.localeCompare(n.name));for(let r of s)r.enabled&&t.push(r.name);return t.join(":")}function Xe(e){w(e.state.env,"SHELLOPTS",ps(e.state.options))}var Pi=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function ms(e){let t=[];for(let s of Pi)e[s]&&t.push(s);return t.join(":")}function ys(e){w(e.state.env,"BASHOPTS",ms(e.state.shoptOptions))}var Ai="BASH_ALIAS_";function Wr(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function zr(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Vr(e,t){let s=e.env.get(`${Ai}${t}`);return s!==void 0?z(s):void 0}function gs(e,t,s){if(!t.name||!Wr(t.name))return t;let r=zr(t.name);if(!r)return t;let n=Vr(e,r);if(!n||s.has(r))return t;try{s.add(r);let i=new H,o=n,a=n.endsWith(" ");if(!a)for(let f of t.args){let d=jr(f);o+=` ${d}`}let c;try{c=i.parse(o)}catch(f){if(f instanceof _t)throw f;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return Br(t,n);let u=c.statements[0].pipelines[0].commands[0];if(u.type!=="SimpleCommand")return Br(t,n);let l={...u,assignments:[...t.assignments,...u.assignments],redirections:[...u.redirections,...t.redirections],line:t.line};if(a&&t.args.length>0&&(l={...l,args:[...l.args,...t.args]},l.args.length>0)){let f=l.args[0];if(Wr(f)){let d=zr(f);if(d&&Vr(e,d)){let h={type:"SimpleCommand",name:f,args:l.args.slice(1),assignments:[],redirections:[]},g=gs(e,h,s);g!==h&&(l={...l,name:g.name,args:[...g.args]})}}}return l}catch(i){throw s.delete(r),i}}function Br(e,t){let s=t;for(let o of e.args){let a=jr(o);s+=` ${a}`}let r=new H,n=r.parseWordFromString("eval",!1,!1),i=r.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:n,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function jr(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(r=>r.type==="Literal"?r.value:`$${r.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 Hr(e,t){let s=t.parts.map(l=>l.type==="Literal"?l.value:"\0").join(""),r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!s.endsWith(")"))return null;let n=r[1],i=[],o=!1,a="",c=!1;for(let l of t.parts)if(l.type==="Literal"){let f=l.value;if(!o){let d=f.indexOf("=(");d!==-1&&(o=!0,f=f.slice(d+2))}if(o){f.endsWith(")")&&(f=f.slice(0,-1));let d=f.split(/(\s+)/);for(let h of d)/^\s+$/.test(h)?(a||c)&&(i.push(a),a="",c=!1):h&&(a+=h)}}else if(o)if(l.type==="BraceExpansion")if(/^\[.+\]=/.test(a))a+=kt({type:"Word",parts:[l]});else{(a||c)&&(i.push(a),a="",c=!1);let d=await Ce(e,{type:"Word",parts:[l]});i.push(...d.values)}else{(l.type==="SingleQuoted"||l.type==="DoubleQuoted"||l.type==="Escaped")&&(c=!0);let f=await L(e,{type:"Word",parts:[l]});a+=f}(a||c)&&i.push(a);let u=i.map(l=>/^\[.+\]=/.test(l)?l:l===""?"''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(l)&&!l.startsWith("'")&&!l.startsWith('"')?`'${l.replace(/'/g,"'\\''")}'`:l);return`${n}=(${u.join(" ")})`}async function Ur(e,t){let s=-1,r=-1,n=!1;for(let m=0;m<t.parts.length;m++){let v=t.parts[m];if(v.type==="Literal"){let S=v.value.indexOf("+=");if(S!==-1){let C=v.value.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(C)){s=m,r=S,n=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(C)){s=m,r=S,n=!0;break}}let A=v.value.indexOf("=");if(A!==-1&&(A===0||v.value[A-1]!=="+")){let C=v.value.slice(0,A);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(C)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(C)){s=m,r=A;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),o=t.parts[s];if(o.type!=="Literal")return null;let a=n?2:1,c=o.value.slice(0,r),u=o.value.slice(r+a),l=t.parts.slice(s+1),f="";for(let m of i)f+=await L(e,{type:"Word",parts:[m]});f+=c;let d={type:"Word",parts:u!==""?[{type:"Literal",value:u},...l]:l},h=d.parts.length>0?await L(e,d):"";return`${f}${n?"+=":"="}${h}`}var _i=["tar","yq","xan","sqlite3","python3","python"];function Gr(e){return _i.includes(e)}var V=Object.freeze({stdout:p,stderr:p,exitCode:0});function we(e=p){return{stdout:e,stderr:p,exitCode:0}}function U(e){return{stdout:E(e),stderr:p,exitCode:0}}function _(e,t=1){return{stdout:p,stderr:E(e),exitCode:t}}function O(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function Q(e){return{stdout:p,stderr:p,exitCode:e?0:1}}function Re(e,t,s=p,r=p){throw new ae(e,t,s,r)}function ws(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Me;return V}if(t.length>1)throw new G(1,p,E(`bash: break: too many arguments
3
+ `),e.writeFileSync("/proc/self/status",vr()),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 Wr(e,t){vi(e)&&(bi(e,t),Ei(e),$i(e))}var Si=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],Pi=["braceexpand","hashall","interactive-comments"];function ps(e){let t=[],s=[...Pi.map(r=>({name:r,enabled:!0})),...Si.map(r=>({name:r,enabled:e[r]}))].sort((r,n)=>r.name.localeCompare(n.name));for(let r of s)r.enabled&&t.push(r.name);return t.join(":")}function Xe(e){w(e.state.env,"SHELLOPTS",ps(e.state.options))}var Ai=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function ms(e){let t=[];for(let s of Ai)e[s]&&t.push(s);return t.join(":")}function ys(e){w(e.state.env,"BASHOPTS",ms(e.state.shoptOptions))}var _i="BASH_ALIAS_";function zr(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Vr(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Br(e,t){let s=e.env.get(`${_i}${t}`);return s!==void 0?z(s):void 0}function gs(e,t,s){if(!t.name||!zr(t.name))return t;let r=Vr(t.name);if(!r)return t;let n=Br(e,r);if(!n||s.has(r))return t;try{s.add(r);let i=new H,o=n,a=n.endsWith(" ");if(!a)for(let f of t.args){let d=Hr(f);o+=` ${d}`}let c;try{c=i.parse(o)}catch(f){if(f instanceof _t)throw f;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return jr(t,n);let u=c.statements[0].pipelines[0].commands[0];if(u.type!=="SimpleCommand")return jr(t,n);let l={...u,assignments:[...t.assignments,...u.assignments],redirections:[...u.redirections,...t.redirections],line:t.line};if(a&&t.args.length>0&&(l={...l,args:[...l.args,...t.args]},l.args.length>0)){let f=l.args[0];if(zr(f)){let d=Vr(f);if(d&&Br(e,d)){let h={type:"SimpleCommand",name:f,args:l.args.slice(1),assignments:[],redirections:[]},g=gs(e,h,s);g!==h&&(l={...l,name:g.name,args:[...g.args]})}}}return l}catch(i){throw s.delete(r),i}}function jr(e,t){let s=t;for(let o of e.args){let a=Hr(o);s+=` ${a}`}let r=new H,n=r.parseWordFromString("eval",!1,!1),i=r.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:n,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Hr(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(r=>r.type==="Literal"?r.value:`$${r.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 Ur(e,t){let s=t.parts.map(l=>l.type==="Literal"?l.value:"\0").join(""),r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!s.endsWith(")"))return null;let n=r[1],i=[],o=!1,a="",c=!1;for(let l of t.parts)if(l.type==="Literal"){let f=l.value;if(!o){let d=f.indexOf("=(");d!==-1&&(o=!0,f=f.slice(d+2))}if(o){f.endsWith(")")&&(f=f.slice(0,-1));let d=f.split(/(\s+)/);for(let h of d)/^\s+$/.test(h)?(a||c)&&(i.push(a),a="",c=!1):h&&(a+=h)}}else if(o)if(l.type==="BraceExpansion")if(/^\[.+\]=/.test(a))a+=kt({type:"Word",parts:[l]});else{(a||c)&&(i.push(a),a="",c=!1);let d=await Ce(e,{type:"Word",parts:[l]});i.push(...d.values)}else{(l.type==="SingleQuoted"||l.type==="DoubleQuoted"||l.type==="Escaped")&&(c=!0);let f=await L(e,{type:"Word",parts:[l]});a+=f}(a||c)&&i.push(a);let u=i.map(l=>/^\[.+\]=/.test(l)?l:l===""?"''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(l)&&!l.startsWith("'")&&!l.startsWith('"')?`'${l.replace(/'/g,"'\\''")}'`:l);return`${n}=(${u.join(" ")})`}async function Gr(e,t){let s=-1,r=-1,n=!1;for(let m=0;m<t.parts.length;m++){let v=t.parts[m];if(v.type==="Literal"){let S=v.value.indexOf("+=");if(S!==-1){let C=v.value.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(C)){s=m,r=S,n=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(C)){s=m,r=S,n=!0;break}}let A=v.value.indexOf("=");if(A!==-1&&(A===0||v.value[A-1]!=="+")){let C=v.value.slice(0,A);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(C)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(C)){s=m,r=A;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),o=t.parts[s];if(o.type!=="Literal")return null;let a=n?2:1,c=o.value.slice(0,r),u=o.value.slice(r+a),l=t.parts.slice(s+1),f="";for(let m of i)f+=await L(e,{type:"Word",parts:[m]});f+=c;let d={type:"Word",parts:u!==""?[{type:"Literal",value:u},...l]:l},h=d.parts.length>0?await L(e,d):"";return`${f}${n?"+=":"="}${h}`}var ki=["tar","yq","xan","sqlite3","python3","python"];function qr(e){return ki.includes(e)}var V=Object.freeze({stdout:p,stderr:p,exitCode:0});function we(e=p){return{stdout:e,stderr:p,exitCode:0}}function U(e){return{stdout:E(e),stderr:p,exitCode:0}}function _(e,t=1){return{stdout:p,stderr:E(e),exitCode:t}}function O(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function Q(e){return{stdout:p,stderr:p,exitCode:e?0:1}}function Re(e,t,s=p,r=p){throw new ae(e,t,s,r)}function ws(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Me;return V}if(t.length>1)throw new G(1,p,E(`bash: break: too many arguments
4
4
  `));let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new G(128,p,E(`bash: break: ${t[0]}: numeric argument required
5
5
  `));s=r}throw new ye(s)}async function vs(e,t){let s,r=!1,n=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")n=!1,i++;else if(t[i]==="-P")n=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let o=t.slice(i);if(o.length===0?s=N(e.state.env,"HOME","/"):o[0]==="~"?s=N(e.state.env,"HOME","/"):o[0]==="-"?(s=e.state.previousDir,r=!0):s=o[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let f=e.state.env.get("CDPATH");if(f){let d=z(f??p).split(":").filter(h=>h);for(let h of d){let g=h.startsWith("/")?`${h}/${s}`:`${e.state.cwd}/${h}/${s}`;try{if((await e.fs.stat(g)).isDirectory){s=g,r=!0;break}}catch{}}}}let c=(s.startsWith("/")?s:`${e.state.cwd}/${s}`).split("/").filter(f=>f&&f!=="."),u="";for(let f of c)if(f==="..")u=u.split("/").slice(0,-1).join("/")||"/";else{u=u?`${u}/${f}`:`/${f}`;try{if(!(await e.fs.stat(u)).isDirectory)return _(`bash: cd: ${s}: Not a directory
6
6
  `)}catch{return _(`bash: cd: ${s}: No such file or directory
7
7
  `)}}let l=u||"/";if(n)try{l=await e.fs.realpath(l)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=l,w(e.state.env,"PWD",e.state.cwd),w(e.state.env,"OLDPWD",e.state.previousDir),r?U(`${l}
8
- `):we()}function bs(e,t){return e.fs.resolvePath(e.state.cwd,t)}var ki=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function Ot(e){return ki.includes(e)}async function Dt(e,t,s){let r=bs(e,s);switch(t){case"-e":case"-a":return e.fs.exists(r);case"-f":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case"-d":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case"-r":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case"-w":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case"-x":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case"-s":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case"-g":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(r);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=>r===i||r.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(r);default:return!1}}var Ci=["-nt","-ot","-ef"];function It(e){return Ci.includes(e)}async function Rt(e,t,s,r){let n=bs(e,s),i=bs(e,r);switch(t){case"-nt":try{let o=await e.fs.stat(n),a=await e.fs.stat(i);return o.mtime>a.mtime}catch{return!1}case"-ot":try{let o=await e.fs.stat(n),a=await e.fs.stat(i);return o.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(n)||!await e.fs.exists(i))return!1;let o=e.fs.resolvePath(e.state.cwd,n),a=e.fs.resolvePath(e.state.cwd,i);return o===a}catch{return!1}default:return!1}}var xi=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function Mt(e){return xi.has(e)}function Ft(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 ht(e){return e==="="||e==="=="||e==="!="}function Lt(e,t,s,r=!1,n=!1,i=!1){if(r){let a=Qe(t,s,n,i);return e==="!="?!a:a}if(n){let a=t.toLowerCase()===s.toLowerCase();return e==="!="?!a:a}let o=t===s;return e==="!="?!o:o}var Ni=new Set(["-z","-n"]);function Wt(e){return Ni.has(e)}function zt(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function Vt(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let r=s[1],n=s[2];if(e.state.associativeArrays?.has(r)){let a=n;return(a.startsWith("'")&&a.endsWith("'")||a.startsWith('"')&&a.endsWith('"'))&&(a=a.slice(1,-1)),a=a.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(c,u)=>N(e.state.env,u)),e.state.env.has(`${r}_${a}`)}let o;try{let a=new H,c=J(a,n);o=await Z(e,c.expression)}catch{if(/^-?\d+$/.test(n))o=Number.parseInt(n,10);else{let a=N(e.state.env,n);o=a?Number.parseInt(a,10):0}}if(o<0){let a=re(e,r),c=e.state.currentLine;if(a.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${c}: ${r}: bad array subscript
8
+ `):we()}function bs(e,t){return e.fs.resolvePath(e.state.cwd,t)}var Ci=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function Ot(e){return Ci.includes(e)}async function Dt(e,t,s){let r=bs(e,s);switch(t){case"-e":case"-a":return e.fs.exists(r);case"-f":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case"-d":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case"-r":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case"-w":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case"-x":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case"-s":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case"-g":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(r);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=>r===i||r.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(r);default:return!1}}var xi=["-nt","-ot","-ef"];function It(e){return xi.includes(e)}async function Rt(e,t,s,r){let n=bs(e,s),i=bs(e,r);switch(t){case"-nt":try{let o=await e.fs.stat(n),a=await e.fs.stat(i);return o.mtime>a.mtime}catch{return!1}case"-ot":try{let o=await e.fs.stat(n),a=await e.fs.stat(i);return o.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(n)||!await e.fs.exists(i))return!1;let o=e.fs.resolvePath(e.state.cwd,n),a=e.fs.resolvePath(e.state.cwd,i);return o===a}catch{return!1}default:return!1}}var Ni=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function Mt(e){return Ni.has(e)}function Ft(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 ht(e){return e==="="||e==="=="||e==="!="}function Lt(e,t,s,r=!1,n=!1,i=!1){if(r){let a=Qe(t,s,n,i);return e==="!="?!a:a}if(n){let a=t.toLowerCase()===s.toLowerCase();return e==="!="?!a:a}let o=t===s;return e==="!="?!o:o}var Ti=new Set(["-z","-n"]);function Wt(e){return Ti.has(e)}function zt(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function Vt(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let r=s[1],n=s[2];if(e.state.associativeArrays?.has(r)){let a=n;return(a.startsWith("'")&&a.endsWith("'")||a.startsWith('"')&&a.endsWith('"'))&&(a=a.slice(1,-1)),a=a.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(c,u)=>N(e.state.env,u)),e.state.env.has(`${r}_${a}`)}let o;try{let a=new H,c=J(a,n);o=await Z(e,c.expression)}catch{if(/^-?\d+$/.test(n))o=Number.parseInt(n,10);else{let a=N(e.state.env,n);o=a?Number.parseInt(a,10):0}}if(o<0){let a=re(e,r),c=e.state.currentLine;if(a.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${c}: ${r}: bad array subscript
9
9
  `,!1;if(o=Math.max(...a)+1+o,o<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${c}: ${r}: bad array subscript
10
- `,!1}return e.state.env.has(`${r}_${o}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Le(e,t).length>0:re(e,t).length>0}async function We(e,t){switch(t.type){case"CondBinary":{let s=await L(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),n;if(t.operator==="=~")if(r){let i=await L(e,t.right);n=kr(i)}else n=await xr(e,t.right);else ht(t.operator)&&!r?n=await Nr(e,t.right):n=await L(e,t.right);if(ht(t.operator)){let i=e.state.shoptOptions.nocasematch;return Lt(t.operator,s,n,!r,i,!0)}if(Mt(t.operator))return Ft(t.operator,await Zr(e,s),await Zr(e,n));if(It(t.operator))return Rt(e,t.operator,s,n);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,o=Ii(n),c=dt(o,i?"i":"").match(s);if(_e(e,"BASH_REMATCH"),c)for(let u=0;u<c.length;u++)w(e.state.env,`BASH_REMATCH_${u}`,c[u]||"");return c!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<n;case">":return s>n;default:return!1}}case"CondUnary":{let s=await L(e,t.operand);return Ot(t.operator)?Dt(e,t.operator,s):Wt(t.operator)?zt(t.operator,s):t.operator==="-v"?await Vt(e,s):t.operator==="-o"?$s(e,s):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await L(e,t.operand.expression.word)})`!=="":!await We(e,t.operand);case"CondAnd":return await We(e,t.left)?await We(e,t.right):!1;case"CondOr":return await We(e,t.left)?!0:await We(e,t.right);case"CondGroup":return await We(e,t.expression);case"CondWord":return await L(e,t.word)!=="";default:return!1}}async function pt(e,t){if(t.length===0)return O(p,p,1);if(t.length===1)return Q(!!t[0]);if(t.length===2){let r=t[0],n=t[1];return r==="("?_(`test: '(' without matching ')'
10
+ `,!1}return e.state.env.has(`${r}_${o}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Le(e,t).length>0:re(e,t).length>0}async function We(e,t){switch(t.type){case"CondBinary":{let s=await L(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),n;if(t.operator==="=~")if(r){let i=await L(e,t.right);n=Cr(i)}else n=await Nr(e,t.right);else ht(t.operator)&&!r?n=await Tr(e,t.right):n=await L(e,t.right);if(ht(t.operator)){let i=e.state.shoptOptions.nocasematch;return Lt(t.operator,s,n,!r,i,!0)}if(Mt(t.operator))return Ft(t.operator,await Yr(e,s),await Yr(e,n));if(It(t.operator))return Rt(e,t.operator,s,n);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,o=Ri(n),c=dt(o,i?"i":"").match(s);if(_e(e,"BASH_REMATCH"),c)for(let u=0;u<c.length;u++)w(e.state.env,`BASH_REMATCH_${u}`,c[u]||"");return c!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<n;case">":return s>n;default:return!1}}case"CondUnary":{let s=await L(e,t.operand);return Ot(t.operator)?Dt(e,t.operator,s):Wt(t.operator)?zt(t.operator,s):t.operator==="-v"?await Vt(e,s):t.operator==="-o"?$s(e,s):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await L(e,t.operand.expression.word)})`!=="":!await We(e,t.operand);case"CondAnd":return await We(e,t.left)?await We(e,t.right):!1;case"CondOr":return await We(e,t.left)?!0:await We(e,t.right);case"CondGroup":return await We(e,t.expression);case"CondWord":return await L(e,t.word)!=="";default:return!1}}async function pt(e,t){if(t.length===0)return O(p,p,1);if(t.length===1)return Q(!!t[0]);if(t.length===2){let r=t[0],n=t[1];return r==="("?_(`test: '(' without matching ')'
11
11
  `,2):Ot(r)?Q(await Dt(e,r,n)):Wt(r)?Q(zt(r,n)):r==="!"?Q(!n):r==="-v"?Q(await Vt(e,n)):r==="-o"?Q($s(e,n)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?_(`test: ${r}: unary operator expected
12
- `,2):O(p,p,1)}if(t.length===3){let r=t[0],n=t[1],i=t[2];if(ht(n))return Q(Lt(n,r,i));if(Mt(n)){let o=Bt(r),a=Bt(i);return!o.valid||!a.valid?O(p,p,2):Q(Ft(n,o.value,a.value))}if(It(n))return Q(await Rt(e,n,r,i));switch(n){case"-a":return Q(r!==""&&i!=="");case"-o":return Q(r!==""||i!=="");case">":return Q(r>i);case"<":return Q(r<i)}if(r==="!"){let o=await pt(e,[n,i]);return O(p,o.stderr,o.exitCode===0?1:o.exitCode===1?0:o.exitCode)}if(r==="("&&i===")")return Q(n!=="")}if(t.length===4){if(t[0]==="!"){let r=await pt(e,t.slice(1));return O(p,r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return pt(e,[t[1],t[2]])}let s=await Kr(e,t,0);return s.pos<t.length?_(`test: too many arguments
13
- `,2):Q(s.value)}async function Kr(e,t,s){return Ti(e,t,s)}async function Ti(e,t,s){let{value:r,pos:n}=await qr(e,t,s);for(;t[n]==="-o";){let i=await qr(e,t,n+1);r=r||i.value,n=i.pos}return{value:r,pos:n}}async function qr(e,t,s){let{value:r,pos:n}=await Es(e,t,s);for(;t[n]==="-a";){let i=await Es(e,t,n+1);r=r&&i.value,n=i.pos}return{value:r,pos:n}}async function Es(e,t,s){if(t[s]==="!"){let{value:r,pos:n}=await Es(e,t,s+1);return{value:!r,pos:n}}return Oi(e,t,s)}async function Oi(e,t,s){let r=t[s];if(r==="("){let{value:i,pos:o}=await Kr(e,t,s+1);return{value:i,pos:t[o]===")"?o+1:o}}let n=t[s+1];if(ht(n)){let i=r,o=t[s+2]??"";return{value:Lt(n,i,o),pos:s+3}}if(Mt(n)){let i=Bt(r),o=Bt(t[s+2]??"0");return!i.valid||!o.valid?{value:!1,pos:s+3}:{value:Ft(n,i.value,o.value),pos:s+3}}if(It(n)){let i=r,o=t[s+2]??"";return{value:await Rt(e,n,i,o),pos:s+3}}if(Ot(r)){let i=t[s+1]??"";return{value:await Dt(e,r,i),pos:s+2}}if(Wt(r)){let i=t[s+1]??"";return{value:zt(r,i),pos:s+2}}if(r==="-v"){let i=t[s+1]??"";return{value:await Vt(e,i),pos:s+2}}if(r==="-o"){let i=t[s+1]??"";return{value:$s(e,i),pos:s+2}}return{value:r!==void 0&&r!=="",pos:s+1}}function Qe(e,t,s=!1,r=!1){let n=`^${Xr(t,r)}$`;return dt(n,s?"is":"s").test(e)}function Xr(e,t){let s="";for(let r=0;r<e.length;r++){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Qr(e,r+1);if(i!==-1){let o=e.slice(r+2,i),a=Jr(o),c=a.map(l=>Xr(l,t)),u=c.length>0?c.join("|"):"(?:)";if(n==="@")s+=`(?:${u})`;else if(n==="*")s+=`(?:${u})*`;else if(n==="+")s+=`(?:${u})+`;else if(n==="?")s+=`(?:${u})?`;else if(n==="!")if(i<e.length-1){let f=a.map(h=>en(h,t));if(f.every(h=>h!==null)&&f.every(h=>h===f[0])&&f[0]!==null){let h=f[0];if(h===0)s+="(?:.+)";else{let g=[];h>0&&g.push(`.{0,${h-1}}`),g.push(`.{${h+1},}`),g.push(`(?!(?:${u})).{${h}}`),s+=`(?:${g.join("|")})`}}else s+=`(?:(?!(?:${u})).)*?`}else s+=`(?!(?:${u})$).*`;r=i;continue}}if(n==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let i=e.indexOf("]",r+1);i!==-1?(s+=e.slice(r,i+1),r=i):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s}function Qr(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function Jr(e){let t=[],s="",r=0,n=0;for(;n<e.length;){let i=e[n];if(i==="\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i==="("?(r++,s+=i):i===")"?(r--,s+=i):i==="|"&&r===0?(t.push(s),s=""):s+=i,n++}return t.push(s),t}function en(e,t){let s=0,r=0;for(;r<e.length;){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Qr(e,r+1);if(i!==-1){if(n==="@"){let o=e.slice(r+2,i),c=Jr(o).map(u=>en(u,t));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){s+=c[0],r=i+1;continue}return null}return null}}if(n==="*")return null;if(n==="?"){s+=1,r++;continue}if(n==="["){let i=e.indexOf("]",r+1);if(i!==-1){s+=1,r=i+1;continue}s+=1,r++;continue}if(n==="\\"){s+=1,r+=2;continue}s+=1,r++}return s}function $s(e,t){let r=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 r?r():!1}async function Zr(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 Yr(t);try{let s=new H,r=J(s,t);return await Z(e,r.expression)}catch{return Yr(t)}}function Di(e,t){let s=0;for(let r of e){let n;if(r>="0"&&r<="9")n=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")n=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")n=r.charCodeAt(0)-65+36;else if(r==="@")n=62;else if(r==="_")n=63;else return Number.NaN;if(n>=t)return Number.NaN;s=s*t+n}return s}function Yr(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,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=Di(r[2],n):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 Bt(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 Ii(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 r=Ri(e,s);t+=r.converted,s=r.endIndex}else t+=e[s],s++;return t}function Ri(e,t){let s=t+1,r="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(r+="^",s++);let n=!1;s<e.length&&e[s]==="]"&&(n=!0,s++);let i=!1;s<e.length&&e[s]==="["&&s+1<e.length&&e[s+1]!==":"&&(i=!0,s++);let o="",a=!1;for(;s<e.length;){let c=e[s];if(c==="]"){a=!0,s++;break}if(c==="["&&s+1<e.length&&e[s+1]===":"){let u=e.indexOf(":]",s+2);if(u!==-1){let l=e.slice(s+2,u);o+=Mi(l),s=u+2;continue}}if(c==="["&&s+1<e.length){let u=e[s+1];if(u==="."||u==="="){let l=`${u}]`,f=e.indexOf(l,s+2);if(f!==-1){let d=e.slice(s+2,f);o+=d,s=f+2;continue}}}if(c==="\\"&&s+1<e.length){o+=c+e[s+1],s+=2;continue}o+=c,s++}return a?(n&&(r+="\\]"),i&&(r+="\\["),r+=o,r+="]",{converted:r,endIndex:s}):{converted:"\\[",endIndex:t+1}}function Mi(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 xe(e){let t=[],s="",r=!1,n=!1,i=!1,o=!1;for(let a of e){if(i){s+=a,i=!1,o=!0;continue}if(a==="\\"){i=!0;continue}if(a==="'"&&!n){r||(o=!0),r=!r;continue}if(a==='"'&&!r){n||(o=!0),n=!n;continue}if((a===" "||a===" "||a===`
14
- `)&&!r&&!n){o&&(t.push(s),s="",o=!1);continue}s+=a,o=!0}return o&&t.push(s),t}function jt(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 r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)r+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function tn(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:xe(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 r=e.indexOf("=");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function Fi(e,t){try{let s=new H,r=J(s,t);return await Z(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function sn(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:o,arrayIndex:a}=t,{makeReadonly:c=!1,checkReadonly:u=!0}=s;if(u){let l=se(e,r);if(l)return l}if(n&&i){for(let l=0;l<i.length;l++)w(e.state.env,`${r}_${l}`,i[l]);w(e.state.env,`${r}__length`,String(i.length))}else if(a!==void 0&&o!==void 0){let l=await Fi(e,a);w(e.state.env,`${r}_${l}`,o);let f=parseInt(N(e.state.env,`${r}__length`,"0"),10);l>=f&&w(e.state.env,`${r}__length`,String(l+1))}else o!==void 0&&w(e.state.env,r,o);return c&&de(e,r),null}function ze(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function Je(e,t){return e.state.localVarDepth?.get(t)}function Ht(e,t){e.state.localVarDepth?.delete(t)}function rn(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function Ut(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function nn(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var Ss=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function on(e){return Ss.has(e)}var Ps=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),et=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"]);async function He(e,t,s,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
12
+ `,2):O(p,p,1)}if(t.length===3){let r=t[0],n=t[1],i=t[2];if(ht(n))return Q(Lt(n,r,i));if(Mt(n)){let o=Bt(r),a=Bt(i);return!o.valid||!a.valid?O(p,p,2):Q(Ft(n,o.value,a.value))}if(It(n))return Q(await Rt(e,n,r,i));switch(n){case"-a":return Q(r!==""&&i!=="");case"-o":return Q(r!==""||i!=="");case">":return Q(r>i);case"<":return Q(r<i)}if(r==="!"){let o=await pt(e,[n,i]);return O(p,o.stderr,o.exitCode===0?1:o.exitCode===1?0:o.exitCode)}if(r==="("&&i===")")return Q(n!=="")}if(t.length===4){if(t[0]==="!"){let r=await pt(e,t.slice(1));return O(p,r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return pt(e,[t[1],t[2]])}let s=await Xr(e,t,0);return s.pos<t.length?_(`test: too many arguments
13
+ `,2):Q(s.value)}async function Xr(e,t,s){return Oi(e,t,s)}async function Oi(e,t,s){let{value:r,pos:n}=await Zr(e,t,s);for(;t[n]==="-o";){let i=await Zr(e,t,n+1);r=r||i.value,n=i.pos}return{value:r,pos:n}}async function Zr(e,t,s){let{value:r,pos:n}=await Es(e,t,s);for(;t[n]==="-a";){let i=await Es(e,t,n+1);r=r&&i.value,n=i.pos}return{value:r,pos:n}}async function Es(e,t,s){if(t[s]==="!"){let{value:r,pos:n}=await Es(e,t,s+1);return{value:!r,pos:n}}return Di(e,t,s)}async function Di(e,t,s){let r=t[s];if(r==="("){let{value:i,pos:o}=await Xr(e,t,s+1);return{value:i,pos:t[o]===")"?o+1:o}}let n=t[s+1];if(ht(n)){let i=r,o=t[s+2]??"";return{value:Lt(n,i,o),pos:s+3}}if(Mt(n)){let i=Bt(r),o=Bt(t[s+2]??"0");return!i.valid||!o.valid?{value:!1,pos:s+3}:{value:Ft(n,i.value,o.value),pos:s+3}}if(It(n)){let i=r,o=t[s+2]??"";return{value:await Rt(e,n,i,o),pos:s+3}}if(Ot(r)){let i=t[s+1]??"";return{value:await Dt(e,r,i),pos:s+2}}if(Wt(r)){let i=t[s+1]??"";return{value:zt(r,i),pos:s+2}}if(r==="-v"){let i=t[s+1]??"";return{value:await Vt(e,i),pos:s+2}}if(r==="-o"){let i=t[s+1]??"";return{value:$s(e,i),pos:s+2}}return{value:r!==void 0&&r!=="",pos:s+1}}function Qe(e,t,s=!1,r=!1){let n=`^${Qr(t,r)}$`;return dt(n,s?"is":"s").test(e)}function Qr(e,t){let s="";for(let r=0;r<e.length;r++){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Jr(e,r+1);if(i!==-1){let o=e.slice(r+2,i),a=en(o),c=a.map(l=>Qr(l,t)),u=c.length>0?c.join("|"):"(?:)";if(n==="@")s+=`(?:${u})`;else if(n==="*")s+=`(?:${u})*`;else if(n==="+")s+=`(?:${u})+`;else if(n==="?")s+=`(?:${u})?`;else if(n==="!")if(i<e.length-1){let f=a.map(h=>tn(h,t));if(f.every(h=>h!==null)&&f.every(h=>h===f[0])&&f[0]!==null){let h=f[0];if(h===0)s+="(?:.+)";else{let g=[];h>0&&g.push(`.{0,${h-1}}`),g.push(`.{${h+1},}`),g.push(`(?!(?:${u})).{${h}}`),s+=`(?:${g.join("|")})`}}else s+=`(?:(?!(?:${u})).)*?`}else s+=`(?!(?:${u})$).*`;r=i;continue}}if(n==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let i=e.indexOf("]",r+1);i!==-1?(s+=e.slice(r,i+1),r=i):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s}function Jr(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function en(e){let t=[],s="",r=0,n=0;for(;n<e.length;){let i=e[n];if(i==="\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i==="("?(r++,s+=i):i===")"?(r--,s+=i):i==="|"&&r===0?(t.push(s),s=""):s+=i,n++}return t.push(s),t}function tn(e,t){let s=0,r=0;for(;r<e.length;){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Jr(e,r+1);if(i!==-1){if(n==="@"){let o=e.slice(r+2,i),c=en(o).map(u=>tn(u,t));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){s+=c[0],r=i+1;continue}return null}return null}}if(n==="*")return null;if(n==="?"){s+=1,r++;continue}if(n==="["){let i=e.indexOf("]",r+1);if(i!==-1){s+=1,r=i+1;continue}s+=1,r++;continue}if(n==="\\"){s+=1,r+=2;continue}s+=1,r++}return s}function $s(e,t){let r=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 r?r():!1}async function Yr(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 Kr(t);try{let s=new H,r=J(s,t);return await Z(e,r.expression)}catch{return Kr(t)}}function Ii(e,t){let s=0;for(let r of e){let n;if(r>="0"&&r<="9")n=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")n=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")n=r.charCodeAt(0)-65+36;else if(r==="@")n=62;else if(r==="_")n=63;else return Number.NaN;if(n>=t)return Number.NaN;s=s*t+n}return s}function Kr(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,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=Ii(r[2],n):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 Bt(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 Ri(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 r=Mi(e,s);t+=r.converted,s=r.endIndex}else t+=e[s],s++;return t}function Mi(e,t){let s=t+1,r="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(r+="^",s++);let n=!1;s<e.length&&e[s]==="]"&&(n=!0,s++);let i=!1;s<e.length&&e[s]==="["&&s+1<e.length&&e[s+1]!==":"&&(i=!0,s++);let o="",a=!1;for(;s<e.length;){let c=e[s];if(c==="]"){a=!0,s++;break}if(c==="["&&s+1<e.length&&e[s+1]===":"){let u=e.indexOf(":]",s+2);if(u!==-1){let l=e.slice(s+2,u);o+=Fi(l),s=u+2;continue}}if(c==="["&&s+1<e.length){let u=e[s+1];if(u==="."||u==="="){let l=`${u}]`,f=e.indexOf(l,s+2);if(f!==-1){let d=e.slice(s+2,f);o+=d,s=f+2;continue}}}if(c==="\\"&&s+1<e.length){o+=c+e[s+1],s+=2;continue}o+=c,s++}return a?(n&&(r+="\\]"),i&&(r+="\\["),r+=o,r+="]",{converted:r,endIndex:s}):{converted:"\\[",endIndex:t+1}}function Fi(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 xe(e){let t=[],s="",r=!1,n=!1,i=!1,o=!1;for(let a of e){if(i){s+=a,i=!1,o=!0;continue}if(a==="\\"){i=!0;continue}if(a==="'"&&!n){r||(o=!0),r=!r;continue}if(a==='"'&&!r){n||(o=!0),n=!n;continue}if((a===" "||a===" "||a===`
14
+ `)&&!r&&!n){o&&(t.push(s),s="",o=!1);continue}s+=a,o=!0}return o&&t.push(s),t}function jt(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 r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)r+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function sn(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:xe(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 r=e.indexOf("=");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function Li(e,t){try{let s=new H,r=J(s,t);return await Z(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function rn(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:o,arrayIndex:a}=t,{makeReadonly:c=!1,checkReadonly:u=!0}=s;if(u){let l=se(e,r);if(l)return l}if(n&&i){for(let l=0;l<i.length;l++)w(e.state.env,`${r}_${l}`,i[l]);w(e.state.env,`${r}__length`,String(i.length))}else if(a!==void 0&&o!==void 0){let l=await Li(e,a);w(e.state.env,`${r}_${l}`,o);let f=parseInt(N(e.state.env,`${r}__length`,"0"),10);l>=f&&w(e.state.env,`${r}__length`,String(l+1))}else o!==void 0&&w(e.state.env,r,o);return c&&de(e,r),null}function ze(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function Je(e,t){return e.state.localVarDepth?.get(t)}function Ht(e,t){e.state.localVarDepth?.delete(t)}function nn(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function Ut(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function on(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var Ss=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function an(e){return Ss.has(e)}var Ps=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),et=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"]);async function He(e,t,s,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
15
15
  `;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&s!=="/dev/null")return`bash: ${s}: cannot overwrite existing file
16
- `}catch{}return null}function Li(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),c=a.indexOf(":");if(c===-1)return null;let u=Number.parseInt(a.slice(0,c),10);if(Number.isNaN(u)||u<0)return null;let l=a.slice(c+1);return{path:i,position:u,content:l}}async function an(e,t){let s=new Map;for(let r=0;r<t.length;r++){let n=t[r];if(n.target.type==="HereDoc")continue;if(n.operator===">&"||n.operator==="<&"){if(ds(e,n.target))return{targets:s,error:`bash: $@: ambiguous redirect
17
- `};s.set(r,await L(e,n.target))}else{let o=await xt(e,n.target);if("error"in o)return{targets:s,error:o.error};s.set(r,o.target)}}return{targets:s}}function Wi(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd;return e.state.nextFd++,t}async function Gt(e,t){for(let s of t){if(!s.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(s.operator===">&"||s.operator==="<&")&&s.target.type==="Word"&&await L(e,s.target)==="-"){if(e.state.env.has(s.fdVariable)){let i=Number.parseInt(N(e.state.env,s.fdVariable),10);Number.isNaN(i)||e.state.fileDescriptors.delete(i)}continue}let r=Wi(e);if(w(e.state.env,s.fdVariable,String(r)),s.target.type==="Word"){let n=await L(e,s.target);if(s.operator===">&"||s.operator==="<&"){let i=Number.parseInt(n,10);if(!Number.isNaN(i)){let o=e.state.fileDescriptors.get(i);o!==void 0&&e.state.fileDescriptors.set(r,o);continue}}if(s.operator===">"||s.operator===">>"||s.operator===">|"||s.operator==="&>"||s.operator==="&>>"){let i=e.fs.resolvePath(e.state.cwd,n);(s.operator===">"||s.operator===">|"||s.operator==="&>")&&await e.fs.writeFile(i,p),e.state.fileDescriptors.set(r,`__file__:${i}`)}else if(s.operator==="<<<")e.state.fileDescriptors.set(r,`${n}
16
+ `}catch{}return null}function Wi(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),c=a.indexOf(":");if(c===-1)return null;let u=Number.parseInt(a.slice(0,c),10);if(Number.isNaN(u)||u<0)return null;let l=a.slice(c+1);return{path:i,position:u,content:l}}async function ln(e,t){let s=new Map;for(let r=0;r<t.length;r++){let n=t[r];if(n.target.type==="HereDoc")continue;if(n.operator===">&"||n.operator==="<&"){if(ds(e,n.target))return{targets:s,error:`bash: $@: ambiguous redirect
17
+ `};s.set(r,await L(e,n.target))}else{let o=await xt(e,n.target);if("error"in o)return{targets:s,error:o.error};s.set(r,o.target)}}return{targets:s}}function zi(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd;return e.state.nextFd++,t}async function Gt(e,t){for(let s of t){if(!s.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(s.operator===">&"||s.operator==="<&")&&s.target.type==="Word"&&await L(e,s.target)==="-"){if(e.state.env.has(s.fdVariable)){let i=Number.parseInt(N(e.state.env,s.fdVariable),10);Number.isNaN(i)||e.state.fileDescriptors.delete(i)}continue}let r=zi(e);if(w(e.state.env,s.fdVariable,String(r)),s.target.type==="Word"){let n=await L(e,s.target);if(s.operator===">&"||s.operator==="<&"){let i=Number.parseInt(n,10);if(!Number.isNaN(i)){let o=e.state.fileDescriptors.get(i);o!==void 0&&e.state.fileDescriptors.set(r,o);continue}}if(s.operator===">"||s.operator===">>"||s.operator===">|"||s.operator==="&>"||s.operator==="&>>"){let i=e.fs.resolvePath(e.state.cwd,n);(s.operator===">"||s.operator===">|"||s.operator==="&>")&&await e.fs.writeFile(i,p),e.state.fileDescriptors.set(r,`__file__:${i}`)}else if(s.operator==="<<<")e.state.fileDescriptors.set(r,`${n}
18
18
  `);else if(s.operator==="<"||s.operator==="<>")try{let i=e.fs.resolvePath(e.state.cwd,n),o=await e.fs.readFile(i);e.state.fileDescriptors.set(r,o)}catch{return O(p,E(`bash: ${n}: No such file or directory
19
19
  `),1)}}}return null}async function Ne(e,t){for(let s of t){if(s.target.type==="HereDoc")continue;let r=s.operator===">&";if(s.operator!==">"&&s.operator!==">|"&&s.operator!=="&>"&&!r)continue;let n;if(r){if(n=await L(e,s.target),n==="-"||!Number.isNaN(Number.parseInt(n,10))||s.fd!=null)continue}else{let a=await xt(e,s.target);if("error"in a)return O(p,E(a.error),1);n=a.target}let i=e.fs.resolvePath(e.state.cwd,n),o=s.operator===">|";if(i.includes("\0"))return O(p,E(`bash: ${n}: No such file or directory
20
20
  `),1);try{let a=await e.fs.stat(i);if(a.isDirectory)return O(p,E(`bash: ${n}: Is a directory
@@ -27,15 +27,15 @@ import{A as fs,C as _r,D as kr,E as de,F as Be,G as se,H as Pe,I as Ct,J as Cr,K
27
27
  `)),o=1;break}if(f==="/dev/null")i=p;else{let m=e.fs.resolvePath(e.state.cwd,f),v=await He(e,m,f,{checkNoclobber:!0,isClobber:g});if(v){i=x(i,E(v)),o=1;break}await e.fs.writeFile(m,i),i=p}}break}case">>":{let h=l.fd??1;if(h===1){if(f==="/dev/stdout")break;if(f==="/dev/stderr"){i=x(i,n),n=p;break}if(f==="/dev/full"){i=x(i,E(`bash: echo: write error: No space left on device
28
28
  `)),o=1,n=p;break}let g=e.fs.resolvePath(e.state.cwd,f),m=await He(e,g,f,{});if(m){i=x(i,E(m)),o=1,n=p;break}await e.fs.appendFile(g,n),n=p}else if(h===2){if(f==="/dev/stderr")break;if(f==="/dev/stdout"){n=x(n,i),i=p;break}if(f==="/dev/full"){i=x(i,E(`bash: echo: write error: No space left on device
29
29
  `)),o=1;break}let g=e.fs.resolvePath(e.state.cwd,f),m=await He(e,g,f,{});if(m){i=x(i,E(m)),o=1;break}await e.fs.appendFile(g,i),i=p}break}case">&":case"<&":{let h=l.fd??1;if(f==="-")break;if(f.endsWith("-")){let g=f.slice(0,-1),m=Number.parseInt(g,10);if(!Number.isNaN(m)){let v=e.state.fileDescriptors?.get(m);v!==void 0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(h,v),m>=3&&e.state.fileDescriptors?.delete(m)):m===1||m===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(h,`__dupout__:${m}`)):m===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(h,`__dupin__:${m}`)):m>=3&&(i=x(i,E(`bash: ${m}: Bad file descriptor
30
- `)),o=1)}break}if(f==="2"||f==="&2")h===1&&(i=x(i,n),n=p);else if(f==="1"||f==="&1")h===2?(n=x(n,i),i=p):(n=x(n,i),i=p);else{let g=Number.parseInt(f,10);if(Number.isNaN(g)){if(l.operator===">&"){let m=e.fs.resolvePath(e.state.cwd,f),v=await He(e,m,f,{checkNoclobber:!0});if(v){i=E(v),o=1,n=p;break}if(l.fd==null){let S=x(n,i);await e.fs.writeFile(m,S),n=p,i=p}else h===1?(await e.fs.writeFile(m,n),n=p):h===2&&(await e.fs.writeFile(m,i),i=p)}}else{let m=e.state.fileDescriptors?.get(g);if(m?.startsWith("__file__:")){let v=m.slice(9);h===1?(await e.fs.appendFile(v,n),n=p):h===2&&(await e.fs.appendFile(v,i),i=p)}else if(m?.startsWith("__rw__:")){let v=Li(m);v&&(h===1?(await e.fs.appendFile(v.path,n),n=p):h===2&&(await e.fs.appendFile(v.path,i),i=p))}else if(m?.startsWith("__dupout__:")){let v=Number.parseInt(m.slice(11),10);if(v!==1)if(v===2)h===1&&(i=x(i,n),n=p);else{let S=e.state.fileDescriptors?.get(v);if(S?.startsWith("__file__:")){let A=S.slice(9);h===1?(await e.fs.appendFile(A,n),n=p):h===2&&(await e.fs.appendFile(A,i),i=p)}}}else m?.startsWith("__dupin__:")?(i=x(i,E(`bash: ${g}: Bad file descriptor
30
+ `)),o=1)}break}if(f==="2"||f==="&2")h===1&&(i=x(i,n),n=p);else if(f==="1"||f==="&1")h===2?(n=x(n,i),i=p):(n=x(n,i),i=p);else{let g=Number.parseInt(f,10);if(Number.isNaN(g)){if(l.operator===">&"){let m=e.fs.resolvePath(e.state.cwd,f),v=await He(e,m,f,{checkNoclobber:!0});if(v){i=E(v),o=1,n=p;break}if(l.fd==null){let S=x(n,i);await e.fs.writeFile(m,S),n=p,i=p}else h===1?(await e.fs.writeFile(m,n),n=p):h===2&&(await e.fs.writeFile(m,i),i=p)}}else{let m=e.state.fileDescriptors?.get(g);if(m?.startsWith("__file__:")){let v=m.slice(9);h===1?(await e.fs.appendFile(v,n),n=p):h===2&&(await e.fs.appendFile(v,i),i=p)}else if(m?.startsWith("__rw__:")){let v=Wi(m);v&&(h===1?(await e.fs.appendFile(v.path,n),n=p):h===2&&(await e.fs.appendFile(v.path,i),i=p))}else if(m?.startsWith("__dupout__:")){let v=Number.parseInt(m.slice(11),10);if(v!==1)if(v===2)h===1&&(i=x(i,n),n=p);else{let S=e.state.fileDescriptors?.get(v);if(S?.startsWith("__file__:")){let A=S.slice(9);h===1?(await e.fs.appendFile(A,n),n=p):h===2&&(await e.fs.appendFile(A,i),i=p)}}}else m?.startsWith("__dupin__:")?(i=x(i,E(`bash: ${g}: Bad file descriptor
31
31
  `)),o=1,n=p):g>=3&&(i=x(i,E(`bash: ${g}: Bad file descriptor
32
32
  `)),o=1,n=p)}}break}case"&>":{if(f==="/dev/full"){i=E(`bash: echo: write error: No space left on device
33
33
  `),o=1,n=p;break}let h=e.fs.resolvePath(e.state.cwd,f),g=await He(e,h,f,{checkNoclobber:!0});if(g){i=E(g),o=1,n=p;break}let m=x(n,i);await e.fs.writeFile(h,m),n=p,i=p;break}case"&>>":{if(f==="/dev/full"){i=E(`bash: echo: write error: No space left on device
34
- `),o=1,n=p;break}let h=e.fs.resolvePath(e.state.cwd,f),g=await He(e,h,f,{});if(g){i=E(g),o=1,n=p;break}let m=x(n,i);await e.fs.appendFile(h,m),n=p,i=p;break}}}}let a=e.state.fileDescriptors?.get(1);if(a){if(a==="__dupout__:2")i=x(i,n),n=p;else if(a.startsWith("__file__:")){let u=a.slice(9);await e.fs.appendFile(u,n),n=p}else if(a.startsWith("__file_append__:")){let u=a.slice(16);await e.fs.appendFile(u,n),n=p}}let c=e.state.fileDescriptors?.get(2);if(c){if(c==="__dupout__:1")n=x(n,i),i=p;else if(c.startsWith("__file__:")){let u=c.slice(9);await e.fs.appendFile(u,i),i=p}else if(c.startsWith("__file_append__:")){let u=c.slice(16);await e.fs.appendFile(u,i),i=p}}return O(n,i,o)}function ln(e,t){if(e.state.options.posix&&Ss.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
35
- `;throw new G(2,p,E(r))}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),V}async function zi(e,t){let s=p;for(let r of t)if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let n=r.target,i=await L(e,n.content);n.stripTabs&&(i=i.split(`
34
+ `),o=1,n=p;break}let h=e.fs.resolvePath(e.state.cwd,f),g=await He(e,h,f,{});if(g){i=E(g),o=1,n=p;break}let m=x(n,i);await e.fs.appendFile(h,m),n=p,i=p;break}}}}let a=e.state.fileDescriptors?.get(1);if(a){if(a==="__dupout__:2")i=x(i,n),n=p;else if(a.startsWith("__file__:")){let u=a.slice(9);await e.fs.appendFile(u,n),n=p}else if(a.startsWith("__file_append__:")){let u=a.slice(16);await e.fs.appendFile(u,n),n=p}}let c=e.state.fileDescriptors?.get(2);if(c){if(c==="__dupout__:1")n=x(n,i),i=p;else if(c.startsWith("__file__:")){let u=c.slice(9);await e.fs.appendFile(u,i),i=p}else if(c.startsWith("__file_append__:")){let u=c.slice(16);await e.fs.appendFile(u,i),i=p}}return O(n,i,o)}function cn(e,t){if(e.state.options.posix&&Ss.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
35
+ `;throw new G(2,p,E(r))}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),V}async function Vi(e,t){let s=p;for(let r of t)if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let n=r.target,i=await L(e,n.content);n.stripTabs&&(i=i.split(`
36
36
  `).map(a=>a.replace(/^\t+/,"")).join(`
37
37
  `)),(r.fd??0)===0&&(s=E(i))}else if(r.operator==="<<<"&&r.target.type==="Word")s=E(`${await L(e,r.target)}
38
- `);else if(r.operator==="<"&&r.target.type==="Word"){let n=await L(e,r.target),i=e.fs.resolvePath(e.state.cwd,n);try{s=E(await e.fs.readFile(i))}catch{}}return s}async function qt(e,t,s,r=p,n){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(n??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 u=0;u<s.length;u++)i.set(String(u+1),N(e.state.env,String(u+1))),w(e.state.env,String(u+1),s[u]);i.set("@",N(e.state.env,"@")),i.set("#",N(e.state.env,"#")),w(e.state.env,"@",s.join(" ")),w(e.state.env,"#",String(s.length));let o=()=>{let u=e.state.localScopes.length-1,l=e.state.localScopes.pop();if(l)for(let[f,d]of l)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);if(nn(e,u),e.state.fullyUnsetLocals)for(let[f,d]of e.state.fullyUnsetLocals.entries())d===u&&e.state.fullyUnsetLocals.delete(f);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let f=e.state.localExportedVars.pop();if(f)for(let d of f)e.state.exportedVars?.delete(d)}for(let[f,d]of i)d===void 0?e.state.env.delete(f):w(e.state.env,f,d);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:a,error:c}=await an(e,t.redirections);if(c)return o(),O(p,E(c),1);try{let u=await zi(e,t.redirections),l=r.length>0?r:u,f=await e.executeCommand(t.body,l);return o(),Y(e,f,t.redirections,a)}catch(u){if(o(),u instanceof ue){let l=O(u.stdout,u.stderr,u.exitCode);return Y(e,l,t.redirections,a)}throw u}}var un=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],_s=[".",":","[","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"],Vi=["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"],Bi=_s;async function ks(e,t){let s=[],r=null,n="",i="",o=null,a=!1,c=!1,u=!1,l=null,f=null,d=null,h=[],g=["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 y=0;y<t.length;y++){let b=t[y];if(b==="-v")s.push("variable");else if(b==="-e")s.push("export");else if(b==="-f")s.push("file");else if(b==="-d")s.push("directory");else if(b==="-k")s.push("keyword");else if(b==="-A"){if(y++,y>=t.length)return _(`compgen: -A: option requires an argument
38
+ `);else if(r.operator==="<"&&r.target.type==="Word"){let n=await L(e,r.target),i=e.fs.resolvePath(e.state.cwd,n);try{s=E(await e.fs.readFile(i))}catch{}}return s}async function qt(e,t,s,r=p,n){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(n??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 u=0;u<s.length;u++)i.set(String(u+1),N(e.state.env,String(u+1))),w(e.state.env,String(u+1),s[u]);i.set("@",N(e.state.env,"@")),i.set("#",N(e.state.env,"#")),w(e.state.env,"@",s.join(" ")),w(e.state.env,"#",String(s.length));let o=()=>{let u=e.state.localScopes.length-1,l=e.state.localScopes.pop();if(l)for(let[f,d]of l)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);if(on(e,u),e.state.fullyUnsetLocals)for(let[f,d]of e.state.fullyUnsetLocals.entries())d===u&&e.state.fullyUnsetLocals.delete(f);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let f=e.state.localExportedVars.pop();if(f)for(let d of f)e.state.exportedVars?.delete(d)}for(let[f,d]of i)d===void 0?e.state.env.delete(f):w(e.state.env,f,d);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:a,error:c}=await ln(e,t.redirections);if(c)return o(),O(p,E(c),1);try{let u=await Vi(e,t.redirections),l=r.length>0?r:u,f=await e.executeCommand(t.body,l);return o(),Y(e,f,t.redirections,a)}catch(u){if(o(),u instanceof ue){let l=O(u.stdout,u.stderr,u.exitCode);return Y(e,l,t.redirections,a)}throw u}}var fn=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],_s=[".",":","[","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"],Bi=["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"],ji=_s;async function ks(e,t){let s=[],r=null,n="",i="",o=null,a=!1,c=!1,u=!1,l=null,f=null,d=null,h=[],g=["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 y=0;y<t.length;y++){let b=t[y];if(b==="-v")s.push("variable");else if(b==="-e")s.push("export");else if(b==="-f")s.push("file");else if(b==="-d")s.push("directory");else if(b==="-k")s.push("keyword");else if(b==="-A"){if(y++,y>=t.length)return _(`compgen: -A: option requires an argument
39
39
  `,2);let k=t[y];if(!g.includes(k))return _(`compgen: ${k}: invalid action name
40
40
  `,2);s.push(k)}else if(b==="-W"){if(y++,y>=t.length)return _(`compgen: -W: option requires an argument
41
41
  `,2);r=t[y]}else if(b==="-P"){if(y++,y>=t.length)return _(`compgen: -P: option requires an argument
@@ -46,15 +46,15 @@ import{A as fs,C as _r,D as kr,E as de,F as Be,G as se,H as Pe,I as Ct,J as Cr,K
46
46
  `,2);f=t[y]}else if(b==="-C"){if(y++,y>=t.length)return _(`compgen: -C: option requires an argument
47
47
  `,2);d=t[y]}else if(b==="-X"){if(y++,y>=t.length)return _(`compgen: -X: option requires an argument
48
48
  `,2);l=t[y]}else if(b==="-G"){if(y++,y>=t.length)return _(`compgen: -G: option requires an argument
49
- `,2)}else if(b==="--"){h.push(...t.slice(y+1));break}else b.startsWith("-")||h.push(b)}o=h[0]??null;let m=[];if(c){let y=await As(e,o);m.push(...y)}if(u){let y=await cn(e,o);m.push(...y)}for(let y of s)if(y==="variable"){let b=ji(e,o);m.push(...b)}else if(y==="export"){let b=Hi(e,o);m.push(...b)}else if(y==="function"){let b=Ui(e,o);m.push(...b)}else if(y==="builtin"){let b=Gi(o);m.push(...b)}else if(y==="keyword"){let b=qi(o);m.push(...b)}else if(y==="alias"){let b=Zi(e,o);m.push(...b)}else if(y==="shopt"){let b=Yi(o);m.push(...b)}else if(y==="helptopic"){let b=Ki(o);m.push(...b)}else if(y==="directory"){let b=await As(e,o);m.push(...b)}else if(y==="file"){let b=await cn(e,o);m.push(...b)}else if(y==="user"){let b=Xi(o);m.push(...b)}else if(y==="command"){let b=await Qi(e,o);m.push(...b)}if(r!==null)try{let y=await Ji(e,r),b=eo(e,y);for(let k of b)(o===null||k.startsWith(o))&&m.push(k)}catch{return O(p,p,1)}if(a){let y=await As(e,o);for(let b of y)m.includes(b)||m.push(b)}let v="";if(f!==null){let y=e.state.functions.get(f);if(y){let b=new Map;b.set("COMP_WORDS__length",N(e.state.env,"COMP_WORDS__length")),w(e.state.env,"COMP_WORDS__length","0"),b.set("COMP_CWORD",N(e.state.env,"COMP_CWORD")),w(e.state.env,"COMP_CWORD","-1"),b.set("COMP_LINE",N(e.state.env,"COMP_LINE")),w(e.state.env,"COMP_LINE",""),b.set("COMP_POINT",N(e.state.env,"COMP_POINT")),w(e.state.env,"COMP_POINT","0");let k=new Map;for(let M of e.state.env.keys())(M==="COMPREPLY"||M.startsWith("COMPREPLY_")||M==="COMPREPLY__length")&&(k.set(M,N(e.state.env,M)),e.state.env.delete(M));let P=["compgen",h[0]??"",""];try{let M=await qt(e,y,P,p);if(M.exitCode!==0)return tt(e,b),tt(e,k),O(p,M.stderr,1);v=z(M.stdout);let I=to(e);m.push(...I)}catch{return tt(e,b),tt(e,k),O(p,p,1)}tt(e,b),tt(e,k)}}if(d!==null)try{let y=Ae(d),b=await e.executeScript(y);if(b.exitCode!==0)return O(p,b.stderr,b.exitCode);if(b.stdout.length>0){let k=z(b.stdout).split(`
49
+ `,2)}else if(b==="--"){h.push(...t.slice(y+1));break}else b.startsWith("-")||h.push(b)}o=h[0]??null;let m=[];if(c){let y=await As(e,o);m.push(...y)}if(u){let y=await un(e,o);m.push(...y)}for(let y of s)if(y==="variable"){let b=Hi(e,o);m.push(...b)}else if(y==="export"){let b=Ui(e,o);m.push(...b)}else if(y==="function"){let b=Gi(e,o);m.push(...b)}else if(y==="builtin"){let b=qi(o);m.push(...b)}else if(y==="keyword"){let b=Zi(o);m.push(...b)}else if(y==="alias"){let b=Yi(e,o);m.push(...b)}else if(y==="shopt"){let b=Ki(o);m.push(...b)}else if(y==="helptopic"){let b=Xi(o);m.push(...b)}else if(y==="directory"){let b=await As(e,o);m.push(...b)}else if(y==="file"){let b=await un(e,o);m.push(...b)}else if(y==="user"){let b=Qi(o);m.push(...b)}else if(y==="command"){let b=await Ji(e,o);m.push(...b)}if(r!==null)try{let y=await eo(e,r),b=to(e,y);for(let k of b)(o===null||k.startsWith(o))&&m.push(k)}catch{return O(p,p,1)}if(a){let y=await As(e,o);for(let b of y)m.includes(b)||m.push(b)}let v="";if(f!==null){let y=e.state.functions.get(f);if(y){let b=new Map;b.set("COMP_WORDS__length",N(e.state.env,"COMP_WORDS__length")),w(e.state.env,"COMP_WORDS__length","0"),b.set("COMP_CWORD",N(e.state.env,"COMP_CWORD")),w(e.state.env,"COMP_CWORD","-1"),b.set("COMP_LINE",N(e.state.env,"COMP_LINE")),w(e.state.env,"COMP_LINE",""),b.set("COMP_POINT",N(e.state.env,"COMP_POINT")),w(e.state.env,"COMP_POINT","0");let k=new Map;for(let M of e.state.env.keys())(M==="COMPREPLY"||M.startsWith("COMPREPLY_")||M==="COMPREPLY__length")&&(k.set(M,N(e.state.env,M)),e.state.env.delete(M));let P=["compgen",h[0]??"",""];try{let M=await qt(e,y,P,p);if(M.exitCode!==0)return tt(e,b),tt(e,k),O(p,M.stderr,1);v=z(M.stdout);let I=so(e);m.push(...I)}catch{return tt(e,b),tt(e,k),O(p,p,1)}tt(e,b),tt(e,k)}}if(d!==null)try{let y=Ae(d),b=await e.executeScript(y);if(b.exitCode!==0)return O(p,b.stderr,b.exitCode);if(b.stdout.length>0){let k=z(b.stdout).split(`
50
50
  `);for(let P of k)P.length>0&&m.push(P)}}catch(y){if(y.name==="ParseException")return _(`compgen: -C: ${y.message}
51
51
  `,2);throw y}let S=m;if(l!==null){let y=l.startsWith("!"),b=y?l.slice(1):l;S=m.filter(k=>{let P=Qe(k,b,!1,!0);return y?P:!P})}if(S.length===0&&o!==null)return O(E(v),p,1);let A=S.map(y=>`${n}${y}${i}`).join(`
52
52
  `),C=v+(A?`${A}
53
- `:"");return U(C)}function ji(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length"))continue;let i=n.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Hi(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length")?!1:e.state.env.has(n)),r.sort()}function Ui(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function Gi(e){let t=[..._s];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function qi(e){let t=[...un];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Zi(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith("BASH_ALIAS_")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Yi(e){let t=[...Vi];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Ki(e){let t=[...Bi];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function As(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let o=t.lastIndexOf("/");if(o!==-1){let a=t.slice(0,o)||"/";n=t.slice(o+1),a.startsWith("/")?r=a:r=`${e.state.cwd}/${a}`}}let i=await e.fs.readdir(r);for(let o of i){let a=`${r}/${o}`;try{if((await e.fs.stat(a)).isDirectory&&(!n||o.startsWith(n)))if(t?.includes("/")){let u=t.lastIndexOf("/"),l=t.slice(0,u+1);s.push(l+o)}else s.push(o)}catch{}}}catch{}return s.sort()}async function cn(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let o=t.lastIndexOf("/");if(o!==-1){let a=t.slice(0,o)||"/";n=t.slice(o+1),a.startsWith("/")?r=a:r=`${e.state.cwd}/${a}`}}let i=await e.fs.readdir(r);for(let o of i)if(!n||o.startsWith(n))if(t?.includes("/")){let a=t.lastIndexOf("/"),c=t.slice(0,a+1);s.push(c+o)}else s.push(o)}catch{}return s.sort()}function Xi(e){return["root","nobody"]}async function Qi(e,t){let s=new Set;for(let i of _s)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 un)s.add(i);let r=N(e.state.env,"PATH","/usr/bin:/bin");for(let i of r.split(":"))if(i)try{let o=await e.fs.readdir(i);for(let a of o)s.add(a)}catch{}let n=Array.from(s);return t!==null&&(n=n.filter(i=>i.startsWith(t))),n.sort()}async function Ji(e,t){let r=new H().parseWordFromString(t,!1,!1);return await L(e,r)}function eo(e,t){let s=N(e.state.env,"IFS",`
54
- `);if(s.length===0)return[t];let r=new Set(s.split("")),n=[],i="",o=0;for(;o<t.length;){let a=t[o];if(a==="\\"&&o+1<t.length){let c=t[o+1];i+=c,o+=2}else r.has(a)?(i.length>0&&(n.push(i),i=""),o++):(i+=a,o++)}return i.length>0&&n.push(i),n}function tt(e,t){for(let[s,r]of t)r===void 0?e.state.env.delete(s):w(e.state.env,s,r)}function to(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let n=Se(e,"COMPREPLY");for(let[,i]of n)t.push(i)}else e.state.env.has("COMPREPLY")&&t.push(N(e.state.env,"COMPREPLY"));return t}var so=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function xs(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=!1,i,o,a,c=[],u=[],l=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")s=!0;else if(d==="-r")r=!0;else if(d==="-D")n=!0;else if(d==="-W"){if(f++,f>=t.length)return _(`complete: -W: option requires an argument
53
+ `:"");return U(C)}function Hi(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length"))continue;let i=n.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Ui(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length")?!1:e.state.env.has(n)),r.sort()}function Gi(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function qi(e){let t=[..._s];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Zi(e){let t=[...fn];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Yi(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith("BASH_ALIAS_")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Ki(e){let t=[...Bi];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Xi(e){let t=[...ji];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function As(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let o=t.lastIndexOf("/");if(o!==-1){let a=t.slice(0,o)||"/";n=t.slice(o+1),a.startsWith("/")?r=a:r=`${e.state.cwd}/${a}`}}let i=await e.fs.readdir(r);for(let o of i){let a=`${r}/${o}`;try{if((await e.fs.stat(a)).isDirectory&&(!n||o.startsWith(n)))if(t?.includes("/")){let u=t.lastIndexOf("/"),l=t.slice(0,u+1);s.push(l+o)}else s.push(o)}catch{}}}catch{}return s.sort()}async function un(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let o=t.lastIndexOf("/");if(o!==-1){let a=t.slice(0,o)||"/";n=t.slice(o+1),a.startsWith("/")?r=a:r=`${e.state.cwd}/${a}`}}let i=await e.fs.readdir(r);for(let o of i)if(!n||o.startsWith(n))if(t?.includes("/")){let a=t.lastIndexOf("/"),c=t.slice(0,a+1);s.push(c+o)}else s.push(o)}catch{}return s.sort()}function Qi(e){return["root","nobody"]}async function Ji(e,t){let s=new Set;for(let i of _s)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 fn)s.add(i);let r=N(e.state.env,"PATH","/usr/bin:/bin");for(let i of r.split(":"))if(i)try{let o=await e.fs.readdir(i);for(let a of o)s.add(a)}catch{}let n=Array.from(s);return t!==null&&(n=n.filter(i=>i.startsWith(t))),n.sort()}async function eo(e,t){let r=new H().parseWordFromString(t,!1,!1);return await L(e,r)}function to(e,t){let s=N(e.state.env,"IFS",`
54
+ `);if(s.length===0)return[t];let r=new Set(s.split("")),n=[],i="",o=0;for(;o<t.length;){let a=t[o];if(a==="\\"&&o+1<t.length){let c=t[o+1];i+=c,o+=2}else r.has(a)?(i.length>0&&(n.push(i),i=""),o++):(i+=a,o++)}return i.length>0&&n.push(i),n}function tt(e,t){for(let[s,r]of t)r===void 0?e.state.env.delete(s):w(e.state.env,s,r)}function so(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let n=Se(e,"COMPREPLY");for(let[,i]of n)t.push(i)}else e.state.env.has("COMPREPLY")&&t.push(N(e.state.env,"COMPREPLY"));return t}var ro=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function xs(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=!1,i,o,a,c=[],u=[],l=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")s=!0;else if(d==="-r")r=!0;else if(d==="-D")n=!0;else if(d==="-W"){if(f++,f>=t.length)return _(`complete: -W: option requires an argument
55
55
  `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return _(`complete: -F: option requires an argument
56
56
  `,2);o=t[f]}else if(d==="-o"){if(f++,f>=t.length)return _(`complete: -o: option requires an argument
57
- `,2);let h=t[f];if(!so.includes(h))return _(`complete: ${h}: invalid option name
57
+ `,2);let h=t[f];if(!ro.includes(h))return _(`complete: ${h}: invalid option name
58
58
  `,2);c.push(h)}else if(d==="-A"){if(f++,f>=t.length)return _(`complete: -A: option requires an argument
59
59
  `,2);u.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return _(`complete: -C: option requires an argument
60
60
  `,2);a=t[f]}else if(d==="-G"){if(f++,f>=t.length)return _(`complete: -G: option requires an argument
@@ -68,31 +68,31 @@ import{A as fs,C as _r,D as kr,E as de,F as Be,G as se,H as Pe,I as Ct,J as Cr,K
68
68
  `:"")),E(`complete: ${i}: no completion specification
69
69
  `),1);continue}let a="complete";if(o.options)for(let c of o.options)a+=` -o ${c}`;if(o.actions)for(let c of o.actions)a+=` -A ${c}`;o.wordlist!==void 0&&(o.wordlist.includes(" ")||o.wordlist.includes("'")?a+=` -W '${o.wordlist}'`:a+=` -W ${o.wordlist}`),o.function!==void 0&&(a+=` -F ${o.function}`),o.isDefault&&(a+=" -D"),a+=` ${i}`,r.push(a)}return r.length===0?we():U(`${r.join(`
70
70
  `)}
71
- `)}var fn=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function Ns(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=[],i=[],o=[];for(let a=0;a<t.length;a++){let c=t[a];if(c==="-D")s=!0;else if(c==="-E")r=!0;else if(c==="-o"){if(a++,a>=t.length)return _(`compopt: -o: option requires an argument
72
- `,2);let u=t[a];if(!fn.includes(u))return _(`compopt: ${u}: invalid option name
71
+ `)}var dn=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function Ns(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=[],i=[],o=[];for(let a=0;a<t.length;a++){let c=t[a];if(c==="-D")s=!0;else if(c==="-E")r=!0;else if(c==="-o"){if(a++,a>=t.length)return _(`compopt: -o: option requires an argument
72
+ `,2);let u=t[a];if(!dn.includes(u))return _(`compopt: ${u}: invalid option name
73
73
  `,2);n.push(u)}else if(c==="+o"){if(a++,a>=t.length)return _(`compopt: +o: option requires an argument
74
- `,2);let u=t[a];if(!fn.includes(u))return _(`compopt: ${u}: invalid option name
74
+ `,2);let u=t[a];if(!dn.includes(u))return _(`compopt: ${u}: invalid option name
75
75
  `,2);i.push(u)}else if(c==="--"){o.push(...t.slice(a+1));break}else!c.startsWith("-")&&!c.startsWith("+")&&o.push(c)}if(s){let a=e.state.completionSpecs.get("__default__")??{isDefault:!0},c=new Set(a.options??[]);for(let u of n)c.add(u);for(let u of i)c.delete(u);return a.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set("__default__",a),we()}if(r){let a=e.state.completionSpecs.get("__empty__")??{},c=new Set(a.options??[]);for(let u of n)c.add(u);for(let u of i)c.delete(u);return a.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set("__empty__",a),we()}if(o.length>0){for(let a of o){let c=e.state.completionSpecs.get(a)??{},u=new Set(c.options??[]);for(let l of n)u.add(l);for(let l of i)u.delete(l);c.options=u.size>0?Array.from(u):void 0,e.state.completionSpecs.set(a,c)}return we()}return _(`compopt: not currently executing completion function
76
76
  `,1)}function Ts(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Me;return V}if(t.length>1)throw new G(1,p,E(`bash: continue: too many arguments
77
77
  `));let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new G(1,p,E(`bash: continue: ${t[0]}: numeric argument required
78
- `));s=r}throw new ge(s)}function K(e,t){let s=N(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 Os(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function Ds(e){let t="$'";for(let s=0;s<e.length;s++){let r=e[s],n=e.charCodeAt(s);n===7?t+="\\a":n===8?t+="\\b":n===9?t+="\\t":n===10?t+="\\n":n===11?t+="\\v":n===12?t+="\\f":n===13?t+="\\r":n===27?t+="\\e":n===39?t+="\\'":n===92?t+="\\\\":n<32||n===127?t+=`\\${n.toString(8).padStart(3,"0")}`:t+=r}return t+="'",t}function Zt(e){return Os(e)?Ds(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Ue(e){return Os(e)?Ds(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Is(e){return Os(e)?Ds(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function dn(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),fe(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 Rs(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function hn(e,t){let s="",r="",n=!1;for(let i of t){let o=dn(e,i);if(e.state.associativeArrays?.has(i)){let u=Le(e,i);if(u.length===0)s+=`declare -A ${i}=()
78
+ `));s=r}throw new ge(s)}function K(e,t){let s=N(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 Os(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function Ds(e){let t="$'";for(let s=0;s<e.length;s++){let r=e[s],n=e.charCodeAt(s);n===7?t+="\\a":n===8?t+="\\b":n===9?t+="\\t":n===10?t+="\\n":n===11?t+="\\v":n===12?t+="\\f":n===13?t+="\\r":n===27?t+="\\e":n===39?t+="\\'":n===92?t+="\\\\":n<32||n===127?t+=`\\${n.toString(8).padStart(3,"0")}`:t+=r}return t+="'",t}function Zt(e){return Os(e)?Ds(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Ue(e){return Os(e)?Ds(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Is(e){return Os(e)?Ds(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function hn(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),fe(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 Rs(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function pn(e,t){let s="",r="",n=!1;for(let i of t){let o=hn(e,i);if(e.state.associativeArrays?.has(i)){let u=Le(e,i);if(u.length===0)s+=`declare -A ${i}=()
79
79
  `;else{let l=u.map(f=>{let d=N(e.state.env,`${i}_${f}`,""),h=Rs(d);return`['${f}']=${h}`});s+=`declare -A ${i}=(${l.join(" ")})
80
80
  `}continue}let c=re(e,i);if(c.length>0){let u=c.map(l=>{let f=N(e.state.env,`${i}_${l}`,"");return`[${l}]=${Ue(f)}`});s+=`declare -a ${i}=(${u.join(" ")})
81
81
  `;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=()
82
82
  `;continue}if(e.state.env.has(i)){let u=N(e.state.env,i);s+=`declare ${o} ${i}=${Is(u)}
83
83
  `}else{let u=e.state.declaredVars?.has(i),l=e.state.localVarDepth?.has(i);u||l?s+=`declare ${o} ${i}
84
84
  `:(r+=`bash: declare: ${i}: not found
85
- `,n=!0)}}return O(E(s),E(r),n?1:0)}function pn(e,t){let{filterExport:s,filterReadonly:r,filterNameref:n,filterIndexedArray:i,filterAssocArray:o}=t,a=s||r||n||i||o,c="",u=new Set;for(let f of e.state.env.keys()){if(f.startsWith("BASH_"))continue;if(f.endsWith("__length")){let h=f.slice(0,-8);u.add(h);continue}let d=f.lastIndexOf("_");if(d>0){let h=f.slice(0,d),g=f.slice(d+1);if(/^\d+$/.test(g)||e.state.associativeArrays?.has(h)){u.add(h);continue}}u.add(f)}if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())u.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)u.add(f);let l=Array.from(u).sort();for(let f of l){let d=dn(e,f),h=e.state.associativeArrays?.has(f),g=re(e,f),m=!h&&(g.length>0||e.state.env.has(`${f}__length`));if(!(a&&(o&&!h||i&&!m||s&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||n&&!fe(e,f)))){if(h){let v=Le(e,f);if(v.length===0)c+=`declare -A ${f}=()
85
+ `,n=!0)}}return O(E(s),E(r),n?1:0)}function mn(e,t){let{filterExport:s,filterReadonly:r,filterNameref:n,filterIndexedArray:i,filterAssocArray:o}=t,a=s||r||n||i||o,c="",u=new Set;for(let f of e.state.env.keys()){if(f.startsWith("BASH_"))continue;if(f.endsWith("__length")){let h=f.slice(0,-8);u.add(h);continue}let d=f.lastIndexOf("_");if(d>0){let h=f.slice(0,d),g=f.slice(d+1);if(/^\d+$/.test(g)||e.state.associativeArrays?.has(h)){u.add(h);continue}}u.add(f)}if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())u.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)u.add(f);let l=Array.from(u).sort();for(let f of l){let d=hn(e,f),h=e.state.associativeArrays?.has(f),g=re(e,f),m=!h&&(g.length>0||e.state.env.has(`${f}__length`));if(!(a&&(o&&!h||i&&!m||s&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||n&&!fe(e,f)))){if(h){let v=Le(e,f);if(v.length===0)c+=`declare -A ${f}=()
86
86
  `;else{let S=v.map(A=>{let C=N(e.state.env,`${f}_${A}`,""),y=Rs(C);return`['${A}']=${y}`});c+=`declare -A ${f}=(${S.join(" ")})
87
87
  `}continue}if(g.length>0){let v=g.map(S=>{let A=N(e.state.env,`${f}_${S}`,"");return`[${S}]=${Ue(A)}`});c+=`declare -a ${f}=(${v.join(" ")})
88
88
  `;continue}if(e.state.env.has(`${f}__length`)){c+=`declare -a ${f}=()
89
89
  `;continue}if(e.state.env.has(f)){let v=N(e.state.env,f);c+=`declare ${d} ${f}=${Is(v)}
90
- `}}}return U(c)}function mn(e){let t="",s=Array.from(e.state.associativeArrays??[]).sort();for(let r of s){let n=Le(e,r);if(n.length===0)t+=`declare -A ${r}=()
90
+ `}}}return U(c)}function yn(e){let t="",s=Array.from(e.state.associativeArrays??[]).sort();for(let r of s){let n=Le(e,r);if(n.length===0)t+=`declare -A ${r}=()
91
91
  `;else{let i=n.map(o=>{let a=N(e.state.env,`${r}_${o}`,""),c=Rs(a);return`['${o}']=${c}`});t+=`declare -A ${r}=(${i.join(" ")})
92
- `}}return U(t)}function yn(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let o=n.slice(0,-8);e.state.associativeArrays?.has(o)||s.add(o);continue}let i=n.lastIndexOf("_");if(i>0){let o=n.slice(0,i),a=n.slice(i+1);/^\d+$/.test(a)&&(e.state.associativeArrays?.has(o)||s.add(o))}}let r=Array.from(s).sort();for(let n of r){let i=re(e,n);if(i.length===0)t+=`declare -a ${n}=()
92
+ `}}return U(t)}function gn(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let o=n.slice(0,-8);e.state.associativeArrays?.has(o)||s.add(o);continue}let i=n.lastIndexOf("_");if(i>0){let o=n.slice(0,i),a=n.slice(i+1);/^\d+$/.test(a)&&(e.state.associativeArrays?.has(o)||s.add(o))}}let r=Array.from(s).sort();for(let n of r){let i=re(e,n);if(i.length===0)t+=`declare -a ${n}=()
93
93
  `;else{let o=i.map(a=>{let c=N(e.state.env,`${n}_${a}`,"");return`[${a}]=${Ue(c)}`});t+=`declare -a ${n}=(${o.join(" ")})
94
- `}}return U(t)}function gn(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let o=n.slice(0,-8);s.add(o);continue}let i=n.lastIndexOf("_");if(i>0){let o=n.slice(0,i),a=n.slice(i+1);if(/^\d+$/.test(a)||e.state.associativeArrays?.has(o)){s.add(o);continue}}s.add(n)}let r=Array.from(s).sort();for(let n of r)e.state.associativeArrays?.has(n)||re(e,n).length>0||e.state.env.has(`${n}__length`)||e.state.env.has(n)&&(t+=`${n}=${Zt(N(e.state.env,n))}
95
- `);return U(t)}function Ms(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function mt(e,t){return e.state.integerVars?.has(t)??!1}function Fs(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function ro(e,t){return e.state.lowercaseVars?.has(t)??!1}function Ls(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function no(e,t){return e.state.uppercaseVars?.has(t)??!1}function st(e,t,s){return ro(e,t)?s.toLowerCase():no(e,t)?s.toUpperCase():s}async function wn(e,t){try{let s=new H,r=J(s,t),n=await Z(e,r.expression);return String(n)}catch{return"0"}}function io(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],r=s.length;if(e[r]!=="[")return null;let n=0,i=r+1;for(;r<e.length;r++)if(e[r]==="[")n++;else if(e[r]==="]"&&(n--,n===0))break;if(n!==0)return null;let o=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let a=e.slice(r);return{name:s,indexExpr:o,value:a}}async function Ws(e,t){let s=!1,r=!1,n=!1,i=!1,o=!1,a=!1,c=!1,u=!1,l=!1,f=!1,d=!1,h=!1,g=!1,m=!1,v=!1,S=[];for(let I=0;I<t.length;I++){let W=t[I];if(W==="-a")s=!0;else if(W==="-A")r=!0;else if(W==="-r")n=!0;else if(W==="-x")i=!0;else if(W==="-p")o=!0;else if(W==="-n")a=!0;else if(W==="+n")c=!0;else if(W==="+a")u=!0;else if(W==="+x")l=!0;else if(W==="--"){S.push(...t.slice(I+1));break}else if(W.startsWith("+")){for(let B of W.slice(1))if(B==="n")c=!0;else if(B==="a")u=!0;else if(B==="x")l=!0;else if(B!=="r"){if(B!=="i"){if(!(B==="f"||B==="F"))return O(p,E(`bash: typeset: +${B}: invalid option
94
+ `}}return U(t)}function wn(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let o=n.slice(0,-8);s.add(o);continue}let i=n.lastIndexOf("_");if(i>0){let o=n.slice(0,i),a=n.slice(i+1);if(/^\d+$/.test(a)||e.state.associativeArrays?.has(o)){s.add(o);continue}}s.add(n)}let r=Array.from(s).sort();for(let n of r)e.state.associativeArrays?.has(n)||re(e,n).length>0||e.state.env.has(`${n}__length`)||e.state.env.has(n)&&(t+=`${n}=${Zt(N(e.state.env,n))}
95
+ `);return U(t)}function Ms(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function mt(e,t){return e.state.integerVars?.has(t)??!1}function Fs(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function no(e,t){return e.state.lowercaseVars?.has(t)??!1}function Ls(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function io(e,t){return e.state.uppercaseVars?.has(t)??!1}function st(e,t,s){return no(e,t)?s.toLowerCase():io(e,t)?s.toUpperCase():s}async function vn(e,t){try{let s=new H,r=J(s,t),n=await Z(e,r.expression);return String(n)}catch{return"0"}}function oo(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],r=s.length;if(e[r]!=="[")return null;let n=0,i=r+1;for(;r<e.length;r++)if(e[r]==="[")n++;else if(e[r]==="]"&&(n--,n===0))break;if(n!==0)return null;let o=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let a=e.slice(r);return{name:s,indexExpr:o,value:a}}async function Ws(e,t){let s=!1,r=!1,n=!1,i=!1,o=!1,a=!1,c=!1,u=!1,l=!1,f=!1,d=!1,h=!1,g=!1,m=!1,v=!1,S=[];for(let I=0;I<t.length;I++){let W=t[I];if(W==="-a")s=!0;else if(W==="-A")r=!0;else if(W==="-r")n=!0;else if(W==="-x")i=!0;else if(W==="-p")o=!0;else if(W==="-n")a=!0;else if(W==="+n")c=!0;else if(W==="+a")u=!0;else if(W==="+x")l=!0;else if(W==="--"){S.push(...t.slice(I+1));break}else if(W.startsWith("+")){for(let B of W.slice(1))if(B==="n")c=!0;else if(B==="a")u=!0;else if(B==="x")l=!0;else if(B!=="r"){if(B!=="i"){if(!(B==="f"||B==="F"))return O(p,E(`bash: typeset: +${B}: invalid option
96
96
  `),2)}}}else if(W==="-i")f=!0;else if(W==="-l")d=!0;else if(W==="-u")h=!0;else if(W==="-f")g=!0;else if(W==="-F")m=!0;else if(W==="-g")v=!0;else if(W.startsWith("-"))for(let B of W.slice(1))if(B==="a")s=!0;else if(B==="A")r=!0;else if(B==="r")n=!0;else if(B==="x")i=!0;else if(B==="p")o=!0;else if(B==="n")a=!0;else if(B==="i")f=!0;else if(B==="l")d=!0;else if(B==="u")h=!0;else if(B==="f")g=!0;else if(B==="F")m=!0;else if(B==="g")v=!0;else return O(p,E(`bash: typeset: -${B}: invalid option
97
97
  `),2);else S.push(W)}let C=e.state.localScopes.length>0&&!v,y=I=>{if(!C)return;let W=e.state.localScopes[e.state.localScopes.length-1];W.has(I)||W.set(I,e.state.env.get(I))},b=I=>{if(!C)return;let W=e.state.localScopes[e.state.localScopes.length-1];W.has(I)||W.set(I,e.state.env.get(I));let B=`${I}_`;for(let T of e.state.env.keys())T.startsWith(B)&&!T.includes("__")&&(W.has(T)||W.set(T,e.state.env.get(T)));let D=`${I}__length`;e.state.env.has(D)&&!W.has(D)&&W.set(D,e.state.env.get(D))},k=I=>{C&&ze(e,I)};if(m){if(S.length===0){let B=Array.from(e.state.functions.keys()).sort(),D="";for(let T of B)D+=`declare -f ${T}
98
98
  `;return U(D)}let I=!0,W="";for(let B of S)e.state.functions.has(B)?W+=`${B}
@@ -100,18 +100,18 @@ import{A as fs,C as _r,D as kr,E as de,F as Be,G as se,H as Pe,I as Ct,J as Cr,K
100
100
  {
101
101
  # function body
102
102
  }
103
- `;return U(W)}let I=!0;for(let W of S)e.state.functions.has(W)||(I=!1);return O(p,p,I?0:1)}if(o&&S.length>0)return hn(e,S);if(o&&S.length===0)return pn(e,{filterExport:i,filterReadonly:n,filterNameref:a,filterIndexedArray:s,filterAssocArray:r});if(S.length===0&&r&&!o)return mn(e);if(S.length===0&&s&&!o)return yn(e);if(S.length===0&&!o)return gn(e);let P="",M=0;for(let I of S){let W=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(W&&!u){let $=W[1],R=W[2];if(r&&re(e,$).length>0){P+=`bash: declare: ${$}: cannot convert indexed to associative array
103
+ `;return U(W)}let I=!0;for(let W of S)e.state.functions.has(W)||(I=!1);return O(p,p,I?0:1)}if(o&&S.length>0)return pn(e,S);if(o&&S.length===0)return mn(e,{filterExport:i,filterReadonly:n,filterNameref:a,filterIndexedArray:s,filterAssocArray:r});if(S.length===0&&r&&!o)return yn(e);if(S.length===0&&s&&!o)return gn(e);if(S.length===0&&!o)return wn(e);let P="",M=0;for(let I of S){let W=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(W&&!u){let $=W[1],R=W[2];if(r&&re(e,$).length>0){P+=`bash: declare: ${$}: cannot convert indexed to associative array
104
104
  `,M=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has($)){P+=`bash: declare: ${$}: cannot convert associative to indexed array
105
- `,M=1;continue}if(b($),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add($)),_e(e,$),e.state.env.delete($),e.state.env.delete(`${$}__length`),r&&R.includes("[")){let F=jt(R);for(let[te,j]of F){let X=K(e,j);w(e.state.env,`${$}_${te}`,X)}}else if(r){let F=xe(R);for(let te=0;te<F.length;te+=2){let j=F[te],X=te+1<F.length?K(e,F[te+1]):"";w(e.state.env,`${$}_${j}`,X)}}else{let F=xe(R);if(F.some(j=>/^\[[^\]]+\]=/.test(j))){let j=0;for(let X of F){let oe=X.match(/^\[([^\]]+)\]=(.*)$/);if(oe){let me=oe[1],Ge=oe[2],li=K(e,Ge),ut;if(/^-?\d+$/.test(me))ut=Number.parseInt(me,10);else try{let ci=new H,ui=J(ci,me);ut=await Z(e,ui.expression)}catch{ut=0}w(e.state.env,`${$}_${ut}`,li),j=ut+1}else{let me=K(e,X);w(e.state.env,`${$}_${j}`,me),j++}}}else{for(let j=0;j<F.length;j++)w(e.state.env,`${$}_${j}`,F[j]);w(e.state.env,`${$}__length`,String(F.length))}}k($),n&&de(e,$),i&&Pe(e,$);continue}if(c){let $=I.includes("=")?I.slice(0,I.indexOf("=")):I;if($r(e,$),!I.includes("="))continue}if(l){let $=I.includes("=")?I.slice(0,I.indexOf("=")):I;if(Ct(e,$),!I.includes("="))continue}let B=io(I);if(B){let{name:$,indexExpr:R,value:F}=B,te=se(e,$);if(te)return te;b($);let j;try{let oe=new H,me=J(oe,R);j=await Z(e,me.expression)}catch{let oe=parseInt(R,10);j=Number.isNaN(oe)?0:oe}w(e.state.env,`${$}_${j}`,F);let X=parseInt(N(e.state.env,`${$}__length`,"0"),10);j>=X&&w(e.state.env,`${$}__length`,String(j+1)),k($),n&&de(e,$),i&&Pe(e,$);continue}let D=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(D&&!u){let $=D[1],R=D[2],F=se(e,$);if(F)return F;b($);let te=xe(R);if(e.state.associativeArrays?.has($)){let j=jt(R);for(let[X,oe]of j){let me=K(e,oe);w(e.state.env,`${$}_${X}`,me)}}else{let j=re(e,$),X=0,oe=e.state.env.get($);j.length===0&&oe!==void 0?(e.state.env.set(`${$}_0`,oe),e.state.env.delete($),X=1):j.length>0&&(X=Math.max(...j)+1);for(let Ge=0;Ge<te.length;Ge++)w(e.state.env,`${$}_${X+Ge}`,K(e,te[Ge]));let me=X+te.length;w(e.state.env,`${$}__length`,String(me))}k($),n&&de(e,$),i&&Pe(e,$);continue}let T=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(T){let $=T[1],R=K(e,T[2]),F=se(e,$);if(F)return F;y($),f&&Ms(e,$),d&&Fs(e,$),h&&Ls(e,$);let j=re(e,$).length>0||e.state.associativeArrays?.has($);if(mt(e,$)){let X=N(e.state.env,$,"0"),oe=parseInt(X,10)||0,me=parseInt(await wn(e,R),10)||0;R=String(oe+me),w(e.state.env,$,R)}else if(j){R=st(e,$,R);let X=`${$}_0`,oe=N(e.state.env,X);w(e.state.env,X,oe+R)}else{R=st(e,$,R);let X=N(e.state.env,$);w(e.state.env,$,X+R)}k($),n&&de(e,$),i&&Pe(e,$),e.state.options.allexport&&!l&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add($));continue}if(I.includes("=")){let $=I.indexOf("="),R=I.slice(0,$),F=I.slice($+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(R)){P+=`bash: typeset: \`${R}': not a valid identifier
105
+ `,M=1;continue}if(b($),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add($)),_e(e,$),e.state.env.delete($),e.state.env.delete(`${$}__length`),r&&R.includes("[")){let F=jt(R);for(let[te,j]of F){let X=K(e,j);w(e.state.env,`${$}_${te}`,X)}}else if(r){let F=xe(R);for(let te=0;te<F.length;te+=2){let j=F[te],X=te+1<F.length?K(e,F[te+1]):"";w(e.state.env,`${$}_${j}`,X)}}else{let F=xe(R);if(F.some(j=>/^\[[^\]]+\]=/.test(j))){let j=0;for(let X of F){let oe=X.match(/^\[([^\]]+)\]=(.*)$/);if(oe){let me=oe[1],Ge=oe[2],ci=K(e,Ge),ut;if(/^-?\d+$/.test(me))ut=Number.parseInt(me,10);else try{let ui=new H,fi=J(ui,me);ut=await Z(e,fi.expression)}catch{ut=0}w(e.state.env,`${$}_${ut}`,ci),j=ut+1}else{let me=K(e,X);w(e.state.env,`${$}_${j}`,me),j++}}}else{for(let j=0;j<F.length;j++)w(e.state.env,`${$}_${j}`,F[j]);w(e.state.env,`${$}__length`,String(F.length))}}k($),n&&de(e,$),i&&Pe(e,$);continue}if(c){let $=I.includes("=")?I.slice(0,I.indexOf("=")):I;if(Sr(e,$),!I.includes("="))continue}if(l){let $=I.includes("=")?I.slice(0,I.indexOf("=")):I;if(Ct(e,$),!I.includes("="))continue}let B=oo(I);if(B){let{name:$,indexExpr:R,value:F}=B,te=se(e,$);if(te)return te;b($);let j;try{let oe=new H,me=J(oe,R);j=await Z(e,me.expression)}catch{let oe=parseInt(R,10);j=Number.isNaN(oe)?0:oe}w(e.state.env,`${$}_${j}`,F);let X=parseInt(N(e.state.env,`${$}__length`,"0"),10);j>=X&&w(e.state.env,`${$}__length`,String(j+1)),k($),n&&de(e,$),i&&Pe(e,$);continue}let D=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(D&&!u){let $=D[1],R=D[2],F=se(e,$);if(F)return F;b($);let te=xe(R);if(e.state.associativeArrays?.has($)){let j=jt(R);for(let[X,oe]of j){let me=K(e,oe);w(e.state.env,`${$}_${X}`,me)}}else{let j=re(e,$),X=0,oe=e.state.env.get($);j.length===0&&oe!==void 0?(e.state.env.set(`${$}_0`,oe),e.state.env.delete($),X=1):j.length>0&&(X=Math.max(...j)+1);for(let Ge=0;Ge<te.length;Ge++)w(e.state.env,`${$}_${X+Ge}`,K(e,te[Ge]));let me=X+te.length;w(e.state.env,`${$}__length`,String(me))}k($),n&&de(e,$),i&&Pe(e,$);continue}let T=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(T){let $=T[1],R=K(e,T[2]),F=se(e,$);if(F)return F;y($),f&&Ms(e,$),d&&Fs(e,$),h&&Ls(e,$);let j=re(e,$).length>0||e.state.associativeArrays?.has($);if(mt(e,$)){let X=N(e.state.env,$,"0"),oe=parseInt(X,10)||0,me=parseInt(await vn(e,R),10)||0;R=String(oe+me),w(e.state.env,$,R)}else if(j){R=st(e,$,R);let X=`${$}_0`,oe=N(e.state.env,X);w(e.state.env,X,oe+R)}else{R=st(e,$,R);let X=N(e.state.env,$);w(e.state.env,$,X+R)}k($),n&&de(e,$),i&&Pe(e,$),e.state.options.allexport&&!l&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add($));continue}if(I.includes("=")){let $=I.indexOf("="),R=I.slice(0,$),F=I.slice($+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(R)){P+=`bash: typeset: \`${R}': not a valid identifier
106
106
  `,M=1;continue}let te=se(e,R);if(te)return te;if(y(R),a){if(F!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(F)){P+=`bash: declare: \`${F}': invalid variable name for name reference
107
- `,M=1;continue}w(e.state.env,R,F),Oe(e,R),F!==""&&us(e,F)&&cs(e,R),k(R),n&&de(e,R),i&&Pe(e,R);continue}if(f&&Ms(e,R),d&&Fs(e,R),h&&Ls(e,R),mt(e,R)&&(F=await wn(e,F)),F=st(e,R,F),fe(e,R)){let j=ke(e,R);j&&j!==R?w(e.state.env,j,F):w(e.state.env,R,F)}else w(e.state.env,R,F);k(R),n&&de(e,R),i&&Pe(e,R),e.state.options.allexport&&!l&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(R))}else{let $=I;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test($)){P+=`bash: typeset: \`${$}': not a valid identifier
108
- `,M=1;continue}if(s||r?b($):y($),a){Oe(e,$);let F=N(e.state.env,$);F!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(F)?Sr(e,$):F&&us(e,F)&&cs(e,$),k($),n&&de(e,$),i&&Pe(e,$);continue}if(f&&Ms(e,$),d&&Fs(e,$),h&&Ls(e,$),r){if(re(e,$).length>0){P+=`bash: declare: ${$}: cannot convert indexed to associative array
107
+ `,M=1;continue}w(e.state.env,R,F),Oe(e,R),F!==""&&us(e,F)&&cs(e,R),k(R),n&&de(e,R),i&&Pe(e,R);continue}if(f&&Ms(e,R),d&&Fs(e,R),h&&Ls(e,R),mt(e,R)&&(F=await vn(e,F)),F=st(e,R,F),fe(e,R)){let j=ke(e,R);j&&j!==R?w(e.state.env,j,F):w(e.state.env,R,F)}else w(e.state.env,R,F);k(R),n&&de(e,R),i&&Pe(e,R),e.state.options.allexport&&!l&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(R))}else{let $=I;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test($)){P+=`bash: typeset: \`${$}': not a valid identifier
108
+ `,M=1;continue}if(s||r?b($):y($),a){Oe(e,$);let F=N(e.state.env,$);F!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(F)?Pr(e,$):F&&us(e,F)&&cs(e,$),k($),n&&de(e,$),i&&Pe(e,$);continue}if(f&&Ms(e,$),d&&Fs(e,$),h&&Ls(e,$),r){if(re(e,$).length>0){P+=`bash: declare: ${$}: cannot convert indexed to associative array
109
109
  `,M=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add($)}let R=Array.from(e.state.env.keys()).some(F=>F.startsWith(`${$}_`)&&!F.startsWith(`${$}__length`));!e.state.env.has($)&&!R&&(s||r?w(e.state.env,`${$}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add($))),k($),n&&de(e,$),i&&Pe(e,$)}}return O(p,E(P),M)}async function zs(e,t){let s=!1,r=!1,n=!1,i=[];for(let o=0;o<t.length;o++){let a=t[o];if(a==="-a")s=!0;else if(a==="-A")r=!0;else if(a==="-p")n=!0;else if(a==="--"){i.push(...t.slice(o+1));break}else a.startsWith("-")||i.push(a)}if(i.length===0){let o="",a=Array.from(e.state.readonlyVars||[]).sort();for(let c of a){let u=e.state.env.get(c);if(u!==void 0){let l=z(u??p).replace(/\\/g,"\\\\").replace(/"/g,'\\"');o+=`declare -r ${c}="${l}"
110
- `}}return U(o)}for(let o of i){let a=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(a){let f=a[1],d=a[2],h=se(e,f);if(h)return h;let g=xe(d);if(e.state.associativeArrays?.has(f)){let m=jt(d);for(let[v,S]of m){let A=K(e,S);w(e.state.env,`${f}_${v}`,A)}}else{let m=re(e,f),v=0,S=e.state.env.get(f);m.length===0&&S!==void 0?(e.state.env.set(`${f}_0`,S),e.state.env.delete(f),v=1):m.length>0&&(v=Math.max(...m)+1);for(let C=0;C<g.length;C++)w(e.state.env,`${f}_${v+C}`,K(e,g[C]));let A=v+g.length;w(e.state.env,`${f}__length`,String(A))}de(e,f);continue}let c=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c){let f=c[1],d=K(e,c[2]),h=se(e,f);if(h)return h;let g=N(e.state.env,f);w(e.state.env,f,g+d),de(e,f);continue}let u=tn(o);if(u.value===void 0&&!u.isArray){de(e,u.name);continue}let l=await sn(e,u,{makeReadonly:!0});if(l)return l}return V}function Vs(e){return e.state.directoryStack??=[],e.state.directoryStack}function yt(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function oo(e){let t=e.split("/").filter(r=>r&&r!=="."),s=[];for(let r of t)r===".."?s.pop():s.push(r);return`/${s.join("/")}`}async function Bs(e,t){let s=Vs(e),r;for(let a=0;a<t.length;a++){let c=t[a];if(c==="--"){if(a+1<t.length){if(r!==void 0)return _(`bash: pushd: too many arguments
110
+ `}}return U(o)}for(let o of i){let a=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(a){let f=a[1],d=a[2],h=se(e,f);if(h)return h;let g=xe(d);if(e.state.associativeArrays?.has(f)){let m=jt(d);for(let[v,S]of m){let A=K(e,S);w(e.state.env,`${f}_${v}`,A)}}else{let m=re(e,f),v=0,S=e.state.env.get(f);m.length===0&&S!==void 0?(e.state.env.set(`${f}_0`,S),e.state.env.delete(f),v=1):m.length>0&&(v=Math.max(...m)+1);for(let C=0;C<g.length;C++)w(e.state.env,`${f}_${v+C}`,K(e,g[C]));let A=v+g.length;w(e.state.env,`${f}__length`,String(A))}de(e,f);continue}let c=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c){let f=c[1],d=K(e,c[2]),h=se(e,f);if(h)return h;let g=N(e.state.env,f);w(e.state.env,f,g+d),de(e,f);continue}let u=sn(o);if(u.value===void 0&&!u.isArray){de(e,u.name);continue}let l=await rn(e,u,{makeReadonly:!0});if(l)return l}return V}function Vs(e){return e.state.directoryStack??=[],e.state.directoryStack}function yt(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function ao(e){let t=e.split("/").filter(r=>r&&r!=="."),s=[];for(let r of t)r===".."?s.pop():s.push(r);return`/${s.join("/")}`}async function Bs(e,t){let s=Vs(e),r;for(let a=0;a<t.length;a++){let c=t[a];if(c==="--"){if(a+1<t.length){if(r!==void 0)return _(`bash: pushd: too many arguments
111
111
  `,2);r=t[a+1],a++}}else{if(c.startsWith("-")&&c!=="-")return _(`bash: pushd: ${c}: invalid option
112
112
  `,2);if(r!==void 0)return _(`bash: pushd: too many arguments
113
113
  `,2);r=c}}if(r===void 0){if(s.length<2)return _(`bash: pushd: no other directory
114
- `,1);let a=s[0];s[0]=s[1],s[1]=a,r=s[0]}let n;if(r.startsWith("/"))n=r;else if(r===".."){let a=e.state.cwd.split("/").filter(c=>c);a.pop(),n=`/${a.join("/")}`}else r==="."?n=e.state.cwd:r.startsWith("~")?n=N(e.state.env,"HOME","/")+r.slice(1):n=`${e.state.cwd}/${r}`;n=oo(n);try{if(!(await e.fs.stat(n)).isDirectory)return _(`bash: pushd: ${r}: Not a directory
114
+ `,1);let a=s[0];s[0]=s[1],s[1]=a,r=s[0]}let n;if(r.startsWith("/"))n=r;else if(r===".."){let a=e.state.cwd.split("/").filter(c=>c);a.pop(),n=`/${a.join("/")}`}else r==="."?n=e.state.cwd:r.startsWith("~")?n=N(e.state.env,"HOME","/")+r.slice(1):n=`${e.state.cwd}/${r}`;n=ao(n);try{if(!(await e.fs.stat(n)).isDirectory)return _(`bash: pushd: ${r}: Not a directory
115
115
  `,1)}catch{return _(`bash: pushd: ${r}: No such file or directory
116
116
  `,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=n,w(e.state.env,"PWD",n),w(e.state.env,"OLDPWD",e.state.previousDir);let i=N(e.state.env,"HOME",""),o=`${[n,...s].map(a=>yt(a,i)).join(" ")}
117
117
  `;return U(o)}function js(e,t){let s=Vs(e);for(let o of t)if(o!=="--")return o.startsWith("-")&&o!=="-"?_(`bash: popd: ${o}: invalid option
@@ -151,7 +151,7 @@ eval: usage: eval [arg ...]
151
151
  `;for(let[,m]of e.state.hashTable)g+=` 1 ${m}
152
152
  `}return U(g)}let l=!1,f="",h=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let g of c){if(g.includes("/")){f+=`bash: hash: ${g}: cannot use / in name
153
153
  `,l=!0;continue}let m=!1;for(let v of h){if(!v)continue;let S=`${v}/${g}`;if(await e.fs.exists(S)){e.state.hashTable.set(g,S),m=!0;break}}m||(f+=`bash: hash: ${g}: not found
154
- `,l=!0)}return l?_(f,1):V}var vn=new Map([[":",[": [arguments]",`Null command.
154
+ `,l=!0)}return l?_(f,1):V}var bn=new Map([[":",[": [arguments]",`Null command.
155
155
  No effect; the command does nothing.
156
156
  Exit Status:
157
157
  Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
@@ -496,31 +496,31 @@ eval: usage: eval [arg ...]
496
496
  job specification, and reports its termination status.
497
497
  Exit Status:
498
498
  Returns the status of the last ID; fails if ID is invalid or an invalid
499
- option is given.`]]]),bn=[...vn.keys()].sort();function Zs(e,t){let s=!1,r=[],n=0;for(;n<t.length;){let c=t[n];if(c==="--"){for(n++;n<t.length;)r.push(t[n]),n++;break}if(c.startsWith("-")&&c.length>1){for(let u=1;u<c.length;u++){let l=c[u];if(l==="s")s=!0;else return _(`bash: help: -${l}: invalid option
500
- `,2)}n++}else r.push(c),n++}if(r.length===0)return lo();let i="",o=!1,a="";for(let c of r){let u=ao(c);if(u.length===0){a+=`bash: help: no help topics match \`${c}'. Try \`help help' or \`man -k ${c}' or \`info ${c}'.
501
- `,o=!0;continue}for(let l of u){let f=vn.get(l);if(!f)continue;let[d,h]=f;s?i+=`${l}: ${d}
499
+ option is given.`]]]),En=[...bn.keys()].sort();function Zs(e,t){let s=!1,r=[],n=0;for(;n<t.length;){let c=t[n];if(c==="--"){for(n++;n<t.length;)r.push(t[n]),n++;break}if(c.startsWith("-")&&c.length>1){for(let u=1;u<c.length;u++){let l=c[u];if(l==="s")s=!0;else return _(`bash: help: -${l}: invalid option
500
+ `,2)}n++}else r.push(c),n++}if(r.length===0)return co();let i="",o=!1,a="";for(let c of r){let u=lo(c);if(u.length===0){a+=`bash: help: no help topics match \`${c}'. Try \`help help' or \`man -k ${c}' or \`info ${c}'.
501
+ `,o=!0;continue}for(let l of u){let f=bn.get(l);if(!f)continue;let[d,h]=f;s?i+=`${l}: ${d}
502
502
  `:i+=`${l}: ${d}
503
503
  ${h}
504
- `}}return{exitCode:o?1:0,stdout:E(i),stderr:E(a)}}function ao(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=dt(`^${t}$`);return bn.filter(r=>s.test(r))}function lo(){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=bn.slice(),r=Math.ceil(s.length/2);for(let n=0;n<r;n++){let i=s[n]||"",o=s[n+r]||"",a=i.padEnd(t);e.push(o?`${a}${o}`:i)}return U(`${e.join(`
504
+ `}}return{exitCode:o?1:0,stdout:E(i),stderr:E(a)}}function lo(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=dt(`^${t}$`);return En.filter(r=>s.test(r))}function co(){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=En.slice(),r=Math.ceil(s.length/2);for(let n=0;n<r;n++){let i=s[n]||"",o=s[n+r]||"",a=i.padEnd(t);e.push(o?`${a}${o}`:i)}return U(`${e.join(`
505
505
  `)}
506
- `)}function co(e){let t=[],s="",r=0;for(let n of e){for(let i of n)i==="("?r++:i===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(t.push(s),s="")}return s&&t.push(s),t}async function Ys(e,t){if(t.length===0)return _(`bash: let: expression expected
507
- `);let s=co(t),r=0;for(let n of s)try{let o=Ae(`(( ${n} ))`).statements[0];if(o&&o.pipelines.length>0&&o.pipelines[0].commands.length>0){let a=o.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await Z(e,a.expression.expression))}}catch(i){return _(`bash: let: ${n}: ${i.message}
506
+ `)}function uo(e){let t=[],s="",r=0;for(let n of e){for(let i of n)i==="("?r++:i===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(t.push(s),s="")}return s&&t.push(s),t}async function Ys(e,t){if(t.length===0)return _(`bash: let: expression expected
507
+ `);let s=uo(t),r=0;for(let n of s)try{let o=Ae(`(( ${n} ))`).statements[0];if(o&&o.pipelines.length>0&&o.pipelines[0].commands.length>0){let a=o.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await Z(e,a.expression.expression))}}catch(i){return _(`bash: let: ${n}: ${i.message}
508
508
  `)}return O(p,p,r===0?1:0)}async function Ks(e,t){if(e.state.localScopes.length===0)return _(`bash: local: can only be used in a function
509
509
  `);let s=e.state.localScopes[e.state.localScopes.length-1],r="",n=0,i=!1,o=!1,a=!1,c=[];for(let u of t)if(u==="-n")i=!0;else if(u==="-a")o=!0;else if(u==="-p")a=!0;else if(u.startsWith("-")&&!u.includes("="))for(let l of u.slice(1))l==="n"?i=!0:l==="a"?o=!0:l==="p"&&(a=!0);else c.push(u);if(c.length===0){let u="",l=Array.from(s.keys()).filter(f=>!f.includes("_")||!f.match(/_\d+$/)).filter(f=>!f.includes("__length")).sort();for(let f of l){let d=e.state.env.get(f);if(d!==void 0){let h=z(d);u+=`${f}=${h}
510
510
  `}}return O(E(u),p,0)}for(let u of c){let l,f,d=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(d){l=d[1];let S=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)){r+=`bash: local: \`${u}': not a valid identifier
511
511
  `,n=1;continue}if(se(e,l,"bash"),!s.has(l)){s.set(l,e.state.env.get(l));let y=`${l}_`;for(let b of e.state.env.keys())b.startsWith(y)&&!b.includes("__")&&(s.has(b)||s.set(b,e.state.env.get(b)))}let A=`${l}_`;for(let y of e.state.env.keys())y.startsWith(A)&&!y.includes("__")&&e.state.env.delete(y);let C=xe(S);for(let y=0;y<C.length;y++)w(e.state.env,`${l}_${y}`,C[y]);w(e.state.env,`${l}__length`,String(C.length)),ze(e,l),i&&Oe(e,l);continue}let h=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(h){l=h[1];let S=h[2];if(se(e,l,"bash"),!s.has(l)){s.set(l,e.state.env.get(l));let P=`${l}_`;for(let I of e.state.env.keys())I.startsWith(P)&&!I.includes("__")&&(s.has(I)||s.set(I,e.state.env.get(I)));let M=`${l}__length`;e.state.env.has(M)&&!s.has(M)&&s.set(M,e.state.env.get(M))}let A=xe(S),C=re(e,l),y=0,b=e.state.env.get(l);C.length===0&&b!==void 0?(e.state.env.set(`${l}_0`,b),e.state.env.delete(l),y=1):C.length>0&&(y=Math.max(...C)+1);for(let P=0;P<A.length;P++)w(e.state.env,`${l}_${y+P}`,K(e,A[P]));let k=y+A.length;w(e.state.env,`${l}__length`,String(k)),ze(e,l),i&&Oe(e,l);continue}let g=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(g){l=g[1];let S=K(e,g[2]);se(e,l,"bash"),s.has(l)||s.set(l,e.state.env.get(l));let A=N(e.state.env,l);w(e.state.env,l,A+S),ze(e,l),i&&Oe(e,l);continue}let m=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(m){l=m[1];let S=m[2],A=K(e,m[3]);if(se(e,l,"bash"),!s.has(l)){s.set(l,e.state.env.get(l));let b=`${l}_`;for(let P of e.state.env.keys())P.startsWith(b)&&!P.includes("__")&&(s.has(P)||s.set(P,e.state.env.get(P)));let k=`${l}__length`;e.state.env.has(k)&&!s.has(k)&&s.set(k,e.state.env.get(k))}let C;try{let b=new H,k=J(b,S);C=await Z(e,k.expression)}catch{let b=parseInt(S,10);C=Number.isNaN(b)?0:b}w(e.state.env,`${l}_${C}`,A);let y=parseInt(N(e.state.env,`${l}__length`,"0"),10);C>=y&&w(e.state.env,`${l}__length`,String(C+1)),ze(e,l),i&&Oe(e,l);continue}if(u.includes("=")){let S=u.indexOf("=");l=u.slice(0,S),f=K(e,u.slice(S+1))}else l=u;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)){r+=`bash: local: \`${u}': not a valid identifier
512
- `,n=1;continue}let v=s.has(l);if(f!==void 0){let S=e.state.env.get(l);if(e.state.tempEnvBindings){let A=e.state.accessedTempEnvVars?.has(l),C=e.state.mutatedTempEnvVars?.has(l);if(!A&&!C)for(let y=e.state.tempEnvBindings.length-1;y>=0;y--){let b=e.state.tempEnvBindings[y];if(b.has(l)){S=b.get(l);break}}}rn(e,l,S)}if(!v){let S=e.state.env.get(l);if(e.state.tempEnvBindings)for(let A=e.state.tempEnvBindings.length-1;A>=0;A--){let C=e.state.tempEnvBindings[A];if(C.has(l)){S=C.get(l);break}}if(s.set(l,S),o){let A=`${l}_`;for(let y of e.state.env.keys())y.startsWith(A)&&!y.includes("__")&&(s.has(y)||s.set(y,e.state.env.get(y)));let C=`${l}__length`;e.state.env.has(C)&&!s.has(C)&&s.set(C,e.state.env.get(C))}}if(o&&f===void 0){let S=`${l}_`;for(let A of e.state.env.keys())A.startsWith(S)&&!A.includes("__")&&e.state.env.delete(A);w(e.state.env,`${l}__length`,"0")}else if(f!==void 0){if(se(e,l,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){r+=`bash: local: \`${f}': invalid variable name for name reference
512
+ `,n=1;continue}let v=s.has(l);if(f!==void 0){let S=e.state.env.get(l);if(e.state.tempEnvBindings){let A=e.state.accessedTempEnvVars?.has(l),C=e.state.mutatedTempEnvVars?.has(l);if(!A&&!C)for(let y=e.state.tempEnvBindings.length-1;y>=0;y--){let b=e.state.tempEnvBindings[y];if(b.has(l)){S=b.get(l);break}}}nn(e,l,S)}if(!v){let S=e.state.env.get(l);if(e.state.tempEnvBindings)for(let A=e.state.tempEnvBindings.length-1;A>=0;A--){let C=e.state.tempEnvBindings[A];if(C.has(l)){S=C.get(l);break}}if(s.set(l,S),o){let A=`${l}_`;for(let y of e.state.env.keys())y.startsWith(A)&&!y.includes("__")&&(s.has(y)||s.set(y,e.state.env.get(y)));let C=`${l}__length`;e.state.env.has(C)&&!s.has(C)&&s.set(C,e.state.env.get(C))}}if(o&&f===void 0){let S=`${l}_`;for(let A of e.state.env.keys())A.startsWith(S)&&!A.includes("__")&&e.state.env.delete(A);w(e.state.env,`${l}__length`,"0")}else if(f!==void 0){if(se(e,l,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){r+=`bash: local: \`${f}': invalid variable name for name reference
513
513
  `,n=1;continue}w(e.state.env,l,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(l))}else{let S=e.state.tempEnvBindings?.some(A=>A.has(l));!v&&!S&&e.state.env.delete(l)}ze(e,l),i&&Oe(e,l)}return O(p,E(r),n)}function Xs(e,t,s){let r=z(s),n=`
514
514
  `,i=0,o=0,a=0,c=!1,u="MAPFILE",l=0;for(;l<t.length;){let C=t[l];C==="-d"&&l+1<t.length?(n=t[l+1]===""?"\0":t[l+1]||`
515
515
  `,l+=2):C==="-n"&&l+1<t.length?(i=Number.parseInt(t[l+1],10)||0,l+=2):C==="-O"&&l+1<t.length?(o=Number.parseInt(t[l+1],10)||0,l+=2):C==="-s"&&l+1<t.length?(a=Number.parseInt(t[l+1],10)||0,l+=2):C==="-t"?(c=!0,l++):C==="-u"||C==="-C"||C==="-c"?l+=2:(C.startsWith("-")||(u=C),l++)}let f=r;!f&&e.state.groupStdin!==void 0&&(f=z(e.state.groupStdin));let d=[],h=f,g=0,m=0,v=e.limits?.maxArrayElements??1e5;for(;h.length>0;){let C=h.indexOf(n);if(C===-1){if(h.length>0){if(m<a)m++;else if(i===0||g<i){if(o+g>=v)return O(p,E(`mapfile: array element limit exceeded (${v})
516
516
  `),1);let k=h,P=k.indexOf("\0");P!==-1&&(k=k.substring(0,P)),d.push(k),g++}}break}let y=h.substring(0,C),b=y.indexOf("\0");if(b!==-1&&(y=y.substring(0,b)),!c&&n!=="\0"&&(y+=n),h=h.substring(C+n.length),m<a){m++;continue}if(i>0&&g>=i)break;if(o+g>=v)return O(p,E(`mapfile: array element limit exceeded (${v})
517
- `),1);d.push(y),g++}o===0&&_e(e,u);for(let C=0;C<d.length;C++)w(e.state.env,`${u}_${o+C}`,d[C]);let S=parseInt(N(e.state.env,`${u}__length`,"0"),10),A=o+d.length;return w(e.state.env,`${u}__length`,String(Math.max(S,A))),e.state.groupStdin!==void 0&&!r&&(e.state.groupStdin=p),O(p,p,0)}function uo(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),c=a.indexOf(":");if(c===-1)return null;let u=Number.parseInt(a.slice(0,c),10);if(Number.isNaN(u)||u<0)return null;let l=a.slice(c+1);return{path:i,position:u,content:l}}function fo(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}function Qs(e,t,s,r=-1){let n=z(s),i=!1,o=`
518
- `,a="",c=-1,u=-1,l=null,f=-1,d=-1,h=[],g=0,m=!1,v=(D,T)=>{let $=1;for(;$<D.length;){let R=D[$];if(R==="r")i=!0,$++;else if(R==="s")$++;else{if(R==="d")return $+1<D.length?(o=D.substring($+1),{nextArgIndex:T+1}):T+1<t.length?(o=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(R==="n"){if($+1<D.length){let F=D.substring($+1);return c=Number.parseInt(F,10),(Number.isNaN(c)||c<0)&&(m=!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)&&(m=!0,c=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(R==="N"){if($+1<D.length){let F=D.substring($+1);return u=Number.parseInt(F,10),(Number.isNaN(u)||u<0)&&(m=!0,u=0),{nextArgIndex:T+1}}else if(T+1<t.length)return u=Number.parseInt(t[T+1],10),(Number.isNaN(u)||u<0)&&(m=!0,u=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else{if(R==="a")return $+1<D.length?(l=D.substring($+1),{nextArgIndex:T+1}):T+1<t.length?(l=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(R==="p")return $+1<D.length?(a=D.substring($+1),{nextArgIndex:T+1}):T+1<t.length?(a=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(R==="u"){if($+1<D.length){let F=D.substring($+1);return f=Number.parseInt(F,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(R==="t"){if($+1<D.length){let F=D.substring($+1);return d=Number.parseFloat(F),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(R==="e"||R==="i"||R==="P"){if(R==="i"&&T+1<t.length)return{nextArgIndex:T+2};$++}else $++}}}return{nextArgIndex:T+1}};for(;g<t.length;){let D=t[g];if(D.startsWith("-")&&D.length>1&&D!=="--"){let T=v(D,g);if(T.nextArgIndex===-1)return{stdout:p,stderr:p,exitCode:2};if(T.nextArgIndex===-2)return{stdout:p,stderr:p,exitCode:1};g=T.nextArgIndex}else if(D==="--")for(g++;g<t.length;)h.push(t[g]),g++;else h.push(D),g++}if(m)return O(p,p,1);if(h.length===0&&l===null&&h.push("REPLY"),d===0){if(l)_e(e,l);else{for(let D of h)w(e.state.env,D,"");h.length===0&&w(e.state.env,"REPLY","")}return O(p,p,0)}if(d<0&&d!==-1)return O(p,p,1);let S=n;f>=0?e.state.fileDescriptors?S=e.state.fileDescriptors.get(f)||"":S="":!S&&e.state.groupStdin!==void 0&&(S=z(e.state.groupStdin));let A=o===""?"\0":o,C="",y=0,b=!0,k=D=>{if(f>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(f,S.substring(D));else if(r>=0&&e.state.fileDescriptors){let T=e.state.fileDescriptors.get(r);if(T?.startsWith("__rw__:")){let $=uo(T);if($){let R=$.position+D;e.state.fileDescriptors.set(r,fo($.path,R,$.content))}}}else e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=E(S.substring(D)))};if(u>=0){let D=Math.min(u,S.length);C=S.substring(0,D),y=D,b=D>=u,k(y);let T=h[0]||"REPLY";w(e.state.env,T,C);for(let $=1;$<h.length;$++)w(e.state.env,h[$],"");return O(p,p,b?0:1)}else if(c>=0){let D=0,T=0,$=!1;for(;T<S.length&&D<c;){let R=S[T];if(R===A){y=T+1,$=!0;break}if(!i&&R==="\\"&&T+1<S.length){let F=S[T+1];if(F===A&&A===`
517
+ `),1);d.push(y),g++}o===0&&_e(e,u);for(let C=0;C<d.length;C++)w(e.state.env,`${u}_${o+C}`,d[C]);let S=parseInt(N(e.state.env,`${u}__length`,"0"),10),A=o+d.length;return w(e.state.env,`${u}__length`,String(Math.max(S,A))),e.state.groupStdin!==void 0&&!r&&(e.state.groupStdin=p),O(p,p,0)}function fo(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),c=a.indexOf(":");if(c===-1)return null;let u=Number.parseInt(a.slice(0,c),10);if(Number.isNaN(u)||u<0)return null;let l=a.slice(c+1);return{path:i,position:u,content:l}}function ho(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}function Qs(e,t,s,r=-1){let n=z(s),i=!1,o=`
518
+ `,a="",c=-1,u=-1,l=null,f=-1,d=-1,h=[],g=0,m=!1,v=(D,T)=>{let $=1;for(;$<D.length;){let R=D[$];if(R==="r")i=!0,$++;else if(R==="s")$++;else{if(R==="d")return $+1<D.length?(o=D.substring($+1),{nextArgIndex:T+1}):T+1<t.length?(o=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(R==="n"){if($+1<D.length){let F=D.substring($+1);return c=Number.parseInt(F,10),(Number.isNaN(c)||c<0)&&(m=!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)&&(m=!0,c=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(R==="N"){if($+1<D.length){let F=D.substring($+1);return u=Number.parseInt(F,10),(Number.isNaN(u)||u<0)&&(m=!0,u=0),{nextArgIndex:T+1}}else if(T+1<t.length)return u=Number.parseInt(t[T+1],10),(Number.isNaN(u)||u<0)&&(m=!0,u=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else{if(R==="a")return $+1<D.length?(l=D.substring($+1),{nextArgIndex:T+1}):T+1<t.length?(l=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(R==="p")return $+1<D.length?(a=D.substring($+1),{nextArgIndex:T+1}):T+1<t.length?(a=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(R==="u"){if($+1<D.length){let F=D.substring($+1);return f=Number.parseInt(F,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(R==="t"){if($+1<D.length){let F=D.substring($+1);return d=Number.parseFloat(F),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(R==="e"||R==="i"||R==="P"){if(R==="i"&&T+1<t.length)return{nextArgIndex:T+2};$++}else $++}}}return{nextArgIndex:T+1}};for(;g<t.length;){let D=t[g];if(D.startsWith("-")&&D.length>1&&D!=="--"){let T=v(D,g);if(T.nextArgIndex===-1)return{stdout:p,stderr:p,exitCode:2};if(T.nextArgIndex===-2)return{stdout:p,stderr:p,exitCode:1};g=T.nextArgIndex}else if(D==="--")for(g++;g<t.length;)h.push(t[g]),g++;else h.push(D),g++}if(m)return O(p,p,1);if(h.length===0&&l===null&&h.push("REPLY"),d===0){if(l)_e(e,l);else{for(let D of h)w(e.state.env,D,"");h.length===0&&w(e.state.env,"REPLY","")}return O(p,p,0)}if(d<0&&d!==-1)return O(p,p,1);let S=n;f>=0?e.state.fileDescriptors?S=e.state.fileDescriptors.get(f)||"":S="":!S&&e.state.groupStdin!==void 0&&(S=z(e.state.groupStdin));let A=o===""?"\0":o,C="",y=0,b=!0,k=D=>{if(f>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(f,S.substring(D));else if(r>=0&&e.state.fileDescriptors){let T=e.state.fileDescriptors.get(r);if(T?.startsWith("__rw__:")){let $=fo(T);if($){let R=$.position+D;e.state.fileDescriptors.set(r,ho($.path,R,$.content))}}}else e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=E(S.substring(D)))};if(u>=0){let D=Math.min(u,S.length);C=S.substring(0,D),y=D,b=D>=u,k(y);let T=h[0]||"REPLY";w(e.state.env,T,C);for(let $=1;$<h.length;$++)w(e.state.env,h[$],"");return O(p,p,b?0:1)}else if(c>=0){let D=0,T=0,$=!1;for(;T<S.length&&D<c;){let R=S[T];if(R===A){y=T+1,$=!0;break}if(!i&&R==="\\"&&T+1<S.length){let F=S[T+1];if(F===A&&A===`
519
519
  `){T+=2,y=T;continue}if(F===A){T+=2,D++,C+=F,y=T;continue}C+=F,T+=2,D++,y=T}else C+=R,T++,D++,y=T}b=D>=c||$,k(y)}else{y=0;let D=0;for(;D<S.length;){let T=S[D];if(T===A){y=D+A.length,b=!0;break}if(!i&&T==="\\"&&D+1<S.length){let $=S[D+1];if($===`
520
520
  `){D+=2;continue}if($===A){C+=$,D+=2;continue}C+=T,C+=$,D+=2;continue}C+=T,D++}if(D>=S.length&&(b=!1,y=D,C.length===0&&S.length===0)){for(let T of h)w(e.state.env,T,"");return l&&_e(e,l),O(p,p,1)}k(y)}A===`
521
521
  `&&C.endsWith(`
522
- `)&&(C=C.slice(0,-1));let P=D=>i?D:D.replace(/\\(.)/g,"$1");if(h.length===1&&h[0]==="REPLY")return w(e.state.env,"REPLY",P(C)),O(p,p,b?0:1);let M=br(e.state.env);if(l){let{words:D}=ls(C,M,void 0,i),T=e.limits?.maxArrayElements??1e5;if(D.length>T)return O(p,E(`read: array element limit exceeded (${T})
523
- `),1);_e(e,l);for(let $=0;$<D.length;$++)w(e.state.env,`${l}_${$}`,P(D[$]));return O(p,p,b?0:1)}let I=h.length,{words:W,wordStarts:B}=ls(C,M,I,i);for(let D=0;D<h.length;D++){let T=h[D];if(D<h.length-1)w(e.state.env,T,P(W[D]??""));else if(D<B.length){let $=C.substring(B[D]);$=Er($,M,i),$=P($),w(e.state.env,T,$)}else w(e.state.env,T,"")}return O(p,p,b?0:1)}function Js(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return _("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let r=t[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return _(`bash: return: ${r}: numeric argument required
522
+ `)&&(C=C.slice(0,-1));let P=D=>i?D:D.replace(/\\(.)/g,"$1");if(h.length===1&&h[0]==="REPLY")return w(e.state.env,"REPLY",P(C)),O(p,p,b?0:1);let M=Er(e.state.env);if(l){let{words:D}=ls(C,M,void 0,i),T=e.limits?.maxArrayElements??1e5;if(D.length>T)return O(p,E(`read: array element limit exceeded (${T})
523
+ `),1);_e(e,l);for(let $=0;$<D.length;$++)w(e.state.env,`${l}_${$}`,P(D[$]));return O(p,p,b?0:1)}let I=h.length,{words:W,wordStarts:B}=ls(C,M,I,i);for(let D=0;D<h.length;D++){let T=h[D];if(D<h.length-1)w(e.state.env,T,P(W[D]??""));else if(D<B.length){let $=C.substring(B[D]);$=$r($,M,i),$=P($),w(e.state.env,T,$)}else w(e.state.env,T,"")}return O(p,p,b?0:1)}function Js(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return _("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let r=t[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return _(`bash: return: ${r}: numeric argument required
524
524
  `,2);s=(n%256+256)%256}throw new ue(s)}var Xt=`set: usage: set [-eux] [+eux] [-o option] [+o option]
525
525
  Options:
526
526
  -e Exit immediately if a command exits with non-zero status
@@ -537,56 +537,56 @@ Options:
537
537
  +o pipefail Disable pipefail
538
538
  -o xtrace Same as -x
539
539
  +o xtrace Disable xtrace
540
- `,En=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]]),$n=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]]),Sn=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],Pn=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function An(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,Xe(e))}function ho(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function po(e,t){let s=re(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=N(e.state.env,`${t}_${n}`,"");return`[${n}]=${Ue(i)}`});return`${t}=(${r.join(" ")})`}function mo(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function yo(e,t){let s=Le(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=N(e.state.env,`${t}_${n}`,"");return`[${mo(n)}]=${Ue(i)}`});return`${t}=(${r.join(" ")} )`}function go(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let n=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(n){let i=n[1];s.has(i)||t.add(i)}}return t}function wo(e){return e.state.associativeArrays??new Set}function tr(e,t){if(t.includes("--help"))return U(Xt);if(t.length===0){let r=go(e),n=wo(e),i=c=>{for(let u of n){let l=`${u}_`,f=`${u}__length`;if(c!==f&&c.startsWith(l)){if(c.slice(l.length).startsWith("_length"))continue;return!0}}return!1},o=[];for(let[c,u]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)||r.has(c)||n.has(c))continue;let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(l&&r.has(l[1]))continue;let f=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&r.has(f[1])||i(c)||f&&n.has(f[1])||o.push([c,z(u)])}let a=[];for(let[c,u]of o.sort(([l],[f])=>l<f?-1:l>f?1:0))a.push(`${c}=${Zt(u)}`);for(let c of[...r].sort((u,l)=>u<l?-1:u>l?1:0))a.push(po(e,c));for(let c of[...n].sort((u,l)=>u<l?-1:u>l?1:0))a.push(yo(e,c));return a.sort((c,u)=>{let l=c.split("=")[0],f=u.split("=")[0];return l<f?-1:l>f?1:0}),U(a.length>0?`${a.join(`
540
+ `,$n=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]]),Sn=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]]),Pn=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],An=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function _n(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,Xe(e))}function po(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function mo(e,t){let s=re(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=N(e.state.env,`${t}_${n}`,"");return`[${n}]=${Ue(i)}`});return`${t}=(${r.join(" ")})`}function yo(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function go(e,t){let s=Le(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=N(e.state.env,`${t}_${n}`,"");return`[${yo(n)}]=${Ue(i)}`});return`${t}=(${r.join(" ")} )`}function wo(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let n=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(n){let i=n[1];s.has(i)||t.add(i)}}return t}function vo(e){return e.state.associativeArrays??new Set}function tr(e,t){if(t.includes("--help"))return U(Xt);if(t.length===0){let r=wo(e),n=vo(e),i=c=>{for(let u of n){let l=`${u}_`,f=`${u}__length`;if(c!==f&&c.startsWith(l)){if(c.slice(l.length).startsWith("_length"))continue;return!0}}return!1},o=[];for(let[c,u]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)||r.has(c)||n.has(c))continue;let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(l&&r.has(l[1]))continue;let f=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&r.has(f[1])||i(c)||f&&n.has(f[1])||o.push([c,z(u)])}let a=[];for(let[c,u]of o.sort(([l],[f])=>l<f?-1:l>f?1:0))a.push(`${c}=${Zt(u)}`);for(let c of[...r].sort((u,l)=>u<l?-1:u>l?1:0))a.push(mo(e,c));for(let c of[...n].sort((u,l)=>u<l?-1:u>l?1:0))a.push(go(e,c));return a.sort((c,u)=>{let l=c.split("=")[0],f=u.split("=")[0];return l<f?-1:l>f?1:0}),U(a.length>0?`${a.join(`
541
541
  `)}
542
- `:"")}let s=0;for(;s<t.length;){let r=t[s];if((r==="-o"||r==="+o")&&ho(t,s)){let n=t[s+1];if(!$n.has(n)){let i=`bash: set: ${n}: invalid option name
543
- ${Xt}`;if(e.state.options.posix)throw new Ee(1,p,E(i));return _(i)}An(e,$n.get(n)??null,r==="-o"),s+=2;continue}if(r==="-o"){let n=Sn.map(a=>`${a.padEnd(16)}${e.state.options[a]?"on":"off"}`),i=Pn.map(a=>`${a.padEnd(16)}off`),o=[...n,...i].sort();return U(`${o.join(`
542
+ `:"")}let s=0;for(;s<t.length;){let r=t[s];if((r==="-o"||r==="+o")&&po(t,s)){let n=t[s+1];if(!Sn.has(n)){let i=`bash: set: ${n}: invalid option name
543
+ ${Xt}`;if(e.state.options.posix)throw new Ee(1,p,E(i));return _(i)}_n(e,Sn.get(n)??null,r==="-o"),s+=2;continue}if(r==="-o"){let n=Pn.map(a=>`${a.padEnd(16)}${e.state.options[a]?"on":"off"}`),i=An.map(a=>`${a.padEnd(16)}off`),o=[...n,...i].sort();return U(`${o.join(`
544
544
  `)}
545
- `)}if(r==="+o"){let n=Sn.map(a=>`set ${e.state.options[a]?"-o":"+o"} ${a}`),i=Pn.map(a=>`set +o ${a}`),o=[...n,...i].sort();return U(`${o.join(`
545
+ `)}if(r==="+o"){let n=Pn.map(a=>`set ${e.state.options[a]?"-o":"+o"} ${a}`),i=An.map(a=>`set +o ${a}`),o=[...n,...i].sort();return U(`${o.join(`
546
546
  `)}
547
- `)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let n=r[0]==="-";for(let i=1;i<r.length;i++){let o=r[i];if(!En.has(o)){let a=`bash: set: ${r[0]}${o}: invalid option
548
- ${Xt}`;if(e.state.options.posix)throw new Ee(1,p,E(a));return _(a)}An(e,En.get(o)??null,n)}s++;continue}if(r==="--")return er(e,t.slice(s+1)),V;if(r==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,Xe(e),s+1<t.length)return er(e,t.slice(s+1)),V;s++;continue}if(r==="+"){s++;continue}if(r.startsWith("-")||r.startsWith("+")){let n=`bash: set: ${r}: invalid option
547
+ `)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let n=r[0]==="-";for(let i=1;i<r.length;i++){let o=r[i];if(!$n.has(o)){let a=`bash: set: ${r[0]}${o}: invalid option
548
+ ${Xt}`;if(e.state.options.posix)throw new Ee(1,p,E(a));return _(a)}_n(e,$n.get(o)??null,n)}s++;continue}if(r==="--")return er(e,t.slice(s+1)),V;if(r==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,Xe(e),s+1<t.length)return er(e,t.slice(s+1)),V;s++;continue}if(r==="+"){s++;continue}if(r.startsWith("-")||r.startsWith("+")){let n=`bash: set: ${r}: invalid option
549
549
  ${Xt}`;if(e.state.options.posix)throw new Ee(1,p,E(n));return _(n)}return er(e,t.slice(s)),V}return V}function er(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let r=0;r<t.length;r++)w(e.state.env,String(r+1),t[r]);w(e.state.env,"#",String(t.length)),w(e.state.env,"@",t.join(" ")),w(e.state.env,"*",t.join(" "))}function sr(e,t){let s=1;if(t.length>0){let o=Number.parseInt(t[0],10);if(Number.isNaN(o)||o<0){let a=`bash: shift: ${t[0]}: numeric argument required
550
550
  `;if(e.state.options.posix)throw new Ee(1,p,E(a));return _(a)}s=o}let r=Number.parseInt(N(e.state.env,"#","0"),10);if(s>r){let o=`bash: shift: shift count out of range
551
551
  `;if(e.state.options.posix)throw new Ee(1,p,E(o));return _(o)}if(s===0)return V;let n=[];for(let o=1;o<=r;o++)n.push(N(e.state.env,String(o))||"");let i=n.slice(s);for(let o=1;o<=r;o++)e.state.env.delete(String(o));for(let o=0;o<i.length;o++)w(e.state.env,String(o+1),i[o]);return w(e.state.env,"#",String(i.length)),w(e.state.env,"@",i.join(" ")),V}async function rr(e,t){let s=t;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return O(p,E(`bash: source: filename argument required
552
552
  `),2);let r=s[0],n=null,i=null;if(r.includes("/")){let u=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(u),n=u}catch{}}else{let l=N(e.state.env,"PATH","").split(":").filter(f=>f);for(let f of l){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFile(d),n=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(f),n=f}catch{}}}if(i===null)return _(`bash: ${r}: No such file or directory
553
553
  `);let o=new Map;if(s.length>1){for(let l=1;l<=9;l++)o.set(String(l),N(e.state.env,String(l)));o.set("#",N(e.state.env,"#")),o.set("@",N(e.state.env,"@"));let u=s.slice(1);w(e.state.env,"#",String(u.length)),w(e.state.env,"@",u.join(" "));for(let l=0;l<u.length&&l<9;l++)w(e.state.env,String(l+1),u[l]);for(let l=u.length+1;l<=9;l++)e.state.env.delete(String(l))}let a=e.state.currentSource,c=()=>{if(e.state.sourceDepth--,e.state.currentSource=a,s.length>1)for(let[u,l]of o)l===void 0?e.state.env.delete(u):w(e.state.env,u,l)};e.state.sourceDepth++,e.state.currentSource=r;try{let u=Ae(i),l=await e.executeScript(u);return c(),l}catch(u){if(c(),u instanceof G)throw u;if(u instanceof ue)return O(u.stdout,u.stderr,u.exitCode);if(u.name==="ParseException")return _(`bash: ${r}: ${u.message}
554
- `);throw u}}function _n(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function vo(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function kn(e,t){if(vo(t))return null;try{let s=new H,r=J(s,t);return await Z(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function Cn(e,t){if(e.state.localVarStack?.has(t)){let r=Ut(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let n=e.state.localVarStack?.get(t);if(!n||n.length===0)Ht(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),nr(e,t);else{let i=n[n.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),Ht(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let n=e.state.localScopes[r];if(n.has(t)){let i=n.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),n.delete(t);let o=!1;for(let a=r-1;a>=0;a--)if(e.state.localScopes[a].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,a+1),o=!0;break}return o||Ht(e,t),!0}}return!1}function nr(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 r=e.state.tempEnvBindings[s];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function xn(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),n=new H().parseWordFromString(s,!0,!1);return L(e,n)}if(t.includes("$")){let r=new H().parseWordFromString(t,!1,!1);return L(e,r)}return t}async function ir(e,t){let s="both",r="",n=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 u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let d=u[1],h=u[2];if(h==="@"||h==="*"){let C=Se(e,d);for(let[y]of C)e.state.env.delete(`${d}_${y}`);e.state.env.delete(d);continue}let g=e.state.associativeArrays?.has(d);if(g){let C=await xn(e,h);e.state.env.delete(`${d}_${C}`);continue}let m=fs(e,d),v=e.state.declaredVars?.has(d);if((e.state.env.has(d)||v)&&!m&&!g){r+=`bash: unset: ${d}: not an array variable
555
- `,n=1;continue}let A=await kn(e,h);if(A===null&&m){r+=`bash: unset: ${h}: not a valid identifier
554
+ `);throw u}}function kn(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function bo(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function Cn(e,t){if(bo(t))return null;try{let s=new H,r=J(s,t);return await Z(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function xn(e,t){if(e.state.localVarStack?.has(t)){let r=Ut(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let n=e.state.localVarStack?.get(t);if(!n||n.length===0)Ht(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),nr(e,t);else{let i=n[n.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),Ht(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let n=e.state.localScopes[r];if(n.has(t)){let i=n.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),n.delete(t);let o=!1;for(let a=r-1;a>=0;a--)if(e.state.localScopes[a].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,a+1),o=!0;break}return o||Ht(e,t),!0}}return!1}function nr(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 r=e.state.tempEnvBindings[s];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function Nn(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),n=new H().parseWordFromString(s,!0,!1);return L(e,n)}if(t.includes("$")){let r=new H().parseWordFromString(t,!1,!1);return L(e,r)}return t}async function ir(e,t){let s="both",r="",n=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 u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let d=u[1],h=u[2];if(h==="@"||h==="*"){let C=Se(e,d);for(let[y]of C)e.state.env.delete(`${d}_${y}`);e.state.env.delete(d);continue}let g=e.state.associativeArrays?.has(d);if(g){let C=await Nn(e,h);e.state.env.delete(`${d}_${C}`);continue}let m=fs(e,d),v=e.state.declaredVars?.has(d);if((e.state.env.has(d)||v)&&!m&&!g){r+=`bash: unset: ${d}: not an array variable
555
+ `,n=1;continue}let A=await Cn(e,h);if(A===null&&m){r+=`bash: unset: ${h}: not a valid identifier
556
556
  `,n=1;continue}if(A===null)continue;if(A<0){let C=Se(e,d),y=C.length,b=e.state.currentLine;if(y===0){r+=`bash: line ${b}: unset: [${A}]: bad array subscript
557
557
  `,n=1;continue}let k=y+A;if(k<0){r+=`bash: line ${b}: unset: [${A}]: bad array subscript
558
- `,n=1;continue}let P=C[k][0];e.state.env.delete(`${d}_${P}`);continue}e.state.env.delete(`${d}_${A}`);continue}if(!_n(i)){r+=`bash: unset: \`${i}': not a valid identifier
558
+ `,n=1;continue}let P=C[k][0];e.state.env.delete(`${d}_${P}`);continue}e.state.env.delete(`${d}_${A}`);continue}if(!kn(i)){r+=`bash: unset: \`${i}': not a valid identifier
559
559
  `,n=1;continue}let l=i;if(fe(e,i)){let d=ke(e,i);d&&d!==i&&(l=d)}if(Be(e,l)){r+=`bash: unset: ${l}: cannot unset: readonly variable
560
- `,n=1;continue}let f=Je(e,l);if(f!==void 0&&f!==e.state.callDepth)Cn(e,l);else if(e.state.fullyUnsetLocals?.has(l))e.state.env.delete(l);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(l),h=e.state.mutatedTempEnvVars?.has(l);if((d||h)&&e.state.localVarStack?.has(l)){let g=Ut(e,l);g?g.value===void 0?e.state.env.delete(l):e.state.env.set(l,g.value):e.state.env.delete(l)}else e.state.env.delete(l)}else nr(e,l)||e.state.env.delete(l);e.state.exportedVars?.delete(l);continue}let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let u=o[1],l=o[2];if(l==="@"||l==="*"){let m=Se(e,u);for(let[v]of m)e.state.env.delete(`${u}_${v}`);e.state.env.delete(u);continue}let f=e.state.associativeArrays?.has(u);if(f){let m=await xn(e,l);e.state.env.delete(`${u}_${m}`);continue}let d=fs(e,u);if(e.state.env.has(u)&&!d&&!f){r+=`bash: unset: ${u}: not an array variable
561
- `,n=1;continue}let g=await kn(e,l);if(g===null&&d){r+=`bash: unset: ${l}: not a valid identifier
560
+ `,n=1;continue}let f=Je(e,l);if(f!==void 0&&f!==e.state.callDepth)xn(e,l);else if(e.state.fullyUnsetLocals?.has(l))e.state.env.delete(l);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(l),h=e.state.mutatedTempEnvVars?.has(l);if((d||h)&&e.state.localVarStack?.has(l)){let g=Ut(e,l);g?g.value===void 0?e.state.env.delete(l):e.state.env.set(l,g.value):e.state.env.delete(l)}else e.state.env.delete(l)}else nr(e,l)||e.state.env.delete(l);e.state.exportedVars?.delete(l);continue}let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let u=o[1],l=o[2];if(l==="@"||l==="*"){let m=Se(e,u);for(let[v]of m)e.state.env.delete(`${u}_${v}`);e.state.env.delete(u);continue}let f=e.state.associativeArrays?.has(u);if(f){let m=await Nn(e,l);e.state.env.delete(`${u}_${m}`);continue}let d=fs(e,u);if(e.state.env.has(u)&&!d&&!f){r+=`bash: unset: ${u}: not an array variable
561
+ `,n=1;continue}let g=await Cn(e,l);if(g===null&&d){r+=`bash: unset: ${l}: not a valid identifier
562
562
  `,n=1;continue}if(g===null)continue;if(g<0){let m=Se(e,u),v=m.length,S=e.state.currentLine;if(v===0){r+=`bash: line ${S}: unset: [${g}]: bad array subscript
563
563
  `,n=1;continue}let A=v+g;if(A<0){r+=`bash: line ${S}: unset: [${g}]: bad array subscript
564
- `,n=1;continue}let C=m[A][0];e.state.env.delete(`${u}_${C}`);continue}e.state.env.delete(`${u}_${g}`);continue}if(!_n(i)){r+=`bash: unset: \`${i}': not a valid identifier
564
+ `,n=1;continue}let C=m[A][0];e.state.env.delete(`${u}_${C}`);continue}e.state.env.delete(`${u}_${g}`);continue}if(!kn(i)){r+=`bash: unset: \`${i}': not a valid identifier
565
565
  `,n=1;continue}let a=i;if(fe(e,i)){let u=ke(e,i);u&&u!==i&&(a=u)}if(Be(e,a)){r+=`bash: unset: ${a}: cannot unset: readonly variable
566
- `,n=1;continue}let c=Je(e,a);if(c!==void 0&&c!==e.state.callDepth)Cn(e,a);else if(e.state.fullyUnsetLocals?.has(a))e.state.env.delete(a);else if(c!==void 0){let u=e.state.accessedTempEnvVars?.has(a),l=e.state.mutatedTempEnvVars?.has(a);if((u||l)&&e.state.localVarStack?.has(a)){let f=Ut(e,a);f?f.value===void 0?e.state.env.delete(a):e.state.env.set(a,f.value):e.state.env.delete(a)}else e.state.env.delete(a)}else nr(e,a)||e.state.env.delete(a);e.state.exportedVars?.delete(a),e.state.functions.delete(i)}return O(p,E(r),n)}var or=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],bo=["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 Qt(e){return or.includes(e)}function Eo(e){return bo.includes(e)}function Nn(e,t){let s=!1,r=!1,n=!1,i=!1,o=!1,a=[],c=0;for(;c<t.length;){let d=t[c];if(d==="--"){c++;break}if(d.startsWith("-")&&d.length>1){for(let h=1;h<d.length;h++){let g=d[h];switch(g){case"s":s=!0;break;case"u":r=!0;break;case"p":n=!0;break;case"q":i=!0;break;case"o":o=!0;break;default:return{exitCode:2,stdout:p,stderr:E(`shopt: -${g}: invalid option
567
- `)}}}c++}else break}for(;c<t.length;)a.push(t[c]),c++;if(o)return $o(e,a,s,r,n,i);if(s&&r)return{exitCode:1,stdout:p,stderr:E(`shopt: cannot set and unset shell options simultaneously
566
+ `,n=1;continue}let c=Je(e,a);if(c!==void 0&&c!==e.state.callDepth)xn(e,a);else if(e.state.fullyUnsetLocals?.has(a))e.state.env.delete(a);else if(c!==void 0){let u=e.state.accessedTempEnvVars?.has(a),l=e.state.mutatedTempEnvVars?.has(a);if((u||l)&&e.state.localVarStack?.has(a)){let f=Ut(e,a);f?f.value===void 0?e.state.env.delete(a):e.state.env.set(a,f.value):e.state.env.delete(a)}else e.state.env.delete(a)}else nr(e,a)||e.state.env.delete(a);e.state.exportedVars?.delete(a),e.state.functions.delete(i)}return O(p,E(r),n)}var or=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],Eo=["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 Qt(e){return or.includes(e)}function $o(e){return Eo.includes(e)}function Tn(e,t){let s=!1,r=!1,n=!1,i=!1,o=!1,a=[],c=0;for(;c<t.length;){let d=t[c];if(d==="--"){c++;break}if(d.startsWith("-")&&d.length>1){for(let h=1;h<d.length;h++){let g=d[h];switch(g){case"s":s=!0;break;case"u":r=!0;break;case"p":n=!0;break;case"q":i=!0;break;case"o":o=!0;break;default:return{exitCode:2,stdout:p,stderr:E(`shopt: -${g}: invalid option
567
+ `)}}}c++}else break}for(;c<t.length;)a.push(t[c]),c++;if(o)return So(e,a,s,r,n,i);if(s&&r)return{exitCode:1,stdout:p,stderr:E(`shopt: cannot set and unset shell options simultaneously
568
568
  `)};if(a.length===0){if(s||r){let h=[];for(let g of or){let m=e.state.shoptOptions[g];s&&m?h.push(n?`shopt -s ${g}`:`${g} on`):r&&!m&&h.push(n?`shopt -u ${g}`:`${g} off`)}return{exitCode:0,stdout:h.length>0?E(`${h.join(`
569
569
  `)}
570
570
  `):p,stderr:p}}let d=[];for(let h of or){let g=e.state.shoptOptions[h];d.push(n?`shopt ${g?"-s":"-u"} ${h}`:`${h} ${g?"on":"off"}`)}return{exitCode:0,stdout:E(`${d.join(`
571
571
  `)}
572
- `),stderr:p}}let u=!1,l="",f=[];for(let d of a){if(!Qt(d)&&!Eo(d)){l+=`shopt: ${d}: invalid shell option name
572
+ `),stderr:p}}let u=!1,l="",f=[];for(let d of a){if(!Qt(d)&&!$o(d)){l+=`shopt: ${d}: invalid shell option name
573
573
  `,u=!0;continue}if(s)Qt(d)&&(e.state.shoptOptions[d]=!0,ys(e));else if(r)Qt(d)&&(e.state.shoptOptions[d]=!1,ys(e));else if(Qt(d)){let h=e.state.shoptOptions[d];i?h||(u=!0):n?(f.push(`shopt ${h?"-s":"-u"} ${d}`),h||(u=!0)):(f.push(`${d} ${h?"on":"off"}`),h||(u=!0))}else i?u=!0:n?(f.push(`shopt -u ${d}`),u=!0):(f.push(`${d} off`),u=!0)}return{exitCode:u?1:0,stdout:f.length>0?E(`${f.join(`
574
574
  `)}
575
- `):p,stderr:E(l)}}function $o(e,t,s,r,n,i){let o=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"]]),a=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],c=[...o.keys(),...a].sort();if(t.length===0){let d=[];for(let h of c){let g=a.includes(h),m=o.get(h),v=g||!m?!1:e.state.options[m];s&&!v||r&&v||d.push(n?`set ${v?"-o":"+o"} ${h}`:`${h} ${v?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?E(`${d.join(`
575
+ `):p,stderr:E(l)}}function So(e,t,s,r,n,i){let o=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"]]),a=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],c=[...o.keys(),...a].sort();if(t.length===0){let d=[];for(let h of c){let g=a.includes(h),m=o.get(h),v=g||!m?!1:e.state.options[m];s&&!v||r&&v||d.push(n?`set ${v?"-o":"+o"} ${h}`:`${h} ${v?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?E(`${d.join(`
576
576
  `)}
577
577
  `):p,stderr:p}}let u=!1,l="",f=[];for(let d of t){let h=o.has(d),g=a.includes(d);if(!h&&!g){l+=`shopt: ${d}: invalid option name
578
578
  `,u=!0;continue}if(g){s||r||(i?u=!0:n?(f.push(`set +o ${d}`),u=!0):(f.push(`${d} off`),u=!0));continue}let m=o.get(d);if(m)if(s)m==="vi"?e.state.options.emacs=!1:m==="emacs"&&(e.state.options.vi=!1),e.state.options[m]=!0,Xe(e);else if(r)e.state.options[m]=!1,Xe(e);else{let v=e.state.options[m];i?v||(u=!0):n?(f.push(`set ${v?"-o":"+o"} ${d}`),v||(u=!0)):(f.push(`${d} ${v?"on":"off"}`),v||(u=!0))}}return{exitCode:u?1:0,stdout:f.length>0?E(`${f.join(`
579
579
  `)}
580
- `):p,stderr:E(l)}}async function Tn(e,t,s){if(t.includes("/")){let o=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(o))return{error:"not_found",path:o};let a=o.split("/").pop()||t,c=e.commands.get(a);try{let u=await e.fs.stat(o);return u.isDirectory?{error:"permission_denied",path:o}:c?{cmd:c,path:o}:(u.mode&73)!==0?{script:!0,path:o}:{error:"permission_denied",path:o}}catch{return{error:"not_found",path:o}}}if(!s&&e.state.hashTable){let o=e.state.hashTable.get(t);if(o)if(await e.fs.exists(o)){let a=e.commands.get(t);if(a)return{cmd:a,path:o};try{let c=await e.fs.stat(o);if(!c.isDirectory&&(c.mode&73)!==0)return{script:!0,path:o}}catch{}}else e.state.hashTable.delete(t)}let n=(s??N(e.state.env,"PATH","/usr/bin:/bin")).split(":");for(let o of n){if(!o)continue;let c=`${o.startsWith("/")?o:e.fs.resolvePath(e.state.cwd,o)}/${t}`;if(await e.fs.exists(c))try{let u=await e.fs.stat(c);if(u.isDirectory)continue;let l=(u.mode&73)!==0,f=e.commands.get(t),d=o==="/bin"||o==="/usr/bin";if(f&&d)return{cmd:f,path:c};if(l){if(f&&!d)return{script:!0,path:c};if(!f)return{script:!0,path:c}}}catch{}}if(!await e.fs.exists("/usr/bin")){let o=e.commands.get(t);if(o)return{cmd:o,path:`/usr/bin/${t}`}}return null}async function Jt(e,t){let s=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let o=await e.fs.stat(i);o.isDirectory||(o.mode&73)!==0&&s.push(t)}catch{}return s}let n=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let i of n){if(!i)continue;let a=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}s.push(i.startsWith("/")?a:`${i}/${t}`)}}return s}async function Rn(e,t,s,r){let n=!1,i=!1,o=!1,a=!1,c=!1,u=[];for(let m of t)if(m.startsWith("-")&&m.length>1)for(let v of m.slice(1))v==="t"?n=!0:v==="p"?i=!0:v==="P"?o=!0:v==="a"?a=!0:v==="f"&&(c=!0);else u.push(m);let l="",f="",d=0,h=!1,g=!1;for(let m of u){let v=!1;if(o){if(a){let k=await r(m);if(k.length>0){for(let P of k)l+=`${P}
580
+ `):p,stderr:E(l)}}async function On(e,t,s){if(t.includes("/")){let o=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(o))return{error:"not_found",path:o};let a=o.split("/").pop()||t,c=e.commands.get(a);try{let u=await e.fs.stat(o);return u.isDirectory?{error:"permission_denied",path:o}:c?{cmd:c,path:o}:(u.mode&73)!==0?{script:!0,path:o}:{error:"permission_denied",path:o}}catch{return{error:"not_found",path:o}}}if(!s&&e.state.hashTable){let o=e.state.hashTable.get(t);if(o)if(await e.fs.exists(o)){let a=e.commands.get(t);if(a)return{cmd:a,path:o};try{let c=await e.fs.stat(o);if(!c.isDirectory&&(c.mode&73)!==0)return{script:!0,path:o}}catch{}}else e.state.hashTable.delete(t)}let n=(s??N(e.state.env,"PATH","/usr/bin:/bin")).split(":");for(let o of n){if(!o)continue;let c=`${o.startsWith("/")?o:e.fs.resolvePath(e.state.cwd,o)}/${t}`;if(await e.fs.exists(c))try{let u=await e.fs.stat(c);if(u.isDirectory)continue;let l=(u.mode&73)!==0,f=e.commands.get(t),d=o==="/bin"||o==="/usr/bin";if(f&&d)return{cmd:f,path:c};if(l){if(f&&!d)return{script:!0,path:c};if(!f)return{script:!0,path:c}}}catch{}}if(!await e.fs.exists("/usr/bin")){let o=e.commands.get(t);if(o)return{cmd:o,path:`/usr/bin/${t}`}}return null}async function Jt(e,t){let s=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let o=await e.fs.stat(i);o.isDirectory||(o.mode&73)!==0&&s.push(t)}catch{}return s}let n=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let i of n){if(!i)continue;let a=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}s.push(i.startsWith("/")?a:`${i}/${t}`)}}return s}async function Mn(e,t,s,r){let n=!1,i=!1,o=!1,a=!1,c=!1,u=[];for(let m of t)if(m.startsWith("-")&&m.length>1)for(let v of m.slice(1))v==="t"?n=!0:v==="p"?i=!0:v==="P"?o=!0:v==="a"?a=!0:v==="f"&&(c=!0);else u.push(m);let l="",f="",d=0,h=!1,g=!1;for(let m of u){let v=!1;if(o){if(a){let k=await r(m);if(k.length>0){for(let P of k)l+=`${P}
581
581
  `;h=!0,v=!0}}else{let k=await s(m);k&&(l+=`${k}
582
582
  `,h=!0,v=!0)}v||(g=!0);continue}let S=!c&&e.state.functions.has(m);if(a&&S){if(!i)if(n)l+=`function
583
- `;else{let k=e.state.functions.get(m),P=k?On(m,k):`${m} is a function
583
+ `;else{let k=e.state.functions.get(m),P=k?Dn(m,k):`${m} is a function
584
584
  `;l+=P}v=!0}let A=e.state.env.get(`BASH_ALIAS_${m}`);if(A!==void 0&&(a||!v)&&(i||(n?l+=`alias
585
585
  `:l+=`${m} is aliased to \`${z(A)}'
586
586
  `),v=!0,!a)||Ps.has(m)&&(a||!v)&&(i||(n?l+=`keyword
587
587
  `:l+=`${m} is a shell keyword
588
588
  `),v=!0,!a))continue;if(!a&&S&&!v){if(!i)if(n)l+=`function
589
- `;else{let k=e.state.functions.get(m),P=k?On(m,k):`${m} is a function
589
+ `;else{let k=e.state.functions.get(m),P=k?Dn(m,k):`${m} is a function
590
590
  `;l+=P}v=!0;continue}if(!(et.has(m)&&(a||!v)&&(i||(n?l+=`builtin
591
591
  `:l+=`${m} is a shell builtin
592
592
  `),v=!0,!a))){if(a){let k=await r(m);for(let P of k)i?l+=`${P}
@@ -596,12 +596,12 @@ ${Xt}`;if(e.state.options.posix)throw new Ee(1,p,E(n));return _(n)}return er(e,t
596
596
  `:n?l+=`file
597
597
  `:l+=`${m} is ${k}
598
598
  `,h=!0,v=!0)}if(!v&&(g=!0,!n&&!i)){let k=!0;if(m.includes("/")){let P=e.fs.resolvePath(e.state.cwd,m);await e.fs.exists(P)&&(k=!1)}k&&(f+=`bash: type: ${m}: not found
599
- `)}}}return i?d=g&&!h?1:0:d=g?1:0,O(E(l),E(f),d)}function On(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(n=>gt(n)).join("; "):s=gt(t.body),`${e} is a function
599
+ `)}}}return i?d=g&&!h?1:0:d=g?1:0,O(E(l),E(f),d)}function Dn(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(n=>gt(n)).join("; "):s=gt(t.body),`${e} is a function
600
600
  ${e} ()
601
601
  {
602
602
  ${s}
603
603
  }
604
- `}function gt(e){if(Array.isArray(e))return e.map(t=>gt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let r=e.pipelines[s];t.push(So(r)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(Dn(t.name));for(let r of t.args)s.push(Dn(r));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>gt(r)).join("; ")}; }`:"..."}function So(e){let t=e.commands.map(s=>gt(s));return(e.negated?"! ":"")+t.join(" | ")}function Dn(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(r=>In(r)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=In(s);return t}function In(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function Mn(e,t,s,r){let n="",i="",o=0;for(let a of t){if(!a){o=1;continue}let c=e.state.env.get(`BASH_ALIAS_${a}`);if(c!==void 0)r?n+=`${a} is an alias for "${z(c)}"
604
+ `}function gt(e){if(Array.isArray(e))return e.map(t=>gt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let r=e.pipelines[s];t.push(Po(r)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(In(t.name));for(let r of t.args)s.push(In(r));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>gt(r)).join("; ")}; }`:"..."}function Po(e){let t=e.commands.map(s=>gt(s));return(e.negated?"! ":"")+t.join(" | ")}function In(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(r=>Rn(r)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=Rn(s);return t}function Rn(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function Fn(e,t,s,r){let n="",i="",o=0;for(let a of t){if(!a){o=1;continue}let c=e.state.env.get(`BASH_ALIAS_${a}`);if(c!==void 0)r?n+=`${a} is an alias for "${z(c)}"
605
605
  `:n+=`alias ${a}='${z(c)}'
606
606
  `;else if(Ps.has(a))r?n+=`${a} is a shell keyword
607
607
  `:n+=`${a}
@@ -615,74 +615,74 @@ ${e} ()
615
615
  `),o=1)}else if(e.commands.has(a)){let l=N(e.state.env,"PATH","/usr/bin:/bin").split(":"),f=null;for(let d of l){if(!d)continue;let h=`${d}/${a}`;try{let g=await e.fs.stat(h);if(!g.isDirectory&&(g.mode&73)!==0){f=h;break}}catch{}}f||(f=`/usr/bin/${a}`),r?n+=`${a} is ${f}
616
616
  `:n+=`${f}
617
617
  `}else r&&(i+=`${a}: not found
618
- `),o=1}return O(E(n),E(i),o)}async function Fn(e,t){if(t.includes("/")){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let i=await e.fs.stat(n);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let n of r){if(!n)continue;let o=`${n.startsWith("/")?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(o)){try{if((await e.fs.stat(o)).isDirectory)continue}catch{continue}return`${n}/${t}`}}if(e.commands.has(t)){for(let n of r)if(n==="/usr/bin"||n==="/bin")return`${n}/${t}`;return`/usr/bin/${t}`}return null}async function Ln(e,t,s,r,n,i,o,a){let{ctx:c,runCommand:u}=e,l=Ze(s);if(c.coverage&&et.has(t)&&c.coverage.hit(`bash:builtin:${t}`),t==="export")return Gs(c,l);if(t==="unset")return ir(c,l);if(t==="exit")return Us(c,l);if(t==="local")return Ks(c,l);if(t==="set")return tr(c,l);if(t==="break")return ws(c,l);if(t==="continue")return Ts(c,l);if(t==="return")return Js(c,l);if(t==="eval"&&c.state.options.posix)return Yt(c,l,n);if(t==="shift")return sr(c,l);if(t==="getopts")return Kt(c,l);if(t==="compgen")return ks(c,l);if(t==="complete")return xs(c,l);if(t==="compopt")return Ns(c,l);if(t==="pushd")return await Bs(c,l);if(t==="popd")return js(c,l);if(t==="dirs")return Hs(c,l);if(t==="source"||t===".")return rr(c,l);if(t==="read")return Qs(c,l,n,a);if(t==="mapfile"||t==="readarray")return Xs(c,l,n);if(t==="declare"||t==="typeset")return Ws(c,l);if(t==="readonly")return zs(c,l);if(!i){let f=c.state.functions.get(t);if(f)return qt(c,f,l,n)}if(t==="eval")return Yt(c,l,n);if(t==="cd")return await vs(c,l);if(t===":"||t==="true")return V;if(t==="false")return Q(!1);if(t==="let")return Ys(c,l);if(t==="command")return Po(e,l,n);if(t==="builtin")return Ao(e,l,n);if(t==="shopt")return Nn(c,l);if(t==="exec"){if(s.length===0)return V;let[f,...d]=s;return u(z(f),d,[],n,!1,!1,-1)}if(t==="wait")return V;if(t==="type")return await Rn(c,l,f=>Fn(c,f),f=>Jt(c,f));if(t==="hash")return qs(c,l);if(t==="help")return Zs(c,l);if(t==="["||t==="test"){let f=l;if(t==="["){if(l[l.length-1]!=="]")return _("[: missing `]'\n",2);f=l.slice(0,-1)}return pt(c,f)}return null}async function Po(e,t,s){let{ctx:r,runCommand:n}=e;if(t.length===0)return V;let i=!1,o=!1,a=!1,c=t;for(;c.length>0&&c[0].startsWith("-");){let f=c[0];if(f==="--"){c=c.slice(1);break}for(let d of f.slice(1))d==="p"?i=!0:d==="V"?o=!0:d==="v"&&(a=!0);c=c.slice(1)}if(c.length===0)return V;if(a||o)return await Mn(r,c,a,o);let[u,...l]=c;return n(u,l.map(f=>E(f)),[],s,!0,i,-1)}async function Ao(e,t,s){let{runCommand:r}=e;if(t.length===0)return V;let n=t;if(n[0]==="--"&&(n=n.slice(1),n.length===0))return V;let i=n[0];if(!et.has(i))return _(`bash: builtin: ${i}: not a shell builtin
619
- `);let[,...o]=n;return r(i,o.map(a=>E(a)),[],s,!0,!1,-1)}async function Wn(e,t,s,r,n){let{ctx:i,buildExportedEnv:o,executeUserScript:a}=e,u=await Tn(i,t,n?"/usr/bin:/bin":void 0);if(!u)return Gr(t)?_(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
618
+ `),o=1}return O(E(n),E(i),o)}async function Ln(e,t){if(t.includes("/")){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let i=await e.fs.stat(n);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let n of r){if(!n)continue;let o=`${n.startsWith("/")?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(o)){try{if((await e.fs.stat(o)).isDirectory)continue}catch{continue}return`${n}/${t}`}}if(e.commands.has(t)){for(let n of r)if(n==="/usr/bin"||n==="/bin")return`${n}/${t}`;return`/usr/bin/${t}`}return null}async function Wn(e,t,s,r,n,i,o,a){let{ctx:c,runCommand:u}=e,l=Ze(s);if(c.coverage&&et.has(t)&&c.coverage.hit(`bash:builtin:${t}`),t==="export")return Gs(c,l);if(t==="unset")return ir(c,l);if(t==="exit")return Us(c,l);if(t==="local")return Ks(c,l);if(t==="set")return tr(c,l);if(t==="break")return ws(c,l);if(t==="continue")return Ts(c,l);if(t==="return")return Js(c,l);if(t==="eval"&&c.state.options.posix)return Yt(c,l,n);if(t==="shift")return sr(c,l);if(t==="getopts")return Kt(c,l);if(t==="compgen")return ks(c,l);if(t==="complete")return xs(c,l);if(t==="compopt")return Ns(c,l);if(t==="pushd")return await Bs(c,l);if(t==="popd")return js(c,l);if(t==="dirs")return Hs(c,l);if(t==="source"||t===".")return rr(c,l);if(t==="read")return Qs(c,l,n,a);if(t==="mapfile"||t==="readarray")return Xs(c,l,n);if(t==="declare"||t==="typeset")return Ws(c,l);if(t==="readonly")return zs(c,l);if(!i){let f=c.state.functions.get(t);if(f)return qt(c,f,l,n)}if(t==="eval")return Yt(c,l,n);if(t==="cd")return await vs(c,l);if(t===":"||t==="true")return V;if(t==="false")return Q(!1);if(t==="let")return Ys(c,l);if(t==="command")return Ao(e,l,n);if(t==="builtin")return _o(e,l,n);if(t==="shopt")return Tn(c,l);if(t==="exec"){if(s.length===0)return V;let[f,...d]=s;return u(z(f),d,[],n,!1,!1,-1)}if(t==="wait")return V;if(t==="type")return await Mn(c,l,f=>Ln(c,f),f=>Jt(c,f));if(t==="hash")return qs(c,l);if(t==="help")return Zs(c,l);if(t==="["||t==="test"){let f=l;if(t==="["){if(l[l.length-1]!=="]")return _("[: missing `]'\n",2);f=l.slice(0,-1)}return pt(c,f)}return null}async function Ao(e,t,s){let{ctx:r,runCommand:n}=e;if(t.length===0)return V;let i=!1,o=!1,a=!1,c=t;for(;c.length>0&&c[0].startsWith("-");){let f=c[0];if(f==="--"){c=c.slice(1);break}for(let d of f.slice(1))d==="p"?i=!0:d==="V"?o=!0:d==="v"&&(a=!0);c=c.slice(1)}if(c.length===0)return V;if(a||o)return await Fn(r,c,a,o);let[u,...l]=c;return n(u,l.map(f=>E(f)),[],s,!0,i,-1)}async function _o(e,t,s){let{runCommand:r}=e;if(t.length===0)return V;let n=t;if(n[0]==="--"&&(n=n.slice(1),n.length===0))return V;let i=n[0];if(!et.has(i))return _(`bash: builtin: ${i}: not a shell builtin
619
+ `);let[,...o]=n;return r(i,o.map(a=>E(a)),[],s,!0,!1,-1)}async function zn(e,t,s,r,n){let{ctx:i,buildExportedEnv:o,executeUserScript:a}=e,u=await On(i,t,n?"/usr/bin:/bin":void 0);if(!u)return qr(t)?_(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
620
620
  `,127):_(`bash: ${t}: command not found
621
621
  `,127);if("error"in u)return u.error==="permission_denied"?_(`bash: ${t}: Permission denied
622
622
  `,126):_(`bash: ${t}: No such file or directory
623
623
  `,127);if("script"in u)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,u.path)),await a(u.path,s,r);let{cmd:l,path:f}=u;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=qe(r)?i.state.groupStdin??p:r,h=o(),g={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:h,stdin:d,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage};try{return await l.execute(s,g)}catch(m){if(m instanceof ae)throw m;return _(`${t}: ${Te(m)}
624
624
  `)}}async function ar(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let r=p,n=p,i=0;try{for(let o of t){let a=await e.executeStatement(o);r=x(r,a.stdout),n=x(n,a.stderr),i=a.exitCode}}finally{e.state.inCondition=s}return{stdout:r,stderr:n,exitCode:i}}function wt(e,t,s,r){if(e instanceof ye)return t=x(t,e.stdout),s=x(s,e.stderr),e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:"rethrow",stdout:t,stderr:s,error:e}):{action:"break",stdout:t,stderr:s};if(e instanceof ge)return t=x(t,e.stdout),s=x(s,e.stderr),e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:"rethrow",stdout:t,stderr:s,error:e}):{action:"continue",stdout:t,stderr:s};if(e instanceof ue||e instanceof ve||e instanceof G||e instanceof ae)return e.prependOutput(t,s),{action:"rethrow",stdout:t,stderr:s,error:e};let n=Te(e);return{action:"error",stdout:t,stderr:x(s,E(`${n}
625
625
  `)),exitCode:1}}async function es(e,t,s=p,r=p){let n=s,i=r,o=0;try{for(let a of t){let c=await e.executeStatement(a);n=x(n,c.stdout),i=x(i,c.stderr),o=c.exitCode}}catch(a){if(At(a)||a instanceof ve||a instanceof G||a instanceof ae||a instanceof Me)throw a.prependOutput(n,i),a;return{stdout:n,stderr:x(i,E(`${Te(a)}
626
- `)),exitCode:1}}return{stdout:n,stderr:i,exitCode:o}}async function zn(e,t){let s=p,r=p;for(let n of t.clauses){let i=await ar(e,n.condition);if(s=x(s,i.stdout),r=x(r,i.stderr),i.exitCode===0)return es(e,n.body,s,r)}return t.elseBody?es(e,t.elseBody,s,r):{stdout:s,stderr:r,exitCode:0}}async function Vn(e,t){let s=await Ne(e,t.redirections);if(s)return s;let r=p,n=p,i=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return _(`bash: \`${t.variable}': not a valid identifier
627
- `);let a=[];if(t.words===null)a=N(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length===0)a=[];else try{for(let u of t.words){let l=await Ce(e,u);a.push(...l.values)}}catch(u){if(u instanceof Pt)return{stdout:p,stderr:u.stderr,exitCode:1};throw u}e.state.loopDepth++;try{for(let u of a){o++,o>e.limits.maxLoopIterations&&Re(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),w(e.state.env,t.variable,u);try{for(let l of t.body){let f=await e.executeStatement(l);r=x(r,f.stdout),n=x(n,f.stderr),i=f.exitCode}}catch(l){let f=wt(l,r,n,e.state.loopDepth);if(r=f.stdout,n=f.stderr,f.action==="break")break;if(f.action==="continue")continue;if(f.action==="error"){let d=O(r,n,f.exitCode??1);return Y(e,d,t.redirections)}throw f.error}}}finally{e.state.loopDepth--}let c=O(r,n,i);return Y(e,c,t.redirections)}async function Bn(e,t){let s=await Ne(e,t.redirections);if(s)return s;let r=t.line;r!==void 0&&(e.state.currentLine=r);let n=p,i=p,o=0,a=0;t.init&&await Z(e,t.init.expression),e.state.loopDepth++;try{for(;a++,a>e.limits.maxLoopIterations&&Re(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,i),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await Z(e,t.condition.expression)===0));){try{for(let u of t.body){let l=await e.executeStatement(u);n=x(n,l.stdout),i=x(i,l.stderr),o=l.exitCode}}catch(u){let l=wt(u,n,i,e.state.loopDepth);if(n=l.stdout,i=l.stderr,l.action==="break")break;if(l.action==="continue"){t.update&&await Z(e,t.update.expression);continue}if(l.action==="error"){let f=O(n,i,l.exitCode??1);return Y(e,f,t.redirections)}throw l.error}t.update&&await Z(e,t.update.expression)}}finally{e.state.loopDepth--}let c=O(n,i,o);return Y(e,c,t.redirections)}async function jn(e,t,s=p){let r=p,n=p,i=0,o=0,a=s;for(let u of t.redirections)if((u.operator==="<<"||u.operator==="<<-")&&u.target.type==="HereDoc"){let l=u.target,f=await L(e,l.content);l.stripTabs&&(f=f.split(`
626
+ `)),exitCode:1}}return{stdout:n,stderr:i,exitCode:o}}async function Vn(e,t){let s=p,r=p;for(let n of t.clauses){let i=await ar(e,n.condition);if(s=x(s,i.stdout),r=x(r,i.stderr),i.exitCode===0)return es(e,n.body,s,r)}return t.elseBody?es(e,t.elseBody,s,r):{stdout:s,stderr:r,exitCode:0}}async function Bn(e,t){let s=await Ne(e,t.redirections);if(s)return s;let r=p,n=p,i=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return _(`bash: \`${t.variable}': not a valid identifier
627
+ `);let a=[];if(t.words===null)a=N(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length===0)a=[];else try{for(let u of t.words){let l=await Ce(e,u);a.push(...l.values)}}catch(u){if(u instanceof Pt)return{stdout:p,stderr:u.stderr,exitCode:1};throw u}e.state.loopDepth++;try{for(let u of a){o++,o>e.limits.maxLoopIterations&&Re(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),w(e.state.env,t.variable,u);try{for(let l of t.body){let f=await e.executeStatement(l);r=x(r,f.stdout),n=x(n,f.stderr),i=f.exitCode}}catch(l){let f=wt(l,r,n,e.state.loopDepth);if(r=f.stdout,n=f.stderr,f.action==="break")break;if(f.action==="continue")continue;if(f.action==="error"){let d=O(r,n,f.exitCode??1);return Y(e,d,t.redirections)}throw f.error}}}finally{e.state.loopDepth--}let c=O(r,n,i);return Y(e,c,t.redirections)}async function jn(e,t){let s=await Ne(e,t.redirections);if(s)return s;let r=t.line;r!==void 0&&(e.state.currentLine=r);let n=p,i=p,o=0,a=0;t.init&&await Z(e,t.init.expression),e.state.loopDepth++;try{for(;a++,a>e.limits.maxLoopIterations&&Re(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,i),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await Z(e,t.condition.expression)===0));){try{for(let u of t.body){let l=await e.executeStatement(u);n=x(n,l.stdout),i=x(i,l.stderr),o=l.exitCode}}catch(u){let l=wt(u,n,i,e.state.loopDepth);if(n=l.stdout,i=l.stderr,l.action==="break")break;if(l.action==="continue"){t.update&&await Z(e,t.update.expression);continue}if(l.action==="error"){let f=O(n,i,l.exitCode??1);return Y(e,f,t.redirections)}throw l.error}t.update&&await Z(e,t.update.expression)}}finally{e.state.loopDepth--}let c=O(n,i,o);return Y(e,c,t.redirections)}async function Hn(e,t,s=p){let r=p,n=p,i=0,o=0,a=s;for(let u of t.redirections)if((u.operator==="<<"||u.operator==="<<-")&&u.target.type==="HereDoc"){let l=u.target,f=await L(e,l.content);l.stripTabs&&(f=f.split(`
628
628
  `).map(d=>d.replace(/^\t+/,"")).join(`
629
629
  `)),a=E(f)}else if(u.operator==="<<<"&&u.target.type==="Word")a=E(`${await L(e,u.target)}
630
630
  `);else if(u.operator==="<"&&u.target.type==="Word")try{let l=await L(e,u.target),f=e.fs.resolvePath(e.state.cwd,l);a=E(await e.fs.readFile(f))}catch{let l=await L(e,u.target);return _(`bash: ${l}: No such file or directory
631
- `)}let c=e.state.groupStdin;a.length>0&&(e.state.groupStdin=a),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&Re(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let u=0,l=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let h of t.condition){let g=await e.executeStatement(h);r=x(r,g.stdout),n=x(n,g.stderr),u=g.exitCode}}catch(h){if(h instanceof ye){if(r=x(r,h.stdout),n=x(n,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;l=!0}else if(h instanceof ge){if(r=x(r,h.stdout),n=x(n,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;f=!0}else throw e.state.inCondition=d,h}finally{e.state.inCondition=d}if(l)break;if(!f){if(u!==0)break;try{for(let h of t.body){let g=await e.executeStatement(h);r=x(r,g.stdout),n=x(n,g.stderr),i=g.exitCode}}catch(h){let g=wt(h,r,n,e.state.loopDepth);if(r=g.stdout,n=g.stderr,g.action==="break")break;if(g.action==="continue")continue;if(g.action==="error")return O(r,n,g.exitCode??1);throw g.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=c}return O(r,n,i)}async function Hn(e,t){let s=p,r=p,n=0,i=0;e.state.loopDepth++;try{for(;;){i++,i>e.limits.maxLoopIterations&&Re(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r);let o=await ar(e,t.condition);if(s=x(s,o.stdout),r=x(r,o.stderr),o.exitCode===0)break;try{for(let a of t.body){let c=await e.executeStatement(a);s=x(s,c.stdout),r=x(r,c.stderr),n=c.exitCode}}catch(a){let c=wt(a,s,r,e.state.loopDepth);if(s=c.stdout,r=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return O(s,r,c.exitCode??1);throw c.error}}}finally{e.state.loopDepth--}return O(s,r,n)}async function Un(e,t){let s=await Ne(e,t.redirections);if(s)return s;let r=p,n=p,i=0,o=await L(e,t.word),a=!1;for(let u=0;u<t.items.length;u++){let l=t.items[u],f=a;if(!a)for(let d of l.patterns){let h=await L(e,d);Cr(d)&&(h=_r(h));let g=e.state.shoptOptions.nocasematch,m=e.state.shoptOptions.extglob;if(Qe(o,h,g,m)){f=!0;break}}if(f){let d=await es(e,l.body,r,n);if(r=d.stdout,n=d.stderr,i=d.exitCode,l.terminator===";;")break;l.terminator===";&"?a=!0:a=!1}else a=!1}let c=O(r,n,i);return Y(e,c,t.redirections)}function lr(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function Gn(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),c=a.indexOf(":");if(c===-1)return null;let u=Number.parseInt(a.slice(0,c),10);if(Number.isNaN(u)||u<0)return null;let l=a.slice(c+1);return{path:i,position:u,content:l}}var qn="+ ";async function Zn(e){let t=e.state.env.get("PS4");if(t===void 0)return qn;let s=z(t);if(s==="")return"";try{let n=new H().parseWordFromString(s,!1,!1);return await L(e,n)}catch{return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${s}: bad substitution
632
- `,s||qn}}function _o(e){return e.map(t=>ko(t)).join(" ")}function ko(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
631
+ `)}let c=e.state.groupStdin;a.length>0&&(e.state.groupStdin=a),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&Re(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let u=0,l=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let h of t.condition){let g=await e.executeStatement(h);r=x(r,g.stdout),n=x(n,g.stderr),u=g.exitCode}}catch(h){if(h instanceof ye){if(r=x(r,h.stdout),n=x(n,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;l=!0}else if(h instanceof ge){if(r=x(r,h.stdout),n=x(n,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;f=!0}else throw e.state.inCondition=d,h}finally{e.state.inCondition=d}if(l)break;if(!f){if(u!==0)break;try{for(let h of t.body){let g=await e.executeStatement(h);r=x(r,g.stdout),n=x(n,g.stderr),i=g.exitCode}}catch(h){let g=wt(h,r,n,e.state.loopDepth);if(r=g.stdout,n=g.stderr,g.action==="break")break;if(g.action==="continue")continue;if(g.action==="error")return O(r,n,g.exitCode??1);throw g.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=c}return O(r,n,i)}async function Un(e,t){let s=p,r=p,n=0,i=0;e.state.loopDepth++;try{for(;;){i++,i>e.limits.maxLoopIterations&&Re(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r);let o=await ar(e,t.condition);if(s=x(s,o.stdout),r=x(r,o.stderr),o.exitCode===0)break;try{for(let a of t.body){let c=await e.executeStatement(a);s=x(s,c.stdout),r=x(r,c.stderr),n=c.exitCode}}catch(a){let c=wt(a,s,r,e.state.loopDepth);if(s=c.stdout,r=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return O(s,r,c.exitCode??1);throw c.error}}}finally{e.state.loopDepth--}return O(s,r,n)}async function Gn(e,t){let s=await Ne(e,t.redirections);if(s)return s;let r=p,n=p,i=0,o=await L(e,t.word),a=!1;for(let u=0;u<t.items.length;u++){let l=t.items[u],f=a;if(!a)for(let d of l.patterns){let h=await L(e,d);xr(d)&&(h=kr(h));let g=e.state.shoptOptions.nocasematch,m=e.state.shoptOptions.extglob;if(Qe(o,h,g,m)){f=!0;break}}if(f){let d=await es(e,l.body,r,n);if(r=d.stdout,n=d.stderr,i=d.exitCode,l.terminator===";;")break;l.terminator===";&"?a=!0:a=!1}else a=!1}let c=O(r,n,i);return Y(e,c,t.redirections)}function lr(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function qn(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),c=a.indexOf(":");if(c===-1)return null;let u=Number.parseInt(a.slice(0,c),10);if(Number.isNaN(u)||u<0)return null;let l=a.slice(c+1);return{path:i,position:u,content:l}}var Zn="+ ";async function Yn(e){let t=e.state.env.get("PS4");if(t===void 0)return Zn;let s=z(t);if(s==="")return"";try{let n=new H().parseWordFromString(s,!1,!1);return await L(e,n)}catch{return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${s}: bad substitution
632
+ `,s||Zn}}function ko(e){return e.map(t=>Co(t)).join(" ")}function Co(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
633
633
  `),n=e.includes(" "),i=e.includes("\\"),o=e.includes("'");if(s||r||n||i){let c="";for(let u of e){let l=u.charCodeAt(0);u===`
634
- `?c+="\\n":u===" "?c+="\\t":u==="\\"?c+="\\\\":u==="'"?c+="'":u==='"'?c+='"':l<32||l===127?l<256?c+=`\\x${l.toString(16).padStart(2,"0")}`:c+=`\\u${l.toString(16).padStart(4,"0")}`:c+=u}return`$'${c}'`}return o?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function Yn(e,t,s){if(!e.state.options.xtrace)return"";let r=await Zn(e),n=[t,...s],i=_o(n);return`${r}${i}
635
- `}async function Kn(e,t,s){return e.state.options.xtrace?`${await Zn(e)}${t}=${s}
636
- `:""}async function Xn(e,t,s){let r=t.timed?performance.now():0,n=p,i=V,o=0,a=[],c=t.commands.length>1,u=e.state.lastArg;for(let f=0;f<t.commands.length;f++){let d=t.commands[f],h=f===t.commands.length-1,g=f===0;c&&(e.state.lastArg=E(""),g||(e.state.groupStdin=void 0));let v=c&&(!h||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,S;try{S=await s(d,n)}catch(A){if(A instanceof St)S={stdout:A.stdout,stderr:A.stderr,exitCode:1};else if(A instanceof G&&t.commands.length>1)S={stdout:A.stdout,stderr:A.stderr,exitCode:A.exitCode};else if(A instanceof ve&&t.commands.length>1)S={stdout:A.stdout,stderr:A.stderr,exitCode:A.exitCode};else throw v&&(e.state.env=v),A}v&&(e.state.env=v),a.push(S.exitCode),S.exitCode!==0&&(o=S.exitCode),h?i=S:t.pipeStderr?.[f]??!1?(n=x(S.stderr,S.stdout),i={stdout:p,stderr:p,exitCode:S.exitCode}):(n=S.stdout,i={stdout:p,stderr:S.stderr,exitCode:S.exitCode})}if(t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand"){for(let f of e.state.env.keys())f.startsWith("PIPESTATUS_")&&e.state.env.delete(f);for(let f=0;f<a.length;f++)w(e.state.env,`PIPESTATUS_${f}`,String(a[f]));w(e.state.env,"PIPESTATUS__length",String(a.length))}if(e.state.options.pipefail&&o!==0&&(i={...i,exitCode:o}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let d=(performance.now()-r)/1e3,h=Math.floor(d/60),g=d%60,m;t.timePosix?m=`real ${d.toFixed(2)}
634
+ `?c+="\\n":u===" "?c+="\\t":u==="\\"?c+="\\\\":u==="'"?c+="'":u==='"'?c+='"':l<32||l===127?l<256?c+=`\\x${l.toString(16).padStart(2,"0")}`:c+=`\\u${l.toString(16).padStart(4,"0")}`:c+=u}return`$'${c}'`}return o?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function Kn(e,t,s){if(!e.state.options.xtrace)return"";let r=await Yn(e),n=[t,...s],i=ko(n);return`${r}${i}
635
+ `}async function Xn(e,t,s){return e.state.options.xtrace?`${await Yn(e)}${t}=${s}
636
+ `:""}async function Qn(e,t,s){let r=t.timed?performance.now():0,n=p,i=V,o=0,a=[],c=t.commands.length>1,u=e.state.lastArg;for(let f=0;f<t.commands.length;f++){let d=t.commands[f],h=f===t.commands.length-1,g=f===0;c&&(e.state.lastArg=E(""),g||(e.state.groupStdin=void 0));let v=c&&(!h||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,S;try{S=await s(d,n)}catch(A){if(A instanceof St)S={stdout:A.stdout,stderr:A.stderr,exitCode:1};else if(A instanceof G&&t.commands.length>1)S={stdout:A.stdout,stderr:A.stderr,exitCode:A.exitCode};else if(A instanceof ve&&t.commands.length>1)S={stdout:A.stdout,stderr:A.stderr,exitCode:A.exitCode};else throw v&&(e.state.env=v),A}v&&(e.state.env=v),a.push(S.exitCode),S.exitCode!==0&&(o=S.exitCode),h?i=S:t.pipeStderr?.[f]??!1?(n=x(S.stderr,S.stdout),i={stdout:p,stderr:p,exitCode:S.exitCode}):(n=S.stdout,i={stdout:p,stderr:S.stderr,exitCode:S.exitCode})}if(t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand"){for(let f of e.state.env.keys())f.startsWith("PIPESTATUS_")&&e.state.env.delete(f);for(let f=0;f<a.length;f++)w(e.state.env,`PIPESTATUS_${f}`,String(a[f]));w(e.state.env,"PIPESTATUS__length",String(a.length))}if(e.state.options.pipefail&&o!==0&&(i={...i,exitCode:o}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let d=(performance.now()-r)/1e3,h=Math.floor(d/60),g=d%60,m;t.timePosix?m=`real ${d.toFixed(2)}
637
637
  user 0.00
638
638
  sys 0.00
639
639
  `:m=`
640
640
  real ${`${h}m${g.toFixed(3)}s`}
641
641
  user 0m0.000s
642
642
  sys 0m0.000s
643
- `,i={...i,stderr:x(i.stderr,E(m))}}return c&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),i}async function Qn(e,t){let s=new Map,r="";for(let n of t.assignments){let i=n.name;if(n.array){let f=await Co(e,t,i,n.array,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(r+=f.xtraceOutput,f.continueToNext)continue}let o=n.value?await L(e,n.value):"",a=n.value?await Ye(e,n.value):p;if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:_(`bash: ${i}: bad array subscript
644
- `)};let u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let f=await Do(e,t,u[1],u[2],o,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(f.continueToNext)continue}let l=await Ro(e,t,i,o,n.append,s,a);if(l.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:l.error};r+=l.xtraceOutput,l.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:s}}async function Co(e,t,s,r,n,i){let o="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:_(`bash: ${s}: cannot assign list to array member
645
- `)};if(fe(e,s)){let l=Pr(e,s);if(l===void 0||l==="")throw new G(1,p,p);let f=ke(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:_(`bash: ${s}: cannot assign list to array member
643
+ `,i={...i,stderr:x(i.stderr,E(m))}}return c&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),i}async function Jn(e,t){let s=new Map,r="";for(let n of t.assignments){let i=n.name;if(n.array){let f=await xo(e,t,i,n.array,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(r+=f.xtraceOutput,f.continueToNext)continue}let o=n.value?await L(e,n.value):"",a=n.value?await Ye(e,n.value):p;if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:_(`bash: ${i}: bad array subscript
644
+ `)};let u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let f=await Io(e,t,u[1],u[2],o,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(f.continueToNext)continue}let l=await Mo(e,t,i,o,n.append,s,a);if(l.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:l.error};r+=l.xtraceOutput,l.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:s}}async function xo(e,t,s,r,n,i){let o="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:_(`bash: ${s}: cannot assign list to array member
645
+ `)};if(fe(e,s)){let l=Ar(e,s);if(l===void 0||l==="")throw new G(1,p,p);let f=ke(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:_(`bash: ${s}: cannot assign list to array member
646
646
  `)}}if(Be(e,s)){if(t.name)return o+=`bash: ${s}: readonly variable
647
- `,{continueToNext:!0,xtraceOutput:o};let l=se(e,s);if(l)return{continueToNext:!1,xtraceOutput:"",error:l}}let a=e.state.associativeArrays?.has(s),c=xo(r),u=()=>{let l=`${s}_`;for(let f of e.state.env.keys())f.startsWith(l)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(a&&c?await No(e,t,s,r,n,u,l=>{o+=l}):c?await To(e,s,r,n,u):await Oo(e,s,r,n,u),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>kt(d)).join(" ")})`;w(e.state.env,s,f)}return{continueToNext:!0,xtraceOutput:o}}function xo(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],r=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let n=t.parts[2];return n.type!=="Literal"?!1:n.value.startsWith("]=")||n.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):s.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function No(e,t,s,r,n,i,o){let a=[];for(let c of r){let u=as(c);if(u){let{key:l,valueParts:f,append:d}=u,h;f.length>0?h=await L(e,{type:"Word",parts:f}):h="",h=K(e,h),a.push({type:"keyed",key:l,value:h,append:d})}else{let l=await L(e,c);a.push({type:"invalid",expandedValue:l})}}n||i();for(let c of a)if(c.type==="keyed")if(c.append){let u=N(e.state.env,`${s}_${c.key}`,"");w(e.state.env,`${s}_${c.key}`,u+c.value)}else w(e.state.env,`${s}_${c.key}`,c.value);else{let u=t.line??e.state.currentLine??1;o(`bash: line ${u}: ${s}: ${c.expandedValue}: must use subscript when assigning associative array
648
- `)}}async function To(e,t,s,r,n){let i=[];for(let a of s){let c=as(a);if(c){let{key:u,valueParts:l,append:f}=c,d;l.length>0?d=await L(e,{type:"Word",parts:l}):d="",d=K(e,d),i.push({type:"keyed",indexExpr:u,value:d,append:f})}else{let u=await Ce(e,a);i.push({type:"non-keyed",values:u.values})}}r||n();let o=0;for(let a of i)if(a.type==="keyed"){let c;try{let u=new H,l=J(u,a.indexExpr);c=await Z(e,l.expression,!1)}catch{if(/^-?\d+$/.test(a.indexExpr))c=Number.parseInt(a.indexExpr,10);else{let u=N(e.state.env,a.indexExpr);c=u?Number.parseInt(u,10):0,Number.isNaN(c)&&(c=0)}}if(a.append){let u=N(e.state.env,`${t}_${c}`,"");w(e.state.env,`${t}_${c}`,u+a.value)}else w(e.state.env,`${t}_${c}`,a.value);o=c+1}else for(let c of a.values)w(e.state.env,`${t}_${o++}`,c)}async function Oo(e,t,s,r,n){let i=[];for(let a of s){let c=await Ce(e,a);i.push(...c.values)}let o=0;if(r){let a=Se(e,t);if(a.length>0)o=Math.max(...a.map(([u])=>typeof u=="number"?u:0))+1;else{let c=e.state.env.get(t);c!==void 0&&(e.state.env.set(`${t}_0`,c),e.state.env.delete(t),o=1)}}else n();for(let a=0;a<i.length;a++)w(e.state.env,`${t}_${o+a}`,i[a]);r||w(e.state.env,`${t}__length`,String(i.length))}async function Do(e,t,s,r,n,i,o){let a=s;if(fe(e,s)){let f=ke(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:_(`bash: \`${f}': not a valid identifier
649
- `)};a=f}}if(Be(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=se(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let c=e.state.associativeArrays?.has(a),u;if(c)u=await Jn(e,a,r);else{let f=await Io(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};u=`${a}_${f.index}`}let l=i?N(e.state.env,u)+n:n;if(t.name)o.set(u,e.state.env.get(u)),w(e.state.env,u,l);else{let f=Je(e,a);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(u)||d.set(u,e.state.env.get(u))}w(e.state.env,u,l)}return{continueToNext:!0,xtraceOutput:""}}async function Jn(e,t,s){let r;if(s.startsWith("'")&&s.endsWith("'"))r=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let n=s.slice(1,-1),o=new H().parseWordFromString(n,!0,!1);r=await L(e,o)}else if(s.includes("$")){let i=new H().parseWordFromString(s,!1,!1);r=await L(e,i)}else r=s;return`${t}_${r}`}async function Io(e,t,s){let r=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(r=s.slice(1,-1));let n;if(/^-?\d+$/.test(r))n=Number.parseInt(r,10);else{try{let i=new H,o=J(i,r);n=await Z(e,o.expression,!1)}catch(i){if(i instanceof Ve){let c=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
647
+ `,{continueToNext:!0,xtraceOutput:o};let l=se(e,s);if(l)return{continueToNext:!1,xtraceOutput:"",error:l}}let a=e.state.associativeArrays?.has(s),c=No(r),u=()=>{let l=`${s}_`;for(let f of e.state.env.keys())f.startsWith(l)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(a&&c?await To(e,t,s,r,n,u,l=>{o+=l}):c?await Oo(e,s,r,n,u):await Do(e,s,r,n,u),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>kt(d)).join(" ")})`;w(e.state.env,s,f)}return{continueToNext:!0,xtraceOutput:o}}function No(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],r=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let n=t.parts[2];return n.type!=="Literal"?!1:n.value.startsWith("]=")||n.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):s.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function To(e,t,s,r,n,i,o){let a=[];for(let c of r){let u=as(c);if(u){let{key:l,valueParts:f,append:d}=u,h;f.length>0?h=await L(e,{type:"Word",parts:f}):h="",h=K(e,h),a.push({type:"keyed",key:l,value:h,append:d})}else{let l=await L(e,c);a.push({type:"invalid",expandedValue:l})}}n||i();for(let c of a)if(c.type==="keyed")if(c.append){let u=N(e.state.env,`${s}_${c.key}`,"");w(e.state.env,`${s}_${c.key}`,u+c.value)}else w(e.state.env,`${s}_${c.key}`,c.value);else{let u=t.line??e.state.currentLine??1;o(`bash: line ${u}: ${s}: ${c.expandedValue}: must use subscript when assigning associative array
648
+ `)}}async function Oo(e,t,s,r,n){let i=[];for(let a of s){let c=as(a);if(c){let{key:u,valueParts:l,append:f}=c,d;l.length>0?d=await L(e,{type:"Word",parts:l}):d="",d=K(e,d),i.push({type:"keyed",indexExpr:u,value:d,append:f})}else{let u=await Ce(e,a);i.push({type:"non-keyed",values:u.values})}}r||n();let o=0;for(let a of i)if(a.type==="keyed"){let c;try{let u=new H,l=J(u,a.indexExpr);c=await Z(e,l.expression,!1)}catch{if(/^-?\d+$/.test(a.indexExpr))c=Number.parseInt(a.indexExpr,10);else{let u=N(e.state.env,a.indexExpr);c=u?Number.parseInt(u,10):0,Number.isNaN(c)&&(c=0)}}if(a.append){let u=N(e.state.env,`${t}_${c}`,"");w(e.state.env,`${t}_${c}`,u+a.value)}else w(e.state.env,`${t}_${c}`,a.value);o=c+1}else for(let c of a.values)w(e.state.env,`${t}_${o++}`,c)}async function Do(e,t,s,r,n){let i=[];for(let a of s){let c=await Ce(e,a);i.push(...c.values)}let o=0;if(r){let a=Se(e,t);if(a.length>0)o=Math.max(...a.map(([u])=>typeof u=="number"?u:0))+1;else{let c=e.state.env.get(t);c!==void 0&&(e.state.env.set(`${t}_0`,c),e.state.env.delete(t),o=1)}}else n();for(let a=0;a<i.length;a++)w(e.state.env,`${t}_${o+a}`,i[a]);r||w(e.state.env,`${t}__length`,String(i.length))}async function Io(e,t,s,r,n,i,o){let a=s;if(fe(e,s)){let f=ke(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:_(`bash: \`${f}': not a valid identifier
649
+ `)};a=f}}if(Be(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=se(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let c=e.state.associativeArrays?.has(a),u;if(c)u=await ei(e,a,r);else{let f=await Ro(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};u=`${a}_${f.index}`}let l=i?N(e.state.env,u)+n:n;if(t.name)o.set(u,e.state.env.get(u)),w(e.state.env,u,l);else{let f=Je(e,a);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(u)||d.set(u,e.state.env.get(u))}w(e.state.env,u,l)}return{continueToNext:!0,xtraceOutput:""}}async function ei(e,t,s){let r;if(s.startsWith("'")&&s.endsWith("'"))r=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let n=s.slice(1,-1),o=new H().parseWordFromString(n,!0,!1);r=await L(e,o)}else if(s.includes("$")){let i=new H().parseWordFromString(s,!1,!1);r=await L(e,i)}else r=s;return`${t}_${r}`}async function Ro(e,t,s){let r=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(r=s.slice(1,-1));let n;if(/^-?\d+$/.test(r))n=Number.parseInt(r,10);else{try{let i=new H,o=J(i,r);n=await Z(e,o.expression,!1)}catch(i){if(i instanceof Ve){let c=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
650
650
  `;if(i.fatal)throw new G(1,p,E(c));return{index:0,error:_(c)}}let o=N(e.state.env,s);n=o?Number.parseInt(o,10):0}Number.isNaN(n)&&(n=0)}if(n<0){let i=Se(e,t);if(i.length===0){let a=e.state.currentLine;return{index:0,error:_(`bash: line ${a}: ${t}[${s}]: bad array subscript
651
651
  `)}}if(n=Math.max(...i.map(([a])=>typeof a=="number"?a:0))+1+n,n<0){let a=e.state.currentLine;return{index:0,error:_(`bash: line ${a}: ${t}[${s}]: bad array subscript
652
- `)}}}return{index:n}}async function Ro(e,t,s,r,n,i,o){let a="",c=s,u=null;if(fe(e,s)){let m=Ar(e,s,r);if(m===void 0)return{continueToNext:!1,xtraceOutput:"",error:_(`bash: ${s}: circular name reference
652
+ `)}}}return{index:n}}async function Mo(e,t,s,r,n,i,o){let a="",c=s,u=null;if(fe(e,s)){let m=_r(e,s,r);if(m===void 0)return{continueToNext:!1,xtraceOutput:"",error:_(`bash: ${s}: circular name reference
653
653
  `)};if(m===null)return{continueToNext:!0,xtraceOutput:""};c=m;let v=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);v&&(u={arrayName:v[1],subscriptExpr:v[2]},c=v[1])}if(Be(e,c)){if(t.name)return a+=`bash: ${c}: readonly variable
654
- `,{continueToNext:!0,xtraceOutput:a};let m=se(e,c);if(m)return{continueToNext:!1,xtraceOutput:"",error:m}}let l,f=!!o&&!n&&!u;if(mt(e,c)){f=!1;try{let m=new H;if(n){let S=`(${N(e.state.env,c,"0")}) + (${r})`,A=J(m,S);l=String(await Z(e,A.expression))}else{let v=J(m,r);l=String(await Z(e,v.expression))}}catch{l="0"}}else{let{isArray:m}=await import("./chunks/expansion-OBOJBZTH.js"),v=m(e,c);v&&(f=!1);let S=v?`${c}_0`:c;l=n?N(e.state.env,S)+r:r}let d=st(e,c,l);d!==l&&(f=!1),l=d,a+=await Kn(e,c,l);let h=c;if(u)h=await Mo(e,u);else{let{isArray:m}=await import("./chunks/expansion-OBOJBZTH.js");m(e,c)&&(h=`${c}_0`,f=!1)}let g=f?()=>e.state.env.set(h,o):()=>w(e.state.env,h,l);return t.name?(i.set(h,e.state.env.get(h)),g()):(g(),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(c)),e.state.tempEnvBindings?.some(m=>m.has(c))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(c))),{continueToNext:!1,xtraceOutput:a}}async function Mo(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return Jn(e,s,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new H,a=J(o,r);i=await Z(e,a.expression,!1)}catch{let o=N(e.state.env,r);i=o?Number.parseInt(o,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let o=Se(e,s);o.length>0&&(i=Math.max(...o.map(c=>c[0]))+1+i)}return`${s}_${i}`}async function ei(e,t,s,r){let n=await Ne(e,t.redirections);if(n)return n;let i=new Map(e.state.env),o=e.state.cwd,a={...e.state.options},c=new Map(e.state.functions),u=e.state.localScopes,l=e.state.localVarStack,f=e.state.localVarDepth,d=e.state.fullyUnsetLocals;if(e.state.localScopes=u.map(P=>new Map(P)),l){e.state.localVarStack=new Map;for(let[P,M]of l.entries())e.state.localVarStack.set(P,M.map(I=>({...I})))}f&&(e.state.localVarDepth=new Map(f)),d&&(e.state.fullyUnsetLocals=new Map(d));let h=e.state.loopDepth,g=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let m=e.state.lastArg,v=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let S=e.state.groupStdin;qe(s)||(e.state.groupStdin=s);let A=p,C=p,y=0,b=()=>{e.state.env=i,e.state.cwd=o,e.state.options=a,e.state.functions=c,e.state.localScopes=u,e.state.localVarStack=l,e.state.localVarDepth=f,e.state.fullyUnsetLocals=d,e.state.loopDepth=h,e.state.parentHasLoopContext=g,e.state.groupStdin=S,e.state.bashPid=v,e.state.lastArg=m};try{for(let P of t.body){let M=await r(P);A=x(A,M.stdout),C=x(C,M.stderr),y=M.exitCode}}catch(P){if(b(),P instanceof ae)throw P;if(P instanceof Me){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,0);return Y(e,I,t.redirections)}if(P instanceof ye||P instanceof ge){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,0);return Y(e,I,t.redirections)}if(P instanceof G){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,P.exitCode);return Y(e,I,t.redirections)}if(P instanceof ue){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,P.exitCode);return Y(e,I,t.redirections)}if(P instanceof ve){let I=O(x(A,P.stdout),x(C,P.stderr),P.exitCode);return Y(e,I,t.redirections)}let M=O(A,x(C,E(`${Te(P)}
655
- `)),1);return Y(e,M,t.redirections)}b();let k=O(A,C,y);return Y(e,k,t.redirections)}async function ti(e,t,s,r){let n=p,i=p,o=0,a=await Gt(e,t.redirections);if(a)return a;let c=s;for(let f of t.redirections)if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,h=await L(e,d.content);d.stripTabs&&(h=h.split(`
654
+ `,{continueToNext:!0,xtraceOutput:a};let m=se(e,c);if(m)return{continueToNext:!1,xtraceOutput:"",error:m}}let l,f=!!o&&!n&&!u;if(mt(e,c)){f=!1;try{let m=new H;if(n){let S=`(${N(e.state.env,c,"0")}) + (${r})`,A=J(m,S);l=String(await Z(e,A.expression))}else{let v=J(m,r);l=String(await Z(e,v.expression))}}catch{l="0"}}else{let{isArray:m}=await import("./chunks/expansion-OBOJBZTH.js"),v=m(e,c);v&&(f=!1);let S=v?`${c}_0`:c;l=n?N(e.state.env,S)+r:r}let d=st(e,c,l);d!==l&&(f=!1),l=d,a+=await Xn(e,c,l);let h=c;if(u)h=await Fo(e,u);else{let{isArray:m}=await import("./chunks/expansion-OBOJBZTH.js");m(e,c)&&(h=`${c}_0`,f=!1)}let g=f?()=>e.state.env.set(h,o):()=>w(e.state.env,h,l);return t.name?(i.set(h,e.state.env.get(h)),g()):(g(),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(c)),e.state.tempEnvBindings?.some(m=>m.has(c))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(c))),{continueToNext:!1,xtraceOutput:a}}async function Fo(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return ei(e,s,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new H,a=J(o,r);i=await Z(e,a.expression,!1)}catch{let o=N(e.state.env,r);i=o?Number.parseInt(o,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let o=Se(e,s);o.length>0&&(i=Math.max(...o.map(c=>c[0]))+1+i)}return`${s}_${i}`}async function ti(e,t,s,r){let n=await Ne(e,t.redirections);if(n)return n;let i=new Map(e.state.env),o=e.state.cwd,a={...e.state.options},c=new Map(e.state.functions),u=e.state.localScopes,l=e.state.localVarStack,f=e.state.localVarDepth,d=e.state.fullyUnsetLocals;if(e.state.localScopes=u.map(P=>new Map(P)),l){e.state.localVarStack=new Map;for(let[P,M]of l.entries())e.state.localVarStack.set(P,M.map(I=>({...I})))}f&&(e.state.localVarDepth=new Map(f)),d&&(e.state.fullyUnsetLocals=new Map(d));let h=e.state.loopDepth,g=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let m=e.state.lastArg,v=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let S=e.state.groupStdin;qe(s)||(e.state.groupStdin=s);let A=p,C=p,y=0,b=()=>{e.state.env=i,e.state.cwd=o,e.state.options=a,e.state.functions=c,e.state.localScopes=u,e.state.localVarStack=l,e.state.localVarDepth=f,e.state.fullyUnsetLocals=d,e.state.loopDepth=h,e.state.parentHasLoopContext=g,e.state.groupStdin=S,e.state.bashPid=v,e.state.lastArg=m};try{for(let P of t.body){let M=await r(P);A=x(A,M.stdout),C=x(C,M.stderr),y=M.exitCode}}catch(P){if(b(),P instanceof ae)throw P;if(P instanceof Me){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,0);return Y(e,I,t.redirections)}if(P instanceof ye||P instanceof ge){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,0);return Y(e,I,t.redirections)}if(P instanceof G){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,P.exitCode);return Y(e,I,t.redirections)}if(P instanceof ue){A=x(A,P.stdout),C=x(C,P.stderr);let I=O(A,C,P.exitCode);return Y(e,I,t.redirections)}if(P instanceof ve){let I=O(x(A,P.stdout),x(C,P.stderr),P.exitCode);return Y(e,I,t.redirections)}let M=O(A,x(C,E(`${Te(P)}
655
+ `)),1);return Y(e,M,t.redirections)}b();let k=O(A,C,y);return Y(e,k,t.redirections)}async function si(e,t,s,r){let n=p,i=p,o=0,a=await Gt(e,t.redirections);if(a)return a;let c=s;for(let f of t.redirections)if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,h=await L(e,d.content);d.stripTabs&&(h=h.split(`
656
656
  `).map(m=>m.replace(/^\t+/,"")).join(`
657
657
  `));let g=f.fd??0;g!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(g,h)):c=E(h)}else if(f.operator==="<<<"&&f.target.type==="Word")c=E(`${await L(e,f.target)}
658
658
  `);else if(f.operator==="<"&&f.target.type==="Word")try{let d=await L(e,f.target),h=e.fs.resolvePath(e.state.cwd,d);c=E(await e.fs.readFile(h))}catch{let d=await L(e,f.target);return _(`bash: ${d}: No such file or directory
659
659
  `)}let u=e.state.groupStdin;qe(c)||(e.state.groupStdin=c);try{for(let f of t.body){let d=await r(f);n=x(n,d.stdout),i=x(i,d.stderr),o=d.exitCode}}catch(f){if(e.state.groupStdin=u,f instanceof ae)throw f;if(At(f)||f instanceof ve||f instanceof G)throw f.prependOutput(n,i),f;return O(n,x(i,E(`${Te(f)}
660
- `)),1)}e.state.groupStdin=u;let l=O(n,i,o);return Y(e,l,t.redirections)}async function si(e,t,s,r,n){let i;try{i=await e.fs.readFile(t)}catch{return _(`bash: ${t}: No such file or directory
660
+ `)),1)}e.state.groupStdin=u;let l=O(n,i,o);return Y(e,l,t.redirections)}async function ri(e,t,s,r,n){let i;try{i=await e.fs.readFile(t)}catch{return _(`bash: ${t}: No such file or directory
661
661
  `,127)}if(i.startsWith("#!")){let v=i.indexOf(`
662
662
  `);v!==-1&&(i=i.slice(v+1))}let o=new Map(e.state.env),a=e.state.cwd,c={...e.state.options},u=e.state.loopDepth,l=e.state.parentHasLoopContext,f=e.state.lastArg,d=e.state.bashPid,h=e.state.groupStdin,g=e.state.currentSource;e.state.parentHasLoopContext=u>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,qe(r)||(e.state.groupStdin=r),e.state.currentSource=t,w(e.state.env,"0",t),w(e.state.env,"#",String(s.length)),w(e.state.env,"@",s.join(" ")),w(e.state.env,"*",s.join(" "));for(let v=0;v<s.length&&v<9;v++)w(e.state.env,String(v+1),s[v]);for(let v=s.length+1;v<=9;v++)e.state.env.delete(String(v));let m=()=>{e.state.env=o,e.state.cwd=a,e.state.options=c,e.state.loopDepth=u,e.state.parentHasLoopContext=l,e.state.lastArg=f,e.state.bashPid=d,e.state.groupStdin=h,e.state.currentSource=g};try{let S=new H().parse(i),A=await n(S);return m(),A}catch(v){if(m(),v instanceof G||v instanceof ae)throw v;if(v.name==="ParseException")return _(`bash: ${t}: ${v.message}
663
- `);throw v}}function Fo(e,t){for(let s of t.parts)switch(s.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"DoubleQuoted":for(let r of s.parts)switch(r.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"ParameterExpansion":if(r.operation||r.parameter==="@"||r.parameter==="*"||r.parameter.endsWith("[@]")||r.parameter.endsWith("[*]"))return!1;if(fe(e,r.parameter)){let n=ke(e,r.parameter);if(n&&(n.endsWith("[@]")||n.endsWith("[*]")))return!1}continue;case"CommandSubstitution":continue;default:return!1}continue;case"ParameterExpansion":return!1;default:return!1}return t.parts.length>0}var vt=class{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,limits:t.limits,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}}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r)this.ctx.state.env.has(i)&&(n[i]=N(this.ctx.state.env,i));return n}async executeScript(t){let s=p,r=p,n=0;for(let i of t.statements)try{let o=await this.executeStatement(i);s=x(s,o.stdout),r=x(r,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n))}catch(o){if(o instanceof G)throw o.prependOutput(s,r),o;if(o instanceof Ee)return s=x(s,o.stdout),r=x(r,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof ae)throw o;if(o instanceof ve)return s=x(s,o.stdout),r=x(r,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof mr)return s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof St)return s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof Ve){s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n));continue}if(o instanceof yr){s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n));continue}if(o instanceof ye||o instanceof ge){if(this.ctx.state.loopDepth>0)throw o.prependOutput(s,r),o;s=x(s,o.stdout),r=x(r,o.stderr);continue}throw o instanceof ue&&o.prependOutput(s,r),o}return{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)}}async executeUserScript(t,s,r=p){return si(this.ctx,t,Ze(s),r,n=>this.executeScript(n))}async executeStatement(t){if(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"),t.deferredError)throw new _t(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return V;this.ctx.state.errexitSafe=!1;let s=p,r=p;this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r=x(r,E(`${t.sourceText}
664
- `)));let n=0,i=-1,o=!1;for(let u=0;u<t.pipelines.length;u++){let l=t.pipelines[u],f=u>0?t.operators[u-1]:null;if(f==="&&"&&n!==0||f==="||"&&n===0)continue;let d=await this.executePipeline(l);s=x(s,d.stdout),r=x(r,d.stderr),n=d.exitCode,i=u,o=l.negated,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n))}let a=i<t.pipelines.length-1,c=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||o||c,this.ctx.state.options.errexit&&n!==0&&i===t.pipelines.length-1&&!o&&!this.ctx.state.inCondition&&!c)throw new ve(n,s,r);return{stdout:s,stderr:r,exitCode:n}}async executePipeline(t){return Xn(this.ctx,t,(s,r)=>this.executeCommand(s,r))}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 zn(this.ctx,t);case"For":return Vn(this.ctx,t);case"CStyleFor":return Bn(this.ctx,t);case"While":return jn(this.ctx,t,s);case"Until":return Hn(this.ctx,t);case"Case":return Un(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return ln(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return V}}async executeSimpleCommand(t,s){try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof Pt)return{stdout:p,stderr:r.stderr,exitCode:1};throw r}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let y=t,b=100;for(;b>0;){let k=this.expandAlias(y);if(k===y)break;y=k,b--}this.aliasExpansionStack.clear(),y!==t&&(t=y)}this.ctx.state.expansionStderr="";let r=await Qn(this.ctx,t);if(r.error)return r.error;let n=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(t.redirections.length>0){let b=await Ne(this.ctx,t.redirections);if(b)return b;let k={stdout:p,stderr:E(i),exitCode:0};return Y(this.ctx,k,t.redirections)}this.ctx.state.lastArg=E("");let y=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",{stdout:p,stderr:E(y),exitCode:this.ctx.state.lastExitCode}}let o=t.name&&lr(t.name,["local","declare","typeset","export","readonly"]),a=Array.from(n.keys());if(a.length>0&&!o){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let y of a)this.ctx.state.tempExportedVars.add(y)}let c=await Gt(this.ctx,t.redirections);if(c){for(let[y,b]of n)b===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,b);return c}let u=-1;for(let y of t.redirections){if((y.operator==="<<"||y.operator==="<<-")&&y.target.type==="HereDoc"){let b=y.target,k=y.fd??0;if(k===0&&!b.stripTabs)s=await Ye(this.ctx,b.content);else{let P=await L(this.ctx,b.content);b.stripTabs&&(P=P.split(`
663
+ `);throw v}}function Lo(e,t){for(let s of t.parts)switch(s.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"DoubleQuoted":for(let r of s.parts)switch(r.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"ParameterExpansion":if(r.operation||r.parameter==="@"||r.parameter==="*"||r.parameter.endsWith("[@]")||r.parameter.endsWith("[*]"))return!1;if(fe(e,r.parameter)){let n=ke(e,r.parameter);if(n&&(n.endsWith("[@]")||n.endsWith("[*]")))return!1}continue;case"CommandSubstitution":continue;default:return!1}continue;case"ParameterExpansion":return!1;default:return!1}return t.parts.length>0}var vt=class{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,limits:t.limits,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}}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r)this.ctx.state.env.has(i)&&(n[i]=N(this.ctx.state.env,i));return n}async executeScript(t){let s=p,r=p,n=0;for(let i of t.statements)try{let o=await this.executeStatement(i);s=x(s,o.stdout),r=x(r,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n))}catch(o){if(o instanceof G)throw o.prependOutput(s,r),o;if(o instanceof Ee)return s=x(s,o.stdout),r=x(r,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof ae)throw o;if(o instanceof ve)return s=x(s,o.stdout),r=x(r,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof mr)return s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof St)return s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)};if(o instanceof Ve){s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n));continue}if(o instanceof yr){s=x(s,o.stdout),r=x(r,o.stderr),n=1,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n));continue}if(o instanceof ye||o instanceof ge){if(this.ctx.state.loopDepth>0)throw o.prependOutput(s,r),o;s=x(s,o.stdout),r=x(r,o.stderr);continue}throw o instanceof ue&&o.prependOutput(s,r),o}return{stdout:s,stderr:r,exitCode:n,env:Fe(this.ctx.state.env)}}async executeUserScript(t,s,r=p){return ri(this.ctx,t,Ze(s),r,n=>this.executeScript(n))}async executeStatement(t){if(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"),t.deferredError)throw new _t(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return V;this.ctx.state.errexitSafe=!1;let s=p,r=p;this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r=x(r,E(`${t.sourceText}
664
+ `)));let n=0,i=-1,o=!1;for(let u=0;u<t.pipelines.length;u++){let l=t.pipelines[u],f=u>0?t.operators[u-1]:null;if(f==="&&"&&n!==0||f==="||"&&n===0)continue;let d=await this.executePipeline(l);s=x(s,d.stdout),r=x(r,d.stderr),n=d.exitCode,i=u,o=l.negated,this.ctx.state.lastExitCode=n,w(this.ctx.state.env,"?",String(n))}let a=i<t.pipelines.length-1,c=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||o||c,this.ctx.state.options.errexit&&n!==0&&i===t.pipelines.length-1&&!o&&!this.ctx.state.inCondition&&!c)throw new ve(n,s,r);return{stdout:s,stderr:r,exitCode:n}}async executePipeline(t){return Qn(this.ctx,t,(s,r)=>this.executeCommand(s,r))}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 Vn(this.ctx,t);case"For":return Bn(this.ctx,t);case"CStyleFor":return jn(this.ctx,t);case"While":return Hn(this.ctx,t,s);case"Until":return Un(this.ctx,t);case"Case":return Gn(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return cn(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return V}}async executeSimpleCommand(t,s){try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof Pt)return{stdout:p,stderr:r.stderr,exitCode:1};throw r}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let y=t,b=100;for(;b>0;){let k=this.expandAlias(y);if(k===y)break;y=k,b--}this.aliasExpansionStack.clear(),y!==t&&(t=y)}this.ctx.state.expansionStderr="";let r=await Jn(this.ctx,t);if(r.error)return r.error;let n=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(t.redirections.length>0){let b=await Ne(this.ctx,t.redirections);if(b)return b;let k={stdout:p,stderr:E(i),exitCode:0};return Y(this.ctx,k,t.redirections)}this.ctx.state.lastArg=E("");let y=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",{stdout:p,stderr:E(y),exitCode:this.ctx.state.lastExitCode}}let o=t.name&&lr(t.name,["local","declare","typeset","export","readonly"]),a=Array.from(n.keys());if(a.length>0&&!o){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let y of a)this.ctx.state.tempExportedVars.add(y)}let c=await Gt(this.ctx,t.redirections);if(c){for(let[y,b]of n)b===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,b);return c}let u=-1;for(let y of t.redirections){if((y.operator==="<<"||y.operator==="<<-")&&y.target.type==="HereDoc"){let b=y.target,k=y.fd??0;if(k===0&&!b.stripTabs)s=await Ye(this.ctx,b.content);else{let P=await L(this.ctx,b.content);b.stripTabs&&(P=P.split(`
665
665
  `).map(M=>M.replace(/^\t+/,"")).join(`
666
666
  `)),k!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set(k,P)):s=E(P)}continue}if(y.operator==="<<<"&&y.target.type==="Word"){let b=await Ye(this.ctx,y.target);s=x(b,E(`
667
667
  `));continue}if(y.operator==="<"&&y.target.type==="Word")try{let b=await L(this.ctx,y.target),k=this.ctx.fs.resolvePath(this.ctx.state.cwd,b);s=await this.ctx.fs.readFileBuffer(k)}catch{let b=await L(this.ctx,y.target);for(let[k,P]of n)P===void 0?this.ctx.state.env.delete(k):this.ctx.state.env.set(k,P);return _(`bash: ${b}: No such file or directory
668
- `)}if(y.operator==="<&"&&y.target.type==="Word"){let b=await L(this.ctx,y.target),k=Number.parseInt(b,10);if(!Number.isNaN(k)&&this.ctx.state.fileDescriptors){let P=this.ctx.state.fileDescriptors.get(k);if(P!==void 0)if(P.startsWith("__rw__:")){let M=Gn(P);M&&(s=E(M.content.slice(M.position)),u=k)}else P.startsWith("__file__:")||P.startsWith("__file_append__:")||(s=E(P))}}}let l=await L(this.ctx,t.name),f=[],d=[];if(lr(t.name,["local","declare","typeset","export","readonly"])&&(l==="local"||l==="declare"||l==="typeset"||l==="export"||l==="readonly"))for(let y of t.args){let b=await Hr(this.ctx,y);if(b)f.push(E(b)),d.push(!0);else{let k=await Ur(this.ctx,y);if(k!==null)f.push(E(k)),d.push(!0);else{let P=await Ce(this.ctx,y);for(let M of P.values)f.push(E(M)),d.push(P.quoted)}}}else for(let y of t.args)if(Fo(this.ctx,y))f.push(await Ye(this.ctx,y)),d.push(!0);else{let b=await Ce(this.ctx,y);for(let k of b.values)f.push(E(k)),d.push(b.quoted)}if(!l){if(t.name.parts.every(b=>b.type==="CommandSubstitution"||b.type==="ParameterExpansion"||b.type==="ArithmeticExpansion")){if(f.length>0){let b=z(f.shift());return d.shift(),await this.runCommand(b,f,d,s,!1,!1,u)}return{stdout:p,stderr:p,exitCode:this.ctx.state.lastExitCode}}return _(`bash: : command not found
668
+ `)}if(y.operator==="<&"&&y.target.type==="Word"){let b=await L(this.ctx,y.target),k=Number.parseInt(b,10);if(!Number.isNaN(k)&&this.ctx.state.fileDescriptors){let P=this.ctx.state.fileDescriptors.get(k);if(P!==void 0)if(P.startsWith("__rw__:")){let M=qn(P);M&&(s=E(M.content.slice(M.position)),u=k)}else P.startsWith("__file__:")||P.startsWith("__file_append__:")||(s=E(P))}}}let l=await L(this.ctx,t.name),f=[],d=[];if(lr(t.name,["local","declare","typeset","export","readonly"])&&(l==="local"||l==="declare"||l==="typeset"||l==="export"||l==="readonly"))for(let y of t.args){let b=await Ur(this.ctx,y);if(b)f.push(E(b)),d.push(!0);else{let k=await Gr(this.ctx,y);if(k!==null)f.push(E(k)),d.push(!0);else{let P=await Ce(this.ctx,y);for(let M of P.values)f.push(E(M)),d.push(P.quoted)}}}else for(let y of t.args)if(Lo(this.ctx,y))f.push(await Ye(this.ctx,y)),d.push(!0);else{let b=await Ce(this.ctx,y);for(let k of b.values)f.push(E(k)),d.push(b.quoted)}if(!l){if(t.name.parts.every(b=>b.type==="CommandSubstitution"||b.type==="ParameterExpansion"||b.type==="ArithmeticExpansion")){if(f.length>0){let b=z(f.shift());return d.shift(),await this.runCommand(b,f,d,s,!1,!1,u)}return{stdout:p,stderr:p,exitCode:this.ctx.state.lastExitCode}}return _(`bash: : command not found
669
669
  `,127)}if(l==="exec"&&(f.length===0||z(f[0])==="--")){for(let y of t.redirections){if(y.target.type==="HereDoc"||y.fdVariable)continue;let b=await L(this.ctx,y.target),k=y.fd??(y.operator==="<"||y.operator==="<>"?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),y.operator){case">":case">|":{let P=this.ctx.fs.resolvePath(this.ctx.state.cwd,b);await this.ctx.fs.writeFile(P,"","utf8"),this.ctx.state.fileDescriptors.set(k,`__file__:${P}`);break}case">>":{let P=this.ctx.fs.resolvePath(this.ctx.state.cwd,b);this.ctx.state.fileDescriptors.set(k,`__file_append__:${P}`);break}case"<":{let P=this.ctx.fs.resolvePath(this.ctx.state.cwd,b);try{let M=await this.ctx.fs.readFile(P);this.ctx.state.fileDescriptors.set(k,M)}catch{return _(`bash: ${b}: No such file or directory
670
- `)}break}case"<>":{let P=this.ctx.fs.resolvePath(this.ctx.state.cwd,b);try{let M=await this.ctx.fs.readFile(P);this.ctx.state.fileDescriptors.set(k,`__rw__:${P.length}:${P}:0:${M}`)}catch{await this.ctx.fs.writeFile(P,"","utf8"),this.ctx.state.fileDescriptors.set(k,`__rw__:${P.length}:${P}:0:`)}break}case">&":{if(b==="-")this.ctx.state.fileDescriptors.delete(k);else if(b.endsWith("-")){let P=b.slice(0,-1),M=Number.parseInt(P,10);if(!Number.isNaN(M)){let I=this.ctx.state.fileDescriptors.get(M);I!==void 0?this.ctx.state.fileDescriptors.set(k,I):this.ctx.state.fileDescriptors.set(k,`__dupout__:${M}`),this.ctx.state.fileDescriptors.delete(M)}}else{let P=Number.parseInt(b,10);Number.isNaN(P)||this.ctx.state.fileDescriptors.set(k,`__dupout__:${P}`)}break}case"<&":{if(b==="-")this.ctx.state.fileDescriptors.delete(k);else if(b.endsWith("-")){let P=b.slice(0,-1),M=Number.parseInt(P,10);if(!Number.isNaN(M)){let I=this.ctx.state.fileDescriptors.get(M);I!==void 0?this.ctx.state.fileDescriptors.set(k,I):this.ctx.state.fileDescriptors.set(k,`__dupin__:${M}`),this.ctx.state.fileDescriptors.delete(M)}}else{let P=Number.parseInt(b,10);Number.isNaN(P)||this.ctx.state.fileDescriptors.set(k,`__dupin__:${P}`)}break}}}for(let[y,b]of n)b===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,b);if(this.ctx.state.tempExportedVars)for(let y of n.keys())this.ctx.state.tempExportedVars.delete(y);return V}let g=await Yn(this.ctx,l,f.map(y=>z(y)));n.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let m,v=null;try{m=await this.runCommand(l,f,d,s,!1,!1,u)}catch(y){if(y instanceof ye||y instanceof ge)v=y,m=V;else throw y}let S=i+g;if(S&&(m={...m,stderr:x(E(S),m.stderr)}),m=await Y(this.ctx,m,t.redirections),v)throw v;if(f.length>0){let y=z(f[f.length-1]);if((l==="declare"||l==="local"||l==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(y)){let b=y.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);b&&(y=b[1])}this.ctx.state.lastArg=E(y)}else this.ctx.state.lastArg=E(l);let A=on(l)&&l!=="unset"&&l!=="eval";if(!this.ctx.state.options.posix||!A)for(let[y,b]of n)this.ctx.state.fullyUnsetLocals?.has(y)||(b===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,b));if(this.ctx.state.tempExportedVars)for(let y of n.keys())this.ctx.state.tempExportedVars.delete(y);return n.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(m={...m,stderr:x(E(this.ctx.state.expansionStderr),m.stderr)},this.ctx.state.expansionStderr=""),m}async runCommand(t,s,r,n,i=!1,o=!1,a=-1){let c={ctx:this.ctx,runCommand:(l,f,d,h,g,m,v)=>this.runCommand(l,f,d,h,g,m,v),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(l,f,d)=>this.executeUserScript(l,f,d)},u=await Ln(c,t,s,r,n,i,o,a);return u!==null?u:Wn(c,t,s,n,o)}aliasExpansionStack=new Set;expandAlias(t){return gs(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Jt(this.ctx,t)}async executeSubshell(t,s=p){return ei(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=p){return ti(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Ne(this.ctx,t.redirections);if(s)return s;try{let r=await Z(this.ctx,t.expression.expression),n=Q(r!==0);return this.ctx.state.expansionStderr&&(n={...n,stderr:x(E(this.ctx.state.expansionStderr),n.stderr)},this.ctx.state.expansionStderr=""),Y(this.ctx,n,t.redirections)}catch(r){let n=_(`bash: arithmetic expression: ${r.message}
670
+ `)}break}case"<>":{let P=this.ctx.fs.resolvePath(this.ctx.state.cwd,b);try{let M=await this.ctx.fs.readFile(P);this.ctx.state.fileDescriptors.set(k,`__rw__:${P.length}:${P}:0:${M}`)}catch{await this.ctx.fs.writeFile(P,"","utf8"),this.ctx.state.fileDescriptors.set(k,`__rw__:${P.length}:${P}:0:`)}break}case">&":{if(b==="-")this.ctx.state.fileDescriptors.delete(k);else if(b.endsWith("-")){let P=b.slice(0,-1),M=Number.parseInt(P,10);if(!Number.isNaN(M)){let I=this.ctx.state.fileDescriptors.get(M);I!==void 0?this.ctx.state.fileDescriptors.set(k,I):this.ctx.state.fileDescriptors.set(k,`__dupout__:${M}`),this.ctx.state.fileDescriptors.delete(M)}}else{let P=Number.parseInt(b,10);Number.isNaN(P)||this.ctx.state.fileDescriptors.set(k,`__dupout__:${P}`)}break}case"<&":{if(b==="-")this.ctx.state.fileDescriptors.delete(k);else if(b.endsWith("-")){let P=b.slice(0,-1),M=Number.parseInt(P,10);if(!Number.isNaN(M)){let I=this.ctx.state.fileDescriptors.get(M);I!==void 0?this.ctx.state.fileDescriptors.set(k,I):this.ctx.state.fileDescriptors.set(k,`__dupin__:${M}`),this.ctx.state.fileDescriptors.delete(M)}}else{let P=Number.parseInt(b,10);Number.isNaN(P)||this.ctx.state.fileDescriptors.set(k,`__dupin__:${P}`)}break}}}for(let[y,b]of n)b===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,b);if(this.ctx.state.tempExportedVars)for(let y of n.keys())this.ctx.state.tempExportedVars.delete(y);return V}let g=await Kn(this.ctx,l,f.map(y=>z(y)));n.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let m,v=null;try{m=await this.runCommand(l,f,d,s,!1,!1,u)}catch(y){if(y instanceof ye||y instanceof ge)v=y,m=V;else throw y}let S=i+g;if(S&&(m={...m,stderr:x(E(S),m.stderr)}),m=await Y(this.ctx,m,t.redirections),v)throw v;if(f.length>0){let y=z(f[f.length-1]);if((l==="declare"||l==="local"||l==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(y)){let b=y.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);b&&(y=b[1])}this.ctx.state.lastArg=E(y)}else this.ctx.state.lastArg=E(l);let A=an(l)&&l!=="unset"&&l!=="eval";if(!this.ctx.state.options.posix||!A)for(let[y,b]of n)this.ctx.state.fullyUnsetLocals?.has(y)||(b===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,b));if(this.ctx.state.tempExportedVars)for(let y of n.keys())this.ctx.state.tempExportedVars.delete(y);return n.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(m={...m,stderr:x(E(this.ctx.state.expansionStderr),m.stderr)},this.ctx.state.expansionStderr=""),m}async runCommand(t,s,r,n,i=!1,o=!1,a=-1){let c={ctx:this.ctx,runCommand:(l,f,d,h,g,m,v)=>this.runCommand(l,f,d,h,g,m,v),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(l,f,d)=>this.executeUserScript(l,f,d)},u=await Wn(c,t,s,r,n,i,o,a);return u!==null?u:zn(c,t,s,n,o)}aliasExpansionStack=new Set;expandAlias(t){return gs(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Jt(this.ctx,t)}async executeSubshell(t,s=p){return ti(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=p){return si(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Ne(this.ctx,t.redirections);if(s)return s;try{let r=await Z(this.ctx,t.expression.expression),n=Q(r!==0);return this.ctx.state.expansionStderr&&(n={...n,stderr:x(E(this.ctx.state.expansionStderr),n.stderr)},this.ctx.state.expansionStderr=""),Y(this.ctx,n,t.redirections)}catch(r){let n=_(`bash: arithmetic expression: ${r.message}
671
671
  `);return Y(this.ctx,n,t.redirections)}}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Ne(this.ctx,t.redirections);if(s)return s;try{let r=await We(this.ctx,t.expression),n=Q(r);return this.ctx.state.expansionStderr&&(n={...n,stderr:x(E(this.ctx.state.expansionStderr),n.stderr)},this.ctx.state.expansionStderr=""),Y(this.ctx,n,t.redirections)}catch(r){let n=r instanceof Ve?1:2,i=_(`bash: conditional expression: ${r.message}
672
- `,n);return Y(this.ctx,i,t.redirections)}}};var he={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};function ri(e){return e?{maxCallDepth:e.maxCallDepth??he.maxCallDepth,maxCommandCount:e.maxCommandCount??he.maxCommandCount,maxLoopIterations:e.maxLoopIterations??he.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??he.maxAwkIterations,maxSedIterations:e.maxSedIterations??he.maxSedIterations,maxJqIterations:e.maxJqIterations??he.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??he.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??he.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??he.maxGlobOperations,maxStringLength:e.maxStringLength??he.maxStringLength,maxArrayElements:e.maxArrayElements??he.maxArrayElements,maxHeredocSize:e.maxHeredocSize??he.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??he.maxSubstitutionDepth}:{...he}}function ni(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Lo(e){let t=ni(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Wo(e,t){let s=ni(e);if(!s)return!1;let r=Lo(t);return!r||s.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:s.pathname.startsWith(r.pathPrefix)}function cr(e,t){return!t||t.length===0?!1:t.some(s=>Wo(e,s))}var rt=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},nt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},it=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},ts=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 zo=20,Vo=3e4,Bo=10485760,jo=["GET","HEAD"],Ho=new Set(["GET","HEAD","OPTIONS"]),Uo=new Set([301,302,303,307,308]);function ur(e){let t=e.maxRedirects??zo,s=e.timeoutMs??Vo,r=e.maxResponseSize??Bo,n=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??jo;function i(c){if(!e.dangerouslyAllowFullInternetAccess&&!cr(c,e.allowedUrlPrefixes??[]))throw new rt(c)}function o(c){if(e.dangerouslyAllowFullInternetAccess)return;let u=c.toUpperCase();if(!n.includes(u))throw new ts(u,n)}async function a(c,u={}){let l=u.method?.toUpperCase()??"GET";i(c),o(l);let f=c,d=0,h=u.followRedirects??!0,g=u.timeoutMs!==void 0?Math.min(u.timeoutMs,s):s;for(;;){let m=new AbortController,v=setTimeout(()=>m.abort(),g);try{let S={method:l,headers:u.headers,signal:m.signal,redirect:"manual"};u.body&&!Ho.has(l)&&(S.body=u.body);let A=await fetch(f,S);if(Uo.has(A.status)&&h){let C=A.headers.get("location");if(!C)return await ii(A,f,r);let y=new URL(C,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!cr(y,e.allowedUrlPrefixes??[]))throw new it(y);if(d++,d>t)throw new nt(t);f=y;continue}return await ii(A,f,r)}finally{clearTimeout(v)}}}return a}async function ii(e,t,s){let r=Object.create(null);if(e.headers.forEach((i,o)=>{r[o.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let o=parseInt(i,10);if(!Number.isNaN(o)&&o>s)throw new bt(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),o=new TextDecoder,a=[],c=0;for(;;){let{done:u,value:l}=await i.read();if(u)break;if(c+=l.byteLength,c>s)throw i.cancel(),new bt(s);a.push(o.decode(l,{stream:!0}))}a.push(o.decode()),n=a.join("")}else n=await e.text();return{status:e.status,statusText:e.statusText,headers:r,body:n,url:t}}function fr(){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 Et=typeof __BROWSER__<"u"&&__BROWSER__;function oi(){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 hr=null;if(!Et)try{let{createRequire:e}=await import("node:module");hr=e(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 Go=`
672
+ `,n);return Y(this.ctx,i,t.redirections)}}};var he={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};function ni(e){return e?{maxCallDepth:e.maxCallDepth??he.maxCallDepth,maxCommandCount:e.maxCommandCount??he.maxCommandCount,maxLoopIterations:e.maxLoopIterations??he.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??he.maxAwkIterations,maxSedIterations:e.maxSedIterations??he.maxSedIterations,maxJqIterations:e.maxJqIterations??he.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??he.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??he.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??he.maxGlobOperations,maxStringLength:e.maxStringLength??he.maxStringLength,maxArrayElements:e.maxArrayElements??he.maxArrayElements,maxHeredocSize:e.maxHeredocSize??he.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??he.maxSubstitutionDepth}:{...he}}function ii(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Wo(e){let t=ii(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function zo(e,t){let s=ii(e);if(!s)return!1;let r=Wo(t);return!r||s.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:s.pathname.startsWith(r.pathPrefix)}function cr(e,t){return!t||t.length===0?!1:t.some(s=>zo(e,s))}var rt=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},nt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},it=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},ts=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 Vo=20,Bo=3e4,jo=10485760,Ho=["GET","HEAD"],Uo=new Set(["GET","HEAD","OPTIONS"]),Go=new Set([301,302,303,307,308]);function ur(e){let t=e.maxRedirects??Vo,s=e.timeoutMs??Bo,r=e.maxResponseSize??jo,n=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??Ho;function i(c){if(!e.dangerouslyAllowFullInternetAccess&&!cr(c,e.allowedUrlPrefixes??[]))throw new rt(c)}function o(c){if(e.dangerouslyAllowFullInternetAccess)return;let u=c.toUpperCase();if(!n.includes(u))throw new ts(u,n)}async function a(c,u={}){let l=u.method?.toUpperCase()??"GET";i(c),o(l);let f=c,d=0,h=u.followRedirects??!0,g=u.timeoutMs!==void 0?Math.min(u.timeoutMs,s):s;for(;;){let m=new AbortController,v=setTimeout(()=>m.abort(),g);try{let S={method:l,headers:u.headers,signal:m.signal,redirect:"manual"};u.body&&!Uo.has(l)&&(S.body=u.body);let A=await fetch(f,S);if(Go.has(A.status)&&h){let C=A.headers.get("location");if(!C)return await oi(A,f,r);let y=new URL(C,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!cr(y,e.allowedUrlPrefixes??[]))throw new it(y);if(d++,d>t)throw new nt(t);f=y;continue}return await oi(A,f,r)}finally{clearTimeout(v)}}}return a}async function oi(e,t,s){let r=Object.create(null);if(e.headers.forEach((i,o)=>{r[o.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let o=parseInt(i,10);if(!Number.isNaN(o)&&o>s)throw new bt(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),o=new TextDecoder,a=[],c=0;for(;;){let{done:u,value:l}=await i.read();if(u)break;if(c+=l.byteLength,c>s)throw i.cancel(),new bt(s);a.push(o.decode(l,{stream:!0}))}a.push(o.decode()),n=a.join("")}else n=await e.text();return{status:e.status,statusText:e.statusText,headers:r,body:n,url:t}}function fr(){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 Et=typeof __BROWSER__<"u"&&__BROWSER__;function ai(){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 hr=null;if(!Et)try{let{createRequire:e}=await import("node:module");hr=e(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 qo=`
673
673
 
674
- This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,ne=class extends Error{violation;constructor(t,s){super(t+Go),this.violation=s,this.name="SecurityViolationError"}},pe=!Et&&hr?new hr:null,qo=1e3,dr={enabled:!0,auditMode:!1};function Zo(e){return e===void 0?{...dr,enabled:!1}:typeof e=="boolean"?{...dr,enabled:e}:{...dr,...e}}var ot=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(Zo(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return pe?pe?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(pe)return pe?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Et||!this.config.enabled){let s=oi();return{run:r=>r(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=oi();return{run:s=>pe.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 Et||this.config.auditMode||!pe?!1:pe?.getStore()?.sandboxActive===!0}recordViolation(t,s,r){let n={timestamp:Date.now(),type:t,message:r,path:s,stack:new Error().stack,executionId:pe?.getStore()?.executionId};if(this.violations.length<qo&&this.violations.push(n),this.config.onViolation)try{this.config.onViolation(n)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return n}createBlockingProxy(t,s,r){let n=this;return new Proxy(t,{apply(i,o,a){if(n.shouldBlock()){let c=`${s} is blocked during script execution`,u=n.recordViolation(r,s,c);throw new ne(c,u)}return n.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} called (audit mode)`),Reflect.apply(i,o,a)},construct(i,o,a){if(n.shouldBlock()){let c=`${s} constructor is blocked during script execution`,u=n.recordViolation(r,s,c);throw new ne(c,u)}return n.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} constructor called (audit mode)`),Reflect.construct(i,o,a)}})}createBlockingObjectProxy(t,s,r){let n=this;return new Proxy(t,{get(i,o,a){if(n.shouldBlock()){let c=`${s}.${String(o)}`,u=`${c} is blocked during script execution`,l=n.recordViolation(r,c,u);throw new ne(u,l)}if(n.config.auditMode&&pe?.getStore()?.sandboxActive===!0){let c=`${s}.${String(o)}`;n.recordViolation(r,c,`${c} accessed (audit mode)`)}return Reflect.get(i,o,a)},set(i,o,a,c){if(n.shouldBlock()){let u=`${s}.${String(o)}`,l=`${u} modification is blocked during script execution`,f=n.recordViolation(r,u,l);throw new ne(l,f)}return Reflect.set(i,o,a,c)},ownKeys(i){if(n.shouldBlock()){let o=`${s} enumeration is blocked during script execution`,a=n.recordViolation(r,s,o);throw new ne(o,a)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,o){if(n.shouldBlock()){let a=`${s}.${String(o)}`,c=`${a} descriptor access is blocked during script execution`,u=n.recordViolation(r,a,c);throw new ne(c,u)}return Reflect.getOwnPropertyDescriptor(i,o)},has(i,o){if(n.shouldBlock()){let a=`${s}.${String(o)}`,c=`${a} existence check is blocked during script execution`,u=n.recordViolation(r,a,c);throw new ne(c,u)}return Reflect.has(i,o)}})}applyPatches(){let t=fr();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 r=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return r},set(n){if(t.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",o=t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new ne(i,o)}t.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),r=n},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,r){let n=this;try{let i=Object.getOwnPropertyDescriptor(t,"constructor");this.originalDescriptors.push({target:t,prop:"constructor",descriptor:i});let o=i?.value;Object.defineProperty(t,"constructor",{get(){if(n.shouldBlock()){let a=`${s} access is blocked during script execution`,c=n.recordViolation(r,s,a);throw new ne(a,c)}return n.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} accessed (audit mode)`),o},set(a){if(n.shouldBlock()){let c=`${s} modification is blocked during script execution`,u=n.recordViolation(r,s,c);throw new ne(c,u)}Object.defineProperty(this,"constructor",{value:a,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 r=s?.value;r!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let n="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",n);throw new ne(n,i)}return t.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),r},set(n){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",o=t.recordViolation("process_main_module","process.mainModule",i);throw new ne(i,o)}Object.defineProperty(process,"mainModule",{value:n,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Et)try{let t=null;if(typeof process<"u"){let o=process.mainModule;o&&typeof o=="object"&&(t=o.constructor)}if(!t&&typeof ft<"u"&&typeof ft.main<"u"&&(t=ft.main.constructor),!t||typeof t._load!="function")return;let s=t._load,r=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:r});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:r,violationType:n,strategy:i}=t;try{let o=s[r];if(o===void 0)return;let a=Object.getOwnPropertyDescriptor(s,r);if(this.originalDescriptors.push({target:s,prop:r,descriptor:a}),i==="freeze")typeof o=="object"&&o!==null&&Object.freeze(o);else{let c=this.getPathForTarget(s,r),u=typeof o=="function"?this.createBlockingProxy(o,c,n):this.createBlockingObjectProxy(o,c,n);Object.defineProperty(s,r,{value:u,writable:!0,configurable:!0})}}catch(o){let a=this.getPathForTarget(s,r);console.debug(`[DefenseInDepthBox] Could not patch ${a}:`,o instanceof Error?o.message:o)}}restorePatches(){for(let t=this.originalDescriptors.length-1;t>=0;t--){let{target:s,prop:r,descriptor:n}=this.originalDescriptors[t];try{n?Object.defineProperty(s,r,n):delete s[r]}catch(i){let o=this.getPathForTarget(s,r);console.debug(`[DefenseInDepthBox] Could not restore ${o}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var $t=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Ie(t.files);this.fs=s,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),n=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
675
- `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"]];for(let[o,a]of i)w(n,o,a);for(let[o,a]of Object.entries(t.env??{}))w(n,o,a);if(this.limits=ri({...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=ur(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:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:p,startTime:Date.now(),lastBackgroundPid:0,bashPid:os().pid,nextVirtualPid:os().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},w(this.state.env,"SHELLOPTS",ps(this.state.options)),w(this.state.env,"BASHOPTS",ms(this.state.shoptOptions)),Lr(s,this.useDefaultLayout),r!=="/"&&s instanceof Ie)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let o of Dr(t.commands))this.registerCommand(o);if(t.network)for(let o of Ir())this.registerCommand(o);if(t.python)for(let o of Rr())this.registerCommand(o);if(t.customCommands)for(let o of t.customCommands)Mr(o)?this.registerCommand(Fr(o)):this.registerCommand(o)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let r=`#!/bin/bash
674
+ This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,ne=class extends Error{violation;constructor(t,s){super(t+qo),this.violation=s,this.name="SecurityViolationError"}},pe=!Et&&hr?new hr:null,Zo=1e3,dr={enabled:!0,auditMode:!1};function Yo(e){return e===void 0?{...dr,enabled:!1}:typeof e=="boolean"?{...dr,enabled:e}:{...dr,...e}}var ot=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(Yo(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return pe?pe?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(pe)return pe?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Et||!this.config.enabled){let s=ai();return{run:r=>r(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=ai();return{run:s=>pe.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 Et||this.config.auditMode||!pe?!1:pe?.getStore()?.sandboxActive===!0}recordViolation(t,s,r){let n={timestamp:Date.now(),type:t,message:r,path:s,stack:new Error().stack,executionId:pe?.getStore()?.executionId};if(this.violations.length<Zo&&this.violations.push(n),this.config.onViolation)try{this.config.onViolation(n)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return n}createBlockingProxy(t,s,r){let n=this;return new Proxy(t,{apply(i,o,a){if(n.shouldBlock()){let c=`${s} is blocked during script execution`,u=n.recordViolation(r,s,c);throw new ne(c,u)}return n.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} called (audit mode)`),Reflect.apply(i,o,a)},construct(i,o,a){if(n.shouldBlock()){let c=`${s} constructor is blocked during script execution`,u=n.recordViolation(r,s,c);throw new ne(c,u)}return n.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} constructor called (audit mode)`),Reflect.construct(i,o,a)}})}createBlockingObjectProxy(t,s,r){let n=this;return new Proxy(t,{get(i,o,a){if(n.shouldBlock()){let c=`${s}.${String(o)}`,u=`${c} is blocked during script execution`,l=n.recordViolation(r,c,u);throw new ne(u,l)}if(n.config.auditMode&&pe?.getStore()?.sandboxActive===!0){let c=`${s}.${String(o)}`;n.recordViolation(r,c,`${c} accessed (audit mode)`)}return Reflect.get(i,o,a)},set(i,o,a,c){if(n.shouldBlock()){let u=`${s}.${String(o)}`,l=`${u} modification is blocked during script execution`,f=n.recordViolation(r,u,l);throw new ne(l,f)}return Reflect.set(i,o,a,c)},ownKeys(i){if(n.shouldBlock()){let o=`${s} enumeration is blocked during script execution`,a=n.recordViolation(r,s,o);throw new ne(o,a)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,o){if(n.shouldBlock()){let a=`${s}.${String(o)}`,c=`${a} descriptor access is blocked during script execution`,u=n.recordViolation(r,a,c);throw new ne(c,u)}return Reflect.getOwnPropertyDescriptor(i,o)},has(i,o){if(n.shouldBlock()){let a=`${s}.${String(o)}`,c=`${a} existence check is blocked during script execution`,u=n.recordViolation(r,a,c);throw new ne(c,u)}return Reflect.has(i,o)}})}applyPatches(){let t=fr();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 r=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return r},set(n){if(t.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",o=t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new ne(i,o)}t.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),r=n},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,r){let n=this;try{let i=Object.getOwnPropertyDescriptor(t,"constructor");this.originalDescriptors.push({target:t,prop:"constructor",descriptor:i});let o=i?.value;Object.defineProperty(t,"constructor",{get(){if(n.shouldBlock()){let a=`${s} access is blocked during script execution`,c=n.recordViolation(r,s,a);throw new ne(a,c)}return n.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} accessed (audit mode)`),o},set(a){if(n.shouldBlock()){let c=`${s} modification is blocked during script execution`,u=n.recordViolation(r,s,c);throw new ne(c,u)}Object.defineProperty(this,"constructor",{value:a,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 r=s?.value;r!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let n="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",n);throw new ne(n,i)}return t.config.auditMode&&pe?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),r},set(n){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",o=t.recordViolation("process_main_module","process.mainModule",i);throw new ne(i,o)}Object.defineProperty(process,"mainModule",{value:n,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Et)try{let t=null;if(typeof process<"u"){let o=process.mainModule;o&&typeof o=="object"&&(t=o.constructor)}if(!t&&typeof ft<"u"&&typeof ft.main<"u"&&(t=ft.main.constructor),!t||typeof t._load!="function")return;let s=t._load,r=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:r});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:r,violationType:n,strategy:i}=t;try{let o=s[r];if(o===void 0)return;let a=Object.getOwnPropertyDescriptor(s,r);if(this.originalDescriptors.push({target:s,prop:r,descriptor:a}),i==="freeze")typeof o=="object"&&o!==null&&Object.freeze(o);else{let c=this.getPathForTarget(s,r),u=typeof o=="function"?this.createBlockingProxy(o,c,n):this.createBlockingObjectProxy(o,c,n);Object.defineProperty(s,r,{value:u,writable:!0,configurable:!0})}}catch(o){let a=this.getPathForTarget(s,r);console.debug(`[DefenseInDepthBox] Could not patch ${a}:`,o instanceof Error?o.message:o)}}restorePatches(){for(let t=this.originalDescriptors.length-1;t>=0;t--){let{target:s,prop:r,descriptor:n}=this.originalDescriptors[t];try{n?Object.defineProperty(s,r,n):delete s[r]}catch(i){let o=this.getPathForTarget(s,r);console.debug(`[DefenseInDepthBox] Could not restore ${o}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var $t=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Ie(t.files);this.fs=s,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),n=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
675
+ `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"]];for(let[o,a]of i)w(n,o,a);for(let[o,a]of Object.entries(t.env??{}))w(n,o,a);if(this.limits=ni({...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=ur(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:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:p,startTime:Date.now(),lastBackgroundPid:0,bashPid:os().pid,nextVirtualPid:os().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},w(this.state.env,"SHELLOPTS",ps(this.state.options)),w(this.state.env,"BASHOPTS",ms(this.state.shoptOptions)),Wr(s,this.useDefaultLayout),r!=="/"&&s instanceof Ie)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let o of Ir(t.commands))this.registerCommand(o);if(t.network)for(let o of Rr())this.registerCommand(o);if(t.python)for(let o of Mr())this.registerCommand(o);if(t.customCommands)for(let o of t.customCommands)Fr(o)?this.registerCommand(Lr(o)):this.registerCommand(o)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let r=`#!/bin/bash
676
676
  # Built-in command: ${t.name}
677
677
  `;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout.length>0&&this.logger.debug("stdout",{output:z(t.stdout)}),t.stderr.length>0&&this.logger.info("stderr",{output:z(t.stderr)}),this.logger.info("exit",{exitCode:t.exitCode})),t}async exec(t,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:p,stderr:E(`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
678
- `),exitCode:1,env:$e(this.state.env,s?.env)};if(!t.trim())return{stdout:p,stderr:p,exitCode:0,env:$e(this.state.env,s?.env)};this.logger?.info("exec",{command:t});let r=s?.cwd??this.state.cwd,n,i=r;if(s?.cwd)if(s.env&&"PWD"in s.env)n=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{n=await this.fs.realpath(r),i=n}catch{n=r}else n=r;let o=new Map(this.state.env);if(s?.env)for(let[f,d]of Object.entries(s.env))w(o,f,d);n!==void 0&&w(o,"PWD",n);let a={...this.state,env:o,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:s?.stdin||void 0},c=t;s?.rawScript||(c=Yo(t));let l=(this.defenseInDepthConfig?ot.getInstance(this.defenseInDepthConfig):null)?.activate();try{let f=async()=>{let d=Ae(c),h={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter},m=await new vt(h,a).executeScript(d);return this.logResult(m)};return l?await l.run(f):await f()}catch(f){if(f instanceof G)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:$e(this.state.env,s?.env)});if(f instanceof Ee)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:$e(this.state.env,s?.env)});if(f instanceof Ve)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:$e(this.state.env,s?.env)});if(f instanceof ae)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:ae.EXIT_CODE,env:$e(this.state.env,s?.env)});if(f instanceof ne)return this.logResult({stdout:p,stderr:E(`bash: security violation: ${f.message}
678
+ `),exitCode:1,env:$e(this.state.env,s?.env)};if(!t.trim())return{stdout:p,stderr:p,exitCode:0,env:$e(this.state.env,s?.env)};this.logger?.info("exec",{command:t});let r=s?.cwd??this.state.cwd,n,i=r;if(s?.cwd)if(s.env&&"PWD"in s.env)n=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{n=await this.fs.realpath(r),i=n}catch{n=r}else n=r;let o=new Map(this.state.env);if(s?.env)for(let[f,d]of Object.entries(s.env))w(o,f,d);n!==void 0&&w(o,"PWD",n);let a={...this.state,env:o,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:s?.stdin||void 0},c=t;s?.rawScript||(c=Ko(t));let l=(this.defenseInDepthConfig?ot.getInstance(this.defenseInDepthConfig):null)?.activate();try{let f=async()=>{let d=Ae(c),h={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter},m=await new vt(h,a).executeScript(d);return this.logResult(m)};return l?await l.run(f):await f()}catch(f){if(f instanceof G)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:$e(this.state.env,s?.env)});if(f instanceof Ee)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:$e(this.state.env,s?.env)});if(f instanceof Ve)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:$e(this.state.env,s?.env)});if(f instanceof ae)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:ae.EXIT_CODE,env:$e(this.state.env,s?.env)});if(f instanceof ne)return this.logResult({stdout:p,stderr:E(`bash: security violation: ${f.message}
679
679
  `),exitCode:1,env:$e(this.state.env,s?.env)});if(f.name==="ParseException")return this.logResult({stdout:p,stderr:E(`bash: syntax error: ${f.message}
680
- `),exitCode:2,env:$e(this.state.env,s?.env)});if(f instanceof vr)return this.logResult({stdout:p,stderr:E(`bash: ${f.message}
680
+ `),exitCode:2,env:$e(this.state.env,s?.env)});if(f instanceof br)return this.logResult({stdout:p,stderr:E(`bash: ${f.message}
681
681
  `),exitCode:2,env:$e(this.state.env,s?.env)});if(f instanceof RangeError)return this.logResult({stdout:p,stderr:E(`bash: ${f.message}
682
- `),exitCode:1,env:$e(this.state.env,s?.env)});throw f}finally{l?.deactivate()}}async readFile(t){return this.fs.readFile(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 Fe(this.state.env)}};function Yo(e){let t=e.split(`
682
+ `),exitCode:1,env:$e(this.state.env,s?.env)});throw f}finally{l?.deactivate()}}async readFile(t){return this.fs.readFile(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 Fe(this.state.env)}};function Ko(e){let t=e.split(`
683
683
  `),s=[],r=[];for(let n=0;n<t.length;n++){let i=t[n];if(r.length>0){let c=r[r.length-1];if((c.stripTabs?i.replace(/^\t+/,""):i)===c.delimiter){s.push(i.trimStart()),r.pop();continue}s.push(i);continue}let o=i.trimStart();s.push(o);let a=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let c of o.matchAll(a)){let u=c[1]==="-",l=c[3];r.push({delimiter:l,stripTabs:u})}}return s.join(`
684
- `)}var ss=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new Ie,t?.mounts)for(let{mountPoint:s,filesystem:r}of t.mounts)this.mount(s,r)}mount(t,s){this.validateMountPath(t);let r=this.normalizePath(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(t){let s=this.normalizePath(t);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=this.normalizePath(t);return this.mounts.has(s)}validateMountPath(t){let s=t.split("/");for(let r of s)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let s of this.mounts.keys())if(s!==t){if(t.startsWith(`${s}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${s}'`);if(s.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${s}'`)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`}routePath(t){let s=this.normalizePath(t),r=null,n=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(s===o)return{fs:i.filesystem,relativePath:"/"};s.startsWith(`${o}/`)&&o.length>n&&(r=i,n=o.length)}if(r){let i=s.slice(n);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(t){let s=this.normalizePath(t),r=s==="/"?"/":`${s}/`,n=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!n.includes(a)&&n.push(a)}return n}async readFile(t,s){let{fs:r,relativePath:n}=this.routePath(t);return r.readFile(n,s)}async readFileBuffer(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readFileBuffer(r)}async writeFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.writeFile(i,s,r)}async appendFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.appendFile(i,s,r)}async exists(t){let s=this.normalizePath(t);if(this.mounts.has(s)||this.getChildMountPoints(s).length>0)return!0;let{fs:n,relativePath:i}=this.routePath(t);return n.exists(i)}async stat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.stat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.stat(o)}async lstat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.lstat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.lstat(o)}async mkdir(t,s){let r=this.normalizePath(t);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:i,relativePath:o}=this.routePath(t);return i.mkdir(o,s)}async readdir(t){let s=this.normalizePath(t),r=new Set,n=null,{fs:i,relativePath:o}=this.routePath(t);try{let c=await i.readdir(o);for(let u of c)r.add(u)}catch(c){let u=c.code,l=c.message||"";if(u!=="ENOENT"&&!l.includes("ENOENT"))throw c;n=c}let a=this.getChildMountPoints(s);for(let c of a)r.add(c);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:o}=this.routePath(t);return i.rm(o,s)}async cp(t,s,r){let n=this.routePath(t),i=this.routePath(s);return n.fs===i.fs?n.fs.cp(n.relativePath,i.relativePath,r):this.crossMountCopy(t,s,r)}async mv(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let n=this.routePath(t),i=this.routePath(s);if(n.fs===i.fs)return n.fs.mv(n.relativePath,i.relativePath);await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=new Set;for(let s of this.baseFs.getAllPaths())t.add(s);for(let s of this.mounts.keys()){let r=s.split("/").filter(Boolean),n="";for(let o of r)n=`${n}/${o}`,t.add(n);let i=this.mounts.get(s);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?t.add(s):t.add(`${s}${o}`)}return Array.from(t).sort()}async chmod(t,s){let r=this.normalizePath(t),n=this.mounts.get(r);if(n)return n.filesystem.chmod("/",s);let{fs:i,relativePath:o}=this.routePath(t);return i.chmod(o,s)}async symlink(t,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(t,n)}async link(t,s){let r=this.routePath(t),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readlink(r)}async realpath(t){let s=this.normalizePath(t);if(this.mounts.get(s))return s;let{fs:n,relativePath:i}=this.routePath(t),o=await n.realpath(i);for(let[a,c]of this.mounts)if(s===a||s.startsWith(`${a}/`))return o==="/"?a:`${a}${o}`;return o}async crossMountCopy(t,s,r){let n=await this.lstat(t);if(n.isFile){let i=await this.readFileBuffer(t);await this.writeFile(s,i),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let i=await this.readdir(t);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`,c=s==="/"?`/${o}`:`${s}/${o}`;await this.crossMountCopy(a,c,r)}}else if(n.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,s)}}async utimes(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.utimes(i,s,r)}};import*as ee from"node:fs";import*as at from"node:path";var Ko="/home/user/project";function ie(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var lt=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=at.resolve(t.root);let s=t.mountPoint??Ko;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,!ee.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ee.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 r of t)s+=`/${r}`,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 n=this.normalizePath(t).split("/").filter(Boolean),i="";for(let o of n)i+=`/${o}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=this.normalizePath(t),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let i=s instanceof Uint8Array?s:new TextEncoder().encode(s);this.memory.set(r,{type:"file",content:i,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 r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.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),r=this.getRelativeToMount(s);if(r===null)return null;let n=at.join(this.root,r),i=at.resolve(n);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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 r=this.toRealPath(s);if(!r)return!1;try{return await ee.promises.access(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Ke(r,n)}async readFileBuffer(t,s=new Set){ie(t,"open");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target);return this.readFileBuffer(o,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.content}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let o=await ee.promises.lstat(i);if(o.isSymbolicLink()){let c=await ee.promises.readlink(i),u=this.resolveSymlink(r,c);return this.readFileBuffer(u,s)}if(o.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&o.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${o.size} bytes, max ${this.maxFileReadSize})`);let a=await ee.promises.readFile(i);return new Uint8Array(a)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):o}}async writeFile(t,s,r){ie(t,"write"),this.assertWritable(`write '${t}'`);let n=this.normalizePath(t);this.ensureParentDirs(n);let i=be(r),o=De(s,i);this.memory.set(n,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){ie(t,"append"),this.assertWritable(`append '${t}'`);let n=this.normalizePath(t),i=be(r),o=De(s,i),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let c=new Uint8Array(a.length+o.length);c.set(a),c.set(o,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:c,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){ie(t,"stat");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.stat(a,s)}let o=0;return n.type==="file"&&(o=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:o,mtime:n.mtime}}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await ee.promises.stat(i);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):o}}async lstat(t){ie(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ee.promises.lstat(n);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 r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(t,s){ie(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=this.normalizePath(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(r);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(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let a of this.deleted)if(a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&n.add(u)}for(let[a,c]of this.memory)if(a!==s&&a.startsWith(i)){let u=a.slice(i.length),l=u.split("/")[0];l&&!n.has(l)&&!u.includes("/",1)&&r.set(l,{name:l,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}let o=this.toRealPath(s);if(o)try{let a=await ee.promises.readdir(o,{withFileTypes:!0});for(let c of a)!n.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async resolveForReaddir(t,s=!1){let r=this.normalizePath(t),n=new Set,i=s,o=this.memory.get(r);for(;o&&o.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,o.target),o=this.memory.get(r)}if(o)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let c=this.toRealPath(r);if(!c)return{normalized:r,outsideOverlay:!0};try{if((await ee.promises.lstat(c)).isSymbolicLink()){let l=await ee.promises.readlink(c),f=this.resolveSymlink(r,l);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){ie(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){ie(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,s){ie(t,"rm"),this.assertWritable(`rm '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let o=await this.readdir(r);if(o.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of o){let c=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(c,s)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(t,s,r){ie(t,"cp"),ie(s,"cp"),this.assertWritable(`cp '${s}'`);let n=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let a=await this.stat(n);if(a.isFile){let c=await this.readFileBuffer(n);await this.writeFile(i,c)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let c=await this.readdir(n);for(let u of c){let l=n==="/"?`/${u}`:`${n}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(l,f,r)}}}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 r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}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 r=this.toRealPath(t);if(r)try{let n=ee.readdirSync(r);for(let i of n){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(o))continue;s.add(o);let a=at.join(r,i);ee.statSync(a).isDirectory()&&this.scanRealFs(o,s)}}catch{}}async chmod(t,s){ie(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let o=await this.stat(r);if(o.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:s,mtime:new Date})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){ie(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=this.normalizePath(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){ie(t,"link"),ie(s,"link"),this.assertWritable(`link '${s}'`);let r=this.normalizePath(t),n=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let c=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:c,mode:o.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){ie(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ee.promises.readlink(n)}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){ie(t,"realpath");let s=this.normalizePath(t),r=new Set,n=async a=>{let c=a==="/"?[]:a.slice(1).split("/"),u="";for(let l of c){if(u=`${u}/${l}`,r.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,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(u),u=this.resolveSymlink(u,f.target),d++,r.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>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let g=this.toRealPath(u);if(g)try{if((await ee.promises.lstat(g)).isSymbolicLink()){let v=await ee.promises.readlink(g);return r.add(u),u=this.resolveSymlink(u,v),n(u)}}catch(m){throw m.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):m}}}return u||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){ie(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let o=this.memory.get(n);if(o){o.mtime=r;return}let a=await this.stat(n);if(a.isFile){let c=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:c,mode:a.mode,mtime:r})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:a.mode,mtime:r})}};import*as q from"node:fs";import*as ce from"node:path";var rs=class{root;maxFileReadSize;constructor(t){if(this.root=ce.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,!q.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!q.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(t){let s=this.normalizePath(t),r=ce.join(this.root,s);return ce.resolve(r)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Ke(r,n)}async readFileBuffer(t){let s=this.toRealPath(t);try{if(this.maxFileReadSize>0){let n=await q.promises.lstat(s);if(n.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${n.size} bytes, max ${this.maxFileReadSize})`)}let r=await q.promises.readFile(s);return new Uint8Array(r)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):n.code==="EISDIR"?new Error(`EISDIR: illegal operation on a directory, read '${t}'`):r}}async writeFile(t,s,r){let n=this.toRealPath(t),i=be(r),o=De(s,i),a=ce.dirname(n);await q.promises.mkdir(a,{recursive:!0}),await q.promises.writeFile(n,o)}async appendFile(t,s,r){let n=this.toRealPath(t),i=be(r),o=De(s,i),a=ce.dirname(n);await q.promises.mkdir(a,{recursive:!0}),await q.promises.appendFile(n,o)}async exists(t){let s=this.toRealPath(t);try{return await q.promises.access(s),!0}catch{return!1}}async stat(t){let s=this.toRealPath(t);try{let r=await q.promises.stat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:!1,mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):r}}async lstat(t){let s=this.toRealPath(t);try{let r=await q.promises.lstat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:r.isSymbolicLink(),mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):r}}async mkdir(t,s){let r=this.toRealPath(t);try{await q.promises.mkdir(r,{recursive:s?.recursive})}catch(n){let i=n;throw i.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${t}'`):i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${t}'`):n}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){let s=this.toRealPath(t);try{return(await q.promises.readdir(s,{withFileTypes:!0})).map(n=>({name:n.name,isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink()})).sort((n,i)=>n.name<i.name?-1:n.name>i.name?1:0)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${t}'`):n.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${t}'`):r}}async rm(t,s){let r=this.toRealPath(t);try{await q.promises.rm(r,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(n){let i=n;throw i.code==="ENOENT"&&!s?.force?new Error(`ENOENT: no such file or directory, rm '${t}'`):i.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${t}'`):n}}async cp(t,s,r){let n=this.toRealPath(t),i=this.toRealPath(s);try{await q.promises.cp(n,i,{recursive:r?.recursive??!1})}catch(o){let a=o;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${t}'`):a.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${t}'`):o}}async mv(t,s){let r=this.toRealPath(t),n=this.toRealPath(s),i=ce.dirname(n);await q.promises.mkdir(i,{recursive:!0});try{await q.promises.rename(r,n)}catch(o){let a=o;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(a.code==="EXDEV"){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0});return}throw o}}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=[];return this.scanDir("/",t),t}scanDir(t,s){let r=this.toRealPath(t);try{let n=q.readdirSync(r);for(let i of n){let o=t==="/"?`/${i}`:`${t}/${i}`;s.push(o);let a=ce.join(r,i);q.statSync(a).isDirectory()&&this.scanDir(o,s)}}catch{}}async chmod(t,s){let r=this.toRealPath(t);try{await q.promises.chmod(r,s)}catch(n){throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${t}'`):n}}async symlink(t,s){let r=this.toRealPath(s),n=this.normalizePath(s),i=this.normalizePath(ce.dirname(n)),o=t.startsWith("/")?this.normalizePath(t):this.normalizePath(i==="/"?`/${t}`:`${i}/${t}`),a=ce.join(this.root,o),c=ce.dirname(r),u=t.startsWith("/")?a:ce.relative(c,a);try{await q.promises.symlink(u,r)}catch(l){throw l.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${s}'`):l}}async link(t,s){let r=this.toRealPath(t),n=this.toRealPath(s);try{await q.promises.link(r,n)}catch(i){let o=i;throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${t}'`):o.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${s}'`):o.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${t}'`):i}}async readlink(t){let s=this.toRealPath(t);try{return await q.promises.readlink(s)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):n.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):r}}async realpath(t){let s=this.toRealPath(t);try{let r=await q.promises.realpath(s),n=await q.promises.realpath(this.root);if(r.startsWith(n))return r.slice(n.length)||"/";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):n.code==="ELOOP"?new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`):r}}async utimes(t,s,r){let n=this.toRealPath(t);try{await q.promises.utimes(n,s,r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, utimes '${t}'`):i}}};var ct=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;resultPromise;constructor(t,s,r,n,i=!1){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=s,this.env=n,this.explicitCwd=i,this.resultPromise=this.execute()}async execute(){let t=this.env||this.explicitCwd?{cwd:this.explicitCwd?this.cwd:void 0,env:this.env}:void 0,s=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=s.exitCode,s}async*logs(){let t=await this.resultPromise;t.stdout.length>0&&(yield{type:"stdout",data:z(t.stdout),timestamp:new Date}),t.stderr.length>0&&(yield{type:"stderr",data:z(t.stderr),timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return z(t.stdout)+z(t.stderr)}async stdout(){let t=await this.resultPromise;return z(t.stdout)}async stderr(){let t=await this.resultPromise;return z(t.stderr)}async kill(){}};var ns=class e{bashEnv;constructor(t){this.bashEnv=t}static async create(t){let s=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");s=new lt({root:t.overlayRoot})}let r=new $t({env:t?.env,cwd:t?.cwd,fs:s,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network});return new e(r)}async runCommand(t,s){let r=s?.cwd??this.bashEnv.getCwd(),n=s?.cwd!==void 0;return new ct(this.bashEnv,t,r,s?.env,n)}async writeFiles(t){for(let[s,r]of Object.entries(t)){let n;typeof r=="string"?n=r:r.encoding==="base64"?n=Buffer.from(r.content,"base64").toString("utf-8"):n=r.content;let i=s.substring(0,s.lastIndexOf("/"))||"/";i!=="/"&&await this.bashEnv.exec(`mkdir -p ${i}`),await this.bashEnv.writeFile(s,n)}}async readFile(t,s){let r=await this.bashEnv.readFile(t);return s==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,s){let r=s?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${t}`)}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var is=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let s=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(s);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(s),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(s)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[s,r]of this.violationsByType){if(r.length===0)continue;let n=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)n.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:s,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(n)})}return t.sort((s,r)=>r.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function ai(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
684
+ `)}var ss=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new Ie,t?.mounts)for(let{mountPoint:s,filesystem:r}of t.mounts)this.mount(s,r)}mount(t,s){this.validateMountPath(t);let r=this.normalizePath(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(t){let s=this.normalizePath(t);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=this.normalizePath(t);return this.mounts.has(s)}validateMountPath(t){let s=t.split("/");for(let r of s)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let s of this.mounts.keys())if(s!==t){if(t.startsWith(`${s}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${s}'`);if(s.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${s}'`)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`}routePath(t){let s=this.normalizePath(t),r=null,n=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(s===o)return{fs:i.filesystem,relativePath:"/"};s.startsWith(`${o}/`)&&o.length>n&&(r=i,n=o.length)}if(r){let i=s.slice(n);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(t){let s=this.normalizePath(t),r=s==="/"?"/":`${s}/`,n=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!n.includes(a)&&n.push(a)}return n}async readFile(t,s){let{fs:r,relativePath:n}=this.routePath(t);return r.readFile(n,s)}async readFileBuffer(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readFileBuffer(r)}async writeFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.writeFile(i,s,r)}async appendFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.appendFile(i,s,r)}async exists(t){let s=this.normalizePath(t);if(this.mounts.has(s)||this.getChildMountPoints(s).length>0)return!0;let{fs:n,relativePath:i}=this.routePath(t);return n.exists(i)}async stat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.stat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.stat(o)}async lstat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.lstat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.lstat(o)}async mkdir(t,s){let r=this.normalizePath(t);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:i,relativePath:o}=this.routePath(t);return i.mkdir(o,s)}async readdir(t){let s=this.normalizePath(t),r=new Set,n=null,{fs:i,relativePath:o}=this.routePath(t);try{let c=await i.readdir(o);for(let u of c)r.add(u)}catch(c){let u=c.code,l=c.message||"";if(u!=="ENOENT"&&!l.includes("ENOENT"))throw c;n=c}let a=this.getChildMountPoints(s);for(let c of a)r.add(c);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:o}=this.routePath(t);return i.rm(o,s)}async cp(t,s,r){let n=this.routePath(t),i=this.routePath(s);return n.fs===i.fs?n.fs.cp(n.relativePath,i.relativePath,r):this.crossMountCopy(t,s,r)}async mv(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let n=this.routePath(t),i=this.routePath(s);if(n.fs===i.fs)return n.fs.mv(n.relativePath,i.relativePath);await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=new Set;for(let s of this.baseFs.getAllPaths())t.add(s);for(let s of this.mounts.keys()){let r=s.split("/").filter(Boolean),n="";for(let o of r)n=`${n}/${o}`,t.add(n);let i=this.mounts.get(s);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?t.add(s):t.add(`${s}${o}`)}return Array.from(t).sort()}async chmod(t,s){let r=this.normalizePath(t),n=this.mounts.get(r);if(n)return n.filesystem.chmod("/",s);let{fs:i,relativePath:o}=this.routePath(t);return i.chmod(o,s)}async symlink(t,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(t,n)}async link(t,s){let r=this.routePath(t),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readlink(r)}async realpath(t){let s=this.normalizePath(t);if(this.mounts.get(s))return s;let{fs:n,relativePath:i}=this.routePath(t),o=await n.realpath(i);for(let[a,c]of this.mounts)if(s===a||s.startsWith(`${a}/`))return o==="/"?a:`${a}${o}`;return o}async crossMountCopy(t,s,r){let n=await this.lstat(t);if(n.isFile){let i=await this.readFileBuffer(t);await this.writeFile(s,i),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let i=await this.readdir(t);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`,c=s==="/"?`/${o}`:`${s}/${o}`;await this.crossMountCopy(a,c,r)}}else if(n.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,s)}}async utimes(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.utimes(i,s,r)}};import*as ee from"node:fs";import*as at from"node:path";var Xo="/home/user/project";function ie(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var lt=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=at.resolve(t.root);let s=t.mountPoint??Xo;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,!ee.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ee.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 r of t)s+=`/${r}`,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 n=this.normalizePath(t).split("/").filter(Boolean),i="";for(let o of n)i+=`/${o}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=this.normalizePath(t),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let i=s instanceof Uint8Array?s:new TextEncoder().encode(s);this.memory.set(r,{type:"file",content:i,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 r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.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),r=this.getRelativeToMount(s);if(r===null)return null;let n=at.join(this.root,r),i=at.resolve(n);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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 r=this.toRealPath(s);if(!r)return!1;try{return await ee.promises.access(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Ke(r,n)}async readFileBuffer(t,s=new Set){ie(t,"open");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target);return this.readFileBuffer(o,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.content}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let o=await ee.promises.lstat(i);if(o.isSymbolicLink()){let c=await ee.promises.readlink(i),u=this.resolveSymlink(r,c);return this.readFileBuffer(u,s)}if(o.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&o.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${o.size} bytes, max ${this.maxFileReadSize})`);let a=await ee.promises.readFile(i);return new Uint8Array(a)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):o}}async writeFile(t,s,r){ie(t,"write"),this.assertWritable(`write '${t}'`);let n=this.normalizePath(t);this.ensureParentDirs(n);let i=be(r),o=De(s,i);this.memory.set(n,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){ie(t,"append"),this.assertWritable(`append '${t}'`);let n=this.normalizePath(t),i=be(r),o=De(s,i),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let c=new Uint8Array(a.length+o.length);c.set(a),c.set(o,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:c,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){ie(t,"stat");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.stat(a,s)}let o=0;return n.type==="file"&&(o=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:o,mtime:n.mtime}}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await ee.promises.stat(i);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):o}}async lstat(t){ie(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ee.promises.lstat(n);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 r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(t,s){ie(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=this.normalizePath(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(r);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(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let a of this.deleted)if(a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&n.add(u)}for(let[a,c]of this.memory)if(a!==s&&a.startsWith(i)){let u=a.slice(i.length),l=u.split("/")[0];l&&!n.has(l)&&!u.includes("/",1)&&r.set(l,{name:l,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}let o=this.toRealPath(s);if(o)try{let a=await ee.promises.readdir(o,{withFileTypes:!0});for(let c of a)!n.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async resolveForReaddir(t,s=!1){let r=this.normalizePath(t),n=new Set,i=s,o=this.memory.get(r);for(;o&&o.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,o.target),o=this.memory.get(r)}if(o)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let c=this.toRealPath(r);if(!c)return{normalized:r,outsideOverlay:!0};try{if((await ee.promises.lstat(c)).isSymbolicLink()){let l=await ee.promises.readlink(c),f=this.resolveSymlink(r,l);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){ie(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){ie(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,s){ie(t,"rm"),this.assertWritable(`rm '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let o=await this.readdir(r);if(o.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of o){let c=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(c,s)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(t,s,r){ie(t,"cp"),ie(s,"cp"),this.assertWritable(`cp '${s}'`);let n=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let a=await this.stat(n);if(a.isFile){let c=await this.readFileBuffer(n);await this.writeFile(i,c)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let c=await this.readdir(n);for(let u of c){let l=n==="/"?`/${u}`:`${n}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(l,f,r)}}}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 r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}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 r=this.toRealPath(t);if(r)try{let n=ee.readdirSync(r);for(let i of n){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(o))continue;s.add(o);let a=at.join(r,i);ee.statSync(a).isDirectory()&&this.scanRealFs(o,s)}}catch{}}async chmod(t,s){ie(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let o=await this.stat(r);if(o.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:s,mtime:new Date})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){ie(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=this.normalizePath(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){ie(t,"link"),ie(s,"link"),this.assertWritable(`link '${s}'`);let r=this.normalizePath(t),n=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let c=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:c,mode:o.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){ie(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ee.promises.readlink(n)}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){ie(t,"realpath");let s=this.normalizePath(t),r=new Set,n=async a=>{let c=a==="/"?[]:a.slice(1).split("/"),u="";for(let l of c){if(u=`${u}/${l}`,r.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,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(u),u=this.resolveSymlink(u,f.target),d++,r.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>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let g=this.toRealPath(u);if(g)try{if((await ee.promises.lstat(g)).isSymbolicLink()){let v=await ee.promises.readlink(g);return r.add(u),u=this.resolveSymlink(u,v),n(u)}}catch(m){throw m.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):m}}}return u||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){ie(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let o=this.memory.get(n);if(o){o.mtime=r;return}let a=await this.stat(n);if(a.isFile){let c=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:c,mode:a.mode,mtime:r})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:a.mode,mtime:r})}};import*as q from"node:fs";import*as ce from"node:path";var rs=class{root;maxFileReadSize;constructor(t){if(this.root=ce.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,!q.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!q.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(t){let s=this.normalizePath(t),r=ce.join(this.root,s);return ce.resolve(r)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Ke(r,n)}async readFileBuffer(t){let s=this.toRealPath(t);try{if(this.maxFileReadSize>0){let n=await q.promises.lstat(s);if(n.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${n.size} bytes, max ${this.maxFileReadSize})`)}let r=await q.promises.readFile(s);return new Uint8Array(r)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):n.code==="EISDIR"?new Error(`EISDIR: illegal operation on a directory, read '${t}'`):r}}async writeFile(t,s,r){let n=this.toRealPath(t),i=be(r),o=De(s,i),a=ce.dirname(n);await q.promises.mkdir(a,{recursive:!0}),await q.promises.writeFile(n,o)}async appendFile(t,s,r){let n=this.toRealPath(t),i=be(r),o=De(s,i),a=ce.dirname(n);await q.promises.mkdir(a,{recursive:!0}),await q.promises.appendFile(n,o)}async exists(t){let s=this.toRealPath(t);try{return await q.promises.access(s),!0}catch{return!1}}async stat(t){let s=this.toRealPath(t);try{let r=await q.promises.stat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:!1,mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):r}}async lstat(t){let s=this.toRealPath(t);try{let r=await q.promises.lstat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:r.isSymbolicLink(),mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):r}}async mkdir(t,s){let r=this.toRealPath(t);try{await q.promises.mkdir(r,{recursive:s?.recursive})}catch(n){let i=n;throw i.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${t}'`):i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${t}'`):n}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){let s=this.toRealPath(t);try{return(await q.promises.readdir(s,{withFileTypes:!0})).map(n=>({name:n.name,isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink()})).sort((n,i)=>n.name<i.name?-1:n.name>i.name?1:0)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${t}'`):n.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${t}'`):r}}async rm(t,s){let r=this.toRealPath(t);try{await q.promises.rm(r,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(n){let i=n;throw i.code==="ENOENT"&&!s?.force?new Error(`ENOENT: no such file or directory, rm '${t}'`):i.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${t}'`):n}}async cp(t,s,r){let n=this.toRealPath(t),i=this.toRealPath(s);try{await q.promises.cp(n,i,{recursive:r?.recursive??!1})}catch(o){let a=o;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${t}'`):a.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${t}'`):o}}async mv(t,s){let r=this.toRealPath(t),n=this.toRealPath(s),i=ce.dirname(n);await q.promises.mkdir(i,{recursive:!0});try{await q.promises.rename(r,n)}catch(o){let a=o;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(a.code==="EXDEV"){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0});return}throw o}}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=[];return this.scanDir("/",t),t}scanDir(t,s){let r=this.toRealPath(t);try{let n=q.readdirSync(r);for(let i of n){let o=t==="/"?`/${i}`:`${t}/${i}`;s.push(o);let a=ce.join(r,i);q.statSync(a).isDirectory()&&this.scanDir(o,s)}}catch{}}async chmod(t,s){let r=this.toRealPath(t);try{await q.promises.chmod(r,s)}catch(n){throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${t}'`):n}}async symlink(t,s){let r=this.toRealPath(s),n=this.normalizePath(s),i=this.normalizePath(ce.dirname(n)),o=t.startsWith("/")?this.normalizePath(t):this.normalizePath(i==="/"?`/${t}`:`${i}/${t}`),a=ce.join(this.root,o),c=ce.dirname(r),u=t.startsWith("/")?a:ce.relative(c,a);try{await q.promises.symlink(u,r)}catch(l){throw l.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${s}'`):l}}async link(t,s){let r=this.toRealPath(t),n=this.toRealPath(s);try{await q.promises.link(r,n)}catch(i){let o=i;throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${t}'`):o.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${s}'`):o.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${t}'`):i}}async readlink(t){let s=this.toRealPath(t);try{return await q.promises.readlink(s)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):n.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):r}}async realpath(t){let s=this.toRealPath(t);try{let r=await q.promises.realpath(s),n=await q.promises.realpath(this.root);if(r.startsWith(n))return r.slice(n.length)||"/";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):n.code==="ELOOP"?new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`):r}}async utimes(t,s,r){let n=this.toRealPath(t);try{await q.promises.utimes(n,s,r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, utimes '${t}'`):i}}};var ct=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;resultPromise;constructor(t,s,r,n,i=!1){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=s,this.env=n,this.explicitCwd=i,this.resultPromise=this.execute()}async execute(){let t=this.env||this.explicitCwd?{cwd:this.explicitCwd?this.cwd:void 0,env:this.env}:void 0,s=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=s.exitCode,s}async*logs(){let t=await this.resultPromise;t.stdout.length>0&&(yield{type:"stdout",data:z(t.stdout),timestamp:new Date}),t.stderr.length>0&&(yield{type:"stderr",data:z(t.stderr),timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return z(t.stdout)+z(t.stderr)}async stdout(){let t=await this.resultPromise;return z(t.stdout)}async stderr(){let t=await this.resultPromise;return z(t.stderr)}async kill(){}};var ns=class e{bashEnv;constructor(t){this.bashEnv=t}static async create(t){let s=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");s=new lt({root:t.overlayRoot})}let r=new $t({env:t?.env,cwd:t?.cwd,fs:s,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network});return new e(r)}async runCommand(t,s){let r=s?.cwd??this.bashEnv.getCwd(),n=s?.cwd!==void 0;return new ct(this.bashEnv,t,r,s?.env,n)}async writeFiles(t){for(let[s,r]of Object.entries(t)){let n;typeof r=="string"?n=r:r.encoding==="base64"?n=Buffer.from(r.content,"base64").toString("utf-8"):n=r.content;let i=s.substring(0,s.lastIndexOf("/"))||"/";i!=="/"&&await this.bashEnv.exec(`mkdir -p ${i}`),await this.bashEnv.writeFile(s,n)}}async readFile(t,s){let r=await this.bashEnv.readFile(t);return s==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,s){let r=s?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${t}`)}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var is=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let s=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(s);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(s),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(s)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[s,r]of this.violationsByType){if(r.length===0)continue;let n=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)n.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:s,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(n)})}return t.sort((s,r)=>r.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function li(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
685
685
  Type: ${e.type}`,`
686
686
  Path: ${e.path}`,`
687
687
  Message: ${e.message}`,e.executionId?`
688
- ExecutionId: ${e.executionId}`:"")}}export{$t as Bash,ot as DefenseInDepthBox,p as EMPTY,Ie as InMemoryFs,ss as MountableFs,rt as NetworkAccessDeniedError,lt as OverlayFs,rs as ReadWriteFs,it as RedirectNotAllowedError,ns as Sandbox,ct as SandboxCommand,ne as SecurityViolationError,is as SecurityViolationLogger,nt as TooManyRedirectsError,ai as createConsoleViolationCallback,z as decode,pi as defineCommand,E as encode,fi as getCommandNames,di as getNetworkCommandNames,hi as getPythonCommandNames};
688
+ ExecutionId: ${e.executionId}`:"")}}export{$t as Bash,ot as DefenseInDepthBox,p as EMPTY,Ie as InMemoryFs,ss as MountableFs,rt as NetworkAccessDeniedError,lt as OverlayFs,rs as ReadWriteFs,it as RedirectNotAllowedError,ns as Sandbox,ct as SandboxCommand,ne as SecurityViolationError,is as SecurityViolationLogger,nt as TooManyRedirectsError,li as createConsoleViolationCallback,z as decode,mi as defineCommand,E as encode,di as getCommandNames,hi as getNetworkCommandNames,pi as getPythonCommandNames};