just-bash 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/chunks/awk2-4DKPX43H.js +20 -0
- package/dist/bin/chunks/chunk-NWWB2XRE.js +6 -0
- package/dist/bin/chunks/sed-LTCVBSRV.js +80 -0
- package/dist/bin/just-bash.js +72 -72
- package/dist/bin/shell/chunks/awk2-4DKPX43H.js +20 -0
- package/dist/bin/shell/chunks/chunk-NWWB2XRE.js +6 -0
- package/dist/bin/shell/chunks/sed-LTCVBSRV.js +80 -0
- package/dist/bin/shell/shell.js +97 -97
- package/dist/bundle/ai/index.js +304 -304
- package/dist/bundle/chunks/awk2-4YCQ6UCB.js +19 -0
- package/dist/bundle/chunks/chunk-CG2HXOFG.js +5 -0
- package/dist/bundle/chunks/sed-IGVS3UIY.js +79 -0
- package/dist/bundle/index.js +111 -111
- package/dist/interpreter/errors.d.ts +8 -0
- package/dist/interpreter/types.d.ts +2 -0
- package/package.json +2 -1
package/dist/bin/just-bash.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as z,b as Q,c as U,d as Y,e as K,f as k,g as W,h as he,i as B,j as We}from"./chunks/chunk-LV662IGP.js";import{a as ne}from"./chunks/chunk-4VDEBYW7.js";import"./chunks/chunk-5KNEBKYN.js";import{resolve as Is}from"node:path";var cr=[{name:"echo",load:async()=>(await import("./chunks/echo-DEUIS5JO.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-YZXBF5YF.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-BOFQVMMK.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-C4MPAF3H.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-LWULWDHP.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-XCIAYF5I.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-W6CCBEMG.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-77UY7PGN.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-TDYCNSIQ.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-DB7J2W5X.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-3G4LK462.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-X4MWD4JP.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-DPNOQY67.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-VGXR3WWL.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-YSVKBQ77.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-CNJ3QDRA.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-3PHITCPO.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-PHBFGJCV.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-PHBFGJCV.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-PHBFGJCV.js")).egrepCommand},{name:"sed",load:async()=>(await import("./chunks/sed-B6FXUN7R.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-UYU2UYZ2.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-UJP353TM.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-W4HF6YSB.js")).uniqCommand},{name:"cut",load:async()=>(await import("./chunks/cut-UYV3FM7R.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-R36J3G4K.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-2EEKHHO6.js")).trCommand},{name:"tee",load:async()=>(await import("./chunks/tee-UU2VS3OM.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-YATLECXJ.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-Y7JDBYHN.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-VLHP44TU.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-4247W67O.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-4FZ7WF2P.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-FVITWNHG.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-FVITWNHG.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-74DFXE2E.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-74DFXE2E.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-PRQ4B6N2.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-YNLVLPOF.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-JCX733LK.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-JCX733LK.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-GTCFHSB2.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-TQGTNXAE.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-TQGTNXAE.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-EYSXBSCP.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-NC7HTKLZ.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-TG2NXCX2.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-7NBRXV2Z.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-E4DIYGTT.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-OZVAGW2H.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-DGJILX2Q.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-HA2ZNL6S.js")).exprCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-L4UWMK4S.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-5V3MPCYQ.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-HX2NMOP3.js")).whichCommand}],Rs=[{name:"curl",load:async()=>(await import("./chunks/curl-NE7XEWMN.js")).curlCommand}],lr=new Map;function fr(t){return{name:t.name,async execute(e,s){let r=lr.get(t.name);return r||(r=await t.load(),lr.set(t.name,r)),r.execute(e,s)}}}function ur(t){return(t?cr.filter(s=>t.includes(s.name)):cr).map(fr)}function hr(){return Rs.map(fr)}function dr(t){return"load"in t&&typeof t.load=="function"}function pr(t){let e=null;return{name:t.name,async execute(s,r){return e||(e=await t.load()),e.execute(s,r)}}}var Ds=new TextEncoder,Os=new TextDecoder;function we(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),s=>s.charCodeAt(0));case"hex":{let s=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)s[r/2]=parseInt(t.slice(r,r+2),16);return s}case"binary":case"latin1":return Uint8Array.from(t,s=>s.charCodeAt(0));default:return Ds.encode(t)}}function Fe(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(s=>s.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return Os.decode(t)}}function ie(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Me=new TextEncoder;function _s(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var de=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[s,r]of Object.entries(e))_s(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`||"/"}dirname(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}ensureParentDirs(e){let s=this.dirname(e);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,s,r,n){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=ie(r),a=we(s,i);this.data.set(o,{type:"file",content:a,mode:n?.mode??420,mtime:n?.mtime??new Date})}async readFile(e,s){let r=await this.readFileBuffer(e),n=ie(s);return Fe(r,n)}async readFileBuffer(e){let s=this.normalizePath(e),r=this.data.get(s),n=s;if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let o=new Set;for(;r&&r.type==="symlink";){if(o.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(n),n=this.resolveSymlink(n,r.target),r=this.data.get(n)}if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return r.content instanceof Uint8Array?r.content:Me.encode(r.content)}async writeFile(e,s,r){this.writeFileSync(e,s,r)}async appendFile(e,s,r){let n=this.normalizePath(e),o=this.data.get(n);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=ie(r),a=we(s,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:Me.encode(o.content),c=new Uint8Array(l.length+a.length);c.set(l),c.set(a,l.length),this.data.set(n,{type:"file",content:c,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,s,r)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(r.type==="symlink"){let o=this.resolveSymlink(s,r.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);r=i}let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Me.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Me.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveSymlink(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(e,s){this.mkdirSync(e,s)}mkdirSync(e,s){let r=this.normalizePath(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let n=this.dirname(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let n=s==="/"?"/":`${s}/`,o=[];for(let i of this.data.keys())if(i!==s&&i.startsWith(n)){let l=i.slice(n.length).split("/")[0];l&&!o.includes(l)&&o.push(l)}return o.sort()}async rm(e,s){let r=this.normalizePath(e),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(n.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=r==="/"?`/${i}`:`${r}/${i}`;await this.rm(a,s)}}}this.data.delete(r)}async cp(e,s,r){let n=this.normalizePath(e),o=this.normalizePath(s),i=this.data.get(n);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(n);for(let l of a){let c=n==="/"?`/${l}`:`${n}/${l}`,f=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(c,f,r)}}}async mv(e,s){await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}async chmod(e,s){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);n.mode=s}async symlink(e,s){let r=this.normalizePath(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,s){let r=this.normalizePath(e),n=this.normalizePath(s),o=this.data.get(r);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}};function L(t,e){return{type:"ArithmeticExpression",expression:J(t,e,0).expr}}function J(t,e,s){return Ls(t,e,s)}function Ls(t,e,s){let{expr:r,pos:n}=ze(t,e,s);for(n=D(e,n);e[n]===",";){n++;let{expr:o,pos:i}=ze(t,e,n);r={type:"ArithBinary",operator:",",left:r,right:o},n=D(e,i)}return{expr:r,pos:n}}function ze(t,e,s){let{expr:r,pos:n}=Ts(t,e,s);if(n=D(e,n),e[n]==="?"){n++;let{expr:o,pos:i}=J(t,e,n);if(n=D(e,i),e[n]===":"){n++;let{expr:a,pos:l}=J(t,e,n);return{expr:{type:"ArithTernary",condition:r,consequent:o,alternate:a},pos:l}}}return{expr:r,pos:n}}function Ts(t,e,s){let{expr:r,pos:n}=mr(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="||";){n+=2;let{expr:o,pos:i}=mr(t,e,n);r={type:"ArithBinary",operator:"||",left:r,right:o},n=i}return{expr:r,pos:n}}function mr(t,e,s){let{expr:r,pos:n}=yr(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="&&";){n+=2;let{expr:o,pos:i}=yr(t,e,n);r={type:"ArithBinary",operator:"&&",left:r,right:o},n=i}return{expr:r,pos:n}}function yr(t,e,s){let{expr:r,pos:n}=Er(t,e,s);for(;n=D(e,n),e[n]==="|"&&e[n+1]!=="|";){n++;let{expr:o,pos:i}=Er(t,e,n);r={type:"ArithBinary",operator:"|",left:r,right:o},n=i}return{expr:r,pos:n}}function Er(t,e,s){let{expr:r,pos:n}=wr(t,e,s);for(;n=D(e,n),e[n]==="^";){n++;let{expr:o,pos:i}=wr(t,e,n);r={type:"ArithBinary",operator:"^",left:r,right:o},n=i}return{expr:r,pos:n}}function wr(t,e,s){let{expr:r,pos:n}=gr(t,e,s);for(;n=D(e,n),e[n]==="&"&&e[n+1]!=="&";){n++;let{expr:o,pos:i}=gr(t,e,n);r={type:"ArithBinary",operator:"&",left:r,right:o},n=i}return{expr:r,pos:n}}function gr(t,e,s){let{expr:r,pos:n}=Ar(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="=="||e.slice(n,n+2)==="!=";){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=Ar(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function Ar(t,e,s){let{expr:r,pos:n}=pt(t,e,s);for(;;)if(n=D(e,n),e.slice(n,n+2)==="<="||e.slice(n,n+2)===">="){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=pt(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else if(e[n]==="<"||e[n]===">"){let o=e[n];n++;let{expr:i,pos:a}=pt(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else break;return{expr:r,pos:n}}function pt(t,e,s){let{expr:r,pos:n}=xr(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="<<"||e.slice(n,n+2)===">>";){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=xr(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function xr(t,e,s){let{expr:r,pos:n}=Sr(t,e,s);for(;n=D(e,n),(e[n]==="+"||e[n]==="-")&&e[n+1]!==e[n];){let o=e[n];n++;let{expr:i,pos:a}=Sr(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function Sr(t,e,s){let{expr:r,pos:n}=Be(t,e,s);for(;;)if(n=D(e,n),e[n]==="*"&&e[n+1]!=="*"){n++;let{expr:o,pos:i}=Be(t,e,n);r={type:"ArithBinary",operator:"*",left:r,right:o},n=i}else if(e[n]==="/"||e[n]==="%"){let o=e[n];n++;let{expr:i,pos:a}=Be(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else break;return{expr:r,pos:n}}function Be(t,e,s){let{expr:r,pos:n}=mt(t,e,s),o=D(e,n);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=Be(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:r,right:i},pos:a}}return{expr:r,pos:n}}function mt(t,e,s){let r=D(e,s);if(e.slice(r,r+2)==="++"||e.slice(r,r+2)==="--"){let n=e.slice(r,r+2);r+=2;let{expr:o,pos:i}=mt(t,e,r);return{expr:{type:"ArithUnary",operator:n,operand:o,prefix:!0},pos:i}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let n=e[r];r++;let{expr:o,pos:i}=mt(t,e,r);return{expr:{type:"ArithUnary",operator:n,operand:o,prefix:!0},pos:i}}return Fs(t,e,r)}function Ws(t,e){let s=t[e];return s==="$"||s==="`"}function Fs(t,e,s){let{expr:r,pos:n}=br(t,e,s),o=[r];for(;Ws(e,n);){let{expr:i,pos:a}=br(t,e,n);o.push(i),n=a}if(o.length>1&&(r={type:"ArithConcat",parts:o}),n=D(e,n),e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let i=e.slice(n,n+2);return n+=2,{expr:{type:"ArithUnary",operator:i,operand:r,prefix:!1},pos:n}}return{expr:r,pos:n}}function br(t,e,s){let r=D(e,s);if(e.slice(r,r+3)==="$(("){r+=3;let n=1,o=r;for(;r<e.length-1&&n>0;)e[r]==="("&&e[r+1]==="("?(n++,r+=2):e[r]===")"&&e[r+1]===")"?(n--,n>0&&(r+=2)):r++;let i=e.slice(o,r),{expr:a}=J(t,i,0);return r+=2,{expr:{type:"ArithNested",expression:a},pos:r}}if(e.slice(r,r+2)==="$("&&e[r+2]!=="("){r+=2;let n=1,o=r;for(;r<e.length&&n>0;)e[r]==="("?n++:e[r]===")"&&n--,n>0&&r++;let i=e.slice(o,r);return r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="`"){r++;let n=r;for(;r<e.length&&e[r]!=="`";)r++;let o=e.slice(n,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="("){r++;let{expr:n,pos:o}=J(t,e,r);return r=D(e,o),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:n},pos:r}}if(/[0-9]/.test(e[r])){let n="",o=!1;for(;r<e.length;){let a=e[r];if(o)if(/[0-9a-zA-Z@_]/.test(a))n+=a,r++;else break;else if(a==="#")o=!0,n+=a,r++;else if(/[0-9a-fA-FxX]/.test(a))n+=a,r++;else break}if(e[r]==="."&&/[0-9]/.test(e[r+1]))throw new W(`${n}.${e[r+1]}...: syntax error: invalid arithmetic operator`);if(e[r]==="["){let a=e.slice(r).trim();return{expr:{type:"ArithNumberSubscript",number:n,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:ge(n)},pos:r}}if(e[r]==="$"&&e[r+1]==="{"){let n=r+2,o=1,i=n;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(n,i),l=i+1;if(e[l]==="#"){let c=l+1;for(;c<e.length&&/[0-9a-zA-Z@_]/.test(e[c]);)c++;let f=e.slice(l+1,c);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:f},pos:c}}if(/[0-9]/.test(e[l])||e[l]==="x"||e[l]==="X"){let c=l;if(e[l]==="x"||e[l]==="X")for(c++;c<e.length&&/[0-9a-fA-F]/.test(e[c]);)c++;else for(;c<e.length&&/[0-9]/.test(e[c]);)c++;let f=e.slice(l,c);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:f},pos:c}}return r=l,{expr:{type:"ArithBracedExpansion",content:a},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[0-9]/.test(e[r+1])){r++;let n="";for(;r<e.length&&/[0-9]/.test(e[r]);)n+=e[r],r++;return{expr:{type:"ArithVariable",name:n},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[a-zA-Z_]/.test(e[r+1])&&r++,/[a-zA-Z_]/.test(e[r])){let n="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)n+=e[r],r++;if(e[r]==="["){r++;let i;if(e[r]==="'"||e[r]==='"'){let c=e[r];for(r++,i="";r<e.length&&e[r]!==c;)i+=e[r],r++;e[r]===c&&r++,r=D(e,r),e[r]==="]"&&r++}let a;if(i===void 0){let{expr:c,pos:f}=J(t,e,r);a=c,r=f,e[r]==="]"&&r++}if(r=D(e,r),e[r]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:n,index:a},pos:r};let l=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let c of l)if(e.slice(r,r+c.length)===c&&e.slice(r,r+c.length+1)!=="=="){r+=c.length;let{expr:f,pos:h}=ze(t,e,r);return{expr:{type:"ArithAssignment",operator:c,variable:n,subscript:a,stringKey:i,value:f},pos:h}}return{expr:{type:"ArithArrayElement",array:n,index:a,stringKey:i},pos:r}}r=D(e,r);let o=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let i of o)if(e.slice(r,r+i.length)===i&&e.slice(r,r+i.length+1)!=="=="){r+=i.length;let{expr:a,pos:l}=ze(t,e,r);return{expr:{type:"ArithAssignment",operator:i,variable:n,value:a},pos:l}}return{expr:{type:"ArithVariable",name:n},pos:r}}return{expr:{type:"ArithNumber",value:0},pos:r}}function ge(t){if(t.includes("#")){let[e,s]=t.split("#"),r=Number.parseInt(e,10);if(r<2||r>64)return Number.NaN;if(r<=36)return Number.parseInt(s,r);let n=0;for(let o of s){let i;if(o>="0"&&o<="9")i=o.charCodeAt(0)-48;else if(o>="a"&&o<="z")i=o.charCodeAt(0)-97+10;else if(o>="A"&&o<="Z")i=o.charCodeAt(0)-65+36;else if(o==="@")i=62;else if(o==="_")i=63;else return Number.NaN;if(i>=r)return Number.NaN;n=n*r+i}return n}return t.startsWith("0x")||t.startsWith("0X")?Number.parseInt(t.slice(2),16):t.startsWith("0")&&t.length>1&&/^[0-9]+$/.test(t)?/[89]/.test(t)?Number.NaN:Number.parseInt(t,8):Number.parseInt(t,10)}function D(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
|
|
3
|
-
`){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var A={script(t){return{type:"Script",statements:t}},statement(t,e=[],s=!1){return{type:"Statement",pipelines:t,operators:e,background:s}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],s=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:s,redirections:r}},word(t){return{type:"Word",parts:t}},literal(t){return{type:"Literal",value:t}},singleQuoted(t){return{type:"SingleQuoted",value:t}},doubleQuoted(t){return{type:"DoubleQuoted",parts:t}},escaped(t){return{type:"Escaped",value:t}},parameterExpansion(t,e=null){return{type:"ParameterExpansion",parameter:t,operation:e}},commandSubstitution(t,e=!1){return{type:"CommandSubstitution",body:t,legacy:e}},arithmeticExpansion(t){return{type:"ArithmeticExpansion",expression:t}},assignment(t,e,s=!1,r=null){return{type:"Assignment",name:t,value:e,append:s,array:r}},redirection(t,e,s=null){return{type:"Redirection",fd:s,operator:t,target:e}},hereDoc(t,e,s=!1,r=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:s,quoted:r}},ifNode(t,e=null,s=[]){return{type:"If",clauses:t,elseBody:e,redirections:s}},forNode(t,e,s,r=[]){return{type:"For",variable:t,words:e,body:s,redirections:r}},whileNode(t,e,s=[]){return{type:"While",condition:t,body:e,redirections:s}},untilNode(t,e,s=[]){return{type:"Until",condition:t,body:e,redirections:s}},caseNode(t,e,s=[]){return{type:"Case",word:t,items:e,redirections:s}},caseItem(t,e,s=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:s}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,s=[]){return{type:"FunctionDef",name:t,body:e,redirections:s}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var u;(function(t){t.EOF="EOF",t.NEWLINE="NEWLINE",t.SEMICOLON="SEMICOLON",t.AMP="AMP",t.PIPE="PIPE",t.PIPE_AMP="PIPE_AMP",t.AND_AND="AND_AND",t.OR_OR="OR_OR",t.BANG="BANG",t.LESS="LESS",t.GREAT="GREAT",t.DLESS="DLESS",t.DGREAT="DGREAT",t.LESSAND="LESSAND",t.GREATAND="GREATAND",t.LESSGREAT="LESSGREAT",t.DLESSDASH="DLESSDASH",t.CLOBBER="CLOBBER",t.TLESS="TLESS",t.AND_GREAT="AND_GREAT",t.AND_DGREAT="AND_DGREAT",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.DSEMI="DSEMI",t.SEMI_AND="SEMI_AND",t.SEMI_SEMI_AND="SEMI_SEMI_AND",t.DBRACK_START="DBRACK_START",t.DBRACK_END="DBRACK_END",t.DPAREN_START="DPAREN_START",t.DPAREN_END="DPAREN_END",t.IF="IF",t.THEN="THEN",t.ELSE="ELSE",t.ELIF="ELIF",t.FI="FI",t.FOR="FOR",t.WHILE="WHILE",t.UNTIL="UNTIL",t.DO="DO",t.DONE="DONE",t.CASE="CASE",t.ESAC="ESAC",t.IN="IN",t.FUNCTION="FUNCTION",t.SELECT="SELECT",t.TIME="TIME",t.COPROC="COPROC",t.WORD="WORD",t.NAME="NAME",t.NUMBER="NUMBER",t.ASSIGNMENT_WORD="ASSIGNMENT_WORD",t.COMMENT="COMMENT",t.HEREDOC_CONTENT="HEREDOC_CONTENT"})(u||(u={}));var
|
|
2
|
+
import{a as z,b as Q,c as U,d as Y,e as K,f as k,g as W,h as de,i as B,j as ie,k as Fe}from"./chunks/chunk-NWWB2XRE.js";import{a as ne}from"./chunks/chunk-4VDEBYW7.js";import"./chunks/chunk-5KNEBKYN.js";import{resolve as ks}from"node:path";var lr=[{name:"echo",load:async()=>(await import("./chunks/echo-DEUIS5JO.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-YZXBF5YF.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-BOFQVMMK.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-C4MPAF3H.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-LWULWDHP.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-XCIAYF5I.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-W6CCBEMG.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-77UY7PGN.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-TDYCNSIQ.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-DB7J2W5X.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-3G4LK462.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-X4MWD4JP.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-DPNOQY67.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-VGXR3WWL.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-YSVKBQ77.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-CNJ3QDRA.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-3PHITCPO.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-PHBFGJCV.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-PHBFGJCV.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-PHBFGJCV.js")).egrepCommand},{name:"sed",load:async()=>(await import("./chunks/sed-LTCVBSRV.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-4DKPX43H.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-UJP353TM.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-W4HF6YSB.js")).uniqCommand},{name:"cut",load:async()=>(await import("./chunks/cut-UYV3FM7R.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-R36J3G4K.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-2EEKHHO6.js")).trCommand},{name:"tee",load:async()=>(await import("./chunks/tee-UU2VS3OM.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-YATLECXJ.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-Y7JDBYHN.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-VLHP44TU.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-4247W67O.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-4FZ7WF2P.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-FVITWNHG.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-FVITWNHG.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-74DFXE2E.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-74DFXE2E.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-PRQ4B6N2.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-YNLVLPOF.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-JCX733LK.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-JCX733LK.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-GTCFHSB2.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-TQGTNXAE.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-TQGTNXAE.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-EYSXBSCP.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-NC7HTKLZ.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-TG2NXCX2.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-7NBRXV2Z.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-E4DIYGTT.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-OZVAGW2H.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-DGJILX2Q.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-HA2ZNL6S.js")).exprCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-L4UWMK4S.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-5V3MPCYQ.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-HX2NMOP3.js")).whichCommand}],Ds=[{name:"curl",load:async()=>(await import("./chunks/curl-NE7XEWMN.js")).curlCommand}],fr=new Map;function ur(t){return{name:t.name,async execute(e,s){let r=fr.get(t.name);return r||(r=await t.load(),fr.set(t.name,r)),r.execute(e,s)}}}function hr(t){return(t?lr.filter(s=>t.includes(s.name)):lr).map(ur)}function dr(){return Ds.map(ur)}function pr(t){return"load"in t&&typeof t.load=="function"}function mr(t){let e=null;return{name:t.name,async execute(s,r){return e||(e=await t.load()),e.execute(s,r)}}}var Os=new TextEncoder,_s=new TextDecoder;function ge(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),s=>s.charCodeAt(0));case"hex":{let s=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)s[r/2]=parseInt(t.slice(r,r+2),16);return s}case"binary":case"latin1":return Uint8Array.from(t,s=>s.charCodeAt(0));default:return Os.encode(t)}}function Me(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(s=>s.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return _s.decode(t)}}function oe(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Be=new TextEncoder;function Ls(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var pe=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[s,r]of Object.entries(e))Ls(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`||"/"}dirname(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}ensureParentDirs(e){let s=this.dirname(e);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,s,r,n){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=oe(r),a=ge(s,i);this.data.set(o,{type:"file",content:a,mode:n?.mode??420,mtime:n?.mtime??new Date})}async readFile(e,s){let r=await this.readFileBuffer(e),n=oe(s);return Me(r,n)}async readFileBuffer(e){let s=this.normalizePath(e),r=this.data.get(s),n=s;if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let o=new Set;for(;r&&r.type==="symlink";){if(o.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(n),n=this.resolveSymlink(n,r.target),r=this.data.get(n)}if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return r.content instanceof Uint8Array?r.content:Be.encode(r.content)}async writeFile(e,s,r){this.writeFileSync(e,s,r)}async appendFile(e,s,r){let n=this.normalizePath(e),o=this.data.get(n);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=oe(r),a=ge(s,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:Be.encode(o.content),c=new Uint8Array(l.length+a.length);c.set(l),c.set(a,l.length),this.data.set(n,{type:"file",content:c,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,s,r)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(r.type==="symlink"){let o=this.resolveSymlink(s,r.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);r=i}let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Be.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Be.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveSymlink(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(e,s){this.mkdirSync(e,s)}mkdirSync(e,s){let r=this.normalizePath(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let n=this.dirname(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let n=s==="/"?"/":`${s}/`,o=[];for(let i of this.data.keys())if(i!==s&&i.startsWith(n)){let l=i.slice(n.length).split("/")[0];l&&!o.includes(l)&&o.push(l)}return o.sort()}async rm(e,s){let r=this.normalizePath(e),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(n.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=r==="/"?`/${i}`:`${r}/${i}`;await this.rm(a,s)}}}this.data.delete(r)}async cp(e,s,r){let n=this.normalizePath(e),o=this.normalizePath(s),i=this.data.get(n);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(n);for(let l of a){let c=n==="/"?`/${l}`:`${n}/${l}`,f=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(c,f,r)}}}async mv(e,s){await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}async chmod(e,s){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);n.mode=s}async symlink(e,s){let r=this.normalizePath(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,s){let r=this.normalizePath(e),n=this.normalizePath(s),o=this.data.get(r);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}};function L(t,e){return{type:"ArithmeticExpression",expression:J(t,e,0).expr}}function J(t,e,s){return Ts(t,e,s)}function Ts(t,e,s){let{expr:r,pos:n}=Ue(t,e,s);for(n=D(e,n);e[n]===",";){n++;let{expr:o,pos:i}=Ue(t,e,n);r={type:"ArithBinary",operator:",",left:r,right:o},n=D(e,i)}return{expr:r,pos:n}}function Ue(t,e,s){let{expr:r,pos:n}=Ws(t,e,s);if(n=D(e,n),e[n]==="?"){n++;let{expr:o,pos:i}=J(t,e,n);if(n=D(e,i),e[n]===":"){n++;let{expr:a,pos:l}=J(t,e,n);return{expr:{type:"ArithTernary",condition:r,consequent:o,alternate:a},pos:l}}}return{expr:r,pos:n}}function Ws(t,e,s){let{expr:r,pos:n}=yr(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="||";){n+=2;let{expr:o,pos:i}=yr(t,e,n);r={type:"ArithBinary",operator:"||",left:r,right:o},n=i}return{expr:r,pos:n}}function yr(t,e,s){let{expr:r,pos:n}=Er(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="&&";){n+=2;let{expr:o,pos:i}=Er(t,e,n);r={type:"ArithBinary",operator:"&&",left:r,right:o},n=i}return{expr:r,pos:n}}function Er(t,e,s){let{expr:r,pos:n}=wr(t,e,s);for(;n=D(e,n),e[n]==="|"&&e[n+1]!=="|";){n++;let{expr:o,pos:i}=wr(t,e,n);r={type:"ArithBinary",operator:"|",left:r,right:o},n=i}return{expr:r,pos:n}}function wr(t,e,s){let{expr:r,pos:n}=gr(t,e,s);for(;n=D(e,n),e[n]==="^";){n++;let{expr:o,pos:i}=gr(t,e,n);r={type:"ArithBinary",operator:"^",left:r,right:o},n=i}return{expr:r,pos:n}}function gr(t,e,s){let{expr:r,pos:n}=Ar(t,e,s);for(;n=D(e,n),e[n]==="&"&&e[n+1]!=="&";){n++;let{expr:o,pos:i}=Ar(t,e,n);r={type:"ArithBinary",operator:"&",left:r,right:o},n=i}return{expr:r,pos:n}}function Ar(t,e,s){let{expr:r,pos:n}=xr(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="=="||e.slice(n,n+2)==="!=";){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=xr(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function xr(t,e,s){let{expr:r,pos:n}=mt(t,e,s);for(;;)if(n=D(e,n),e.slice(n,n+2)==="<="||e.slice(n,n+2)===">="){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=mt(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else if(e[n]==="<"||e[n]===">"){let o=e[n];n++;let{expr:i,pos:a}=mt(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else break;return{expr:r,pos:n}}function mt(t,e,s){let{expr:r,pos:n}=Sr(t,e,s);for(;n=D(e,n),e.slice(n,n+2)==="<<"||e.slice(n,n+2)===">>";){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=Sr(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function Sr(t,e,s){let{expr:r,pos:n}=br(t,e,s);for(;n=D(e,n),(e[n]==="+"||e[n]==="-")&&e[n+1]!==e[n];){let o=e[n];n++;let{expr:i,pos:a}=br(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function br(t,e,s){let{expr:r,pos:n}=ze(t,e,s);for(;;)if(n=D(e,n),e[n]==="*"&&e[n+1]!=="*"){n++;let{expr:o,pos:i}=ze(t,e,n);r={type:"ArithBinary",operator:"*",left:r,right:o},n=i}else if(e[n]==="/"||e[n]==="%"){let o=e[n];n++;let{expr:i,pos:a}=ze(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else break;return{expr:r,pos:n}}function ze(t,e,s){let{expr:r,pos:n}=yt(t,e,s),o=D(e,n);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=ze(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:r,right:i},pos:a}}return{expr:r,pos:n}}function yt(t,e,s){let r=D(e,s);if(e.slice(r,r+2)==="++"||e.slice(r,r+2)==="--"){let n=e.slice(r,r+2);r+=2;let{expr:o,pos:i}=yt(t,e,r);return{expr:{type:"ArithUnary",operator:n,operand:o,prefix:!0},pos:i}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let n=e[r];r++;let{expr:o,pos:i}=yt(t,e,r);return{expr:{type:"ArithUnary",operator:n,operand:o,prefix:!0},pos:i}}return Ms(t,e,r)}function Fs(t,e){let s=t[e];return s==="$"||s==="`"}function Ms(t,e,s){let{expr:r,pos:n}=Cr(t,e,s),o=[r];for(;Fs(e,n);){let{expr:i,pos:a}=Cr(t,e,n);o.push(i),n=a}if(o.length>1&&(r={type:"ArithConcat",parts:o}),n=D(e,n),e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let i=e.slice(n,n+2);return n+=2,{expr:{type:"ArithUnary",operator:i,operand:r,prefix:!1},pos:n}}return{expr:r,pos:n}}function Cr(t,e,s){let r=D(e,s);if(e.slice(r,r+3)==="$(("){r+=3;let n=1,o=r;for(;r<e.length-1&&n>0;)e[r]==="("&&e[r+1]==="("?(n++,r+=2):e[r]===")"&&e[r+1]===")"?(n--,n>0&&(r+=2)):r++;let i=e.slice(o,r),{expr:a}=J(t,i,0);return r+=2,{expr:{type:"ArithNested",expression:a},pos:r}}if(e.slice(r,r+2)==="$("&&e[r+2]!=="("){r+=2;let n=1,o=r;for(;r<e.length&&n>0;)e[r]==="("?n++:e[r]===")"&&n--,n>0&&r++;let i=e.slice(o,r);return r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="`"){r++;let n=r;for(;r<e.length&&e[r]!=="`";)r++;let o=e.slice(n,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="("){r++;let{expr:n,pos:o}=J(t,e,r);return r=D(e,o),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:n},pos:r}}if(/[0-9]/.test(e[r])){let n="",o=!1;for(;r<e.length;){let a=e[r];if(o)if(/[0-9a-zA-Z@_]/.test(a))n+=a,r++;else break;else if(a==="#")o=!0,n+=a,r++;else if(/[0-9a-fA-FxX]/.test(a))n+=a,r++;else break}if(e[r]==="."&&/[0-9]/.test(e[r+1]))throw new W(`${n}.${e[r+1]}...: syntax error: invalid arithmetic operator`);if(e[r]==="["){let a=e.slice(r).trim();return{expr:{type:"ArithNumberSubscript",number:n,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:Ae(n)},pos:r}}if(e[r]==="$"&&e[r+1]==="{"){let n=r+2,o=1,i=n;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(n,i),l=i+1;if(e[l]==="#"){let c=l+1;for(;c<e.length&&/[0-9a-zA-Z@_]/.test(e[c]);)c++;let f=e.slice(l+1,c);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:f},pos:c}}if(/[0-9]/.test(e[l])||e[l]==="x"||e[l]==="X"){let c=l;if(e[l]==="x"||e[l]==="X")for(c++;c<e.length&&/[0-9a-fA-F]/.test(e[c]);)c++;else for(;c<e.length&&/[0-9]/.test(e[c]);)c++;let f=e.slice(l,c);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:f},pos:c}}return r=l,{expr:{type:"ArithBracedExpansion",content:a},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[0-9]/.test(e[r+1])){r++;let n="";for(;r<e.length&&/[0-9]/.test(e[r]);)n+=e[r],r++;return{expr:{type:"ArithVariable",name:n},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[a-zA-Z_]/.test(e[r+1])&&r++,/[a-zA-Z_]/.test(e[r])){let n="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)n+=e[r],r++;if(e[r]==="["){r++;let i;if(e[r]==="'"||e[r]==='"'){let c=e[r];for(r++,i="";r<e.length&&e[r]!==c;)i+=e[r],r++;e[r]===c&&r++,r=D(e,r),e[r]==="]"&&r++}let a;if(i===void 0){let{expr:c,pos:f}=J(t,e,r);a=c,r=f,e[r]==="]"&&r++}if(r=D(e,r),e[r]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:n,index:a},pos:r};let l=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let c of l)if(e.slice(r,r+c.length)===c&&e.slice(r,r+c.length+1)!=="=="){r+=c.length;let{expr:f,pos:h}=Ue(t,e,r);return{expr:{type:"ArithAssignment",operator:c,variable:n,subscript:a,stringKey:i,value:f},pos:h}}return{expr:{type:"ArithArrayElement",array:n,index:a,stringKey:i},pos:r}}r=D(e,r);let o=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let i of o)if(e.slice(r,r+i.length)===i&&e.slice(r,r+i.length+1)!=="=="){r+=i.length;let{expr:a,pos:l}=Ue(t,e,r);return{expr:{type:"ArithAssignment",operator:i,variable:n,value:a},pos:l}}return{expr:{type:"ArithVariable",name:n},pos:r}}return{expr:{type:"ArithNumber",value:0},pos:r}}function Ae(t){if(t.includes("#")){let[e,s]=t.split("#"),r=Number.parseInt(e,10);if(r<2||r>64)return Number.NaN;if(r<=36)return Number.parseInt(s,r);let n=0;for(let o of s){let i;if(o>="0"&&o<="9")i=o.charCodeAt(0)-48;else if(o>="a"&&o<="z")i=o.charCodeAt(0)-97+10;else if(o>="A"&&o<="Z")i=o.charCodeAt(0)-65+36;else if(o==="@")i=62;else if(o==="_")i=63;else return Number.NaN;if(i>=r)return Number.NaN;n=n*r+i}return n}return t.startsWith("0x")||t.startsWith("0X")?Number.parseInt(t.slice(2),16):t.startsWith("0")&&t.length>1&&/^[0-9]+$/.test(t)?/[89]/.test(t)?Number.NaN:Number.parseInt(t,8):Number.parseInt(t,10)}function D(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
|
|
3
|
+
`){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var A={script(t){return{type:"Script",statements:t}},statement(t,e=[],s=!1){return{type:"Statement",pipelines:t,operators:e,background:s}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],s=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:s,redirections:r}},word(t){return{type:"Word",parts:t}},literal(t){return{type:"Literal",value:t}},singleQuoted(t){return{type:"SingleQuoted",value:t}},doubleQuoted(t){return{type:"DoubleQuoted",parts:t}},escaped(t){return{type:"Escaped",value:t}},parameterExpansion(t,e=null){return{type:"ParameterExpansion",parameter:t,operation:e}},commandSubstitution(t,e=!1){return{type:"CommandSubstitution",body:t,legacy:e}},arithmeticExpansion(t){return{type:"ArithmeticExpansion",expression:t}},assignment(t,e,s=!1,r=null){return{type:"Assignment",name:t,value:e,append:s,array:r}},redirection(t,e,s=null){return{type:"Redirection",fd:s,operator:t,target:e}},hereDoc(t,e,s=!1,r=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:s,quoted:r}},ifNode(t,e=null,s=[]){return{type:"If",clauses:t,elseBody:e,redirections:s}},forNode(t,e,s,r=[]){return{type:"For",variable:t,words:e,body:s,redirections:r}},whileNode(t,e,s=[]){return{type:"While",condition:t,body:e,redirections:s}},untilNode(t,e,s=[]){return{type:"Until",condition:t,body:e,redirections:s}},caseNode(t,e,s=[]){return{type:"Case",word:t,items:e,redirections:s}},caseItem(t,e,s=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:s}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,s=[]){return{type:"FunctionDef",name:t,body:e,redirections:s}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var u;(function(t){t.EOF="EOF",t.NEWLINE="NEWLINE",t.SEMICOLON="SEMICOLON",t.AMP="AMP",t.PIPE="PIPE",t.PIPE_AMP="PIPE_AMP",t.AND_AND="AND_AND",t.OR_OR="OR_OR",t.BANG="BANG",t.LESS="LESS",t.GREAT="GREAT",t.DLESS="DLESS",t.DGREAT="DGREAT",t.LESSAND="LESSAND",t.GREATAND="GREATAND",t.LESSGREAT="LESSGREAT",t.DLESSDASH="DLESSDASH",t.CLOBBER="CLOBBER",t.TLESS="TLESS",t.AND_GREAT="AND_GREAT",t.AND_DGREAT="AND_DGREAT",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.DSEMI="DSEMI",t.SEMI_AND="SEMI_AND",t.SEMI_SEMI_AND="SEMI_SEMI_AND",t.DBRACK_START="DBRACK_START",t.DBRACK_END="DBRACK_END",t.DPAREN_START="DPAREN_START",t.DPAREN_END="DPAREN_END",t.IF="IF",t.THEN="THEN",t.ELSE="ELSE",t.ELIF="ELIF",t.FI="FI",t.FOR="FOR",t.WHILE="WHILE",t.UNTIL="UNTIL",t.DO="DO",t.DONE="DONE",t.CASE="CASE",t.ESAC="ESAC",t.IN="IN",t.FUNCTION="FUNCTION",t.SELECT="SELECT",t.TIME="TIME",t.COPROC="COPROC",t.WORD="WORD",t.NAME="NAME",t.NUMBER="NUMBER",t.ASSIGNMENT_WORD="ASSIGNMENT_WORD",t.COMMENT="COMMENT",t.HEREDOC_CONTENT="HEREDOC_CONTENT"})(u||(u={}));var je={if:u.IF,then:u.THEN,else:u.ELSE,elif:u.ELIF,fi:u.FI,for:u.FOR,while:u.WHILE,until:u.UNTIL,do:u.DO,done:u.DONE,case:u.CASE,esac:u.ESAC,in:u.IN,function:u.FUNCTION,select:u.SELECT,time:u.TIME,coproc:u.COPROC};function $r(t){let e=t.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!e)return!1;let s=t.slice(e[0].length);if(s===""||s==="+")return!0;if(s[0]==="["){let r=0,n=0;for(;n<s.length;n++)if(s[n]==="[")r++;else if(s[n]==="]"&&(r--,r===0))break;if(r!==0||n>=s.length)return!1;let o=s.slice(n+1);return o===""||o==="+"}return!1}var Bs=[[";",";","&",u.SEMI_SEMI_AND],["<","<","<",u.TLESS],["&",">",">",u.AND_DGREAT]],zs=[["[","[",u.DBRACK_START],["]","]",u.DBRACK_END],["(","(",u.DPAREN_START],[")",")",u.DPAREN_END],["&","&",u.AND_AND],["|","|",u.OR_OR],[";",";",u.DSEMI],[";","&",u.SEMI_AND],["|","&",u.PIPE_AMP],[">",">",u.DGREAT],["<","&",u.LESSAND],[">","&",u.GREATAND],["<",">",u.LESSGREAT],[">","|",u.CLOBBER],["&",">",u.AND_GREAT]],Us={"|":u.PIPE,"&":u.AMP,";":u.SEMICOLON,"(":u.LPAREN,")":u.RPAREN,"<":u.LESS,">":u.GREAT};function js(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var Ge=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];constructor(e){this.input=e}tokenize(){let s=this.input.length,r=this.tokens,n=this.pendingHeredocs;for(;this.pos<s&&(this.skipWhitespace(),!(this.pos>=s));){if(n.length>0&&r.length>0&&r[r.length-1].type===u.NEWLINE){this.readHeredocContent();continue}let o=this.nextToken();o&&r.push(o)}return r.push({type:u.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),r}skipWhitespace(){let e=this.input,s=e.length,r=this.pos,n=this.column,o=this.line;for(;r<s;){let i=e[r];if(i===" "||i===" ")r++,n++;else if(i==="\\"&&e[r+1]===`
|
|
4
4
|
`)r+=2,o++,n=1;else break}this.pos=r,this.column=n,this.line=o}nextToken(){let e=this.input,s=this.pos,r=this.line,n=this.column,o=e[s],i=e[s+1],a=e[s+2];if(o==="#")return this.readComment(s,r,n);if(o===`
|
|
5
5
|
`)return this.pos=s+1,this.line++,this.column=1,{type:u.NEWLINE,value:`
|
|
6
|
-
`,start:s,end:s+1,line:r,column:n};if(o==="<"&&i==="<"&&a==="-")return this.pos=s+3,this.column=n+3,this.registerHeredocFromLookahead(!0),this.makeToken(u.DLESSDASH,"<<-",s,r,n);for(let[c,f,h,d]of
|
|
6
|
+
`,start:s,end:s+1,line:r,column:n};if(o==="<"&&i==="<"&&a==="-")return this.pos=s+3,this.column=n+3,this.registerHeredocFromLookahead(!0),this.makeToken(u.DLESSDASH,"<<-",s,r,n);for(let[c,f,h,d]of Bs)if(o===c&&i===f&&a===h)return this.pos=s+3,this.column=n+3,this.makeToken(d,c+f+h,s,r,n);if(o==="<"&&i==="<")return this.pos=s+2,this.column=n+2,this.registerHeredocFromLookahead(!1),this.makeToken(u.DLESS,"<<",s,r,n);for(let[c,f,h]of zs)if(o===c&&i===f)return this.pos=s+2,this.column=n+2,this.makeToken(h,c+f,s,r,n);let l=Us[o];return l?(this.pos=s+1,this.column=n+1,this.makeToken(l,o,s,r,n)):o==="{"?i==="}"?(this.pos=s+2,this.column=n+2,{type:u.WORD,value:"{}",start:s,end:s+2,line:r,column:n,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(s)!==null?this.readWordWithBraceExpansion(s,r,n):this.scanLiteralBraceWord(s)!==null?this.readWordWithBraceExpansion(s,r,n):i!==void 0&&i!==" "&&i!==" "&&i!==`
|
|
7
7
|
`?this.readWord(s,r,n):(this.pos=s+1,this.column=n+1,this.makeToken(u.LBRACE,"{",s,r,n)):o==="}"?this.isWordCharFollowing(s+1)?this.readWord(s,r,n):(this.pos=s+1,this.column=n+1,this.makeToken(u.RBRACE,"}",s,r,n)):o==="!"?i==="="?(this.pos=s+2,this.column=n+2,this.makeToken(u.WORD,"!=",s,r,n)):(this.pos=s+1,this.column=n+1,this.makeToken(u.BANG,"!",s,r,n)):this.readWord(s,r,n)}makeToken(e,s,r,n,o){return{type:e,value:s,start:r,end:this.pos,line:n,column:o}}readComment(e,s,r){let n=this.input,o=n.length,i=this.pos;for(;i<o&&n[i]!==`
|
|
8
8
|
`;)i++;let a=n.slice(e,i);return this.pos=i,this.column=r+(i-e),{type:u.COMMENT,value:a,start:e,end:i,line:s,column:r}}readWord(e,s,r){let n=this.input,o=n.length,i=this.pos,a=i;for(;i<o;){let m=n[i];if(m===" "||m===" "||m===`
|
|
9
9
|
`||m===";"||m==="&"||m==="|"||m==="("||m===")"||m==="<"||m===">"||m==="'"||m==='"'||m==="\\"||m==="$"||m==="`"||m==="{"||m==="}"||m==="~"||m==="*"||m==="?"||m==="[")break;i++}if(i>a){let m=n[i];if(i>=o||m===" "||m===" "||m===`
|
|
10
|
-
`||m===";"||m==="&"||m==="|"||m==="("||m===")"||m==="<"||m===">"){let E=n.slice(a,i);if(this.pos=i,this.column=r+(i-a),
|
|
10
|
+
`||m===";"||m==="&"||m==="|"||m==="("||m===")"||m==="<"||m===">"){let E=n.slice(a,i);if(this.pos=i,this.column=r+(i-a),je[E])return{type:je[E],value:E,start:e,end:i,line:s,column:r};let w=E.indexOf("=");return w>0&&$r(E.slice(0,w))?{type:u.ASSIGNMENT_WORD,value:E,start:e,end:i,line:s,column:r}:/^[0-9]+$/.test(E)?{type:u.NUMBER,value:E,start:e,end:i,line:s,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)?{type:u.NAME,value:E,start:e,end:i,line:s,column:r,quoted:!1,singleQuoted:!1}:{type:u.WORD,value:E,start:e,end:i,line:s,column:r,quoted:!1,singleQuoted:!1}}}i=this.pos;let l=this.column,c=this.line,f="",h=!1,d=!1,p=!1,y=!1,g=n[i]==='"'||n[i]==="'";for(;i<o;){let m=n[i];if(!p&&!y&&(m===" "||m===" "||m===`
|
|
11
11
|
`||m===";"||m==="&"||m==="|"||m==="("||m===")"||m==="<"||m===">"))break;if(m==="$"&&i+1<o&&n[i+1]==="'"&&!p&&!y){for(f+="$'",i+=2,l+=2;i<o&&n[i]!=="'";)n[i]==="\\"&&i+1<o?(f+=n[i]+n[i+1],i+=2,l+=2):(f+=n[i],i++,l++);i<o&&(f+="'",i++,l++);continue}if(m==="$"&&i+1<o&&n[i+1]==='"'&&!p&&!y){i++,l++,y=!0,h=!0,f===""&&(g=!0),i++,l++;continue}if(m==="'"&&!y){p?(p=!1,g||(f+=m)):(p=!0,g?(d=!0,h=!0):f+=m),i++,l++;continue}if(m==='"'&&!p){y?(y=!1,g||(f+=m)):(y=!0,g?h=!0:f+=m),i++,l++;continue}if(m==="\\"&&!p&&i+1<o){let E=n[i+1];if(E===`
|
|
12
12
|
`){i+=2,c++,l=1;continue}if(y){if(E==='"'||E==="\\"||E==="$"||E==="`"||E===`
|
|
13
|
-
`){E==="$"||E==="`"?f+=m+E:f+=E,i+=2,l+=2;continue}}else{E==='"'||E==="'"?f+=m+E:f+=E,i+=2,l+=2;continue}}if(m==="$"&&i+1<o&&n[i+1]==="("){f+=m,i++,l++,f+=n[i],i++,l++;let E=1,w=!1,b=!1,P=0,I=!1,R="",
|
|
13
|
+
`){E==="$"||E==="`"?f+=m+E:f+=E,i+=2,l+=2;continue}}else{E==='"'||E==="'"?f+=m+E:f+=E,i+=2,l+=2;continue}}if(m==="$"&&i+1<o&&n[i+1]==="("){f+=m,i++,l++,f+=n[i],i++,l++;let E=1,w=!1,b=!1,P=0,I=!1,R="",he=n[i]==="(";for(;E>0&&i<o;){let _=n[i];if(f+=_,w)_==="'"&&(w=!1);else if(b)_==="\\"&&i+1<o?(f+=n[i+1],i++,l++):_==='"'&&(b=!1);else if(_==="'")w=!0,R="";else if(_==='"')b=!0,R="";else if(_==="\\"&&i+1<o)f+=n[i+1],i++,l++,R="";else if(_==="#"&&!he&&(R===""||/\s/.test(n[i-1]||""))){for(;i+1<o&&n[i+1]!==`
|
|
14
14
|
`;)i++,l++,f+=n[i];R=""}else/[a-zA-Z_]/.test(_)?R+=_:(R==="case"?(P++,I=!1):R==="in"&&P>0?I=!0:R==="esac"&&P>0&&(P--,I=!1),R="",_==="("?i>0&&n[i-1]==="$"?E++:I||E++:_===")"?I?I=!1:E--:_===";"&&P>0&&i+1<o&&n[i+1]===";"&&(I=!0));_===`
|
|
15
15
|
`&&(c++,l=0,R=""),i++,l++}continue}if(m==="$"&&i+1<o&&n[i+1]==="["){f+=m,i++,l++,f+=n[i],i++,l++;let E=1;for(;E>0&&i<o;){let w=n[i];f+=w,w==="["?E++:w==="]"?E--:w===`
|
|
16
16
|
`&&(c++,l=0),i++,l++}continue}if(m==="$"&&i+1<o&&n[i+1]==="{"){f+=m,i++,l++,f+=n[i],i++,l++;let E=1;for(;E>0&&i<o;){let w=n[i];f+=w,w==="{"?E++:w==="}"?E--:w===`
|
|
17
17
|
`&&(c++,l=0),i++,l++}continue}if(m==="$"&&i+1<o){let E=n[i+1];if(E==="#"||E==="?"||E==="$"||E==="!"||E==="@"||E==="*"||E==="-"||E>="0"&&E<="9"){f+=m+E,i+=2,l+=2;continue}}if(m==="`"){for(f+=m,i++,l++;i<o&&n[i]!=="`";){let E=n[i];f+=E,E==="\\"&&i+1<o&&(f+=n[i+1],i++,l++),E===`
|
|
18
18
|
`&&(c++,l=0),i++,l++}i<o&&(f+=n[i],i++,l++);continue}f+=m,i++,m===`
|
|
19
|
-
`?(c++,l=1):l++}if(this.pos=i,this.column=l,this.line=c,f==="")return{type:u.WORD,value:"",start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d};if(!h&&
|
|
19
|
+
`?(c++,l=1):l++}if(this.pos=i,this.column=l,this.line=c,f==="")return{type:u.WORD,value:"",start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d};if(!h&&je[f])return{type:je[f],value:f,start:e,end:i,line:s,column:r};if(!g){let m=f.indexOf("=");if(m>0&&$r(f.slice(0,m)))return{type:u.ASSIGNMENT_WORD,value:f,start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d}}return/^[0-9]+$/.test(f)?{type:u.NUMBER,value:f,start:e,end:i,line:s,column:r}:js(f)?{type:u.NAME,value:f,start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d}:{type:u.WORD,value:f,start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let s=this.pos,r=this.line,n=this.column,o="";for(;this.pos<this.input.length;){let i=this.pos,a="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
|
|
20
20
|
`;)a+=this.input[this.pos],this.pos++,this.column++;if((e.stripTabs?a.replace(/^\t+/,""):a)===e.delimiter){this.pos<this.input.length&&this.input[this.pos]===`
|
|
21
21
|
`&&(this.pos++,this.line++,this.column=1);break}o+=a,this.pos<this.input.length&&this.input[this.pos]===`
|
|
22
22
|
`&&(o+=`
|
|
@@ -24,46 +24,46 @@ import{a as z,b as Q,c as U,d as Y,e as K,f as k,g as W,h as he,i as B,j as We}f
|
|
|
24
24
|
`||s===";"||s==="&"||s==="|"||s==="("||s===")"||s==="<"||s===">")}readWordWithBraceExpansion(e,s,r){let n=this.input,o=n.length,i=e,a=r;for(;i<o;){let c=n[i];if(c===" "||c===" "||c===`
|
|
25
25
|
`||c===";"||c==="&"||c==="|"||c==="("||c===")"||c==="<"||c===">")break;if(c==="{"){if(this.scanBraceExpansion(i)!==null){let h=1;for(i++,a++;i<o&&h>0;)n[i]==="{"?h++:n[i]==="}"&&h--,i++,a++;continue}i++,a++;continue}if(c==="}"){i++,a++;continue}if(c==="$"&&i+1<o&&n[i+1]==="("){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)n[i]==="("?f++:n[i]===")"&&f--,i++,a++;continue}if(c==="$"&&i+1<o&&n[i+1]==="{"){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)n[i]==="{"?f++:n[i]==="}"&&f--,i++,a++;continue}if(c==="`"){for(i++,a++;i<o&&n[i]!=="`";)n[i]==="\\"&&i+1<o?(i+=2,a+=2):(i++,a++);i<o&&(i++,a++);continue}i++,a++}let l=n.slice(e,i);return this.pos=i,this.column=a,{type:u.WORD,value:l,start:e,end:i,line:s,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let s=this.input,r=s.length,n=e+1,o=1,i=!1,a=!1;for(;n<r&&o>0;){let l=s[n];if(l==="{")o++,n++;else if(l==="}")o--,n++;else if(l===","&&o===1)i=!0,n++;else if(l==="."&&n+1<r&&s[n+1]===".")a=!0,n+=2;else{if(l===" "||l===" "||l===`
|
|
26
26
|
`||l===";"||l==="&"||l==="|")return null;n++}}return o===0&&(i||a)?s.slice(e,n):null}scanLiteralBraceWord(e){let s=this.input,r=s.length,n=e+1,o=1;for(;n<r&&o>0;){let i=s[n];if(i==="{")o++,n++;else if(i==="}"){if(o--,o===0)return s.slice(e,n+1);n++}else{if(i===" "||i===" "||i===`
|
|
27
|
-
`||i===";"||i==="&"||i==="|")return null;n++}}return null}};var
|
|
28
|
-
`,n+=2;break;case"t":r+=" ",n+=2;break;case"r":r+="\r",n+=2;break;case"\\":r+="\\",n+=2;break;case"'":r+="'",n+=2;break;case'"':r+='"',n+=2;break;case"a":r+="\x07",n+=2;break;case"b":r+="\b",n+=2;break;case"e":case"E":r+="\x1B",n+=2;break;case"f":r+="\f",n+=2;break;case"v":r+="\v",n+=2;break;case"x":{let a=e.slice(n+2,n+4),l=parseInt(a,16);Number.isNaN(l)?(r+="\\x",n+=2):(r+=String.fromCharCode(l),n+=4);break}case"u":{let a=e.slice(n+2,n+6),l=parseInt(a,16);Number.isNaN(l)?(r+="\\u",n+=2):(r+=String.fromCharCode(l),n+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",l=n+1;for(;l<e.length&&l<n+4&&/[0-7]/.test(e[l]);)a+=e[l],l++;let c=parseInt(a,8);r+=String.fromCharCode(c),n=l;break}default:r+=o,n++}else r+=o,n++}return n<e.length&&e[n]==="'"&&n++,{part:A.literal(r),endIndex:n}}function gt(t,e){let s=e.trim();return s===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:L(t,s)}function Ir(t){let e=[],s="",r=0;for(let n=0;n<t.length;n++){let o=t[n];o==="{"?(r++,s+=o):o==="}"?(r--,s+=o):o===","&&r===0?(e.push(s),s=""):s+=o}return e.push(s),e}function _r(t,e,s,r){let n=wt(t,e,s,"{","}");if(n===-1)return null;let o=e.slice(s+1,n),i=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(i)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:n+1};let a=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:n+1}:o.includes(",")&&r?{part:{type:"BraceExpansion",items:Ir(o).map(f=>({type:"Word",word:A.word(r(t,f,!1,!1,!1))}))},endIndex:n+1}:o.includes(",")?{part:{type:"BraceExpansion",items:Ir(o).map(f=>({type:"Word",word:A.word([A.literal(f)])}))},endIndex:n+1}:null}function Lr(t,e){let s="";for(let r of e.parts)switch(r.type){case"Literal":case"SingleQuoted":case"Escaped":s+=r.value;break;case"DoubleQuoted":s+='"';for(let n of r.parts)n.type==="Literal"||n.type==="Escaped"?s+=n.value:n.type==="ParameterExpansion"&&(s+=`\${${n.parameter}}`);s+='"';break;case"ParameterExpansion":s+=`\${${r.parameter}}`;break;case"Glob":s+=r.pattern;break;default:s+=r.type}return s}function Tr(t,e){return{[u.LESS]:"<",[u.GREAT]:">",[u.DGREAT]:">>",[u.LESSAND]:"<&",[u.GREATAND]:">&",[u.LESSGREAT]:"<>",[u.CLOBBER]:">|",[u.TLESS]:"<<<",[u.AND_GREAT]:"&>",[u.AND_DGREAT]:"&>>",[u.DLESS]:"<",[u.DLESSDASH]:"<"}[e]||">"}function Ge(t){let e=t.current(),s=e.type;if(s===u.NUMBER){let r=t.peek(1);return e.end!==r.start?!1:Pr.has(r.type)}return vr.has(s)}function Ve(t){let e=null;t.check(u.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let s=t.advance(),r=Tr(t,s.type);if(s.type===u.DLESS||s.type===u.DLESSDASH)return Gs(t,r,e,s.type===u.DLESSDASH);t.isWord()||t.error("Expected redirection target");let n=t.parseWord();return A.redirection(r,n,e)}function Gs(t,e,s,r){t.isWord()||t.error("Expected here-document delimiter");let n=t.advance(),o=n.value,i=n.quoted||!1;(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1));let a=A.redirection(r?"<<-":"<<",A.hereDoc(o,A.word([]),r,i),s);return t.addPendingHeredoc(a,o,r,i),a}function Fr(t){let e=[],s=null,r=[],n=[];for(;t.check(u.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(Vs(t));for(;Ge(t);)t.checkIterationLimit(),n.push(Ve(t));for(t.isWord()&&(s=t.parseWord());(!t.isStatementEnd()||t.check(u.RBRACE))&&!t.check(u.PIPE,u.PIPE_AMP);)if(t.checkIterationLimit(),Ge(t))n.push(Ve(t));else if(t.check(u.RBRACE)){let o=t.advance();r.push(t.parseWordFromString(o.value,!1,!1))}else if(t.isWord())r.push(t.parseWord());else if(t.check(u.ASSIGNMENT_WORD)){let o=t.advance(),i=o.value,a=i.endsWith("="),l=i.endsWith("=(");if((a||l)&&(l||t.check(u.LPAREN))){let c=l?i.slice(0,-2):i.slice(0,-1);l||t.expect(u.LPAREN);let f=At(t);t.expect(u.RPAREN);let h=f.map(p=>Lr(t,p)),d=`${c}=(${h.join(" ")})`;r.push(t.parseWordFromString(d,!1,!1))}else r.push(t.parseWordFromString(i,o.quoted,o.singleQuoted))}else if(t.check(u.LPAREN))t.error("syntax error near unexpected token `('");else break;return A.simpleCommand(s,r,e,n)}function Vs(t){let e=t.expect(u.ASSIGNMENT_WORD),s=e.value,r=s.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||t.error(`Invalid assignment: ${s}`);let n=r[0],o,i=n.length;if(s[i]==="["){let h=0,d=i+1;for(;i<s.length;i++)if(s[i]==="[")h++;else if(s[i]==="]"&&(h--,h===0))break;h!==0&&t.error(`Invalid assignment: ${s}`),o=s.slice(d,i),i++}let a=s[i]==="+";a&&i++,s[i]!=="="&&t.error(`Invalid assignment: ${s}`),i++;let l=s.slice(i);if(l==="("){let h=At(t);t.expect(u.RPAREN);let d=o!==void 0?`${n}[${o}]`:n;return A.assignment(d,null,a,h)}if(l===""&&t.check(u.LPAREN)){let h=t.current();if(e.end===h.start){t.advance();let d=At(t);t.expect(u.RPAREN);let p=o!==void 0?`${n}[${o}]`:n;return A.assignment(p,null,a,d)}}let c=l?t.parseWordFromString(l,e.quoted,e.singleQuoted,!0):null,f=o!==void 0?`${n}[${o}]`:n;return A.assignment(f,c,a,null)}function At(t){let e=[];for(t.skipNewlines();!t.check(u.RPAREN,u.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function xt(t){t.expect(u.IF);let e=[],s=t.parseCompoundList();t.expect(u.THEN);let r=t.parseCompoundList();if(r.length===0){let i=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${i}'`)}for(e.push({condition:s,body:r});t.check(u.ELIF);){t.advance();let i=t.parseCompoundList();t.expect(u.THEN);let a=t.parseCompoundList();if(a.length===0){let l=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${l}'`)}e.push({condition:i,body:a})}let n=null;t.check(u.ELSE)&&(t.advance(),n=t.parseCompoundList(),n.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(u.FI);let o=t.parseOptionalRedirections();return A.ifNode(e,n,o)}function St(t){if(t.expect(u.FOR),t.check(u.DPAREN_START))return Zs(t);t.isWord()||t.error("Expected variable name in for loop");let s=t.advance().value,r=null;if(t.skipNewlines(),t.check(u.IN))for(t.advance(),r=[];!t.check(u.SEMICOLON,u.NEWLINE,u.DO,u.EOF)&&t.isWord();)r.push(t.parseWord());t.check(u.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(u.DO);let n=t.parseCompoundList();t.expect(u.DONE);let o=t.parseOptionalRedirections();return A.forNode(s,r,n,o)}function Zs(t){t.expect(u.DPAREN_START);let e=null,s=null,r=null,n=["","",""],o=0,i=0;for(;!t.check(u.DPAREN_END,u.EOF);){let c=t.advance();if(c.type===u.SEMICOLON&&i===0){if(o++,o>2)break}else c.value==="("&&i++,c.value===")"&&i--,n[o]+=c.value}t.expect(u.DPAREN_END),n[0].trim()&&(e=L(t,n[0].trim())),n[1].trim()&&(s=L(t,n[1].trim())),n[2].trim()&&(r=L(t,n[2].trim())),t.skipNewlines(),t.check(u.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(u.DO);let a=t.parseCompoundList();t.expect(u.DONE);let l=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:s,update:r,body:a,redirections:l}}function bt(t){t.expect(u.WHILE);let e=t.parseCompoundList();t.expect(u.DO);let s=t.parseCompoundList();s.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.whileNode(e,s,r)}function Ct(t){t.expect(u.UNTIL);let e=t.parseCompoundList();t.expect(u.DO);let s=t.parseCompoundList();s.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.untilNode(e,s,r)}function Nt(t){t.expect(u.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(u.IN),t.skipNewlines();let s=[];for(;!t.check(u.ESAC,u.EOF);){t.checkIterationLimit();let n=t.getPos(),o=qs(t);if(o&&s.push(o),t.skipNewlines(),t.getPos()===n&&!o)break}t.expect(u.ESAC);let r=t.parseOptionalRedirections();return A.caseNode(e,s,r)}function qs(t){t.check(u.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(u.PIPE));)t.advance();if(e.length===0)return null;t.expect(u.RPAREN),t.skipNewlines();let s=[];for(;!t.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND,u.ESAC,u.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===u.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(u.LPAREN)&&t.peek(1).type===u.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let n=t.getPos(),o=t.parseStatement();if(o&&s.push(o),t.skipSeparators(!1),t.getPos()===n&&!o)break}let r=";;";return t.check(u.DSEMI)?(t.advance(),r=";;"):t.check(u.SEMI_AND)?(t.advance(),r=";&"):t.check(u.SEMI_SEMI_AND)&&(t.advance(),r=";;&"),A.caseItem(e,s,r)}function $t(t){t.peek(1).type,u.LPAREN,t.expect(u.LPAREN),t.check(u.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(u.RPAREN);let s=t.parseOptionalRedirections();return A.subshell(e,s)}function vt(t){t.expect(u.LBRACE);let e=t.parseCompoundList();t.expect(u.RBRACE);let s=t.parseOptionalRedirections();return A.group(e,s)}var Ks=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],Xs=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function It(t){return t.skipNewlines(),Ys(t)}function Ys(t){let e=Mr(t);for(t.skipNewlines();t.check(u.OR_OR);){t.advance(),t.skipNewlines();let s=Mr(t);e={type:"CondOr",left:e,right:s},t.skipNewlines()}return e}function Mr(t){let e=Pt(t);for(t.skipNewlines();t.check(u.AND_AND);){t.advance(),t.skipNewlines();let s=Pt(t);e={type:"CondAnd",left:e,right:s},t.skipNewlines()}return e}function Pt(t){return t.skipNewlines(),t.check(u.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:Pt(t)}):Js(t)}function Js(t){if(t.check(u.LPAREN)){t.advance();let e=It(t);return t.expect(u.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),s=e.value;if(Ks.includes(s)&&!e.quoted&&(t.advance(),t.check(u.DBRACK_END)&&t.error(`Expected operand after ${s}`),t.isWord())){let n=t.parseWord();return{type:"CondUnary",operator:s,operand:n}}let r=t.parseWord();if(t.isWord()&&Xs.includes(t.current().value)){let n=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:n,left:r,right:o}}if(t.check(u.LESS)){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:"<",left:r,right:n}}if(t.check(u.GREAT)){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:">",left:r,right:n}}if(t.isWord()&&t.current().value==="="){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:"==",left:r,right:n}}return{type:"CondWord",word:r}}t.error("Expected conditional expression")}function tn(t,e,s){let r=s+1,n=e[r];if("@*#?$!-0123456789".includes(n))return{part:A.parameterExpansion(n),endIndex:r+1};let o="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)o+=e[r],r++;return{part:A.parameterExpansion(o),endIndex:r}}function rn(t,e,s,r=!1){let n=s+2,o=!1;e[n]==="!"&&(o=!0,n++);let i=!1;e[n]==="#"&&!/[}:#%/^,]/.test(e[n+1]||"}")&&(i=!0,n++);let a="",l=e[n];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(e[n+1]||""))a=l,n++;else for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)a+=e[n],n++;if(e[n]==="["){let f=wt(t,e,n,"[","]");a+=e.slice(n,f+1),n=f+1}a===""&&!o&&!i&&e[n]!=="}"&&t.error(`\${${e[n]}}: bad substitution`);let c=null;if(o){let f=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(f)c={type:"ArrayKeys",array:f[1],star:f[2]==="*"},a="";else if(e[n]==="*"||e[n]==="@"){let h=e[n];n++,c={type:"VarNamePrefix",prefix:a,star:h==="*"},a=""}else c={type:"Indirection"}}else if(i)if(e[n]===":")for(c={type:"LengthSliceError"};n<e.length&&e[n]!=="}";)n++;else e[n]!=="}"&&/[-+=?]/.test(e[n])?t.error(`\${#${a}${e.slice(n,e.indexOf("}",n))}}: bad substitution`):c={type:"Length"};if(!c&&n<e.length&&e[n]!=="}"){let f=sn(t,e,n,a,r);c=f.operation,n=f.endIndex}if(n<e.length&&e[n]!=="}"){let f=e[n];if(!/[:\-+=?#%/^,@[]/.test(f)){let h=n;for(;h<e.length&&e[h]!=="}";)h++;let d=e.slice(s,h+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;n<e.length&&e[n]!=="}";)n++;return{part:A.parameterExpansion(a,c),endIndex:n+1}}function sn(t,e,s,r,n=!1){let o=s,i=e[o],a=e[o+1]||"";if(i===":"){let l=a;if("-=?+".includes(l)){o+=2;let E=pe(t,e,o),w=e.slice(o,E),b=oe(t,w,!1,!1,!0,!1,n),P=A.word(b.length>0?b:[A.literal("")]);if(l==="-")return{operation:{type:"DefaultValue",word:P,checkEmpty:!0},endIndex:E};if(l==="=")return{operation:{type:"AssignDefault",word:P,checkEmpty:!0},endIndex:E};if(l==="?")return{operation:{type:"ErrorIfUnset",word:P,checkEmpty:!0},endIndex:E};if(l==="+")return{operation:{type:"UseAlternative",word:P,checkEmpty:!0},endIndex:E}}o++;let c=pe(t,e,o),f=e.slice(o,c),h=-1,d=0,p=0;for(let m=0;m<f.length;m++){let E=f[m];if(E==="("||E==="[")d++;else if(E===")"||E==="]")d--;else if(E==="?"&&d===0)p++;else if(E===":"&&d===0)if(p>0)p--;else{h=m;break}}let y=h>=0?f.slice(0,h):f,g=h>=0?f.slice(h+1):null;return{operation:{type:"Substring",offset:gt(t,y),length:g?gt(t,g):null},endIndex:c}}if("-=?+".includes(i)){o++;let l=pe(t,e,o),c=e.slice(o,l),f=oe(t,c,!1,!1,!0,!1,n),h=A.word(f.length>0?f:[A.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:h,checkEmpty:!1},endIndex:l};if(i==="=")return{operation:{type:"AssignDefault",word:h,checkEmpty:!1},endIndex:l};if(i==="?")return{operation:{type:"ErrorIfUnset",word:c?h:null,checkEmpty:!1},endIndex:l};if(i==="+")return{operation:{type:"UseAlternative",word:h,checkEmpty:!1},endIndex:l}}if(i==="#"||i==="%"){let l=a===i,c=i==="#"?"prefix":"suffix";o+=l?2:1;let f=pe(t,e,o),h=e.slice(o,f),d=oe(t,h,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:A.word(d.length>0?d:[A.literal("")]),side:c,greedy:l},endIndex:f}}if(i==="/"){let l=a==="/";o+=l?2:1;let c=null;e[o]==="#"?(c="start",o++):e[o]==="%"&&(c="end",o++);let f=Rr(t,e,o),h=e.slice(o,f),d=oe(t,h,!1,!1,!1),p=A.word(d.length>0?d:[A.literal("")]),y=null,g=f;if(e[f]==="/"){let m=f+1,E=pe(t,e,m),w=e.slice(m,E),b=oe(t,w,!1,!1,!1);y=A.word(b.length>0?b:[A.literal("")]),g=E}return{operation:{type:"PatternReplacement",pattern:p,replacement:y,all:l,anchor:c},endIndex:g}}if(i==="^"||i===","){let l=a===i,c=i==="^"?"upper":"lower";o+=l?2:1;let f=pe(t,e,o),h=e.slice(o,f),d=h?A.word([A.literal(h)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:d},endIndex:f}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function kt(t,e,s,r=!1){let n=s+1;if(n>=e.length)return{part:A.literal("$"),endIndex:n};let o=e[n];if(o==="("&&e[n+1]==="(")return t.parseArithmeticExpansion(e,s);if(o==="["){let i=1,a=n+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let l=e.slice(n+1,a),c=L(t,l);return{part:A.arithmeticExpansion(c),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,s):o==="{"?rn(t,e,s,r):/[a-zA-Z_0-9@*#?$!-]/.test(o)?tn(t,e,s):{part:A.literal("$"),endIndex:n}}function nn(t,e){let s=[],r=0,n="",o=()=>{n&&(s.push(A.literal(n)),n="")};for(;r<e.length;){let i=e[r];if(i==="\\"&&r+1<e.length){let a=e[r+1];if(a==="$"||a==="`"){n+=a,r+=2;continue}n+=i,r++;continue}if(i==="$"){o();let{part:a,endIndex:l}=kt(t,e,r,!0);a&&s.push(a),r=l;continue}if(i==="`"){o();let{part:a,endIndex:l}=t.parseBacktickSubstitution(e,r,!0);s.push(a),r=l;continue}n+=i,r++}return o(),s}function on(t,e,s){let r=[],n=s,o="",i=()=>{o&&(r.push(A.literal(o)),o="")};for(;n<e.length&&e[n]!=='"';){let a=e[n];if(a==="\\"&&n+1<e.length){let l=e[n+1];if('"\\$`\n'.includes(l)){o+=l,n+=2;continue}o+=a,n++;continue}if(a==="$"){i();let{part:l,endIndex:c}=kt(t,e,n,!0);l&&r.push(l),n=c;continue}if(a==="`"){i();let{part:l,endIndex:c}=t.parseBacktickSubstitution(e,n,!0);r.push(l),n=c;continue}o+=a,n++}return i(),{part:A.doubleQuoted(r),endIndex:n}}function oe(t,e,s=!1,r=!1,n=!1,o=!1,i=!1){if(r)return[A.singleQuoted(e)];if(s){let h=nn(t,e);return[A.doubleQuoted(h)]}let a=[],l=0,c="",f=()=>{c&&(a.push(A.literal(c)),c="")};for(;l<e.length;){let h=e[l];if(h==="\\"&&l+1<e.length){let d=e[l+1];(o?d==="$"||d==="`"||d==="\\"||d===`
|
|
27
|
+
`||i===";"||i==="&"||i==="|")return null;n++}}return null}};var Et=1e6,wt=1e5,vr=1e6,Pr=new Set([u.LESS,u.GREAT,u.DLESS,u.DGREAT,u.LESSAND,u.GREATAND,u.LESSGREAT,u.DLESSDASH,u.CLOBBER,u.TLESS,u.AND_GREAT,u.AND_DGREAT]),Ir=new Set([u.LESS,u.GREAT,u.DLESS,u.DGREAT,u.LESSAND,u.GREATAND,u.LESSGREAT,u.DLESSDASH,u.CLOBBER,u.TLESS]),ee=class extends Error{line;column;token;constructor(e,s,r,n=void 0){super(`Parse error at ${s}:${r}: ${e}`),this.line=s,this.column=r,this.token=n,this.name="ParseException"}};function Rr(t,e,s){let r=s+1;for(;r<e.length&&/[a-zA-Z0-9_-]/.test(e[r]);)r++;return r}function gt(t,e,s,r,n){let o=1,i=s+1;for(;i<e.length&&o>0;)e[i]===r?o++:e[i]===n&&o--,o>0&&i++;return o===0?i:-1}function me(t,e,s){let r=s,n=1;for(;r<e.length&&n>0;){let o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o==="'"){let i=e.indexOf("'",r+1);if(i!==-1){r=i+1;continue}}if(o==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}o==="{"?n++:o==="}"&&n--,n>0&&r++}return r}function Dr(t,e,s){let r=s,n=!1;for(;r<e.length;){let o=e[r];if(o==="/"&&n||o==="}")break;if(o==="'"){let i=e.indexOf("'",r+1);if(i!==-1){r=i+1,n=!0;continue}}if(o==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++,n=!0;continue}o==="\\"?(r+=2,n=!0):(r++,n=!0)}return r}function Or(t,e,s){let r=s,n="";for(;r<e.length;){let o=e[r];if(o==="*"||o==="?")n+=o,r++;else if(o==="["){let i=Gs(e,r);i===-1?(n+=o,r++):(n+=e.slice(r,i+1),r=i+1)}else break}return{pattern:n,endIndex:r}}function Gs(t,e){let s=e+1;for(s<t.length&&t[s]==="^"&&s++,s<t.length&&t[s]==="]"&&s++;s<t.length;){let r=t[s];if(r==="\\"&&s+1<t.length){s+=2;continue}if(r==="]")return s;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let n=t.indexOf("'",s+1);if(n!==-1){s=n+1;continue}}if(r==="["&&s+1<t.length&&t[s+1]===":"){let n=t.indexOf(":]",s+2);if(n!==-1){s=n+2;continue}}if(r==="["&&s+1<t.length&&(t[s+1]==="."||t[s+1]==="=")){let o=`${t[s+1]}]`,i=t.indexOf(o,s+2);if(i!==-1){s=i+2;continue}}s++}return-1}function _r(t,e,s){let r="",n=s;for(;n<e.length&&e[n]!=="'";){let o=e[n];if(o==="\\"&&n+1<e.length)switch(e[n+1]){case"n":r+=`
|
|
28
|
+
`,n+=2;break;case"t":r+=" ",n+=2;break;case"r":r+="\r",n+=2;break;case"\\":r+="\\",n+=2;break;case"'":r+="'",n+=2;break;case'"':r+='"',n+=2;break;case"a":r+="\x07",n+=2;break;case"b":r+="\b",n+=2;break;case"e":case"E":r+="\x1B",n+=2;break;case"f":r+="\f",n+=2;break;case"v":r+="\v",n+=2;break;case"x":{let a=e.slice(n+2,n+4),l=parseInt(a,16);Number.isNaN(l)?(r+="\\x",n+=2):(r+=String.fromCharCode(l),n+=4);break}case"u":{let a=e.slice(n+2,n+6),l=parseInt(a,16);Number.isNaN(l)?(r+="\\u",n+=2):(r+=String.fromCharCode(l),n+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",l=n+1;for(;l<e.length&&l<n+4&&/[0-7]/.test(e[l]);)a+=e[l],l++;let c=parseInt(a,8);r+=String.fromCharCode(c),n=l;break}default:r+=o,n++}else r+=o,n++}return n<e.length&&e[n]==="'"&&n++,{part:A.literal(r),endIndex:n}}function At(t,e){let s=e.trim();return s===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:L(t,s)}function kr(t){let e=[],s="",r=0;for(let n=0;n<t.length;n++){let o=t[n];o==="{"?(r++,s+=o):o==="}"?(r--,s+=o):o===","&&r===0?(e.push(s),s=""):s+=o}return e.push(s),e}function Lr(t,e,s,r){let n=gt(t,e,s,"{","}");if(n===-1)return null;let o=e.slice(s+1,n),i=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(i)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:n+1};let a=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:n+1}:o.includes(",")&&r?{part:{type:"BraceExpansion",items:kr(o).map(f=>({type:"Word",word:A.word(r(t,f,!1,!1,!1))}))},endIndex:n+1}:o.includes(",")?{part:{type:"BraceExpansion",items:kr(o).map(f=>({type:"Word",word:A.word([A.literal(f)])}))},endIndex:n+1}:null}function Tr(t,e){let s="";for(let r of e.parts)switch(r.type){case"Literal":case"SingleQuoted":case"Escaped":s+=r.value;break;case"DoubleQuoted":s+='"';for(let n of r.parts)n.type==="Literal"||n.type==="Escaped"?s+=n.value:n.type==="ParameterExpansion"&&(s+=`\${${n.parameter}}`);s+='"';break;case"ParameterExpansion":s+=`\${${r.parameter}}`;break;case"Glob":s+=r.pattern;break;default:s+=r.type}return s}function Wr(t,e){return{[u.LESS]:"<",[u.GREAT]:">",[u.DGREAT]:">>",[u.LESSAND]:"<&",[u.GREATAND]:">&",[u.LESSGREAT]:"<>",[u.CLOBBER]:">|",[u.TLESS]:"<<<",[u.AND_GREAT]:"&>",[u.AND_DGREAT]:"&>>",[u.DLESS]:"<",[u.DLESSDASH]:"<"}[e]||">"}function He(t){let e=t.current(),s=e.type;if(s===u.NUMBER){let r=t.peek(1);return e.end!==r.start?!1:Ir.has(r.type)}return Pr.has(s)}function Ve(t){let e=null;t.check(u.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let s=t.advance(),r=Wr(t,s.type);if(s.type===u.DLESS||s.type===u.DLESSDASH)return Hs(t,r,e,s.type===u.DLESSDASH);t.isWord()||t.error("Expected redirection target");let n=t.parseWord();return A.redirection(r,n,e)}function Hs(t,e,s,r){t.isWord()||t.error("Expected here-document delimiter");let n=t.advance(),o=n.value,i=n.quoted||!1;(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1));let a=A.redirection(r?"<<-":"<<",A.hereDoc(o,A.word([]),r,i),s);return t.addPendingHeredoc(a,o,r,i),a}function Mr(t){let e=[],s=null,r=[],n=[];for(;t.check(u.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(Vs(t));for(;He(t);)t.checkIterationLimit(),n.push(Ve(t));for(t.isWord()&&(s=t.parseWord());(!t.isStatementEnd()||t.check(u.RBRACE))&&!t.check(u.PIPE,u.PIPE_AMP);)if(t.checkIterationLimit(),He(t))n.push(Ve(t));else if(t.check(u.RBRACE)){let o=t.advance();r.push(t.parseWordFromString(o.value,!1,!1))}else if(t.isWord())r.push(t.parseWord());else if(t.check(u.ASSIGNMENT_WORD)){let o=t.advance(),i=o.value,a=i.endsWith("="),l=i.endsWith("=(");if((a||l)&&(l||t.check(u.LPAREN))){let c=l?i.slice(0,-2):i.slice(0,-1);l||t.expect(u.LPAREN);let f=xt(t);t.expect(u.RPAREN);let h=f.map(p=>Tr(t,p)),d=`${c}=(${h.join(" ")})`;r.push(t.parseWordFromString(d,!1,!1))}else r.push(t.parseWordFromString(i,o.quoted,o.singleQuoted))}else if(t.check(u.LPAREN))t.error("syntax error near unexpected token `('");else break;return A.simpleCommand(s,r,e,n)}function Vs(t){let e=t.expect(u.ASSIGNMENT_WORD),s=e.value,r=s.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||t.error(`Invalid assignment: ${s}`);let n=r[0],o,i=n.length;if(s[i]==="["){let h=0,d=i+1;for(;i<s.length;i++)if(s[i]==="[")h++;else if(s[i]==="]"&&(h--,h===0))break;h!==0&&t.error(`Invalid assignment: ${s}`),o=s.slice(d,i),i++}let a=s[i]==="+";a&&i++,s[i]!=="="&&t.error(`Invalid assignment: ${s}`),i++;let l=s.slice(i);if(l==="("){let h=xt(t);t.expect(u.RPAREN);let d=o!==void 0?`${n}[${o}]`:n;return A.assignment(d,null,a,h)}if(l===""&&t.check(u.LPAREN)){let h=t.current();if(e.end===h.start){t.advance();let d=xt(t);t.expect(u.RPAREN);let p=o!==void 0?`${n}[${o}]`:n;return A.assignment(p,null,a,d)}}let c=l?t.parseWordFromString(l,e.quoted,e.singleQuoted,!0):null,f=o!==void 0?`${n}[${o}]`:n;return A.assignment(f,c,a,null)}function xt(t){let e=[];for(t.skipNewlines();!t.check(u.RPAREN,u.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function St(t){t.expect(u.IF);let e=[],s=t.parseCompoundList();t.expect(u.THEN);let r=t.parseCompoundList();if(r.length===0){let i=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${i}'`)}for(e.push({condition:s,body:r});t.check(u.ELIF);){t.advance();let i=t.parseCompoundList();t.expect(u.THEN);let a=t.parseCompoundList();if(a.length===0){let l=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${l}'`)}e.push({condition:i,body:a})}let n=null;t.check(u.ELSE)&&(t.advance(),n=t.parseCompoundList(),n.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(u.FI);let o=t.parseOptionalRedirections();return A.ifNode(e,n,o)}function bt(t){if(t.expect(u.FOR),t.check(u.DPAREN_START))return qs(t);t.isWord()||t.error("Expected variable name in for loop");let s=t.advance().value,r=null;if(t.skipNewlines(),t.check(u.IN))for(t.advance(),r=[];!t.check(u.SEMICOLON,u.NEWLINE,u.DO,u.EOF)&&t.isWord();)r.push(t.parseWord());t.check(u.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(u.DO);let n=t.parseCompoundList();t.expect(u.DONE);let o=t.parseOptionalRedirections();return A.forNode(s,r,n,o)}function qs(t){t.expect(u.DPAREN_START);let e=null,s=null,r=null,n=["","",""],o=0,i=0;for(;!t.check(u.DPAREN_END,u.EOF);){let c=t.advance();if(c.type===u.SEMICOLON&&i===0){if(o++,o>2)break}else c.value==="("&&i++,c.value===")"&&i--,n[o]+=c.value}t.expect(u.DPAREN_END),n[0].trim()&&(e=L(t,n[0].trim())),n[1].trim()&&(s=L(t,n[1].trim())),n[2].trim()&&(r=L(t,n[2].trim())),t.skipNewlines(),t.check(u.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(u.DO);let a=t.parseCompoundList();t.expect(u.DONE);let l=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:s,update:r,body:a,redirections:l}}function Ct(t){t.expect(u.WHILE);let e=t.parseCompoundList();t.expect(u.DO);let s=t.parseCompoundList();s.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.whileNode(e,s,r)}function Nt(t){t.expect(u.UNTIL);let e=t.parseCompoundList();t.expect(u.DO);let s=t.parseCompoundList();s.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.untilNode(e,s,r)}function $t(t){t.expect(u.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(u.IN),t.skipNewlines();let s=[];for(;!t.check(u.ESAC,u.EOF);){t.checkIterationLimit();let n=t.getPos(),o=Qs(t);if(o&&s.push(o),t.skipNewlines(),t.getPos()===n&&!o)break}t.expect(u.ESAC);let r=t.parseOptionalRedirections();return A.caseNode(e,s,r)}function Qs(t){t.check(u.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(u.PIPE));)t.advance();if(e.length===0)return null;t.expect(u.RPAREN),t.skipNewlines();let s=[];for(;!t.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND,u.ESAC,u.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===u.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(u.LPAREN)&&t.peek(1).type===u.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let n=t.getPos(),o=t.parseStatement();if(o&&s.push(o),t.skipSeparators(!1),t.getPos()===n&&!o)break}let r=";;";return t.check(u.DSEMI)?(t.advance(),r=";;"):t.check(u.SEMI_AND)?(t.advance(),r=";&"):t.check(u.SEMI_SEMI_AND)&&(t.advance(),r=";;&"),A.caseItem(e,s,r)}function vt(t){t.peek(1).type,u.LPAREN,t.expect(u.LPAREN),t.check(u.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(u.RPAREN);let s=t.parseOptionalRedirections();return A.subshell(e,s)}function Pt(t){t.expect(u.LBRACE);let e=t.parseCompoundList();t.expect(u.RBRACE);let s=t.parseOptionalRedirections();return A.group(e,s)}var Xs=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],Ys=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function kt(t){return t.skipNewlines(),Js(t)}function Js(t){let e=Br(t);for(t.skipNewlines();t.check(u.OR_OR);){t.advance(),t.skipNewlines();let s=Br(t);e={type:"CondOr",left:e,right:s},t.skipNewlines()}return e}function Br(t){let e=It(t);for(t.skipNewlines();t.check(u.AND_AND);){t.advance(),t.skipNewlines();let s=It(t);e={type:"CondAnd",left:e,right:s},t.skipNewlines()}return e}function It(t){return t.skipNewlines(),t.check(u.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:It(t)}):en(t)}function en(t){if(t.check(u.LPAREN)){t.advance();let e=kt(t);return t.expect(u.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),s=e.value;if(Xs.includes(s)&&!e.quoted&&(t.advance(),t.check(u.DBRACK_END)&&t.error(`Expected operand after ${s}`),t.isWord())){let n=t.parseWord();return{type:"CondUnary",operator:s,operand:n}}let r=t.parseWord();if(t.isWord()&&Ys.includes(t.current().value)){let n=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:n,left:r,right:o}}if(t.check(u.LESS)){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:"<",left:r,right:n}}if(t.check(u.GREAT)){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:">",left:r,right:n}}if(t.isWord()&&t.current().value==="="){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:"==",left:r,right:n}}return{type:"CondWord",word:r}}t.error("Expected conditional expression")}function rn(t,e,s){let r=s+1,n=e[r];if("@*#?$!-0123456789".includes(n))return{part:A.parameterExpansion(n),endIndex:r+1};let o="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)o+=e[r],r++;return{part:A.parameterExpansion(o),endIndex:r}}function sn(t,e,s,r=!1){let n=s+2,o=!1;e[n]==="!"&&(o=!0,n++);let i=!1;e[n]==="#"&&!/[}:#%/^,]/.test(e[n+1]||"}")&&(i=!0,n++);let a="",l=e[n];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(e[n+1]||""))a=l,n++;else for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)a+=e[n],n++;if(e[n]==="["){let f=gt(t,e,n,"[","]");a+=e.slice(n,f+1),n=f+1}a===""&&!o&&!i&&e[n]!=="}"&&t.error(`\${${e[n]}}: bad substitution`);let c=null;if(o){let f=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(f)c={type:"ArrayKeys",array:f[1],star:f[2]==="*"},a="";else if(e[n]==="*"||e[n]==="@"){let h=e[n];n++,c={type:"VarNamePrefix",prefix:a,star:h==="*"},a=""}else c={type:"Indirection"}}else if(i)if(e[n]===":")for(c={type:"LengthSliceError"};n<e.length&&e[n]!=="}";)n++;else e[n]!=="}"&&/[-+=?]/.test(e[n])?t.error(`\${#${a}${e.slice(n,e.indexOf("}",n))}}: bad substitution`):c={type:"Length"};if(!c&&n<e.length&&e[n]!=="}"){let f=nn(t,e,n,a,r);c=f.operation,n=f.endIndex}if(n<e.length&&e[n]!=="}"){let f=e[n];if(!/[:\-+=?#%/^,@[]/.test(f)){let h=n;for(;h<e.length&&e[h]!=="}";)h++;let d=e.slice(s,h+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;n<e.length&&e[n]!=="}";)n++;return{part:A.parameterExpansion(a,c),endIndex:n+1}}function nn(t,e,s,r,n=!1){let o=s,i=e[o],a=e[o+1]||"";if(i===":"){let l=a;if("-=?+".includes(l)){o+=2;let E=me(t,e,o),w=e.slice(o,E),b=ae(t,w,!1,!1,!0,!1,n),P=A.word(b.length>0?b:[A.literal("")]);if(l==="-")return{operation:{type:"DefaultValue",word:P,checkEmpty:!0},endIndex:E};if(l==="=")return{operation:{type:"AssignDefault",word:P,checkEmpty:!0},endIndex:E};if(l==="?")return{operation:{type:"ErrorIfUnset",word:P,checkEmpty:!0},endIndex:E};if(l==="+")return{operation:{type:"UseAlternative",word:P,checkEmpty:!0},endIndex:E}}o++;let c=me(t,e,o),f=e.slice(o,c),h=-1,d=0,p=0;for(let m=0;m<f.length;m++){let E=f[m];if(E==="("||E==="[")d++;else if(E===")"||E==="]")d--;else if(E==="?"&&d===0)p++;else if(E===":"&&d===0)if(p>0)p--;else{h=m;break}}let y=h>=0?f.slice(0,h):f,g=h>=0?f.slice(h+1):null;return{operation:{type:"Substring",offset:At(t,y),length:g?At(t,g):null},endIndex:c}}if("-=?+".includes(i)){o++;let l=me(t,e,o),c=e.slice(o,l),f=ae(t,c,!1,!1,!0,!1,n),h=A.word(f.length>0?f:[A.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:h,checkEmpty:!1},endIndex:l};if(i==="=")return{operation:{type:"AssignDefault",word:h,checkEmpty:!1},endIndex:l};if(i==="?")return{operation:{type:"ErrorIfUnset",word:c?h:null,checkEmpty:!1},endIndex:l};if(i==="+")return{operation:{type:"UseAlternative",word:h,checkEmpty:!1},endIndex:l}}if(i==="#"||i==="%"){let l=a===i,c=i==="#"?"prefix":"suffix";o+=l?2:1;let f=me(t,e,o),h=e.slice(o,f),d=ae(t,h,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:A.word(d.length>0?d:[A.literal("")]),side:c,greedy:l},endIndex:f}}if(i==="/"){let l=a==="/";o+=l?2:1;let c=null;e[o]==="#"?(c="start",o++):e[o]==="%"&&(c="end",o++);let f=Dr(t,e,o),h=e.slice(o,f),d=ae(t,h,!1,!1,!1),p=A.word(d.length>0?d:[A.literal("")]),y=null,g=f;if(e[f]==="/"){let m=f+1,E=me(t,e,m),w=e.slice(m,E),b=ae(t,w,!1,!1,!1);y=A.word(b.length>0?b:[A.literal("")]),g=E}return{operation:{type:"PatternReplacement",pattern:p,replacement:y,all:l,anchor:c},endIndex:g}}if(i==="^"||i===","){let l=a===i,c=i==="^"?"upper":"lower";o+=l?2:1;let f=me(t,e,o),h=e.slice(o,f),d=h?A.word([A.literal(h)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:d},endIndex:f}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Rt(t,e,s,r=!1){let n=s+1;if(n>=e.length)return{part:A.literal("$"),endIndex:n};let o=e[n];if(o==="("&&e[n+1]==="(")return t.parseArithmeticExpansion(e,s);if(o==="["){let i=1,a=n+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let l=e.slice(n+1,a),c=L(t,l);return{part:A.arithmeticExpansion(c),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,s):o==="{"?sn(t,e,s,r):/[a-zA-Z_0-9@*#?$!-]/.test(o)?rn(t,e,s):{part:A.literal("$"),endIndex:n}}function on(t,e){let s=[],r=0,n="",o=()=>{n&&(s.push(A.literal(n)),n="")};for(;r<e.length;){let i=e[r];if(i==="\\"&&r+1<e.length){let a=e[r+1];if(a==="$"||a==="`"){n+=a,r+=2;continue}n+=i,r++;continue}if(i==="$"){o();let{part:a,endIndex:l}=Rt(t,e,r,!0);a&&s.push(a),r=l;continue}if(i==="`"){o();let{part:a,endIndex:l}=t.parseBacktickSubstitution(e,r,!0);s.push(a),r=l;continue}n+=i,r++}return o(),s}function an(t,e,s){let r=[],n=s,o="",i=()=>{o&&(r.push(A.literal(o)),o="")};for(;n<e.length&&e[n]!=='"';){let a=e[n];if(a==="\\"&&n+1<e.length){let l=e[n+1];if('"\\$`\n'.includes(l)){o+=l,n+=2;continue}o+=a,n++;continue}if(a==="$"){i();let{part:l,endIndex:c}=Rt(t,e,n,!0);l&&r.push(l),n=c;continue}if(a==="`"){i();let{part:l,endIndex:c}=t.parseBacktickSubstitution(e,n,!0);r.push(l),n=c;continue}o+=a,n++}return i(),{part:A.doubleQuoted(r),endIndex:n}}function ae(t,e,s=!1,r=!1,n=!1,o=!1,i=!1){if(r)return[A.singleQuoted(e)];if(s){let h=on(t,e);return[A.doubleQuoted(h)]}let a=[],l=0,c="",f=()=>{c&&(a.push(A.literal(c)),c="")};for(;l<e.length;){let h=e[l];if(h==="\\"&&l+1<e.length){let d=e[l+1];(o?d==="$"||d==="`"||d==="\\"||d===`
|
|
29
29
|
`:d==="$"||d==="`"||d==="\\"||d==='"'||d===`
|
|
30
|
-
`)?c+=d:c+=`\\${d}`,l+=2;continue}if(h==="'"&&!i){f();let d=e.indexOf("'",l+1);if(d===-1){c+=e.slice(l);break}a.push(A.singleQuoted(e.slice(l+1,d))),l=d+1;continue}if(h==='"'){f();let{part:d,endIndex:p}=
|
|
30
|
+
`)?c+=d:c+=`\\${d}`,l+=2;continue}if(h==="'"&&!i){f();let d=e.indexOf("'",l+1);if(d===-1){c+=e.slice(l);break}a.push(A.singleQuoted(e.slice(l+1,d))),l=d+1;continue}if(h==='"'){f();let{part:d,endIndex:p}=an(t,e,l+1);a.push(d),l=p+1;continue}if(h==="$"&&e[l+1]==="'"){f();let{part:d,endIndex:p}=_r(t,e,l+2);a.push(d),l=p;continue}if(h==="$"){f();let{part:d,endIndex:p}=Rt(t,e,l);d&&a.push(d),l=p;continue}if(h==="`"){f();let{part:d,endIndex:p}=t.parseBacktickSubstitution(e,l);a.push(d),l=p;continue}if(h==="~"){let d=l>0?e[l-1]:"";if(l===0||d==="="||n&&d===":"){let y=Rr(t,e,l),g=e[y];if(g===void 0||g==="/"||g===":"){f();let m=e.slice(l+1,y)||null;a.push({type:"TildeExpansion",user:m}),l=y;continue}}}if(h==="*"||h==="?"||h==="["){f();let{pattern:d,endIndex:p}=Or(t,e,l);a.push({type:"Glob",pattern:d}),l=p;continue}if(h==="{"&&!n){let d=Lr(t,e,l,ae);if(d){f(),a.push(d.part),l=d.endIndex;continue}}c+=h,l++}return f(),a}var F=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>vr)throw new ee("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>Et)throw new ee(`Input too large: ${e.length} bytes exceeds limit of ${Et}`,1,1);let s=new Ge(e);if(this.tokens=s.tokenize(),this.tokens.length>wt)throw new ee(`Too many tokens: ${this.tokens.length} exceeds limit of ${wt}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseScript()}parseTokens(e){return this.tokens=e,this.pos=0,this.pendingHeredocs=[],this.parseScript()}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(e=0){return this.tokens[this.pos+e]||this.tokens[this.tokens.length-1]}advance(){let e=this.current();return this.pos<this.tokens.length-1&&this.pos++,e}getPos(){return this.pos}check(e,s,r,n,...o){let i=this.tokens[this.pos]?.type;return i===e||s!==void 0&&i===s||r!==void 0&&i===r||n!==void 0&&i===n?!0:o.length>0?o.includes(i):!1}expect(e,s){if(this.check(e))return this.advance();let r=this.current();throw new ee(s||`Expected ${e}, got ${r.type}`,r.line,r.column,r)}error(e){let s=this.current();throw new ee(e,s.line,s.column,s)}skipNewlines(){for(;this.check(u.NEWLINE,u.COMMENT);)this.check(u.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(u.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(u.SEMICOLON,u.COMMENT)){this.advance();continue}if(e&&this.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,s,r,n){this.pendingHeredocs.push({redirect:e,delimiter:s,stripTabs:r,quoted:n})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(u.HEREDOC_CONTENT)){let s=this.advance(),r;e.quoted?r=A.word([A.literal(s.value)]):r=this.parseWordFromString(s.value,!1,!1,!1,!0),e.redirect.target=A.hereDoc(e.delimiter,r,e.stripTabs,e.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(u.EOF,u.NEWLINE,u.SEMICOLON,u.AMP,u.AND_AND,u.OR_OR,u.RPAREN,u.RBRACE,u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return e===u.WORD||e===u.NAME||e===u.NUMBER||e===u.ASSIGNMENT_WORD||e===u.IF||e===u.FOR||e===u.WHILE||e===u.UNTIL||e===u.CASE||e===u.LPAREN||e===u.LBRACE||e===u.DPAREN_START||e===u.DBRACK_START||e===u.FUNCTION||e===u.BANG||e===u.IN}parseScript(){let e=[],r=0;for(this.skipNewlines();!this.check(u.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)"),this.checkUnexpectedToken();let n=this.pos,o=this.parseStatement();o&&e.push(o),this.skipSeparators(!1),this.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===n&&!this.check(u.EOF)&&this.advance()}return A.script(e)}checkUnexpectedToken(){let e=this.current().type,s=this.current().value;(e===u.DO||e===u.DONE||e===u.THEN||e===u.ELSE||e===u.ELIF||e===u.FI||e===u.ESAC)&&this.error(`syntax error near unexpected token \`${s}'`),(e===u.RBRACE||e===u.RPAREN)&&this.error(`syntax error near unexpected token \`${s}'`),(e===u.DSEMI||e===u.SEMI_AND||e===u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${s}'`),e===u.SEMICOLON&&this.error(`syntax error near unexpected token \`${s}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],s=[],r=!1,n=this.parsePipeline();for(e.push(n);this.check(u.AND_AND,u.OR_OR);){let o=this.advance();s.push(o.type===u.AND_AND?"&&":"||"),this.skipNewlines();let i=this.parsePipeline();e.push(i)}return this.check(u.AMP)&&(this.advance(),r=!0),A.statement(e,s,r)}parsePipeline(){let e=0;for(;this.check(u.BANG);)this.advance(),e++;let s=e%2===1,r=[],n=this.parseCommand();for(r.push(n);this.check(u.PIPE,u.PIPE_AMP);){let o=this.advance();this.skipNewlines();let i=this.parseCommand();o.type===u.PIPE_AMP&&i.type==="SimpleCommand"&&i.redirections.unshift(A.redirection(">&",A.word([A.literal("1")]),2)),r.push(i)}return A.pipeline(r,s)}parseCommand(){return this.check(u.IF)?St(this):this.check(u.FOR)?bt(this):this.check(u.WHILE)?Ct(this):this.check(u.UNTIL)?Nt(this):this.check(u.CASE)?$t(this):this.check(u.LPAREN)?vt(this):this.check(u.LBRACE)?Pt(this):this.check(u.DPAREN_START)?this.parseArithmeticCommand():this.check(u.DBRACK_START)?this.parseConditionalCommand():this.check(u.FUNCTION)?this.parseFunctionDef():this.check(u.NAME,u.WORD)&&this.peek(1).type===u.LPAREN&&this.peek(2).type===u.RPAREN?this.parseFunctionDef():Mr(this)}isWord(){let e=this.current().type;return e===u.WORD||e===u.NAME||e===u.NUMBER||e===u.IF||e===u.FOR||e===u.WHILE||e===u.UNTIL||e===u.CASE||e===u.FUNCTION||e===u.ELSE||e===u.ELIF||e===u.FI||e===u.THEN||e===u.DO||e===u.DONE||e===u.ESAC||e===u.IN||e===u.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,s=!1,r=!1,n=!1,o=!1){let i=ae(this,e,s,r,n,o);return A.word(i)}parseCommandSubstitution(e,s){let r=s+2,n=1,o=r,i=!1,a=!1,l=0,c=!1,f="";for(;o<e.length&&n>0;){let y=e[o];i?y==="'"&&(i=!1):a?y==="\\"&&o+1<e.length?o++:y==='"'&&(a=!1):y==="'"?(i=!0,f=""):y==='"'?(a=!0,f=""):y==="\\"&&o+1<e.length?(o++,f=""):/[a-zA-Z_]/.test(y)?f+=y:(f==="case"?(l++,c=!1):f==="in"&&l>0?c=!0:f==="esac"&&l>0&&(l--,c=!1),f="",y==="("?o>0&&e[o-1]==="$"?n++:c||n++:y===")"?c?c=!1:n--:y===";"&&l>0&&o+1<e.length&&e[o+1]===";"&&(c=!0)),n>0&&o++}n>0&&this.error("unexpected EOF while looking for matching `)'");let h=e.slice(r,o),p=new t().parse(h);return{part:A.commandSubstitution(p,!1),endIndex:o+1}}parseBacktickSubstitution(e,s,r=!1){let o=s+1,i="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let c=e[o+1];c==="$"||c==="`"||c==="\\"||c===`
|
|
31
31
|
`||r&&c==='"'?(c!==`
|
|
32
|
-
`&&(i+=c),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let l=new t().parse(i);return{part:A.commandSubstitution(l,!0),endIndex:o+1}}parseArithmeticExpansion(e,s){let r=s+3,n=1,o=0,i=r;for(;i<e.length-1&&n>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(n++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(n++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(n--,n>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(r,i),l=this.parseArithmeticExpression(a);return{part:A.arithmeticExpansion(l),endIndex:i+2}}parseArithmeticCommand(){this.expect(u.DPAREN_START);let e="",s=1,r=0,n=!1,o=!1;for(;s>0&&!this.check(u.EOF);){if(n){if(n=!1,r>0){r--,e+=")";continue}if(this.check(u.RPAREN)){s--,o=!0,this.advance();continue}if(this.check(u.DPAREN_END)){s--,o=!0;continue}e+=")";continue}this.check(u.DPAREN_START)?(s++,e+="((",this.advance()):this.check(u.DPAREN_END)?r>=2?(r-=2,e+="))",this.advance()):r===1?(r--,e+=")",n=!0,this.advance()):(s--,o=!0,s>0&&(e+="))"),this.advance()):this.check(u.LPAREN)?(r++,e+="(",this.advance()):this.check(u.RPAREN)?(r>0&&r--,e+=")",this.advance()):(e+=this.current().value,this.advance())}o||this.expect(u.DPAREN_END);let i=this.parseArithmeticExpression(e.trim()),a=this.parseOptionalRedirections();return A.arithmeticCommand(i,a)}parseConditionalCommand(){this.expect(u.DBRACK_START);let e=It(this);this.expect(u.DBRACK_END);let s=this.parseOptionalRedirections();return A.conditionalCommand(e,s)}parseFunctionDef(){let e;this.check(u.FUNCTION)?(this.advance(),e=this.expect(u.NAME,"Expected function name").value,this.check(u.LPAREN)&&(this.advance(),this.expect(u.RPAREN))):(e=this.advance().value,this.expect(u.LPAREN),this.expect(u.RPAREN)),this.skipNewlines();let s=this.parseCompoundCommandBody(),r=this.parseOptionalRedirections();return A.functionDef(e,s,r)}parseCompoundCommandBody(){if(this.check(u.LBRACE))return vt(this);if(this.check(u.LPAREN))return $t(this);if(this.check(u.IF))return xt(this);if(this.check(u.FOR))return St(this);if(this.check(u.WHILE))return bt(this);if(this.check(u.UNTIL))return Ct(this);if(this.check(u.CASE))return Nt(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(u.EOF,u.FI,u.ELSE,u.ELIF,u.THEN,u.DO,u.DONE,u.ESAC,u.RPAREN,u.RBRACE,u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let s=this.pos,r=this.parseStatement();if(r&&e.push(r),this.skipSeparators(),this.pos===s&&!r)break}return e}parseOptionalRedirections(){let e=[];for(;Ge(this);){this.checkIterationLimit();let s=this.pos;if(e.push(Ve(this)),this.pos===s)break}return e}parseArithmeticExpression(e){return L(this,e)}};function ae(t){return new F().parse(t)}var Ae=class{fs;cwd;constructor(e,s){this.fs=e,this.cwd=s}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,s){let r=[];for(let n=0;n<e.length;n++){let o=e[n];if((s?.[n]??!1)||!this.isGlobPattern(o))r.push(o);else{let a=await this.expand(o);a.length>0?r.push(...a):r.push(o)}}return r}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let s=[],r=e.lastIndexOf("/"),n,o;r===-1?(n=this.cwd,o=e):(n=e.slice(0,r)||"/",o=e.slice(r+1));let i=this.fs.resolvePath(this.cwd,n);try{let a=await this.fs.readdir(i);for(let l of a)if(this.matchPattern(l,o)){let c=r===-1?l:`${n}/${l}`;s.push(c)}}catch{}return s.sort()}async expandRecursive(e){let s=[],r=e.indexOf("**"),n=e.slice(0,r).replace(/\/$/,"")||".",i=e.slice(r+2).replace(/^\//,"");return await this.walkDirectory(n,i,s),s.sort()}async walkDirectory(e,s,r){let n=this.fs.resolvePath(this.cwd,e);try{let o=await this.fs.readdir(n);for(let i of o){let a=e==="."?i:`${e}/${i}`,l=this.fs.resolvePath(this.cwd,a);try{(await this.fs.stat(l)).isDirectory?await this.walkDirectory(a,s,r):s&&this.matchPattern(i,s)&&r.push(a)}catch{}}}catch{}}matchPattern(e,s){return this.patternToRegex(s).test(e)}patternToRegex(e){let s="^";for(let r=0;r<e.length;r++){let n=e[r];if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let o=r+1,i="[";for(o<e.length&&(e[o]==="^"||e[o]==="!")&&(i+="^",o++),o<e.length&&e[o]==="]"&&(i+="\\]",o++);o<e.length&&e[o]!=="]";){if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let a=e.indexOf(":]",o+2);if(a!==-1){let l=e.slice(o+2,a),c=this.posixClassToRegex(l);i+=c,o=a+2;continue}}if(e[o]==="\\"&&o+1<e.length){i+=`\\${e[o+1]}`,o+=2;continue}e[o]==="-"?i+="\\-":i+=e[o],o++}i+="]",s+=i,r=o}else if(n==="\\"&&r+1<e.length){let o=e[r+1];/[.+^${}()|\\*?[\]]/.test(o)?s+=`\\${o}`:s+=o,r++}else/[.+^${}()|]/.test(n)?s+=`\\${n}`:s+=n}return s+="$",new RegExp(s)}posixClassToRegex(e){return{alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9a-fA-F"}[e]||""}};function H(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return H(t.expression);case"ArithBinary":return H(t.left)||H(t.right);case"ArithUnary":return H(t.operand);case"ArithTernary":return H(t.condition)||H(t.consequent)||H(t.alternate);case"ArithAssignment":return H(t.value);case"ArithGroup":return H(t.expression);case"ArithArrayElement":return t.index?H(t.index):!1;case"ArithConcat":return t.parts.some(H);default:return!1}}function Rt(t){let e=t.operation;return e?!!("word"in e&&e.word&&te(e.word)||e.type==="PatternReplacement"&&(e.pattern&&te(e.pattern)||e.replacement&&te(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&te(e.pattern)):!1}function He(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return H(t.expression.expression);case"DoubleQuoted":return t.parts.some(He);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&te(e.word));case"ParameterExpansion":return Rt(t);default:return!1}}function te(t){return t.parts.some(He)}function Dt(t){if(!t.operation)return!1;let e=t.operation,s;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(s=e.word?.parts),!s)return!1;for(let r of s)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Br(t){let e=!1,s=!1,r=!1,n=!1,o=!1;for(let i of t){if((i.type==="SingleQuoted"||i.type==="DoubleQuoted")&&(e=!0,i.type==="DoubleQuoted"))for(let a of i.parts)a.type==="ParameterExpansion"&&a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!a.operation&&(n=!0);i.type==="CommandSubstitution"&&(s=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(r=!0),Dt(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:s,hasArrayVar:r,hasArrayAtExpansion:n,hasParamExpansion:o}}function cn(t,e,s,r,n){let o=s??1;o===0&&(o=1);let i=Math.abs(o),a=[],l=0;r?.match(/^-?0\d/)&&(l=Math.max(l,r.replace(/^-/,"").length)),n?.match(/^-?0\d/)&&(l=Math.max(l,n.replace(/^-/,"").length));let c=f=>{if(l>0){let h=f<0,d=String(Math.abs(f)).padStart(l,"0");return h?`-${d}`:d}return String(f)};if(t<=e)for(let f=t,h=0;f<=e&&h<1e4;f+=i,h++)a.push(c(f));else for(let f=t,h=0;f>=e&&h<1e4;f-=i,h++)a.push(c(f));return a}function ln(t,e,s){let r=s??1;r===0&&(r=1);let n=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(r),a=t>="A"&&t<="Z",l=t>="a"&&t<="z",c=e>="A"&&e<="Z",f=e>="a"&&e<="z";if(a&&f||l&&c)return null;let h=[];if(n<=o)for(let d=n,p=0;d<=o&&p<1e4;d+=i,p++)h.push(String.fromCharCode(d));else for(let d=n,p=0;d>=o&&p<1e4;d-=i,p++)h.push(String.fromCharCode(d));return h}function ve(t,e,s,r,n){let o=s!==void 0?`..${s}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:cn(t,e,s,r,n),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:ln(t,e,s),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function j(t,e){let s="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\")if(r+1<t.length){let o=t[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?s+=`\\${o}`:s+=o,r+=2}else s+="\\\\",r++;else if(n==="*")s+=e?".*":".*?",r++;else if(n==="?")s+=".",r++;else if(n==="["){let o=fn(t,r);if(o===-1)s+="\\[",r++;else{let i=t.slice(r+1,o);s+=un(i),r=o+1}}else/[\^$.|+(){}]/.test(n)?(s+=`\\${n}`,r++):(s+=n,r++)}return s}function fn(t,e){let s=e+1;for(s<t.length&&t[s]==="^"&&s++,s<t.length&&t[s]==="]"&&s++;s<t.length;){if(t[s]==="\\"&&s+1<t.length){s+=2;continue}if(t[s]==="]")return s;if(t[s]==="'"){let r=t.indexOf("'",s+1);if(r!==-1){s=r+1;continue}}if(t[s]==="["&&s+1<t.length&&t[s+1]===":"){let r=t.indexOf(":]",s+2);if(r!==-1){s=r+2;continue}}s++}return-1}function un(t){let e="[",s=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",s++);s<t.length;){if(t[s]==="'"){let n=t.indexOf("'",s+1);if(n!==-1){let o=t.slice(s+1,n);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;s=n+1;continue}}if(t[s]==="["&&s+1<t.length&&t[s+1]===":"){let n=t.indexOf(":]",s+2);if(n!==-1){let o=t.slice(s+2,n);e+=dn(o),s=n+2;continue}}let r=t[s];r==="\\"?s+1<t.length?(e+=`\\${t[s+1]}`,s+=2):(e+="\\\\",s++):r==="-"&&s>0&&s<t.length-1?(e+="-",s++):r==="^"&&s===0?(e+="^",s++):(r==="]"&&s===0?e+="\\]":e+=r,s++)}return e+="]",e}var hn={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9A-Fa-f"};function dn(t){return hn[t]??""}function Pe(t,e){let s=`${e}_`,r=[];for(let n of Object.keys(t.state.env))if(n.startsWith(s)){let o=n.slice(s.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&r.push(i)}return r.sort((n,o)=>n-o)}function Ot(t,e){let s=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(s)&&delete t.state.env[r]}function _t(t,e){let s=`${e}_`,r=[];for(let n of Object.keys(t.state.env))if(n.startsWith(s)&&!n.includes("__")){let o=n.slice(s.length);r.push(o)}return r.sort()}function zr(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Ze(t){return t.IFS??`
|
|
33
|
-
`}function
|
|
34
|
-
`?"\\n":e).join("")}function
|
|
32
|
+
`&&(i+=c),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let l=new t().parse(i);return{part:A.commandSubstitution(l,!0),endIndex:o+1}}parseArithmeticExpansion(e,s){let r=s+3,n=1,o=0,i=r;for(;i<e.length-1&&n>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(n++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(n++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(n--,n>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(r,i),l=this.parseArithmeticExpression(a);return{part:A.arithmeticExpansion(l),endIndex:i+2}}parseArithmeticCommand(){this.expect(u.DPAREN_START);let e="",s=1,r=0,n=!1,o=!1;for(;s>0&&!this.check(u.EOF);){if(n){if(n=!1,r>0){r--,e+=")";continue}if(this.check(u.RPAREN)){s--,o=!0,this.advance();continue}if(this.check(u.DPAREN_END)){s--,o=!0;continue}e+=")";continue}this.check(u.DPAREN_START)?(s++,e+="((",this.advance()):this.check(u.DPAREN_END)?r>=2?(r-=2,e+="))",this.advance()):r===1?(r--,e+=")",n=!0,this.advance()):(s--,o=!0,s>0&&(e+="))"),this.advance()):this.check(u.LPAREN)?(r++,e+="(",this.advance()):this.check(u.RPAREN)?(r>0&&r--,e+=")",this.advance()):(e+=this.current().value,this.advance())}o||this.expect(u.DPAREN_END);let i=this.parseArithmeticExpression(e.trim()),a=this.parseOptionalRedirections();return A.arithmeticCommand(i,a)}parseConditionalCommand(){this.expect(u.DBRACK_START);let e=kt(this);this.expect(u.DBRACK_END);let s=this.parseOptionalRedirections();return A.conditionalCommand(e,s)}parseFunctionDef(){let e;this.check(u.FUNCTION)?(this.advance(),e=this.expect(u.NAME,"Expected function name").value,this.check(u.LPAREN)&&(this.advance(),this.expect(u.RPAREN))):(e=this.advance().value,this.expect(u.LPAREN),this.expect(u.RPAREN)),this.skipNewlines();let s=this.parseCompoundCommandBody(),r=this.parseOptionalRedirections();return A.functionDef(e,s,r)}parseCompoundCommandBody(){if(this.check(u.LBRACE))return Pt(this);if(this.check(u.LPAREN))return vt(this);if(this.check(u.IF))return St(this);if(this.check(u.FOR))return bt(this);if(this.check(u.WHILE))return Ct(this);if(this.check(u.UNTIL))return Nt(this);if(this.check(u.CASE))return $t(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(u.EOF,u.FI,u.ELSE,u.ELIF,u.THEN,u.DO,u.DONE,u.ESAC,u.RPAREN,u.RBRACE,u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let s=this.pos,r=this.parseStatement();if(r&&e.push(r),this.skipSeparators(),this.pos===s&&!r)break}return e}parseOptionalRedirections(){let e=[];for(;He(this);){this.checkIterationLimit();let s=this.pos;if(e.push(Ve(this)),this.pos===s)break}return e}parseArithmeticExpression(e){return L(this,e)}};function ce(t){return new F().parse(t)}var xe=class{fs;cwd;constructor(e,s){this.fs=e,this.cwd=s}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,s){let r=[];for(let n=0;n<e.length;n++){let o=e[n];if((s?.[n]??!1)||!this.isGlobPattern(o))r.push(o);else{let a=await this.expand(o);a.length>0?r.push(...a):r.push(o)}}return r}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let s=[],r=e.lastIndexOf("/"),n,o;r===-1?(n=this.cwd,o=e):(n=e.slice(0,r)||"/",o=e.slice(r+1));let i=this.fs.resolvePath(this.cwd,n);try{let a=await this.fs.readdir(i);for(let l of a)if(this.matchPattern(l,o)){let c=r===-1?l:`${n}/${l}`;s.push(c)}}catch{}return s.sort()}async expandRecursive(e){let s=[],r=e.indexOf("**"),n=e.slice(0,r).replace(/\/$/,"")||".",i=e.slice(r+2).replace(/^\//,"");return await this.walkDirectory(n,i,s),s.sort()}async walkDirectory(e,s,r){let n=this.fs.resolvePath(this.cwd,e);try{let o=await this.fs.readdir(n);for(let i of o){let a=e==="."?i:`${e}/${i}`,l=this.fs.resolvePath(this.cwd,a);try{(await this.fs.stat(l)).isDirectory?await this.walkDirectory(a,s,r):s&&this.matchPattern(i,s)&&r.push(a)}catch{}}}catch{}}matchPattern(e,s){return this.patternToRegex(s).test(e)}patternToRegex(e){let s="^";for(let r=0;r<e.length;r++){let n=e[r];if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let o=r+1,i="[";for(o<e.length&&(e[o]==="^"||e[o]==="!")&&(i+="^",o++),o<e.length&&e[o]==="]"&&(i+="\\]",o++);o<e.length&&e[o]!=="]";){if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let a=e.indexOf(":]",o+2);if(a!==-1){let l=e.slice(o+2,a),c=this.posixClassToRegex(l);i+=c,o=a+2;continue}}if(e[o]==="\\"&&o+1<e.length){i+=`\\${e[o+1]}`,o+=2;continue}e[o]==="-"?i+="\\-":i+=e[o],o++}i+="]",s+=i,r=o}else if(n==="\\"&&r+1<e.length){let o=e[r+1];/[.+^${}()|\\*?[\]]/.test(o)?s+=`\\${o}`:s+=o,r++}else/[.+^${}()|]/.test(n)?s+=`\\${n}`:s+=n}return s+="$",new RegExp(s)}posixClassToRegex(e){return{alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9a-fA-F"}[e]||""}};function V(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return V(t.expression);case"ArithBinary":return V(t.left)||V(t.right);case"ArithUnary":return V(t.operand);case"ArithTernary":return V(t.condition)||V(t.consequent)||V(t.alternate);case"ArithAssignment":return V(t.value);case"ArithGroup":return V(t.expression);case"ArithArrayElement":return t.index?V(t.index):!1;case"ArithConcat":return t.parts.some(V);default:return!1}}function Dt(t){let e=t.operation;return e?!!("word"in e&&e.word&&te(e.word)||e.type==="PatternReplacement"&&(e.pattern&&te(e.pattern)||e.replacement&&te(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&te(e.pattern)):!1}function Ze(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return V(t.expression.expression);case"DoubleQuoted":return t.parts.some(Ze);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&te(e.word));case"ParameterExpansion":return Dt(t);default:return!1}}function te(t){return t.parts.some(Ze)}function Ot(t){if(!t.operation)return!1;let e=t.operation,s;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(s=e.word?.parts),!s)return!1;for(let r of s)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function zr(t){let e=!1,s=!1,r=!1,n=!1,o=!1;for(let i of t){if((i.type==="SingleQuoted"||i.type==="DoubleQuoted")&&(e=!0,i.type==="DoubleQuoted"))for(let a of i.parts)a.type==="ParameterExpansion"&&a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!a.operation&&(n=!0);i.type==="CommandSubstitution"&&(s=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(r=!0),Ot(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:s,hasArrayVar:r,hasArrayAtExpansion:n,hasParamExpansion:o}}function ln(t,e,s,r,n){let o=s??1;o===0&&(o=1);let i=Math.abs(o),a=[],l=0;r?.match(/^-?0\d/)&&(l=Math.max(l,r.replace(/^-/,"").length)),n?.match(/^-?0\d/)&&(l=Math.max(l,n.replace(/^-/,"").length));let c=f=>{if(l>0){let h=f<0,d=String(Math.abs(f)).padStart(l,"0");return h?`-${d}`:d}return String(f)};if(t<=e)for(let f=t,h=0;f<=e&&h<1e4;f+=i,h++)a.push(c(f));else for(let f=t,h=0;f>=e&&h<1e4;f-=i,h++)a.push(c(f));return a}function fn(t,e,s){let r=s??1;r===0&&(r=1);let n=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(r),a=t>="A"&&t<="Z",l=t>="a"&&t<="z",c=e>="A"&&e<="Z",f=e>="a"&&e<="z";if(a&&f||l&&c)return null;let h=[];if(n<=o)for(let d=n,p=0;d<=o&&p<1e4;d+=i,p++)h.push(String.fromCharCode(d));else for(let d=n,p=0;d>=o&&p<1e4;d-=i,p++)h.push(String.fromCharCode(d));return h}function Pe(t,e,s,r,n){let o=s!==void 0?`..${s}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:ln(t,e,s,r,n),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:fn(t,e,s),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function j(t,e){let s="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\")if(r+1<t.length){let o=t[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?s+=`\\${o}`:s+=o,r+=2}else s+="\\\\",r++;else if(n==="*")s+=e?".*":".*?",r++;else if(n==="?")s+=".",r++;else if(n==="["){let o=un(t,r);if(o===-1)s+="\\[",r++;else{let i=t.slice(r+1,o);s+=hn(i),r=o+1}}else/[\^$.|+(){}]/.test(n)?(s+=`\\${n}`,r++):(s+=n,r++)}return s}function un(t,e){let s=e+1;for(s<t.length&&t[s]==="^"&&s++,s<t.length&&t[s]==="]"&&s++;s<t.length;){if(t[s]==="\\"&&s+1<t.length){s+=2;continue}if(t[s]==="]")return s;if(t[s]==="'"){let r=t.indexOf("'",s+1);if(r!==-1){s=r+1;continue}}if(t[s]==="["&&s+1<t.length&&t[s+1]===":"){let r=t.indexOf(":]",s+2);if(r!==-1){s=r+2;continue}}s++}return-1}function hn(t){let e="[",s=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",s++);s<t.length;){if(t[s]==="'"){let n=t.indexOf("'",s+1);if(n!==-1){let o=t.slice(s+1,n);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;s=n+1;continue}}if(t[s]==="["&&s+1<t.length&&t[s+1]===":"){let n=t.indexOf(":]",s+2);if(n!==-1){let o=t.slice(s+2,n);e+=pn(o),s=n+2;continue}}let r=t[s];r==="\\"?s+1<t.length?(e+=`\\${t[s+1]}`,s+=2):(e+="\\\\",s++):r==="-"&&s>0&&s<t.length-1?(e+="-",s++):r==="^"&&s===0?(e+="^",s++):(r==="]"&&s===0?e+="\\]":e+=r,s++)}return e+="]",e}var dn={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9A-Fa-f"};function pn(t){return dn[t]??""}function Ie(t,e){let s=`${e}_`,r=[];for(let n of Object.keys(t.state.env))if(n.startsWith(s)){let o=n.slice(s.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&r.push(i)}return r.sort((n,o)=>n-o)}function _t(t,e){let s=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(s)&&delete t.state.env[r]}function Lt(t,e){let s=`${e}_`,r=[];for(let n of Object.keys(t.state.env))if(n.startsWith(s)&&!n.includes("__")){let o=n.slice(s.length);r.push(o)}return r.sort()}function Ur(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function qe(t){return t.IFS??`
|
|
33
|
+
`}function jr(t){return t.IFS===""}function ke(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
|
|
34
|
+
`?"\\n":e).join("")}function mn(t,e){let s=ke(t);return new RegExp(`[${s}]+`,e)}function yn(t){let e=ke(t);return new RegExp(`^[${e}]+`)}function En(t){let e=ke(t);return new RegExp(`[${e}]+$`)}function Re(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function Gr(t,e){if(e==="")return{words:[t],wordStarts:[0]};let s=[],r=[],n=mn(e,"g"),o=0,i=t.match(yn(e));i&&(o=i[0].length),n.lastIndex=o;let a=n.exec(t);for(;a!==null;)a.index>o&&(r.push(o),s.push(t.substring(o,a.index))),o=n.lastIndex,a=n.exec(t);return o<t.length&&(r.push(o),s.push(t.substring(o))),{words:s,wordStarts:r}}function Hr(t,e){return e===""?t:t.replace(En(e),"")}function T(t,e){return t.state.associativeArrays?.has(e)?Lt(t,e).map(o=>[o,t.state.env[`${e}_${o}`]]):Ie(t,e).map(n=>[n,t.state.env[`${e}_${n}`]])}function Vr(t,e){return t.state.associativeArrays?.has(e)?Lt(t,e).length>0:Ie(t,e).length>0}function Z(t,e,s=!0,r=!1){switch(e){case"?":return String(t.state.lastExitCode);case"$":return String(process.pid);case"#":return t.state.env["#"]||"0";case"@":return t.state.env["@"]||"";case"_":return t.state.lastArg;case"-":{let i="";return t.state.options.errexit&&(i+="e"),t.state.options.nounset&&(i+="u"),t.state.options.verbose&&(i+="v"),t.state.options.xtrace&&(i+="x"),t.state.options.pipefail&&(i+="p"),i}case"*":{let i=Number.parseInt(t.state.env["#"]||"0",10);if(i===0)return"";let a=[];for(let l=1;l<=i;l++)a.push(t.state.env[String(l)]||"");return a.join(Re(t.state.env))}case"0":return t.state.env[0]||"bash";case"PWD":return t.state.env.PWD!==void 0?t.state.env.PWD:"";case"OLDPWD":return t.state.env.OLDPWD!==void 0?t.state.env.OLDPWD:""}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(e))throw new de(`\${${e}}`);let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let i=n[1],a=n[2];if(a==="@"||a==="*"){let h=T(t,i);if(h.length>0)return h.map(([,p])=>p).join(" ");let d=t.state.env[i];return d!==void 0?d:""}if(t.state.associativeArrays?.has(i)){let h=Ur(a),d=t.state.env[`${i}_${h}`];if(d===void 0&&s&&t.state.options.nounset)throw new K(`${i}[${a}]`);return d||""}let c;if(/^-?\d+$/.test(a))c=Number.parseInt(a,10);else try{let h=new F,d=L(h,a);c=N(t,d.expression)}catch{let h=t.state.env[a];c=h?Number.parseInt(h,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let h=T(t,i);if(h.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
35
35
|
`,"";let p=Math.max(...h.map(([g])=>typeof g=="number"?g:0))+1+c;return p<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
36
|
-
`,""):t.state.env[`${i}_${p}`]||""}let f=t.state.env[`${i}_${c}`];if(f===void 0&&s&&t.state.options.nounset)throw new K(`${i}[${c}]`);return f||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&s&&t.state.options.nounset)throw new K(e);return i||""}let o=t.state.env[e];if(o===void 0&&s&&t.state.options.nounset)throw new K(e);return o||""}async function
|
|
37
|
-
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=s.charCodeAt(0);r<32||r===127?e+=`\\x${r.toString(16).padStart(2,"0")}`:e+=s}}return`${e}'`}function
|
|
38
|
-
`)}return i}case"UseAlternative":return!(a||n.checkEmpty&&l)&&n.word?
|
|
39
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return h}});case"K":return"";default:return i}}case"Indirection":return Z(t,i);case"ArrayKeys":{let f=T(t,n.array).map(([h])=>String(h));return n.star?f.join(
|
|
40
|
-
`)}return i}case"UseAlternative":return!(a||n.checkEmpty&&l)&&n.word?
|
|
36
|
+
`,""):t.state.env[`${i}_${p}`]||""}let f=t.state.env[`${i}_${c}`];if(f===void 0&&s&&t.state.options.nounset)throw new K(`${i}[${c}]`);return f||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&s&&t.state.options.nounset)throw new K(e);return i||""}let o=t.state.env[e];if(o===void 0&&s&&t.state.options.nounset)throw new K(e);return o||""}async function Zr(t,e,s,r,n){let o=[];for(let f of e){let h=f.type==="ParameterExpansion"||f.type==="CommandSubstitution"||f.type==="ArithmeticExpansion";if(f.type==="ParameterExpansion"&&Ot(f)){let d=await n(t,f);o.push({value:d,splittable:!1})}else{let d=await n(t,f);o.push({value:d,splittable:h})}}if(!o.some(f=>f.splittable&&new RegExp(`[${r}]`).test(f.value))){let f=o.map(h=>h.value).join("");return f?[f]:[]}let a=new RegExp(`[${r}]+`),l=[],c="";for(let f=0;f<o.length;f++){let h=o[f];if(!h.splittable)c+=h.value;else{let d=h.value.split(a);for(let p=0;p<d.length;p++)p===0?c+=d[p]:(c!==""&&l.push(c),c=d[p])}}return c!==""&&l.push(c),l}function G(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qr(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function Qr(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Tt(t){if(t==="")return"''";if(!/['\\\n\r\t\x00-\x1f\x7f]/.test(t))return`'${t}'`;let e="$'";for(let s of t)switch(s){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
|
|
37
|
+
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=s.charCodeAt(0);r<32||r===127?e+=`\\x${r.toString(16).padStart(2,"0")}`:e+=s}}return`${e}'`}function ye(t,e,s=!1){return e.map(r=>re(t,r,s)).join("")}async function Ee(t,e,s=!1){let r=[];for(let n of e)r.push(await X(t,n));return r.join("")}function wn(t){return Qr(t)}function Kr(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!wn(e))return!1;return!0}function Xr(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function Yr(t,e,s=!1){let r=qr(e);if(r!==null)return r;switch(e.type){case"ParameterExpansion":return ss(t,e,s);case"TildeExpansion":return s?e.user===null?"~":`~${e.user}`:e.user===null?t.state.env.HOME||"/home/user":e.user==="root"?"/root":`~${e.user}`;case"Glob":return e.pattern;default:return null}}function re(t,e,s=!1){let r=Yr(t,e,s);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let n=[];for(let o of e.parts)n.push(re(t,o,!0));return n.join("")}case"ArithmeticExpansion":return String(N(t,e.expression.expression));case"BraceExpansion":{let n=[];for(let o of e.items)if(o.type==="Range"){let i=Pe(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)n.push(...i.expanded);else return i.literal}else n.push(Qe(t,o.word));return n.join(" ")}default:return""}}function Qe(t,e){let s=e.parts,r=s.length;if(r===1)return re(t,s[0]);let n=[];for(let o=0;o<r;o++)n.push(re(t,s[o]));return n.join("")}async function v(t,e){return te(e)?rs(t,e):Qe(t,e)}function Ke(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&Ke(e.parts))return!0;return!1}function gn(t){for(let e of t){if(e.type==="BraceExpansion"){for(let s of e.items)if(s.type==="Word"&&te(s.word))return!0}if(Ze(e))return!0}return!1}var Jr=1e4,Se=1e5;function es(t,e,s={count:0}){if(s.count>Se)return[[]];let r=[[]];for(let n of e)if(n.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of n.items)if(f.type==="Range"){let h=Pe(f.start,f.end,f.step,f.startStr,f.endStr);if(h.expanded)for(let d of h.expanded)s.count++,o.push(d);else{i=!0,a=h.literal;break}}else{let h=es(t,f.word.parts,s);for(let d of h)s.count++,o.push(d.join(""))}if(i){for(let f of r)s.count++,f.push(a);continue}if(r.length*o.length>Jr||s.count>Se)return r;let c=[];for(let f of r)for(let h of o){if(s.count++,s.count>Se)return c.length>0?c:r;c.push([...f,h])}r=c}else{let o=re(t,n);for(let i of r)s.count++,i.push(o)}return r}function An(t,e){let s=e.parts;return Ke(s)?es(t,s).map(n=>n.join("")):[Qe(t,e)]}async function ts(t,e,s={count:0}){if(s.count>Se)return[[]];let r=[[]];for(let n of e)if(n.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of n.items)if(f.type==="Range"){let h=Pe(f.start,f.end,f.step,f.startStr,f.endStr);if(h.expanded)for(let d of h.expanded)s.count++,o.push(d);else{i=!0,a=h.literal;break}}else{let h=await ts(t,f.word.parts,s);for(let d of h)s.count++,o.push(d.join(""))}if(i){for(let f of r)s.count++,f.push(a);continue}if(r.length*o.length>Jr||s.count>Se)return r;let c=[];for(let f of r)for(let h of o){if(s.count++,s.count>Se)return c.length>0?c:r;c.push([...f,h])}r=c}else{let o=await X(t,n);for(let i of r)s.count++,i.push(o)}return r}async function xn(t,e){let s=e.parts;return Ke(s)?(await ts(t,s)).map(n=>n.join("")):[await v(t,e)]}async function De(t,e){let s=e.parts,{hasQuoted:r,hasCommandSub:n,hasArrayVar:o,hasArrayAtExpansion:i,hasParamExpansion:a}=zr(s),c=Ke(s)?gn(s)?await xn(t,e):An(t,e):null;if(c&&c.length>1){let d=[];for(let p of c)if(!r&&/[*?[]/.test(p)){let g=await new xe(t.fs,t.state.cwd).expand(p);g.length>0?d.push(...g):d.push(p)}else d.push(p);return{values:d,quoted:!1}}if(i&&s.length===1&&s[0].type==="DoubleQuoted"){let d=s[0];if(d.parts.length===1&&d.parts[0].type==="ParameterExpansion"){let y=d.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(y){let g=y[1],m=T(t,g);if(m.length>0)return{values:m.map(([,w])=>w),quoted:!0};let E=t.state.env[g];return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}}}if(!r&&o&&s.length===1&&s[0].type==="ParameterExpansion"){let d=s[0].parameter;if(d==="@"||d==="*"){let p=Number.parseInt(t.state.env["#"]||"0",10);if(p===0)return{values:[],quoted:!1};let y=[];for(let g=1;g<=p;g++)y.push(t.state.env[String(g)]||"");return{values:y,quoted:!1}}}if(!r&&(n||o||a)&&!jr(t.state.env)){let d=qe(t.state.env),p=ke(d),y=await Zr(t,s,d,p,X),g=[],m=new xe(t.fs,t.state.cwd);for(let E of y)if(/[*?[]/.test(E)){let w=await m.expand(E);w.length>0?g.push(...w):g.push(E)}else g.push(E);return{values:g,quoted:!1}}let h=te(e)?await rs(t,e):Qe(t,e);if(!r&&/[*?[]/.test(h)){let p=await new xe(t.fs,t.state.cwd).expand(h);if(p.length>0)return{values:p,quoted:!1}}return h===""&&!r?{values:[],quoted:!1}:{values:[h],quoted:r}}async function rs(t,e){let s=e.parts,r=s.length;if(r===1)return X(t,s[0]);let n=[];for(let o=0;o<r;o++)n.push(await X(t,s[o]));return n.join("")}async function X(t,e){if(e.type==="ParameterExpansion"&&Dt(e))return Sn(t,e);let s=Yr(t,e);if(s!==null)return s;switch(e.type){case"DoubleQuoted":{let r=[];for(let n of e.parts)r.push(await X(t,n));return r.join("")}case"CommandSubstitution":try{let r=await t.executeScript(e.body);return t.state.lastExitCode=r.exitCode,t.state.env["?"]=String(r.exitCode),r.stdout.replace(/\n+$/,"")}catch(r){if(r instanceof B)throw r;if(r instanceof k)return t.state.lastExitCode=r.exitCode,t.state.env["?"]=String(r.exitCode),r.stdout.replace(/\n+$/,"");throw r}case"ArithmeticExpansion":return String(await $(t,e.expression.expression));case"BraceExpansion":{let r=[];for(let n of e.items)if(n.type==="Range"){let o=Pe(n.start,n.end,n.step,n.startStr,n.endStr);if(o.expanded)r.push(...o.expanded);else return o.literal}else r.push(await v(t,n.word));return r.join(" ")}default:return""}}function ss(t,e,s=!1){let{parameter:r,operation:n}=e,o=n&&(n.type==="DefaultValue"||n.type==="AssignDefault"||n.type==="UseAlternative"||n.type==="ErrorIfUnset"),i=Z(t,r,!o);if(!n)return i;let a=!(r in t.state.env),l=i==="";switch(n.type){case"DefaultValue":return(a||n.checkEmpty&&l)&&n.word?ye(t,n.word.parts,s):i;case"AssignDefault":{if((a||n.checkEmpty&&l)&&n.word){let f=ye(t,n.word.parts,s),h=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,d,p]=h,y;if(/^\d+$/.test(p))y=Number.parseInt(p,10);else{try{let m=new F,E=L(m,p);y=N(t,E.expression)}catch{let m=t.state.env[p];y=m?Number.parseInt(m,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${d}_${y}`]=f;let g=Number.parseInt(t.state.env[`${d}__length`]||"0",10);y>=g&&(t.state.env[`${d}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||n.checkEmpty&&l){let f=n.word?ye(t,n.word.parts,s):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
|
|
38
|
+
`)}return i}case"UseAlternative":return!(a||n.checkEmpty&&l)&&n.word?ye(t,n.word.parts,s):"";case"Length":{let c=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(c){let f=T(t,c[1]);return String(f.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&Vr(t,r)){let f=t.state.env[`${r}_0`]||"";return String(f.length)}return String(i.length)}case"LengthSliceError":throw new de(r);case"Substring":{let c=n.offset?N(t,n.offset.expression):0,f=n.length?N(t,n.length.expression):void 0;if(r==="@"||r==="*"){let y=(t.state.env["@"]||"").split(" ").filter(w=>w),g=t.state.env[0]||"bash",m=c===0?[g,...y]:y,E=c===0?0:c-1;if(E<0||E>=m.length)return"";if(f!==void 0){let w=f<0?m.length+f:E+f;return m.slice(E,Math.max(E,w)).join(" ")}return m.slice(E).join(" ")}let h=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(h){let g=T(t,h[1]).map(([,E])=>E),m=c;if(m<0&&(m=g.length+m,m<0))return"";if(f!==void 0){if(f<0){let E=g.length+f;return g.slice(m,Math.max(m,E)).join(" ")}return g.slice(m,m+f).join(" ")}return g.slice(m).join(" ")}let d=[...i],p=c;if(p<0&&(p=Math.max(0,d.length+p)),f!==void 0){if(f<0){let y=d.length+f;return d.slice(p,Math.max(p,y)).join("")}return d.slice(p,p+f).join("")}return d.slice(p).join("")}case"PatternRemoval":{let c="";if(n.pattern)for(let h of n.pattern.parts)if(h.type==="Glob")c+=j(h.pattern,n.greedy);else if(h.type==="Literal")c+=j(h.value,n.greedy);else if(h.type==="SingleQuoted"||h.type==="Escaped")c+=G(h.value);else if(h.type==="DoubleQuoted"){let d=ye(t,h.parts);c+=G(d)}else if(h.type==="ParameterExpansion"){let d=re(t,h);c+=j(d,n.greedy)}else{let d=re(t,h);c+=G(d)}if(n.side==="prefix")return i.replace(new RegExp(`^${c}`),"");let f=new RegExp(`${c}$`);if(n.greedy)return i.replace(f,"");for(let h=i.length;h>=0;h--){let d=i.slice(h);if(f.test(d))return i.slice(0,h)}return i}case"PatternReplacement":{let c="";if(n.pattern)for(let d of n.pattern.parts)if(d.type==="Glob")c+=j(d.pattern,!0);else if(d.type==="Literal")c+=j(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=G(d.value);else if(d.type==="DoubleQuoted"){let p=ye(t,d.parts);c+=G(p)}else if(d.type==="ParameterExpansion"){let p=re(t,d);c+=j(p,!0)}else{let p=re(t,d);c+=G(p)}let f=n.replacement?ye(t,n.replacement.parts):"";if(c==="")return i;n.anchor==="start"?c=`^${c}`:n.anchor==="end"&&(c=`${c}$`);let h=n.all?"g":"";try{let d=new RegExp(c,h);if(n.all){let p="",y=0,g=d.exec(i);for(;g!==null&&!(g[0].length===0&&g.index===i.length);)p+=i.slice(y,g.index)+f,y=g.index+g[0].length,g[0].length===0&&y++,g=d.exec(i);return p+=i.slice(y),p}return i.replace(d,f)}catch{return i}}case"CaseModification":return n.direction==="upper"?n.all?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):n.all?i.toLowerCase():i.charAt(0).toLowerCase()+i.slice(1);case"Transform":{let c=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(c&&n.operator==="Q")return T(t,c[1]).map(([,d])=>Tt(d)).join(" ");switch(n.operator){case"Q":return Tt(i);case"P":return i;case"a":return"";case"A":return`${r}=${Tt(i)}`;case"E":return i.replace(/\\([\\abefnrtv'"?])/g,(f,h)=>{switch(h){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
|
|
39
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return h}});case"K":return"";default:return i}}case"Indirection":return Z(t,i);case"ArrayKeys":{let f=T(t,n.array).map(([h])=>String(h));return n.star?f.join(Re(t.state.env)):f.join(" ")}case"VarNamePrefix":{let c=Object.keys(t.state.env).filter(f=>f.startsWith(n.prefix)&&!f.includes("__")).sort();return n.star?c.join(Re(t.state.env)):c.join(" ")}default:return i}}async function Sn(t,e,s=!1){let{parameter:r,operation:n}=e,o=n&&(n.type==="DefaultValue"||n.type==="AssignDefault"||n.type==="UseAlternative"||n.type==="ErrorIfUnset"),i=Z(t,r,!o);if(!n)return i;let a=!(r in t.state.env),l=i==="";switch(n.type){case"DefaultValue":return(a||n.checkEmpty&&l)&&n.word?Ee(t,n.word.parts,s):i;case"AssignDefault":{if((a||n.checkEmpty&&l)&&n.word){let f=await Ee(t,n.word.parts,s),h=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,d,p]=h,y;if(/^\d+$/.test(p))y=Number.parseInt(p,10);else{try{let m=new F,E=L(m,p);y=await $(t,E.expression)}catch{let m=t.state.env[p];y=m?Number.parseInt(m,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${d}_${y}`]=f;let g=Number.parseInt(t.state.env[`${d}__length`]||"0",10);y>=g&&(t.state.env[`${d}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||n.checkEmpty&&l){let f=n.word?await Ee(t,n.word.parts,s):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
|
|
40
|
+
`)}return i}case"UseAlternative":return!(a||n.checkEmpty&&l)&&n.word?Ee(t,n.word.parts,s):"";case"PatternRemoval":{let c="";if(n.pattern)for(let h of n.pattern.parts)if(h.type==="Glob")c+=j(h.pattern,n.greedy);else if(h.type==="Literal")c+=j(h.value,n.greedy);else if(h.type==="SingleQuoted"||h.type==="Escaped")c+=G(h.value);else if(h.type==="DoubleQuoted"){let d=await Ee(t,h.parts);c+=G(d)}else if(h.type==="ParameterExpansion"){let d=await X(t,h);c+=j(d,n.greedy)}else{let d=await X(t,h);c+=G(d)}if(n.side==="prefix")return i.replace(new RegExp(`^${c}`),"");let f=new RegExp(`${c}$`);if(n.greedy)return i.replace(f,"");for(let h=i.length;h>=0;h--){let d=i.slice(h);if(f.test(d))return i.slice(0,h)}return i}case"PatternReplacement":{let c="";if(n.pattern)for(let d of n.pattern.parts)if(d.type==="Glob")c+=j(d.pattern,!0);else if(d.type==="Literal")c+=j(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=G(d.value);else if(d.type==="DoubleQuoted"){let p=await Ee(t,d.parts);c+=G(p)}else if(d.type==="ParameterExpansion"){let p=await X(t,d);c+=j(p,!0)}else{let p=await X(t,d);c+=G(p)}let f=n.replacement?await Ee(t,n.replacement.parts):"";if(c==="")return i;n.anchor==="start"?c=`^${c}`:n.anchor==="end"&&(c=`${c}$`);let h=n.all?"g":"";try{let d=new RegExp(c,h);if(n.all){let p="",y=0,g=d.exec(i);for(;g!==null&&!(g[0].length===0&&g.index===i.length);)p+=i.slice(y,g.index)+f,y=g.index+g[0].length,g[0].length===0&&y++,g=d.exec(i);return p+=i.slice(y),p}return i.replace(d,f)}catch{return i}}default:return ss(t,e,s)}}function Wt(t,e,s){switch(s){case"+":return t+e;case"-":return t-e;case"*":return t*e;case"/":return e!==0?Math.trunc(t/e):0;case"%":return e!==0?t%e:0;case"**":if(e<0)throw new W("exponent less than 0");return t**e;case"<<":return t<<e;case">>":return t>>e;case"<":return t<e?1:0;case"<=":return t<=e?1:0;case">":return t>e?1:0;case">=":return t>=e?1:0;case"==":return t===e?1:0;case"!=":return t!==e?1:0;case"&":return t&e;case"|":return t|e;case"^":return t^e;case",":return e;default:return 0}}function ns(t,e,s){switch(s){case"=":return e;case"+=":return t+e;case"-=":return t-e;case"*=":return t*e;case"/=":return e!==0?Math.trunc(t/e):0;case"%=":return e!==0?t%e:0;case"<<=":return t<<e;case">>=":return t>>e;case"&=":return t&e;case"|=":return t|e;case"^=":return t^e;default:return e}}function Ft(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function bn(t,e){let s=t.state.env[e];if(s!==void 0)return s;let r=t.state.env[`${e}_0`];return r!==void 0?r:Z(t,e)}function be(t){if(!t)return 0;let e=Number.parseInt(t,10);if(!Number.isNaN(e)&&/^-?\d+$/.test(t.trim()))return e;let s=t.trim();if(!s)return 0;try{let r=new F,{expr:n,pos:o}=J(r,s,0);if(o<s.length){let i=s.slice(o).trim().split(/\s+/)[0];throw new W(`${s}: syntax error in expression (error token is "${i}")`)}return n.type==="ArithNumber"?n.value:e||0}catch(r){if(r instanceof W)throw r;let n=s.split(/\s+/).slice(1)[0]||s;throw new W(`${s}: syntax error in expression (error token is "${n}")`)}}function Xe(t,e,s=new Set){if(s.has(e))return 0;s.add(e);let r=bn(t,e);if(!r)return 0;let n=Number.parseInt(r,10);if(!Number.isNaN(n)&&/^-?\d+$/.test(r.trim()))return n;let o=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return Xe(t,o,s);try{let i=new F,{expr:a}=J(i,o,0);return q(t,a,s)}catch{return 0}}function q(t,e,s){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return Xe(t,e.name,s);case"ArithBinary":{if(e.operator==="||")return q(t,e.left,s)||q(t,e.right,s)?1:0;if(e.operator==="&&")return q(t,e.left,s)&&q(t,e.right,s)?1:0;let r=q(t,e.left,s),n=q(t,e.right,s);return Wt(r,n,e.operator)}case"ArithUnary":{let r=q(t,e.operand,s);return Ft(r,e.operator)}case"ArithTernary":return q(t,e.condition,s)?q(t,e.consequent,s):q(t,e.alternate,s);case"ArithGroup":return q(t,e.expression,s);default:return N(t,e)}}function le(t,e){if(e.startsWith("#")){let h=e.slice(1),d=t.state.env[h]||"";return String(d.length)}if(e.startsWith("!")){let h=e.slice(1),d=t.state.env[h]||"";return t.state.env[d]||""}let s=[":-",":=",":?",":+","-","=","?","+"],r=-1,n="";for(let h of s){let d=e.indexOf(h);d>0&&(r===-1||d<r)&&(r=d,n=h)}if(r===-1)return Z(t,e);let o=e.slice(0,r),i=e.slice(r+n.length),a=t.state.env[o],l=a===void 0,c=a==="",f=n.startsWith(":");switch(n){case":-":case"-":return l||f&&c?i:a||"";case":=":case"=":return l||f&&c?(t.state.env[o]=i,i):a||"";case":+":case"+":return!(l||f&&c)?i:"";case":?":case"?":{if(l||f&&c)throw new Error(i||`${o}: parameter null or not set`);return a||""}default:return a||""}}function N(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return Xe(t,e.name);case"ArithNested":return N(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let s=le(t,e.content);return Number.parseInt(s,10)||0}case"ArithDynamicBase":{let s=le(t,e.baseExpr),r=Number.parseInt(s,10);if(r<2||r>64)return 0;let n=`${r}#${e.value}`;return Ae(n)}case"ArithDynamicNumber":{let r=le(t,e.prefix)+e.suffix;return Ae(r)}case"ArithArrayElement":{let s=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(s&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let o=N(t,e.index);if(o<0){let a=T(t,e.array);if(a.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
41
41
|
`,0;let c=Math.max(...a.map(([f])=>typeof f=="number"?f:0))+1+o;if(c<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
42
|
-
`,0;o=c}r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return
|
|
43
|
-
`);s=r}throw new z(s)}async function
|
|
42
|
+
`,0;o=c}r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return be(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return be(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new K(`${e.array}[${o}]`);return 0}else return 0;let n=t.state.env[r];return n!==void 0?be(n):0}case"ArithDoubleSubscript":throw new W("double subscript","","");case"ArithNumberSubscript":throw new W(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return N(t,e.left)||N(t,e.right)?1:0;if(e.operator==="&&")return N(t,e.left)&&N(t,e.right)?1:0;let s=N(t,e.left),r=N(t,e.right);return Wt(s,r,e.operator)}case"ArithUnary":{let s=N(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,n=Number.parseInt(Z(t,r),10)||0,o=e.operator==="++"?n+1:n-1;return t.state.env[r]=String(o),e.prefix?o:n}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,n=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(n&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let l=N(t,e.operand.index);o=`${r}_${l}`}else return s;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return s}return Ft(s,e.operator)}case"ArithTernary":return N(t,e.condition)?N(t,e.consequent):N(t,e.alternate);case"ArithAssignment":{let s=e.variable,r=s;if(e.stringKey!==void 0)r=`${s}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(s);if(a&&e.subscript.type==="ArithVariable")r=`${s}_${e.subscript.name}`;else if(a){let l=N(t,e.subscript);r=`${s}_${l}`}else{let l=N(t,e.subscript);if(l<0){let c=T(t,s);c.length>0&&(l=Math.max(...c.map(([h])=>typeof h=="number"?h:0))+1+l)}r=`${s}_${l}`}}let n=Number.parseInt(t.state.env[r]||"0",10)||0,o=N(t,e.value),i=ns(n,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return N(t,e.expression);case"ArithConcat":{let s="";for(let r of e.parts)s+=is(t,r);return Number.parseInt(s,10)||0}default:return 0}}function is(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return Z(t,e.name);case"ArithBracedExpansion":return le(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let s="";for(let r of e.parts)s+=is(t,r);return s}default:return String(N(t,e))}}async function $(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return Xe(t,e.name);case"ArithNested":return $(t,e.expression);case"ArithCommandSubst":{if(t.execFn){let r=(await t.execFn(e.command)).stdout.trim();return Number.parseInt(r,10)||0}return 0}case"ArithBracedExpansion":{let s=le(t,e.content);return Number.parseInt(s,10)||0}case"ArithDynamicBase":{let s=le(t,e.baseExpr),r=Number.parseInt(s,10);if(r<2||r>64)return 0;let n=`${r}#${e.value}`;return Ae(n)}case"ArithDynamicNumber":{let r=le(t,e.prefix)+e.suffix;return Ae(r)}case"ArithArrayElement":{let s=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(s&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let o=await $(t,e.index);r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return be(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return be(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new K(`${e.array}[${o}]`);return 0}else return 0;let n=t.state.env[r];return n!==void 0?be(n):0}case"ArithDoubleSubscript":throw new W("double subscript","","");case"ArithNumberSubscript":throw new W(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return await $(t,e.left)||await $(t,e.right)?1:0;if(e.operator==="&&")return await $(t,e.left)&&await $(t,e.right)?1:0;let s=await $(t,e.left),r=await $(t,e.right);return Wt(s,r,e.operator)}case"ArithUnary":{let s=await $(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,n=Number.parseInt(Z(t,r),10)||0,o=e.operator==="++"?n+1:n-1;return t.state.env[r]=String(o),e.prefix?o:n}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,n=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(n&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let l=await $(t,e.operand.index);o=`${r}_${l}`}else return s;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return s}return Ft(s,e.operator)}case"ArithTernary":return await $(t,e.condition)?await $(t,e.consequent):await $(t,e.alternate);case"ArithAssignment":{let s=e.variable,r=s;if(e.stringKey!==void 0)r=`${s}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(s);if(a&&e.subscript.type==="ArithVariable")r=`${s}_${e.subscript.name}`;else if(a){let l=await $(t,e.subscript);r=`${s}_${l}`}else{let l=await $(t,e.subscript);if(l<0){let c=T(t,s);c.length>0&&(l=Math.max(...c.map(([h])=>typeof h=="number"?h:0))+1+l)}r=`${s}_${l}`}}let n=Number.parseInt(t.state.env[r]||"0",10)||0,o=await $(t,e.value),i=ns(n,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return await $(t,e.expression);case"ArithConcat":{let s="";for(let r of e.parts)s+=await os(t,r);return Number.parseInt(s,10)||0}default:return 0}}async function os(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return Z(t,e.name);case"ArithBracedExpansion":return le(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command)).stdout.trim():"0";case"ArithConcat":{let s="";for(let r of e.parts)s+=await os(t,r);return s}default:return String(await $(t,e))}}var C=Object.freeze({stdout:"",stderr:"",exitCode:0});function H(t=""){return{stdout:t,stderr:"",exitCode:0}}function S(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function x(t,e,s){return{stdout:t,stderr:e,exitCode:s}}function O(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function se(t,e,s="",r=""){throw new B(t,e,s,r)}function Mt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ie;return C}let s=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)throw new k(128,"",`bash: break: ${e[0]}: numeric argument required
|
|
43
|
+
`);s=r}throw new z(s)}async function Bt(t,e){let s,r=!1,n=!1,o=0;for(;o<e.length;)if(e[o]==="--"){o++;break}else if(e[o]==="-L")n=!1,o++;else if(e[o]==="-P")n=!0,o++;else if(e[o].startsWith("-")&&e[o]!=="-")o++;else break;let i=e.slice(o);if(i.length===0||i[0]==="~"?s=t.state.env.HOME||"/":i[0]==="-"?(s=t.state.previousDir,r=!0):s=i[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let h=t.state.env.CDPATH;if(h){let d=h.split(":").filter(p=>p);for(let p of d){let y=p.startsWith("/")?`${p}/${s}`:`${t.state.cwd}/${p}/${s}`;try{if((await t.fs.stat(y)).isDirectory){s=y,r=!0;break}}catch{}}}}let l=(s.startsWith("/")?s:`${t.state.cwd}/${s}`).split("/").filter(h=>h&&h!=="."),c="";for(let h of l)if(h==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${h}`:`/${h}`;try{if(!(await t.fs.stat(c)).isDirectory)return S(`bash: cd: ${s}: Not a directory
|
|
44
44
|
`)}catch{return S(`bash: cd: ${s}: No such file or directory
|
|
45
|
-
`)}}let f=c||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=f,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,
|
|
46
|
-
`:"")}function
|
|
47
|
-
`);s=r}throw new Q(s)}function
|
|
48
|
-
`):null}function
|
|
49
|
-
`}}return
|
|
50
|
-
`}return
|
|
51
|
-
`)&&!r&&!n){s&&(e.push(s),s="");continue}s+=i}return s&&e.push(s),e}function
|
|
52
|
-
`)}return
|
|
45
|
+
`)}}let f=c||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=f,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,H(r?`${f}
|
|
46
|
+
`:"")}function zt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ie;return C}if(e.length>1)throw new z(1);let s=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)return S(`bash: continue: ${e[0]}: numeric argument required
|
|
47
|
+
`);s=r}throw new Q(s)}function we(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function Cn(t,e){return t.state.readonlyVars?.has(e)??!1}function fe(t,e,s="bash"){return Cn(t,e)?S(`${s}: ${e}: readonly variable
|
|
48
|
+
`):null}function as(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:Ut(e[2])};if(t.includes("=")){let s=t.indexOf("=");return{name:t.slice(0,s),isArray:!1,value:t.slice(s+1)}}return{name:t,isArray:!1}}function cs(t,e,s={}){let{name:r,isArray:n,arrayElements:o,value:i}=e,{makeReadonly:a=!1,checkReadonly:l=!0}=s;if(l){let c=fe(t,r);if(c)return c}if(n&&o){for(let c=0;c<o.length;c++)t.state.env[`${r}_${c}`]=o[c];t.state.env[`${r}__length`]=String(o.length)}else i!==void 0&&(t.state.env[r]=i);return a&&we(t,r),null}function jt(t,e){let s=!1,r=!1,n=!1,o=!1,i=!1,a=[];for(let l=0;l<e.length;l++){let c=e[l];if(c==="-a")s=!0;else if(c==="-A")r=!0;else if(c==="-r")n=!0;else if(c==="-x")o=!0;else if(c==="-p")i=!0;else if(c==="--"){a.push(...e.slice(l+1));break}else if(c.startsWith("-"))for(let f of c.slice(1))f==="a"?s=!0:f==="A"?r=!0:f==="r"?n=!0:f==="x"?o=!0:f==="p"&&(i=!0);else a.push(c)}if(i&&a.length>0){let l="";for(let c of a){let f=t.state.env[c];if(f!==void 0){let h=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"');l+=`declare -- ${c}="${h}"
|
|
49
|
+
`}}return H(l)}if(a.length===0&&!i){let l="",c=Object.entries(t.state.env).filter(([f])=>!f.startsWith("BASH_")).sort(([f],[h])=>f.localeCompare(h));for(let[f,h]of c){let d=h.replace(/'/g,"'\\''");l+=`declare -- ${f}='${d}'
|
|
50
|
+
`}return H(l)}for(let l of a){let c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(c){let f=c[1],h=c[2];if(r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f)),r&&h.includes("[")){let d=Nn(h);for(let[p,y]of d)t.state.env[`${f}_${p}`]=y}else{let d=Ut(h);for(let p=0;p<d.length;p++)t.state.env[`${f}_${p}`]=d[p];t.state.env[`${f}__length`]=String(d.length)}n&&we(t,f);continue}if(l.includes("=")){let f=l.indexOf("="),h=l.slice(0,f),d=l.slice(f+1),p=fe(t,h);if(p)return p;t.state.env[h]=d,n&&we(t,h)}else{let f=l;r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f));let h=Object.keys(t.state.env).some(d=>d.startsWith(`${f}_`)&&!d.startsWith(`${f}__length`));!(f in t.state.env)&&!h&&(s||r?t.state.env[`${f}__length`]="0":t.state.env[f]=""),n&&we(t,f)}}return C}function Ut(t){let e=[],s="",r=!1,n=!1,o=!1;for(let i of t){if(o){s+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(i==="'"&&!n){r=!r;continue}if(i==='"'&&!r){n=!n;continue}if((i===" "||i===" "||i===`
|
|
51
|
+
`)&&!r&&!n){s&&(e.push(s),s="");continue}s+=i}return s&&e.push(s),e}function Nn(t){let e=[],s=0;for(;s<t.length;){for(;s<t.length&&/\s/.test(t[s]);)s++;if(s>=t.length)break;if(t[s]!=="["){s++;continue}s++;let r="";if(t[s]==="'"||t[s]==='"'){let o=t[s];for(s++;s<t.length&&t[s]!==o;)r+=t[s],s++;t[s]===o&&s++}else for(;s<t.length&&t[s]!=="]"&&t[s]!=="=";)r+=t[s],s++;for(;s<t.length&&t[s]!=="]";)s++;if(t[s]==="]"&&s++,t[s]!=="=")continue;s++;let n="";if(t[s]==="'"||t[s]==='"'){let o=t[s];for(s++;s<t.length&&t[s]!==o;)t[s]==="\\"&&s+1<t.length&&s++,n+=t[s],s++;t[s]===o&&s++}else for(;s<t.length&&!/\s/.test(t[s]);)n+=t[s],s++;e.push([r,n])}return e}function Gt(t,e){let s=!1,r=!1,n=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="-a")s=!0;else if(i==="-A")r=!0;else if(i==="-p"){if(e.length===1){let a="";for(let l of t.state.readonlyVars||[]){let c=t.state.env[l];c!==void 0&&(a+=`declare -r ${l}="${c}"
|
|
52
|
+
`)}return H(a)}}else if(i==="--"){n.push(...e.slice(o+1));break}else i.startsWith("-")||n.push(i)}for(let o of n){let i=as(o);if(i.value===void 0&&!i.isArray){we(t,i.name);continue}let a=cs(t,i,{makeReadonly:!0});if(a)return a}return C}async function Ht(t,e){let s=e;if(s.length>0){let n=s[0];if(n==="--")s=s.slice(1);else if(n.startsWith("-")&&n!=="-"&&n.length>1)return S(`bash: eval: ${n}: invalid option
|
|
53
53
|
eval: usage: eval [arg ...]
|
|
54
|
-
`,2)}if(s.length===0)return C;let r=s.join(" ");if(r.trim()==="")return C;try{let n=
|
|
54
|
+
`,2)}if(s.length===0)return C;let r=s.join(" ");if(r.trim()==="")return C;try{let n=ce(r);return t.executeScript(n)}catch(n){if(n instanceof z||n instanceof Q||n instanceof U||n instanceof k)throw n;if(n.name==="ParseException")return S(`bash: eval: ${n.message}
|
|
55
55
|
`);throw n}}function Vt(t,e){let s,r="";if(e.length===0)s=t.state.lastExitCode;else{let n=e[0],o=Number.parseInt(n,10);n===""||Number.isNaN(o)||!/^-?\d+$/.test(n)?(r=`bash: exit: ${n}: numeric argument required
|
|
56
|
-
`,s=2):s=(o%256+256)%256}throw new k(s,"",r)}function
|
|
57
|
-
`}return
|
|
58
|
-
`,o=1;continue}l!==void 0?t.state.env[a]=l:a in t.state.env||(t.state.env[a]="")}return x("",n,o)}function
|
|
59
|
-
`);let s
|
|
60
|
-
`)}return x("","",r===0?1:0)}function
|
|
61
|
-
`);let s=t.state.localScopes[t.state.localScopes.length-1],r="",n=0;for(let o of e){let i,a;if(o.includes("=")){let l=o.indexOf("=");i=o.slice(0,l),a
|
|
62
|
-
`,n=1;continue}s.has(i)||s.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return x("",r,n)}function
|
|
63
|
-
`,o="",i=-1,a=null,l=[],c=0,f=!1;for(;c<e.length;){let w=e[c];w==="-r"?r=!0:w==="-d"&&c+1<e.length?(n=e[c+1],c++):w==="-p"&&c+1<e.length?(o=e[c+1],c++):w==="-n"&&c+1<e.length?(i=Number.parseInt(e[c+1],10),(Number.isNaN(i)||i<0)&&(f=!0,i=0),c++):w==="-a"&&c+1<e.length?(a=e[c+1],c++):w==="-t"?c+1<e.length&&!e[c+1].startsWith("-")&&c++:w==="-s"||w.startsWith("-")||l.push(w),c++}if(f)return x("","",1);l.length===0&&a===null&&l.push("REPLY");let h=s;!h&&t.state.groupStdin!==void 0&&(h=t.state.groupStdin);let d="",p=0,y=!0;if(i>=0){for(let w=0;w<h.length&&w<i;w++){let b=h[w];if(b===n){p=w+1;break}d+=b,p=w+1}t.state.groupStdin!==void 0&&!s&&(t.state.groupStdin=h.substring(p))}else{let w=h;for(p=0;;){let b=w.indexOf(n);if(b!==-1){let P=w.substring(0,b);if(p+=b+n.length,w=w.substring(b+n.length),!r&&P.endsWith("\\")){d+=P.slice(0,-1);continue}d+=P,y=!0;break}else if(w.length>0){d+=w,p+=w.length,y=!1,w="";break}else{if(d.length===0){for(let P of l)t.state.env[P]="";return a&&
|
|
56
|
+
`,s=2):s=(o%256+256)%256}throw new k(s,"",r)}function Zt(t,e){let s=!1,r=[];for(let i of e)i==="-n"?s=!0:i==="-p"||i==="--"||r.push(i);if(r.length===0&&!s){let i="",a=Object.entries(t.state.env).filter(([l])=>!l.startsWith("BASH_ALIAS_")).sort(([l],[c])=>l.localeCompare(c));for(let[l,c]of a){let f=c.replace(/'/g,"'\\''");i+=`declare -x ${l}='${f}'
|
|
57
|
+
`}return H(i)}if(s){for(let i of r){let a=i.split("=")[0];delete t.state.env[a]}return C}let n="",o=0;for(let i of r){let a,l;if(i.includes("=")){let c=i.indexOf("=");a=i.slice(0,c),l=i.slice(c+1)}else a=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){n+=`bash: export: \`${i}': not a valid identifier
|
|
58
|
+
`,o=1;continue}l!==void 0?t.state.env[a]=l:a in t.state.env||(t.state.env[a]="")}return x("",n,o)}function $n(t){let e=[],s="",r=0;for(let n of t){for(let o of n)o==="("?r++:o===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(e.push(s),s="")}return s&&e.push(s),e}async function qt(t,e){if(e.length===0)return S(`bash: let: expression expected
|
|
59
|
+
`);let s=$n(e),r=0;for(let n of s)try{let i=ce(`(( ${n} ))`).statements[0];if(i&&i.pipelines.length>0&&i.pipelines[0].commands.length>0){let a=i.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await $(t,a.expression.expression))}}catch(o){return S(`bash: let: ${n}: ${o.message}
|
|
60
|
+
`)}return x("","",r===0?1:0)}function vn(t,e){let s=t.state.env.HOME||"/home/user";return e.split(":").map(o=>o==="~"?s:o==="~root"?"/root":o.startsWith("~/")?s+o.slice(1):o.startsWith("~root/")?`/root${o.slice(5)}`:o).join(":")}function Qt(t,e){if(t.state.localScopes.length===0)return S(`bash: local: can only be used in a function
|
|
61
|
+
`);let s=t.state.localScopes[t.state.localScopes.length-1],r="",n=0;for(let o of e){let i,a;if(o.includes("=")){let l=o.indexOf("=");i=o.slice(0,l),a=vn(t,o.slice(l+1))}else i=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)){r+=`bash: local: \`${o}': not a valid identifier
|
|
62
|
+
`,n=1;continue}s.has(i)||s.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return x("",r,n)}function Kt(t,e,s){let r=!1,n=`
|
|
63
|
+
`,o="",i=-1,a=null,l=[],c=0,f=!1;for(;c<e.length;){let w=e[c];w==="-r"?r=!0:w==="-d"&&c+1<e.length?(n=e[c+1],c++):w==="-p"&&c+1<e.length?(o=e[c+1],c++):w==="-n"&&c+1<e.length?(i=Number.parseInt(e[c+1],10),(Number.isNaN(i)||i<0)&&(f=!0,i=0),c++):w==="-a"&&c+1<e.length?(a=e[c+1],c++):w==="-t"?c+1<e.length&&!e[c+1].startsWith("-")&&c++:w==="-s"||w.startsWith("-")||l.push(w),c++}if(f)return x("","",1);l.length===0&&a===null&&l.push("REPLY");let h=s;!h&&t.state.groupStdin!==void 0&&(h=t.state.groupStdin);let d="",p=0,y=!0;if(i>=0){for(let w=0;w<h.length&&w<i;w++){let b=h[w];if(b===n){p=w+1;break}d+=b,p=w+1}t.state.groupStdin!==void 0&&!s&&(t.state.groupStdin=h.substring(p))}else{let w=h;for(p=0;;){let b=w.indexOf(n);if(b!==-1){let P=w.substring(0,b);if(p+=b+n.length,w=w.substring(b+n.length),!r&&P.endsWith("\\")){d+=P.slice(0,-1);continue}d+=P,y=!0;break}else if(w.length>0){d+=w,p+=w.length,y=!1,w="";break}else{if(d.length===0){for(let P of l)t.state.env[P]="";return a&&_t(t,a),x("","",1)}y=!1;break}}t.state.groupStdin!==void 0&&!s&&(t.state.groupStdin=h.substring(p))}if(n===`
|
|
64
64
|
`&&d.endsWith(`
|
|
65
|
-
`)&&(d=d.slice(0,-1)),r||(d=d.replace(/\\(.)/g,"$1")),l.length===1&&l[0]==="REPLY")return t.state.env.REPLY=d,x("","",y?0:1);let g=
|
|
66
|
-
`,2);s=(n%256+256)%256}throw new U(s)}function
|
|
65
|
+
`)&&(d=d.slice(0,-1)),r||(d=d.replace(/\\(.)/g,"$1")),l.length===1&&l[0]==="REPLY")return t.state.env.REPLY=d,x("","",y?0:1);let g=qe(t.state.env),{words:m,wordStarts:E}=Gr(d,g);if(a){_t(t,a);for(let w=0;w<m.length;w++)t.state.env[`${a}_${w}`]=m[w];return x("","",y?0:1)}for(let w=0;w<l.length;w++){let b=l[w];if(w<l.length-1)t.state.env[b]=m[w]??"";else if(w<E.length){let P=Hr(d.substring(E[w]),g);t.state.env[b]=P}else t.state.env[b]=""}return x("","",y?0:1)}function Xt(t,e){if(t.state.callDepth===0&&t.state.sourceDepth===0)return S("bash: return: can only `return' from a function or sourced script\n");let s=t.state.lastExitCode;if(e.length>0){let r=e[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return S(`bash: return: ${r}: numeric argument required
|
|
66
|
+
`,2);s=(n%256+256)%256}throw new U(s)}function Pn(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var Ye=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
67
67
|
Options:
|
|
68
68
|
-e Exit immediately if a command exits with non-zero status
|
|
69
69
|
+e Disable -e
|
|
@@ -79,67 +79,67 @@ Options:
|
|
|
79
79
|
+o pipefail Disable pipefail
|
|
80
80
|
-o xtrace Same as -x
|
|
81
81
|
+o xtrace Disable xtrace
|
|
82
|
-
`,
|
|
83
|
-
`);return
|
|
84
|
-
`:"")}let s=0;for(;s<e.length;){let r=e[s];if((r==="-o"||r==="+o")&&
|
|
85
|
-
${
|
|
82
|
+
`,ls={e:"errexit",u:"nounset",x:"xtrace",v:"verbose",f:null,h:null,C:null,n:null,a:null,b:null,m:null,B:null,H:null,P:null,T:null,E:null,p:null},fs={errexit:"errexit",pipefail:"pipefail",nounset:"nounset",xtrace:"xtrace",verbose:"verbose",noclobber:null,noglob:null,noexec:null,allexport:null,notify:null,monitor:null,braceexpand:null,histexpand:null,physical:null,functrace:null,errtrace:null,privileged:null,hashall:null,posix:null,vi:null,emacs:null,ignoreeof:null,"interactive-comments":null,keyword:null,onecmd:null},us=["errexit","nounset","pipefail","verbose","xtrace"],hs=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function ds(t,e,s){e!==null&&(t.state.options[e]=s)}function In(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function Jt(t,e){if(e.includes("--help"))return H(Ye);if(e.length===0){let r=Object.entries(t.state.env).filter(([n])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${n}=${Pn(o)}`).join(`
|
|
83
|
+
`);return H(r?`${r}
|
|
84
|
+
`:"")}let s=0;for(;s<e.length;){let r=e[s];if((r==="-o"||r==="+o")&&In(e,s)){let n=e[s+1];if(!(n in fs))return S(`bash: set: ${n}: invalid option name
|
|
85
|
+
${Ye}`);ds(t,fs[n],r==="-o"),s+=2;continue}if(r==="-o"){let n=us.map(a=>`${a.padEnd(16)}${t.state.options[a]?"on":"off"}`),o=hs.map(a=>`${a.padEnd(16)}off`),i=[...n,...o].sort();return H(`${i.join(`
|
|
86
86
|
`)}
|
|
87
|
-
`)}if(r==="+o"){let n=
|
|
87
|
+
`)}if(r==="+o"){let n=us.map(a=>`set ${t.state.options[a]?"-o":"+o"} ${a}`),o=hs.map(a=>`set +o ${a}`),i=[...n,...o].sort();return H(`${i.join(`
|
|
88
88
|
`)}
|
|
89
|
-
`)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let n=r[0]==="-";for(let o=1;o<r.length;o++){let i=r[o];if(!(i in
|
|
90
|
-
${
|
|
91
|
-
${
|
|
89
|
+
`)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let n=r[0]==="-";for(let o=1;o<r.length;o++){let i=r[o];if(!(i in ls))return S(`bash: set: ${r[0]}${i}: invalid option
|
|
90
|
+
${Ye}`);ds(t,ls[i],n)}s++;continue}if(r==="--")return Yt(t,e.slice(s+1)),C;if(r==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,s+1<e.length)return Yt(t,e.slice(s+1)),C;s++;continue}if(r==="+"){s++;continue}return r.startsWith("-")||r.startsWith("+")?S(`bash: set: ${r}: invalid option
|
|
91
|
+
${Ye}`):(Yt(t,e.slice(s)),C)}return C}function Yt(t,e){let s=1;for(;t.state.env[String(s)]!==void 0;)delete t.state.env[String(s)],s++;for(let r=0;r<e.length;r++)t.state.env[String(r+1)]=e[r];t.state.env["#"]=String(e.length),t.state.env["@"]=e.join(" "),t.state.env["*"]=e.join(" ")}function er(t,e){let s=1;if(e.length>0){let i=Number.parseInt(e[0],10);if(Number.isNaN(i)||i<0)return S(`bash: shift: ${e[0]}: numeric argument required
|
|
92
92
|
`);s=i}let r=Number.parseInt(t.state.env["#"]||"0",10);if(s>r)return S(`bash: shift: shift count out of range
|
|
93
|
-
`);if(s===0)return C;let n=[];for(let i=1;i<=r;i++)n.push(t.state.env[String(i)]||"");let o=n.slice(s);for(let i=1;i<=r;i++)delete t.state.env[String(i)];for(let i=0;i<o.length;i++)t.state.env[String(i+1)]=o[i];return t.state.env["#"]=String(o.length),t.state.env["@"]=o.join(" "),C}async function
|
|
93
|
+
`);if(s===0)return C;let n=[];for(let i=1;i<=r;i++)n.push(t.state.env[String(i)]||"");let o=n.slice(s);for(let i=1;i<=r;i++)delete t.state.env[String(i)];for(let i=0;i<o.length;i++)t.state.env[String(i+1)]=o[i];return t.state.env["#"]=String(o.length),t.state.env["@"]=o.join(" "),C}async function tr(t,e){let s=e;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return x("",`bash: source: filename argument required
|
|
94
94
|
`,2);let r=s[0],n=null,o=null;if(r.includes("/")){let l=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(l),n=l}catch{}}else{let c=(t.state.env.PATH||"").split(":").filter(f=>f);for(let f of c){let h=t.fs.resolvePath(t.state.cwd,`${f}/${r}`);try{if((await t.fs.stat(h)).isDirectory)continue;o=await t.fs.readFile(h),n=h;break}catch{}}if(o===null){let f=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(f),n=f}catch{}}}if(o===null)return S(`bash: ${r}: No such file or directory
|
|
95
|
-
`);let i={};if(s.length>1){for(let c=1;c<=9;c++)i[String(c)]=t.state.env[String(c)];i["#"]=t.state.env["#"],i["@"]=t.state.env["@"];let l=s.slice(1);t.state.env["#"]=String(l.length),t.state.env["@"]=l.join(" ");for(let c=0;c<l.length&&c<9;c++)t.state.env[String(c+1)]=l[c];for(let c=l.length+1;c<=9;c++)delete t.state.env[String(c)]}let a=()=>{if(t.state.sourceDepth--,s.length>1)for(let[l,c]of Object.entries(i))c===void 0?delete t.state.env[l]:t.state.env[l]=c};t.state.sourceDepth++;try{let l=
|
|
96
|
-
`);throw l}}function
|
|
95
|
+
`);let i={};if(s.length>1){for(let c=1;c<=9;c++)i[String(c)]=t.state.env[String(c)];i["#"]=t.state.env["#"],i["@"]=t.state.env["@"];let l=s.slice(1);t.state.env["#"]=String(l.length),t.state.env["@"]=l.join(" ");for(let c=0;c<l.length&&c<9;c++)t.state.env[String(c+1)]=l[c];for(let c=l.length+1;c<=9;c++)delete t.state.env[String(c)]}let a=()=>{if(t.state.sourceDepth--,s.length>1)for(let[l,c]of Object.entries(i))c===void 0?delete t.state.env[l]:t.state.env[l]=c};t.state.sourceDepth++;try{let l=ce(o),c=await t.executeScript(l);return a(),c}catch(l){if(a(),l instanceof k)throw l;if(l instanceof U)return x(l.stdout,l.stderr,l.exitCode);if(l.name==="ParseException")return S(`bash: ${r}: ${l.message}
|
|
96
|
+
`);throw l}}function rr(t,e){let s="variable",r="",n=0;for(let o of e){if(o==="-v"){s="variable";continue}if(o==="-f"){s="function";continue}if(s==="function"){t.state.functions.delete(o);continue}let i=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let a=i[1],l=i[2];if(l==="@"||l==="*"){let f=T(t,a);for(let[h]of f)delete t.state.env[`${a}_${h}`];delete t.state.env[a];continue}let c;if(/^-?\d+$/.test(l))c=Number.parseInt(l,10);else{let f=t.state.env[l];c=f?Number.parseInt(f,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let f=T(t,a),h=f.length;if(h===0){r+=`bash: unset: [${c}]: bad array subscript
|
|
97
97
|
`,n=1;continue}let d=h+c;if(d<0){r+=`bash: unset: [${c}]: bad array subscript
|
|
98
|
-
`,n=1;continue}let p=f[d][0];delete t.state.env[`${a}_${p}`];continue}delete t.state.env[`${a}_${c}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return x("",r,n)}function
|
|
99
|
-
`,2):
|
|
100
|
-
`,2):x("","",1)}if(e.length===3){let r=e[0],n=e[1],o=e[2];if(
|
|
101
|
-
`,2):O(s.value)}async function
|
|
102
|
-
`,exitCode:1}}async function
|
|
103
|
-
`,exitCode:1}}return{stdout:n,stderr:o,exitCode:i}}async function
|
|
104
|
-
`);let i=[];if(e.words===null)i=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else for(let a of e.words){let l=await
|
|
98
|
+
`,n=1;continue}let p=f[d][0];delete t.state.env[`${a}_${p}`];continue}delete t.state.env[`${a}_${c}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return x("",r,n)}function sr(t,e){return t.fs.resolvePath(t.state.cwd,e)}var kn=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function Je(t){return kn.includes(t)}async function et(t,e,s){let r=sr(t,s);switch(e){case"-e":case"-a":return t.fs.exists(r);case"-f":return await t.fs.exists(r)?(await t.fs.stat(r)).isFile:!1;case"-d":return await t.fs.exists(r)?(await t.fs.stat(r)).isDirectory:!1;case"-r":case"-w":case"-x":return t.fs.exists(r);case"-s":return await t.fs.exists(r)?(await t.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await t.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await t.fs.exists(r)?((await t.fs.stat(r)).mode&512)!==0:!1;case"-g":return await t.fs.exists(r)?((await t.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await t.fs.exists(r)?((await t.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return t.fs.exists(r);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].some(o=>r===o||r.endsWith(o));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(r);default:return!1}}var Rn=["-nt","-ot","-ef"];function tt(t){return Rn.includes(t)}async function rt(t,e,s,r){let n=sr(t,s),o=sr(t,r);switch(e){case"-nt":try{let i=await t.fs.stat(n),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(n),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(n)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,n),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var Dn=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function st(t){return Dn.has(t)}function nt(t,e,s){switch(t){case"-eq":return e===s;case"-ne":return e!==s;case"-lt":return e<s;case"-le":return e<=s;case"-gt":return e>s;case"-ge":return e>=s}}function it(t){return t==="="||t==="=="||t==="!="}function ot(t,e,s,r=!1){let n=r?at(e,s):e===s;return t==="!="?!n:n}var On=new Set(["-z","-n"]);function ct(t){return On.has(t)}function lt(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function ft(t,e){let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let r=s[1],n=s[2];n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(n))o=Number.parseInt(n,10);else try{let i=Function(`"use strict"; return (${n})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[n];o=i?Number.parseInt(i,10):0}if(o<0){let i=Ie(t,r);if(i.length===0||(o=Math.max(...i)+1+o,o<0))return!1}return`${r}_${o}`in t.state.env}return e in t.state.env}async function ue(t,e){switch(e.type){case"CondBinary":{let s=await v(t,e.left),r=await v(t,e.right),n=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(it(e.operator))return ot(e.operator,s,r,!n);if(st(e.operator))return nt(e.operator,ms(t,s),ms(t,r));if(tt(e.operator))return rt(t,e.operator,s,r);switch(e.operator){case"=~":try{let o=new RegExp(r),i=s.match(o);if(i){t.state.env.BASH_REMATCH=i[0];for(let a=1;a<i.length;a++)t.state.env[`BASH_REMATCH_${a}`]=i[a]||""}return i!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<r;case">":return s>r;default:return!1}}case"CondUnary":{let s=await v(t,e.operand);return Je(e.operator)?et(t,e.operator,s):ct(e.operator)?lt(e.operator,s):e.operator==="-v"?ft(t,s):e.operator==="-o"?ir(t,s):!1}case"CondNot":return!await ue(t,e.operand);case"CondAnd":return await ue(t,e.left)?await ue(t,e.right):!1;case"CondOr":return await ue(t,e.left)?!0:await ue(t,e.right);case"CondGroup":return await ue(t,e.expression);case"CondWord":return await v(t,e.word)!=="";default:return!1}}async function Ce(t,e){if(e.length===0)return x("","",1);if(e.length===1)return O(!!e[0]);if(e.length===2){let r=e[0],n=e[1];return r==="("?S(`test: '(' without matching ')'
|
|
99
|
+
`,2):Je(r)?O(await et(t,r,n)):ct(r)?O(lt(r,n)):r==="!"?O(!n):r==="-v"?O(ft(t,n)):r==="-o"?O(ir(t,n)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?S(`test: ${r}: unary operator expected
|
|
100
|
+
`,2):x("","",1)}if(e.length===3){let r=e[0],n=e[1],o=e[2];if(it(n))return O(ot(n,r,o));if(st(n)){let i=ut(r),a=ut(o);return!i.valid||!a.valid?x("","",2):O(nt(n,i.value,a.value))}if(tt(n))return O(await rt(t,n,r,o));switch(n){case"-a":return O(r!==""&&o!=="");case"-o":return O(r!==""||o!=="");case">":return O(r>o);case"<":return O(r<o)}if(r==="!"){let i=await Ce(t,[n,o]);return x("",i.stderr,i.exitCode===0?1:i.exitCode===1?0:i.exitCode)}if(r==="("&&o===")")return O(n!=="")}if(e.length===4){if(e[0]==="!"){let r=await Ce(t,e.slice(1));return x("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(e[0]==="("&&e[3]===")")return Ce(t,[e[1],e[2]])}let s=await Es(t,e,0);return s.pos<e.length?S(`test: too many arguments
|
|
101
|
+
`,2):O(s.value)}async function Es(t,e,s){return _n(t,e,s)}async function _n(t,e,s){let{value:r,pos:n}=await ps(t,e,s);for(;e[n]==="-o";){let o=await ps(t,e,n+1);r=r||o.value,n=o.pos}return{value:r,pos:n}}async function ps(t,e,s){let{value:r,pos:n}=await nr(t,e,s);for(;e[n]==="-a";){let o=await nr(t,e,n+1);r=r&&o.value,n=o.pos}return{value:r,pos:n}}async function nr(t,e,s){if(e[s]==="!"){let{value:r,pos:n}=await nr(t,e,s+1);return{value:!r,pos:n}}return Ln(t,e,s)}async function Ln(t,e,s){let r=e[s];if(r==="("){let{value:o,pos:i}=await Es(t,e,s+1);return{value:o,pos:e[i]===")"?i+1:i}}if(Je(r)){let o=e[s+1]??"";return{value:await et(t,r,o),pos:s+2}}if(ct(r)){let o=e[s+1]??"";return{value:lt(r,o),pos:s+2}}if(r==="-v"){let o=e[s+1]??"";return{value:ft(t,o),pos:s+2}}if(r==="-o"){let o=e[s+1]??"";return{value:ir(t,o),pos:s+2}}let n=e[s+1];if(it(n)){let o=r,i=e[s+2]??"";return{value:ot(n,o,i),pos:s+3}}if(st(n)){let o=ut(r),i=ut(e[s+2]??"0");return!o.valid||!i.valid?{value:!1,pos:s+3}:{value:nt(n,o.value,i.value),pos:s+3}}if(tt(n)){let o=r,i=e[s+2]??"";return{value:await rt(t,n,o,i),pos:s+3}}return{value:r!==void 0&&r!=="",pos:s+1}}function at(t,e){let s="^";for(let r=0;r<e.length;r++){let n=e[r];if(n==="\\")if(r+1<e.length){let o=e[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?s+=`\\${o}`:s+=o,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let o=e.indexOf("]",r+1);o!==-1?(s+=e.slice(r,o+1),r=o):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s+="$",new RegExp(s).test(t)}function ir(t,e){let r={errexit:()=>t.state.options.errexit===!0,nounset:()=>t.state.options.nounset===!0,pipefail:()=>t.state.options.pipefail===!0,xtrace:()=>t.state.options.xtrace===!0,e:()=>t.state.options.errexit===!0,u:()=>t.state.options.nounset===!0,x:()=>t.state.options.xtrace===!0}[e];return r?r():!1}function ms(t,e){if(e=e.trim(),e==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(e))return ys(e);try{let s=new F,r=L(s,e);return N(t,r.expression)}catch{return ys(e)}}function Tn(t,e){let s=0;for(let r of t){let n;if(r>="0"&&r<="9")n=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")n=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")n=r.charCodeAt(0)-65+36;else if(r==="@")n=62;else if(r==="_")n=63;else return Number.NaN;if(n>=e)return Number.NaN;s=s*e+n}return s}function ys(t){if(t=t.trim(),t==="")return 0;let e=!1;t.startsWith("-")?(e=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1));let s,r=t.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=Tn(r[2],n):s=0}else/^0[xX][0-9a-fA-F]+$/.test(t)?s=Number.parseInt(t,16):/^0[0-7]+$/.test(t)?s=Number.parseInt(t,8):s=Number.parseInt(t,10);return Number.isNaN(s)&&(s=0),e?-s:s}function ut(t){if(t=t.trim(),t==="")return{value:0,valid:!0};let e=!1;if(t.startsWith("-")?(e=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1)),!/^\d+$/.test(t))return{value:0,valid:!1};let s=Number.parseInt(t,10);return Number.isNaN(s)?{value:0,valid:!1}:{value:e?-s:s,valid:!0}}async function or(t,e){let s=t.state.inCondition;t.state.inCondition=!0;let r="",n="",o=0;try{for(let i of e){let a=await t.executeStatement(i);r+=a.stdout,n+=a.stderr,o=a.exitCode}}finally{t.state.inCondition=s}return{stdout:r,stderr:n,exitCode:o}}function Oe(t,e,s,r){if(t instanceof z)return e+=t.stdout,s+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=s,{action:"rethrow",stdout:e,stderr:s,error:t}):{action:"break",stdout:e,stderr:s};if(t instanceof Q)return e+=t.stdout,s+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=s,{action:"rethrow",stdout:e,stderr:s,error:t}):{action:"continue",stdout:e,stderr:s};if(t instanceof U||t instanceof Y||t instanceof k||t instanceof B)return t.prependOutput(e,s),{action:"rethrow",stdout:e,stderr:s,error:t};let n=ne(t);return{action:"error",stdout:e,stderr:`${s}${n}
|
|
102
|
+
`,exitCode:1}}async function ht(t,e,s="",r=""){let n=s,o=r,i=0;try{for(let a of e){let l=await t.executeStatement(a);n+=l.stdout,o+=l.stderr,i=l.exitCode}}catch(a){if(Fe(a)||a instanceof Y||a instanceof k||a instanceof B||a instanceof ie)throw a.prependOutput(n,o),a;return{stdout:n,stderr:`${o}${ne(a)}
|
|
103
|
+
`,exitCode:1}}return{stdout:n,stderr:o,exitCode:i}}async function ws(t,e){let s="",r="";for(let n of e.clauses){let o=await or(t,n.condition);if(s+=o.stdout,r+=o.stderr,o.exitCode===0)return ht(t,n.body,s,r)}return e.elseBody?ht(t,e.elseBody,s,r):x(s,r,0)}async function gs(t,e){let s="",r="",n=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return S(`bash: \`${e.variable}': not a valid identifier
|
|
104
|
+
`);let i=[];if(e.words===null)i=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else for(let a of e.words){let l=await De(t,a);i.push(...l.values)}t.state.loopDepth++;try{for(let a of i){o++,o>t.limits.maxLoopIterations&&se(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r),t.state.env[e.variable]=a;try{for(let l of e.body){let c=await t.executeStatement(l);s+=c.stdout,r+=c.stderr,n=c.exitCode}}catch(l){let c=Oe(l,s,r,t.state.loopDepth);if(s=c.stdout,r=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return x(s,r,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return x(s,r,n)}async function As(t,e){let s="",r="",n=0,o=0;e.init&&await $(t,e.init.expression),t.state.loopDepth++;try{for(;o++,o>t.limits.maxLoopIterations&&se(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r),!(e.condition&&await $(t,e.condition.expression)===0);){try{for(let i of e.body){let a=await t.executeStatement(i);s+=a.stdout,r+=a.stderr,n=a.exitCode}}catch(i){let a=Oe(i,s,r,t.state.loopDepth);if(s=a.stdout,r=a.stderr,a.action==="break")break;if(a.action==="continue"){e.update&&await $(t,e.update.expression);continue}if(a.action==="error")return x(s,r,a.exitCode??1);throw a.error}e.update&&await $(t,e.update.expression)}}finally{t.state.loopDepth--}return x(s,r,n)}async function xs(t,e,s=""){let r="",n="",o=0,i=0,a=s;for(let c of e.redirections)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let f=c.target,h=await v(t,f.content);f.stripTabs&&(h=h.split(`
|
|
105
105
|
`).map(d=>d.replace(/^\t+/,"")).join(`
|
|
106
106
|
`)),a=h}else if(c.operator==="<<<"&&c.target.type==="Word")a=`${await v(t,c.target)}
|
|
107
107
|
`;else if(c.operator==="<"&&c.target.type==="Word")try{let f=await v(t,c.target),h=t.fs.resolvePath(t.state.cwd,f);a=await t.fs.readFile(h)}catch{let f=await v(t,c.target);return S(`bash: ${f}: No such file or directory
|
|
108
|
-
`)}let l=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&se(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let c=0,f=!1,h=!1,d=t.state.inCondition;t.state.inCondition=!0;try{for(let p of e.condition){let y=await t.executeStatement(p);r+=y.stdout,n+=y.stderr,c=y.exitCode}}catch(p){if(p instanceof z){if(r+=p.stdout,n+=p.stderr,p.levels>1&&t.state.loopDepth>1)throw p.levels--,p.stdout=r,p.stderr=n,t.state.inCondition=d,p;f=!0}else if(p instanceof Q){if(r+=p.stdout,n+=p.stderr,p.levels>1&&t.state.loopDepth>1)throw p.levels--,p.stdout=r,p.stderr=n,t.state.inCondition=d,p;h=!0}else throw t.state.inCondition=d,p}finally{t.state.inCondition=d}if(f)break;if(!h){if(c!==0)break;try{for(let p of e.body){let y=await t.executeStatement(p);r+=y.stdout,n+=y.stderr,o=y.exitCode}}catch(p){let y=
|
|
108
|
+
`)}let l=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&se(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let c=0,f=!1,h=!1,d=t.state.inCondition;t.state.inCondition=!0;try{for(let p of e.condition){let y=await t.executeStatement(p);r+=y.stdout,n+=y.stderr,c=y.exitCode}}catch(p){if(p instanceof z){if(r+=p.stdout,n+=p.stderr,p.levels>1&&t.state.loopDepth>1)throw p.levels--,p.stdout=r,p.stderr=n,t.state.inCondition=d,p;f=!0}else if(p instanceof Q){if(r+=p.stdout,n+=p.stderr,p.levels>1&&t.state.loopDepth>1)throw p.levels--,p.stdout=r,p.stderr=n,t.state.inCondition=d,p;h=!0}else throw t.state.inCondition=d,p}finally{t.state.inCondition=d}if(f)break;if(!h){if(c!==0)break;try{for(let p of e.body){let y=await t.executeStatement(p);r+=y.stdout,n+=y.stderr,o=y.exitCode}}catch(p){let y=Oe(p,r,n,t.state.loopDepth);if(r=y.stdout,n=y.stderr,y.action==="break")break;if(y.action==="continue")continue;if(y.action==="error")return x(r,n,y.exitCode??1);throw y.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=l}return x(r,n,o)}async function Ss(t,e){let s="",r="",n=0,o=0;t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&se(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r);let i=await or(t,e.condition);if(s+=i.stdout,r+=i.stderr,i.exitCode===0)break;try{for(let a of e.body){let l=await t.executeStatement(a);s+=l.stdout,r+=l.stderr,n=l.exitCode}}catch(a){let l=Oe(a,s,r,t.state.loopDepth);if(s=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return x(s,r,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return x(s,r,n)}async function bs(t,e){let s="",r="",n=0,o=await v(t,e.word),i=!1;for(let a=0;a<e.items.length;a++){let l=e.items[a],c=i;if(!i)for(let f of l.patterns){let h=await v(t,f);if(Kr(f)&&(h=Xr(h)),at(o,h)){c=!0;break}}if(c){let f=await ht(t,l.body,s,r);if(s=f.stdout,r=f.stderr,n=f.exitCode,l.terminator===";;")break;l.terminator===";&"?i=!0:i=!1}else i=!1}return x(s,r,n)}function Cs(t,e){return t.state.functions.set(e.name,e),C}async function Ns(t,e,s){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,se(`${e.name}: maximum recursion depth (${t.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),t.state.localScopes.push(new Map);let r={};for(let o=0;o<s.length;o++)r[String(o+1)]=t.state.env[String(o+1)],t.state.env[String(o+1)]=s[o];r["@"]=t.state.env["@"],r["#"]=t.state.env["#"],t.state.env["@"]=s.join(" "),t.state.env["#"]=String(s.length);let n=()=>{let o=t.state.localScopes.pop();if(o)for(let[i,a]of o)a===void 0?delete t.state.env[i]:t.state.env[i]=a;for(let[i,a]of Object.entries(r))a===void 0?delete t.state.env[i]:t.state.env[i]=a;t.state.callDepth--};try{let o=await t.executeCommand(e.body,"");return n(),o}catch(o){if(n(),o instanceof U)return x(o.stdout,o.stderr,o.exitCode);throw o}}async function $s(t,e,s){let{stdout:r,stderr:n,exitCode:o}=e;for(let i of s){if(i.target.type==="HereDoc")continue;let a=await v(t,i.target);switch(i.operator){case">":{let l=i.fd??1;if(l===1){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
109
109
|
`,o=1,r="";break}}catch{}await t.fs.writeFile(c,r),r=""}else if(l===2)if(a==="/dev/null")n="";else{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
110
110
|
`,o=1;break}}catch{}await t.fs.writeFile(c,n),n=""}break}case">>":{let l=i.fd??1;if(l===1){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
111
111
|
`,o=1,r="";break}}catch{}await t.fs.appendFile(c,r),r=""}else if(l===2){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
112
112
|
`,o=1;break}}catch{}await t.fs.appendFile(c,n),n=""}break}case">&":{let l=i.fd??1;a==="2"||a==="&2"?l===1&&(n+=r,r=""):(a==="1"||a==="&1")&&(r+=n,n="");break}case"&>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){n=`bash: ${a}: Is a directory
|
|
113
113
|
`,o=1,r="";break}}catch{}await t.fs.writeFile(l,r+n),r="",n="";break}case"&>>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){n=`bash: ${a}: Is a directory
|
|
114
|
-
`,o=1,r="";break}}catch{}await t.fs.appendFile(l,r+n),r="",n="";break}}}return x(r,n,o)}var
|
|
115
|
-
`,1);let g=
|
|
116
|
-
`,1);let d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let g=d[1],m=d[2],E=
|
|
114
|
+
`,o=1,r="";break}}catch{}await t.fs.appendFile(l,r+n),r="",n="";break}}}return x(r,n,o)}var _e=class{ctx;constructor(e,s){this.ctx={state:s,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep}}async executeScript(e){let s="",r="",n=0;for(let o of e.statements)try{let i=await this.executeStatement(o);s+=i.stdout,r+=i.stderr,n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n)}catch(i){if(i instanceof k)throw i.prependOutput(s,r),i;if(i instanceof B)throw i;if(i instanceof Y)return s+=i.stdout,r+=i.stderr,n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n),{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}};if(i instanceof K)return s+=i.stdout,r+=i.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n),{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}};if(i instanceof de)return s+=i.stdout,r+=i.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n),{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}};if(i instanceof z||i instanceof Q){if(this.ctx.state.loopDepth>0)throw i.prependOutput(s,r),i;s+=i.stdout,r+=i.stderr;continue}throw i instanceof U&&i.prependOutput(s,r),i}return{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&se(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let s="",r="",n=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let l=e.pipelines[a],c=a>0?e.operators[a-1]:null;if(c==="&&"&&n!==0||c==="||"&&n===0)continue;let f=await this.executePipeline(l);s+=f.stdout,r+=f.stderr,n=f.exitCode,o=a,i=l.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n)}if(this.ctx.state.options.errexit&&n!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new Y(n,s,r);return x(s,r,n)}async executePipeline(e){let s="",r=C,n=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],l=i===e.commands.length-1,c;try{c=await this.executeCommand(a,s)}catch(f){if(f instanceof de)c={stdout:f.stdout,stderr:f.stderr,exitCode:1};else if(f instanceof k&&e.commands.length>1)c={stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode};else throw f}o.push(c.exitCode),c.exitCode!==0&&(n=c.exitCode),l?r=c:(s=c.stdout,r={stdout:"",stderr:c.stderr,exitCode:c.exitCode})}for(let i of Object.keys(this.ctx.state.env))i.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[i];for(let i=0;i<o.length;i++)this.ctx.state.env[`PIPESTATUS_${i}`]=String(o[i]);return this.ctx.state.env.PIPESTATUS__length=String(o.length),this.ctx.state.options.pipefail&&n!==0&&(r={...r,exitCode:n}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,s){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,s);case"If":return ws(this.ctx,e);case"For":return gs(this.ctx,e);case"CStyleFor":return As(this.ctx,e);case"While":return xs(this.ctx,e,s);case"Until":return Ss(this.ctx,e);case"Case":return bs(this.ctx,e);case"Subshell":return this.executeSubshell(e,s);case"Group":return this.executeGroup(e,s);case"FunctionDef":return Cs(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return C}}async executeSimpleCommand(e,s){try{return await this.executeSimpleCommandInner(e,s)}catch(r){if(r instanceof W)return S(r.stderr);throw r}}async executeSimpleCommandInner(e,s){this.ctx.state.expansionStderr="";let r={};for(let l of e.assignments){let c=l.name;if(l.array){if(/\[.+\]$/.test(c))return x("",`bash: ${c}: cannot assign list to array member
|
|
115
|
+
`,1);let g=fe(this.ctx,c);if(g)return g;let m=[];for(let w of l.array){let b=await De(this.ctx,w);m.push(...b.values)}let E=0;if(l.append){let w=T(this.ctx,c);w.length>0&&(E=Math.max(...w.map(([P])=>typeof P=="number"?P:0))+1)}else{let w=`${c}_`;for(let b of Object.keys(this.ctx.state.env))b.startsWith(w)&&!b.includes("__")&&delete this.ctx.state.env[b]}for(let w=0;w<m.length;w++)this.ctx.state.env[`${c}_${E+w}`]=m[w];l.append||(this.ctx.state.env[`${c}__length`]=String(m.length));continue}let f=l.value?await v(this.ctx,l.value):"";if(c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return x("",`bash: ${c}: bad array subscript
|
|
116
|
+
`,1);let d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let g=d[1],m=d[2],E=fe(this.ctx,g);if(E)return E;let w=this.ctx.state.associativeArrays?.has(g),b;if(w){let I;if(m.startsWith("'")&&m.endsWith("'"))I=m.slice(1,-1);else if(m.startsWith('"')&&m.endsWith('"')){let R=m.slice(1,-1),_=new F().parseWordFromString(R,!0,!1);I=await v(this.ctx,_)}else if(m.includes("$")){let he=new F().parseWordFromString(m,!1,!1);I=await v(this.ctx,he)}else I=m;b=`${g}_${I}`}else{let I;if(/^-?\d+$/.test(m))I=Number.parseInt(m,10);else{try{let R=new F,he=L(R,m);I=N(this.ctx,he.expression)}catch{let R=this.ctx.state.env[m];I=R?Number.parseInt(R,10):0}Number.isNaN(I)&&(I=0)}if(I<0){let R=T(this.ctx,g);if(R.length===0)return x("",`bash: ${g}[${m}]: bad array subscript
|
|
117
117
|
`,1);if(I=Math.max(...R.map(([_])=>typeof _=="number"?_:0))+1+I,I<0)return x("",`bash: ${g}[${m}]: bad array subscript
|
|
118
|
-
`,1)}b=`${g}_${I}`}let P=l.append?(this.ctx.state.env[b]||"")+f:f;e.name?(r[b]=this.ctx.state.env[b],this.ctx.state.env[b]=P):this.ctx.state.env[b]=P;continue}let p=
|
|
118
|
+
`,1)}b=`${g}_${I}`}let P=l.append?(this.ctx.state.env[b]||"")+f:f;e.name?(r[b]=this.ctx.state.env[b],this.ctx.state.env[b]=P):this.ctx.state.env[b]=P;continue}let p=fe(this.ctx,c);if(p)return p;let y=l.append?(this.ctx.state.env[c]||"")+f:f;e.name?(r[c]=this.ctx.state.env[c],this.ctx.state.env[c]=y):this.ctx.state.env[c]=y}if(!e.name)return x("","",this.ctx.state.lastExitCode);for(let l of e.redirections){if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let c=l.target,f=await v(this.ctx,c.content);c.stripTabs&&(f=f.split(`
|
|
119
119
|
`).map(h=>h.replace(/^\t+/,"")).join(`
|
|
120
120
|
`)),s=f;continue}if(l.operator==="<<<"&&l.target.type==="Word"){s=`${await v(this.ctx,l.target)}
|
|
121
121
|
`;continue}if(l.operator==="<"&&l.target.type==="Word")try{let c=await v(this.ctx,l.target),f=this.ctx.fs.resolvePath(this.ctx.state.cwd,c);s=await this.ctx.fs.readFile(f)}catch{let c=await v(this.ctx,l.target);for(let[f,h]of Object.entries(r))h===void 0?delete this.ctx.state.env[f]:this.ctx.state.env[f]=h;return S(`bash: ${c}: No such file or directory
|
|
122
|
-
`)}}let n=await v(this.ctx,e.name),o=[],i=[];for(let l of e.args){let c=await
|
|
123
|
-
`,127)}let a=await this.runCommand(n,o,i,s);a=await
|
|
122
|
+
`)}}let n=await v(this.ctx,e.name),o=[],i=[];for(let l of e.args){let c=await De(this.ctx,l);for(let f of c.values)o.push(f),i.push(c.quoted)}if(!n){if(e.name.parts.every(c=>c.type==="CommandSubstitution"||c.type==="ParameterExpansion"||c.type==="ArithmeticExpansion")){if(o.length>0){let c=o.shift();return i.shift(),await this.runCommand(c,o,i,s)}return x("","",this.ctx.state.lastExitCode)}return S(`bash: : command not found
|
|
123
|
+
`,127)}let a=await this.runCommand(n,o,i,s);a=await $s(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:n;for(let[l,c]of Object.entries(r))c===void 0?delete this.ctx.state.env[l]:this.ctx.state.env[l]=c;return this.ctx.state.expansionStderr&&(a={...a,stderr:this.ctx.state.expansionStderr+a.stderr},this.ctx.state.expansionStderr=""),a}async runCommand(e,s,r,n,o=!1){if(e==="cd")return await Bt(this.ctx,s);if(e==="export")return Zt(this.ctx,s);if(e==="unset")return rr(this.ctx,s);if(e==="exit")return Vt(this.ctx,s);if(e==="local")return Qt(this.ctx,s);if(e==="set")return Jt(this.ctx,s);if(e==="break")return Mt(this.ctx,s);if(e==="continue")return zt(this.ctx,s);if(e==="return")return Xt(this.ctx,s);if(e==="eval")return Ht(this.ctx,s);if(e==="shift")return er(this.ctx,s);if(e==="source"||e===".")return tr(this.ctx,s);if(e==="read")return Kt(this.ctx,s,n);if(e==="declare"||e==="typeset")return jt(this.ctx,s);if(e==="readonly")return Gt(this.ctx,s);if(!o){let f=this.ctx.state.functions.get(e);if(f)return Ns(this.ctx,f,s)}if(e===":"||e==="true")return C;if(e==="false")return O(!1);if(e==="let")return qt(this.ctx,s);if(e==="command"){if(s.length===0)return C;let f=s;for(;f.length>0&&f[0].startsWith("-");)f=f.slice(1);if(f.length===0)return C;let[h,...d]=f;return this.runCommand(h,d,[],n,!0)}if(e==="builtin"){if(s.length===0)return C;let[f,...h]=s;return this.runCommand(f,h,[],n)}if(e==="shopt")return C;if(e==="exec"){if(s.length===0)return C;let[f,...h]=s;return this.runCommand(f,h,[],n)}if(e==="wait")return C;if(e==="type")return this.handleType(s);if(e==="[["){let f=s.lastIndexOf("]]");if(f!==-1){let h=s.slice(0,f);return Ce(this.ctx,h)}return S("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let f=s;if(e==="["){if(s[s.length-1]!=="]")return S("[: missing `]'\n",2);f=s.slice(0,-1)}return Ce(this.ctx,f)}let i=await this.resolveCommand(e);if(!i)return S(`bash: ${e}: command not found
|
|
124
124
|
`,127);let{cmd:a,path:l}=i,c={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:n,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep};try{return await a.execute(s,c)}catch(f){return S(`${e}: ${ne(f)}
|
|
125
125
|
`)}}async resolveCommand(e){if(e.includes("/")){let o=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(o))return null;let i=o.split("/").pop()||e,a=this.ctx.commands.get(i);return a?{cmd:a,path:o}:null}let r=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of r){if(!o)continue;let i=`${o}/${e}`;if(await this.ctx.fs.exists(i)){let a=this.ctx.commands.get(e);if(a)return{cmd:a,path:i}}}if(!await this.ctx.fs.exists("/bin")){let o=this.ctx.commands.get(e);if(o)return{cmd:o,path:`/bin/${e}`}}return null}async findCommandInPath(e){let s=[],n=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of n){if(!o)continue;let i=`${o}/${e}`;await this.ctx.fs.exists(i)&&s.push(i)}return s}handleType(e){let s=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),r=new Set(["cd","export","unset","exit","local","set","break","continue","return","eval","shift","source",".","read","declare","typeset","readonly",":","true","false","let","command","builtin","shopt","exec","wait","type","[","test"]),n="",o="",i=0;for(let a of e)s.has(a)?n+=`${a} is a shell keyword
|
|
126
126
|
`:r.has(a)?n+=`${a} is a shell builtin
|
|
127
127
|
`:this.ctx.state.functions.has(a)?n+=`${a} is a function
|
|
128
128
|
`:this.ctx.commands.has(a)?n+=`${a} is /bin/${a}
|
|
129
129
|
`:(o+=`bash: type: ${a}: not found
|
|
130
|
-
`,i=1);return x(n,o,i)}async executeSubshell(e,s=""){let r={...this.ctx.state.env},n=this.ctx.state.cwd,o=this.ctx.state.loopDepth;this.ctx.state.loopDepth=0;let
|
|
131
|
-
`,1)}return this.ctx.state.env=r,this.ctx.state.cwd=n,this.ctx.state.loopDepth=o,this.ctx.state.
|
|
130
|
+
`,i=1);return x(n,o,i)}async executeSubshell(e,s=""){let r={...this.ctx.state.env},n=this.ctx.state.cwd,o=this.ctx.state.loopDepth,i=this.ctx.state.parentHasLoopContext;this.ctx.state.parentHasLoopContext=o>0,this.ctx.state.loopDepth=0;let a=this.ctx.state.groupStdin;s&&(this.ctx.state.groupStdin=s);let l="",c="",f=0;try{for(let h of e.body){let d=await this.executeStatement(h);l+=d.stdout,c+=d.stderr,f=d.exitCode}}catch(h){if(this.ctx.state.env=r,this.ctx.state.cwd=n,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,h instanceof B)throw h;if(h instanceof ie)return l+=h.stdout,c+=h.stderr,x(l,c,0);if(h instanceof z||h instanceof Q)return l+=h.stdout,c+=h.stderr,x(l,c,0);if(h instanceof k)return l+=h.stdout,c+=h.stderr,x(l,c,h.exitCode);if(h instanceof U)return l+=h.stdout,c+=h.stderr,x(l,c,h.exitCode);if(h instanceof Y)throw h.stdout=l+h.stdout,h.stderr=c+h.stderr,h;return x(l,`${c}${ne(h)}
|
|
131
|
+
`,1)}return this.ctx.state.env=r,this.ctx.state.cwd=n,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,x(l,c,f)}async executeGroup(e,s=""){let r="",n="",o=0,i=this.ctx.state.groupStdin;s&&(this.ctx.state.groupStdin=s);try{for(let a of e.body){let l=await this.executeStatement(a);r+=l.stdout,n+=l.stderr,o=l.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof B)throw a;if(Fe(a)||a instanceof Y||a instanceof k)throw a.prependOutput(r,n),a;return x(r,`${n}${ne(a)}
|
|
132
132
|
`,1)}return this.ctx.state.groupStdin=i,x(r,n,o)}async executeArithmeticCommand(e){try{let s=await $(this.ctx,e.expression.expression);return O(s!==0)}catch(s){return S(`bash: arithmetic expression: ${s.message}
|
|
133
|
-
`)}}async executeConditionalCommand(e){try{let s=await
|
|
134
|
-
`,2)}}};var
|
|
135
|
-
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits
|
|
133
|
+
`)}}async executeConditionalCommand(e){try{let s=await ue(this.ctx,e.expression);return O(s)}catch(s){return S(`bash: conditional expression: ${s.message}
|
|
134
|
+
`,2)}}};var Ne={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4};function vs(t){return t?{maxCallDepth:t.maxCallDepth??Ne.maxCallDepth,maxCommandCount:t.maxCommandCount??Ne.maxCommandCount,maxLoopIterations:t.maxLoopIterations??Ne.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??Ne.maxAwkIterations,maxSedIterations:t.maxSedIterations??Ne.maxSedIterations}:{...Ne}}function Ps(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function Wn(t){let e=Ps(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function Fn(t,e){let s=Ps(t);if(!s)return!1;let r=Wn(e);return!r||s.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:s.pathname.startsWith(r.pathPrefix)}function ar(t,e){return!e||e.length===0?!1:e.some(s=>Fn(t,s))}var Le=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Te=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},We=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},dt=class extends Error{constructor(e,s){super(`HTTP method '${e}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}};var Mn=20,Bn=3e4,zn=["GET","HEAD"],Un=new Set(["GET","HEAD","OPTIONS"]),jn=new Set([301,302,303,307,308]);function cr(t){let e=t.maxRedirects??Mn,s=t.timeoutMs??Bn,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??zn;function n(a){if(!t.dangerouslyAllowFullInternetAccess&&!ar(a,t.allowedUrlPrefixes??[]))throw new Le(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let l=a.toUpperCase();if(!r.includes(l))throw new dt(l,r)}async function i(a,l={}){let c=l.method?.toUpperCase()??"GET";n(a),o(c);let f=a,h=0,d=l.followRedirects??!0,p=l.timeoutMs!==void 0?Math.min(l.timeoutMs,s):s;for(;;){let y=new AbortController,g=setTimeout(()=>y.abort(),p);try{let m={method:c,headers:l.headers,signal:y.signal,redirect:"manual"};l.body&&!Un.has(c)&&(m.body=l.body);let E=await fetch(f,m);if(jn.has(E.status)&&d){let w=E.headers.get("location");if(!w)return await Is(E,f);let b=new URL(w,f).href;if(!t.dangerouslyAllowFullInternetAccess&&!ar(b,t.allowedUrlPrefixes??[]))throw new We(b);if(h++,h>e)throw new Te(e);f=b;continue}return await Is(E,f)}finally{clearTimeout(g)}}}return i}async function Is(t,e){let s={};return t.headers.forEach((r,n)=>{s[n.toLowerCase()]=r}),{status:t.status,statusText:t.statusText,headers:s,body:await t.text(),url:e}}var pt=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;logger;state;constructor(e={}){let s=e.fs??new pe(e.files);this.fs=s,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),n={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
|
|
135
|
+
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=vs({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.network&&(this.secureFetch=cr(e.network)),this.sleepFn=e.sleep,this.logger=e.logger,this.state={env:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},s instanceof pe)try{s.mkdirSync("/bin",{recursive:!0}),s.mkdirSync("/usr/bin",{recursive:!0}),this.useDefaultLayout&&(s.mkdirSync("/home/user",{recursive:!0}),s.mkdirSync("/tmp",{recursive:!0}))}catch{}if(r!=="/"&&s instanceof pe)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let o of hr(e.commands))this.registerCommand(o);if(e.network)for(let o of dr())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)pr(o)?this.registerCommand(mr(o)):this.registerCommand(o)}registerCommand(e){if(this.commands.set(e.name,e),this.fs instanceof pe)try{this.fs.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
|
|
136
136
|
# Built-in command: ${e.name}
|
|
137
137
|
`)}catch{}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e}async exec(e,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
138
138
|
`,exitCode:1,env:{...this.state.env,...s?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...s?.env}};this.logger?.info("exec",{command:e});let r=s?.cwd??this.state.cwd,n={...this.state,env:{...this.state.env,...s?.env,...s?.cwd?{PWD:s.cwd}:{}},cwd:r,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},o=e;s?.rawScript||(o=e.split(`
|
|
139
139
|
`).map(a=>a.trimStart()).join(`
|
|
140
|
-
`));try{let i=
|
|
140
|
+
`));try{let i=ce(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn},c=await new _e(a,n).executeScript(i);return this.logResult(c)}catch(i){if(i instanceof k)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...s?.env}});if(i instanceof W)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...s?.env}});if(i instanceof B)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:B.EXIT_CODE,env:{...this.state.env,...s?.env}});if(i.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${i.message}
|
|
141
141
|
`,exitCode:2,env:{...this.state.env,...s?.env}});if(i instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${i.message}
|
|
142
|
-
`,exitCode:1,env:{...this.state.env,...s?.env}});throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,s){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),s)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};import*as M from"node:fs";import*as Ne from"node:path";var jn="/home/user/project",$e=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Ne.resolve(e.root);let s=e.mountPoint??jn;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);if(this.readOnly=e.readOnly??!1,!M.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!M.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${e}`)}createMountPointDirs(){let e=this.mountPoint.split("/").filter(Boolean),s="";for(let r of e)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}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let s=this.normalizePath(e),r=this.getRelativeToMount(s);if(r===null)return null;let n=Ne.join(this.root,r),o=Ne.resolve(n);return!o.startsWith(this.root)&&o!==this.root.replace(/\/$/,"")?null:o}dirname(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}ensureParentDirs(e){let s=this.dirname(e);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(e){let s=this.normalizePath(e);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.toRealPath(s);if(!r)return!1;try{return await M.promises.access(r),!0}catch{return!1}}async readFile(e,s){let r=await this.readFileBuffer(e),n=ie(s);return Fe(r,n)}async readFileBuffer(e,s=new Set){let r=this.normalizePath(e);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let i=this.resolveSymlink(r,n.target);return this.readFileBuffer(i,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return n.content}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let i=await M.promises.lstat(o);if(i.isSymbolicLink()){let l=await M.promises.readlink(o),c=this.resolveSymlink(r,l);return this.readFileBuffer(c,s)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await M.promises.readFile(o);return new Uint8Array(a)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):i}}async writeFile(e,s,r){this.assertWritable(`write '${e}'`);let n=this.normalizePath(e);this.ensureParentDirs(n);let o=ie(r),i=we(s,o);this.memory.set(n,{type:"file",content:i,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(e,s,r){this.assertWritable(`append '${e}'`);let n=this.normalizePath(e),o=ie(r),i=we(s,o),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+i.length);l.set(a),l.set(i,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(e){return this.existsInOverlay(e)}async stat(e,s=new Set){let r=this.normalizePath(e);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);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 i=0;return n.type==="file"&&(i=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:i,mtime:n.mtime}}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let i=await M.promises.stat(o);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:!1,mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):i}}async lstat(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);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 o=0;return r.type==="file"&&(o=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:o,mtime:r.mtime}}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let o=await M.promises.lstat(n);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:o.isSymbolicLink(),mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):o}}resolveSymlink(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(e,s){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let o=this.dirname(r);if(o!=="/"&&!await this.existsInOverlay(o))if(s?.recursive)await this.mkdir(o,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdir(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set,n=new Set,o=s==="/"?"/":`${s}/`;for(let a of this.deleted)if(a.startsWith(o)){let l=a.slice(o.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let a of this.memory.keys())if(a!==s&&a.startsWith(o)){let c=a.slice(o.length).split("/")[0];c&&!n.has(c)&&r.add(c)}let i=this.toRealPath(s);if(i)try{let a=await M.promises.readdir(i);for(let l of a)n.has(l)||r.add(l)}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return Array.from(r).sort()}async rm(e,s){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}try{if((await this.stat(r)).isDirectory){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,s)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,s,r){this.assertWritable(`cp '${s}'`);let n=this.normalizePath(e),o=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(n);if(a.isFile){let l=await this.readFileBuffer(n);await this.writeFile(o,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let l=await this.readdir(n);for(let c of l){let f=n==="/"?`/${c}`:`${n}/${c}`,h=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(f,h,r)}}}async mv(e,s){this.assertWritable(`mv '${s}'`),await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let s of this.deleted)e.delete(s);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,s){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let n=M.readdirSync(r);for(let o of n){let i=e==="/"?`/${o}`:`${e}/${o}`;if(this.deleted.has(i))continue;s.add(i);let a=Ne.join(r,o);M.statSync(a).isDirectory()&&this.scanRealFs(i,s)}}catch{}}async chmod(e,s){this.assertWritable(`chmod '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);let o=this.memory.get(r);if(o){o.mode=s;return}let i=await this.stat(r);if(i.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:s,mtime:new Date})}else i.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(e,s){this.assertWritable(`symlink '${s}'`);let r=this.normalizePath(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,s){this.assertWritable(`link '${s}'`);let r=this.normalizePath(e),n=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${e}'`);let i=await this.stat(r);if(!i.isFile)throw new Error(`EPERM: operation not permitted, link '${e}'`);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:i.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await M.promises.readlink(n)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):o.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):o}}};function ks(){console.log(`just-bash - A secure bash environment for AI agents
|
|
142
|
+
`,exitCode:1,env:{...this.state.env,...s?.env}});throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,s){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),s)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};import*as M from"node:fs";import*as $e from"node:path";var Gn="/home/user/project",ve=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=$e.resolve(e.root);let s=e.mountPoint??Gn;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);if(this.readOnly=e.readOnly??!1,!M.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!M.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${e}`)}createMountPointDirs(){let e=this.mountPoint.split("/").filter(Boolean),s="";for(let r of e)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}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let s=this.normalizePath(e),r=this.getRelativeToMount(s);if(r===null)return null;let n=$e.join(this.root,r),o=$e.resolve(n);return!o.startsWith(this.root)&&o!==this.root.replace(/\/$/,"")?null:o}dirname(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}ensureParentDirs(e){let s=this.dirname(e);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(e){let s=this.normalizePath(e);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.toRealPath(s);if(!r)return!1;try{return await M.promises.access(r),!0}catch{return!1}}async readFile(e,s){let r=await this.readFileBuffer(e),n=oe(s);return Me(r,n)}async readFileBuffer(e,s=new Set){let r=this.normalizePath(e);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let i=this.resolveSymlink(r,n.target);return this.readFileBuffer(i,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return n.content}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let i=await M.promises.lstat(o);if(i.isSymbolicLink()){let l=await M.promises.readlink(o),c=this.resolveSymlink(r,l);return this.readFileBuffer(c,s)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await M.promises.readFile(o);return new Uint8Array(a)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):i}}async writeFile(e,s,r){this.assertWritable(`write '${e}'`);let n=this.normalizePath(e);this.ensureParentDirs(n);let o=oe(r),i=ge(s,o);this.memory.set(n,{type:"file",content:i,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(e,s,r){this.assertWritable(`append '${e}'`);let n=this.normalizePath(e),o=oe(r),i=ge(s,o),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+i.length);l.set(a),l.set(i,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(e){return this.existsInOverlay(e)}async stat(e,s=new Set){let r=this.normalizePath(e);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);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 i=0;return n.type==="file"&&(i=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:i,mtime:n.mtime}}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let i=await M.promises.stat(o);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:!1,mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):i}}async lstat(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);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 o=0;return r.type==="file"&&(o=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:o,mtime:r.mtime}}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let o=await M.promises.lstat(n);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:o.isSymbolicLink(),mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):o}}resolveSymlink(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(e,s){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let o=this.dirname(r);if(o!=="/"&&!await this.existsInOverlay(o))if(s?.recursive)await this.mkdir(o,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdir(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set,n=new Set,o=s==="/"?"/":`${s}/`;for(let a of this.deleted)if(a.startsWith(o)){let l=a.slice(o.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let a of this.memory.keys())if(a!==s&&a.startsWith(o)){let c=a.slice(o.length).split("/")[0];c&&!n.has(c)&&r.add(c)}let i=this.toRealPath(s);if(i)try{let a=await M.promises.readdir(i);for(let l of a)n.has(l)||r.add(l)}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return Array.from(r).sort()}async rm(e,s){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}try{if((await this.stat(r)).isDirectory){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,s)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,s,r){this.assertWritable(`cp '${s}'`);let n=this.normalizePath(e),o=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(n);if(a.isFile){let l=await this.readFileBuffer(n);await this.writeFile(o,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let l=await this.readdir(n);for(let c of l){let f=n==="/"?`/${c}`:`${n}/${c}`,h=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(f,h,r)}}}async mv(e,s){this.assertWritable(`mv '${s}'`),await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let s of this.deleted)e.delete(s);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,s){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let n=M.readdirSync(r);for(let o of n){let i=e==="/"?`/${o}`:`${e}/${o}`;if(this.deleted.has(i))continue;s.add(i);let a=$e.join(r,o);M.statSync(a).isDirectory()&&this.scanRealFs(i,s)}}catch{}}async chmod(e,s){this.assertWritable(`chmod '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);let o=this.memory.get(r);if(o){o.mode=s;return}let i=await this.stat(r);if(i.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:s,mtime:new Date})}else i.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(e,s){this.assertWritable(`symlink '${s}'`);let r=this.normalizePath(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,s){this.assertWritable(`link '${s}'`);let r=this.normalizePath(e),n=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${e}'`);let i=await this.stat(r);if(!i.isFile)throw new Error(`EPERM: operation not permitted, link '${e}'`);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:i.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await M.promises.readlink(n)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):o.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):o}}};function Rs(){console.log(`just-bash - A secure bash environment for AI agents
|
|
143
143
|
|
|
144
144
|
Usage:
|
|
145
145
|
just-bash [options] [script-file]
|
|
@@ -184,5 +184,5 @@ Examples:
|
|
|
184
184
|
|
|
185
185
|
# Allow write operations (writes stay in memory)
|
|
186
186
|
just-bash -c 'echo test > /tmp/file.txt && cat /tmp/file.txt' --allow-write
|
|
187
|
-
`)}function
|
|
188
|
-
${s}`);try{let a=await i.exec(s);e.json?console.log(JSON.stringify({stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})):(a.stdout&&process.stdout.write(a.stdout),a.stderr&&process.stderr.write(a.stderr)),process.exit(a.exitCode)}catch(a){e.json?console.log(JSON.stringify({stdout:"",stderr:a instanceof Error?a.message:String(a),exitCode:1})):console.error(a instanceof Error?a.message:String(a)),process.exit(1)}}
|
|
187
|
+
`)}function Hn(){console.log("just-bash 1.0.0")}function Vn(t){let e={root:process.cwd(),cwd:"/",cwdOverridden:!1,errexit:!1,allowWrite:!1,json:!1,help:!1,version:!1},s=0;for(;s<t.length;){let r=t[s];if(r==="-h"||r==="--help")e.help=!0,s++;else if(r==="-v"||r==="--version")e.version=!0,s++;else if(r==="-c")s+1>=t.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),e.script=t[s+1],s+=2;else if(r==="-e"||r==="--errexit")e.errexit=!0,s++;else if(r==="--root")s+1>=t.length&&(console.error("Error: --root requires a path argument"),process.exit(1)),e.root=ks(t[s+1]),s+=2;else if(r==="--cwd")s+1>=t.length&&(console.error("Error: --cwd requires a path argument"),process.exit(1)),e.cwd=t[s+1],e.cwdOverridden=!0,s+=2;else if(r==="--json")e.json=!0,s++;else if(r==="--allow-write")e.allowWrite=!0,s++;else if(r.startsWith("-"))if(r.length>2&&!r.startsWith("--")){let n=r.slice(1);for(let o of n)if(o==="e")e.errexit=!0;else if(o==="h")e.help=!0;else if(o==="v")e.version=!0;else if(o==="c"){s+1>=t.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),e.script=t[s+1],s++;break}else console.error(`Error: Unknown option: -${o}`),process.exit(1);s++}else console.error(`Error: Unknown option: ${r}`),process.exit(1);else!e.scriptFile&&!e.script?e.scriptFile=r:e.scriptFile&&e.root===process.cwd()&&(e.root=ks(r)),s++}return e}async function Zn(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function qn(){let t=process.argv.slice(2),e=Vn(t);e.help&&(Rs(),process.exit(0)),e.version&&(Hn(),process.exit(0));let s;if(e.script)s=e.script;else if(e.scriptFile){let a=new ve({root:e.root}),l=a.getMountPoint();try{let c=e.scriptFile.startsWith("/")?e.scriptFile:`${l}/${e.scriptFile}`;s=await a.readFile(c,"utf-8")}catch(c){console.error(`Error: Cannot read script file: ${e.scriptFile}`),console.error(c instanceof Error?c.message:String(c)),process.exit(1)}}else process.stdin.isTTY?(Rs(),process.exit(1)):s=await Zn();s.trim()||(e.json&&console.log(JSON.stringify({stdout:"",stderr:"",exitCode:0})),process.exit(0));let r=new ve({root:e.root,readOnly:!e.allowWrite}),n=r.getMountPoint(),o=e.cwdOverridden?e.cwd:n,i=new pt({fs:r,cwd:o});e.errexit&&(s=`set -e
|
|
188
|
+
${s}`);try{let a=await i.exec(s);e.json?console.log(JSON.stringify({stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})):(a.stdout&&process.stdout.write(a.stdout),a.stderr&&process.stderr.write(a.stderr)),process.exit(a.exitCode)}catch(a){e.json?console.log(JSON.stringify({stdout:"",stderr:a instanceof Error?a.message:String(a),exitCode:1})):console.error(a instanceof Error?a.message:String(a)),process.exit(1)}}qn().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
|