just-bash 2.11.11 → 2.11.13

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.
@@ -21,7 +21,7 @@ import{B as Er,C as Sr,D as ue,E as ze,F as Q,G as $e,H as St,I as Ar,J as D,K a
21
21
  `,1);try{let a=await e.fs.stat(i);if(a.isDirectory)return C("",`bash: ${n}: Is a directory
22
22
  `,1);if(e.state.options.noclobber&&!o&&!a.isDirectory&&n!=="/dev/null")return C("",`bash: ${n}: cannot overwrite existing file
23
23
  `,1)}catch{}if(n!=="/dev/null"&&n!=="/dev/stdout"&&n!=="/dev/stderr"&&n!=="/dev/full"&&await e.fs.writeFile(i,"","binary"),n==="/dev/full")return C("",`bash: /dev/full: No space left on device
24
- `,1)}return null}async function U(e,t,s,r){let{stdout:n,stderr:i,exitCode:o}=t;for(let c=0;c<s.length;c++){let u=s[c];if(u.target.type==="HereDoc")continue;let f,d=r?.get(c);if(d!==void 0)f=d;else if(u.operator===">&"||u.operator==="<&"){if(os(e,u.target)){i+=`bash: $@: ambiguous redirect
24
+ `,1)}return null}async function H(e,t,s,r){let{stdout:n,stderr:i,exitCode:o}=t;for(let c=0;c<s.length;c++){let u=s[c];if(u.target.type==="HereDoc")continue;let f,d=r?.get(c);if(d!==void 0)f=d;else if(u.operator===">&"||u.operator==="<&"){if(os(e,u.target)){i+=`bash: $@: ambiguous redirect
25
25
  `,o=1,n="";continue}f=await D(e,u.target)}else{let m=await At(e,u.target);if("error"in m){i+=m.error,o=1,n="";continue}f=m.target}if(!u.fdVariable){if(f.includes("\0")){i+=`bash: ${f.replace(/\0/g,"")}: No such file or directory
26
26
  `,o=1,n="";continue}switch(u.operator){case">":case">|":{let h=u.fd??1,m=u.operator===">|";if(h===1){if(f==="/dev/stdout")break;if(f==="/dev/stderr"){i+=n,n="";break}if(f==="/dev/full"){i+=`bash: echo: write error: No space left on device
27
27
  `,o=1,n="";break}let p=e.fs.resolvePath(e.state.cwd,f),g=await Ve(e,p,f,{checkNoclobber:!0,isClobber:m});if(g){i+=g,o=1,n="";break}await e.fs.writeFile(p,n,J(n)),n=""}else if(h===2){if(f==="/dev/stderr")break;if(f==="/dev/stdout"){n+=i,i="";break}if(f==="/dev/full"){i+=`bash: echo: write error: No space left on device
@@ -36,7 +36,7 @@ import{B as Er,C as Sr,D as ue,E as ze,F as Q,G as $e,H as St,I as Ar,J as D,K a
36
36
  `;throw new z(2,"",r)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),L}async function Bi(e,t){let s="";for(let r of t)if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let n=r.target,i=await D(e,n.content);n.stripTabs&&(i=i.split(`
37
37
  `).map(a=>a.replace(/^\t+/,"")).join(`
38
38
  `)),(r.fd??0)===0&&(s=i)}else if(r.operator==="<<<"&&r.target.type==="Word")s=`${await D(e,r.target)}
39
- `;else if(r.operator==="<"&&r.target.type==="Word"){let n=await D(e,r.target),i=e.fs.resolvePath(e.state.cwd,n);try{s=await e.fs.readFile(i)}catch{}}return s}async function Vt(e,t,s,r="",n){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Oe(`${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 c=0;c<s.length;c++)i.set(String(c+1),e.state.env.get(String(c+1))),e.state.env.set(String(c+1),s[c]);i.set("@",e.state.env.get("@")),i.set("#",e.state.env.get("#")),e.state.env.set("@",s.join(" ")),e.state.env.set("#",String(s.length));let o=()=>{let c=e.state.localScopes.length-1,u=e.state.localScopes.pop();if(u)for(let[f,d]of u)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);if(Jr(e,c),e.state.fullyUnsetLocals)for(let[f,d]of e.state.fullyUnsetLocals.entries())d===c&&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):e.state.env.set(f,d);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:a,error:l}=await tn(e,t.redirections);if(l)return o(),C("",l,1);try{let c=await Bi(e,t.redirections),u=r||c,f=await e.executeCommand(t.body,u);return o(),U(e,f,t.redirections,a)}catch(c){if(o(),c instanceof ce){let u=C(c.stdout,c.stderr,c.exitCode);return U(e,u,t.redirections,a)}throw c}}var nn=["!","[[","]]","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"],ji=["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"],Ui=$s;async function Es(e,t){let s=[],r=null,n="",i="",o=null,a=!1,l=!1,c=!1,u=null,f=null,d=null,h=[],m=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let y=0;y<t.length;y++){let w=t[y];if(w==="-v")s.push("variable");else if(w==="-e")s.push("export");else if(w==="-f")s.push("file");else if(w==="-d")s.push("directory");else if(w==="-k")s.push("keyword");else if(w==="-A"){if(y++,y>=t.length)return _(`compgen: -A: option requires an argument
39
+ `;else if(r.operator==="<"&&r.target.type==="Word"){let n=await D(e,r.target),i=e.fs.resolvePath(e.state.cwd,n);try{s=await e.fs.readFile(i)}catch{}}return s}async function Vt(e,t,s,r="",n){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Oe(`${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 c=0;c<s.length;c++)i.set(String(c+1),e.state.env.get(String(c+1))),e.state.env.set(String(c+1),s[c]);i.set("@",e.state.env.get("@")),i.set("#",e.state.env.get("#")),e.state.env.set("@",s.join(" ")),e.state.env.set("#",String(s.length));let o=()=>{let c=e.state.localScopes.length-1,u=e.state.localScopes.pop();if(u)for(let[f,d]of u)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);if(Jr(e,c),e.state.fullyUnsetLocals)for(let[f,d]of e.state.fullyUnsetLocals.entries())d===c&&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):e.state.env.set(f,d);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:a,error:l}=await tn(e,t.redirections);if(l)return o(),C("",l,1);try{let c=await Bi(e,t.redirections),u=r||c,f=await e.executeCommand(t.body,u);return o(),H(e,f,t.redirections,a)}catch(c){if(o(),c instanceof ce){let u=C(c.stdout,c.stderr,c.exitCode);return H(e,u,t.redirections,a)}throw c}}var nn=["!","[[","]]","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"],ji=["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"],Ui=$s;async function Es(e,t){let s=[],r=null,n="",i="",o=null,a=!1,l=!1,c=!1,u=null,f=null,d=null,h=[],m=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let y=0;y<t.length;y++){let w=t[y];if(w==="-v")s.push("variable");else if(w==="-e")s.push("export");else if(w==="-f")s.push("file");else if(w==="-d")s.push("directory");else if(w==="-k")s.push("keyword");else if(w==="-A"){if(y++,y>=t.length)return _(`compgen: -A: option requires an argument
40
40
  `,2);let b=t[y];if(!m.includes(b))return _(`compgen: ${b}: invalid action name
41
41
  `,2);s.push(b)}else if(w==="-W"){if(y++,y>=t.length)return _(`compgen: -W: option requires an argument
42
42
  `,2);r=t[y]}else if(w==="-P"){if(y++,y>=t.length)return _(`compgen: -P: option requires an argument
@@ -76,7 +76,7 @@ import{B as Er,C as Sr,D as ue,E as ze,F as Q,G as $e,H as St,I as Ar,J as D,K a
76
76
  `,2);i.push(c)}else if(l==="--"){o.push(...t.slice(a+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&o.push(l)}if(s){let a=e.state.completionSpecs.get("__default__")??{isDefault:!0},l=new Set(a.options??[]);for(let c of n)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__default__",a),F("")}if(r){let a=e.state.completionSpecs.get("__empty__")??{},l=new Set(a.options??[]);for(let c of n)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__empty__",a),F("")}if(o.length>0){for(let a of o){let l=e.state.completionSpecs.get(a)??{},c=new Set(l.options??[]);for(let u of n)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set(a,l)}return F("")}return _(`compopt: not currently executing completion function
77
77
  `,1)}function Ps(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new xe;return L}if(t.length>1)throw new z(1,"",`bash: continue: too many arguments
78
78
  `);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new z(1,"",`bash: continue: ${t[0]}: numeric argument required
79
- `);s=r}throw new he(s)}function H(e,t){let s=e.state.env.get("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 Cs(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function ks(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 Bt(e){return Cs(e)?ks(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Be(e){return Cs(e)?ks(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Ns(e){return Cs(e)?ks(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function an(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),me(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 Os(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function ln(e,t){let s="",r="",n=!1;for(let i of t){let o=an(e,i);if(e.state.associativeArrays?.has(i)){let u=De(e,i);if(u.length===0)s+=`declare -A ${i}=()
79
+ `);s=r}throw new he(s)}function q(e,t){let s=e.state.env.get("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 Cs(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function ks(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 Bt(e){return Cs(e)?ks(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Be(e){return Cs(e)?ks(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Ns(e){return Cs(e)?ks(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function an(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),me(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 Os(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function ln(e,t){let s="",r="",n=!1;for(let i of t){let o=an(e,i);if(e.state.associativeArrays?.has(i)){let u=De(e,i);if(u.length===0)s+=`declare -A ${i}=()
80
80
  `;else{let f=u.map(d=>{let h=e.state.env.get(`${i}_${d}`)??"",m=Os(h);return`['${d}']=${m}`});s+=`declare -A ${i}=(${f.join(" ")})
81
81
  `}continue}let l=ee(e,i);if(l.length>0){let u=l.map(f=>{let d=e.state.env.get(`${i}_${f}`)??"";return`[${f}]=${Be(d)}`});s+=`declare -a ${i}=(${u.join(" ")})
82
82
  `;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=()
@@ -103,12 +103,12 @@ import{B as Er,C as Sr,D as ue,E as ze,F as Q,G as $e,H as St,I as Ar,J as D,K a
103
103
  }
104
104
  `;return F(I)}let N=!0;for(let I of S)e.state.functions.has(I)||(N=!1);return C("","",N?0:1)}if(o&&S.length>0)return ln(e,S);if(o&&S.length===0)return cn(e,{filterExport:i,filterReadonly:n,filterNameref:a,filterIndexedArray:s,filterAssocArray:r});if(S.length===0&&r&&!o)return un(e);if(S.length===0&&s&&!o)return fn(e);if(S.length===0&&!o)return dn(e);let $="",T=0;for(let N of S){let I=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(I&&!c){let E=I[1],x=I[2];if(r&&ee(e,E).length>0){$+=`bash: declare: ${E}: cannot convert indexed to associative array
105
105
  `,T=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has(E)){$+=`bash: declare: ${E}: cannot convert associative to indexed array
106
- `,T=1;continue}if(w(E),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(E)),Ae(e,E),e.state.env.delete(E),e.state.env.delete(`${E}__length`),r&&x.includes("[")){let R=Ft(x);for(let[X,M]of R){let q=H(e,M);e.state.env.set(`${E}_${X}`,q)}}else if(r){let R=Pe(x);for(let X=0;X<R.length;X+=2){let M=R[X],q=X+1<R.length?H(e,R[X+1]):"";e.state.env.set(`${E}_${M}`,q)}}else{let R=Pe(x);if(R.some(M=>/^\[[^\]]+\]=/.test(M))){let M=0;for(let q of R){let re=q.match(/^\[([^\]]+)\]=(.*)$/);if(re){let fe=re[1],He=re[2],hi=H(e,He),rt;if(/^-?\d+$/.test(fe))rt=Number.parseInt(fe,10);else try{let pi=new W,mi=K(pi,fe);rt=await V(e,mi.expression)}catch{rt=0}e.state.env.set(`${E}_${rt}`,hi),M=rt+1}else{let fe=H(e,q);e.state.env.set(`${E}_${M}`,fe),M++}}}else{for(let M=0;M<R.length;M++)e.state.env.set(`${E}_${M}`,R[M]);e.state.env.set(`${E}__length`,String(R.length))}}b(E),n&&ue(e,E),i&&$e(e,E);continue}if(l){let E=N.includes("=")?N.slice(0,N.indexOf("=")):N;if(wr(e,E),!N.includes("="))continue}if(u){let E=N.includes("=")?N.slice(0,N.indexOf("=")):N;if(St(e,E),!N.includes("="))continue}let P=ao(N);if(P){let{name:E,indexExpr:x,value:R}=P,X=Q(e,E);if(X)return X;w(E);let M;try{let re=new W,fe=K(re,x);M=await V(e,fe.expression)}catch{let re=parseInt(x,10);M=Number.isNaN(re)?0:re}e.state.env.set(`${E}_${M}`,R);let q=parseInt(e.state.env.get(`${E}__length`)??"0",10);M>=q&&e.state.env.set(`${E}__length`,String(M+1)),b(E),n&&ue(e,E),i&&$e(e,E);continue}let k=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(k&&!c){let E=k[1],x=k[2],R=Q(e,E);if(R)return R;w(E);let X=Pe(x);if(e.state.associativeArrays?.has(E)){let M=Ft(x);for(let[q,re]of M){let fe=H(e,re);e.state.env.set(`${E}_${q}`,fe)}}else{let M=ee(e,E),q=0,re=e.state.env.get(E);M.length===0&&re!==void 0?(e.state.env.set(`${E}_0`,re),e.state.env.delete(E),q=1):M.length>0&&(q=Math.max(...M)+1);for(let He=0;He<X.length;He++)e.state.env.set(`${E}_${q+He}`,H(e,X[He]));let fe=q+X.length;e.state.env.set(`${E}__length`,String(fe))}b(E),n&&ue(e,E),i&&$e(e,E);continue}let O=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(O){let E=O[1],x=H(e,O[2]),R=Q(e,E);if(R)return R;y(E),f&&xs(e,E),d&&Ts(e,E),h&&Ds(e,E);let M=ee(e,E).length>0||e.state.associativeArrays?.has(E);if(lt(e,E)){let q=e.state.env.get(E)??"0",re=parseInt(q,10)||0,fe=parseInt(await hn(e,x),10)||0;x=String(re+fe),e.state.env.set(E,x)}else if(M){x=et(e,E,x);let q=`${E}_0`,re=e.state.env.get(q)??"";e.state.env.set(q,re+x)}else{x=et(e,E,x);let q=e.state.env.get(E)??"";e.state.env.set(E,q+x)}b(E),n&&ue(e,E),i&&$e(e,E),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(E));continue}if(N.includes("=")){let E=N.indexOf("="),x=N.slice(0,E),R=N.slice(E+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(x)){$+=`bash: typeset: \`${x}': not a valid identifier
106
+ `,T=1;continue}if(w(E),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(E)),Ae(e,E),e.state.env.delete(E),e.state.env.delete(`${E}__length`),r&&x.includes("[")){let R=Ft(x);for(let[X,M]of R){let Z=q(e,M);e.state.env.set(`${E}_${X}`,Z)}}else if(r){let R=Pe(x);for(let X=0;X<R.length;X+=2){let M=R[X],Z=X+1<R.length?q(e,R[X+1]):"";e.state.env.set(`${E}_${M}`,Z)}}else{let R=Pe(x);if(R.some(M=>/^\[[^\]]+\]=/.test(M))){let M=0;for(let Z of R){let re=Z.match(/^\[([^\]]+)\]=(.*)$/);if(re){let fe=re[1],He=re[2],hi=q(e,He),rt;if(/^-?\d+$/.test(fe))rt=Number.parseInt(fe,10);else try{let pi=new W,mi=K(pi,fe);rt=await V(e,mi.expression)}catch{rt=0}e.state.env.set(`${E}_${rt}`,hi),M=rt+1}else{let fe=q(e,Z);e.state.env.set(`${E}_${M}`,fe),M++}}}else{for(let M=0;M<R.length;M++)e.state.env.set(`${E}_${M}`,R[M]);e.state.env.set(`${E}__length`,String(R.length))}}b(E),n&&ue(e,E),i&&$e(e,E);continue}if(l){let E=N.includes("=")?N.slice(0,N.indexOf("=")):N;if(wr(e,E),!N.includes("="))continue}if(u){let E=N.includes("=")?N.slice(0,N.indexOf("=")):N;if(St(e,E),!N.includes("="))continue}let P=ao(N);if(P){let{name:E,indexExpr:x,value:R}=P,X=Q(e,E);if(X)return X;w(E);let M;try{let re=new W,fe=K(re,x);M=await V(e,fe.expression)}catch{let re=parseInt(x,10);M=Number.isNaN(re)?0:re}e.state.env.set(`${E}_${M}`,R);let Z=parseInt(e.state.env.get(`${E}__length`)??"0",10);M>=Z&&e.state.env.set(`${E}__length`,String(M+1)),b(E),n&&ue(e,E),i&&$e(e,E);continue}let k=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(k&&!c){let E=k[1],x=k[2],R=Q(e,E);if(R)return R;w(E);let X=Pe(x);if(e.state.associativeArrays?.has(E)){let M=Ft(x);for(let[Z,re]of M){let fe=q(e,re);e.state.env.set(`${E}_${Z}`,fe)}}else{let M=ee(e,E),Z=0,re=e.state.env.get(E);M.length===0&&re!==void 0?(e.state.env.set(`${E}_0`,re),e.state.env.delete(E),Z=1):M.length>0&&(Z=Math.max(...M)+1);for(let He=0;He<X.length;He++)e.state.env.set(`${E}_${Z+He}`,q(e,X[He]));let fe=Z+X.length;e.state.env.set(`${E}__length`,String(fe))}b(E),n&&ue(e,E),i&&$e(e,E);continue}let O=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(O){let E=O[1],x=q(e,O[2]),R=Q(e,E);if(R)return R;y(E),f&&xs(e,E),d&&Ts(e,E),h&&Ds(e,E);let M=ee(e,E).length>0||e.state.associativeArrays?.has(E);if(lt(e,E)){let Z=e.state.env.get(E)??"0",re=parseInt(Z,10)||0,fe=parseInt(await hn(e,x),10)||0;x=String(re+fe),e.state.env.set(E,x)}else if(M){x=et(e,E,x);let Z=`${E}_0`,re=e.state.env.get(Z)??"";e.state.env.set(Z,re+x)}else{x=et(e,E,x);let Z=e.state.env.get(E)??"";e.state.env.set(E,Z+x)}b(E),n&&ue(e,E),i&&$e(e,E),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(E));continue}if(N.includes("=")){let E=N.indexOf("="),x=N.slice(0,E),R=N.slice(E+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(x)){$+=`bash: typeset: \`${x}': not a valid identifier
107
107
  `,T=1;continue}let X=Q(e,x);if(X)return X;if(y(x),a){if(R!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(R)){$+=`bash: declare: \`${R}': invalid variable name for name reference
108
108
  `,T=1;continue}e.state.env.set(x,R),Ne(e,x),R!==""&&ns(e,R)&&rs(e,x),b(x),n&&ue(e,x),i&&$e(e,x);continue}if(f&&xs(e,x),d&&Ts(e,x),h&&Ds(e,x),lt(e,x)&&(R=await hn(e,R)),R=et(e,x,R),me(e,x)){let M=Ie(e,x);M&&M!==x?e.state.env.set(M,R):e.state.env.set(x,R)}else e.state.env.set(x,R);b(x),n&&ue(e,x),i&&$e(e,x),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(x))}else{let E=N;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)){$+=`bash: typeset: \`${E}': not a valid identifier
109
109
  `,T=1;continue}if(s||r?w(E):y(E),a){Ne(e,E);let R=e.state.env.get(E);R!==void 0&&R!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(R)?vr(e,E):R&&ns(e,R)&&rs(e,E),b(E),n&&ue(e,E),i&&$e(e,E);continue}if(f&&xs(e,E),d&&Ts(e,E),h&&Ds(e,E),r){if(ee(e,E).length>0){$+=`bash: declare: ${E}: cannot convert indexed to associative array
110
110
  `,T=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(E)}let x=Array.from(e.state.env.keys()).some(R=>R.startsWith(`${E}_`)&&!R.startsWith(`${E}__length`));!e.state.env.has(E)&&!x&&(s||r?e.state.env.set(`${E}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(E))),b(E),n&&ue(e,E),i&&$e(e,E)}}return C("",$,T)}async function Rs(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 l of a){let c=e.state.env.get(l);if(c!==void 0){let u=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"');o+=`declare -r ${l}="${u}"
111
- `}}return F(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=Q(e,f);if(h)return h;let m=Pe(d);if(e.state.associativeArrays?.has(f)){let p=Ft(d);for(let[g,S]of p){let v=H(e,S);e.state.env.set(`${f}_${g}`,v)}}else{let p=ee(e,f),g=0,S=e.state.env.get(f);p.length===0&&S!==void 0?(e.state.env.set(`${f}_0`,S),e.state.env.delete(f),g=1):p.length>0&&(g=Math.max(...p)+1);for(let A=0;A<m.length;A++)e.state.env.set(`${f}_${g+A}`,H(e,m[A]));let v=g+m.length;e.state.env.set(`${f}__length`,String(v))}ue(e,f);continue}let l=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=H(e,l[2]),h=Q(e,f);if(h)return h;let m=e.state.env.get(f)??"";e.state.env.set(f,m+d),ue(e,f);continue}let c=Xr(o);if(c.value===void 0&&!c.isArray){ue(e,c.name);continue}let u=await Yr(e,c,{makeReadonly:!0});if(u)return u}return L}function Ls(e){return e.state.directoryStack??=[],e.state.directoryStack}function ct(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function lo(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 Fs(e,t){let s=Ls(e),r;for(let a=0;a<t.length;a++){let l=t[a];if(l==="--"){if(a+1<t.length){if(r!==void 0)return _(`bash: pushd: too many arguments
111
+ `}}return F(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=Q(e,f);if(h)return h;let m=Pe(d);if(e.state.associativeArrays?.has(f)){let p=Ft(d);for(let[g,S]of p){let v=q(e,S);e.state.env.set(`${f}_${g}`,v)}}else{let p=ee(e,f),g=0,S=e.state.env.get(f);p.length===0&&S!==void 0?(e.state.env.set(`${f}_0`,S),e.state.env.delete(f),g=1):p.length>0&&(g=Math.max(...p)+1);for(let A=0;A<m.length;A++)e.state.env.set(`${f}_${g+A}`,q(e,m[A]));let v=g+m.length;e.state.env.set(`${f}__length`,String(v))}ue(e,f);continue}let l=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=q(e,l[2]),h=Q(e,f);if(h)return h;let m=e.state.env.get(f)??"";e.state.env.set(f,m+d),ue(e,f);continue}let c=Xr(o);if(c.value===void 0&&!c.isArray){ue(e,c.name);continue}let u=await Yr(e,c,{makeReadonly:!0});if(u)return u}return L}function Ls(e){return e.state.directoryStack??=[],e.state.directoryStack}function ct(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function lo(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 Fs(e,t){let s=Ls(e),r;for(let a=0;a<t.length;a++){let l=t[a];if(l==="--"){if(a+1<t.length){if(r!==void 0)return _(`bash: pushd: too many arguments
112
112
  `,2);r=t[a+1],a++}}else{if(l.startsWith("-")&&l!=="-")return _(`bash: pushd: ${l}: invalid option
113
113
  `,2);if(r!==void 0)return _(`bash: pushd: too many arguments
114
114
  `,2);r=l}}if(r===void 0){if(s.length<2)return _(`bash: pushd: no other directory
@@ -132,7 +132,7 @@ eval: usage: eval [arg ...]
132
132
  `,2)}if(r.length===0)return L;let n=r.join(" ");if(n.trim()==="")return L;let i=e.state.groupStdin,o=s??e.state.groupStdin;o!==void 0&&(e.state.groupStdin=o);try{let a=ve(n);return await e.executeScript(a)}catch(a){if(a instanceof de||a instanceof he||a instanceof ce||a instanceof z)throw a;if(a.name==="ParseException")return _(`bash: eval: ${a.message}
133
133
  `);throw a}finally{e.state.groupStdin=i}}function zs(e,t){let s,r="";if(t.length===0)s=e.state.lastExitCode;else{let n=t[0],i=Number.parseInt(n,10);n===""||Number.isNaN(i)||!/^-?\d+$/.test(n)?(r=`bash: exit: ${n}: numeric argument required
134
134
  `,s=2):s=(i%256+256)%256}throw new z(s,"",r)}function Vs(e,t){let s=!1,r=[];for(let o of t)o==="-n"?s=!0:o==="-p"||o==="--"||r.push(o);if(r.length===0&&!s){let o="",a=e.state.exportedVars??new Set,l=Array.from(a).sort();for(let c of l){let u=e.state.env.get(c);if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');o+=`declare -x ${c}="${f}"
135
- `}}return F(o)}if(s){for(let o of r){let a,l;if(o.includes("=")){let c=o.indexOf("=");a=o.slice(0,c),l=H(e,o.slice(c+1)),e.state.env.set(a,l)}else a=o;St(e,a)}return L}let n="",i=0;for(let o of r){let a,l,c=!1,u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)a=u[1],l=H(e,u[2]),c=!0;else if(o.includes("=")){let f=o.indexOf("=");a=o.slice(0,f),l=H(e,o.slice(f+1))}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){n+=`bash: export: \`${o}': not a valid identifier
135
+ `}}return F(o)}if(s){for(let o of r){let a,l;if(o.includes("=")){let c=o.indexOf("=");a=o.slice(0,c),l=q(e,o.slice(c+1)),e.state.env.set(a,l)}else a=o;St(e,a)}return L}let n="",i=0;for(let o of r){let a,l,c=!1,u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)a=u[1],l=q(e,u[2]),c=!0;else if(o.includes("=")){let f=o.indexOf("=");a=o.slice(0,f),l=q(e,o.slice(f+1))}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){n+=`bash: export: \`${o}': not a valid identifier
136
136
  `,i=1;continue}if(l!==void 0)if(c){let f=e.state.env.get(a)??"";e.state.env.set(a,f+l)}else e.state.env.set(a,l);else e.state.env.has(a)||e.state.env.set(a,"");$e(e,a)}return C("",n,i)}function Ut(e,t){if(t.length<2)return _(`bash: getopts: usage: getopts optstring name [arg ...]
137
137
  `);let s=t[0],r=t[1],n=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=s.startsWith(":"),o=i?s.slice(1):s,a;if(t.length>2)a=t.slice(2);else{let p=Number.parseInt(e.state.env.get("#")||"0",10);a=[];for(let g=1;g<=p;g++)a.push(e.state.env.get(String(g))||"")}let l=Number.parseInt(e.state.env.get("OPTIND")||"1",10);l<1&&(l=1);let c=Number.parseInt(e.state.env.get("__GETOPTS_CHARINDEX")||"0",10);if(e.state.env.set("OPTARG",""),l>a.length)return n||e.state.env.set(r,"?"),e.state.env.set("OPTIND",String(a.length+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:n?2:1,stdout:"",stderr:""};let u=a[l-1];if(!u||u==="-"||!u.startsWith("-"))return n||e.state.env.set(r,"?"),{exitCode:n?2:1,stdout:"",stderr:""};if(u==="--")return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),n||e.state.env.set(r,"?"),{exitCode:n?2:1,stdout:"",stderr:""};let f=c===0?1:c,d=u[f];if(!d)return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),Ut(e,t);let h=o.indexOf(d);if(h===-1){let p="";return i?e.state.env.set("OPTARG",d):p=`bash: illegal option -- ${d}
138
138
  `,n||e.state.env.set(r,"?"),f+1<u.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(l))):(e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0")),{exitCode:n?2:0,stdout:"",stderr:p}}if(h+1<o.length&&o[h+1]===":")if(f+1<u.length)e.state.env.set("OPTARG",u.slice(f+1)),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0");else{if(l>=a.length){let p="";return i?(e.state.env.set("OPTARG",d),n||e.state.env.set(r,":")):(p=`bash: option requires an argument -- ${d}
@@ -509,7 +509,7 @@ ${h}
509
509
  `)}return C("","",r===0?1:0)}async function Hs(e,t){if(e.state.localScopes.length===0)return _(`bash: local: can only be used in a function
510
510
  `);let s=e.state.localScopes[e.state.localScopes.length-1],r="",n=0,i=!1,o=!1,a=!1,l=[];for(let c of t)if(c==="-n")i=!0;else if(c==="-a")o=!0;else if(c==="-p")a=!0;else if(c.startsWith("-")&&!c.includes("="))for(let u of c.slice(1))u==="n"?i=!0:u==="a"?o=!0:u==="p"&&(a=!0);else l.push(c);if(l.length===0){let c="",u=Array.from(s.keys()).filter(f=>!f.includes("_")||!f.match(/_\d+$/)).filter(f=>!f.includes("__length")).sort();for(let f of u){let d=e.state.env.get(f);d!==void 0&&(c+=`${f}=${d}
511
511
  `)}return C(c,"",0)}for(let c of l){let u,f,d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(d){u=d[1];let S=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \`${c}': not a valid identifier
512
- `,n=1;continue}if(Q(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let y=`${u}_`;for(let w of e.state.env.keys())w.startsWith(y)&&!w.includes("__")&&(s.has(w)||s.set(w,e.state.env.get(w)))}let v=`${u}_`;for(let y of e.state.env.keys())y.startsWith(v)&&!y.includes("__")&&e.state.env.delete(y);let A=Pe(S);for(let y=0;y<A.length;y++)e.state.env.set(`${u}_${y}`,A[y]);e.state.env.set(`${u}__length`,String(A.length)),Fe(e,u),i&&Ne(e,u);continue}let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(h){u=h[1];let S=h[2];if(Q(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let $=`${u}_`;for(let N of e.state.env.keys())N.startsWith($)&&!N.includes("__")&&(s.has(N)||s.set(N,e.state.env.get(N)));let T=`${u}__length`;e.state.env.has(T)&&!s.has(T)&&s.set(T,e.state.env.get(T))}let v=Pe(S),A=ee(e,u),y=0,w=e.state.env.get(u);A.length===0&&w!==void 0?(e.state.env.set(`${u}_0`,w),e.state.env.delete(u),y=1):A.length>0&&(y=Math.max(...A)+1);for(let $=0;$<v.length;$++)e.state.env.set(`${u}_${y+$}`,H(e,v[$]));let b=y+v.length;e.state.env.set(`${u}__length`,String(b)),Fe(e,u),i&&Ne(e,u);continue}let m=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){u=m[1];let S=H(e,m[2]);Q(e,u,"bash"),s.has(u)||s.set(u,e.state.env.get(u));let v=e.state.env.get(u)??"";e.state.env.set(u,v+S),Fe(e,u),i&&Ne(e,u);continue}let p=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(p){u=p[1];let S=p[2],v=H(e,p[3]);if(Q(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let w=`${u}_`;for(let $ of e.state.env.keys())$.startsWith(w)&&!$.includes("__")&&(s.has($)||s.set($,e.state.env.get($)));let b=`${u}__length`;e.state.env.has(b)&&!s.has(b)&&s.set(b,e.state.env.get(b))}let A;try{let w=new W,b=K(w,S);A=await V(e,b.expression)}catch{let w=parseInt(S,10);A=Number.isNaN(w)?0:w}e.state.env.set(`${u}_${A}`,v);let y=parseInt(e.state.env.get(`${u}__length`)??"0",10);A>=y&&e.state.env.set(`${u}__length`,String(A+1)),Fe(e,u),i&&Ne(e,u);continue}if(c.includes("=")){let S=c.indexOf("=");u=c.slice(0,S),f=H(e,c.slice(S+1))}else u=c;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \`${c}': not a valid identifier
512
+ `,n=1;continue}if(Q(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let y=`${u}_`;for(let w of e.state.env.keys())w.startsWith(y)&&!w.includes("__")&&(s.has(w)||s.set(w,e.state.env.get(w)))}let v=`${u}_`;for(let y of e.state.env.keys())y.startsWith(v)&&!y.includes("__")&&e.state.env.delete(y);let A=Pe(S);for(let y=0;y<A.length;y++)e.state.env.set(`${u}_${y}`,A[y]);e.state.env.set(`${u}__length`,String(A.length)),Fe(e,u),i&&Ne(e,u);continue}let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(h){u=h[1];let S=h[2];if(Q(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let $=`${u}_`;for(let N of e.state.env.keys())N.startsWith($)&&!N.includes("__")&&(s.has(N)||s.set(N,e.state.env.get(N)));let T=`${u}__length`;e.state.env.has(T)&&!s.has(T)&&s.set(T,e.state.env.get(T))}let v=Pe(S),A=ee(e,u),y=0,w=e.state.env.get(u);A.length===0&&w!==void 0?(e.state.env.set(`${u}_0`,w),e.state.env.delete(u),y=1):A.length>0&&(y=Math.max(...A)+1);for(let $=0;$<v.length;$++)e.state.env.set(`${u}_${y+$}`,q(e,v[$]));let b=y+v.length;e.state.env.set(`${u}__length`,String(b)),Fe(e,u),i&&Ne(e,u);continue}let m=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){u=m[1];let S=q(e,m[2]);Q(e,u,"bash"),s.has(u)||s.set(u,e.state.env.get(u));let v=e.state.env.get(u)??"";e.state.env.set(u,v+S),Fe(e,u),i&&Ne(e,u);continue}let p=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(p){u=p[1];let S=p[2],v=q(e,p[3]);if(Q(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let w=`${u}_`;for(let $ of e.state.env.keys())$.startsWith(w)&&!$.includes("__")&&(s.has($)||s.set($,e.state.env.get($)));let b=`${u}__length`;e.state.env.has(b)&&!s.has(b)&&s.set(b,e.state.env.get(b))}let A;try{let w=new W,b=K(w,S);A=await V(e,b.expression)}catch{let w=parseInt(S,10);A=Number.isNaN(w)?0:w}e.state.env.set(`${u}_${A}`,v);let y=parseInt(e.state.env.get(`${u}__length`)??"0",10);A>=y&&e.state.env.set(`${u}__length`,String(A+1)),Fe(e,u),i&&Ne(e,u);continue}if(c.includes("=")){let S=c.indexOf("=");u=c.slice(0,S),f=q(e,c.slice(S+1))}else u=c;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \`${c}': not a valid identifier
513
513
  `,n=1;continue}let g=s.has(u);if(f!==void 0){let S=e.state.env.get(u);if(e.state.tempEnvBindings){let v=e.state.accessedTempEnvVars?.has(u),A=e.state.mutatedTempEnvVars?.has(u);if(!v&&!A)for(let y=e.state.tempEnvBindings.length-1;y>=0;y--){let w=e.state.tempEnvBindings[y];if(w.has(u)){S=w.get(u);break}}}Qr(e,u,S)}if(!g){let S=e.state.env.get(u);if(e.state.tempEnvBindings)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let A=e.state.tempEnvBindings[v];if(A.has(u)){S=A.get(u);break}}if(s.set(u,S),o){let v=`${u}_`;for(let y of e.state.env.keys())y.startsWith(v)&&!y.includes("__")&&(s.has(y)||s.set(y,e.state.env.get(y)));let A=`${u}__length`;e.state.env.has(A)&&!s.has(A)&&s.set(A,e.state.env.get(A))}}if(o&&f===void 0){let S=`${u}_`;for(let v of e.state.env.keys())v.startsWith(S)&&!v.includes("__")&&e.state.env.delete(v);e.state.env.set(`${u}__length`,"0")}else if(f!==void 0){if(Q(e,u,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){r+=`bash: local: \`${f}': invalid variable name for name reference
514
514
  `,n=1;continue}e.state.env.set(u,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(u))}else{let S=e.state.tempEnvBindings?.some(v=>v.has(u));!g&&!S&&e.state.env.delete(u)}Fe(e,u),i&&Ne(e,u)}return C("",r,n)}function qs(e,t,s){let r=`
515
515
  `,n=0,i=0,o=0,a=!1,l="MAPFILE",c=0;for(;c<t.length;){let v=t[c];v==="-d"&&c+1<t.length?(r=t[c+1]===""?"\0":t[c+1]||`
@@ -625,11 +625,11 @@ ${e} ()
625
625
  `)}}async function sr(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let r="",n="",i=0;try{for(let o of t){let a=await e.executeStatement(o);r+=a.stdout,n+=a.stderr,i=a.exitCode}}finally{e.state.inCondition=s}return{stdout:r,stderr:n,exitCode:i}}function ft(e,t,s,r){if(e instanceof de)return t+=e.stdout,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 he)return t+=e.stdout,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 ce||e instanceof pe||e instanceof z||e instanceof ne)return e.prependOutput(t,s),{action:"rethrow",stdout:t,stderr:s,error:e};let n=ke(e);return{action:"error",stdout:t,stderr:`${s}${n}
626
626
  `,exitCode:1}}async function Gt(e,t,s="",r=""){let n=s,i=r,o=0;try{for(let a of t){let l=await e.executeStatement(a);n+=l.stdout,i+=l.stderr,o=l.exitCode}}catch(a){if(bt(a)||a instanceof pe||a instanceof z||a instanceof ne||a instanceof xe)throw a.prependOutput(n,i),a;return{stdout:n,stderr:`${i}${ke(a)}
627
627
  `,exitCode:1}}return{stdout:n,stderr:i,exitCode:o}}async function Rn(e,t){let s="",r="";for(let n of t.clauses){let i=await sr(e,n.condition);if(s+=i.stdout,r+=i.stderr,i.exitCode===0)return Gt(e,n.body,s,r)}return t.elseBody?Gt(e,t.elseBody,s,r):C(s,r,0)}async function Ln(e,t){let s=await Ce(e,t.redirections);if(s)return s;let r="",n="",i=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return _(`bash: \`${t.variable}': not a valid identifier
628
- `);let a=[];if(t.words===null)a=(e.state.env.get("@")||"").split(" ").filter(Boolean);else if(t.words.length===0)a=[];else try{for(let c of t.words){let u=await _e(e,c);a.push(...u.values)}}catch(c){if(c instanceof vt)return{stdout:"",stderr:c.stderr,exitCode:1};throw c}e.state.loopDepth++;try{for(let c of a){o++,o>e.limits.maxLoopIterations&&Oe(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),e.state.env.set(t.variable,c);try{for(let u of t.body){let f=await e.executeStatement(u);r+=f.stdout,n+=f.stderr,i=f.exitCode}}catch(u){let f=ft(u,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=C(r,n,f.exitCode??1);return U(e,d,t.redirections)}throw f.error}}}finally{e.state.loopDepth--}let l=C(r,n,i);return U(e,l,t.redirections)}async function Fn(e,t){let s=await Ce(e,t.redirections);if(s)return s;let r=t.line;r!==void 0&&(e.state.currentLine=r);let n="",i="",o=0,a=0;t.init&&await V(e,t.init.expression),e.state.loopDepth++;try{for(;a++,a>e.limits.maxLoopIterations&&Oe(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,i),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await V(e,t.condition.expression)===0));){try{for(let c of t.body){let u=await e.executeStatement(c);n+=u.stdout,i+=u.stderr,o=u.exitCode}}catch(c){let u=ft(c,n,i,e.state.loopDepth);if(n=u.stdout,i=u.stderr,u.action==="break")break;if(u.action==="continue"){t.update&&await V(e,t.update.expression);continue}if(u.action==="error"){let f=C(n,i,u.exitCode??1);return U(e,f,t.redirections)}throw u.error}t.update&&await V(e,t.update.expression)}}finally{e.state.loopDepth--}let l=C(n,i,o);return U(e,l,t.redirections)}async function Mn(e,t,s=""){let r="",n="",i=0,o=0,a=s;for(let c of t.redirections)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let u=c.target,f=await D(e,u.content);u.stripTabs&&(f=f.split(`
628
+ `);let a=[];if(t.words===null)a=(e.state.env.get("@")||"").split(" ").filter(Boolean);else if(t.words.length===0)a=[];else try{for(let c of t.words){let u=await _e(e,c);a.push(...u.values)}}catch(c){if(c instanceof vt)return{stdout:"",stderr:c.stderr,exitCode:1};throw c}e.state.loopDepth++;try{for(let c of a){o++,o>e.limits.maxLoopIterations&&Oe(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),e.state.env.set(t.variable,c);try{for(let u of t.body){let f=await e.executeStatement(u);r+=f.stdout,n+=f.stderr,i=f.exitCode}}catch(u){let f=ft(u,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=C(r,n,f.exitCode??1);return H(e,d,t.redirections)}throw f.error}}}finally{e.state.loopDepth--}let l=C(r,n,i);return H(e,l,t.redirections)}async function Fn(e,t){let s=await Ce(e,t.redirections);if(s)return s;let r=t.line;r!==void 0&&(e.state.currentLine=r);let n="",i="",o=0,a=0;t.init&&await V(e,t.init.expression),e.state.loopDepth++;try{for(;a++,a>e.limits.maxLoopIterations&&Oe(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,i),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await V(e,t.condition.expression)===0));){try{for(let c of t.body){let u=await e.executeStatement(c);n+=u.stdout,i+=u.stderr,o=u.exitCode}}catch(c){let u=ft(c,n,i,e.state.loopDepth);if(n=u.stdout,i=u.stderr,u.action==="break")break;if(u.action==="continue"){t.update&&await V(e,t.update.expression);continue}if(u.action==="error"){let f=C(n,i,u.exitCode??1);return H(e,f,t.redirections)}throw u.error}t.update&&await V(e,t.update.expression)}}finally{e.state.loopDepth--}let l=C(n,i,o);return H(e,l,t.redirections)}async function Mn(e,t,s=""){let r="",n="",i=0,o=0,a=s;for(let c of t.redirections)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let u=c.target,f=await D(e,u.content);u.stripTabs&&(f=f.split(`
629
629
  `).map(d=>d.replace(/^\t+/,"")).join(`
630
630
  `)),a=f}else if(c.operator==="<<<"&&c.target.type==="Word")a=`${await D(e,c.target)}
631
631
  `;else if(c.operator==="<"&&c.target.type==="Word")try{let u=await D(e,c.target),f=e.fs.resolvePath(e.state.cwd,u);a=await e.fs.readFile(f)}catch{let u=await D(e,c.target);return _(`bash: ${u}: No such file or directory
632
- `)}let l=e.state.groupStdin;a&&(e.state.groupStdin=a),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&Oe(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let c=0,u=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let h of t.condition){let m=await e.executeStatement(h);r+=m.stdout,n+=m.stderr,c=m.exitCode}}catch(h){if(h instanceof de){if(r+=h.stdout,n+=h.stderr,h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;u=!0}else if(h instanceof he){if(r+=h.stdout,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(u)break;if(!f){if(c!==0)break;try{for(let h of t.body){let m=await e.executeStatement(h);r+=m.stdout,n+=m.stderr,i=m.exitCode}}catch(h){let m=ft(h,r,n,e.state.loopDepth);if(r=m.stdout,n=m.stderr,m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return C(r,n,m.exitCode??1);throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return C(r,n,i)}async function Wn(e,t){let s="",r="",n=0,i=0;e.state.loopDepth++;try{for(;;){i++,i>e.limits.maxLoopIterations&&Oe(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r);let o=await sr(e,t.condition);if(s+=o.stdout,r+=o.stderr,o.exitCode===0)break;try{for(let a of t.body){let l=await e.executeStatement(a);s+=l.stdout,r+=l.stderr,n=l.exitCode}}catch(a){let l=ft(a,s,r,e.state.loopDepth);if(s=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return C(s,r,l.exitCode??1);throw l.error}}}finally{e.state.loopDepth--}return C(s,r,n)}async function zn(e,t){let s=await Ce(e,t.redirections);if(s)return s;let r="",n="",i=0,o=await D(e,t.word),a=!1;for(let c=0;c<t.items.length;c++){let u=t.items[c],f=a;if(!a)for(let d of u.patterns){let h=await D(e,d);Ar(d)&&(h=Er(h));let m=e.state.shoptOptions.nocasematch,p=e.state.shoptOptions.extglob;if(Xe(o,h,m,p)){f=!0;break}}if(f){let d=await Gt(e,u.body,r,n);if(r=d.stdout,n=d.stderr,i=d.exitCode,u.terminator===";;")break;u.terminator===";&"?a=!0:a=!1}else a=!1}let l=C(r,n,i);return U(e,l,t.redirections)}function rr(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function Vn(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),l=a.indexOf(":");if(l===-1)return null;let c=Number.parseInt(a.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=a.slice(l+1);return{path:i,position:c,content:u}}var Bn="+ ";async function jn(e){let t=e.state.env.get("PS4");if(t===void 0)return Bn;if(t==="")return"";try{let r=new W().parseWordFromString(t,!1,!1);return await D(e,r)}catch{return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${t}: bad substitution
632
+ `)}let l=e.state.groupStdin;a&&(e.state.groupStdin=a),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&Oe(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let c=0,u=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let h of t.condition){let m=await e.executeStatement(h);r+=m.stdout,n+=m.stderr,c=m.exitCode}}catch(h){if(h instanceof de){if(r+=h.stdout,n+=h.stderr,h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;u=!0}else if(h instanceof he){if(r+=h.stdout,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(u)break;if(!f){if(c!==0)break;try{for(let h of t.body){let m=await e.executeStatement(h);r+=m.stdout,n+=m.stderr,i=m.exitCode}}catch(h){let m=ft(h,r,n,e.state.loopDepth);if(r=m.stdout,n=m.stderr,m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return C(r,n,m.exitCode??1);throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return C(r,n,i)}async function Wn(e,t){let s="",r="",n=0,i=0;e.state.loopDepth++;try{for(;;){i++,i>e.limits.maxLoopIterations&&Oe(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r);let o=await sr(e,t.condition);if(s+=o.stdout,r+=o.stderr,o.exitCode===0)break;try{for(let a of t.body){let l=await e.executeStatement(a);s+=l.stdout,r+=l.stderr,n=l.exitCode}}catch(a){let l=ft(a,s,r,e.state.loopDepth);if(s=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return C(s,r,l.exitCode??1);throw l.error}}}finally{e.state.loopDepth--}return C(s,r,n)}async function zn(e,t){let s=await Ce(e,t.redirections);if(s)return s;let r="",n="",i=0,o=await D(e,t.word),a=!1;for(let c=0;c<t.items.length;c++){let u=t.items[c],f=a;if(!a)for(let d of u.patterns){let h=await D(e,d);Ar(d)&&(h=Er(h));let m=e.state.shoptOptions.nocasematch,p=e.state.shoptOptions.extglob;if(Xe(o,h,m,p)){f=!0;break}}if(f){let d=await Gt(e,u.body,r,n);if(r=d.stdout,n=d.stderr,i=d.exitCode,u.terminator===";;")break;u.terminator===";&"?a=!0:a=!1}else a=!1}let l=C(r,n,i);return H(e,l,t.redirections)}function rr(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function Vn(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),l=a.indexOf(":");if(l===-1)return null;let c=Number.parseInt(a.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=a.slice(l+1);return{path:i,position:c,content:u}}var Bn="+ ";async function jn(e){let t=e.state.env.get("PS4");if(t===void 0)return Bn;if(t==="")return"";try{let r=new W().parseWordFromString(t,!1,!1);return await D(e,r)}catch{return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${t}: bad substitution
633
633
  `,t||Bn}}function ko(e){return e.map(t=>No(t)).join(" ")}function No(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
634
634
  `),n=e.includes(" "),i=e.includes("\\"),o=e.includes("'");if(s||r||n||i){let l="";for(let c of e){let u=c.charCodeAt(0);c===`
635
635
  `?l+="\\n":c===" "?l+="\\t":c==="\\"?l+="\\\\":c==="'"?l+="'":c==='"'?l+='"':u<32||u===127?u<256?l+=`\\x${u.toString(16).padStart(2,"0")}`:l+=`\\u${u.toString(16).padStart(4,"0")}`:l+=c}return`$'${l}'`}return o?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function Un(e,t,s){if(!e.state.options.xtrace)return"";let r=await jn(e),n=[t,...s],i=ko(n);return`${r}${i}
@@ -645,32 +645,32 @@ sys 0m0.000s
645
645
  `,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let u=await Ro(e,t,l[1],l[2],o,n.append,s);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:u.error};if(u.continueToNext)continue}let c=await Fo(e,t,i,o,n.append,s);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:s}}async function Oo(e,t,s,r,n,i){let o="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:C("",`bash: ${s}: cannot assign list to array member
646
646
  `,1)};if(me(e,s)){let u=br(e,s);if(u===void 0||u==="")throw new z(1,"","");let f=Ie(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:C("",`bash: ${s}: cannot assign list to array member
647
647
  `,1)}}if(ze(e,s)){if(t.name)return o+=`bash: ${s}: readonly variable
648
- `,{continueToNext:!0,xtraceOutput:o};let u=Q(e,s);if(u)return{continueToNext:!1,xtraceOutput:"",error:u}}let a=e.state.associativeArrays?.has(s),l=xo(r),c=()=>{let u=`${s}_`;for(let f of e.state.env.keys())f.startsWith(u)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(a&&l?await To(e,t,s,r,n,c,u=>{o+=u}):l?await Do(e,s,r,n,c):await Io(e,s,r,n,c),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>Et(d)).join(" ")})`;e.state.env.set(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 To(e,t,s,r,n,i,o){let a=[];for(let l of r){let c=ts(l);if(c){let{key:u,valueParts:f,append:d}=c,h;f.length>0?h=await D(e,{type:"Word",parts:f}):h="",h=H(e,h),a.push({type:"keyed",key:u,value:h,append:d})}else{let u=await D(e,l);a.push({type:"invalid",expandedValue:u})}}n||i();for(let l of a)if(l.type==="keyed")if(l.append){let c=e.state.env.get(`${s}_${l.key}`)??"";e.state.env.set(`${s}_${l.key}`,c+l.value)}else e.state.env.set(`${s}_${l.key}`,l.value);else{let c=t.line??e.state.currentLine??1;o(`bash: line ${c}: ${s}: ${l.expandedValue}: must use subscript when assigning associative array
649
- `)}}async function Do(e,t,s,r,n){let i=[];for(let a of s){let l=ts(a);if(l){let{key:c,valueParts:u,append:f}=l,d;u.length>0?d=await D(e,{type:"Word",parts:u}):d="",d=H(e,d),i.push({type:"keyed",indexExpr:c,value:d,append:f})}else{let c=await _e(e,a);i.push({type:"non-keyed",values:c.values})}}r||n();let o=0;for(let a of i)if(a.type==="keyed"){let l;try{let c=new W,u=K(c,a.indexExpr);l=await V(e,u.expression,!1)}catch{if(/^-?\d+$/.test(a.indexExpr))l=Number.parseInt(a.indexExpr,10);else{let c=e.state.env.get(a.indexExpr);l=c?Number.parseInt(c,10):0,Number.isNaN(l)&&(l=0)}}if(a.append){let c=e.state.env.get(`${t}_${l}`)??"";e.state.env.set(`${t}_${l}`,c+a.value)}else e.state.env.set(`${t}_${l}`,a.value);o=l+1}else for(let l of a.values)e.state.env.set(`${t}_${o++}`,l)}async function Io(e,t,s,r,n){let i=[];for(let a of s){let l=await _e(e,a);i.push(...l.values)}let o=0;if(r){let a=be(e,t);if(a.length>0)o=Math.max(...a.map(([c])=>typeof c=="number"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(e.state.env.set(`${t}_0`,l),e.state.env.delete(t),o=1)}}else n();for(let a=0;a<i.length;a++)e.state.env.set(`${t}_${o+a}`,i[a]);r||e.state.env.set(`${t}__length`,String(i.length))}async function Ro(e,t,s,r,n,i,o){let a=s;if(me(e,s)){let f=Ie(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:C("",`bash: \`${f}': not a valid identifier
648
+ `,{continueToNext:!0,xtraceOutput:o};let u=Q(e,s);if(u)return{continueToNext:!1,xtraceOutput:"",error:u}}let a=e.state.associativeArrays?.has(s),l=xo(r),c=()=>{let u=`${s}_`;for(let f of e.state.env.keys())f.startsWith(u)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(a&&l?await To(e,t,s,r,n,c,u=>{o+=u}):l?await Do(e,s,r,n,c):await Io(e,s,r,n,c),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>Et(d)).join(" ")})`;e.state.env.set(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 To(e,t,s,r,n,i,o){let a=[];for(let l of r){let c=ts(l);if(c){let{key:u,valueParts:f,append:d}=c,h;f.length>0?h=await D(e,{type:"Word",parts:f}):h="",h=q(e,h),a.push({type:"keyed",key:u,value:h,append:d})}else{let u=await D(e,l);a.push({type:"invalid",expandedValue:u})}}n||i();for(let l of a)if(l.type==="keyed")if(l.append){let c=e.state.env.get(`${s}_${l.key}`)??"";e.state.env.set(`${s}_${l.key}`,c+l.value)}else e.state.env.set(`${s}_${l.key}`,l.value);else{let c=t.line??e.state.currentLine??1;o(`bash: line ${c}: ${s}: ${l.expandedValue}: must use subscript when assigning associative array
649
+ `)}}async function Do(e,t,s,r,n){let i=[];for(let a of s){let l=ts(a);if(l){let{key:c,valueParts:u,append:f}=l,d;u.length>0?d=await D(e,{type:"Word",parts:u}):d="",d=q(e,d),i.push({type:"keyed",indexExpr:c,value:d,append:f})}else{let c=await _e(e,a);i.push({type:"non-keyed",values:c.values})}}r||n();let o=0;for(let a of i)if(a.type==="keyed"){let l;try{let c=new W,u=K(c,a.indexExpr);l=await V(e,u.expression,!1)}catch{if(/^-?\d+$/.test(a.indexExpr))l=Number.parseInt(a.indexExpr,10);else{let c=e.state.env.get(a.indexExpr);l=c?Number.parseInt(c,10):0,Number.isNaN(l)&&(l=0)}}if(a.append){let c=e.state.env.get(`${t}_${l}`)??"";e.state.env.set(`${t}_${l}`,c+a.value)}else e.state.env.set(`${t}_${l}`,a.value);o=l+1}else for(let l of a.values)e.state.env.set(`${t}_${o++}`,l)}async function Io(e,t,s,r,n){let i=[];for(let a of s){let l=await _e(e,a);i.push(...l.values)}let o=0;if(r){let a=be(e,t);if(a.length>0)o=Math.max(...a.map(([c])=>typeof c=="number"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(e.state.env.set(`${t}_0`,l),e.state.env.delete(t),o=1)}}else n();for(let a=0;a<i.length;a++)e.state.env.set(`${t}_${o+a}`,i[a]);r||e.state.env.set(`${t}__length`,String(i.length))}async function Ro(e,t,s,r,n,i,o){let a=s;if(me(e,s)){let f=Ie(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:C("",`bash: \`${f}': not a valid identifier
650
650
  `,1)};a=f}}if(ze(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=Q(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(a),c;if(l)c=await Gn(e,a,r);else{let f=await Lo(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};c=`${a}_${f.index}`}let u=i?(e.state.env.get(c)||"")+n:n;if(t.name)o.set(c,e.state.env.get(c)),e.state.env.set(c,u);else{let f=Ye(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(c)||d.set(c,e.state.env.get(c))}e.state.env.set(c,u)}return{continueToNext:!0,xtraceOutput:""}}async function Gn(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 W().parseWordFromString(n,!0,!1);r=await D(e,o)}else if(s.includes("$")){let i=new W().parseWordFromString(s,!1,!1);r=await D(e,i)}else r=s;return`${t}_${r}`}async function Lo(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 W,o=K(i,r);n=await V(e,o.expression,!1)}catch(i){if(i instanceof We){let l=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
651
651
  `;if(i.fatal)throw new z(1,"",l);return{index:0,error:C("",l,1)}}let o=e.state.env.get(s);n=o?Number.parseInt(o,10):0}Number.isNaN(n)&&(n=0)}if(n<0){let i=be(e,t);if(i.length===0){let a=e.state.currentLine;return{index:0,error:C("",`bash: line ${a}: ${t}[${s}]: bad array subscript
652
652
  `,1)}}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:C("",`bash: line ${a}: ${t}[${s}]: bad array subscript
653
653
  `,1)}}}return{index:n}}async function Fo(e,t,s,r,n,i){let o="",a=s,l=null;if(me(e,s)){let f=$r(e,s,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:"",error:C("",`bash: ${s}: circular name reference
654
654
  `,1)};if(f===null)return{continueToNext:!0,xtraceOutput:""};a=f;let d=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);d&&(l={arrayName:d[1],subscriptExpr:d[2]},a=d[1])}if(ze(e,a)){if(t.name)return o+=`bash: ${a}: readonly variable
655
- `,{continueToNext:!0,xtraceOutput:o};let f=Q(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let c;if(lt(e,a))try{let f=new W;if(n){let h=`(${e.state.env.get(a)||"0"}) + (${r})`,m=K(f,h);c=String(await V(e,m.expression))}else{let d=K(f,r);c=String(await V(e,d.expression))}}catch{c="0"}else{let{isArray:f}=await import("./chunks/expansion-AMH5BAVV.js"),d=f(e,a)?`${a}_0`:a;c=n?(e.state.env.get(d)||"")+r:r}c=et(e,a,c),o+=await Hn(e,a,c);let u=a;if(l)u=await Mo(e,l);else{let{isArray:f}=await import("./chunks/expansion-AMH5BAVV.js");f(e,a)&&(u=`${a}_0`)}return t.name?(i.set(u,e.state.env.get(u)),e.state.env.set(u,c)):(e.state.env.set(u,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(a)),e.state.tempEnvBindings?.some(f=>f.has(a))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(a))),{continueToNext:!1,xtraceOutput:o}}async function Mo(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return Gn(e,s,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new W,a=K(o,r);i=await V(e,a.expression,!1)}catch{let o=e.state.env.get(r);i=o?Number.parseInt(o,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let o=be(e,s);o.length>0&&(i=Math.max(...o.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function Kn(e,t,s,r){let n=await Ce(e,t.redirections);if(n)return n;let i=new Map(e.state.env),o=e.state.cwd,a={...e.state.options},l=new Map(e.state.functions),c=e.state.localScopes,u=e.state.localVarStack,f=e.state.localVarDepth,d=e.state.fullyUnsetLocals;if(e.state.localScopes=c.map($=>new Map($)),u){e.state.localVarStack=new Map;for(let[$,T]of u.entries())e.state.localVarStack.set($,T.map(N=>({...N})))}f&&(e.state.localVarDepth=new Map(f)),d&&(e.state.fullyUnsetLocals=new Map(d));let h=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let p=e.state.lastArg,g=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let S=e.state.groupStdin;s&&(e.state.groupStdin=s);let v="",A="",y=0,w=()=>{e.state.env=i,e.state.cwd=o,e.state.options=a,e.state.functions=l,e.state.localScopes=c,e.state.localVarStack=u,e.state.localVarDepth=f,e.state.fullyUnsetLocals=d,e.state.loopDepth=h,e.state.parentHasLoopContext=m,e.state.groupStdin=S,e.state.bashPid=g,e.state.lastArg=p};try{for(let $ of t.body){let T=await r($);v+=T.stdout,A+=T.stderr,y=T.exitCode}}catch($){if(w(),$ instanceof ne)throw $;if($ instanceof xe){v+=$.stdout,A+=$.stderr;let N=C(v,A,0);return U(e,N,t.redirections)}if($ instanceof de||$ instanceof he){v+=$.stdout,A+=$.stderr;let N=C(v,A,0);return U(e,N,t.redirections)}if($ instanceof z){v+=$.stdout,A+=$.stderr;let N=C(v,A,$.exitCode);return U(e,N,t.redirections)}if($ instanceof ce){v+=$.stdout,A+=$.stderr;let N=C(v,A,$.exitCode);return U(e,N,t.redirections)}if($ instanceof pe){let N=C(v+$.stdout,A+$.stderr,$.exitCode);return U(e,N,t.redirections)}let T=C(v,`${A}${ke($)}
656
- `,1);return U(e,T,t.redirections)}w();let b=C(v,A,y);return U(e,b,t.redirections)}async function Xn(e,t,s,r){let n="",i="",o=0,a=await zt(e,t.redirections);if(a)return a;let l=s;for(let f of t.redirections)if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,h=await D(e,d.content);d.stripTabs&&(h=h.split(`
655
+ `,{continueToNext:!0,xtraceOutput:o};let f=Q(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let c;if(lt(e,a))try{let f=new W;if(n){let h=`(${e.state.env.get(a)||"0"}) + (${r})`,m=K(f,h);c=String(await V(e,m.expression))}else{let d=K(f,r);c=String(await V(e,d.expression))}}catch{c="0"}else{let{isArray:f}=await import("./chunks/expansion-AMH5BAVV.js"),d=f(e,a)?`${a}_0`:a;c=n?(e.state.env.get(d)||"")+r:r}c=et(e,a,c),o+=await Hn(e,a,c);let u=a;if(l)u=await Mo(e,l);else{let{isArray:f}=await import("./chunks/expansion-AMH5BAVV.js");f(e,a)&&(u=`${a}_0`)}return t.name?(i.set(u,e.state.env.get(u)),e.state.env.set(u,c)):(e.state.env.set(u,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(a)),e.state.tempEnvBindings?.some(f=>f.has(a))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(a))),{continueToNext:!1,xtraceOutput:o}}async function Mo(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return Gn(e,s,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new W,a=K(o,r);i=await V(e,a.expression,!1)}catch{let o=e.state.env.get(r);i=o?Number.parseInt(o,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let o=be(e,s);o.length>0&&(i=Math.max(...o.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function Kn(e,t,s,r){let n=await Ce(e,t.redirections);if(n)return n;let i=new Map(e.state.env),o=e.state.cwd,a={...e.state.options},l=new Map(e.state.functions),c=e.state.localScopes,u=e.state.localVarStack,f=e.state.localVarDepth,d=e.state.fullyUnsetLocals;if(e.state.localScopes=c.map($=>new Map($)),u){e.state.localVarStack=new Map;for(let[$,T]of u.entries())e.state.localVarStack.set($,T.map(N=>({...N})))}f&&(e.state.localVarDepth=new Map(f)),d&&(e.state.fullyUnsetLocals=new Map(d));let h=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let p=e.state.lastArg,g=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let S=e.state.groupStdin;s&&(e.state.groupStdin=s);let v="",A="",y=0,w=()=>{e.state.env=i,e.state.cwd=o,e.state.options=a,e.state.functions=l,e.state.localScopes=c,e.state.localVarStack=u,e.state.localVarDepth=f,e.state.fullyUnsetLocals=d,e.state.loopDepth=h,e.state.parentHasLoopContext=m,e.state.groupStdin=S,e.state.bashPid=g,e.state.lastArg=p};try{for(let $ of t.body){let T=await r($);v+=T.stdout,A+=T.stderr,y=T.exitCode}}catch($){if(w(),$ instanceof ne)throw $;if($ instanceof xe){v+=$.stdout,A+=$.stderr;let N=C(v,A,0);return H(e,N,t.redirections)}if($ instanceof de||$ instanceof he){v+=$.stdout,A+=$.stderr;let N=C(v,A,0);return H(e,N,t.redirections)}if($ instanceof z){v+=$.stdout,A+=$.stderr;let N=C(v,A,$.exitCode);return H(e,N,t.redirections)}if($ instanceof ce){v+=$.stdout,A+=$.stderr;let N=C(v,A,$.exitCode);return H(e,N,t.redirections)}if($ instanceof pe){let N=C(v+$.stdout,A+$.stderr,$.exitCode);return H(e,N,t.redirections)}let T=C(v,`${A}${ke($)}
656
+ `,1);return H(e,T,t.redirections)}w();let b=C(v,A,y);return H(e,b,t.redirections)}async function Xn(e,t,s,r){let n="",i="",o=0,a=await zt(e,t.redirections);if(a)return a;let l=s;for(let f of t.redirections)if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,h=await D(e,d.content);d.stripTabs&&(h=h.split(`
657
657
  `).map(p=>p.replace(/^\t+/,"")).join(`
658
658
  `));let m=f.fd??0;m!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(m,h)):l=h}else if(f.operator==="<<<"&&f.target.type==="Word")l=`${await D(e,f.target)}
659
659
  `;else if(f.operator==="<"&&f.target.type==="Word")try{let d=await D(e,f.target),h=e.fs.resolvePath(e.state.cwd,d);l=await e.fs.readFile(h)}catch{let d=await D(e,f.target);return C("",`bash: ${d}: No such file or directory
660
660
  `,1)}let c=e.state.groupStdin;l&&(e.state.groupStdin=l);try{for(let f of t.body){let d=await r(f);n+=d.stdout,i+=d.stderr,o=d.exitCode}}catch(f){if(e.state.groupStdin=c,f instanceof ne)throw f;if(bt(f)||f instanceof pe||f instanceof z)throw f.prependOutput(n,i),f;return C(n,`${i}${ke(f)}
661
- `,1)}e.state.groupStdin=c;let u=C(n,i,o);return U(e,u,t.redirections)}async function Yn(e,t,s,r,n){let i;try{i=await e.fs.readFile(t)}catch{return _(`bash: ${t}: No such file or directory
661
+ `,1)}e.state.groupStdin=c;let u=C(n,i,o);return H(e,u,t.redirections)}async function Yn(e,t,s,r,n){let i;try{i=await e.fs.readFile(t)}catch{return _(`bash: ${t}: No such file or directory
662
662
  `,127)}if(i.startsWith("#!")){let g=i.indexOf(`
663
663
  `);g!==-1&&(i=i.slice(g+1))}let o=new Map(e.state.env),a=e.state.cwd,l={...e.state.options},c=e.state.loopDepth,u=e.state.parentHasLoopContext,f=e.state.lastArg,d=e.state.bashPid,h=e.state.groupStdin,m=e.state.currentSource;e.state.parentHasLoopContext=c>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set("0",t),e.state.env.set("#",String(s.length)),e.state.env.set("@",s.join(" ")),e.state.env.set("*",s.join(" "));for(let g=0;g<s.length&&g<9;g++)e.state.env.set(String(g+1),s[g]);for(let g=s.length+1;g<=9;g++)e.state.env.delete(String(g));let p=()=>{e.state.env=o,e.state.cwd=a,e.state.options=l,e.state.loopDepth=c,e.state.parentHasLoopContext=u,e.state.lastArg=f,e.state.bashPid=d,e.state.groupStdin=h,e.state.currentSource=m};try{let S=new W().parse(i),v=await n(S);return p(),v}catch(g){if(p(),g instanceof z||g instanceof ne)throw g;if(g.name==="ParseException")return _(`bash: ${t}: ${g.message}
664
664
  `);throw g}}var dt=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){let o=this.ctx.state.env.get(i);o!==void 0&&(n[i]=o)}return n}async executeScript(t){let s="",r="",n=0;for(let i of t.statements)try{let o=await this.executeStatement(i);s+=o.stdout,r+=o.stderr,n=o.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(o){if(o instanceof z)throw o.prependOutput(s,r),o;if(o instanceof ge)return s+=o.stdout,r+=o.stderr,n=o.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Te(this.ctx.state.env)};if(o instanceof ne)throw o;if(o instanceof pe)return s+=o.stdout,r+=o.stderr,n=o.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Te(this.ctx.state.env)};if(o instanceof lr)return s+=o.stdout,r+=o.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Te(this.ctx.state.env)};if(o instanceof wt)return s+=o.stdout,r+=o.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Te(this.ctx.state.env)};if(o instanceof We){s+=o.stdout,r+=o.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(o instanceof cr){s+=o.stdout,r+=o.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(o instanceof de||o instanceof he){if(this.ctx.state.loopDepth>0)throw o.prependOutput(s,r),o;s+=o.stdout,r+=o.stderr;continue}throw o instanceof ce&&o.prependOutput(s,r),o}return{stdout:s,stderr:r,exitCode:n,env:Te(this.ctx.state.env)}}async executeUserScript(t,s,r=""){return Yn(this.ctx,t,s,r,n=>this.executeScript(n))}async executeStatement(t){if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Oe(`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 L;this.ctx.state.errexitSafe=!1;let s="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r+=`${t.sourceText}
665
- `);let n=0,i=-1,o=!1;for(let c=0;c<t.pipelines.length;c++){let u=t.pipelines[c],f=c>0?t.operators[c-1]:null;if(f==="&&"&&n!==0||f==="||"&&n===0)continue;let d=await this.executePipeline(u);s+=d.stdout,r+=d.stderr,n=d.exitCode,i=c,o=u.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}let a=i<t.pipelines.length-1,l=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||o||l,this.ctx.state.options.errexit&&n!==0&&i===t.pipelines.length-1&&!o&&!this.ctx.state.inCondition&&!l)throw new pe(n,s,r);return C(s,r,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 Rn(this.ctx,t);case"For":return Ln(this.ctx,t);case"CStyleFor":return Fn(this.ctx,t);case"While":return Mn(this.ctx,t,s);case"Until":return Wn(this.ctx,t);case"Case":return zn(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return sn(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return L}}async executeSimpleCommand(t,s){try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof vt)return _(r.stderr);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,w=100;for(;w>0;){let b=this.expandAlias(y);if(b===y)break;y=b,w--}this.aliasExpansionStack.clear(),y!==t&&(t=y)}this.ctx.state.expansionStderr="";let r=await Zn(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 w=await Ce(this.ctx,t.redirections);if(w)return w;let b=C("",i,0);return U(this.ctx,b,t.redirections)}this.ctx.state.lastArg="";let y=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",C("",y,this.ctx.state.lastExitCode)}let o=t.name&&rr(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 l=await zt(this.ctx,t.redirections);if(l){for(let[y,w]of n)w===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,w);return l}let c=-1;for(let y of t.redirections){if((y.operator==="<<"||y.operator==="<<-")&&y.target.type==="HereDoc"){let w=y.target,b=await D(this.ctx,w.content);w.stripTabs&&(b=b.split(`
665
+ `);let n=0,i=-1,o=!1;for(let c=0;c<t.pipelines.length;c++){let u=t.pipelines[c],f=c>0?t.operators[c-1]:null;if(f==="&&"&&n!==0||f==="||"&&n===0)continue;let d=await this.executePipeline(u);s+=d.stdout,r+=d.stderr,n=d.exitCode,i=c,o=u.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}let a=i<t.pipelines.length-1,l=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||o||l,this.ctx.state.options.errexit&&n!==0&&i===t.pipelines.length-1&&!o&&!this.ctx.state.inCondition&&!l)throw new pe(n,s,r);return C(s,r,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 Rn(this.ctx,t);case"For":return Ln(this.ctx,t);case"CStyleFor":return Fn(this.ctx,t);case"While":return Mn(this.ctx,t,s);case"Until":return Wn(this.ctx,t);case"Case":return zn(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return sn(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return L}}async executeSimpleCommand(t,s){try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof vt)return _(r.stderr);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,w=100;for(;w>0;){let b=this.expandAlias(y);if(b===y)break;y=b,w--}this.aliasExpansionStack.clear(),y!==t&&(t=y)}this.ctx.state.expansionStderr="";let r=await Zn(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 w=await Ce(this.ctx,t.redirections);if(w)return w;let b=C("",i,0);return H(this.ctx,b,t.redirections)}this.ctx.state.lastArg="";let y=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",C("",y,this.ctx.state.lastExitCode)}let o=t.name&&rr(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 l=await zt(this.ctx,t.redirections);if(l){for(let[y,w]of n)w===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,w);return l}let c=-1;for(let y of t.redirections){if((y.operator==="<<"||y.operator==="<<-")&&y.target.type==="HereDoc"){let w=y.target,b=await D(this.ctx,w.content);w.stripTabs&&(b=b.split(`
666
666
  `).map(T=>T.replace(/^\t+/,"")).join(`
667
667
  `));let $=y.fd??0;$!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set($,b)):s=b;continue}if(y.operator==="<<<"&&y.target.type==="Word"){s=`${await D(this.ctx,y.target)}
668
668
  `;continue}if(y.operator==="<"&&y.target.type==="Word")try{let w=await D(this.ctx,y.target),b=this.ctx.fs.resolvePath(this.ctx.state.cwd,w);s=await this.ctx.fs.readFile(b)}catch{let w=await D(this.ctx,y.target);for(let[b,$]of n)$===void 0?this.ctx.state.env.delete(b):this.ctx.state.env.set(b,$);return _(`bash: ${w}: No such file or directory
669
669
  `)}if(y.operator==="<&"&&y.target.type==="Word"){let w=await D(this.ctx,y.target),b=Number.parseInt(w,10);if(!Number.isNaN(b)&&this.ctx.state.fileDescriptors){let $=this.ctx.state.fileDescriptors.get(b);if($!==void 0)if($.startsWith("__rw__:")){let T=Vn($);T&&(s=T.content.slice(T.position),c=b)}else $.startsWith("__file__:")||$.startsWith("__file_append__:")||(s=$)}}}let u=await D(this.ctx,t.name),f=[],d=[];if(rr(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let y of t.args){let w=await Wr(this.ctx,y);if(w)f.push(w),d.push(!0);else{let b=await zr(this.ctx,y);if(b!==null)f.push(b),d.push(!0);else{let $=await _e(this.ctx,y);for(let T of $.values)f.push(T),d.push($.quoted)}}}else for(let y of t.args){let w=await _e(this.ctx,y);for(let b of w.values)f.push(b),d.push(w.quoted)}if(!u){if(t.name.parts.every(w=>w.type==="CommandSubstitution"||w.type==="ParameterExpansion"||w.type==="ArithmeticExpansion")){if(f.length>0){let w=f.shift();return d.shift(),await this.runCommand(w,f,d,s,!1,!1,c)}return C("","",this.ctx.state.lastExitCode)}return _(`bash: : command not found
670
670
  `,127)}if(u==="exec"&&(f.length===0||f[0]==="--")){for(let y of t.redirections){if(y.target.type==="HereDoc"||y.fdVariable)continue;let w=await D(this.ctx,y.target),b=y.fd??(y.operator==="<"||y.operator==="<>"?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),y.operator){case">":case">|":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,w);await this.ctx.fs.writeFile($,"","utf8"),this.ctx.state.fileDescriptors.set(b,`__file__:${$}`);break}case">>":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,w);this.ctx.state.fileDescriptors.set(b,`__file_append__:${$}`);break}case"<":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,w);try{let T=await this.ctx.fs.readFile($);this.ctx.state.fileDescriptors.set(b,T)}catch{return _(`bash: ${w}: No such file or directory
671
- `)}break}case"<>":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,w);try{let T=await this.ctx.fs.readFile($);this.ctx.state.fileDescriptors.set(b,`__rw__:${$.length}:${$}:0:${T}`)}catch{await this.ctx.fs.writeFile($,"","utf8"),this.ctx.state.fileDescriptors.set(b,`__rw__:${$.length}:${$}:0:`)}break}case">&":{if(w==="-")this.ctx.state.fileDescriptors.delete(b);else if(w.endsWith("-")){let $=w.slice(0,-1),T=Number.parseInt($,10);if(!Number.isNaN(T)){let N=this.ctx.state.fileDescriptors.get(T);N!==void 0?this.ctx.state.fileDescriptors.set(b,N):this.ctx.state.fileDescriptors.set(b,`__dupout__:${T}`),this.ctx.state.fileDescriptors.delete(T)}}else{let $=Number.parseInt(w,10);Number.isNaN($)||this.ctx.state.fileDescriptors.set(b,`__dupout__:${$}`)}break}case"<&":{if(w==="-")this.ctx.state.fileDescriptors.delete(b);else if(w.endsWith("-")){let $=w.slice(0,-1),T=Number.parseInt($,10);if(!Number.isNaN(T)){let N=this.ctx.state.fileDescriptors.get(T);N!==void 0?this.ctx.state.fileDescriptors.set(b,N):this.ctx.state.fileDescriptors.set(b,`__dupin__:${T}`),this.ctx.state.fileDescriptors.delete(T)}}else{let $=Number.parseInt(w,10);Number.isNaN($)||this.ctx.state.fileDescriptors.set(b,`__dupin__:${$}`)}break}}}for(let[y,w]of n)w===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,w);if(this.ctx.state.tempExportedVars)for(let y of n.keys())this.ctx.state.tempExportedVars.delete(y);return L}let m=await Un(this.ctx,u,f);n.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let p,g=null;try{p=await this.runCommand(u,f,d,s,!1,!1,c)}catch(y){if(y instanceof de||y instanceof he)g=y,p=L;else throw y}let S=i+m;if(S&&(p={...p,stderr:S+p.stderr}),p=await U(this.ctx,p,t.redirections),g)throw g;if(f.length>0){let y=f[f.length-1];if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(y)){let w=y.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);w&&(y=w[1])}this.ctx.state.lastArg=y}else this.ctx.state.lastArg=u;let v=en(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!v)for(let[y,w]of n)this.ctx.state.fullyUnsetLocals?.has(y)||(w===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,w));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&&(p={...p,stderr:this.ctx.state.expansionStderr+p.stderr},this.ctx.state.expansionStderr=""),p}async runCommand(t,s,r,n,i=!1,o=!1,a=-1){let l={ctx:this.ctx,runCommand:(u,f,d,h,m,p,g)=>this.runCommand(u,f,d,h,m,p,g),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(u,f,d)=>this.executeUserScript(u,f,d)},c=await Dn(l,t,s,r,n,i,o,a);return c!==null?c:In(l,t,s,n,o)}aliasExpansionStack=new Set;expandAlias(t){return ds(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Zt(this.ctx,t)}async executeSubshell(t,s=""){return Kn(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=""){return Xn(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Ce(this.ctx,t.redirections);if(s)return s;try{let r=await V(this.ctx,t.expression.expression),n=G(r!==0);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=""),U(this.ctx,n,t.redirections)}catch(r){let n=_(`bash: arithmetic expression: ${r.message}
672
- `);return U(this.ctx,n,t.redirections)}}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Ce(this.ctx,t.redirections);if(s)return s;try{let r=await Le(this.ctx,t.expression),n=G(r);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=""),U(this.ctx,n,t.redirections)}catch(r){let n=r instanceof We?1:2,i=_(`bash: conditional expression: ${r.message}
673
- `,n);return U(this.ctx,i,t.redirections)}}};var ae={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,maxBraceExpansionResults:1e4};function Qn(e){return e?{maxCallDepth:e.maxCallDepth??ae.maxCallDepth,maxCommandCount:e.maxCommandCount??ae.maxCommandCount,maxLoopIterations:e.maxLoopIterations??ae.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??ae.maxAwkIterations,maxSedIterations:e.maxSedIterations??ae.maxSedIterations,maxJqIterations:e.maxJqIterations??ae.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??ae.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??ae.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??ae.maxGlobOperations,maxStringLength:e.maxStringLength??ae.maxStringLength,maxArrayElements:e.maxArrayElements??ae.maxArrayElements,maxHeredocSize:e.maxHeredocSize??ae.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??ae.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??ae.maxBraceExpansionResults}:{...ae}}function Jn(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=Jn(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function zo(e,t){let s=Jn(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 nr(e,t){return!t||t.length===0?!1:t.some(s=>zo(e,s))}var ht=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},pt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},mt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Kt=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},yt=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Vo=20,Bo=3e4,jo=10485760,Uo=["GET","HEAD"],Ho=new Set(["GET","HEAD","OPTIONS"]),qo=new Set([301,302,303,307,308]);function ir(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??Uo;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!nr(l,e.allowedUrlPrefixes??[]))throw new ht(l)}function o(l){if(e.dangerouslyAllowFullInternetAccess)return;let c=l.toUpperCase();if(!n.includes(c))throw new Kt(c,n)}async function a(l,c={}){let u=c.method?.toUpperCase()??"GET";i(l),o(u);let f=l,d=0,h=c.followRedirects??!0,m=c.timeoutMs!==void 0?Math.min(c.timeoutMs,s):s;for(;;){let p=new AbortController,g=setTimeout(()=>p.abort(),m);try{let S={method:u,headers:c.headers,signal:p.signal,redirect:"manual"};c.body&&!Ho.has(u)&&(S.body=c.body);let v=await fetch(f,S);if(qo.has(v.status)&&h){let A=v.headers.get("location");if(!A)return await ei(v,f,r);let y=new URL(A,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!nr(y,e.allowedUrlPrefixes??[]))throw new mt(y);if(d++,d>t)throw new pt(t);f=y;continue}return await ei(v,f,r)}finally{clearTimeout(g)}}}return a}async function ei(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 yt(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),o=new TextDecoder,a=[],l=0;for(;;){let{done:c,value:u}=await i.read();if(c)break;if(l+=u.byteLength,l>s)throw i.cancel(),new yt(s);a.push(o.decode(u,{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 ti(){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:"getBuiltinModule",target:process,violationType:"process_get_builtin_module",strategy:"throw",reason:"process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)"},{prop:"exit",target:process,violationType:"process_exit",strategy:"throw",reason:"process.exit could terminate the interpreter"},{prop:"abort",target:process,violationType:"process_exit",strategy:"throw",reason:"process.abort could crash the interpreter"},{prop:"kill",target:process,violationType:"process_kill",strategy:"throw",reason:"process.kill could signal other processes"},{prop:"setuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setuid could escalate privileges"},{prop:"setgid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgid could escalate privileges"},{prop:"umask",target:process,violationType:"process_umask",strategy:"throw",reason:"process.umask could modify file creation permissions"},{prop:"argv",target:process,violationType:"process_argv",strategy:"throw",reason:"process.argv may contain secrets in CLI arguments"},{prop:"chdir",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.chdir could confuse the interpreter's CWD tracking"},{prop:"send",target:process,violationType:"process_send",strategy:"throw",reason:"process.send could communicate with parent process in IPC contexts"},{prop:"channel",target:process,violationType:"process_channel",strategy:"throw",reason:"process.channel could access IPC channel to parent process"},{prop:"cpuUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.cpuUsage could enable timing side-channel attacks"},{prop:"memoryUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.memoryUsage could enable timing side-channel attacks"},{prop:"hrtime",target:process,violationType:"process_timing",strategy:"throw",reason:"process.hrtime could enable timing side-channel attacks"},{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}})}import{AsyncLocalStorage as Zo}from"node:async_hooks";var tt=typeof __BROWSER__<"u"&&__BROWSER__;function si(){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 ar=null;tt||(ar=Zo);var Go=`
671
+ `)}break}case"<>":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,w);try{let T=await this.ctx.fs.readFile($);this.ctx.state.fileDescriptors.set(b,`__rw__:${$.length}:${$}:0:${T}`)}catch{await this.ctx.fs.writeFile($,"","utf8"),this.ctx.state.fileDescriptors.set(b,`__rw__:${$.length}:${$}:0:`)}break}case">&":{if(w==="-")this.ctx.state.fileDescriptors.delete(b);else if(w.endsWith("-")){let $=w.slice(0,-1),T=Number.parseInt($,10);if(!Number.isNaN(T)){let N=this.ctx.state.fileDescriptors.get(T);N!==void 0?this.ctx.state.fileDescriptors.set(b,N):this.ctx.state.fileDescriptors.set(b,`__dupout__:${T}`),this.ctx.state.fileDescriptors.delete(T)}}else{let $=Number.parseInt(w,10);Number.isNaN($)||this.ctx.state.fileDescriptors.set(b,`__dupout__:${$}`)}break}case"<&":{if(w==="-")this.ctx.state.fileDescriptors.delete(b);else if(w.endsWith("-")){let $=w.slice(0,-1),T=Number.parseInt($,10);if(!Number.isNaN(T)){let N=this.ctx.state.fileDescriptors.get(T);N!==void 0?this.ctx.state.fileDescriptors.set(b,N):this.ctx.state.fileDescriptors.set(b,`__dupin__:${T}`),this.ctx.state.fileDescriptors.delete(T)}}else{let $=Number.parseInt(w,10);Number.isNaN($)||this.ctx.state.fileDescriptors.set(b,`__dupin__:${$}`)}break}}}for(let[y,w]of n)w===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,w);if(this.ctx.state.tempExportedVars)for(let y of n.keys())this.ctx.state.tempExportedVars.delete(y);return L}let m=await Un(this.ctx,u,f);n.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let p,g=null;try{p=await this.runCommand(u,f,d,s,!1,!1,c)}catch(y){if(y instanceof de||y instanceof he)g=y,p=L;else throw y}let S=i+m;if(S&&(p={...p,stderr:S+p.stderr}),p=await H(this.ctx,p,t.redirections),g)throw g;if(f.length>0){let y=f[f.length-1];if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(y)){let w=y.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);w&&(y=w[1])}this.ctx.state.lastArg=y}else this.ctx.state.lastArg=u;let v=en(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!v)for(let[y,w]of n)this.ctx.state.fullyUnsetLocals?.has(y)||(w===void 0?this.ctx.state.env.delete(y):this.ctx.state.env.set(y,w));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&&(p={...p,stderr:this.ctx.state.expansionStderr+p.stderr},this.ctx.state.expansionStderr=""),p}async runCommand(t,s,r,n,i=!1,o=!1,a=-1){let l={ctx:this.ctx,runCommand:(u,f,d,h,m,p,g)=>this.runCommand(u,f,d,h,m,p,g),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(u,f,d)=>this.executeUserScript(u,f,d)},c=await Dn(l,t,s,r,n,i,o,a);return c!==null?c:In(l,t,s,n,o)}aliasExpansionStack=new Set;expandAlias(t){return ds(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Zt(this.ctx,t)}async executeSubshell(t,s=""){return Kn(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=""){return Xn(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Ce(this.ctx,t.redirections);if(s)return s;try{let r=await V(this.ctx,t.expression.expression),n=G(r!==0);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=""),H(this.ctx,n,t.redirections)}catch(r){let n=_(`bash: arithmetic expression: ${r.message}
672
+ `);return H(this.ctx,n,t.redirections)}}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Ce(this.ctx,t.redirections);if(s)return s;try{let r=await Le(this.ctx,t.expression),n=G(r);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=""),H(this.ctx,n,t.redirections)}catch(r){let n=r instanceof We?1:2,i=_(`bash: conditional expression: ${r.message}
673
+ `,n);return H(this.ctx,i,t.redirections)}}};var ae={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,maxBraceExpansionResults:1e4};function Qn(e){return e?{maxCallDepth:e.maxCallDepth??ae.maxCallDepth,maxCommandCount:e.maxCommandCount??ae.maxCommandCount,maxLoopIterations:e.maxLoopIterations??ae.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??ae.maxAwkIterations,maxSedIterations:e.maxSedIterations??ae.maxSedIterations,maxJqIterations:e.maxJqIterations??ae.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??ae.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??ae.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??ae.maxGlobOperations,maxStringLength:e.maxStringLength??ae.maxStringLength,maxArrayElements:e.maxArrayElements??ae.maxArrayElements,maxHeredocSize:e.maxHeredocSize??ae.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??ae.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??ae.maxBraceExpansionResults}:{...ae}}function Jn(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=Jn(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function zo(e,t){let s=Jn(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 nr(e,t){return!t||t.length===0?!1:t.some(s=>zo(e,s))}var ht=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},pt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},mt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Kt=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},yt=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Vo=20,Bo=3e4,jo=10485760,Uo=["GET","HEAD"],Ho=new Set(["GET","HEAD","OPTIONS"]),qo=new Set([301,302,303,307,308]);function ir(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??Uo;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!nr(l,e.allowedUrlPrefixes??[]))throw new ht(l)}function o(l){if(e.dangerouslyAllowFullInternetAccess)return;let c=l.toUpperCase();if(!n.includes(c))throw new Kt(c,n)}async function a(l,c={}){let u=c.method?.toUpperCase()??"GET";i(l),o(u);let f=l,d=0,h=c.followRedirects??!0,m=c.timeoutMs!==void 0?Math.min(c.timeoutMs,s):s;for(;;){let p=new AbortController,g=setTimeout(()=>p.abort(),m);try{let S={method:u,headers:c.headers,signal:p.signal,redirect:"manual"};c.body&&!Ho.has(u)&&(S.body=c.body);let v=await fetch(f,S);if(qo.has(v.status)&&h){let A=v.headers.get("location");if(!A)return await ei(v,f,r);let y=new URL(A,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!nr(y,e.allowedUrlPrefixes??[]))throw new mt(y);if(d++,d>t)throw new pt(t);f=y;continue}return await ei(v,f,r)}finally{clearTimeout(g)}}}return a}async function ei(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 yt(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),o=new TextDecoder,a=[],l=0;for(;;){let{done:c,value:u}=await i.read();if(c)break;if(l+=u.byteLength,l>s)throw i.cancel(),new yt(s);a.push(o.decode(u,{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 ti(){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:"getBuiltinModule",target:process,violationType:"process_get_builtin_module",strategy:"throw",reason:"process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)"},{prop:"exit",target:process,violationType:"process_exit",strategy:"throw",reason:"process.exit could terminate the interpreter"},{prop:"abort",target:process,violationType:"process_exit",strategy:"throw",reason:"process.abort could crash the interpreter"},{prop:"kill",target:process,violationType:"process_kill",strategy:"throw",reason:"process.kill could signal other processes"},{prop:"setuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setuid could escalate privileges"},{prop:"setgid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgid could escalate privileges"},{prop:"umask",target:process,violationType:"process_umask",strategy:"throw",reason:"process.umask could modify file creation permissions"},{prop:"argv",target:process,violationType:"process_argv",strategy:"throw",reason:"process.argv may contain secrets in CLI arguments"},{prop:"chdir",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.chdir could confuse the interpreter's CWD tracking"},{prop:"send",target:process,violationType:"process_send",strategy:"throw",reason:"process.send could communicate with parent process in IPC contexts"},{prop:"channel",target:process,violationType:"process_channel",strategy:"throw",reason:"process.channel could access IPC channel to parent process"},{prop:"cpuUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.cpuUsage could enable timing side-channel attacks"},{prop:"memoryUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.memoryUsage could enable timing side-channel attacks"},{prop:"hrtime",target:process,violationType:"process_timing",strategy:"throw",reason:"process.hrtime could enable timing side-channel attacks"},{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}})}import{AsyncLocalStorage as Zo}from"node:async_hooks";var tt=typeof __BROWSER__<"u"&&__BROWSER__;function si(){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 ar=null;tt||(ar=Zo);var Go=`
674
674
 
675
675
  This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,se=class extends Error{violation;constructor(t,s){super(t+Go),this.violation=s,this.name="SecurityViolationError"}},oe=!tt&&ar?new ar:null,Ko=1e3,or={enabled:!0,auditMode:!1};function Xo(e){return e===void 0?{...or,enabled:!1}:typeof e=="boolean"?{...or,enabled:e}:{...or,...e}}var Xt=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(Xo(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return oe?oe?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(oe)return oe?.getStore()?.executionId}isEnabled(){return this.config.enabled===!0&&oe!==null&&!tt}updateConfig(t){this.config={...this.config,...t}}activate(){if(tt||!this.config.enabled){let s=si();return{run:r=>r(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=si();return{run:s=>oe.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 tt||this.config.auditMode||!oe?!1:oe?.getStore()?.sandboxActive===!0}recordViolation(t,s,r){let n={timestamp:Date.now(),type:t,message:r,path:s,stack:new Error().stack,executionId:oe?.getStore()?.executionId};if(this.violations.length<Ko&&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 l=`${s} is blocked during script execution`,c=n.recordViolation(r,s,l);throw new se(l,c)}return n.config.auditMode&&oe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} called (audit mode)`),Reflect.apply(i,o,a)},construct(i,o,a){if(n.shouldBlock()){let l=`${s} constructor is blocked during script execution`,c=n.recordViolation(r,s,l);throw new se(l,c)}return n.config.auditMode&&oe?.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 l=`${s}.${String(o)}`,c=`${l} is blocked during script execution`,u=n.recordViolation(r,l,c);throw new se(c,u)}if(n.config.auditMode&&oe?.getStore()?.sandboxActive===!0){let l=`${s}.${String(o)}`;n.recordViolation(r,l,`${l} accessed (audit mode)`)}return Reflect.get(i,o,a)},set(i,o,a,l){if(n.shouldBlock()){let c=`${s}.${String(o)}`,u=`${c} modification is blocked during script execution`,f=n.recordViolation(r,c,u);throw new se(u,f)}return Reflect.set(i,o,a,l)},ownKeys(i){if(n.shouldBlock()){let o=`${s} enumeration is blocked during script execution`,a=n.recordViolation(r,s,o);throw new se(o,a)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,o){if(n.shouldBlock()){let a=`${s}.${String(o)}`,l=`${a} descriptor access is blocked during script execution`,c=n.recordViolation(r,a,l);throw new se(l,c)}return Reflect.getOwnPropertyDescriptor(i,o)},has(i,o){if(n.shouldBlock()){let a=`${s}.${String(o)}`,l=`${a} existence check is blocked during script execution`,c=n.recordViolation(r,a,l);throw new se(l,c)}return Reflect.has(i,o)}})}applyPatches(){let t=ti(),s=new Set(["process_send","process_channel"]);for(let r of t)s.has(r.violationType)||this.applyPatch(r);this.protectConstructorChain(),this.protectErrorPrepareStackTrace(),this.protectModuleLoad(),this.protectProcessMainModule(),this.protectProcessExecPath()}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 se(i,o)}t.config.auditMode&&oe?.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`,l=n.recordViolation(r,s,a);throw new se(a,l)}return n.config.auditMode&&oe?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} accessed (audit mode)`),o},set(a){if(n.shouldBlock()){let l=`${s} modification is blocked during script execution`,c=n.recordViolation(r,s,l);throw new se(l,c)}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 se(n,i)}return t.config.auditMode&&oe?.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 se(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)}}protectProcessExecPath(){if(typeof process>"u")return;let t=this;try{let s=Object.getOwnPropertyDescriptor(process,"execPath");this.originalDescriptors.push({target:process,prop:"execPath",descriptor:s});let r=s?.value??process.execPath;Object.defineProperty(process,"execPath",{get(){if(t.shouldBlock()){let n="process.execPath access is blocked during script execution",i=t.recordViolation("process_exec_path","process.execPath",n);throw new se(n,i)}return t.config.auditMode&&oe?.getStore()?.sandboxActive===!0&&t.recordViolation("process_exec_path","process.execPath","process.execPath accessed (audit mode)"),r},set(n){if(t.shouldBlock()){let i="process.execPath modification is blocked during script execution",o=t.recordViolation("process_exec_path","process.execPath",i);throw new se(i,o)}Object.defineProperty(process,"execPath",{value:n,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.execPath:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!tt)try{let t=null;if(typeof process<"u"){let o=process.mainModule;o&&typeof o=="object"&&(t=o.constructor)}if(!t&&typeof gt<"u"&&typeof gt.main<"u"&&(t=gt.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 l=this.getPathForTarget(s,r),c=typeof o=="function"?this.createBlockingProxy(o,l,n):this.createBlockingObjectProxy(o,l,n);Object.defineProperty(s,r,{value:c,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=[]}};function ri(e){return Ue(e)}function Ue(e){return e.statements.map(ni).join(`
676
676
  `)}function ni(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(Yo(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let s=t.join(" ");return e.background&&(s+=" &"),s}function Yo(e){let t=[];e.timed&&t.push(e.timePosix?"time -p":"time"),e.negated&&t.push("!");let s=[];for(let n=0;n<e.commands.length;n++)if(s.push(ii(e.commands[n])),n<e.commands.length-1){let i=e.pipeStderr?.[n];s.push(i?"|&":"|")}return(t.length>0?`${t.join(" ")} `:"")+s.join(" ")}function ii(e){switch(e.type){case"SimpleCommand":return Qo(e);case"If":return aa(e);case"For":return la(e);case"CStyleFor":return ca(e);case"While":return ua(e);case"Until":return fa(e);case"Case":return da(e);case"Subshell":return pa(e);case"Group":return ma(e);case"ArithmeticCommand":return ya(e);case"ConditionalCommand":return ga(e);case"FunctionDef":return wa(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function Qo(e){let t=[];for(let s of e.assignments)t.push(Jo(s));e.name&&t.push(le(e.name));for(let s of e.args)t.push(le(s));for(let s of e.redirections)t.push(li(s));return t.join(" ")}function Jo(e){let t=e.append?"+=":"=";if(e.array){let s=e.array.map(le).join(" ");return`${e.name}${t}(${s})`}return e.value?`${e.name}${t}${le(e.value)}`:`${e.name}${t}`}function le(e){return e.parts.map(t=>Yt(t,!1)).join("")}function Me(e){return e.parts.map(t=>Yt(t,!0)).join("")}function Yt(e,t){switch(e.type){case"Literal":return t?ta(e.value):ea(e.value);case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(s=>Yt(s,!0)).join("")}"`;case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return oi(e);case"CommandSubstitution":return e.legacy?`\`${Ue(e.body)}\``:`$(${Ue(e.body)})`;case"ArithmeticExpansion":return`$((${B(e.expression.expression)}))`;case"ProcessSubstitution":return e.direction==="input"?`<(${Ue(e.body)})`:`>(${Ue(e.body)})`;case"BraceExpansion":return ia(e);case"TildeExpansion":return e.user!==null?`~${e.user}`:"~";case"Glob":return e.pattern;default:{let s=e;throw new Error(`Unsupported word part type: ${s.type}`)}}}function ea(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,"\\$&")}function ta(e){return e.replace(/[$`"\\]/g,"\\$&")}function sa(e,t){return e.parts.map(s=>ra(s,t)).join("")}function ra(e,t){switch(e.type){case"Literal":return t?e.value:e.value.replace(/[$`]/g,"\\$&");case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return oi(e);case"CommandSubstitution":return e.legacy?`\`${Ue(e.body)}\``:`$(${Ue(e.body)})`;case"ArithmeticExpansion":return`$((${B(e.expression.expression)}))`;default:return Yt(e,!1)}}function oi(e){return e.operation?`\${${ai(e.parameter,e.operation)}}`:na(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function na(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function ai(e,t){switch(t.type){case"Length":return`#${e}`;case"LengthSliceError":return`#${e}:`;case"BadSubstitution":return t.text;case"DefaultValue":return`${e}${t.checkEmpty?":":""}-${Me(t.word)}`;case"AssignDefault":return`${e}${t.checkEmpty?":":""}=${Me(t.word)}`;case"ErrorIfUnset":return`${e}${t.checkEmpty?":":""}?${t.word?Me(t.word):""}`;case"UseAlternative":return`${e}${t.checkEmpty?":":""}+${Me(t.word)}`;case"Substring":{let s=B(t.offset.expression);return t.length?`${e}:${s}:${B(t.length.expression)}`:`${e}:${s}`}case"PatternRemoval":{let s=t.side==="prefix"?"#":"%",r=t.greedy?`${s}${s}`:s;return`${e}${r}${Me(t.pattern)}`}case"PatternReplacement":{let s="/";t.all?s="//":t.anchor==="start"?s="/#":t.anchor==="end"&&(s="/%");let r=t.replacement?`/${Me(t.replacement)}`:"";return`${e}${s}${Me(t.pattern)}${r}`}case"CaseModification":{let s=t.direction==="upper"?"^":",",r=t.all?`${s}${s}`:s,n=t.pattern?Me(t.pattern):"";return`${e}${r}${n}`}case"Transform":return`${e}@${t.operator}`;case"Indirection":return t.innerOp?`!${ai(e,t.innerOp)}`:`!${e}`;case"ArrayKeys":return`!${t.array}[${t.star?"*":"@"}]`;case"VarNamePrefix":return`!${t.prefix}${t.star?"*":"@"}`;default:{let s=t;throw new Error(`Unsupported parameter operation type: ${s.type}`)}}}function ia(e){return`{${e.items.map(oa).join(",")}}`}function oa(e){if(e.type==="Word")return le(e.word);let t=e.startStr??String(e.start),s=e.endStr??String(e.end);return e.step!==void 0?`${t}..${s}..${e.step}`:`${t}..${s}`}function li(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd!==null?String(e.fd):"";if(e.operator==="<<"||e.operator==="<<-"){let s=e.target,r=s.quoted?`'${s.delimiter}'`:s.delimiter,n=sa(s.content,s.quoted);return`${t}${e.operator}${r}
@@ -703,7 +703,7 @@ ${e.terminator}`}function pa(e){return`(${ye(e.body)})${Ee(e.redirections)}`}fun
703
703
  `,exitCode:2,env:we(this.state.env,s?.env)});if(f instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${Se(f.message)}
704
704
  `,exitCode:1,env:we(this.state.env,s?.env)});throw f}finally{u?.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 Te(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){let s=ci(t),r=ve(s,{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let i of this.transformPlugins){let o=i.transform({ast:r,metadata:n});r=o.ast,o.metadata&&(n={...n,...o.metadata})}return{script:ri(r),ast:r,metadata:n}}};function ci(e){let t=e.split(`
705
705
  `),s=[],r=[];for(let n=0;n<t.length;n++){let i=t[n];if(r.length>0){let l=r[r.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.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 l of o.matchAll(a)){let c=l[1]==="-",u=l[3];r.push({delimiter:u,stripTabs:c})}}return s.join(`
706
- `)}var va=new TextDecoder("utf-8",{fatal:!0});function ui(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);try{return va.decode(s)}catch{return e}}import*as Z from"node:fs";import*as ie from"node:path";var ba="/home/user/project",st=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;allowSymlinks;memory=new Map;deleted=new Set;constructor(t){this.root=ie.resolve(t.root);let s=t.mountPoint??ba;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,dr(this.root,"OverlayFs"),this.canonicalRoot=Z.realpathSync(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=j(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=j(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)}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=j(t),r=this.getRelativeToMount(s);if(r===null)return null;let n=ie.join(this.root,r),i=ie.resolve(n);return Jt(i,this.root)?i:null}dirname(t){let s=j(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}resolveRealPath_(t){return t?this.allowSymlinks?ur(t,this.canonicalRoot):fr(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let s=ie.dirname(t),r=this.resolveRealPath_(s);return r===null?null:ie.join(r,ie.basename(t))}sanitizeError(t,s,r){let n=t;if(n.path===void 0&&(n.message?.includes("ELOOP")||n.message?.includes("EFBIG")||n.message?.includes("EPERM")))throw t;let i=n.code||"EIO";throw new Error(`${i}: ${r} '${s}'`)}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=j(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.resolveRealPathParent_(this.toRealPath(s));if(!r)return!1;try{return await Z.promises.lstat(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=Re(s);return _t(r,n)}async readFileBuffer(t,s=new Set){Y(t,"open");let r=j(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.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let o=await Z.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let l=await Z.promises.readlink(i),c=this.realTargetToVirtual(r,l),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 Z.promises.readFile(i);return new Uint8Array(a)}catch(o){if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(o,t,"open")}}async writeFile(t,s,r){Y(t,"write"),this.assertWritable(`write '${t}'`);let n=j(t);this.ensureParentDirs(n);let i=Re(r),o=Ze(s,i);this.memory.set(n,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){Y(t,"append"),this.assertWritable(`append '${t}'`);let n=j(t),i=Re(r),o=Ze(s,i),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+o.length);l.set(a),l.set(o,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,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){Y(t,"stat");let r=j(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.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await Z.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let a=await Z.promises.readlink(i),l=this.realTargetToVirtual(r,a),c=this.resolveSymlink(r,l);return this.stat(c,s)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){Y(t,"lstat");let s=j(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.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await Z.promises.lstat(n);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}resolveSymlink(t,s){if(s.startsWith("/"))return j(s);let r=this.dirname(t);return j(r==="/"?`/${s}`:`${r}/${s}`)}realTargetToVirtual(t,s){let r=hr(s,this.canonicalRoot);if(r.withinRoot){if(!ie.isAbsolute(s))return s;let n=r.relativePath;return this.mountPoint==="/"?n:`${this.mountPoint}${n}`}return r.safeName}async mkdir(t,s){Y(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=j(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 l=a.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let[a,l]of this.memory)if(a!==s&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!n.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let o=this.resolveRealPath_(this.toRealPath(s));if(o)try{let a=await Z.promises.readdir(o,{withFileTypes:!0});for(let l of a)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else a.code!=="ENOTDIR"&&this.sanitizeError(a,t,"scandir")}return r}async resolveForReaddir(t,s=!1){let r=j(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 l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await Z.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await Z.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){Y(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){Y(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){Y(t,"rm"),this.assertWritable(`rm '${t}'`);let r=j(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 l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,s)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.deleted.add(r),this.memory.delete(r)}async cp(t,s,r){Y(t,"cp"),Y(s,"cp"),this.assertWritable(`cp '${s}'`);let n=j(t),i=j(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 l=await this.readFileBuffer(n);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let c of l){let u=n==="/"?`/${c}`:`${n}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,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 j(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return j(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.resolveRealPath_(this.toRealPath(t));if(r)try{let n=Z.readdirSync(r);for(let i of n){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(o))continue;s.add(o);let a=ie.join(r,i);Z.lstatSync(a).isDirectory()&&this.scanRealFs(o,s)}}catch{}}async chmod(t,s){Y(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=j(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){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);Y(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=j(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){Y(t,"link"),Y(s,"link"),this.assertWritable(`link '${s}'`);let r=j(t),n=j(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 l=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:o.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){Y(t,"readlink");let s=j(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.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await Z.promises.readlink(n);if(!ie.isAbsolute(i)){let o=ie.resolve(ie.dirname(n),i),a;try{a=Z.realpathSync(o)}catch{a=o}if(!Jt(a,this.canonicalRoot))return ie.basename(i)}return this.realTargetToVirtual(s,i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){Y(t,"realpath");let s=j(t),r=new Set,n=async a=>{let l=a==="/"?[]:a.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let m=this.toRealPath(c),p=this.resolveRealPath_(m);if(p)try{if((await Z.promises.lstat(p)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let S=await Z.promises.readlink(p),v=this.realTargetToVirtual(c,S);return r.add(c),c=this.resolveSymlink(c,v),n(c)}}catch(g){if(g.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(g,t,"realpath")}else if(!this.allowSymlinks){let g=this.resolveRealPathParent_(m);if(g)try{if((await Z.promises.lstat(g)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(S){if(S.message?.includes("ENOENT")||S.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(S,t,"realpath")}}}}return c||"/"},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){Y(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=j(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 l=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:l,mode:a.mode,mtime:r})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:a.mode,mtime:r})}};function di(){console.log(`just-bash - A secure bash environment for AI agents
706
+ `)}var va=new TextDecoder("utf-8",{fatal:!0});function ui(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);try{return va.decode(s)}catch{return e}}import*as U from"node:fs";import*as ie from"node:path";var ba="/home/user/project",st=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;allowSymlinks;memory=new Map;deleted=new Set;constructor(t){this.root=ie.resolve(t.root);let s=t.mountPoint??ba;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,dr(this.root,"OverlayFs"),this.canonicalRoot=U.realpathSync(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=j(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=j(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)}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=j(t),r=this.getRelativeToMount(s);if(r===null)return null;let n=ie.join(this.root,r),i=ie.resolve(n);return Jt(i,this.root)?i:null}dirname(t){let s=j(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}resolveRealPath_(t){return t?this.allowSymlinks?ur(t,this.canonicalRoot):fr(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let s=ie.dirname(t),r=this.resolveRealPath_(s);return r===null?null:ie.join(r,ie.basename(t))}sanitizeError(t,s,r){let n=t;if(n.path===void 0&&(n.message?.includes("ELOOP")||n.message?.includes("EFBIG")||n.message?.includes("EPERM")))throw t;let i=n.code||"EIO";throw new Error(`${i}: ${r} '${s}'`)}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=j(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.resolveRealPathParent_(this.toRealPath(s));if(!r)return!1;try{return await U.promises.lstat(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=Re(s);return _t(r,n)}async readFileBuffer(t,s=new Set){Y(t,"open");let r=j(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.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let o=await U.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let c=await U.promises.readlink(i),u=this.realTargetToVirtual(r,c),f=this.resolveSymlink(r,u);return this.readFileBuffer(f,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=this.allowSymlinks?U.constants.O_RDONLY:U.constants.O_RDONLY|U.constants.O_NOFOLLOW,l=await U.promises.open(i,a);try{let c=await l.readFile();return new Uint8Array(c)}finally{await l.close()}}catch(o){let a=o.code;if(a==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(a==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(o,t,"open")}}async writeFile(t,s,r){Y(t,"write"),this.assertWritable(`write '${t}'`);let n=j(t);this.ensureParentDirs(n);let i=Re(r),o=Ze(s,i);this.memory.set(n,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){Y(t,"append"),this.assertWritable(`append '${t}'`);let n=j(t),i=Re(r),o=Ze(s,i),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+o.length);l.set(a),l.set(o,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,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){Y(t,"stat");let r=j(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.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await U.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let a=await U.promises.readlink(i),l=this.realTargetToVirtual(r,a),c=this.resolveSymlink(r,l);return this.stat(c,s)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){Y(t,"lstat");let s=j(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.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await U.promises.lstat(n);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}resolveSymlink(t,s){if(s.startsWith("/"))return j(s);let r=this.dirname(t);return j(r==="/"?`/${s}`:`${r}/${s}`)}realTargetToVirtual(t,s){let r=hr(s,this.canonicalRoot);if(r.withinRoot){if(!ie.isAbsolute(s))return s;let n=r.relativePath;return this.mountPoint==="/"?n:`${this.mountPoint}${n}`}return r.safeName}async mkdir(t,s){Y(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=j(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 l=a.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let[a,l]of this.memory)if(a!==s&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!n.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let o=this.resolveRealPath_(this.toRealPath(s));if(o)try{if(!this.allowSymlinks&&(await U.promises.lstat(o)).isSymbolicLink()){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let a=await U.promises.readdir(o,{withFileTypes:!0});for(let l of a)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else a.code!=="ENOTDIR"&&this.sanitizeError(a,t,"scandir")}return r}async resolveForReaddir(t,s=!1){let r=j(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 l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await U.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await U.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){Y(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){Y(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){Y(t,"rm"),this.assertWritable(`rm '${t}'`);let r=j(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 l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,s)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.deleted.add(r),this.memory.delete(r)}async cp(t,s,r){Y(t,"cp"),Y(s,"cp"),this.assertWritable(`cp '${s}'`);let n=j(t),i=j(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 l=await this.readFileBuffer(n);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let c of l){let u=n==="/"?`/${c}`:`${n}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,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 j(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return j(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.resolveRealPath_(this.toRealPath(t));if(r)try{let n=U.readdirSync(r);for(let i of n){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(o))continue;s.add(o);let a=ie.join(r,i);U.lstatSync(a).isDirectory()&&this.scanRealFs(o,s)}}catch{}}async chmod(t,s){Y(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=j(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){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);Y(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=j(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){Y(t,"link"),Y(s,"link"),this.assertWritable(`link '${s}'`);let r=j(t),n=j(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 l=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:o.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){Y(t,"readlink");let s=j(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.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await U.promises.readlink(n);if(!ie.isAbsolute(i)){let o=ie.resolve(ie.dirname(n),i),a;try{a=U.realpathSync(o)}catch{a=o}if(!Jt(a,this.canonicalRoot))return ie.basename(i)}return this.realTargetToVirtual(s,i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){Y(t,"realpath");let s=j(t),r=new Set,n=async a=>{let l=a==="/"?[]:a.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let m=this.toRealPath(c),p=this.resolveRealPath_(m);if(p)try{if((await U.promises.lstat(p)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let S=await U.promises.readlink(p),v=this.realTargetToVirtual(c,S);return r.add(c),c=this.resolveSymlink(c,v),n(c)}}catch(g){if(g.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(g,t,"realpath")}else if(!this.allowSymlinks){let g=this.resolveRealPathParent_(m);if(g)try{if((await U.promises.lstat(g)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(S){if(S.message?.includes("ENOENT")||S.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(S,t,"realpath")}}}}return c||"/"},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){Y(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=j(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 l=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:l,mode:a.mode,mtime:r})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:a.mode,mtime:r})}};function di(){console.log(`just-bash - A secure bash environment for AI agents
707
707
 
708
708
  Usage:
709
709
  just-bash [options] [script-file]