just-bash 2.5.1 → 2.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/bin/chunks/chunk-UKYJ3JMW.js +17 -0
  2. package/dist/bin/chunks/file-LNCFDPQZ.js +23 -0
  3. package/dist/bin/chunks/grep-JUSJYJL4.js +9 -0
  4. package/dist/bin/chunks/rg-4VGBMMUO.js +33 -0
  5. package/dist/bin/just-bash.js +99 -99
  6. package/dist/bin/shell/chunks/chunk-UKYJ3JMW.js +17 -0
  7. package/dist/bin/shell/chunks/file-LNCFDPQZ.js +23 -0
  8. package/dist/bin/shell/chunks/grep-JUSJYJL4.js +9 -0
  9. package/dist/bin/shell/chunks/rg-4VGBMMUO.js +33 -0
  10. package/dist/bin/shell/shell.js +33 -33
  11. package/dist/bundle/browser.js +332 -332
  12. package/dist/bundle/chunks/chunk-PINJ2PBS.js +16 -0
  13. package/dist/bundle/chunks/file-XPA6O6H2.js +22 -0
  14. package/dist/bundle/chunks/grep-TKGBN6VV.js +8 -0
  15. package/dist/bundle/chunks/rg-QWPJPSNC.js +32 -0
  16. package/dist/bundle/index.js +116 -116
  17. package/dist/commands/search-engine/index.d.ts +1 -1
  18. package/dist/commands/search-engine/matcher.d.ts +2 -0
  19. package/dist/commands/search-engine/regex.d.ts +6 -1
  20. package/package.json +1 -1
  21. package/dist/bin/chunks/chunk-CTLU5QUH.js +0 -17
  22. package/dist/bin/chunks/file-XMPFXMUJ.js +0 -23
  23. package/dist/bin/chunks/grep-QCXXYC54.js +0 -9
  24. package/dist/bin/chunks/rg-GVIT6FTE.js +0 -33
  25. package/dist/bin/shell/chunks/chunk-CTLU5QUH.js +0 -17
  26. package/dist/bin/shell/chunks/file-XMPFXMUJ.js +0 -23
  27. package/dist/bin/shell/chunks/grep-QCXXYC54.js +0 -9
  28. package/dist/bin/shell/chunks/rg-GVIT6FTE.js +0 -33
  29. package/dist/bundle/chunks/chunk-OHJS5H37.js +0 -16
  30. package/dist/bundle/chunks/file-AWZ3TUFP.js +0 -22
  31. package/dist/bundle/chunks/grep-TUWLGQC2.js +0 -8
  32. package/dist/bundle/chunks/rg-KTCMPGU6.js +0 -32
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as z,b as K,c as U,d as Y,e as X,f as k,g as W,h as me,i as B,j as ie,k as Ue}from"./chunks/chunk-NWWB2XRE.js";import"./chunks/chunk-OBH7XN5N.js";import{a as se}from"./chunks/chunk-4VDEBYW7.js";import"./chunks/chunk-KGOUQS5A.js";import{resolve as Mn}from"node:path";var ge=[{name:"echo",load:async()=>(await import("./chunks/echo-WSKTON6U.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-AJXZOSPN.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-HWUQKYUM.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-BEHQBUMC.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-XJABRAUN.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-TSNAXMZ2.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-2PKAWTSQ.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-XXWRVG2D.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-3ATZ2ABL.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-EFFNQ3RY.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-3DIKREF7.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-53KG2MCJ.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-VL3R4LAM.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-DYK37Z24.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-BES27CZT.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-QSBRKIF5.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-UEQ7KMY5.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-QCXXYC54.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-QCXXYC54.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-QCXXYC54.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-GVIT6FTE.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-5LQMJYRJ.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-D2US2LMM.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-KUHOCH5S.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-IXHB2FVS.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-CPIFQTKY.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-IHF6BEOO.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-FT6WBQZG.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-MBLEXZBI.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-VP42N2JN.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-DSM3NUGM.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-452R4I2C.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-77K5HH2M.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-BFVYAPOU.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-ZEKN6D4Q.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-JJFZRWRC.js")).split},{name:"column",load:async()=>(await import("./chunks/column-TSFEMTG6.js")).column},{name:"join",load:async()=>(await import("./chunks/join-3IXMEGNA.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-ZFIT2GTM.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-CBEJ35BR.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SO5MVUEX.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-EES7TR26.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-DQBEJH47.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-XQPYLN3H.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-YLLSNZZN.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-YLLSNZZN.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-PCMLRCRW.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-PCMLRCRW.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-G5C2J2OY.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-IWT2HHEA.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-OVATH2SQ.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-OVATH2SQ.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-CI7A5IXQ.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-UT3MT5UU.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-UT3MT5UU.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-XXZPU5CA.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-O7TCK5TL.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-GI3QVUGD.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-IQLPMFYI.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-O5BOTJGJ.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-JED4EKFH.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-AVK43XM2.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-RMGXYNQJ.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-2VAAFCTS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-67P4ME4N.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-MV3WQ4QF.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-XMPFXMUJ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-EPEXKI4B.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-7C5JICNL.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-73KOOLC6.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-KNRFDAY7.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-WXDKRL2Z.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-SLM7SRWU.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-YXK3WZQL.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-YXK3WZQL.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-YXK3WZQL.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ge.push({name:"tar",load:async()=>(await import("./chunks/tar-C27YYUAS.js")).tarCommand}),ge.push({name:"yq",load:async()=>(await import("./chunks/yq-MF2SNFGL.js")).yqCommand}),ge.push({name:"xan",load:async()=>(await import("./chunks/xan-6K2NGTHM.js")).xanCommand}),ge.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-THMDBIGF.js")).sqlite3Command}));var zn=[{name:"curl",load:async()=>(await import("./chunks/curl-LCMREE7R.js")).curlCommand}],hr=new Map;function mr(t){return{name:t.name,async execute(e,n){let r=hr.get(t.name);return r||(r=await t.load(),hr.set(t.name,r)),r.execute(e,n)}}}function pr(t){return(t?ge.filter(n=>t.includes(n.name)):ge).map(mr)}function yr(){return zn.map(mr)}function wr(t){return"load"in t&&typeof t.load=="function"}function Er(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var Un=new TextEncoder,jn=new TextDecoder;function Ae(t,e){if(t instanceof Uint8Array)return t;if(e==="base64")return Uint8Array.from(atob(t),n=>n.charCodeAt(0));if(e==="hex"){let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}return e==="binary"||e==="latin1"?Uint8Array.from(t,n=>n.charCodeAt(0)):Un.encode(t)}function je(t,e){return e==="base64"?btoa(String.fromCharCode(...t)):e==="hex"?Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join(""):e==="binary"||e==="latin1"?String.fromCharCode(...t):jn.decode(t)}function oe(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Ge=new TextEncoder;function Gn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var ke=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[n,r]of Object.entries(e))Gn(r)?this.writeFileSync(n,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(n,r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,n,r,s){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=oe(r),a=Ae(n,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,n){let r=await this.readFileBuffer(e),s=oe(n);return je(r,s)}async readFileBuffer(e){let n=this.resolvePathWithSymlinks(e),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:Ge.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=oe(r),a=Ae(n,i);if(o?.type==="file"){let c=o.content instanceof Uint8Array?o.content:Ge.encode(o.content),l=new Uint8Array(c.length+a.length);l.set(c),l.set(a,c.length),this.data.set(s,{type:"file",content:l,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){try{let n=this.resolvePathWithSymlinks(e);return this.data.has(n)}catch{return!1}}async stat(e){let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ge.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}async lstat(e){let n=this.resolveIntermediateSymlinks(e),r=this.data.get(n);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 s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ge.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}resolveIntermediateSymlinks(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",o=new Set;for(let i=0;i<r.length-1;i++){let a=r[i];s=`${s}/${a}`;let c=this.data.get(s),l=0,f=40;for(;c&&c.type==="symlink"&&l<f;){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);o.add(s),s=this.resolveSymlink(s,c.target),c=this.data.get(s),l++}if(l>=f)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",o=new Set;for(let i of r){s=`${s}/${i}`;let a=this.data.get(s),c=0,l=40;for(;a&&a.type==="symlink"&&c<l;){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,a.target),a=this.data.get(s),c++}if(c>=l)throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return s}async mkdir(e,n){this.mkdirSync(e,n)}mkdirSync(e,n){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(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{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){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);s.add(n),n=this.resolveSymlink(n,r.target),r=this.data.get(n)}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 o=n==="/"?"/":`${n}/`,i=new Map;for(let[a,c]of this.data.entries())if(a!==n&&a.startsWith(o)){let l=a.slice(o.length),f=l.split("/")[0];f&&!l.includes("/",f.length)&&!i.has(f)&&i.set(f,{name:f,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}return Array.from(i.values()).sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0)}async rm(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!n?.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,n)}}}this.data.delete(r)}async cp(e,n,r){let s=this.normalizePath(e),o=this.normalizePath(n),i=this.data.get(s);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(s);for(let c of a){let l=s==="/"?`/${c}`:`${s}/${c}`,f=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(l,f,r)}}}async mv(e,n){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}async chmod(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){let r=this.normalizePath(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,n){let r=this.normalizePath(e),s=this.normalizePath(n),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(s))throw new Error(`EEXIST: file already exists, link '${n}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let n=this.normalizePath(e),r=this.data.get(n);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}};var gr="5.1.0(1)-release",Ar="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Re(){return{pid:process.pid,ppid:process.ppid,uid:process.getuid?.()??1e3,gid:process.getgid?.()??1e3}}function xr(){let{pid:t,ppid:e,uid:n,gid:r}=Re();return`Name: bash
2
+ import{a as z,b as K,c as U,d as Y,e as X,f as k,g as W,h as me,i as B,j as ie,k as Ue}from"./chunks/chunk-NWWB2XRE.js";import"./chunks/chunk-OBH7XN5N.js";import{a as se}from"./chunks/chunk-4VDEBYW7.js";import"./chunks/chunk-KGOUQS5A.js";import{resolve as Mn}from"node:path";var ge=[{name:"echo",load:async()=>(await import("./chunks/echo-WSKTON6U.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-AJXZOSPN.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-HWUQKYUM.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-BEHQBUMC.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-XJABRAUN.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-TSNAXMZ2.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-2PKAWTSQ.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-XXWRVG2D.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-3ATZ2ABL.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-EFFNQ3RY.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-3DIKREF7.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-53KG2MCJ.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-VL3R4LAM.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-DYK37Z24.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-BES27CZT.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-QSBRKIF5.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-UEQ7KMY5.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-JUSJYJL4.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-JUSJYJL4.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-JUSJYJL4.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-4VGBMMUO.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-5LQMJYRJ.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-D2US2LMM.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-KUHOCH5S.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-IXHB2FVS.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-CPIFQTKY.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-IHF6BEOO.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-FT6WBQZG.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-MBLEXZBI.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-VP42N2JN.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-DSM3NUGM.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-452R4I2C.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-77K5HH2M.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-BFVYAPOU.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-ZEKN6D4Q.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-JJFZRWRC.js")).split},{name:"column",load:async()=>(await import("./chunks/column-TSFEMTG6.js")).column},{name:"join",load:async()=>(await import("./chunks/join-3IXMEGNA.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-ZFIT2GTM.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-CBEJ35BR.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SO5MVUEX.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-EES7TR26.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-DQBEJH47.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-XQPYLN3H.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-YLLSNZZN.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-YLLSNZZN.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-PCMLRCRW.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-PCMLRCRW.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-G5C2J2OY.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-IWT2HHEA.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-OVATH2SQ.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-OVATH2SQ.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-CI7A5IXQ.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-UT3MT5UU.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-UT3MT5UU.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-XXZPU5CA.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-O7TCK5TL.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-GI3QVUGD.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-IQLPMFYI.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-O5BOTJGJ.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-JED4EKFH.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-AVK43XM2.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-RMGXYNQJ.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-2VAAFCTS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-67P4ME4N.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-MV3WQ4QF.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-LNCFDPQZ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-EPEXKI4B.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-7C5JICNL.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-73KOOLC6.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-KNRFDAY7.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-WXDKRL2Z.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-SLM7SRWU.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-YXK3WZQL.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-YXK3WZQL.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-YXK3WZQL.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ge.push({name:"tar",load:async()=>(await import("./chunks/tar-C27YYUAS.js")).tarCommand}),ge.push({name:"yq",load:async()=>(await import("./chunks/yq-MF2SNFGL.js")).yqCommand}),ge.push({name:"xan",load:async()=>(await import("./chunks/xan-6K2NGTHM.js")).xanCommand}),ge.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-THMDBIGF.js")).sqlite3Command}));var zn=[{name:"curl",load:async()=>(await import("./chunks/curl-LCMREE7R.js")).curlCommand}],hr=new Map;function mr(t){return{name:t.name,async execute(e,n){let r=hr.get(t.name);return r||(r=await t.load(),hr.set(t.name,r)),r.execute(e,n)}}}function pr(t){return(t?ge.filter(n=>t.includes(n.name)):ge).map(mr)}function yr(){return zn.map(mr)}function wr(t){return"load"in t&&typeof t.load=="function"}function Er(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var Un=new TextEncoder,jn=new TextDecoder;function Ae(t,e){if(t instanceof Uint8Array)return t;if(e==="base64")return Uint8Array.from(atob(t),n=>n.charCodeAt(0));if(e==="hex"){let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}return e==="binary"||e==="latin1"?Uint8Array.from(t,n=>n.charCodeAt(0)):Un.encode(t)}function je(t,e){return e==="base64"?btoa(String.fromCharCode(...t)):e==="hex"?Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join(""):e==="binary"||e==="latin1"?String.fromCharCode(...t):jn.decode(t)}function oe(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Ge=new TextEncoder;function Gn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var ke=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[n,r]of Object.entries(e))Gn(r)?this.writeFileSync(n,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(n,r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,n,r,s){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=oe(r),a=Ae(n,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,n){let r=await this.readFileBuffer(e),s=oe(n);return je(r,s)}async readFileBuffer(e){let n=this.resolvePathWithSymlinks(e),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:Ge.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=oe(r),a=Ae(n,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:Ge.encode(o.content),c=new Uint8Array(l.length+a.length);c.set(l),c.set(a,l.length),this.data.set(s,{type:"file",content:c,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){try{let n=this.resolvePathWithSymlinks(e);return this.data.has(n)}catch{return!1}}async stat(e){let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ge.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}async lstat(e){let n=this.resolveIntermediateSymlinks(e),r=this.data.get(n);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 s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ge.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}resolveIntermediateSymlinks(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",o=new Set;for(let i=0;i<r.length-1;i++){let a=r[i];s=`${s}/${a}`;let l=this.data.get(s),c=0,f=40;for(;l&&l.type==="symlink"&&c<f;){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);o.add(s),s=this.resolveSymlink(s,l.target),l=this.data.get(s),c++}if(c>=f)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",o=new Set;for(let i of r){s=`${s}/${i}`;let a=this.data.get(s),l=0,c=40;for(;a&&a.type==="symlink"&&l<c;){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,a.target),a=this.data.get(s),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return s}async mkdir(e,n){this.mkdirSync(e,n)}mkdirSync(e,n){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(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{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){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);s.add(n),n=this.resolveSymlink(n,r.target),r=this.data.get(n)}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 o=n==="/"?"/":`${n}/`,i=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(o)){let c=a.slice(o.length),f=c.split("/")[0];f&&!c.includes("/",f.length)&&!i.has(f)&&i.set(f,{name:f,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(i.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!n?.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,n)}}}this.data.delete(r)}async cp(e,n,r){let s=this.normalizePath(e),o=this.normalizePath(n),i=this.data.get(s);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(s);for(let l of a){let c=s==="/"?`/${l}`:`${s}/${l}`,f=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(c,f,r)}}}async mv(e,n){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}async chmod(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){let r=this.normalizePath(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,n){let r=this.normalizePath(e),s=this.normalizePath(n),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(s))throw new Error(`EEXIST: file already exists, link '${n}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let n=this.normalizePath(e),r=this.data.get(n);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}};var gr="5.1.0(1)-release",Ar="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Re(){return{pid:process.pid,ppid:process.ppid,uid:process.getuid?.()??1e3,gid:process.getgid?.()??1e3}}function Sr(){let{pid:t,ppid:e,uid:n,gid:r}=Re();return`Name: bash
3
3
  State: R (running)
4
4
  Pid: ${t}
5
5
  PPid: ${e}
@@ -7,72 +7,72 @@ Uid: ${n} ${n} ${n} ${n}
7
7
  Gid: ${r} ${r} ${r} ${r}
8
8
  `}function Hn(t){let e=t;return typeof e.mkdirSync=="function"&&typeof e.writeFileSync=="function"}function Vn(t,e){t.mkdirSync("/bin",{recursive:!0}),t.mkdirSync("/usr/bin",{recursive:!0}),e&&(t.mkdirSync("/home/user",{recursive:!0}),t.mkdirSync("/tmp",{recursive:!0}))}function qn(t){t.mkdirSync("/dev",{recursive:!0}),t.writeFileSync("/dev/null",""),t.writeFileSync("/dev/zero",new Uint8Array(0)),t.writeFileSync("/dev/stdin",""),t.writeFileSync("/dev/stdout",""),t.writeFileSync("/dev/stderr","")}function Zn(t){t.mkdirSync("/proc/self/fd",{recursive:!0}),t.writeFileSync("/proc/version",`${Ar}
9
9
  `),t.writeFileSync("/proc/self/exe","/bin/bash"),t.writeFileSync("/proc/self/cmdline","bash\0"),t.writeFileSync("/proc/self/comm",`bash
10
- `),t.writeFileSync("/proc/self/status",xr()),t.writeFileSync("/proc/self/fd/0","/dev/stdin"),t.writeFileSync("/proc/self/fd/1","/dev/stdout"),t.writeFileSync("/proc/self/fd/2","/dev/stderr")}function Sr(t,e){Hn(t)&&(Vn(t,e),qn(t),Zn(t))}var Qn=["tar","yq","xan","sqlite3"];function br(t){return Qn.includes(t)}function L(t,e){return{type:"ArithmeticExpression",expression:J(t,e,0).expr}}function J(t,e,n){return Kn(t,e,n)}function Kn(t,e,n){let{expr:r,pos:s}=Ve(t,e,n);for(s=D(e,s);e[s]===",";){s++;let{expr:o,pos:i}=Ve(t,e,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=D(e,i)}return{expr:r,pos:s}}function Ve(t,e,n){let{expr:r,pos:s}=Xn(t,e,n);if(s=D(e,s),e[s]==="?"){s++;let{expr:o,pos:i}=J(t,e,s);if(s=D(e,i),e[s]===":"){s++;let{expr:a,pos:c}=J(t,e,s);return{expr:{type:"ArithTernary",condition:r,consequent:o,alternate:a},pos:c}}}return{expr:r,pos:s}}function Xn(t,e,n){let{expr:r,pos:s}=Cr(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:o,pos:i}=Cr(t,e,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=i}return{expr:r,pos:s}}function Cr(t,e,n){let{expr:r,pos:s}=Nr(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:o,pos:i}=Nr(t,e,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=i}return{expr:r,pos:s}}function Nr(t,e,n){let{expr:r,pos:s}=vr(t,e,n);for(;s=D(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:o,pos:i}=vr(t,e,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=i}return{expr:r,pos:s}}function vr(t,e,n){let{expr:r,pos:s}=$r(t,e,n);for(;s=D(e,s),e[s]==="^";){s++;let{expr:o,pos:i}=$r(t,e,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=i}return{expr:r,pos:s}}function $r(t,e,n){let{expr:r,pos:s}=Pr(t,e,n);for(;s=D(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:o,pos:i}=Pr(t,e,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=i}return{expr:r,pos:s}}function Pr(t,e,n){let{expr:r,pos:s}=Ir(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Ir(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Ir(t,e,n){let{expr:r,pos:s}=gt(t,e,n);for(;;)if(s=D(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=gt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else if(e[s]==="<"||e[s]===">"){let o=e[s];s++;let{expr:i,pos:a}=gt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function gt(t,e,n){let{expr:r,pos:s}=kr(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=kr(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function kr(t,e,n){let{expr:r,pos:s}=Rr(t,e,n);for(;s=D(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let o=e[s];s++;let{expr:i,pos:a}=Rr(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Rr(t,e,n){let{expr:r,pos:s}=He(t,e,n);for(;;)if(s=D(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:o,pos:i}=He(t,e,s);r={type:"ArithBinary",operator:"*",left:r,right:o},s=i}else if(e[s]==="/"||e[s]==="%"){let o=e[s];s++;let{expr:i,pos:a}=He(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function He(t,e,n){let{expr:r,pos:s}=At(t,e,n),o=D(e,s);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=He(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:r,right:i},pos:a}}return{expr:r,pos:s}}function At(t,e,n){let r=D(e,n);if(e.slice(r,r+2)==="++"||e.slice(r,r+2)==="--"){let s=e.slice(r,r+2);r+=2;let{expr:o,pos:i}=At(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let s=e[r];r++;let{expr:o,pos:i}=At(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}return Jn(t,e,r)}function Yn(t,e){let n=t[e];return n==="$"||n==="`"}function Jn(t,e,n){let{expr:r,pos:s}=Dr(t,e,n),o=[r];for(;Yn(e,s);){let{expr:i,pos:a}=Dr(t,e,s);o.push(i),s=a}if(o.length>1&&(r={type:"ArithConcat",parts:o}),s=D(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let i=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:i,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function Dr(t,e,n){let r=D(e,n);if(e.slice(r,r+3)==="$(("){r+=3;let s=1,o=r;for(;r<e.length-1&&s>0;)e[r]==="("&&e[r+1]==="("?(s++,r+=2):e[r]===")"&&e[r+1]===")"?(s--,s>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 s=1,o=r;for(;r<e.length&&s>0;)e[r]==="("?s++:e[r]===")"&&s--,s>0&&r++;let i=e.slice(o,r);return r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="`"){r++;let s=r;for(;r<e.length&&e[r]!=="`";)r++;let o=e.slice(s,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="("){r++;let{expr:s,pos:o}=J(t,e,r);return r=D(e,o),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:s},pos:r}}if(/[0-9]/.test(e[r])){let s="",o=!1;for(;r<e.length;){let a=e[r];if(o)if(/[0-9a-zA-Z@_]/.test(a))s+=a,r++;else break;else if(a==="#")o=!0,s+=a,r++;else if(/[0-9a-fA-FxX]/.test(a))s+=a,r++;else break}if(e[r]==="."&&/[0-9]/.test(e[r+1]))throw new W(`${s}.${e[r+1]}...: syntax error: invalid arithmetic operator`);if(e[r]==="["){let a=e.slice(r).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:xe(s)},pos:r}}if(e[r]==="$"&&e[r+1]==="{"){let s=r+2,o=1,i=s;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(s,i),c=i+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let f=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:f},pos:l}}if(/[0-9]/.test(e[c])||e[c]==="x"||e[c]==="X"){let l=c;if(e[c]==="x"||e[c]==="X")for(l++;l<e.length&&/[0-9a-fA-F]/.test(e[l]);)l++;else for(;l<e.length&&/[0-9]/.test(e[l]);)l++;let f=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:f},pos:l}}return r=c,{expr:{type:"ArithBracedExpansion",content:a},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[0-9]/.test(e[r+1])){r++;let s="";for(;r<e.length&&/[0-9]/.test(e[r]);)s+=e[r],r++;return{expr:{type:"ArithVariable",name:s},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[a-zA-Z_]/.test(e[r+1])&&r++,/[a-zA-Z_]/.test(e[r])){let s="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)s+=e[r],r++;if(e[r]==="["){r++;let i;if(e[r]==="'"||e[r]==='"'){let l=e[r];for(r++,i="";r<e.length&&e[r]!==l;)i+=e[r],r++;e[r]===l&&r++,r=D(e,r),e[r]==="]"&&r++}let a;if(i===void 0){let{expr:l,pos:f}=J(t,e,r);a=l,r=f,e[r]==="]"&&r++}if(r=D(e,r),e[r]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:s,index:a},pos:r};let c=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let l of c)if(e.slice(r,r+l.length)===l&&e.slice(r,r+l.length+1)!=="=="){r+=l.length;let{expr:f,pos:d}=Ve(t,e,r);return{expr:{type:"ArithAssignment",operator:l,variable:s,subscript:a,stringKey:i,value:f},pos:d}}return{expr:{type:"ArithArrayElement",array:s,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:c}=Ve(t,e,r);return{expr:{type:"ArithAssignment",operator:i,variable:s,value:a},pos:c}}return{expr:{type:"ArithVariable",name:s},pos:r}}return{expr:{type:"ArithNumber",value:0},pos:r}}function xe(t){if(t.includes("#")){let[e,n]=t.split("#"),r=Number.parseInt(e,10);if(r<2||r>64)return Number.NaN;if(r<=36)return Number.parseInt(n,r);let s=0;for(let o of n){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;s=s*r+i}return s}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]===`
10
+ `),t.writeFileSync("/proc/self/status",Sr()),t.writeFileSync("/proc/self/fd/0","/dev/stdin"),t.writeFileSync("/proc/self/fd/1","/dev/stdout"),t.writeFileSync("/proc/self/fd/2","/dev/stderr")}function xr(t,e){Hn(t)&&(Vn(t,e),qn(t),Zn(t))}var Qn=["tar","yq","xan","sqlite3"];function br(t){return Qn.includes(t)}function L(t,e){return{type:"ArithmeticExpression",expression:J(t,e,0).expr}}function J(t,e,n){return Kn(t,e,n)}function Kn(t,e,n){let{expr:r,pos:s}=Ve(t,e,n);for(s=D(e,s);e[s]===",";){s++;let{expr:o,pos:i}=Ve(t,e,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=D(e,i)}return{expr:r,pos:s}}function Ve(t,e,n){let{expr:r,pos:s}=Xn(t,e,n);if(s=D(e,s),e[s]==="?"){s++;let{expr:o,pos:i}=J(t,e,s);if(s=D(e,i),e[s]===":"){s++;let{expr:a,pos:l}=J(t,e,s);return{expr:{type:"ArithTernary",condition:r,consequent:o,alternate:a},pos:l}}}return{expr:r,pos:s}}function Xn(t,e,n){let{expr:r,pos:s}=Cr(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:o,pos:i}=Cr(t,e,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=i}return{expr:r,pos:s}}function Cr(t,e,n){let{expr:r,pos:s}=Nr(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:o,pos:i}=Nr(t,e,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=i}return{expr:r,pos:s}}function Nr(t,e,n){let{expr:r,pos:s}=vr(t,e,n);for(;s=D(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:o,pos:i}=vr(t,e,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=i}return{expr:r,pos:s}}function vr(t,e,n){let{expr:r,pos:s}=$r(t,e,n);for(;s=D(e,s),e[s]==="^";){s++;let{expr:o,pos:i}=$r(t,e,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=i}return{expr:r,pos:s}}function $r(t,e,n){let{expr:r,pos:s}=Pr(t,e,n);for(;s=D(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:o,pos:i}=Pr(t,e,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=i}return{expr:r,pos:s}}function Pr(t,e,n){let{expr:r,pos:s}=Ir(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Ir(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Ir(t,e,n){let{expr:r,pos:s}=gt(t,e,n);for(;;)if(s=D(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=gt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else if(e[s]==="<"||e[s]===">"){let o=e[s];s++;let{expr:i,pos:a}=gt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function gt(t,e,n){let{expr:r,pos:s}=kr(t,e,n);for(;s=D(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=kr(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function kr(t,e,n){let{expr:r,pos:s}=Rr(t,e,n);for(;s=D(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let o=e[s];s++;let{expr:i,pos:a}=Rr(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Rr(t,e,n){let{expr:r,pos:s}=He(t,e,n);for(;;)if(s=D(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:o,pos:i}=He(t,e,s);r={type:"ArithBinary",operator:"*",left:r,right:o},s=i}else if(e[s]==="/"||e[s]==="%"){let o=e[s];s++;let{expr:i,pos:a}=He(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function He(t,e,n){let{expr:r,pos:s}=At(t,e,n),o=D(e,s);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=He(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:r,right:i},pos:a}}return{expr:r,pos:s}}function At(t,e,n){let r=D(e,n);if(e.slice(r,r+2)==="++"||e.slice(r,r+2)==="--"){let s=e.slice(r,r+2);r+=2;let{expr:o,pos:i}=At(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let s=e[r];r++;let{expr:o,pos:i}=At(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}return Jn(t,e,r)}function Yn(t,e){let n=t[e];return n==="$"||n==="`"}function Jn(t,e,n){let{expr:r,pos:s}=Dr(t,e,n),o=[r];for(;Yn(e,s);){let{expr:i,pos:a}=Dr(t,e,s);o.push(i),s=a}if(o.length>1&&(r={type:"ArithConcat",parts:o}),s=D(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let i=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:i,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function Dr(t,e,n){let r=D(e,n);if(e.slice(r,r+3)==="$(("){r+=3;let s=1,o=r;for(;r<e.length-1&&s>0;)e[r]==="("&&e[r+1]==="("?(s++,r+=2):e[r]===")"&&e[r+1]===")"?(s--,s>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 s=1,o=r;for(;r<e.length&&s>0;)e[r]==="("?s++:e[r]===")"&&s--,s>0&&r++;let i=e.slice(o,r);return r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="`"){r++;let s=r;for(;r<e.length&&e[r]!=="`";)r++;let o=e.slice(s,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="("){r++;let{expr:s,pos:o}=J(t,e,r);return r=D(e,o),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:s},pos:r}}if(/[0-9]/.test(e[r])){let s="",o=!1;for(;r<e.length;){let a=e[r];if(o)if(/[0-9a-zA-Z@_]/.test(a))s+=a,r++;else break;else if(a==="#")o=!0,s+=a,r++;else if(/[0-9a-fA-FxX]/.test(a))s+=a,r++;else break}if(e[r]==="."&&/[0-9]/.test(e[r+1]))throw new W(`${s}.${e[r+1]}...: syntax error: invalid arithmetic operator`);if(e[r]==="["){let a=e.slice(r).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:Se(s)},pos:r}}if(e[r]==="$"&&e[r+1]==="{"){let s=r+2,o=1,i=s;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(s,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 s="";for(;r<e.length&&/[0-9]/.test(e[r]);)s+=e[r],r++;return{expr:{type:"ArithVariable",name:s},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[a-zA-Z_]/.test(e[r+1])&&r++,/[a-zA-Z_]/.test(e[r])){let s="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)s+=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:s,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:d}=Ve(t,e,r);return{expr:{type:"ArithAssignment",operator:c,variable:s,subscript:a,stringKey:i,value:f},pos:d}}return{expr:{type:"ArithArrayElement",array:s,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}=Ve(t,e,r);return{expr:{type:"ArithAssignment",operator:i,variable:s,value:a},pos:l}}return{expr:{type:"ArithVariable",name:s},pos:r}}return{expr:{type:"ArithNumber",value:0},pos:r}}function Se(t){if(t.includes("#")){let[e,n]=t.split("#"),r=Number.parseInt(e,10);if(r<2||r>64)return Number.NaN;if(r<=36)return Number.parseInt(n,r);let s=0;for(let o of n){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;s=s*r+i}return s}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]===`
11
11
  `){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=[],n=!1){return{type:"Statement",pipelines:t,operators:e,background:n}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],n=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:n,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,n=!1,r=null){return{type:"Assignment",name:t,value:e,append:n,array:r}},redirection(t,e,n=null){return{type:"Redirection",fd:n,operator:t,target:e}},hereDoc(t,e,n=!1,r=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:n,quoted:r}},ifNode(t,e=null,n=[]){return{type:"If",clauses:t,elseBody:e,redirections:n}},forNode(t,e,n,r=[]){return{type:"For",variable:t,words:e,body:n,redirections:r}},whileNode(t,e,n=[]){return{type:"While",condition:t,body:e,redirections:n}},untilNode(t,e,n=[]){return{type:"Until",condition:t,body:e,redirections:n}},caseNode(t,e,n=[]){return{type:"Case",word:t,items:e,redirections:n}},caseItem(t,e,n=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:n}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,n=[]){return{type:"FunctionDef",name:t,body:e,redirections:n}},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 qe={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 n=t.slice(e[0].length);if(n===""||n==="+")return!0;if(n[0]==="["){let r=0,s=0;for(;s<n.length;s++)if(n[s]==="[")r++;else if(n[s]==="]"&&(r--,r===0))break;if(r!==0||s>=n.length)return!1;let o=n.slice(s+1);return o===""||o==="+"}return!1}var es=[[";",";","&",u.SEMI_SEMI_AND],["<","<","<",u.TLESS],["&",">",">",u.AND_DGREAT]],ts=[["[","[",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]],rs={"|":u.PIPE,"&":u.AMP,";":u.SEMICOLON,"(":u.LPAREN,")":u.RPAREN,"<":u.LESS,">":u.GREAT};function ns(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var Ze=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];constructor(e){this.input=e}tokenize(){let n=this.input.length,r=this.tokens,s=this.pendingHeredocs;for(;this.pos<n&&(this.skipWhitespace(),!(this.pos>=n));){if(s.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,n=e.length,r=this.pos,s=this.column,o=this.line;for(;r<n;){let i=e[r];if(i===" "||i===" ")r++,s++;else if(i==="\\"&&e[r+1]===`
12
12
  `)r+=2,o++,s=1;else break}this.pos=r,this.column=s,this.line=o}nextToken(){let e=this.input,n=this.pos,r=this.line,s=this.column,o=e[n],i=e[n+1],a=e[n+2];if(o==="#")return this.readComment(n,r,s);if(o===`
13
13
  `)return this.pos=n+1,this.line++,this.column=1,{type:u.NEWLINE,value:`
14
- `,start:n,end:n+1,line:r,column:s};if(o==="<"&&i==="<"&&a==="-")return this.pos=n+3,this.column=s+3,this.registerHeredocFromLookahead(!0),this.makeToken(u.DLESSDASH,"<<-",n,r,s);for(let[l,f,d,h]of es)if(o===l&&i===f&&a===d)return this.pos=n+3,this.column=s+3,this.makeToken(h,l+f+d,n,r,s);if(o==="<"&&i==="<")return this.pos=n+2,this.column=s+2,this.registerHeredocFromLookahead(!1),this.makeToken(u.DLESS,"<<",n,r,s);for(let[l,f,d]of ts)if(o===l&&i===f)return this.pos=n+2,this.column=s+2,this.makeToken(d,l+f,n,r,s);let c=rs[o];return c?(this.pos=n+1,this.column=s+1,this.makeToken(c,o,n,r,s)):o==="{"?i==="}"?(this.pos=n+2,this.column=s+2,{type:u.WORD,value:"{}",start:n,end:n+2,line:r,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(n)!==null?this.readWordWithBraceExpansion(n,r,s):this.scanLiteralBraceWord(n)!==null?this.readWordWithBraceExpansion(n,r,s):i!==void 0&&i!==" "&&i!==" "&&i!==`
14
+ `,start:n,end:n+1,line:r,column:s};if(o==="<"&&i==="<"&&a==="-")return this.pos=n+3,this.column=s+3,this.registerHeredocFromLookahead(!0),this.makeToken(u.DLESSDASH,"<<-",n,r,s);for(let[c,f,d,h]of es)if(o===c&&i===f&&a===d)return this.pos=n+3,this.column=s+3,this.makeToken(h,c+f+d,n,r,s);if(o==="<"&&i==="<")return this.pos=n+2,this.column=s+2,this.registerHeredocFromLookahead(!1),this.makeToken(u.DLESS,"<<",n,r,s);for(let[c,f,d]of ts)if(o===c&&i===f)return this.pos=n+2,this.column=s+2,this.makeToken(d,c+f,n,r,s);let l=rs[o];return l?(this.pos=n+1,this.column=s+1,this.makeToken(l,o,n,r,s)):o==="{"?i==="}"?(this.pos=n+2,this.column=s+2,{type:u.WORD,value:"{}",start:n,end:n+2,line:r,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(n)!==null?this.readWordWithBraceExpansion(n,r,s):this.scanLiteralBraceWord(n)!==null?this.readWordWithBraceExpansion(n,r,s):i!==void 0&&i!==" "&&i!==" "&&i!==`
15
15
  `?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(u.LBRACE,"{",n,r,s)):o==="}"?this.isWordCharFollowing(n+1)?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(u.RBRACE,"}",n,r,s)):o==="!"?i==="="?(this.pos=n+2,this.column=s+2,this.makeToken(u.WORD,"!=",n,r,s)):(this.pos=n+1,this.column=s+1,this.makeToken(u.BANG,"!",n,r,s)):this.readWord(n,r,s)}makeToken(e,n,r,s,o){return{type:e,value:n,start:r,end:this.pos,line:s,column:o}}readComment(e,n,r){let s=this.input,o=s.length,i=this.pos;for(;i<o&&s[i]!==`
16
16
  `;)i++;let a=s.slice(e,i);return this.pos=i,this.column=r+(i-e),{type:u.COMMENT,value:a,start:e,end:i,line:n,column:r}}readWord(e,n,r){let s=this.input,o=s.length,i=this.pos,a=i;for(;i<o;){let p=s[i];if(p===" "||p===" "||p===`
17
17
  `||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"||p==="'"||p==='"'||p==="\\"||p==="$"||p==="`"||p==="{"||p==="}"||p==="~"||p==="*"||p==="?"||p==="[")break;i++}if(i>a){let p=s[i];if(i>=o||p===" "||p===" "||p===`
18
- `||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"){let w=s.slice(a,i);if(this.pos=i,this.column=r+(i-a),qe[w])return{type:qe[w],value:w,start:e,end:i,line:n,column:r};let g=w.indexOf("=");return g>0&&_r(w.slice(0,g))?{type:u.ASSIGNMENT_WORD,value:w,start:e,end:i,line:n,column:r}:/^[0-9]+$/.test(w)?{type:u.NUMBER,value:w,start:e,end:i,line:n,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)?{type:u.NAME,value:w,start:e,end:i,line:n,column:r,quoted:!1,singleQuoted:!1}:{type:u.WORD,value:w,start:e,end:i,line:n,column:r,quoted:!1,singleQuoted:!1}}}i=this.pos;let c=this.column,l=this.line,f="",d=!1,h=!1,m=!1,y=!1,E=s[i]==='"'||s[i]==="'";for(;i<o;){let p=s[i];if(!m&&!y&&(p===" "||p===" "||p===`
19
- `||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"))break;if(p==="$"&&i+1<o&&s[i+1]==="'"&&!m&&!y){for(f+="$'",i+=2,c+=2;i<o&&s[i]!=="'";)s[i]==="\\"&&i+1<o?(f+=s[i]+s[i+1],i+=2,c+=2):(f+=s[i],i++,c++);i<o&&(f+="'",i++,c++);continue}if(p==="$"&&i+1<o&&s[i+1]==='"'&&!m&&!y){i++,c++,y=!0,d=!0,f===""&&(E=!0),i++,c++;continue}if(p==="'"&&!y){m?(m=!1,E||(f+=p)):(m=!0,E?(h=!0,d=!0):f+=p),i++,c++;continue}if(p==='"'&&!m){y?(y=!1,E||(f+=p)):(y=!0,E?d=!0:f+=p),i++,c++;continue}if(p==="\\"&&!m&&i+1<o){let w=s[i+1];if(w===`
20
- `){i+=2,l++,c=1;continue}if(y){if(w==='"'||w==="\\"||w==="$"||w==="`"||w===`
21
- `){w==="$"||w==="`"?f+=p+w:f+=w,i+=2,c+=2;continue}}else{w==='"'||w==="'"?f+=p+w:f+=w,i+=2,c+=2;continue}}if(p==="$"&&i+1<o&&s[i+1]==="("){f+=p,i++,c++,f+=s[i],i++,c++;let w=1,g=!1,b=!1,C=0,I=!1,R="",he=s[i]==="(";for(;w>0&&i<o;){let _=s[i];if(f+=_,g)_==="'"&&(g=!1);else if(b)_==="\\"&&i+1<o?(f+=s[i+1],i++,c++):_==='"'&&(b=!1);else if(_==="'")g=!0,R="";else if(_==='"')b=!0,R="";else if(_==="\\"&&i+1<o)f+=s[i+1],i++,c++,R="";else if(_==="#"&&!he&&(R===""||/\s/.test(s[i-1]||""))){for(;i+1<o&&s[i+1]!==`
22
- `;)i++,c++,f+=s[i];R=""}else/[a-zA-Z_]/.test(_)?R+=_:(R==="case"?(C++,I=!1):R==="in"&&C>0?I=!0:R==="esac"&&C>0&&(C--,I=!1),R="",_==="("?i>0&&s[i-1]==="$"?w++:I||w++:_===")"?I?I=!1:w--:_===";"&&C>0&&i+1<o&&s[i+1]===";"&&(I=!0));_===`
23
- `&&(l++,c=0,R=""),i++,c++}continue}if(p==="$"&&i+1<o&&s[i+1]==="["){f+=p,i++,c++,f+=s[i],i++,c++;let w=1;for(;w>0&&i<o;){let g=s[i];f+=g,g==="["?w++:g==="]"?w--:g===`
24
- `&&(l++,c=0),i++,c++}continue}if(p==="$"&&i+1<o&&s[i+1]==="{"){f+=p,i++,c++,f+=s[i],i++,c++;let w=1;for(;w>0&&i<o;){let g=s[i];f+=g,g==="{"?w++:g==="}"?w--:g===`
25
- `&&(l++,c=0),i++,c++}continue}if(p==="$"&&i+1<o){let w=s[i+1];if(w==="#"||w==="?"||w==="$"||w==="!"||w==="@"||w==="*"||w==="-"||w>="0"&&w<="9"){f+=p+w,i+=2,c+=2;continue}}if(p==="`"){for(f+=p,i++,c++;i<o&&s[i]!=="`";){let w=s[i];f+=w,w==="\\"&&i+1<o&&(f+=s[i+1],i++,c++),w===`
26
- `&&(l++,c=0),i++,c++}i<o&&(f+=s[i],i++,c++);continue}f+=p,i++,p===`
27
- `?(l++,c=1):c++}if(this.pos=i,this.column=c,this.line=l,f==="")return{type:u.WORD,value:"",start:e,end:i,line:n,column:r,quoted:d,singleQuoted:h};if(!d&&qe[f])return{type:qe[f],value:f,start:e,end:i,line:n,column:r};if(!E){let p=f.indexOf("=");if(p>0&&_r(f.slice(0,p)))return{type:u.ASSIGNMENT_WORD,value:f,start:e,end:i,line:n,column:r,quoted:d,singleQuoted:h}}return/^[0-9]+$/.test(f)?{type:u.NUMBER,value:f,start:e,end:i,line:n,column:r}:ns(f)?{type:u.NAME,value:f,start:e,end:i,line:n,column:r,quoted:d,singleQuoted:h}:{type:u.WORD,value:f,start:e,end:i,line:n,column:r,quoted:d,singleQuoted:h}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let n=this.pos,r=this.line,s=this.column,o="";for(;this.pos<this.input.length;){let i=this.pos,a="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
18
+ `||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"){let w=s.slice(a,i);if(this.pos=i,this.column=r+(i-a),qe[w])return{type:qe[w],value:w,start:e,end:i,line:n,column:r};let g=w.indexOf("=");return g>0&&_r(w.slice(0,g))?{type:u.ASSIGNMENT_WORD,value:w,start:e,end:i,line:n,column:r}:/^[0-9]+$/.test(w)?{type:u.NUMBER,value:w,start:e,end:i,line:n,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)?{type:u.NAME,value:w,start:e,end:i,line:n,column:r,quoted:!1,singleQuoted:!1}:{type:u.WORD,value:w,start:e,end:i,line:n,column:r,quoted:!1,singleQuoted:!1}}}i=this.pos;let l=this.column,c=this.line,f="",d=!1,h=!1,m=!1,y=!1,E=s[i]==='"'||s[i]==="'";for(;i<o;){let p=s[i];if(!m&&!y&&(p===" "||p===" "||p===`
19
+ `||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"))break;if(p==="$"&&i+1<o&&s[i+1]==="'"&&!m&&!y){for(f+="$'",i+=2,l+=2;i<o&&s[i]!=="'";)s[i]==="\\"&&i+1<o?(f+=s[i]+s[i+1],i+=2,l+=2):(f+=s[i],i++,l++);i<o&&(f+="'",i++,l++);continue}if(p==="$"&&i+1<o&&s[i+1]==='"'&&!m&&!y){i++,l++,y=!0,d=!0,f===""&&(E=!0),i++,l++;continue}if(p==="'"&&!y){m?(m=!1,E||(f+=p)):(m=!0,E?(h=!0,d=!0):f+=p),i++,l++;continue}if(p==='"'&&!m){y?(y=!1,E||(f+=p)):(y=!0,E?d=!0:f+=p),i++,l++;continue}if(p==="\\"&&!m&&i+1<o){let w=s[i+1];if(w===`
20
+ `){i+=2,c++,l=1;continue}if(y){if(w==='"'||w==="\\"||w==="$"||w==="`"||w===`
21
+ `){w==="$"||w==="`"?f+=p+w:f+=w,i+=2,l+=2;continue}}else{w==='"'||w==="'"?f+=p+w:f+=w,i+=2,l+=2;continue}}if(p==="$"&&i+1<o&&s[i+1]==="("){f+=p,i++,l++,f+=s[i],i++,l++;let w=1,g=!1,b=!1,C=0,I=!1,R="",he=s[i]==="(";for(;w>0&&i<o;){let _=s[i];if(f+=_,g)_==="'"&&(g=!1);else if(b)_==="\\"&&i+1<o?(f+=s[i+1],i++,l++):_==='"'&&(b=!1);else if(_==="'")g=!0,R="";else if(_==='"')b=!0,R="";else if(_==="\\"&&i+1<o)f+=s[i+1],i++,l++,R="";else if(_==="#"&&!he&&(R===""||/\s/.test(s[i-1]||""))){for(;i+1<o&&s[i+1]!==`
22
+ `;)i++,l++,f+=s[i];R=""}else/[a-zA-Z_]/.test(_)?R+=_:(R==="case"?(C++,I=!1):R==="in"&&C>0?I=!0:R==="esac"&&C>0&&(C--,I=!1),R="",_==="("?i>0&&s[i-1]==="$"?w++:I||w++:_===")"?I?I=!1:w--:_===";"&&C>0&&i+1<o&&s[i+1]===";"&&(I=!0));_===`
23
+ `&&(c++,l=0,R=""),i++,l++}continue}if(p==="$"&&i+1<o&&s[i+1]==="["){f+=p,i++,l++,f+=s[i],i++,l++;let w=1;for(;w>0&&i<o;){let g=s[i];f+=g,g==="["?w++:g==="]"?w--:g===`
24
+ `&&(c++,l=0),i++,l++}continue}if(p==="$"&&i+1<o&&s[i+1]==="{"){f+=p,i++,l++,f+=s[i],i++,l++;let w=1;for(;w>0&&i<o;){let g=s[i];f+=g,g==="{"?w++:g==="}"?w--:g===`
25
+ `&&(c++,l=0),i++,l++}continue}if(p==="$"&&i+1<o){let w=s[i+1];if(w==="#"||w==="?"||w==="$"||w==="!"||w==="@"||w==="*"||w==="-"||w>="0"&&w<="9"){f+=p+w,i+=2,l+=2;continue}}if(p==="`"){for(f+=p,i++,l++;i<o&&s[i]!=="`";){let w=s[i];f+=w,w==="\\"&&i+1<o&&(f+=s[i+1],i++,l++),w===`
26
+ `&&(c++,l=0),i++,l++}i<o&&(f+=s[i],i++,l++);continue}f+=p,i++,p===`
27
+ `?(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:n,column:r,quoted:d,singleQuoted:h};if(!d&&qe[f])return{type:qe[f],value:f,start:e,end:i,line:n,column:r};if(!E){let p=f.indexOf("=");if(p>0&&_r(f.slice(0,p)))return{type:u.ASSIGNMENT_WORD,value:f,start:e,end:i,line:n,column:r,quoted:d,singleQuoted:h}}return/^[0-9]+$/.test(f)?{type:u.NUMBER,value:f,start:e,end:i,line:n,column:r}:ns(f)?{type:u.NAME,value:f,start:e,end:i,line:n,column:r,quoted:d,singleQuoted:h}:{type:u.WORD,value:f,start:e,end:i,line:n,column:r,quoted:d,singleQuoted:h}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let n=this.pos,r=this.line,s=this.column,o="";for(;this.pos<this.input.length;){let i=this.pos,a="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
28
28
  `;)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]===`
29
29
  `&&(this.pos++,this.line++,this.column=1);break}o+=a,this.pos<this.input.length&&this.input[this.pos]===`
30
30
  `&&(o+=`
31
31
  `,this.pos++,this.line++,this.column=1)}this.tokens.push({type:u.HEREDOC_CONTENT,value:o,start:n,end:this.pos,line:r,column:s})}}addPendingHeredoc(e,n,r){this.pendingHeredocs.push({delimiter:e,stripTabs:n,quoted:r})}registerHeredocFromLookahead(e){let n=this.pos,r=this.column;for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]===" ");)this.pos++,this.column++;let s="",o=!1,i=this.input[this.pos];if(i==="'"||i==='"'){o=!0;let a=i;for(this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]!==a;)s+=this.input[this.pos],this.pos++,this.column++}else for(;this.pos<this.input.length&&!/[\s;<>&|()]/.test(this.input[this.pos]);)s+=this.input[this.pos],this.pos++,this.column++;this.pos=n,this.column=r,s&&this.pendingHeredocs.push({delimiter:s,stripTabs:e,quoted:o})}isWordCharFollowing(e){if(e>=this.input.length)return!1;let n=this.input[e];return!(n===" "||n===" "||n===`
32
- `||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(e,n,r){let s=this.input,o=s.length,i=e,a=r;for(;i<o;){let l=s[i];if(l===" "||l===" "||l===`
33
- `||l===";"||l==="&"||l==="|"||l==="("||l===")"||l==="<"||l===">")break;if(l==="{"){if(this.scanBraceExpansion(i)!==null){let d=1;for(i++,a++;i<o&&d>0;)s[i]==="{"?d++:s[i]==="}"&&d--,i++,a++;continue}i++,a++;continue}if(l==="}"){i++,a++;continue}if(l==="$"&&i+1<o&&s[i+1]==="("){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)s[i]==="("?f++:s[i]===")"&&f--,i++,a++;continue}if(l==="$"&&i+1<o&&s[i+1]==="{"){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)s[i]==="{"?f++:s[i]==="}"&&f--,i++,a++;continue}if(l==="`"){for(i++,a++;i<o&&s[i]!=="`";)s[i]==="\\"&&i+1<o?(i+=2,a+=2):(i++,a++);i<o&&(i++,a++);continue}i++,a++}let c=s.slice(e,i);return this.pos=i,this.column=a,{type:u.WORD,value:c,start:e,end:i,line:n,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let n=this.input,r=n.length,s=e+1,o=1,i=!1,a=!1;for(;s<r&&o>0;){let c=n[s];if(c==="{")o++,s++;else if(c==="}")o--,s++;else if(c===","&&o===1)i=!0,s++;else if(c==="."&&s+1<r&&n[s+1]===".")a=!0,s+=2;else{if(c===" "||c===" "||c===`
34
- `||c===";"||c==="&"||c==="|")return null;s++}}return o===0&&(i||a)?n.slice(e,s):null}scanLiteralBraceWord(e){let n=this.input,r=n.length,s=e+1,o=1;for(;s<r&&o>0;){let i=n[s];if(i==="{")o++,s++;else if(i==="}"){if(o--,o===0)return n.slice(e,s+1);s++}else{if(i===" "||i===" "||i===`
35
- `||i===";"||i==="&"||i==="|")return null;s++}}return null}};var xt=1e6,St=1e5,Lr=1e6,Tr=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]),Wr=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,n,r,s=void 0){super(`Parse error at ${n}:${r}: ${e}`),this.line=n,this.column=r,this.token=s,this.name="ParseException"}};function Mr(t,e,n){let r=n+1;for(;r<e.length&&/[a-zA-Z0-9_-]/.test(e[r]);)r++;return r}function bt(t,e,n,r,s){let o=1,i=n+1;for(;i<e.length&&o>0;)e[i]===r?o++:e[i]===s&&o--,o>0&&i++;return o===0?i:-1}function pe(t,e,n){let r=n,s=1;for(;r<e.length&&s>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==="{"?s++:o==="}"&&s--,s>0&&r++}return r}function Br(t,e,n){let r=n,s=!1;for(;r<e.length;){let o=e[r];if(o==="/"&&s||o==="}")break;if(o==="'"){let i=e.indexOf("'",r+1);if(i!==-1){r=i+1,s=!0;continue}}if(o==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++,s=!0;continue}o==="\\"?(r+=2,s=!0):(r++,s=!0)}return r}function zr(t,e,n){let r=n,s="";for(;r<e.length;){let o=e[r];if(o==="*"||o==="?")s+=o,r++;else if(o==="["){let i=ss(e,r);i===-1?(s+=o,r++):(s+=e.slice(r,i+1),r=i+1)}else break}return{pattern:s,endIndex:r}}function ss(t,e){let n=e+1;for(n<t.length&&t[n]==="^"&&n++,n<t.length&&t[n]==="]"&&n++;n<t.length;){let r=t[n];if(r==="\\"&&n+1<t.length){n+=2;continue}if(r==="]")return n;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let s=t.indexOf("'",n+1);if(s!==-1){n=s+1;continue}}if(r==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){n=s+2;continue}}if(r==="["&&n+1<t.length&&(t[n+1]==="."||t[n+1]==="=")){let o=`${t[n+1]}]`,i=t.indexOf(o,n+2);if(i!==-1){n=i+2;continue}}n++}return-1}function Ur(t,e,n){let r="",s=n;for(;s<e.length&&e[s]!=="'";){let o=e[s];if(o==="\\"&&s+1<e.length)switch(e[s+1]){case"n":r+=`
36
- `,s+=2;break;case"t":r+=" ",s+=2;break;case"r":r+="\r",s+=2;break;case"\\":r+="\\",s+=2;break;case"'":r+="'",s+=2;break;case'"':r+='"',s+=2;break;case"a":r+="\x07",s+=2;break;case"b":r+="\b",s+=2;break;case"e":case"E":r+="\x1B",s+=2;break;case"f":r+="\f",s+=2;break;case"v":r+="\v",s+=2;break;case"x":{let a=e.slice(s+2,s+4),c=parseInt(a,16);Number.isNaN(c)?(r+="\\x",s+=2):(r+=String.fromCharCode(c),s+=4);break}case"u":{let a=e.slice(s+2,s+6),c=parseInt(a,16);Number.isNaN(c)?(r+="\\u",s+=2):(r+=String.fromCharCode(c),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",c=s+1;for(;c<e.length&&c<s+4&&/[0-7]/.test(e[c]);)a+=e[c],c++;let l=parseInt(a,8);r+=String.fromCharCode(l),s=c;break}default:r+=o,s++}else r+=o,s++}return s<e.length&&e[s]==="'"&&s++,{part:A.literal(r),endIndex:s}}function Ct(t,e){let n=e.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:L(t,n)}function Fr(t){let e=[],n="",r=0;for(let s=0;s<t.length;s++){let o=t[s];o==="{"?(r++,n+=o):o==="}"?(r--,n+=o):o===","&&r===0?(e.push(n),n=""):n+=o}return e.push(n),e}function jr(t,e,n,r){let s=bt(t,e,n,"{","}");if(s===-1)return null;let o=e.slice(n+1,s),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:s+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:s+1}:o.includes(",")&&r?{part:{type:"BraceExpansion",items:Fr(o).map(f=>({type:"Word",word:A.word(r(t,f,!1,!1,!1))}))},endIndex:s+1}:o.includes(",")?{part:{type:"BraceExpansion",items:Fr(o).map(f=>({type:"Word",word:A.word([A.literal(f)])}))},endIndex:s+1}:null}function Gr(t,e){let n="";for(let r of e.parts)switch(r.type){case"Literal":case"SingleQuoted":case"Escaped":n+=r.value;break;case"DoubleQuoted":n+='"';for(let s of r.parts)s.type==="Literal"||s.type==="Escaped"?n+=s.value:s.type==="ParameterExpansion"&&(n+=`\${${s.parameter}}`);n+='"';break;case"ParameterExpansion":n+=`\${${r.parameter}}`;break;case"Glob":n+=r.pattern;break;default:n+=r.type}return n}function Hr(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 Qe(t){let e=t.current(),n=e.type;if(n===u.NUMBER){let r=t.peek(1);return e.end!==r.start?!1:Wr.has(r.type)}return Tr.has(n)}function Ke(t){let e=null;t.check(u.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let n=t.advance(),r=Hr(t,n.type);if(n.type===u.DLESS||n.type===u.DLESSDASH)return is(t,r,e,n.type===u.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return A.redirection(r,s,e)}function is(t,e,n,r){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),o=s.value,i=s.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),n);return t.addPendingHeredoc(a,o,r,i),a}function qr(t){let e=t.current().line,n=[],r=null,s=[],o=[];for(;t.check(u.ASSIGNMENT_WORD);)t.checkIterationLimit(),n.push(os(t));for(;Qe(t);)t.checkIterationLimit(),o.push(Ke(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(u.RBRACE))&&!t.check(u.PIPE,u.PIPE_AMP);)if(t.checkIterationLimit(),Qe(t))o.push(Ke(t));else if(t.check(u.RBRACE)){let a=t.advance();s.push(t.parseWordFromString(a.value,!1,!1))}else if(t.isWord())s.push(t.parseWord());else if(t.check(u.ASSIGNMENT_WORD)){let a=t.advance(),c=a.value,l=c.endsWith("="),f=c.endsWith("=(");if((l||f)&&(f||t.check(u.LPAREN))){let d=f?c.slice(0,-2):c.slice(0,-1);f||t.expect(u.LPAREN);let h=Nt(t);t.expect(u.RPAREN);let m=h.map(E=>Gr(t,E)),y=`${d}=(${m.join(" ")})`;s.push(t.parseWordFromString(y,!1,!1))}else s.push(t.parseWordFromString(c,a.quoted,a.singleQuoted))}else if(t.check(u.LPAREN))t.error("syntax error near unexpected token `('");else break;let i=A.simpleCommand(r,s,n,o);return i.line=e,i}function os(t){let e=t.expect(u.ASSIGNMENT_WORD),n=e.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||t.error(`Invalid assignment: ${n}`);let s=r[0],o,i=s.length;if(n[i]==="["){let d=0,h=i+1;for(;i<n.length;i++)if(n[i]==="[")d++;else if(n[i]==="]"&&(d--,d===0))break;d!==0&&t.error(`Invalid assignment: ${n}`),o=n.slice(h,i),i++}let a=n[i]==="+";a&&i++,n[i]!=="="&&t.error(`Invalid assignment: ${n}`),i++;let c=n.slice(i);if(c==="("){let d=Nt(t);t.expect(u.RPAREN);let h=o!==void 0?`${s}[${o}]`:s;return A.assignment(h,null,a,d)}if(c===""&&t.check(u.LPAREN)){let d=t.current();if(e.end===d.start){t.advance();let h=Nt(t);t.expect(u.RPAREN);let m=o!==void 0?`${s}[${o}]`:s;return A.assignment(m,null,a,h)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,f=o!==void 0?`${s}[${o}]`:s;return A.assignment(f,l,a,null)}function Nt(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 vt(t){t.expect(u.IF);let e=[],n=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:n,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 c=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${c}'`)}e.push({condition:i,body:a})}let s=null;t.check(u.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(u.FI);let o=t.parseOptionalRedirections();return A.ifNode(e,s,o)}function $t(t){if(t.expect(u.FOR),t.check(u.DPAREN_START))return cs(t);t.isWord()||t.error("Expected variable name in for loop");let n=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 s=t.parseCompoundList();t.expect(u.DONE);let o=t.parseOptionalRedirections();return A.forNode(n,r,s,o)}function cs(t){t.expect(u.DPAREN_START);let e=null,n=null,r=null,s=["","",""],o=0,i=0;for(;!t.check(u.DPAREN_END,u.EOF);){let l=t.advance();if(l.type===u.SEMICOLON&&i===0){if(o++,o>2)break}else l.value==="("&&i++,l.value===")"&&i--,s[o]+=l.value}t.expect(u.DPAREN_END),s[0].trim()&&(e=L(t,s[0].trim())),s[1].trim()&&(n=L(t,s[1].trim())),s[2].trim()&&(r=L(t,s[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 c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:n,update:r,body:a,redirections:c}}function Pt(t){t.expect(u.WHILE);let e=t.parseCompoundList();t.expect(u.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.whileNode(e,n,r)}function It(t){t.expect(u.UNTIL);let e=t.parseCompoundList();t.expect(u.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.untilNode(e,n,r)}function kt(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 n=[];for(;!t.check(u.ESAC,u.EOF);){t.checkIterationLimit();let s=t.getPos(),o=ls(t);if(o&&n.push(o),t.skipNewlines(),t.getPos()===s&&!o)break}t.expect(u.ESAC);let r=t.parseOptionalRedirections();return A.caseNode(e,n,r)}function ls(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 n=[];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 s=t.getPos(),o=t.parseStatement();if(o&&n.push(o),t.skipSeparators(!1),t.getPos()===s&&!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,n,r)}function Rt(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 n=t.parseOptionalRedirections();return A.subshell(e,n)}function Dt(t){t.expect(u.LBRACE);let e=t.parseCompoundList();t.expect(u.RBRACE);let n=t.parseOptionalRedirections();return A.group(e,n)}var us=["-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"],ds=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function _t(t){return t.skipNewlines(),hs(t)}function hs(t){let e=Zr(t);for(t.skipNewlines();t.check(u.OR_OR);){t.advance(),t.skipNewlines();let n=Zr(t);e={type:"CondOr",left:e,right:n},t.skipNewlines()}return e}function Zr(t){let e=Ot(t);for(t.skipNewlines();t.check(u.AND_AND);){t.advance(),t.skipNewlines();let n=Ot(t);e={type:"CondAnd",left:e,right:n},t.skipNewlines()}return e}function Ot(t){return t.skipNewlines(),t.check(u.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:Ot(t)}):ms(t)}function ms(t){if(t.check(u.LPAREN)){t.advance();let e=_t(t);return t.expect(u.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),n=e.value;if(us.includes(n)&&!e.quoted&&(t.advance(),t.check(u.DBRACK_END)&&t.error(`Expected operand after ${n}`),t.isWord())){let s=t.parseWord();return{type:"CondUnary",operator:n,operand:s}}let r=t.parseWord();if(t.isWord()&&ds.includes(t.current().value)){let s=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:s,left:r,right:o}}if(t.check(u.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:r,right:s}}if(t.check(u.GREAT)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:">",left:r,right:s}}if(t.isWord()&&t.current().value==="="){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}t.error("Expected conditional expression")}function ys(t,e,n){let r=n+1,s=e[r];if("@*#?$!-0123456789".includes(s))return{part:A.parameterExpansion(s),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 ws(t,e,n,r=!1){let s=n+2,o=!1;e[s]==="!"&&(o=!0,s++);let i=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(i=!0,s++);let a="",c=e[s];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))a=c,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)a+=e[s],s++;if(e[s]==="["){let f=bt(t,e,s,"[","]");a+=e.slice(s,f+1),s=f+1}a===""&&!o&&!i&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let l=null;if(o){let f=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(f)l={type:"ArrayKeys",array:f[1],star:f[2]==="*"},a="";else if(e[s]==="*"||e[s]==="@"){let d=e[s];s++,l={type:"VarNamePrefix",prefix:a,star:d==="*"},a=""}else l={type:"Indirection"}}else if(i)if(e[s]===":")for(l={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${a}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):l={type:"Length"};if(!l&&s<e.length&&e[s]!=="}"){let f=Es(t,e,s,a,r);l=f.operation,s=f.endIndex}if(s<e.length&&e[s]!=="}"){let f=e[s];if(!/[:\-+=?#%/^,@[]/.test(f)){let d=s;for(;d<e.length&&e[d]!=="}";)d++;let h=e.slice(n,d+1);t.error(`\${${h.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:A.parameterExpansion(a,l),endIndex:s+1}}function Es(t,e,n,r,s=!1){let o=n,i=e[o],a=e[o+1]||"";if(i===":"){let c=a;if("-=?+".includes(c)){o+=2;let w=pe(t,e,o),g=e.slice(o,w),b=ae(t,g,!1,!1,!0,!1,s),C=A.word(b.length>0?b:[A.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:C,checkEmpty:!0},endIndex:w};if(c==="=")return{operation:{type:"AssignDefault",word:C,checkEmpty:!0},endIndex:w};if(c==="?")return{operation:{type:"ErrorIfUnset",word:C,checkEmpty:!0},endIndex:w};if(c==="+")return{operation:{type:"UseAlternative",word:C,checkEmpty:!0},endIndex:w}}o++;let l=pe(t,e,o),f=e.slice(o,l),d=-1,h=0,m=0;for(let p=0;p<f.length;p++){let w=f[p];if(w==="("||w==="[")h++;else if(w===")"||w==="]")h--;else if(w==="?"&&h===0)m++;else if(w===":"&&h===0)if(m>0)m--;else{d=p;break}}let y=d>=0?f.slice(0,d):f,E=d>=0?f.slice(d+1):null;return{operation:{type:"Substring",offset:Ct(t,y),length:E?Ct(t,E):null},endIndex:l}}if("-=?+".includes(i)){o++;let c=pe(t,e,o),l=e.slice(o,c),f=ae(t,l,!1,!1,!0,!1,s),d=A.word(f.length>0?f:[A.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:d,checkEmpty:!1},endIndex:c};if(i==="=")return{operation:{type:"AssignDefault",word:d,checkEmpty:!1},endIndex:c};if(i==="?")return{operation:{type:"ErrorIfUnset",word:l?d:null,checkEmpty:!1},endIndex:c};if(i==="+")return{operation:{type:"UseAlternative",word:d,checkEmpty:!1},endIndex:c}}if(i==="#"||i==="%"){let c=a===i,l=i==="#"?"prefix":"suffix";o+=c?2:1;let f=pe(t,e,o),d=e.slice(o,f),h=ae(t,d,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:A.word(h.length>0?h:[A.literal("")]),side:l,greedy:c},endIndex:f}}if(i==="/"){let c=a==="/";o+=c?2:1;let l=null;e[o]==="#"?(l="start",o++):e[o]==="%"&&(l="end",o++);let f=Br(t,e,o),d=e.slice(o,f),h=ae(t,d,!1,!1,!1),m=A.word(h.length>0?h:[A.literal("")]),y=null,E=f;if(e[f]==="/"){let p=f+1,w=pe(t,e,p),g=e.slice(p,w),b=ae(t,g,!1,!1,!1);y=A.word(b.length>0?b:[A.literal("")]),E=w}return{operation:{type:"PatternReplacement",pattern:m,replacement:y,all:c,anchor:l},endIndex:E}}if(i==="^"||i===","){let c=a===i,l=i==="^"?"upper":"lower";o+=c?2:1;let f=pe(t,e,o),d=e.slice(o,f),h=d?A.word([A.literal(d)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:h},endIndex:f}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Lt(t,e,n,r=!1){let s=n+1;if(s>=e.length)return{part:A.literal("$"),endIndex:s};let o=e[s];if(o==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,n);if(o==="["){let i=1,a=s+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let c=e.slice(s+1,a),l=L(t,c);return{part:A.arithmeticExpansion(l),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,n):o==="{"?ws(t,e,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(o)?ys(t,e,n):{part:A.literal("$"),endIndex:s}}function gs(t,e){let n=[],r=0,s="",o=()=>{s&&(n.push(A.literal(s)),s="")};for(;r<e.length;){let i=e[r];if(i==="\\"&&r+1<e.length){let a=e[r+1];if(a==="$"||a==="`"){s+=a,r+=2;continue}s+=i,r++;continue}if(i==="$"){o();let{part:a,endIndex:c}=Lt(t,e,r,!0);a&&n.push(a),r=c;continue}if(i==="`"){o();let{part:a,endIndex:c}=t.parseBacktickSubstitution(e,r,!0);n.push(a),r=c;continue}s+=i,r++}return o(),n}function As(t,e,n){let r=[],s=n,o="",i=()=>{o&&(r.push(A.literal(o)),o="")};for(;s<e.length&&e[s]!=='"';){let a=e[s];if(a==="\\"&&s+1<e.length){let c=e[s+1];if('"\\$`\n'.includes(c)){o+=c,s+=2;continue}o+=a,s++;continue}if(a==="$"){i();let{part:c,endIndex:l}=Lt(t,e,s,!0);c&&r.push(c),s=l;continue}if(a==="`"){i();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,s,!0);r.push(c),s=l;continue}o+=a,s++}return i(),{part:A.doubleQuoted(r),endIndex:s}}function ae(t,e,n=!1,r=!1,s=!1,o=!1,i=!1){if(r)return[A.singleQuoted(e)];if(n){let d=gs(t,e);return[A.doubleQuoted(d)]}let a=[],c=0,l="",f=()=>{l&&(a.push(A.literal(l)),l="")};for(;c<e.length;){let d=e[c];if(d==="\\"&&c+1<e.length){let h=e[c+1];(o?h==="$"||h==="`"||h==="\\"||h===`
32
+ `||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(e,n,r){let s=this.input,o=s.length,i=e,a=r;for(;i<o;){let c=s[i];if(c===" "||c===" "||c===`
33
+ `||c===";"||c==="&"||c==="|"||c==="("||c===")"||c==="<"||c===">")break;if(c==="{"){if(this.scanBraceExpansion(i)!==null){let d=1;for(i++,a++;i<o&&d>0;)s[i]==="{"?d++:s[i]==="}"&&d--,i++,a++;continue}i++,a++;continue}if(c==="}"){i++,a++;continue}if(c==="$"&&i+1<o&&s[i+1]==="("){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)s[i]==="("?f++:s[i]===")"&&f--,i++,a++;continue}if(c==="$"&&i+1<o&&s[i+1]==="{"){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)s[i]==="{"?f++:s[i]==="}"&&f--,i++,a++;continue}if(c==="`"){for(i++,a++;i<o&&s[i]!=="`";)s[i]==="\\"&&i+1<o?(i+=2,a+=2):(i++,a++);i<o&&(i++,a++);continue}i++,a++}let l=s.slice(e,i);return this.pos=i,this.column=a,{type:u.WORD,value:l,start:e,end:i,line:n,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let n=this.input,r=n.length,s=e+1,o=1,i=!1,a=!1;for(;s<r&&o>0;){let l=n[s];if(l==="{")o++,s++;else if(l==="}")o--,s++;else if(l===","&&o===1)i=!0,s++;else if(l==="."&&s+1<r&&n[s+1]===".")a=!0,s+=2;else{if(l===" "||l===" "||l===`
34
+ `||l===";"||l==="&"||l==="|")return null;s++}}return o===0&&(i||a)?n.slice(e,s):null}scanLiteralBraceWord(e){let n=this.input,r=n.length,s=e+1,o=1;for(;s<r&&o>0;){let i=n[s];if(i==="{")o++,s++;else if(i==="}"){if(o--,o===0)return n.slice(e,s+1);s++}else{if(i===" "||i===" "||i===`
35
+ `||i===";"||i==="&"||i==="|")return null;s++}}return null}};var St=1e6,xt=1e5,Lr=1e6,Tr=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]),Wr=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,n,r,s=void 0){super(`Parse error at ${n}:${r}: ${e}`),this.line=n,this.column=r,this.token=s,this.name="ParseException"}};function Mr(t,e,n){let r=n+1;for(;r<e.length&&/[a-zA-Z0-9_-]/.test(e[r]);)r++;return r}function bt(t,e,n,r,s){let o=1,i=n+1;for(;i<e.length&&o>0;)e[i]===r?o++:e[i]===s&&o--,o>0&&i++;return o===0?i:-1}function pe(t,e,n){let r=n,s=1;for(;r<e.length&&s>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==="{"?s++:o==="}"&&s--,s>0&&r++}return r}function Br(t,e,n){let r=n,s=!1;for(;r<e.length;){let o=e[r];if(o==="/"&&s||o==="}")break;if(o==="'"){let i=e.indexOf("'",r+1);if(i!==-1){r=i+1,s=!0;continue}}if(o==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++,s=!0;continue}o==="\\"?(r+=2,s=!0):(r++,s=!0)}return r}function zr(t,e,n){let r=n,s="";for(;r<e.length;){let o=e[r];if(o==="*"||o==="?")s+=o,r++;else if(o==="["){let i=ss(e,r);i===-1?(s+=o,r++):(s+=e.slice(r,i+1),r=i+1)}else break}return{pattern:s,endIndex:r}}function ss(t,e){let n=e+1;for(n<t.length&&t[n]==="^"&&n++,n<t.length&&t[n]==="]"&&n++;n<t.length;){let r=t[n];if(r==="\\"&&n+1<t.length){n+=2;continue}if(r==="]")return n;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let s=t.indexOf("'",n+1);if(s!==-1){n=s+1;continue}}if(r==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){n=s+2;continue}}if(r==="["&&n+1<t.length&&(t[n+1]==="."||t[n+1]==="=")){let o=`${t[n+1]}]`,i=t.indexOf(o,n+2);if(i!==-1){n=i+2;continue}}n++}return-1}function Ur(t,e,n){let r="",s=n;for(;s<e.length&&e[s]!=="'";){let o=e[s];if(o==="\\"&&s+1<e.length)switch(e[s+1]){case"n":r+=`
36
+ `,s+=2;break;case"t":r+=" ",s+=2;break;case"r":r+="\r",s+=2;break;case"\\":r+="\\",s+=2;break;case"'":r+="'",s+=2;break;case'"':r+='"',s+=2;break;case"a":r+="\x07",s+=2;break;case"b":r+="\b",s+=2;break;case"e":case"E":r+="\x1B",s+=2;break;case"f":r+="\f",s+=2;break;case"v":r+="\v",s+=2;break;case"x":{let a=e.slice(s+2,s+4),l=parseInt(a,16);Number.isNaN(l)?(r+="\\x",s+=2):(r+=String.fromCharCode(l),s+=4);break}case"u":{let a=e.slice(s+2,s+6),l=parseInt(a,16);Number.isNaN(l)?(r+="\\u",s+=2):(r+=String.fromCharCode(l),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",l=s+1;for(;l<e.length&&l<s+4&&/[0-7]/.test(e[l]);)a+=e[l],l++;let c=parseInt(a,8);r+=String.fromCharCode(c),s=l;break}default:r+=o,s++}else r+=o,s++}return s<e.length&&e[s]==="'"&&s++,{part:A.literal(r),endIndex:s}}function Ct(t,e){let n=e.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:L(t,n)}function Fr(t){let e=[],n="",r=0;for(let s=0;s<t.length;s++){let o=t[s];o==="{"?(r++,n+=o):o==="}"?(r--,n+=o):o===","&&r===0?(e.push(n),n=""):n+=o}return e.push(n),e}function jr(t,e,n,r){let s=bt(t,e,n,"{","}");if(s===-1)return null;let o=e.slice(n+1,s),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:s+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:s+1}:o.includes(",")&&r?{part:{type:"BraceExpansion",items:Fr(o).map(f=>({type:"Word",word:A.word(r(t,f,!1,!1,!1))}))},endIndex:s+1}:o.includes(",")?{part:{type:"BraceExpansion",items:Fr(o).map(f=>({type:"Word",word:A.word([A.literal(f)])}))},endIndex:s+1}:null}function Gr(t,e){let n="";for(let r of e.parts)switch(r.type){case"Literal":case"SingleQuoted":case"Escaped":n+=r.value;break;case"DoubleQuoted":n+='"';for(let s of r.parts)s.type==="Literal"||s.type==="Escaped"?n+=s.value:s.type==="ParameterExpansion"&&(n+=`\${${s.parameter}}`);n+='"';break;case"ParameterExpansion":n+=`\${${r.parameter}}`;break;case"Glob":n+=r.pattern;break;default:n+=r.type}return n}function Hr(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 Qe(t){let e=t.current(),n=e.type;if(n===u.NUMBER){let r=t.peek(1);return e.end!==r.start?!1:Wr.has(r.type)}return Tr.has(n)}function Ke(t){let e=null;t.check(u.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let n=t.advance(),r=Hr(t,n.type);if(n.type===u.DLESS||n.type===u.DLESSDASH)return is(t,r,e,n.type===u.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return A.redirection(r,s,e)}function is(t,e,n,r){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),o=s.value,i=s.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),n);return t.addPendingHeredoc(a,o,r,i),a}function qr(t){let e=t.current().line,n=[],r=null,s=[],o=[];for(;t.check(u.ASSIGNMENT_WORD);)t.checkIterationLimit(),n.push(os(t));for(;Qe(t);)t.checkIterationLimit(),o.push(Ke(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(u.RBRACE))&&!t.check(u.PIPE,u.PIPE_AMP);)if(t.checkIterationLimit(),Qe(t))o.push(Ke(t));else if(t.check(u.RBRACE)){let a=t.advance();s.push(t.parseWordFromString(a.value,!1,!1))}else if(t.isWord())s.push(t.parseWord());else if(t.check(u.ASSIGNMENT_WORD)){let a=t.advance(),l=a.value,c=l.endsWith("="),f=l.endsWith("=(");if((c||f)&&(f||t.check(u.LPAREN))){let d=f?l.slice(0,-2):l.slice(0,-1);f||t.expect(u.LPAREN);let h=Nt(t);t.expect(u.RPAREN);let m=h.map(E=>Gr(t,E)),y=`${d}=(${m.join(" ")})`;s.push(t.parseWordFromString(y,!1,!1))}else s.push(t.parseWordFromString(l,a.quoted,a.singleQuoted))}else if(t.check(u.LPAREN))t.error("syntax error near unexpected token `('");else break;let i=A.simpleCommand(r,s,n,o);return i.line=e,i}function os(t){let e=t.expect(u.ASSIGNMENT_WORD),n=e.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||t.error(`Invalid assignment: ${n}`);let s=r[0],o,i=s.length;if(n[i]==="["){let d=0,h=i+1;for(;i<n.length;i++)if(n[i]==="[")d++;else if(n[i]==="]"&&(d--,d===0))break;d!==0&&t.error(`Invalid assignment: ${n}`),o=n.slice(h,i),i++}let a=n[i]==="+";a&&i++,n[i]!=="="&&t.error(`Invalid assignment: ${n}`),i++;let l=n.slice(i);if(l==="("){let d=Nt(t);t.expect(u.RPAREN);let h=o!==void 0?`${s}[${o}]`:s;return A.assignment(h,null,a,d)}if(l===""&&t.check(u.LPAREN)){let d=t.current();if(e.end===d.start){t.advance();let h=Nt(t);t.expect(u.RPAREN);let m=o!==void 0?`${s}[${o}]`:s;return A.assignment(m,null,a,h)}}let c=l?t.parseWordFromString(l,e.quoted,e.singleQuoted,!0):null,f=o!==void 0?`${s}[${o}]`:s;return A.assignment(f,c,a,null)}function Nt(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 vt(t){t.expect(u.IF);let e=[],n=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:n,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 s=null;t.check(u.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(u.FI);let o=t.parseOptionalRedirections();return A.ifNode(e,s,o)}function $t(t){if(t.expect(u.FOR),t.check(u.DPAREN_START))return cs(t);t.isWord()||t.error("Expected variable name in for loop");let n=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 s=t.parseCompoundList();t.expect(u.DONE);let o=t.parseOptionalRedirections();return A.forNode(n,r,s,o)}function cs(t){t.expect(u.DPAREN_START);let e=null,n=null,r=null,s=["","",""],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--,s[o]+=c.value}t.expect(u.DPAREN_END),s[0].trim()&&(e=L(t,s[0].trim())),s[1].trim()&&(n=L(t,s[1].trim())),s[2].trim()&&(r=L(t,s[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:n,update:r,body:a,redirections:l}}function Pt(t){t.expect(u.WHILE);let e=t.parseCompoundList();t.expect(u.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.whileNode(e,n,r)}function It(t){t.expect(u.UNTIL);let e=t.parseCompoundList();t.expect(u.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.untilNode(e,n,r)}function kt(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 n=[];for(;!t.check(u.ESAC,u.EOF);){t.checkIterationLimit();let s=t.getPos(),o=ls(t);if(o&&n.push(o),t.skipNewlines(),t.getPos()===s&&!o)break}t.expect(u.ESAC);let r=t.parseOptionalRedirections();return A.caseNode(e,n,r)}function ls(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 n=[];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 s=t.getPos(),o=t.parseStatement();if(o&&n.push(o),t.skipSeparators(!1),t.getPos()===s&&!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,n,r)}function Rt(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 n=t.parseOptionalRedirections();return A.subshell(e,n)}function Dt(t){t.expect(u.LBRACE);let e=t.parseCompoundList();t.expect(u.RBRACE);let n=t.parseOptionalRedirections();return A.group(e,n)}var us=["-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"],ds=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function _t(t){return t.skipNewlines(),hs(t)}function hs(t){let e=Zr(t);for(t.skipNewlines();t.check(u.OR_OR);){t.advance(),t.skipNewlines();let n=Zr(t);e={type:"CondOr",left:e,right:n},t.skipNewlines()}return e}function Zr(t){let e=Ot(t);for(t.skipNewlines();t.check(u.AND_AND);){t.advance(),t.skipNewlines();let n=Ot(t);e={type:"CondAnd",left:e,right:n},t.skipNewlines()}return e}function Ot(t){return t.skipNewlines(),t.check(u.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:Ot(t)}):ms(t)}function ms(t){if(t.check(u.LPAREN)){t.advance();let e=_t(t);return t.expect(u.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),n=e.value;if(us.includes(n)&&!e.quoted&&(t.advance(),t.check(u.DBRACK_END)&&t.error(`Expected operand after ${n}`),t.isWord())){let s=t.parseWord();return{type:"CondUnary",operator:n,operand:s}}let r=t.parseWord();if(t.isWord()&&ds.includes(t.current().value)){let s=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:s,left:r,right:o}}if(t.check(u.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:r,right:s}}if(t.check(u.GREAT)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:">",left:r,right:s}}if(t.isWord()&&t.current().value==="="){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}t.error("Expected conditional expression")}function ys(t,e,n){let r=n+1,s=e[r];if("@*#?$!-0123456789".includes(s))return{part:A.parameterExpansion(s),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 ws(t,e,n,r=!1){let s=n+2,o=!1;e[s]==="!"&&(o=!0,s++);let i=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(i=!0,s++);let a="",l=e[s];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))a=l,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)a+=e[s],s++;if(e[s]==="["){let f=bt(t,e,s,"[","]");a+=e.slice(s,f+1),s=f+1}a===""&&!o&&!i&&e[s]!=="}"&&t.error(`\${${e[s]}}: 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[s]==="*"||e[s]==="@"){let d=e[s];s++,c={type:"VarNamePrefix",prefix:a,star:d==="*"},a=""}else c={type:"Indirection"}}else if(i)if(e[s]===":")for(c={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${a}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):c={type:"Length"};if(!c&&s<e.length&&e[s]!=="}"){let f=Es(t,e,s,a,r);c=f.operation,s=f.endIndex}if(s<e.length&&e[s]!=="}"){let f=e[s];if(!/[:\-+=?#%/^,@[]/.test(f)){let d=s;for(;d<e.length&&e[d]!=="}";)d++;let h=e.slice(n,d+1);t.error(`\${${h.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:A.parameterExpansion(a,c),endIndex:s+1}}function Es(t,e,n,r,s=!1){let o=n,i=e[o],a=e[o+1]||"";if(i===":"){let l=a;if("-=?+".includes(l)){o+=2;let w=pe(t,e,o),g=e.slice(o,w),b=ae(t,g,!1,!1,!0,!1,s),C=A.word(b.length>0?b:[A.literal("")]);if(l==="-")return{operation:{type:"DefaultValue",word:C,checkEmpty:!0},endIndex:w};if(l==="=")return{operation:{type:"AssignDefault",word:C,checkEmpty:!0},endIndex:w};if(l==="?")return{operation:{type:"ErrorIfUnset",word:C,checkEmpty:!0},endIndex:w};if(l==="+")return{operation:{type:"UseAlternative",word:C,checkEmpty:!0},endIndex:w}}o++;let c=pe(t,e,o),f=e.slice(o,c),d=-1,h=0,m=0;for(let p=0;p<f.length;p++){let w=f[p];if(w==="("||w==="[")h++;else if(w===")"||w==="]")h--;else if(w==="?"&&h===0)m++;else if(w===":"&&h===0)if(m>0)m--;else{d=p;break}}let y=d>=0?f.slice(0,d):f,E=d>=0?f.slice(d+1):null;return{operation:{type:"Substring",offset:Ct(t,y),length:E?Ct(t,E):null},endIndex:c}}if("-=?+".includes(i)){o++;let l=pe(t,e,o),c=e.slice(o,l),f=ae(t,c,!1,!1,!0,!1,s),d=A.word(f.length>0?f:[A.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:d,checkEmpty:!1},endIndex:l};if(i==="=")return{operation:{type:"AssignDefault",word:d,checkEmpty:!1},endIndex:l};if(i==="?")return{operation:{type:"ErrorIfUnset",word:c?d:null,checkEmpty:!1},endIndex:l};if(i==="+")return{operation:{type:"UseAlternative",word:d,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),d=e.slice(o,f),h=ae(t,d,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:A.word(h.length>0?h:[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=Br(t,e,o),d=e.slice(o,f),h=ae(t,d,!1,!1,!1),m=A.word(h.length>0?h:[A.literal("")]),y=null,E=f;if(e[f]==="/"){let p=f+1,w=pe(t,e,p),g=e.slice(p,w),b=ae(t,g,!1,!1,!1);y=A.word(b.length>0?b:[A.literal("")]),E=w}return{operation:{type:"PatternReplacement",pattern:m,replacement:y,all:l,anchor:c},endIndex:E}}if(i==="^"||i===","){let l=a===i,c=i==="^"?"upper":"lower";o+=l?2:1;let f=pe(t,e,o),d=e.slice(o,f),h=d?A.word([A.literal(d)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:h},endIndex:f}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Lt(t,e,n,r=!1){let s=n+1;if(s>=e.length)return{part:A.literal("$"),endIndex:s};let o=e[s];if(o==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,n);if(o==="["){let i=1,a=s+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let l=e.slice(s+1,a),c=L(t,l);return{part:A.arithmeticExpansion(c),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,n):o==="{"?ws(t,e,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(o)?ys(t,e,n):{part:A.literal("$"),endIndex:s}}function gs(t,e){let n=[],r=0,s="",o=()=>{s&&(n.push(A.literal(s)),s="")};for(;r<e.length;){let i=e[r];if(i==="\\"&&r+1<e.length){let a=e[r+1];if(a==="$"||a==="`"){s+=a,r+=2;continue}s+=i,r++;continue}if(i==="$"){o();let{part:a,endIndex:l}=Lt(t,e,r,!0);a&&n.push(a),r=l;continue}if(i==="`"){o();let{part:a,endIndex:l}=t.parseBacktickSubstitution(e,r,!0);n.push(a),r=l;continue}s+=i,r++}return o(),n}function As(t,e,n){let r=[],s=n,o="",i=()=>{o&&(r.push(A.literal(o)),o="")};for(;s<e.length&&e[s]!=='"';){let a=e[s];if(a==="\\"&&s+1<e.length){let l=e[s+1];if('"\\$`\n'.includes(l)){o+=l,s+=2;continue}o+=a,s++;continue}if(a==="$"){i();let{part:l,endIndex:c}=Lt(t,e,s,!0);l&&r.push(l),s=c;continue}if(a==="`"){i();let{part:l,endIndex:c}=t.parseBacktickSubstitution(e,s,!0);r.push(l),s=c;continue}o+=a,s++}return i(),{part:A.doubleQuoted(r),endIndex:s}}function ae(t,e,n=!1,r=!1,s=!1,o=!1,i=!1){if(r)return[A.singleQuoted(e)];if(n){let d=gs(t,e);return[A.doubleQuoted(d)]}let a=[],l=0,c="",f=()=>{c&&(a.push(A.literal(c)),c="")};for(;l<e.length;){let d=e[l];if(d==="\\"&&l+1<e.length){let h=e[l+1];(o?h==="$"||h==="`"||h==="\\"||h===`
37
37
  `:h==="$"||h==="`"||h==="\\"||h==='"'||h===`
38
- `)?l+=h:l+=`\\${h}`,c+=2;continue}if(d==="'"&&!i&&!o){f();let h=e.indexOf("'",c+1);if(h===-1){l+=e.slice(c);break}a.push(A.singleQuoted(e.slice(c+1,h))),c=h+1;continue}if(d==='"'&&!o){f();let{part:h,endIndex:m}=As(t,e,c+1);a.push(h),c=m+1;continue}if(d==="$"&&e[c+1]==="'"){f();let{part:h,endIndex:m}=Ur(t,e,c+2);a.push(h),c=m;continue}if(d==="$"){f();let{part:h,endIndex:m}=Lt(t,e,c);h&&a.push(h),c=m;continue}if(d==="`"){f();let{part:h,endIndex:m}=t.parseBacktickSubstitution(e,c);a.push(h),c=m;continue}if(d==="~"){let h=c>0?e[c-1]:"";if(c===0||h==="="||s&&h===":"){let y=Mr(t,e,c),E=e[y];if(E===void 0||E==="/"||E===":"){f();let p=e.slice(c+1,y)||null;a.push({type:"TildeExpansion",user:p}),c=y;continue}}}if(d==="*"||d==="?"||d==="["){f();let{pattern:h,endIndex:m}=zr(t,e,c);a.push({type:"Glob",pattern:h}),c=m;continue}if(d==="{"&&!s){let h=jr(t,e,c,ae);if(h){f(),a.push(h.part),c=h.endIndex;continue}}l+=d,c++}return f(),a}var M=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Lr)throw new ee("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>xt)throw new ee(`Input too large: ${e.length} bytes exceeds limit of ${xt}`,1,1);let n=new Ze(e);if(this.tokens=n.tokenize(),this.tokens.length>St)throw new ee(`Too many tokens: ${this.tokens.length} exceeds limit of ${St}`,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,n,r,s,...o){let i=this.tokens[this.pos]?.type;return i===e||n!==void 0&&i===n||r!==void 0&&i===r||s!==void 0&&i===s?!0:o.length>0?o.includes(i):!1}expect(e,n){if(this.check(e))return this.advance();let r=this.current();throw new ee(n||`Expected ${e}, got ${r.type}`,r.line,r.column,r)}error(e){let n=this.current();throw new ee(e,n.line,n.column,n)}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,n,r,s){this.pendingHeredocs.push({redirect:e,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(u.HEREDOC_CONTENT)){let n=this.advance(),r;e.quoted?r=A.word([A.literal(n.value)]):r=this.parseWordFromString(n.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||e===u.LESS||e===u.GREAT||e===u.DLESS||e===u.DGREAT||e===u.LESSAND||e===u.GREATAND||e===u.LESSGREAT||e===u.DLESSDASH||e===u.CLOBBER||e===u.TLESS||e===u.AND_GREAT||e===u.AND_DGREAT}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 s=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===s&&!this.check(u.EOF)&&this.advance()}return A.script(e)}checkUnexpectedToken(){let e=this.current().type,n=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 \`${n}'`),(e===u.RBRACE||e===u.RPAREN)&&this.error(`syntax error near unexpected token \`${n}'`),(e===u.DSEMI||e===u.SEMI_AND||e===u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),e===u.SEMICOLON&&this.error(`syntax error near unexpected token \`${n}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],n=[],r=!1,s=this.parsePipeline();for(e.push(s);this.check(u.AND_AND,u.OR_OR);){let o=this.advance();n.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,n,r)}parsePipeline(){let e=0;for(;this.check(u.BANG);)this.advance(),e++;let n=e%2===1,r=[],s=this.parseCommand();for(r.push(s);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,n)}parseCommand(){return this.check(u.IF)?vt(this):this.check(u.FOR)?$t(this):this.check(u.WHILE)?Pt(this):this.check(u.UNTIL)?It(this):this.check(u.CASE)?kt(this):this.check(u.LPAREN)?Rt(this):this.check(u.LBRACE)?Dt(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():qr(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.SELECT||e===u.TIME||e===u.COPROC||e===u.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,n=!1,r=!1,s=!1,o=!1){let i=ae(this,e,n,r,s,o);return A.word(i)}parseCommandSubstitution(e,n){let r=n+2,s=1,o=r,i=!1,a=!1,c=0,l=!1,f="";for(;o<e.length&&s>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"?(c++,l=!1):f==="in"&&c>0?l=!0:f==="esac"&&c>0&&(c--,l=!1),f="",y==="("?o>0&&e[o-1]==="$"?s++:l||s++:y===")"?l?l=!1:s--:y===";"&&c>0&&o+1<e.length&&e[o+1]===";"&&(l=!0)),s>0&&o++}s>0&&this.error("unexpected EOF while looking for matching `)'");let d=e.slice(r,o),m=new t().parse(d);return{part:A.commandSubstitution(m,!1),endIndex:o+1}}parseBacktickSubstitution(e,n,r=!1){let o=n+1,i="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let l=e[o+1];l==="$"||l==="`"||l==="\\"||l===`
39
- `||r&&l==='"'?(l!==`
40
- `&&(i+=l),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(i);return{part:A.commandSubstitution(c,!0),endIndex:o+1}}parseArithmeticExpansion(e,n){let r=n+3,s=1,o=0,i=r;for(;i<e.length-1&&s>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(s++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(s++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(s--,s>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(r,i),c=this.parseArithmeticExpression(a);return{part:A.arithmeticExpansion(c),endIndex:i+2}}parseArithmeticCommand(){this.expect(u.DPAREN_START);let e="",n=1,r=0,s=!1,o=!1;for(;n>0&&!this.check(u.EOF);){if(s){if(s=!1,r>0){r--,e+=")";continue}if(this.check(u.RPAREN)){n--,o=!0,this.advance();continue}if(this.check(u.DPAREN_END)){n--,o=!0;continue}e+=")";continue}this.check(u.DPAREN_START)?(n++,e+="((",this.advance()):this.check(u.DPAREN_END)?r>=2?(r-=2,e+="))",this.advance()):r===1?(r--,e+=")",s=!0,this.advance()):(n--,o=!0,n>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=_t(this);this.expect(u.DBRACK_END);let n=this.parseOptionalRedirections();return A.conditionalCommand(e,n)}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 n=this.parseCompoundCommandBody(),r=this.parseOptionalRedirections();return A.functionDef(e,n,r)}parseCompoundCommandBody(){if(this.check(u.LBRACE))return Dt(this);if(this.check(u.LPAREN))return Rt(this);if(this.check(u.IF))return vt(this);if(this.check(u.FOR))return $t(this);if(this.check(u.WHILE))return Pt(this);if(this.check(u.UNTIL))return It(this);if(this.check(u.CASE))return kt(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 n=this.pos,r=this.parseStatement();if(r&&e.push(r),this.skipSeparators(),this.pos===n&&!r)break}return e}parseOptionalRedirections(){let e=[];for(;Qe(this);){this.checkIterationLimit();let n=this.pos;if(e.push(Ke(this)),this.pos===n)break}return e}parseArithmeticExpression(e){return L(this,e)}};function ce(t){return new M().parse(t)}var be=class{fs;cwd;constructor(e,n){this.fs=e,this.cwd=n}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,n){let r=e.map((i,a)=>(n?.[a]??!1)||!this.isGlobPattern(i)?null:this.expand(i)),s=await Promise.all(r.map(i=>i||Promise.resolve(null))),o=[];for(let i=0;i<e.length;i++){let a=s[i];a===null?o.push(e[i]):a.length>0?o.push(...a):o.push(e[i])}return o}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let n=[],r=e.lastIndexOf("/"),s,o;r===-1?(s=this.cwd,o=e):(s=e.slice(0,r)||"/",o=e.slice(r+1));let i=this.fs.resolvePath(this.cwd,s);try{let a=await this.fs.readdir(i);for(let c of a)if(this.matchPattern(c,o)){let l=r===-1?c:`${s}/${c}`;n.push(l)}}catch{}return n.sort()}async expandRecursive(e){let n=[],r=e.indexOf("**"),s=e.slice(0,r).replace(/\/$/,"")||".",i=e.slice(r+2).replace(/^\//,"");return await this.walkDirectory(s,i,n),n.sort()}async walkDirectory(e,n,r){let s=this.fs.resolvePath(this.cwd,e);try{if(this.fs.readdirWithFileTypes){let o=await this.fs.readdirWithFileTypes(s),i=[],a=[];for(let c of o){let l=e==="."?c.name:`${e}/${c.name}`;c.isDirectory?a.push(l):n&&this.matchPattern(c.name,n)&&i.push(l)}r.push(...i);for(let c=0;c<a.length;c+=100){let l=a.slice(c,c+100);await Promise.all(l.map(f=>this.walkDirectory(f,n,r)))}}else{let o=await this.fs.readdir(s),i=[];for(let c=0;c<o.length;c+=100){let l=o.slice(c,c+100),f=await Promise.all(l.map(async d=>{let h=e==="."?d:`${e}/${d}`,m=this.fs.resolvePath(this.cwd,h);try{let y=await this.fs.stat(m);return{name:d,path:h,isDirectory:y.isDirectory}}catch{return null}}));i.push(...f.filter(d=>d!==null))}for(let c of i)!c.isDirectory&&n&&this.matchPattern(c.name,n)&&r.push(c.path);let a=i.filter(c=>c.isDirectory);for(let c=0;c<a.length;c+=100){let l=a.slice(c,c+100);await Promise.all(l.map(f=>this.walkDirectory(f.path,n,r)))}}}catch{}}matchPattern(e,n){return this.patternToRegex(n).test(e)}patternToRegex(e){let n="^";for(let r=0;r<e.length;r++){let s=e[r];if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){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 c=e.slice(o+2,a),l=this.posixClassToRegex(c);i+=l,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+="]",n+=i,r=o}else if(s==="\\"&&r+1<e.length){let o=e[r+1];/[.+^${}()|\\*?[\]]/.test(o)?n+=`\\${o}`:n+=o,r++}else/[.+^${}()|]/.test(s)?n+=`\\${s}`:n+=s}return n+="$",new RegExp(n)}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 Tt(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 Xe(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return V(t.expression.expression);case"DoubleQuoted":return t.parts.some(Xe);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&te(e.word));case"ParameterExpansion":return Tt(t);default:return!1}}function te(t){return t.parts.some(Xe)}function Wt(t){if(!t.operation)return!1;let e=t.operation,n;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(n=e.word?.parts),!n)return!1;for(let r of n)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Qr(t){let e=!1,n=!1,r=!1,s=!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&&(s=!0);i.type==="CommandSubstitution"&&(n=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(r=!0),Wt(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:o}}function Ss(t,e,n,r,s){let o=n??1;o===0&&(o=1);let i=Math.abs(o),a=[],c=0;r?.match(/^-?0\d/)&&(c=Math.max(c,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length));let l=f=>{if(c>0){let d=f<0,h=String(Math.abs(f)).padStart(c,"0");return d?`-${h}`:h}return String(f)};if(t<=e)for(let f=t,d=0;f<=e&&d<1e4;f+=i,d++)a.push(l(f));else for(let f=t,d=0;f>=e&&d<1e4;f-=i,d++)a.push(l(f));return a}function bs(t,e,n){let r=n??1;r===0&&(r=1);let s=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(r),a=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",f=e>="a"&&e<="z";if(a&&f||c&&l)return null;let d=[];if(s<=o)for(let h=s,m=0;h<=o&&m<1e4;h+=i,m++)d.push(String.fromCharCode(h));else for(let h=s,m=0;h>=o&&m<1e4;h-=i,m++)d.push(String.fromCharCode(h));return d}function De(t,e,n,r,s){let o=n!==void 0?`..${n}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:Ss(t,e,n,r,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:bs(t,e,n),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function j(t,e){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\")if(r+1<t.length){let o=t[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?n+=`\\${o}`:n+=o,r+=2}else n+="\\\\",r++;else if(s==="*")n+=e?".*":".*?",r++;else if(s==="?")n+=".",r++;else if(s==="["){let o=Cs(t,r);if(o===-1)n+="\\[",r++;else{let i=t.slice(r+1,o);n+=Ns(i),r=o+1}}else/[\^$.|+(){}]/.test(s)?(n+=`\\${s}`,r++):(n+=s,r++)}return n}function Cs(t,e){let n=e+1;for(n<t.length&&t[n]==="^"&&n++,n<t.length&&t[n]==="]"&&n++;n<t.length;){if(t[n]==="\\"&&n+1<t.length){n+=2;continue}if(t[n]==="]")return n;if(t[n]==="'"){let r=t.indexOf("'",n+1);if(r!==-1){n=r+1;continue}}if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let r=t.indexOf(":]",n+2);if(r!==-1){n=r+2;continue}}n++}return-1}function Ns(t){let e="[",n=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",n++);n<t.length;){if(t[n]==="'"){let s=t.indexOf("'",n+1);if(s!==-1){let o=t.slice(n+1,s);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;n=s+1;continue}}if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){let o=t.slice(n+2,s);e+=$s(o),n=s+2;continue}}let r=t[n];r==="\\"?n+1<t.length?(e+=`\\${t[n+1]}`,n+=2):(e+="\\\\",n++):r==="-"&&n>0&&n<t.length-1?(e+="-",n++):r==="^"&&n===0?(e+="^",n++):(r==="]"&&n===0?e+="\\]":e+=r,n++)}return e+="]",e}var vs={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 $s(t){return vs[t]??""}function Oe(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)){let o=s.slice(n.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&r.push(i)}return r.sort((s,o)=>s-o)}function _e(t,e){let n=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(n)&&delete t.state.env[r]}function Ft(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)&&!s.includes("__")){let o=s.slice(n.length);r.push(o)}return r.sort()}function Kr(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Ye(t){return t.IFS??`
38
+ `)?c+=h:c+=`\\${h}`,l+=2;continue}if(d==="'"&&!i&&!o){f();let h=e.indexOf("'",l+1);if(h===-1){c+=e.slice(l);break}a.push(A.singleQuoted(e.slice(l+1,h))),l=h+1;continue}if(d==='"'&&!o){f();let{part:h,endIndex:m}=As(t,e,l+1);a.push(h),l=m+1;continue}if(d==="$"&&e[l+1]==="'"){f();let{part:h,endIndex:m}=Ur(t,e,l+2);a.push(h),l=m;continue}if(d==="$"){f();let{part:h,endIndex:m}=Lt(t,e,l);h&&a.push(h),l=m;continue}if(d==="`"){f();let{part:h,endIndex:m}=t.parseBacktickSubstitution(e,l);a.push(h),l=m;continue}if(d==="~"){let h=l>0?e[l-1]:"";if(l===0||h==="="||s&&h===":"){let y=Mr(t,e,l),E=e[y];if(E===void 0||E==="/"||E===":"){f();let p=e.slice(l+1,y)||null;a.push({type:"TildeExpansion",user:p}),l=y;continue}}}if(d==="*"||d==="?"||d==="["){f();let{pattern:h,endIndex:m}=zr(t,e,l);a.push({type:"Glob",pattern:h}),l=m;continue}if(d==="{"&&!s){let h=jr(t,e,l,ae);if(h){f(),a.push(h.part),l=h.endIndex;continue}}c+=d,l++}return f(),a}var M=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Lr)throw new ee("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>St)throw new ee(`Input too large: ${e.length} bytes exceeds limit of ${St}`,1,1);let n=new Ze(e);if(this.tokens=n.tokenize(),this.tokens.length>xt)throw new ee(`Too many tokens: ${this.tokens.length} exceeds limit of ${xt}`,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,n,r,s,...o){let i=this.tokens[this.pos]?.type;return i===e||n!==void 0&&i===n||r!==void 0&&i===r||s!==void 0&&i===s?!0:o.length>0?o.includes(i):!1}expect(e,n){if(this.check(e))return this.advance();let r=this.current();throw new ee(n||`Expected ${e}, got ${r.type}`,r.line,r.column,r)}error(e){let n=this.current();throw new ee(e,n.line,n.column,n)}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,n,r,s){this.pendingHeredocs.push({redirect:e,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(u.HEREDOC_CONTENT)){let n=this.advance(),r;e.quoted?r=A.word([A.literal(n.value)]):r=this.parseWordFromString(n.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||e===u.LESS||e===u.GREAT||e===u.DLESS||e===u.DGREAT||e===u.LESSAND||e===u.GREATAND||e===u.LESSGREAT||e===u.DLESSDASH||e===u.CLOBBER||e===u.TLESS||e===u.AND_GREAT||e===u.AND_DGREAT}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 s=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===s&&!this.check(u.EOF)&&this.advance()}return A.script(e)}checkUnexpectedToken(){let e=this.current().type,n=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 \`${n}'`),(e===u.RBRACE||e===u.RPAREN)&&this.error(`syntax error near unexpected token \`${n}'`),(e===u.DSEMI||e===u.SEMI_AND||e===u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),e===u.SEMICOLON&&this.error(`syntax error near unexpected token \`${n}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],n=[],r=!1,s=this.parsePipeline();for(e.push(s);this.check(u.AND_AND,u.OR_OR);){let o=this.advance();n.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,n,r)}parsePipeline(){let e=0;for(;this.check(u.BANG);)this.advance(),e++;let n=e%2===1,r=[],s=this.parseCommand();for(r.push(s);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,n)}parseCommand(){return this.check(u.IF)?vt(this):this.check(u.FOR)?$t(this):this.check(u.WHILE)?Pt(this):this.check(u.UNTIL)?It(this):this.check(u.CASE)?kt(this):this.check(u.LPAREN)?Rt(this):this.check(u.LBRACE)?Dt(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():qr(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.SELECT||e===u.TIME||e===u.COPROC||e===u.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,n=!1,r=!1,s=!1,o=!1){let i=ae(this,e,n,r,s,o);return A.word(i)}parseCommandSubstitution(e,n){let r=n+2,s=1,o=r,i=!1,a=!1,l=0,c=!1,f="";for(;o<e.length&&s>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]==="$"?s++:c||s++:y===")"?c?c=!1:s--:y===";"&&l>0&&o+1<e.length&&e[o+1]===";"&&(c=!0)),s>0&&o++}s>0&&this.error("unexpected EOF while looking for matching `)'");let d=e.slice(r,o),m=new t().parse(d);return{part:A.commandSubstitution(m,!1),endIndex:o+1}}parseBacktickSubstitution(e,n,r=!1){let o=n+1,i="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let c=e[o+1];c==="$"||c==="`"||c==="\\"||c===`
39
+ `||r&&c==='"'?(c!==`
40
+ `&&(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,n){let r=n+3,s=1,o=0,i=r;for(;i<e.length-1&&s>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(s++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(s++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(s--,s>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="",n=1,r=0,s=!1,o=!1;for(;n>0&&!this.check(u.EOF);){if(s){if(s=!1,r>0){r--,e+=")";continue}if(this.check(u.RPAREN)){n--,o=!0,this.advance();continue}if(this.check(u.DPAREN_END)){n--,o=!0;continue}e+=")";continue}this.check(u.DPAREN_START)?(n++,e+="((",this.advance()):this.check(u.DPAREN_END)?r>=2?(r-=2,e+="))",this.advance()):r===1?(r--,e+=")",s=!0,this.advance()):(n--,o=!0,n>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=_t(this);this.expect(u.DBRACK_END);let n=this.parseOptionalRedirections();return A.conditionalCommand(e,n)}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 n=this.parseCompoundCommandBody(),r=this.parseOptionalRedirections();return A.functionDef(e,n,r)}parseCompoundCommandBody(){if(this.check(u.LBRACE))return Dt(this);if(this.check(u.LPAREN))return Rt(this);if(this.check(u.IF))return vt(this);if(this.check(u.FOR))return $t(this);if(this.check(u.WHILE))return Pt(this);if(this.check(u.UNTIL))return It(this);if(this.check(u.CASE))return kt(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 n=this.pos,r=this.parseStatement();if(r&&e.push(r),this.skipSeparators(),this.pos===n&&!r)break}return e}parseOptionalRedirections(){let e=[];for(;Qe(this);){this.checkIterationLimit();let n=this.pos;if(e.push(Ke(this)),this.pos===n)break}return e}parseArithmeticExpression(e){return L(this,e)}};function ce(t){return new M().parse(t)}var be=class{fs;cwd;constructor(e,n){this.fs=e,this.cwd=n}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,n){let r=e.map((i,a)=>(n?.[a]??!1)||!this.isGlobPattern(i)?null:this.expand(i)),s=await Promise.all(r.map(i=>i||Promise.resolve(null))),o=[];for(let i=0;i<e.length;i++){let a=s[i];a===null?o.push(e[i]):a.length>0?o.push(...a):o.push(e[i])}return o}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}hasGlobChars(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandSimple(e){let n=e.startsWith("/"),r=e.split("/").filter(c=>c!==""),s=-1;for(let c=0;c<r.length;c++)if(this.hasGlobChars(r[c])){s=c;break}if(s===-1)return[e];let o,i;if(s===0)n?(o="/",i="/"):(o=this.cwd,i="");else{let c=r.slice(0,s);n?(o=`/${c.join("/")}`,i=`/${c.join("/")}`):(o=this.fs.resolvePath(this.cwd,c.join("/")),i=c.join("/"))}let a=r.slice(s);return(await this.expandSegments(o,i,a)).sort()}async expandSegments(e,n,r){if(r.length===0)return[n];let[s,...o]=r,i=[];try{if(this.fs.readdirWithFileTypes){let a=await this.fs.readdirWithFileTypes(e),l=[];for(let f of a)if(!(f.name.startsWith(".")&&!s.startsWith("."))&&this.matchPattern(f.name,s)){let d=e==="/"?`/${f.name}`:`${e}/${f.name}`,h;n===""?h=f.name:n==="/"?h=`/${f.name}`:h=`${n}/${f.name}`,o.length===0?l.push(Promise.resolve([h])):f.isDirectory&&l.push(this.expandSegments(d,h,o))}let c=await Promise.all(l);for(let f of c)i.push(...f)}else{let a=await this.fs.readdir(e),l=[];for(let f of a)if(!(f.startsWith(".")&&!s.startsWith("."))&&this.matchPattern(f,s)){let d=e==="/"?`/${f}`:`${e}/${f}`,h;n===""?h=f:n==="/"?h=`/${f}`:h=`${n}/${f}`,o.length===0?l.push(Promise.resolve([h])):l.push((async()=>{try{if((await this.fs.stat(d)).isDirectory)return this.expandSegments(d,h,o)}catch{}return[]})())}let c=await Promise.all(l);for(let f of c)i.push(...f)}}catch{}return i}async expandRecursive(e){let n=[],r=e.indexOf("**"),s=e.slice(0,r).replace(/\/$/,"")||".",i=e.slice(r+2).replace(/^\//,"");return await this.walkDirectory(s,i,n),n.sort()}async walkDirectory(e,n,r){let s=this.fs.resolvePath(this.cwd,e);try{if(this.fs.readdirWithFileTypes){let o=await this.fs.readdirWithFileTypes(s),i=[],a=[];for(let l of o){let c=e==="."?l.name:`${e}/${l.name}`;l.isDirectory?a.push(c):n&&this.matchPattern(l.name,n)&&i.push(c)}r.push(...i);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(f=>this.walkDirectory(f,n,r)))}}else{let o=await this.fs.readdir(s),i=[];for(let l=0;l<o.length;l+=100){let c=o.slice(l,l+100),f=await Promise.all(c.map(async d=>{let h=e==="."?d:`${e}/${d}`,m=this.fs.resolvePath(this.cwd,h);try{let y=await this.fs.stat(m);return{name:d,path:h,isDirectory:y.isDirectory}}catch{return null}}));i.push(...f.filter(d=>d!==null))}for(let l of i)!l.isDirectory&&n&&this.matchPattern(l.name,n)&&r.push(l.path);let a=i.filter(l=>l.isDirectory);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(f=>this.walkDirectory(f.path,n,r)))}}}catch{}}matchPattern(e,n){return this.patternToRegex(n).test(e)}patternToRegex(e){let n="^";for(let r=0;r<e.length;r++){let s=e[r];if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){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+="]",n+=i,r=o}else if(s==="\\"&&r+1<e.length){let o=e[r+1];/[.+^${}()|\\*?[\]]/.test(o)?n+=`\\${o}`:n+=o,r++}else/[.+^${}()|]/.test(s)?n+=`\\${s}`:n+=s}return n+="$",new RegExp(n)}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 Tt(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 Xe(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return V(t.expression.expression);case"DoubleQuoted":return t.parts.some(Xe);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&te(e.word));case"ParameterExpansion":return Tt(t);default:return!1}}function te(t){return t.parts.some(Xe)}function Wt(t){if(!t.operation)return!1;let e=t.operation,n;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(n=e.word?.parts),!n)return!1;for(let r of n)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Qr(t){let e=!1,n=!1,r=!1,s=!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&&(s=!0);i.type==="CommandSubstitution"&&(n=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(r=!0),Wt(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:o}}function xs(t,e,n,r,s){let o=n??1;o===0&&(o=1);let i=Math.abs(o),a=[],l=0;r?.match(/^-?0\d/)&&(l=Math.max(l,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(l=Math.max(l,s.replace(/^-/,"").length));let c=f=>{if(l>0){let d=f<0,h=String(Math.abs(f)).padStart(l,"0");return d?`-${h}`:h}return String(f)};if(t<=e)for(let f=t,d=0;f<=e&&d<1e4;f+=i,d++)a.push(c(f));else for(let f=t,d=0;f>=e&&d<1e4;f-=i,d++)a.push(c(f));return a}function bs(t,e,n){let r=n??1;r===0&&(r=1);let s=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 d=[];if(s<=o)for(let h=s,m=0;h<=o&&m<1e4;h+=i,m++)d.push(String.fromCharCode(h));else for(let h=s,m=0;h>=o&&m<1e4;h-=i,m++)d.push(String.fromCharCode(h));return d}function De(t,e,n,r,s){let o=n!==void 0?`..${n}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:xs(t,e,n,r,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:bs(t,e,n),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function j(t,e){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\")if(r+1<t.length){let o=t[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?n+=`\\${o}`:n+=o,r+=2}else n+="\\\\",r++;else if(s==="*")n+=e?".*":".*?",r++;else if(s==="?")n+=".",r++;else if(s==="["){let o=Cs(t,r);if(o===-1)n+="\\[",r++;else{let i=t.slice(r+1,o);n+=Ns(i),r=o+1}}else/[\^$.|+(){}]/.test(s)?(n+=`\\${s}`,r++):(n+=s,r++)}return n}function Cs(t,e){let n=e+1;for(n<t.length&&t[n]==="^"&&n++,n<t.length&&t[n]==="]"&&n++;n<t.length;){if(t[n]==="\\"&&n+1<t.length){n+=2;continue}if(t[n]==="]")return n;if(t[n]==="'"){let r=t.indexOf("'",n+1);if(r!==-1){n=r+1;continue}}if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let r=t.indexOf(":]",n+2);if(r!==-1){n=r+2;continue}}n++}return-1}function Ns(t){let e="[",n=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",n++);n<t.length;){if(t[n]==="'"){let s=t.indexOf("'",n+1);if(s!==-1){let o=t.slice(n+1,s);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;n=s+1;continue}}if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){let o=t.slice(n+2,s);e+=$s(o),n=s+2;continue}}let r=t[n];r==="\\"?n+1<t.length?(e+=`\\${t[n+1]}`,n+=2):(e+="\\\\",n++):r==="-"&&n>0&&n<t.length-1?(e+="-",n++):r==="^"&&n===0?(e+="^",n++):(r==="]"&&n===0?e+="\\]":e+=r,n++)}return e+="]",e}var vs={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 $s(t){return vs[t]??""}function Oe(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)){let o=s.slice(n.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&r.push(i)}return r.sort((s,o)=>s-o)}function _e(t,e){let n=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(n)&&delete t.state.env[r]}function Ft(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)&&!s.includes("__")){let o=s.slice(n.length);r.push(o)}return r.sort()}function Kr(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Ye(t){return t.IFS??`
41
41
  `}function Xr(t){return t.IFS===""}function Le(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
42
- `?"\\n":e).join("")}function Ps(t,e){let n=Le(t);return new RegExp(`[${n}]+`,e)}function Is(t){let e=Le(t);return new RegExp(`^[${e}]+`)}function ks(t){let e=Le(t);return new RegExp(`[${e}]+$`)}function Ce(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function Yr(t,e){if(e==="")return{words:[t],wordStarts:[0]};let n=[],r=[],s=Ps(e,"g"),o=0,i=t.match(Is(e));i&&(o=i[0].length),s.lastIndex=o;let a=s.exec(t);for(;a!==null;)a.index>o&&(r.push(o),n.push(t.substring(o,a.index))),o=s.lastIndex,a=s.exec(t);return o<t.length&&(r.push(o),n.push(t.substring(o))),{words:n,wordStarts:r}}function Jr(t,e){return e===""?t:t.replace(ks(e),"")}function T(t,e){return t.state.associativeArrays?.has(e)?Ft(t,e).map(o=>[o,t.state.env[`${e}_${o}`]]):Oe(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function en(t,e){return t.state.associativeArrays?.has(e)?Ft(t,e).length>0:Oe(t,e).length>0}function q(t,e,n=!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 c=1;c<=i;c++)a.push(t.state.env[String(c)]||"");return a.join(Ce(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:"";case"PPID":{let{ppid:i}=Re();return String(i)}case"UID":{let{uid:i}=Re();return String(i)}case"EUID":return String(process.geteuid?.()??Re().uid);case"RANDOM":return String(Math.floor(Math.random()*32768));case"SECONDS":return String(Math.floor((Date.now()-t.state.startTime)/1e3));case"BASH_VERSION":return gr;case"!":return String(t.state.lastBackgroundPid);case"LINENO":return String(t.state.currentLine)}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(e))throw new me(`\${${e}}`);let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let i=s[1],a=s[2];if(a==="@"||a==="*"){let d=T(t,i);if(d.length>0)return d.map(([,m])=>m).join(" ");let h=t.state.env[i];return h!==void 0?h:""}if(t.state.associativeArrays?.has(i)){let d=Kr(a),h=t.state.env[`${i}_${d}`];if(h===void 0&&n&&t.state.options.nounset)throw new X(`${i}[${a}]`);return h||""}let l;if(/^-?\d+$/.test(a))l=Number.parseInt(a,10);else try{let d=new M,h=L(d,a);l=v(t,h.expression)}catch{let d=t.state.env[a];l=d?Number.parseInt(d,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let d=T(t,i);if(d.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
43
- `,"";let m=Math.max(...d.map(([E])=>typeof E=="number"?E:0))+1+l;return m<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
44
- `,""):t.state.env[`${i}_${m}`]||""}let f=t.state.env[`${i}_${l}`];if(f===void 0&&n&&t.state.options.nounset)throw new X(`${i}[${l}]`);return f||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&n&&t.state.options.nounset)throw new X(e);return i||""}let o=t.state.env[e];if(o===void 0&&n&&t.state.options.nounset)throw new X(e);return o||""}async function tn(t,e,n,r,s){let o=[];for(let f of e){let d=f.type==="ParameterExpansion"||f.type==="CommandSubstitution"||f.type==="ArithmeticExpansion";if(f.type==="ParameterExpansion"&&Wt(f)){let h=await s(t,f);o.push({value:h,splittable:!1})}else{let h=await s(t,f);o.push({value:h,splittable:d})}}if(!o.some(f=>f.splittable&&new RegExp(`[${r}]`).test(f.value))){let f=o.map(d=>d.value).join("");return f?[f]:[]}let a=new RegExp(`[${r}]+`),c=[],l="";for(let f=0;f<o.length;f++){let d=o[f];if(!d.splittable)l+=d.value;else{let h=d.value.split(a);for(let m=0;m<h.length;m++)m===0?l+=h[m]:(l!==""&&c.push(l),l=h[m])}}return l!==""&&c.push(l),c}function G(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rn(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function nn(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Mt(t){if(t==="")return"''";if(!/['\\\n\r\t\x00-\x1f\x7f]/.test(t))return`'${t}'`;let e="$'";for(let n of t)switch(n){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
45
- `:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=n.charCodeAt(0);r<32||r===127?e+=`\\x${r.toString(16).padStart(2,"0")}`:e+=n}}return`${e}'`}function ye(t,e,n=!1){return e.map(r=>re(t,r,n)).join("")}async function we(t,e,n=!1){let r=[];for(let s of e)r.push(await Z(t,s));return r.join("")}function Rs(t){return nn(t)}function sn(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!Rs(e))return!1;return!0}function on(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function an(t,e,n=!1){let r=rn(e);if(r!==null)return r;switch(e.type){case"ParameterExpansion":return dn(t,e,n);case"TildeExpansion":return n?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,n=!1){let r=an(t,e,n);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let s=[];for(let o of e.parts)s.push(re(t,o,!0));return s.join("")}case"ArithmeticExpansion":return String(v(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let o of e.items)if(o.type==="Range"){let i=De(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)s.push(...i.expanded);else return i.literal}else s.push(Je(t,o.word));return s.join(" ")}default:return""}}function Je(t,e){let n=e.parts,r=n.length;if(r===1)return re(t,n[0]);let s=[];for(let o=0;o<r;o++)s.push(re(t,n[o]));return s.join("")}async function P(t,e){return te(e)?un(t,e):Je(t,e)}function et(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&et(e.parts))return!0;return!1}function Ds(t){for(let e of t){if(e.type==="BraceExpansion"){for(let n of e.items)if(n.type==="Word"&&te(n.word))return!0}if(Xe(e))return!0}return!1}var cn=1e4,Ne=1e5;function ln(t,e,n={count:0}){if(n.count>Ne)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of s.items)if(f.type==="Range"){let d=De(f.start,f.end,f.step,f.startStr,f.endStr);if(d.expanded)for(let h of d.expanded)n.count++,o.push(h);else{i=!0,a=d.literal;break}}else{let d=ln(t,f.word.parts,n);for(let h of d)n.count++,o.push(h.join(""))}if(i){for(let f of r)n.count++,f.push(a);continue}if(r.length*o.length>cn||n.count>Ne)return r;let l=[];for(let f of r)for(let d of o){if(n.count++,n.count>Ne)return l.length>0?l:r;l.push([...f,d])}r=l}else{let o=re(t,s);for(let i of r)n.count++,i.push(o)}return r}function Os(t,e){let n=e.parts;return et(n)?ln(t,n).map(s=>s.join("")):[Je(t,e)]}async function fn(t,e,n={count:0}){if(n.count>Ne)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of s.items)if(f.type==="Range"){let d=De(f.start,f.end,f.step,f.startStr,f.endStr);if(d.expanded)for(let h of d.expanded)n.count++,o.push(h);else{i=!0,a=d.literal;break}}else{let d=await fn(t,f.word.parts,n);for(let h of d)n.count++,o.push(h.join(""))}if(i){for(let f of r)n.count++,f.push(a);continue}if(r.length*o.length>cn||n.count>Ne)return r;let l=[];for(let f of r)for(let d of o){if(n.count++,n.count>Ne)return l.length>0?l:r;l.push([...f,d])}r=l}else{let o=await Z(t,s);for(let i of r)n.count++,i.push(o)}return r}async function _s(t,e){let n=e.parts;return et(n)?(await fn(t,n)).map(s=>s.join("")):[await P(t,e)]}async function Te(t,e){let n=e.parts,{hasQuoted:r,hasCommandSub:s,hasArrayVar:o,hasArrayAtExpansion:i,hasParamExpansion:a}=Qr(n),l=et(n)?Ds(n)?await _s(t,e):Os(t,e):null;if(l&&l.length>1){let h=[];for(let m of l)if(!r&&/[*?[]/.test(m)){let E=await new be(t.fs,t.state.cwd).expand(m);E.length>0?h.push(...E):h.push(m)}else h.push(m);return{values:h,quoted:!1}}if(i&&n.length===1&&n[0].type==="DoubleQuoted"){let h=n[0];if(h.parts.length===1&&h.parts[0].type==="ParameterExpansion"){let y=h.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(y){let E=y[1],p=T(t,E);if(p.length>0)return{values:p.map(([,g])=>g),quoted:!0};let w=t.state.env[E];return w!==void 0?{values:[w],quoted:!0}:{values:[],quoted:!0}}}}if(n.length===1&&n[0].type==="DoubleQuoted"){let h=n[0],m=-1,y=!1;for(let E=0;E<h.parts.length;E++){let p=h.parts[E];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")){m=E,y=p.parameter==="*";break}}if(m!==-1){let E=h.parts[m];E.type==="ParameterExpansion"&&E.operation&&(m=-1)}if(m!==-1){let E=Number.parseInt(t.state.env["#"]||"0",10),p="";for(let C=0;C<m;C++)p+=await Z(t,h.parts[C]);let w="";for(let C=m+1;C<h.parts.length;C++)w+=await Z(t,h.parts[C]);if(E===0){if(y)return{values:[p+w],quoted:!0};let C=p+w;return{values:C?[C]:[],quoted:!0}}let g=[];for(let C=1;C<=E;C++)g.push(t.state.env[String(C)]||"");if(y){let C=Ce(t.state.env);return{values:[p+g.join(C)+w],quoted:!0}}return g.length===1?{values:[p+g[0]+w],quoted:!0}:{values:[p+g[0],...g.slice(1,-1),g[g.length-1]+w],quoted:!0}}}if((s||o||a)&&!Xr(t.state.env)){let h=Ye(t.state.env),m=Le(h),y=await tn(t,n,h,m,Z),E=[],p=new be(t.fs,t.state.cwd);for(let w of y)if(/[*?[]/.test(w)){let g=await p.expand(w);g.length>0?E.push(...g):E.push(w)}else E.push(w);return{values:E,quoted:!1}}let d=te(e)?await un(t,e):Je(t,e);if(!r&&/[*?[]/.test(d)){let m=await new be(t.fs,t.state.cwd).expand(d);if(m.length>0)return{values:m,quoted:!1}}return d===""&&!r?{values:[],quoted:!1}:{values:[d],quoted:r}}async function un(t,e){let n=e.parts,r=n.length;if(r===1)return Z(t,n[0]);let s=[];for(let o=0;o<r;o++)s.push(await Z(t,n[o]));return s.join("")}async function Z(t,e){if(e.type==="ParameterExpansion"&&Tt(e))return Ls(t,e);let n=an(t,e);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let r=[];for(let s of e.parts)r.push(await Z(t,s));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 s of e.items)if(s.type==="Range"){let o=De(s.start,s.end,s.step,s.startStr,s.endStr);if(o.expanded)r.push(...o.expanded);else return o.literal}else r.push(await P(t,s.word));return r.join(" ")}default:return""}}function dn(t,e,n=!1){let{parameter:r,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=q(t,r,!o);if(!s)return i;let a=!(r in t.state.env),c=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?ye(t,s.word.parts,n):i;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let f=ye(t,s.word.parts,n),d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let[,h,m]=d,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new M,w=L(p,m);y=v(t,w.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${h}_${y}`]=f;let E=Number.parseInt(t.state.env[`${h}__length`]||"0",10);y>=E&&(t.state.env[`${h}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let f=s.word?ye(t,s.word.parts,n):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
46
- `)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?ye(t,s.word.parts,n):"";case"Length":{let l=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let f=T(t,l[1]);return String(f.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&en(t,r)){let f=t.state.env[`${r}_0`]||"";return String(f.length)}return String(i.length)}case"LengthSliceError":throw new me(r);case"Substring":{let l=s.offset?v(t,s.offset.expression):0,f=s.length?v(t,s.length.expression):void 0;if(r==="@"||r==="*"){let y=(t.state.env["@"]||"").split(" ").filter(g=>g),E=t.state.env[0]||"bash",p=l===0?[E,...y]:y,w=l===0?0:l-1;if(w<0||w>=p.length)return"";if(f!==void 0){let g=f<0?p.length+f:w+f;return p.slice(w,Math.max(w,g)).join(" ")}return p.slice(w).join(" ")}let d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let E=T(t,d[1]).map(([,w])=>w),p=l;if(p<0&&(p=E.length+p,p<0))return"";if(f!==void 0){if(f<0){let w=E.length+f;return E.slice(p,Math.max(p,w)).join(" ")}return E.slice(p,p+f).join(" ")}return E.slice(p).join(" ")}let h=[...i],m=l;if(m<0&&(m=Math.max(0,h.length+m)),f!==void 0){if(f<0){let y=h.length+f;return h.slice(m,Math.max(m,y)).join("")}return h.slice(m,m+f).join("")}return h.slice(m).join("")}case"PatternRemoval":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=j(d.pattern,s.greedy);else if(d.type==="Literal")l+=j(d.value,s.greedy);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=G(d.value);else if(d.type==="DoubleQuoted"){let h=ye(t,d.parts);l+=G(h)}else if(d.type==="ParameterExpansion"){let h=re(t,d);l+=j(h,s.greedy)}else{let h=re(t,d);l+=G(h)}if(s.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let f=new RegExp(`${l}$`);if(s.greedy)return i.replace(f,"");for(let d=i.length;d>=0;d--){let h=i.slice(d);if(f.test(h))return i.slice(0,d)}return i}case"PatternReplacement":{let l="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")l+=j(h.pattern,!0);else if(h.type==="Literal")l+=j(h.value,!0);else if(h.type==="SingleQuoted"||h.type==="Escaped")l+=G(h.value);else if(h.type==="DoubleQuoted"){let m=ye(t,h.parts);l+=G(m)}else if(h.type==="ParameterExpansion"){let m=re(t,h);l+=j(m,!0)}else{let m=re(t,h);l+=G(m)}let f=s.replacement?ye(t,s.replacement.parts):"";if(l==="")return i;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let d=s.all?"g":"";try{let h=new RegExp(l,d);if(s.all){let m="",y=0,E=h.exec(i);for(;E!==null&&!(E[0].length===0&&E.index===i.length);)m+=i.slice(y,E.index)+f,y=E.index+E[0].length,E[0].length===0&&y++,E=h.exec(i);return m+=i.slice(y),m}return i.replace(h,f)}catch{return i}}case"CaseModification":return s.direction==="upper"?s.all?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):s.all?i.toLowerCase():i.charAt(0).toLowerCase()+i.slice(1);case"Transform":{let l=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l&&s.operator==="Q")return T(t,l[1]).map(([,h])=>Mt(h)).join(" ");switch(s.operator){case"Q":return Mt(i);case"P":return i;case"a":return"";case"A":return`${r}=${Mt(i)}`;case"E":return i.replace(/\\([\\abefnrtv'"?])/g,(f,d)=>{switch(d){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
47
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return d}});case"K":return"";default:return i}}case"Indirection":return q(t,i);case"ArrayKeys":{let f=T(t,s.array).map(([d])=>String(d));return s.star?f.join(Ce(t.state.env)):f.join(" ")}case"VarNamePrefix":{let l=Object.keys(t.state.env).filter(f=>f.startsWith(s.prefix)&&!f.includes("__")).sort();return s.star?l.join(Ce(t.state.env)):l.join(" ")}default:return i}}async function Ls(t,e,n=!1){let{parameter:r,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=q(t,r,!o);if(!s)return i;let a=!(r in t.state.env),c=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?we(t,s.word.parts,n):i;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let f=await we(t,s.word.parts,n),d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let[,h,m]=d,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new M,w=L(p,m);y=await $(t,w.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${h}_${y}`]=f;let E=Number.parseInt(t.state.env[`${h}__length`]||"0",10);y>=E&&(t.state.env[`${h}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let f=s.word?await we(t,s.word.parts,n):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
48
- `)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?we(t,s.word.parts,n):"";case"PatternRemoval":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=j(d.pattern,s.greedy);else if(d.type==="Literal")l+=j(d.value,s.greedy);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=G(d.value);else if(d.type==="DoubleQuoted"){let h=await we(t,d.parts);l+=G(h)}else if(d.type==="ParameterExpansion"){let h=await Z(t,d);l+=j(h,s.greedy)}else{let h=await Z(t,d);l+=G(h)}if(s.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let f=new RegExp(`${l}$`);if(s.greedy)return i.replace(f,"");for(let d=i.length;d>=0;d--){let h=i.slice(d);if(f.test(h))return i.slice(0,d)}return i}case"PatternReplacement":{let l="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")l+=j(h.pattern,!0);else if(h.type==="Literal")l+=j(h.value,!0);else if(h.type==="SingleQuoted"||h.type==="Escaped")l+=G(h.value);else if(h.type==="DoubleQuoted"){let m=await we(t,h.parts);l+=G(m)}else if(h.type==="ParameterExpansion"){let m=await Z(t,h);l+=j(m,!0)}else{let m=await Z(t,h);l+=G(m)}let f=s.replacement?await we(t,s.replacement.parts):"";if(l==="")return i;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let d=s.all?"g":"";try{let h=new RegExp(l,d);if(s.all){let m="",y=0,E=h.exec(i);for(;E!==null&&!(E[0].length===0&&E.index===i.length);)m+=i.slice(y,E.index)+f,y=E.index+E[0].length,E[0].length===0&&y++,E=h.exec(i);return m+=i.slice(y),m}return i.replace(h,f)}catch{return i}}default:return dn(t,e,n)}}function Bt(t,e,n){switch(n){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 hn(t,e,n){switch(n){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 zt(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function Ts(t,e){let n=t.state.env[e];if(n!==void 0)return n;let r=t.state.env[`${e}_0`];return r!==void 0?r:q(t,e)}function ve(t){if(!t)return 0;let e=Number.parseInt(t,10);if(!Number.isNaN(e)&&/^-?\d+$/.test(t.trim()))return e;let n=t.trim();if(!n)return 0;try{let r=new M,{expr:s,pos:o}=J(r,n,0);if(o<n.length){let i=n.slice(o).trim().split(/\s+/)[0];throw new W(`${n}: syntax error in expression (error token is "${i}")`)}return s.type==="ArithNumber"?s.value:e||0}catch(r){if(r instanceof W)throw r;let s=n.split(/\s+/).slice(1)[0]||n;throw new W(`${n}: syntax error in expression (error token is "${s}")`)}}function tt(t,e,n=new Set){if(n.has(e))return 0;n.add(e);let r=Ts(t,e);if(!r)return 0;let s=Number.parseInt(r,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(r.trim()))return s;let o=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return tt(t,o,n);try{let i=new M,{expr:a}=J(i,o,0);return Q(t,a,n)}catch{return 0}}function Q(t,e,n){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return tt(t,e.name,n);case"ArithBinary":{if(e.operator==="||")return Q(t,e.left,n)||Q(t,e.right,n)?1:0;if(e.operator==="&&")return Q(t,e.left,n)&&Q(t,e.right,n)?1:0;let r=Q(t,e.left,n),s=Q(t,e.right,n);return Bt(r,s,e.operator)}case"ArithUnary":{let r=Q(t,e.operand,n);return zt(r,e.operator)}case"ArithTernary":return Q(t,e.condition,n)?Q(t,e.consequent,n):Q(t,e.alternate,n);case"ArithGroup":return Q(t,e.expression,n);default:return v(t,e)}}function le(t,e){if(e.startsWith("#")){let d=e.slice(1),h=t.state.env[d]||"";return String(h.length)}if(e.startsWith("!")){let d=e.slice(1),h=t.state.env[d]||"";return t.state.env[h]||""}let n=[":-",":=",":?",":+","-","=","?","+"],r=-1,s="";for(let d of n){let h=e.indexOf(d);h>0&&(r===-1||h<r)&&(r=h,s=d)}if(r===-1)return q(t,e);let o=e.slice(0,r),i=e.slice(r+s.length),a=t.state.env[o],c=a===void 0,l=a==="",f=s.startsWith(":");switch(s){case":-":case"-":return c||f&&l?i:a||"";case":=":case"=":return c||f&&l?(t.state.env[o]=i,i):a||"";case":+":case"+":return!(c||f&&l)?i:"";case":?":case"?":{if(c||f&&l)throw new Error(i||`${o}: parameter null or not set`);return a||""}default:return a||""}}function v(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 tt(t,e.name);case"ArithNested":return v(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let n=le(t,e.content);return Number.parseInt(n,10)||0}case"ArithDynamicBase":{let n=le(t,e.baseExpr),r=Number.parseInt(n,10);if(r<2||r>64)return 0;let s=`${r}#${e.value}`;return xe(s)}case"ArithDynamicNumber":{let r=le(t,e.prefix)+e.suffix;return xe(r)}case"ArithArrayElement":{let n=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(n&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let o=v(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
49
- `,0;let l=Math.max(...a.map(([f])=>typeof f=="number"?f:0))+1+o;if(l<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
50
- `,0;o=l}r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return ve(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return ve(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new X(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?ve(s):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 v(t,e.left)||v(t,e.right)?1:0;if(e.operator==="&&")return v(t,e.left)&&v(t,e.right)?1:0;let n=v(t,e.left),r=v(t,e.right);return Bt(n,r,e.operator)}case"ArithUnary":{let n=v(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,s=Number.parseInt(q(t,r),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let c=v(t,e.operand.index);o=`${r}_${c}`}else return n;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 n}return zt(n,e.operator)}case"ArithTernary":return v(t,e.condition)?v(t,e.consequent):v(t,e.alternate);case"ArithAssignment":{let n=e.variable,r=n;if(e.stringKey!==void 0)r=`${n}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(n);if(a&&e.subscript.type==="ArithVariable")r=`${n}_${e.subscript.name}`;else if(a){let c=v(t,e.subscript);r=`${n}_${c}`}else{let c=v(t,e.subscript);if(c<0){let l=T(t,n);l.length>0&&(c=Math.max(...l.map(([d])=>typeof d=="number"?d:0))+1+c)}r=`${n}_${c}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,o=v(t,e.value),i=hn(s,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return v(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=mn(t,r);return Number.parseInt(n,10)||0}default:return 0}}function mn(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return q(t,e.name);case"ArithBracedExpansion":return le(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let n="";for(let r of e.parts)n+=mn(t,r);return n}default:return String(v(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 tt(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 n=le(t,e.content);return Number.parseInt(n,10)||0}case"ArithDynamicBase":{let n=le(t,e.baseExpr),r=Number.parseInt(n,10);if(r<2||r>64)return 0;let s=`${r}#${e.value}`;return xe(s)}case"ArithDynamicNumber":{let r=le(t,e.prefix)+e.suffix;return xe(r)}case"ArithArrayElement":{let n=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(n&&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 ve(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return ve(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new X(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?ve(s):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 n=await $(t,e.left),r=await $(t,e.right);return Bt(n,r,e.operator)}case"ArithUnary":{let n=await $(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,s=Number.parseInt(q(t,r),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let c=await $(t,e.operand.index);o=`${r}_${c}`}else return n;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 n}return zt(n,e.operator)}case"ArithTernary":return await $(t,e.condition)?await $(t,e.consequent):await $(t,e.alternate);case"ArithAssignment":{let n=e.variable,r=n;if(e.stringKey!==void 0)r=`${n}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(n);if(a&&e.subscript.type==="ArithVariable")r=`${n}_${e.subscript.name}`;else if(a){let c=await $(t,e.subscript);r=`${n}_${c}`}else{let c=await $(t,e.subscript);if(c<0){let l=T(t,n);l.length>0&&(c=Math.max(...l.map(([d])=>typeof d=="number"?d:0))+1+c)}r=`${n}_${c}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,o=await $(t,e.value),i=hn(s,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return await $(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=await pn(t,r);return Number.parseInt(n,10)||0}default:return 0}}async function pn(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return q(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 n="";for(let r of e.parts)n+=await pn(t,r);return n}default:return String(await $(t,e))}}var N=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,n){return{stdout:t,stderr:e,exitCode:n}}function O(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function ne(t,e,n="",r=""){throw new B(t,e,n,r)}function Ut(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ie;return N}let n=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
51
- `);n=r}throw new z(n)}async function jt(t,e){let n,r=!1,s=!1,o=0;for(;o<e.length;)if(e[o]==="--"){o++;break}else if(e[o]==="-L")s=!1,o++;else if(e[o]==="-P")s=!0,o++;else if(e[o].startsWith("-")&&e[o]!=="-")o++;else break;let i=e.slice(o);if(i.length===0||i[0]==="~"?n=t.state.env.HOME||"/":i[0]==="-"?(n=t.state.previousDir,r=!0):n=i[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let d=t.state.env.CDPATH;if(d){let h=d.split(":").filter(m=>m);for(let m of h){let y=m.startsWith("/")?`${m}/${n}`:`${t.state.cwd}/${m}/${n}`;try{if((await t.fs.stat(y)).isDirectory){n=y,r=!0;break}}catch{}}}}let c=(n.startsWith("/")?n:`${t.state.cwd}/${n}`).split("/").filter(d=>d&&d!=="."),l="";for(let d of c)if(d==="..")l=l.split("/").slice(0,-1).join("/")||"/";else{l=l?`${l}/${d}`:`/${d}`;try{if(!(await t.fs.stat(l)).isDirectory)return S(`bash: cd: ${n}: Not a directory
52
- `)}catch{return S(`bash: cd: ${n}: No such file or directory
53
- `)}}let f=l||"/";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}
54
- `:"")}function Gt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ie;return N}if(e.length>1)throw new z(1);let n=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
55
- `);n=r}throw new K(n)}function Ee(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function Ws(t,e){return t.state.readonlyVars?.has(e)??!1}function fe(t,e,n="bash"){return Ws(t,e)?S(`${n}: ${e}: readonly variable
56
- `):null}function yn(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:Ht(e[2])};if(t.includes("=")){let n=t.indexOf("=");return{name:t.slice(0,n),isArray:!1,value:t.slice(n+1)}}return{name:t,isArray:!1}}function wn(t,e,n={}){let{name:r,isArray:s,arrayElements:o,value:i}=e,{makeReadonly:a=!1,checkReadonly:c=!0}=n;if(c){let l=fe(t,r);if(l)return l}if(s&&o){for(let l=0;l<o.length;l++)t.state.env[`${r}_${l}`]=o[l];t.state.env[`${r}__length`]=String(o.length)}else i!==void 0&&(t.state.env[r]=i);return a&&Ee(t,r),null}function Vt(t,e){let n=!1,r=!1,s=!1,o=!1,i=!1,a=[];for(let c=0;c<e.length;c++){let l=e[c];if(l==="-a")n=!0;else if(l==="-A")r=!0;else if(l==="-r")s=!0;else if(l==="-x")o=!0;else if(l==="-p")i=!0;else if(l==="--"){a.push(...e.slice(c+1));break}else if(l.startsWith("-"))for(let f of l.slice(1))f==="a"?n=!0:f==="A"?r=!0:f==="r"?s=!0:f==="x"?o=!0:f==="p"&&(i=!0);else a.push(l)}if(i&&a.length>0){let c="";for(let l of a){let f=t.state.env[l];if(f!==void 0){let d=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"');c+=`declare -- ${l}="${d}"
57
- `}}return H(c)}if(a.length===0&&!i){let c="",l=Object.entries(t.state.env).filter(([f])=>!f.startsWith("BASH_")).sort(([f],[d])=>f.localeCompare(d));for(let[f,d]of l){let h=d.replace(/'/g,"'\\''");c+=`declare -- ${f}='${h}'
58
- `}return H(c)}for(let c of a){let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){let f=l[1],d=l[2];if(r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f)),r&&d.includes("[")){let h=Fs(d);for(let[m,y]of h)t.state.env[`${f}_${m}`]=y}else{let h=Ht(d);for(let m=0;m<h.length;m++)t.state.env[`${f}_${m}`]=h[m];t.state.env[`${f}__length`]=String(h.length)}s&&Ee(t,f);continue}if(c.includes("=")){let f=c.indexOf("="),d=c.slice(0,f),h=c.slice(f+1),m=fe(t,d);if(m)return m;t.state.env[d]=h,s&&Ee(t,d)}else{let f=c;r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f));let d=Object.keys(t.state.env).some(h=>h.startsWith(`${f}_`)&&!h.startsWith(`${f}__length`));!(f in t.state.env)&&!d&&(n||r?t.state.env[`${f}__length`]="0":t.state.env[f]=""),s&&Ee(t,f)}}return N}function Ht(t){let e=[],n="",r=!1,s=!1,o=!1;for(let i of t){if(o){n+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(i==="'"&&!s){r=!r;continue}if(i==='"'&&!r){s=!s;continue}if((i===" "||i===" "||i===`
59
- `)&&!r&&!s){n&&(e.push(n),n="");continue}n+=i}return n&&e.push(n),e}function Fs(t){let e=[],n=0;for(;n<t.length;){for(;n<t.length&&/\s/.test(t[n]);)n++;if(n>=t.length)break;if(t[n]!=="["){n++;continue}n++;let r="";if(t[n]==="'"||t[n]==='"'){let o=t[n];for(n++;n<t.length&&t[n]!==o;)r+=t[n],n++;t[n]===o&&n++}else for(;n<t.length&&t[n]!=="]"&&t[n]!=="=";)r+=t[n],n++;for(;n<t.length&&t[n]!=="]";)n++;if(t[n]==="]"&&n++,t[n]!=="=")continue;n++;let s="";if(t[n]==="'"||t[n]==='"'){let o=t[n];for(n++;n<t.length&&t[n]!==o;)t[n]==="\\"&&n+1<t.length&&n++,s+=t[n],n++;t[n]===o&&n++}else for(;n<t.length&&!/\s/.test(t[n]);)s+=t[n],n++;e.push([r,s])}return e}function qt(t,e){let n=!1,r=!1,s=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="-a")n=!0;else if(i==="-A")r=!0;else if(i==="-p"){if(e.length===1){let a="";for(let c of t.state.readonlyVars||[]){let l=t.state.env[c];l!==void 0&&(a+=`declare -r ${c}="${l}"
60
- `)}return H(a)}}else if(i==="--"){s.push(...e.slice(o+1));break}else i.startsWith("-")||s.push(i)}for(let o of s){let i=yn(o);if(i.value===void 0&&!i.isArray){Ee(t,i.name);continue}let a=wn(t,i,{makeReadonly:!0});if(a)return a}return N}async function Zt(t,e){let n=e;if(n.length>0){let s=n[0];if(s==="--")n=n.slice(1);else if(s.startsWith("-")&&s!=="-"&&s.length>1)return S(`bash: eval: ${s}: invalid option
42
+ `?"\\n":e).join("")}function Ps(t,e){let n=Le(t);return new RegExp(`[${n}]+`,e)}function Is(t){let e=Le(t);return new RegExp(`^[${e}]+`)}function ks(t){let e=Le(t);return new RegExp(`[${e}]+$`)}function Ce(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function Yr(t,e){if(e==="")return{words:[t],wordStarts:[0]};let n=[],r=[],s=Ps(e,"g"),o=0,i=t.match(Is(e));i&&(o=i[0].length),s.lastIndex=o;let a=s.exec(t);for(;a!==null;)a.index>o&&(r.push(o),n.push(t.substring(o,a.index))),o=s.lastIndex,a=s.exec(t);return o<t.length&&(r.push(o),n.push(t.substring(o))),{words:n,wordStarts:r}}function Jr(t,e){return e===""?t:t.replace(ks(e),"")}function T(t,e){return t.state.associativeArrays?.has(e)?Ft(t,e).map(o=>[o,t.state.env[`${e}_${o}`]]):Oe(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function en(t,e){return t.state.associativeArrays?.has(e)?Ft(t,e).length>0:Oe(t,e).length>0}function q(t,e,n=!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(Ce(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:"";case"PPID":{let{ppid:i}=Re();return String(i)}case"UID":{let{uid:i}=Re();return String(i)}case"EUID":return String(process.geteuid?.()??Re().uid);case"RANDOM":return String(Math.floor(Math.random()*32768));case"SECONDS":return String(Math.floor((Date.now()-t.state.startTime)/1e3));case"BASH_VERSION":return gr;case"!":return String(t.state.lastBackgroundPid);case"LINENO":return String(t.state.currentLine)}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(e))throw new me(`\${${e}}`);let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let i=s[1],a=s[2];if(a==="@"||a==="*"){let d=T(t,i);if(d.length>0)return d.map(([,m])=>m).join(" ");let h=t.state.env[i];return h!==void 0?h:""}if(t.state.associativeArrays?.has(i)){let d=Kr(a),h=t.state.env[`${i}_${d}`];if(h===void 0&&n&&t.state.options.nounset)throw new X(`${i}[${a}]`);return h||""}let c;if(/^-?\d+$/.test(a))c=Number.parseInt(a,10);else try{let d=new M,h=L(d,a);c=v(t,h.expression)}catch{let d=t.state.env[a];c=d?Number.parseInt(d,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let d=T(t,i);if(d.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
43
+ `,"";let m=Math.max(...d.map(([E])=>typeof E=="number"?E:0))+1+c;return m<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
44
+ `,""):t.state.env[`${i}_${m}`]||""}let f=t.state.env[`${i}_${c}`];if(f===void 0&&n&&t.state.options.nounset)throw new X(`${i}[${c}]`);return f||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&n&&t.state.options.nounset)throw new X(e);return i||""}let o=t.state.env[e];if(o===void 0&&n&&t.state.options.nounset)throw new X(e);return o||""}async function tn(t,e,n,r,s){let o=[];for(let f of e){let d=f.type==="ParameterExpansion"||f.type==="CommandSubstitution"||f.type==="ArithmeticExpansion";if(f.type==="ParameterExpansion"&&Wt(f)){let h=await s(t,f);o.push({value:h,splittable:!1})}else{let h=await s(t,f);o.push({value:h,splittable:d})}}if(!o.some(f=>f.splittable&&new RegExp(`[${r}]`).test(f.value))){let f=o.map(d=>d.value).join("");return f?[f]:[]}let a=new RegExp(`[${r}]+`),l=[],c="";for(let f=0;f<o.length;f++){let d=o[f];if(!d.splittable)c+=d.value;else{let h=d.value.split(a);for(let m=0;m<h.length;m++)m===0?c+=h[m]:(c!==""&&l.push(c),c=h[m])}}return c!==""&&l.push(c),l}function G(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rn(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function nn(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Mt(t){if(t==="")return"''";if(!/['\\\n\r\t\x00-\x1f\x7f]/.test(t))return`'${t}'`;let e="$'";for(let n of t)switch(n){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
45
+ `:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=n.charCodeAt(0);r<32||r===127?e+=`\\x${r.toString(16).padStart(2,"0")}`:e+=n}}return`${e}'`}function ye(t,e,n=!1){return e.map(r=>re(t,r,n)).join("")}async function we(t,e,n=!1){let r=[];for(let s of e)r.push(await Z(t,s));return r.join("")}function Rs(t){return nn(t)}function sn(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!Rs(e))return!1;return!0}function on(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function an(t,e,n=!1){let r=rn(e);if(r!==null)return r;switch(e.type){case"ParameterExpansion":return dn(t,e,n);case"TildeExpansion":return n?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,n=!1){let r=an(t,e,n);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let s=[];for(let o of e.parts)s.push(re(t,o,!0));return s.join("")}case"ArithmeticExpansion":return String(v(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let o of e.items)if(o.type==="Range"){let i=De(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)s.push(...i.expanded);else return i.literal}else s.push(Je(t,o.word));return s.join(" ")}default:return""}}function Je(t,e){let n=e.parts,r=n.length;if(r===1)return re(t,n[0]);let s=[];for(let o=0;o<r;o++)s.push(re(t,n[o]));return s.join("")}async function P(t,e){return te(e)?un(t,e):Je(t,e)}function et(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&et(e.parts))return!0;return!1}function Ds(t){for(let e of t){if(e.type==="BraceExpansion"){for(let n of e.items)if(n.type==="Word"&&te(n.word))return!0}if(Xe(e))return!0}return!1}var cn=1e4,Ne=1e5;function ln(t,e,n={count:0}){if(n.count>Ne)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of s.items)if(f.type==="Range"){let d=De(f.start,f.end,f.step,f.startStr,f.endStr);if(d.expanded)for(let h of d.expanded)n.count++,o.push(h);else{i=!0,a=d.literal;break}}else{let d=ln(t,f.word.parts,n);for(let h of d)n.count++,o.push(h.join(""))}if(i){for(let f of r)n.count++,f.push(a);continue}if(r.length*o.length>cn||n.count>Ne)return r;let c=[];for(let f of r)for(let d of o){if(n.count++,n.count>Ne)return c.length>0?c:r;c.push([...f,d])}r=c}else{let o=re(t,s);for(let i of r)n.count++,i.push(o)}return r}function Os(t,e){let n=e.parts;return et(n)?ln(t,n).map(s=>s.join("")):[Je(t,e)]}async function fn(t,e,n={count:0}){if(n.count>Ne)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of s.items)if(f.type==="Range"){let d=De(f.start,f.end,f.step,f.startStr,f.endStr);if(d.expanded)for(let h of d.expanded)n.count++,o.push(h);else{i=!0,a=d.literal;break}}else{let d=await fn(t,f.word.parts,n);for(let h of d)n.count++,o.push(h.join(""))}if(i){for(let f of r)n.count++,f.push(a);continue}if(r.length*o.length>cn||n.count>Ne)return r;let c=[];for(let f of r)for(let d of o){if(n.count++,n.count>Ne)return c.length>0?c:r;c.push([...f,d])}r=c}else{let o=await Z(t,s);for(let i of r)n.count++,i.push(o)}return r}async function _s(t,e){let n=e.parts;return et(n)?(await fn(t,n)).map(s=>s.join("")):[await P(t,e)]}async function Te(t,e){let n=e.parts,{hasQuoted:r,hasCommandSub:s,hasArrayVar:o,hasArrayAtExpansion:i,hasParamExpansion:a}=Qr(n),c=et(n)?Ds(n)?await _s(t,e):Os(t,e):null;if(c&&c.length>1){let h=[];for(let m of c)if(!r&&/[*?[]/.test(m)){let E=await new be(t.fs,t.state.cwd).expand(m);E.length>0?h.push(...E):h.push(m)}else h.push(m);return{values:h,quoted:!1}}if(i&&n.length===1&&n[0].type==="DoubleQuoted"){let h=n[0];if(h.parts.length===1&&h.parts[0].type==="ParameterExpansion"){let y=h.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(y){let E=y[1],p=T(t,E);if(p.length>0)return{values:p.map(([,g])=>g),quoted:!0};let w=t.state.env[E];return w!==void 0?{values:[w],quoted:!0}:{values:[],quoted:!0}}}}if(n.length===1&&n[0].type==="DoubleQuoted"){let h=n[0],m=-1,y=!1;for(let E=0;E<h.parts.length;E++){let p=h.parts[E];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")){m=E,y=p.parameter==="*";break}}if(m!==-1){let E=h.parts[m];E.type==="ParameterExpansion"&&E.operation&&(m=-1)}if(m!==-1){let E=Number.parseInt(t.state.env["#"]||"0",10),p="";for(let C=0;C<m;C++)p+=await Z(t,h.parts[C]);let w="";for(let C=m+1;C<h.parts.length;C++)w+=await Z(t,h.parts[C]);if(E===0){if(y)return{values:[p+w],quoted:!0};let C=p+w;return{values:C?[C]:[],quoted:!0}}let g=[];for(let C=1;C<=E;C++)g.push(t.state.env[String(C)]||"");if(y){let C=Ce(t.state.env);return{values:[p+g.join(C)+w],quoted:!0}}return g.length===1?{values:[p+g[0]+w],quoted:!0}:{values:[p+g[0],...g.slice(1,-1),g[g.length-1]+w],quoted:!0}}}if((s||o||a)&&!Xr(t.state.env)){let h=Ye(t.state.env),m=Le(h),y=await tn(t,n,h,m,Z),E=[],p=new be(t.fs,t.state.cwd);for(let w of y)if(/[*?[]/.test(w)){let g=await p.expand(w);g.length>0?E.push(...g):E.push(w)}else E.push(w);return{values:E,quoted:!1}}let d=te(e)?await un(t,e):Je(t,e);if(!r&&/[*?[]/.test(d)){let m=await new be(t.fs,t.state.cwd).expand(d);if(m.length>0)return{values:m,quoted:!1}}return d===""&&!r?{values:[],quoted:!1}:{values:[d],quoted:r}}async function un(t,e){let n=e.parts,r=n.length;if(r===1)return Z(t,n[0]);let s=[];for(let o=0;o<r;o++)s.push(await Z(t,n[o]));return s.join("")}async function Z(t,e){if(e.type==="ParameterExpansion"&&Tt(e))return Ls(t,e);let n=an(t,e);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let r=[];for(let s of e.parts)r.push(await Z(t,s));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 s of e.items)if(s.type==="Range"){let o=De(s.start,s.end,s.step,s.startStr,s.endStr);if(o.expanded)r.push(...o.expanded);else return o.literal}else r.push(await P(t,s.word));return r.join(" ")}default:return""}}function dn(t,e,n=!1){let{parameter:r,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=q(t,r,!o);if(!s)return i;let a=!(r in t.state.env),l=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&l)&&s.word?ye(t,s.word.parts,n):i;case"AssignDefault":{if((a||s.checkEmpty&&l)&&s.word){let f=ye(t,s.word.parts,n),d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let[,h,m]=d,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new M,w=L(p,m);y=v(t,w.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${h}_${y}`]=f;let E=Number.parseInt(t.state.env[`${h}__length`]||"0",10);y>=E&&(t.state.env[`${h}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&l){let f=s.word?ye(t,s.word.parts,n):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
46
+ `)}return i}case"UseAlternative":return!(a||s.checkEmpty&&l)&&s.word?ye(t,s.word.parts,n):"";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)&&en(t,r)){let f=t.state.env[`${r}_0`]||"";return String(f.length)}return String(i.length)}case"LengthSliceError":throw new me(r);case"Substring":{let c=s.offset?v(t,s.offset.expression):0,f=s.length?v(t,s.length.expression):void 0;if(r==="@"||r==="*"){let y=(t.state.env["@"]||"").split(" ").filter(g=>g),E=t.state.env[0]||"bash",p=c===0?[E,...y]:y,w=c===0?0:c-1;if(w<0||w>=p.length)return"";if(f!==void 0){let g=f<0?p.length+f:w+f;return p.slice(w,Math.max(w,g)).join(" ")}return p.slice(w).join(" ")}let d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let E=T(t,d[1]).map(([,w])=>w),p=c;if(p<0&&(p=E.length+p,p<0))return"";if(f!==void 0){if(f<0){let w=E.length+f;return E.slice(p,Math.max(p,w)).join(" ")}return E.slice(p,p+f).join(" ")}return E.slice(p).join(" ")}let h=[...i],m=c;if(m<0&&(m=Math.max(0,h.length+m)),f!==void 0){if(f<0){let y=h.length+f;return h.slice(m,Math.max(m,y)).join("")}return h.slice(m,m+f).join("")}return h.slice(m).join("")}case"PatternRemoval":{let c="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")c+=j(d.pattern,s.greedy);else if(d.type==="Literal")c+=j(d.value,s.greedy);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=G(d.value);else if(d.type==="DoubleQuoted"){let h=ye(t,d.parts);c+=G(h)}else if(d.type==="ParameterExpansion"){let h=re(t,d);c+=j(h,s.greedy)}else{let h=re(t,d);c+=G(h)}if(s.side==="prefix")return i.replace(new RegExp(`^${c}`),"");let f=new RegExp(`${c}$`);if(s.greedy)return i.replace(f,"");for(let d=i.length;d>=0;d--){let h=i.slice(d);if(f.test(h))return i.slice(0,d)}return i}case"PatternReplacement":{let c="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")c+=j(h.pattern,!0);else if(h.type==="Literal")c+=j(h.value,!0);else if(h.type==="SingleQuoted"||h.type==="Escaped")c+=G(h.value);else if(h.type==="DoubleQuoted"){let m=ye(t,h.parts);c+=G(m)}else if(h.type==="ParameterExpansion"){let m=re(t,h);c+=j(m,!0)}else{let m=re(t,h);c+=G(m)}let f=s.replacement?ye(t,s.replacement.parts):"";if(c==="")return i;s.anchor==="start"?c=`^${c}`:s.anchor==="end"&&(c=`${c}$`);let d=s.all?"g":"";try{let h=new RegExp(c,d);if(s.all){let m="",y=0,E=h.exec(i);for(;E!==null&&!(E[0].length===0&&E.index===i.length);)m+=i.slice(y,E.index)+f,y=E.index+E[0].length,E[0].length===0&&y++,E=h.exec(i);return m+=i.slice(y),m}return i.replace(h,f)}catch{return i}}case"CaseModification":return s.direction==="upper"?s.all?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):s.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&&s.operator==="Q")return T(t,c[1]).map(([,h])=>Mt(h)).join(" ");switch(s.operator){case"Q":return Mt(i);case"P":return i;case"a":return"";case"A":return`${r}=${Mt(i)}`;case"E":return i.replace(/\\([\\abefnrtv'"?])/g,(f,d)=>{switch(d){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
47
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return d}});case"K":return"";default:return i}}case"Indirection":return q(t,i);case"ArrayKeys":{let f=T(t,s.array).map(([d])=>String(d));return s.star?f.join(Ce(t.state.env)):f.join(" ")}case"VarNamePrefix":{let c=Object.keys(t.state.env).filter(f=>f.startsWith(s.prefix)&&!f.includes("__")).sort();return s.star?c.join(Ce(t.state.env)):c.join(" ")}default:return i}}async function Ls(t,e,n=!1){let{parameter:r,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=q(t,r,!o);if(!s)return i;let a=!(r in t.state.env),l=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&l)&&s.word?we(t,s.word.parts,n):i;case"AssignDefault":{if((a||s.checkEmpty&&l)&&s.word){let f=await we(t,s.word.parts,n),d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let[,h,m]=d,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new M,w=L(p,m);y=await $(t,w.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${h}_${y}`]=f;let E=Number.parseInt(t.state.env[`${h}__length`]||"0",10);y>=E&&(t.state.env[`${h}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&l){let f=s.word?await we(t,s.word.parts,n):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
48
+ `)}return i}case"UseAlternative":return!(a||s.checkEmpty&&l)&&s.word?we(t,s.word.parts,n):"";case"PatternRemoval":{let c="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")c+=j(d.pattern,s.greedy);else if(d.type==="Literal")c+=j(d.value,s.greedy);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=G(d.value);else if(d.type==="DoubleQuoted"){let h=await we(t,d.parts);c+=G(h)}else if(d.type==="ParameterExpansion"){let h=await Z(t,d);c+=j(h,s.greedy)}else{let h=await Z(t,d);c+=G(h)}if(s.side==="prefix")return i.replace(new RegExp(`^${c}`),"");let f=new RegExp(`${c}$`);if(s.greedy)return i.replace(f,"");for(let d=i.length;d>=0;d--){let h=i.slice(d);if(f.test(h))return i.slice(0,d)}return i}case"PatternReplacement":{let c="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")c+=j(h.pattern,!0);else if(h.type==="Literal")c+=j(h.value,!0);else if(h.type==="SingleQuoted"||h.type==="Escaped")c+=G(h.value);else if(h.type==="DoubleQuoted"){let m=await we(t,h.parts);c+=G(m)}else if(h.type==="ParameterExpansion"){let m=await Z(t,h);c+=j(m,!0)}else{let m=await Z(t,h);c+=G(m)}let f=s.replacement?await we(t,s.replacement.parts):"";if(c==="")return i;s.anchor==="start"?c=`^${c}`:s.anchor==="end"&&(c=`${c}$`);let d=s.all?"g":"";try{let h=new RegExp(c,d);if(s.all){let m="",y=0,E=h.exec(i);for(;E!==null&&!(E[0].length===0&&E.index===i.length);)m+=i.slice(y,E.index)+f,y=E.index+E[0].length,E[0].length===0&&y++,E=h.exec(i);return m+=i.slice(y),m}return i.replace(h,f)}catch{return i}}default:return dn(t,e,n)}}function Bt(t,e,n){switch(n){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 hn(t,e,n){switch(n){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 zt(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function Ts(t,e){let n=t.state.env[e];if(n!==void 0)return n;let r=t.state.env[`${e}_0`];return r!==void 0?r:q(t,e)}function ve(t){if(!t)return 0;let e=Number.parseInt(t,10);if(!Number.isNaN(e)&&/^-?\d+$/.test(t.trim()))return e;let n=t.trim();if(!n)return 0;try{let r=new M,{expr:s,pos:o}=J(r,n,0);if(o<n.length){let i=n.slice(o).trim().split(/\s+/)[0];throw new W(`${n}: syntax error in expression (error token is "${i}")`)}return s.type==="ArithNumber"?s.value:e||0}catch(r){if(r instanceof W)throw r;let s=n.split(/\s+/).slice(1)[0]||n;throw new W(`${n}: syntax error in expression (error token is "${s}")`)}}function tt(t,e,n=new Set){if(n.has(e))return 0;n.add(e);let r=Ts(t,e);if(!r)return 0;let s=Number.parseInt(r,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(r.trim()))return s;let o=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return tt(t,o,n);try{let i=new M,{expr:a}=J(i,o,0);return Q(t,a,n)}catch{return 0}}function Q(t,e,n){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return tt(t,e.name,n);case"ArithBinary":{if(e.operator==="||")return Q(t,e.left,n)||Q(t,e.right,n)?1:0;if(e.operator==="&&")return Q(t,e.left,n)&&Q(t,e.right,n)?1:0;let r=Q(t,e.left,n),s=Q(t,e.right,n);return Bt(r,s,e.operator)}case"ArithUnary":{let r=Q(t,e.operand,n);return zt(r,e.operator)}case"ArithTernary":return Q(t,e.condition,n)?Q(t,e.consequent,n):Q(t,e.alternate,n);case"ArithGroup":return Q(t,e.expression,n);default:return v(t,e)}}function le(t,e){if(e.startsWith("#")){let d=e.slice(1),h=t.state.env[d]||"";return String(h.length)}if(e.startsWith("!")){let d=e.slice(1),h=t.state.env[d]||"";return t.state.env[h]||""}let n=[":-",":=",":?",":+","-","=","?","+"],r=-1,s="";for(let d of n){let h=e.indexOf(d);h>0&&(r===-1||h<r)&&(r=h,s=d)}if(r===-1)return q(t,e);let o=e.slice(0,r),i=e.slice(r+s.length),a=t.state.env[o],l=a===void 0,c=a==="",f=s.startsWith(":");switch(s){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 v(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 tt(t,e.name);case"ArithNested":return v(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let n=le(t,e.content);return Number.parseInt(n,10)||0}case"ArithDynamicBase":{let n=le(t,e.baseExpr),r=Number.parseInt(n,10);if(r<2||r>64)return 0;let s=`${r}#${e.value}`;return Se(s)}case"ArithDynamicNumber":{let r=le(t,e.prefix)+e.suffix;return Se(r)}case"ArithArrayElement":{let n=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(n&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let o=v(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
49
+ `,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
50
+ `,0;o=c}r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return ve(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return ve(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new X(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?ve(s):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 v(t,e.left)||v(t,e.right)?1:0;if(e.operator==="&&")return v(t,e.left)&&v(t,e.right)?1:0;let n=v(t,e.left),r=v(t,e.right);return Bt(n,r,e.operator)}case"ArithUnary":{let n=v(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,s=Number.parseInt(q(t,r),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let l=v(t,e.operand.index);o=`${r}_${l}`}else return n;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 n}return zt(n,e.operator)}case"ArithTernary":return v(t,e.condition)?v(t,e.consequent):v(t,e.alternate);case"ArithAssignment":{let n=e.variable,r=n;if(e.stringKey!==void 0)r=`${n}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(n);if(a&&e.subscript.type==="ArithVariable")r=`${n}_${e.subscript.name}`;else if(a){let l=v(t,e.subscript);r=`${n}_${l}`}else{let l=v(t,e.subscript);if(l<0){let c=T(t,n);c.length>0&&(l=Math.max(...c.map(([d])=>typeof d=="number"?d:0))+1+l)}r=`${n}_${l}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,o=v(t,e.value),i=hn(s,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return v(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=mn(t,r);return Number.parseInt(n,10)||0}default:return 0}}function mn(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return q(t,e.name);case"ArithBracedExpansion":return le(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let n="";for(let r of e.parts)n+=mn(t,r);return n}default:return String(v(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 tt(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 n=le(t,e.content);return Number.parseInt(n,10)||0}case"ArithDynamicBase":{let n=le(t,e.baseExpr),r=Number.parseInt(n,10);if(r<2||r>64)return 0;let s=`${r}#${e.value}`;return Se(s)}case"ArithDynamicNumber":{let r=le(t,e.prefix)+e.suffix;return Se(r)}case"ArithArrayElement":{let n=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(n&&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 ve(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return ve(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new X(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?ve(s):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 n=await $(t,e.left),r=await $(t,e.right);return Bt(n,r,e.operator)}case"ArithUnary":{let n=await $(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,s=Number.parseInt(q(t,r),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(s&&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 n;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 n}return zt(n,e.operator)}case"ArithTernary":return await $(t,e.condition)?await $(t,e.consequent):await $(t,e.alternate);case"ArithAssignment":{let n=e.variable,r=n;if(e.stringKey!==void 0)r=`${n}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(n);if(a&&e.subscript.type==="ArithVariable")r=`${n}_${e.subscript.name}`;else if(a){let l=await $(t,e.subscript);r=`${n}_${l}`}else{let l=await $(t,e.subscript);if(l<0){let c=T(t,n);c.length>0&&(l=Math.max(...c.map(([d])=>typeof d=="number"?d:0))+1+l)}r=`${n}_${l}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,o=await $(t,e.value),i=hn(s,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return await $(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=await pn(t,r);return Number.parseInt(n,10)||0}default:return 0}}async function pn(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return q(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 n="";for(let r of e.parts)n+=await pn(t,r);return n}default:return String(await $(t,e))}}var N=Object.freeze({stdout:"",stderr:"",exitCode:0});function H(t=""){return{stdout:t,stderr:"",exitCode:0}}function x(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function S(t,e,n){return{stdout:t,stderr:e,exitCode:n}}function O(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function ne(t,e,n="",r=""){throw new B(t,e,n,r)}function Ut(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ie;return N}let n=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
51
+ `);n=r}throw new z(n)}async function jt(t,e){let n,r=!1,s=!1,o=0;for(;o<e.length;)if(e[o]==="--"){o++;break}else if(e[o]==="-L")s=!1,o++;else if(e[o]==="-P")s=!0,o++;else if(e[o].startsWith("-")&&e[o]!=="-")o++;else break;let i=e.slice(o);if(i.length===0||i[0]==="~"?n=t.state.env.HOME||"/":i[0]==="-"?(n=t.state.previousDir,r=!0):n=i[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let d=t.state.env.CDPATH;if(d){let h=d.split(":").filter(m=>m);for(let m of h){let y=m.startsWith("/")?`${m}/${n}`:`${t.state.cwd}/${m}/${n}`;try{if((await t.fs.stat(y)).isDirectory){n=y,r=!0;break}}catch{}}}}let l=(n.startsWith("/")?n:`${t.state.cwd}/${n}`).split("/").filter(d=>d&&d!=="."),c="";for(let d of l)if(d==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${d}`:`/${d}`;try{if(!(await t.fs.stat(c)).isDirectory)return x(`bash: cd: ${n}: Not a directory
52
+ `)}catch{return x(`bash: cd: ${n}: No such file or directory
53
+ `)}}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}
54
+ `:"")}function Gt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ie;return N}if(e.length>1)throw new z(1);let n=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)return x(`bash: continue: ${e[0]}: numeric argument required
55
+ `);n=r}throw new K(n)}function Ee(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function Ws(t,e){return t.state.readonlyVars?.has(e)??!1}function fe(t,e,n="bash"){return Ws(t,e)?x(`${n}: ${e}: readonly variable
56
+ `):null}function yn(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:Ht(e[2])};if(t.includes("=")){let n=t.indexOf("=");return{name:t.slice(0,n),isArray:!1,value:t.slice(n+1)}}return{name:t,isArray:!1}}function wn(t,e,n={}){let{name:r,isArray:s,arrayElements:o,value:i}=e,{makeReadonly:a=!1,checkReadonly:l=!0}=n;if(l){let c=fe(t,r);if(c)return c}if(s&&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&&Ee(t,r),null}function Vt(t,e){let n=!1,r=!1,s=!1,o=!1,i=!1,a=[];for(let l=0;l<e.length;l++){let c=e[l];if(c==="-a")n=!0;else if(c==="-A")r=!0;else if(c==="-r")s=!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"?n=!0:f==="A"?r=!0:f==="r"?s=!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 d=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"');l+=`declare -- ${c}="${d}"
57
+ `}}return H(l)}if(a.length===0&&!i){let l="",c=Object.entries(t.state.env).filter(([f])=>!f.startsWith("BASH_")).sort(([f],[d])=>f.localeCompare(d));for(let[f,d]of c){let h=d.replace(/'/g,"'\\''");l+=`declare -- ${f}='${h}'
58
+ `}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],d=c[2];if(r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f)),r&&d.includes("[")){let h=Fs(d);for(let[m,y]of h)t.state.env[`${f}_${m}`]=y}else{let h=Ht(d);for(let m=0;m<h.length;m++)t.state.env[`${f}_${m}`]=h[m];t.state.env[`${f}__length`]=String(h.length)}s&&Ee(t,f);continue}if(l.includes("=")){let f=l.indexOf("="),d=l.slice(0,f),h=l.slice(f+1),m=fe(t,d);if(m)return m;t.state.env[d]=h,s&&Ee(t,d)}else{let f=l;r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f));let d=Object.keys(t.state.env).some(h=>h.startsWith(`${f}_`)&&!h.startsWith(`${f}__length`));!(f in t.state.env)&&!d&&(n||r?t.state.env[`${f}__length`]="0":t.state.env[f]=""),s&&Ee(t,f)}}return N}function Ht(t){let e=[],n="",r=!1,s=!1,o=!1;for(let i of t){if(o){n+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(i==="'"&&!s){r=!r;continue}if(i==='"'&&!r){s=!s;continue}if((i===" "||i===" "||i===`
59
+ `)&&!r&&!s){n&&(e.push(n),n="");continue}n+=i}return n&&e.push(n),e}function Fs(t){let e=[],n=0;for(;n<t.length;){for(;n<t.length&&/\s/.test(t[n]);)n++;if(n>=t.length)break;if(t[n]!=="["){n++;continue}n++;let r="";if(t[n]==="'"||t[n]==='"'){let o=t[n];for(n++;n<t.length&&t[n]!==o;)r+=t[n],n++;t[n]===o&&n++}else for(;n<t.length&&t[n]!=="]"&&t[n]!=="=";)r+=t[n],n++;for(;n<t.length&&t[n]!=="]";)n++;if(t[n]==="]"&&n++,t[n]!=="=")continue;n++;let s="";if(t[n]==="'"||t[n]==='"'){let o=t[n];for(n++;n<t.length&&t[n]!==o;)t[n]==="\\"&&n+1<t.length&&n++,s+=t[n],n++;t[n]===o&&n++}else for(;n<t.length&&!/\s/.test(t[n]);)s+=t[n],n++;e.push([r,s])}return e}function qt(t,e){let n=!1,r=!1,s=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="-a")n=!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}"
60
+ `)}return H(a)}}else if(i==="--"){s.push(...e.slice(o+1));break}else i.startsWith("-")||s.push(i)}for(let o of s){let i=yn(o);if(i.value===void 0&&!i.isArray){Ee(t,i.name);continue}let a=wn(t,i,{makeReadonly:!0});if(a)return a}return N}async function Zt(t,e){let n=e;if(n.length>0){let s=n[0];if(s==="--")n=n.slice(1);else if(s.startsWith("-")&&s!=="-"&&s.length>1)return x(`bash: eval: ${s}: invalid option
61
61
  eval: usage: eval [arg ...]
62
- `,2)}if(n.length===0)return N;let r=n.join(" ");if(r.trim()==="")return N;try{let s=ce(r);return t.executeScript(s)}catch(s){if(s instanceof z||s instanceof K||s instanceof U||s instanceof k)throw s;if(s.name==="ParseException")return S(`bash: eval: ${s.message}
62
+ `,2)}if(n.length===0)return N;let r=n.join(" ");if(r.trim()==="")return N;try{let s=ce(r);return t.executeScript(s)}catch(s){if(s instanceof z||s instanceof K||s instanceof U||s instanceof k)throw s;if(s.name==="ParseException")return x(`bash: eval: ${s.message}
63
63
  `);throw s}}function Qt(t,e){let n,r="";if(e.length===0)n=t.state.lastExitCode;else{let s=e[0],o=Number.parseInt(s,10);s===""||Number.isNaN(o)||!/^-?\d+$/.test(s)?(r=`bash: exit: ${s}: numeric argument required
64
- `,n=2):n=(o%256+256)%256}throw new k(n,"",r)}function Kt(t,e){let n=!1,r=[];for(let i of e)i==="-n"?n=!0:i==="-p"||i==="--"||r.push(i);if(r.length===0&&!n){let i="",a=Object.entries(t.state.env).filter(([c])=>!c.startsWith("BASH_ALIAS_")).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of a){let f=l.replace(/'/g,"'\\''");i+=`declare -x ${c}='${f}'
65
- `}return H(i)}if(n){for(let i of r){let a=i.split("=")[0];delete t.state.env[a]}return N}let s="",o=0;for(let i of r){let a,c;if(i.includes("=")){let l=i.indexOf("=");a=i.slice(0,l),c=i.slice(l+1)}else a=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${i}': not a valid identifier
66
- `,o=1;continue}c!==void 0?t.state.env[a]=c:a in t.state.env||(t.state.env[a]="")}return x("",s,o)}function Ms(t){let e=[],n="",r=0;for(let s of t){for(let o of s)o==="("?r++:o===")"&&r--;n?n+=` ${s}`:n=s,r===0&&(e.push(n),n="")}return n&&e.push(n),e}async function Xt(t,e){if(e.length===0)return S(`bash: let: expression expected
67
- `);let n=Ms(e),r=0;for(let s of n)try{let i=ce(`(( ${s} ))`).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: ${s}: ${o.message}
68
- `)}return x("","",r===0?1:0)}function Bs(t,e){let n=t.state.env.HOME||"/home/user";return e.split(":").map(o=>o==="~"?n:o==="~root"?"/root":o.startsWith("~/")?n+o.slice(1):o.startsWith("~root/")?`/root${o.slice(5)}`:o).join(":")}function Yt(t,e){if(t.state.localScopes.length===0)return S(`bash: local: can only be used in a function
69
- `);let n=t.state.localScopes[t.state.localScopes.length-1],r="",s=0;for(let o of e){let i,a;if(o.includes("=")){let c=o.indexOf("=");i=o.slice(0,c),a=Bs(t,o.slice(c+1))}else i=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)){r+=`bash: local: \`${o}': not a valid identifier
70
- `,s=1;continue}n.has(i)||n.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return x("",r,s)}function Jt(t,e,n){let r=`
71
- `,s=0,o=0,i=0,a=!1,c="MAPFILE",l=0;for(;l<e.length;){let E=e[l];E==="-d"&&l+1<e.length?(r=e[l+1]||`
72
- `,l+=2):E==="-n"&&l+1<e.length?(s=Number.parseInt(e[l+1],10)||0,l+=2):E==="-O"&&l+1<e.length?(o=Number.parseInt(e[l+1],10)||0,l+=2):E==="-s"&&l+1<e.length?(i=Number.parseInt(e[l+1],10)||0,l+=2):E==="-t"?(a=!0,l++):E==="-u"||E==="-C"||E==="-c"?l+=2:(E.startsWith("-")||(c=E),l++)}let f=n;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let d=[],h=f,m=0,y=0;for(;h.length>0;){let E=h.indexOf(r);if(E===-1){h.length>0&&(y<i?y++:(s===0||m<s)&&(d.push(h),m++));break}let p=h.substring(0,E);if(a||(p+=r),h=h.substring(E+r.length),y<i){y++;continue}if(s>0&&m>=s)break;d.push(p),m++}_e(t,c);for(let E=0;E<d.length;E++)t.state.env[`${c}_${o+E}`]=d[E];return d.length>0&&(t.state.env[`${c}__length`]=String(o+d.length)),t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=""),x("","",0)}function er(t,e,n){let r=!1,s=`
73
- `,o="",i=-1,a=null,c=[],l=0,f=!1;for(;l<e.length;){let g=e[l];g==="-r"?r=!0:g==="-d"&&l+1<e.length?(s=e[l+1],l++):g==="-p"&&l+1<e.length?(o=e[l+1],l++):g==="-n"&&l+1<e.length?(i=Number.parseInt(e[l+1],10),(Number.isNaN(i)||i<0)&&(f=!0,i=0),l++):g==="-a"&&l+1<e.length?(a=e[l+1],l++):g==="-t"?l+1<e.length&&!e[l+1].startsWith("-")&&l++:g==="-s"||g.startsWith("-")||c.push(g),l++}if(f)return x("","",1);c.length===0&&a===null&&c.push("REPLY");let d=n;!d&&t.state.groupStdin!==void 0&&(d=t.state.groupStdin);let h="",m=0,y=!0;if(i>=0){for(let g=0;g<d.length&&g<i;g++){let b=d[g];if(b===s){m=g+1;break}h+=b,m=g+1}t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=d.substring(m))}else{let g=d;for(m=0;;){let b=g.indexOf(s);if(b!==-1){let C=g.substring(0,b);if(m+=b+s.length,g=g.substring(b+s.length),!r&&C.endsWith("\\")){h+=C.slice(0,-1);continue}h+=C,y=!0;break}else if(g.length>0){h+=g,m+=g.length,y=!1,g="";break}else{if(h.length===0){for(let C of c)t.state.env[C]="";return a&&_e(t,a),x("","",1)}y=!1;break}}t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=d.substring(m))}if(s===`
64
+ `,n=2):n=(o%256+256)%256}throw new k(n,"",r)}function Kt(t,e){let n=!1,r=[];for(let i of e)i==="-n"?n=!0:i==="-p"||i==="--"||r.push(i);if(r.length===0&&!n){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}'
65
+ `}return H(i)}if(n){for(let i of r){let a=i.split("=")[0];delete t.state.env[a]}return N}let s="",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)){s+=`bash: export: \`${i}': not a valid identifier
66
+ `,o=1;continue}l!==void 0?t.state.env[a]=l:a in t.state.env||(t.state.env[a]="")}return S("",s,o)}function Ms(t){let e=[],n="",r=0;for(let s of t){for(let o of s)o==="("?r++:o===")"&&r--;n?n+=` ${s}`:n=s,r===0&&(e.push(n),n="")}return n&&e.push(n),e}async function Xt(t,e){if(e.length===0)return x(`bash: let: expression expected
67
+ `);let n=Ms(e),r=0;for(let s of n)try{let i=ce(`(( ${s} ))`).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 x(`bash: let: ${s}: ${o.message}
68
+ `)}return S("","",r===0?1:0)}function Bs(t,e){let n=t.state.env.HOME||"/home/user";return e.split(":").map(o=>o==="~"?n:o==="~root"?"/root":o.startsWith("~/")?n+o.slice(1):o.startsWith("~root/")?`/root${o.slice(5)}`:o).join(":")}function Yt(t,e){if(t.state.localScopes.length===0)return x(`bash: local: can only be used in a function
69
+ `);let n=t.state.localScopes[t.state.localScopes.length-1],r="",s=0;for(let o of e){let i,a;if(o.includes("=")){let l=o.indexOf("=");i=o.slice(0,l),a=Bs(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
70
+ `,s=1;continue}n.has(i)||n.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return S("",r,s)}function Jt(t,e,n){let r=`
71
+ `,s=0,o=0,i=0,a=!1,l="MAPFILE",c=0;for(;c<e.length;){let E=e[c];E==="-d"&&c+1<e.length?(r=e[c+1]||`
72
+ `,c+=2):E==="-n"&&c+1<e.length?(s=Number.parseInt(e[c+1],10)||0,c+=2):E==="-O"&&c+1<e.length?(o=Number.parseInt(e[c+1],10)||0,c+=2):E==="-s"&&c+1<e.length?(i=Number.parseInt(e[c+1],10)||0,c+=2):E==="-t"?(a=!0,c++):E==="-u"||E==="-C"||E==="-c"?c+=2:(E.startsWith("-")||(l=E),c++)}let f=n;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let d=[],h=f,m=0,y=0;for(;h.length>0;){let E=h.indexOf(r);if(E===-1){h.length>0&&(y<i?y++:(s===0||m<s)&&(d.push(h),m++));break}let p=h.substring(0,E);if(a||(p+=r),h=h.substring(E+r.length),y<i){y++;continue}if(s>0&&m>=s)break;d.push(p),m++}_e(t,l);for(let E=0;E<d.length;E++)t.state.env[`${l}_${o+E}`]=d[E];return d.length>0&&(t.state.env[`${l}__length`]=String(o+d.length)),t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=""),S("","",0)}function er(t,e,n){let r=!1,s=`
73
+ `,o="",i=-1,a=null,l=[],c=0,f=!1;for(;c<e.length;){let g=e[c];g==="-r"?r=!0:g==="-d"&&c+1<e.length?(s=e[c+1],c++):g==="-p"&&c+1<e.length?(o=e[c+1],c++):g==="-n"&&c+1<e.length?(i=Number.parseInt(e[c+1],10),(Number.isNaN(i)||i<0)&&(f=!0,i=0),c++):g==="-a"&&c+1<e.length?(a=e[c+1],c++):g==="-t"?c+1<e.length&&!e[c+1].startsWith("-")&&c++:g==="-s"||g.startsWith("-")||l.push(g),c++}if(f)return S("","",1);l.length===0&&a===null&&l.push("REPLY");let d=n;!d&&t.state.groupStdin!==void 0&&(d=t.state.groupStdin);let h="",m=0,y=!0;if(i>=0){for(let g=0;g<d.length&&g<i;g++){let b=d[g];if(b===s){m=g+1;break}h+=b,m=g+1}t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=d.substring(m))}else{let g=d;for(m=0;;){let b=g.indexOf(s);if(b!==-1){let C=g.substring(0,b);if(m+=b+s.length,g=g.substring(b+s.length),!r&&C.endsWith("\\")){h+=C.slice(0,-1);continue}h+=C,y=!0;break}else if(g.length>0){h+=g,m+=g.length,y=!1,g="";break}else{if(h.length===0){for(let C of l)t.state.env[C]="";return a&&_e(t,a),S("","",1)}y=!1;break}}t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=d.substring(m))}if(s===`
74
74
  `&&h.endsWith(`
75
- `)&&(h=h.slice(0,-1)),r||(h=h.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=h,x("","",y?0:1);let E=Ye(t.state.env),{words:p,wordStarts:w}=Yr(h,E);if(a){_e(t,a);for(let g=0;g<p.length;g++)t.state.env[`${a}_${g}`]=p[g];return x("","",y?0:1)}for(let g=0;g<c.length;g++){let b=c[g];if(g<c.length-1)t.state.env[b]=p[g]??"";else if(g<w.length){let C=Jr(h.substring(w[g]),E);t.state.env[b]=C}else t.state.env[b]=""}return x("","",y?0:1)}function tr(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 n=t.state.lastExitCode;if(e.length>0){let r=e[0],s=Number.parseInt(r,10);if(r===""||Number.isNaN(s)||!/^-?\d+$/.test(r))return S(`bash: return: ${r}: numeric argument required
75
+ `)&&(h=h.slice(0,-1)),r||(h=h.replace(/\\(.)/g,"$1")),l.length===1&&l[0]==="REPLY")return t.state.env.REPLY=h,S("","",y?0:1);let E=Ye(t.state.env),{words:p,wordStarts:w}=Yr(h,E);if(a){_e(t,a);for(let g=0;g<p.length;g++)t.state.env[`${a}_${g}`]=p[g];return S("","",y?0:1)}for(let g=0;g<l.length;g++){let b=l[g];if(g<l.length-1)t.state.env[b]=p[g]??"";else if(g<w.length){let C=Jr(h.substring(w[g]),E);t.state.env[b]=C}else t.state.env[b]=""}return S("","",y?0:1)}function tr(t,e){if(t.state.callDepth===0&&t.state.sourceDepth===0)return x("bash: return: can only `return' from a function or sourced script\n");let n=t.state.lastExitCode;if(e.length>0){let r=e[0],s=Number.parseInt(r,10);if(r===""||Number.isNaN(s)||!/^-?\d+$/.test(r))return x(`bash: return: ${r}: numeric argument required
76
76
  `,2);n=(s%256+256)%256}throw new U(n)}function zs(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var rt=`set: usage: set [-eux] [+eux] [-o option] [+o option]
77
77
  Options:
78
78
  -e Exit immediately if a command exits with non-zero status
@@ -89,68 +89,68 @@ Options:
89
89
  +o pipefail Disable pipefail
90
90
  -o xtrace Same as -x
91
91
  +o xtrace Disable xtrace
92
- `,En={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},gn={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},An=["errexit","nounset","pipefail","verbose","xtrace"],xn=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function Sn(t,e,n){e!==null&&(t.state.options[e]=n)}function Us(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function nr(t,e){if(e.includes("--help"))return H(rt);if(e.length===0){let r=Object.entries(t.state.env).filter(([s])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}=${zs(o)}`).join(`
92
+ `,En={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},gn={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},An=["errexit","nounset","pipefail","verbose","xtrace"],Sn=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function xn(t,e,n){e!==null&&(t.state.options[e]=n)}function Us(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function nr(t,e){if(e.includes("--help"))return H(rt);if(e.length===0){let r=Object.entries(t.state.env).filter(([s])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}=${zs(o)}`).join(`
93
93
  `);return H(r?`${r}
94
- `:"")}let n=0;for(;n<e.length;){let r=e[n];if((r==="-o"||r==="+o")&&Us(e,n)){let s=e[n+1];if(!(s in gn))return S(`bash: set: ${s}: invalid option name
95
- ${rt}`);Sn(t,gn[s],r==="-o"),n+=2;continue}if(r==="-o"){let s=An.map(a=>`${a.padEnd(16)}${t.state.options[a]?"on":"off"}`),o=xn.map(a=>`${a.padEnd(16)}off`),i=[...s,...o].sort();return H(`${i.join(`
94
+ `:"")}let n=0;for(;n<e.length;){let r=e[n];if((r==="-o"||r==="+o")&&Us(e,n)){let s=e[n+1];if(!(s in gn))return x(`bash: set: ${s}: invalid option name
95
+ ${rt}`);xn(t,gn[s],r==="-o"),n+=2;continue}if(r==="-o"){let s=An.map(a=>`${a.padEnd(16)}${t.state.options[a]?"on":"off"}`),o=Sn.map(a=>`${a.padEnd(16)}off`),i=[...s,...o].sort();return H(`${i.join(`
96
96
  `)}
97
- `)}if(r==="+o"){let s=An.map(a=>`set ${t.state.options[a]?"-o":"+o"} ${a}`),o=xn.map(a=>`set +o ${a}`),i=[...s,...o].sort();return H(`${i.join(`
97
+ `)}if(r==="+o"){let s=An.map(a=>`set ${t.state.options[a]?"-o":"+o"} ${a}`),o=Sn.map(a=>`set +o ${a}`),i=[...s,...o].sort();return H(`${i.join(`
98
98
  `)}
99
- `)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let s=r[0]==="-";for(let o=1;o<r.length;o++){let i=r[o];if(!(i in En))return S(`bash: set: ${r[0]}${i}: invalid option
100
- ${rt}`);Sn(t,En[i],s)}n++;continue}if(r==="--")return rr(t,e.slice(n+1)),N;if(r==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,n+1<e.length)return rr(t,e.slice(n+1)),N;n++;continue}if(r==="+"){n++;continue}return r.startsWith("-")||r.startsWith("+")?S(`bash: set: ${r}: invalid option
101
- ${rt}`):(rr(t,e.slice(n)),N)}return N}function rr(t,e){let n=1;for(;t.state.env[String(n)]!==void 0;)delete t.state.env[String(n)],n++;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 sr(t,e){let n=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
102
- `);n=i}let r=Number.parseInt(t.state.env["#"]||"0",10);if(n>r)return S(`bash: shift: shift count out of range
103
- `);if(n===0)return N;let s=[];for(let i=1;i<=r;i++)s.push(t.state.env[String(i)]||"");let o=s.slice(n);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(" "),N}async function ir(t,e){let n=e;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return x("",`bash: source: filename argument required
104
- `,2);let r=n[0],s=null,o=null;if(r.includes("/")){let c=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(c),s=c}catch{}}else{let l=(t.state.env.PATH||"").split(":").filter(f=>f);for(let f of l){let d=t.fs.resolvePath(t.state.cwd,`${f}/${r}`);try{if((await t.fs.stat(d)).isDirectory)continue;o=await t.fs.readFile(d),s=d;break}catch{}}if(o===null){let f=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(f),s=f}catch{}}}if(o===null)return S(`bash: ${r}: No such file or directory
105
- `);let i={};if(n.length>1){for(let l=1;l<=9;l++)i[String(l)]=t.state.env[String(l)];i["#"]=t.state.env["#"],i["@"]=t.state.env["@"];let c=n.slice(1);t.state.env["#"]=String(c.length),t.state.env["@"]=c.join(" ");for(let l=0;l<c.length&&l<9;l++)t.state.env[String(l+1)]=c[l];for(let l=c.length+1;l<=9;l++)delete t.state.env[String(l)]}let a=()=>{if(t.state.sourceDepth--,n.length>1)for(let[c,l]of Object.entries(i))l===void 0?delete t.state.env[c]:t.state.env[c]=l};t.state.sourceDepth++;try{let c=ce(o),l=await t.executeScript(c);return a(),l}catch(c){if(a(),c instanceof k)throw c;if(c instanceof U)return x(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return S(`bash: ${r}: ${c.message}
106
- `);throw c}}function or(t,e){let n="variable",r="",s=0;for(let o of e){if(o==="-v"){n="variable";continue}if(o==="-f"){n="function";continue}if(n==="function"){t.state.functions.delete(o);continue}let i=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let a=i[1],c=i[2];if(c==="@"||c==="*"){let f=T(t,a);for(let[d]of f)delete t.state.env[`${a}_${d}`];delete t.state.env[a];continue}let l;if(/^-?\d+$/.test(c))l=Number.parseInt(c,10);else{let f=t.state.env[c];l=f?Number.parseInt(f,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let f=T(t,a),d=f.length;if(d===0){r+=`bash: unset: [${l}]: bad array subscript
107
- `,s=1;continue}let h=d+l;if(h<0){r+=`bash: unset: [${l}]: bad array subscript
108
- `,s=1;continue}let m=f[h][0];delete t.state.env[`${a}_${m}`];continue}delete t.state.env[`${a}_${l}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return x("",r,s)}function ar(t,e){return t.fs.resolvePath(t.state.cwd,e)}var js=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function nt(t){return js.includes(t)}async function st(t,e,n){let r=ar(t,n);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 Gs=["-nt","-ot","-ef"];function it(t){return Gs.includes(t)}async function ot(t,e,n,r){let s=ar(t,n),o=ar(t,r);switch(e){case"-nt":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,s),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var Hs=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function at(t){return Hs.has(t)}function ct(t,e,n){switch(t){case"-eq":return e===n;case"-ne":return e!==n;case"-lt":return e<n;case"-le":return e<=n;case"-gt":return e>n;case"-ge":return e>=n}}function lt(t){return t==="="||t==="=="||t==="!="}function ft(t,e,n,r=!1){let s=r?ut(e,n):e===n;return t==="!="?!s:s}var Vs=new Set(["-z","-n"]);function dt(t){return Vs.has(t)}function ht(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function mt(t,e){let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let r=n[1],s=n[2];s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else try{let i=Function(`"use strict"; return (${s})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[s];o=i?Number.parseInt(i,10):0}if(o<0){let i=Oe(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 n=await P(t,e.left),r=await P(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(lt(e.operator))return ft(e.operator,n,r,!s);if(at(e.operator))return ct(e.operator,Cn(t,n),Cn(t,r));if(it(e.operator))return ot(t,e.operator,n,r);switch(e.operator){case"=~":try{let o=new RegExp(r),i=n.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 n<r;case">":return n>r;default:return!1}}case"CondUnary":{let n=await P(t,e.operand);return nt(e.operator)?st(t,e.operator,n):dt(e.operator)?ht(e.operator,n):e.operator==="-v"?mt(t,n):e.operator==="-o"?lr(t,n):!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 P(t,e.word)!=="";default:return!1}}async function $e(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],s=e[1];return r==="("?S(`test: '(' without matching ')'
109
- `,2):nt(r)?O(await st(t,r,s)):dt(r)?O(ht(r,s)):r==="!"?O(!s):r==="-v"?O(mt(t,s)):r==="-o"?O(lr(t,s)):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
110
- `,2):x("","",1)}if(e.length===3){let r=e[0],s=e[1],o=e[2];if(lt(s))return O(ft(s,r,o));if(at(s)){let i=pt(r),a=pt(o);return!i.valid||!a.valid?x("","",2):O(ct(s,i.value,a.value))}if(it(s))return O(await ot(t,s,r,o));switch(s){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 $e(t,[s,o]);return x("",i.stderr,i.exitCode===0?1:i.exitCode===1?0:i.exitCode)}if(r==="("&&o===")")return O(s!=="")}if(e.length===4){if(e[0]==="!"){let r=await $e(t,e.slice(1));return x("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(e[0]==="("&&e[3]===")")return $e(t,[e[1],e[2]])}let n=await vn(t,e,0);return n.pos<e.length?S(`test: too many arguments
99
+ `)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let s=r[0]==="-";for(let o=1;o<r.length;o++){let i=r[o];if(!(i in En))return x(`bash: set: ${r[0]}${i}: invalid option
100
+ ${rt}`);xn(t,En[i],s)}n++;continue}if(r==="--")return rr(t,e.slice(n+1)),N;if(r==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,n+1<e.length)return rr(t,e.slice(n+1)),N;n++;continue}if(r==="+"){n++;continue}return r.startsWith("-")||r.startsWith("+")?x(`bash: set: ${r}: invalid option
101
+ ${rt}`):(rr(t,e.slice(n)),N)}return N}function rr(t,e){let n=1;for(;t.state.env[String(n)]!==void 0;)delete t.state.env[String(n)],n++;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 sr(t,e){let n=1;if(e.length>0){let i=Number.parseInt(e[0],10);if(Number.isNaN(i)||i<0)return x(`bash: shift: ${e[0]}: numeric argument required
102
+ `);n=i}let r=Number.parseInt(t.state.env["#"]||"0",10);if(n>r)return x(`bash: shift: shift count out of range
103
+ `);if(n===0)return N;let s=[];for(let i=1;i<=r;i++)s.push(t.state.env[String(i)]||"");let o=s.slice(n);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(" "),N}async function ir(t,e){let n=e;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return S("",`bash: source: filename argument required
104
+ `,2);let r=n[0],s=null,o=null;if(r.includes("/")){let l=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(l),s=l}catch{}}else{let c=(t.state.env.PATH||"").split(":").filter(f=>f);for(let f of c){let d=t.fs.resolvePath(t.state.cwd,`${f}/${r}`);try{if((await t.fs.stat(d)).isDirectory)continue;o=await t.fs.readFile(d),s=d;break}catch{}}if(o===null){let f=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(f),s=f}catch{}}}if(o===null)return x(`bash: ${r}: No such file or directory
105
+ `);let i={};if(n.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=n.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--,n.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 S(l.stdout,l.stderr,l.exitCode);if(l.name==="ParseException")return x(`bash: ${r}: ${l.message}
106
+ `);throw l}}function or(t,e){let n="variable",r="",s=0;for(let o of e){if(o==="-v"){n="variable";continue}if(o==="-f"){n="function";continue}if(n==="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[d]of f)delete t.state.env[`${a}_${d}`];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),d=f.length;if(d===0){r+=`bash: unset: [${c}]: bad array subscript
107
+ `,s=1;continue}let h=d+c;if(h<0){r+=`bash: unset: [${c}]: bad array subscript
108
+ `,s=1;continue}let m=f[h][0];delete t.state.env[`${a}_${m}`];continue}delete t.state.env[`${a}_${c}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return S("",r,s)}function ar(t,e){return t.fs.resolvePath(t.state.cwd,e)}var js=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function nt(t){return js.includes(t)}async function st(t,e,n){let r=ar(t,n);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 Gs=["-nt","-ot","-ef"];function it(t){return Gs.includes(t)}async function ot(t,e,n,r){let s=ar(t,n),o=ar(t,r);switch(e){case"-nt":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,s),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var Hs=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function at(t){return Hs.has(t)}function ct(t,e,n){switch(t){case"-eq":return e===n;case"-ne":return e!==n;case"-lt":return e<n;case"-le":return e<=n;case"-gt":return e>n;case"-ge":return e>=n}}function lt(t){return t==="="||t==="=="||t==="!="}function ft(t,e,n,r=!1){let s=r?ut(e,n):e===n;return t==="!="?!s:s}var Vs=new Set(["-z","-n"]);function dt(t){return Vs.has(t)}function ht(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function mt(t,e){let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let r=n[1],s=n[2];s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else try{let i=Function(`"use strict"; return (${s})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[s];o=i?Number.parseInt(i,10):0}if(o<0){let i=Oe(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 n=await P(t,e.left),r=await P(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(lt(e.operator))return ft(e.operator,n,r,!s);if(at(e.operator))return ct(e.operator,Cn(t,n),Cn(t,r));if(it(e.operator))return ot(t,e.operator,n,r);switch(e.operator){case"=~":try{let o=new RegExp(r),i=n.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 n<r;case">":return n>r;default:return!1}}case"CondUnary":{let n=await P(t,e.operand);return nt(e.operator)?st(t,e.operator,n):dt(e.operator)?ht(e.operator,n):e.operator==="-v"?mt(t,n):e.operator==="-o"?lr(t,n):!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 P(t,e.word)!=="";default:return!1}}async function $e(t,e){if(e.length===0)return S("","",1);if(e.length===1)return O(!!e[0]);if(e.length===2){let r=e[0],s=e[1];return r==="("?x(`test: '(' without matching ')'
109
+ `,2):nt(r)?O(await st(t,r,s)):dt(r)?O(ht(r,s)):r==="!"?O(!s):r==="-v"?O(mt(t,s)):r==="-o"?O(lr(t,s)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?x(`test: ${r}: unary operator expected
110
+ `,2):S("","",1)}if(e.length===3){let r=e[0],s=e[1],o=e[2];if(lt(s))return O(ft(s,r,o));if(at(s)){let i=pt(r),a=pt(o);return!i.valid||!a.valid?S("","",2):O(ct(s,i.value,a.value))}if(it(s))return O(await ot(t,s,r,o));switch(s){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 $e(t,[s,o]);return S("",i.stderr,i.exitCode===0?1:i.exitCode===1?0:i.exitCode)}if(r==="("&&o===")")return O(s!=="")}if(e.length===4){if(e[0]==="!"){let r=await $e(t,e.slice(1));return S("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(e[0]==="("&&e[3]===")")return $e(t,[e[1],e[2]])}let n=await vn(t,e,0);return n.pos<e.length?x(`test: too many arguments
111
111
  `,2):O(n.value)}async function vn(t,e,n){return qs(t,e,n)}async function qs(t,e,n){let{value:r,pos:s}=await bn(t,e,n);for(;e[s]==="-o";){let o=await bn(t,e,s+1);r=r||o.value,s=o.pos}return{value:r,pos:s}}async function bn(t,e,n){let{value:r,pos:s}=await cr(t,e,n);for(;e[s]==="-a";){let o=await cr(t,e,s+1);r=r&&o.value,s=o.pos}return{value:r,pos:s}}async function cr(t,e,n){if(e[n]==="!"){let{value:r,pos:s}=await cr(t,e,n+1);return{value:!r,pos:s}}return Zs(t,e,n)}async function Zs(t,e,n){let r=e[n];if(r==="("){let{value:o,pos:i}=await vn(t,e,n+1);return{value:o,pos:e[i]===")"?i+1:i}}if(nt(r)){let o=e[n+1]??"";return{value:await st(t,r,o),pos:n+2}}if(dt(r)){let o=e[n+1]??"";return{value:ht(r,o),pos:n+2}}if(r==="-v"){let o=e[n+1]??"";return{value:mt(t,o),pos:n+2}}if(r==="-o"){let o=e[n+1]??"";return{value:lr(t,o),pos:n+2}}let s=e[n+1];if(lt(s)){let o=r,i=e[n+2]??"";return{value:ft(s,o,i),pos:n+3}}if(at(s)){let o=pt(r),i=pt(e[n+2]??"0");return!o.valid||!i.valid?{value:!1,pos:n+3}:{value:ct(s,o.value,i.value),pos:n+3}}if(it(s)){let o=r,i=e[n+2]??"";return{value:await ot(t,s,o,i),pos:n+3}}return{value:r!==void 0&&r!=="",pos:n+1}}function ut(t,e){let n="^";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\")if(r+1<e.length){let o=e[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?n+=`\\${o}`:n+=o,r++}else n+="\\\\";else if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let o=e.indexOf("]",r+1);o!==-1?(n+=e.slice(r,o+1),r=o):n+="\\["}else/[\\^$.|+(){}]/.test(s)?n+=`\\${s}`:n+=s}return n+="$",new RegExp(n).test(t)}function lr(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 Cn(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 Nn(e);try{let n=new M,r=L(n,e);return v(t,r.expression)}catch{return Nn(e)}}function Qs(t,e){let n=0;for(let r of t){let s;if(r>="0"&&r<="9")s=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")s=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")s=r.charCodeAt(0)-65+36;else if(r==="@")s=62;else if(r==="_")s=63;else return Number.NaN;if(s>=e)return Number.NaN;n=n*e+s}return n}function Nn(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 n,r=t.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let s=Number.parseInt(r[1],10);s>=2&&s<=64?n=Qs(r[2],s):n=0}else/^0[xX][0-9a-fA-F]+$/.test(t)?n=Number.parseInt(t,16):/^0[0-7]+$/.test(t)?n=Number.parseInt(t,8):n=Number.parseInt(t,10);return Number.isNaN(n)&&(n=0),e?-n:n}function pt(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 n=Number.parseInt(t,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:e?-n:n,valid:!0}}async function fr(t,e){let n=t.state.inCondition;t.state.inCondition=!0;let r="",s="",o=0;try{for(let i of e){let a=await t.executeStatement(i);r+=a.stdout,s+=a.stderr,o=a.exitCode}}finally{t.state.inCondition=n}return{stdout:r,stderr:s,exitCode:o}}function We(t,e,n,r){if(t instanceof z)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"break",stdout:e,stderr:n};if(t instanceof K)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"continue",stdout:e,stderr:n};if(t instanceof U||t instanceof Y||t instanceof k||t instanceof B)return t.prependOutput(e,n),{action:"rethrow",stdout:e,stderr:n,error:t};let s=se(t);return{action:"error",stdout:e,stderr:`${n}${s}
112
- `,exitCode:1}}async function yt(t,e,n="",r=""){let s=n,o=r,i=0;try{for(let a of e){let c=await t.executeStatement(a);s+=c.stdout,o+=c.stderr,i=c.exitCode}}catch(a){if(Ue(a)||a instanceof Y||a instanceof k||a instanceof B||a instanceof ie)throw a.prependOutput(s,o),a;return{stdout:s,stderr:`${o}${se(a)}
113
- `,exitCode:1}}return{stdout:s,stderr:o,exitCode:i}}async function $n(t,e){let n="",r="";for(let s of e.clauses){let o=await fr(t,s.condition);if(n+=o.stdout,r+=o.stderr,o.exitCode===0)return yt(t,s.body,n,r)}return e.elseBody?yt(t,e.elseBody,n,r):x(n,r,0)}async function Pn(t,e){let n="",r="",s=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return S(`bash: \`${e.variable}': not a valid identifier
114
- `);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 c=await Te(t,a);i.push(...c.values)}t.state.loopDepth++;try{for(let a of i){o++,o>t.limits.maxLoopIterations&&ne(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r),t.state.env[e.variable]=a;try{for(let c of e.body){let l=await t.executeStatement(c);n+=l.stdout,r+=l.stderr,s=l.exitCode}}catch(c){let l=We(c,n,r,t.state.loopDepth);if(n=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return x(n,r,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return x(n,r,s)}async function In(t,e){let n="",r="",s=0,o=0;e.init&&await $(t,e.init.expression),t.state.loopDepth++;try{for(;o++,o>t.limits.maxLoopIterations&&ne(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r),!(e.condition&&await $(t,e.condition.expression)===0);){try{for(let i of e.body){let a=await t.executeStatement(i);n+=a.stdout,r+=a.stderr,s=a.exitCode}}catch(i){let a=We(i,n,r,t.state.loopDepth);if(n=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(n,r,a.exitCode??1);throw a.error}e.update&&await $(t,e.update.expression)}}finally{t.state.loopDepth--}return x(n,r,s)}async function kn(t,e,n=""){let r="",s="",o=0,i=0,a=n;for(let l of e.redirections)if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let f=l.target,d=await P(t,f.content);f.stripTabs&&(d=d.split(`
112
+ `,exitCode:1}}async function yt(t,e,n="",r=""){let s=n,o=r,i=0;try{for(let a of e){let l=await t.executeStatement(a);s+=l.stdout,o+=l.stderr,i=l.exitCode}}catch(a){if(Ue(a)||a instanceof Y||a instanceof k||a instanceof B||a instanceof ie)throw a.prependOutput(s,o),a;return{stdout:s,stderr:`${o}${se(a)}
113
+ `,exitCode:1}}return{stdout:s,stderr:o,exitCode:i}}async function $n(t,e){let n="",r="";for(let s of e.clauses){let o=await fr(t,s.condition);if(n+=o.stdout,r+=o.stderr,o.exitCode===0)return yt(t,s.body,n,r)}return e.elseBody?yt(t,e.elseBody,n,r):S(n,r,0)}async function Pn(t,e){let n="",r="",s=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return x(`bash: \`${e.variable}': not a valid identifier
114
+ `);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 Te(t,a);i.push(...l.values)}t.state.loopDepth++;try{for(let a of i){o++,o>t.limits.maxLoopIterations&&ne(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r),t.state.env[e.variable]=a;try{for(let l of e.body){let c=await t.executeStatement(l);n+=c.stdout,r+=c.stderr,s=c.exitCode}}catch(l){let c=We(l,n,r,t.state.loopDepth);if(n=c.stdout,r=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return S(n,r,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return S(n,r,s)}async function In(t,e){let n="",r="",s=0,o=0;e.init&&await $(t,e.init.expression),t.state.loopDepth++;try{for(;o++,o>t.limits.maxLoopIterations&&ne(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r),!(e.condition&&await $(t,e.condition.expression)===0);){try{for(let i of e.body){let a=await t.executeStatement(i);n+=a.stdout,r+=a.stderr,s=a.exitCode}}catch(i){let a=We(i,n,r,t.state.loopDepth);if(n=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 S(n,r,a.exitCode??1);throw a.error}e.update&&await $(t,e.update.expression)}}finally{t.state.loopDepth--}return S(n,r,s)}async function kn(t,e,n=""){let r="",s="",o=0,i=0,a=n;for(let c of e.redirections)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let f=c.target,d=await P(t,f.content);f.stripTabs&&(d=d.split(`
115
115
  `).map(h=>h.replace(/^\t+/,"")).join(`
116
- `)),a=d}else if(l.operator==="<<<"&&l.target.type==="Word")a=`${await P(t,l.target)}
117
- `;else if(l.operator==="<"&&l.target.type==="Word")try{let f=await P(t,l.target),d=t.fs.resolvePath(t.state.cwd,f);a=await t.fs.readFile(d)}catch{let f=await P(t,l.target);return S(`bash: ${f}: No such file or directory
118
- `)}let c=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ne(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,s);let l=0,f=!1,d=!1,h=t.state.inCondition;t.state.inCondition=!0;try{for(let m of e.condition){let y=await t.executeStatement(m);r+=y.stdout,s+=y.stderr,l=y.exitCode}}catch(m){if(m instanceof z){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=h,m;f=!0}else if(m instanceof K){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=h,m;d=!0}else throw t.state.inCondition=h,m}finally{t.state.inCondition=h}if(f)break;if(!d){if(l!==0)break;try{for(let m of e.body){let y=await t.executeStatement(m);r+=y.stdout,s+=y.stderr,o=y.exitCode}}catch(m){let y=We(m,r,s,t.state.loopDepth);if(r=y.stdout,s=y.stderr,y.action==="break")break;if(y.action==="continue")continue;if(y.action==="error")return x(r,s,y.exitCode??1);throw y.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=c}return x(r,s,o)}async function Rn(t,e){let n="",r="",s=0,o=0;t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&ne(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r);let i=await fr(t,e.condition);if(n+=i.stdout,r+=i.stderr,i.exitCode===0)break;try{for(let a of e.body){let c=await t.executeStatement(a);n+=c.stdout,r+=c.stderr,s=c.exitCode}}catch(a){let c=We(a,n,r,t.state.loopDepth);if(n=c.stdout,r=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return x(n,r,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return x(n,r,s)}async function Dn(t,e){let n="",r="",s=0,o=await P(t,e.word),i=!1;for(let a=0;a<e.items.length;a++){let c=e.items[a],l=i;if(!i)for(let f of c.patterns){let d=await P(t,f);if(sn(f)&&(d=on(d)),ut(o,d)){l=!0;break}}if(l){let f=await yt(t,c.body,n,r);if(n=f.stdout,r=f.stderr,s=f.exitCode,c.terminator===";;")break;c.terminator===";&"?i=!0:i=!1}else i=!1}return x(n,r,s)}function On(t,e){return t.state.functions.set(e.name,e),N}async function _n(t,e,n){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,ne(`${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<n.length;o++)r[String(o+1)]=t.state.env[String(o+1)],t.state.env[String(o+1)]=n[o];r["@"]=t.state.env["@"],r["#"]=t.state.env["#"],t.state.env["@"]=n.join(" "),t.state.env["#"]=String(n.length);let s=()=>{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 s(),o}catch(o){if(s(),o instanceof U)return x(o.stdout,o.stderr,o.exitCode);throw o}}async function Ln(t,e,n){let{stdout:r,stderr:s,exitCode:o}=e;for(let i of n){if(i.target.type==="HereDoc")continue;let a=await P(t,i.target);switch(i.operator){case">":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
119
- `,o=1,r="";break}}catch{}await t.fs.writeFile(l,r,"binary"),r=""}else if(c===2)if(a==="/dev/null")s="";else{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
120
- `,o=1;break}}catch{}await t.fs.writeFile(l,s,"binary"),s=""}break}case">>":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
121
- `,o=1,r="";break}}catch{}await t.fs.appendFile(l,r,"binary"),r=""}else if(c===2){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
122
- `,o=1;break}}catch{}await t.fs.appendFile(l,s,"binary"),s=""}break}case">&":{let c=i.fd??1;a==="2"||a==="&2"?c===1&&(s+=r,r=""):(a==="1"||a==="&1")&&(r+=s,s="");break}case"&>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
123
- `,o=1,r="";break}}catch{}await t.fs.writeFile(c,r+s,"binary"),r="",s="";break}case"&>>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
124
- `,o=1,r="";break}}catch{}await t.fs.appendFile(c,r+s,"binary"),r="",s="";break}}}return x(r,s,o)}var Fe=class{ctx;constructor(e,n){this.ctx={state:n,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,trace:e.trace}}async executeScript(e){let n="",r="",s=0;for(let o of e.statements)try{let i=await this.executeStatement(o);n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(i){if(i instanceof k)throw i.prependOutput(n,r),i;if(i instanceof B)throw i;if(i instanceof Y)return n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof X)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof me)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof z||i instanceof K){if(this.ctx.state.loopDepth>0)throw i.prependOutput(n,r),i;n+=i.stdout,r+=i.stderr;continue}throw i instanceof U&&i.prependOutput(n,r),i}return{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ne(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let n="",r="",s=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let c=e.pipelines[a],l=a>0?e.operators[a-1]:null;if(l==="&&"&&s!==0||l==="||"&&s===0)continue;let f=await this.executePipeline(c);n+=f.stdout,r+=f.stderr,s=f.exitCode,o=a,i=c.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new Y(s,n,r);return x(n,r,s)}async executePipeline(e){let n="",r=N,s=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],c=i===e.commands.length-1,l;try{l=await this.executeCommand(a,n)}catch(f){if(f instanceof me)l={stdout:f.stdout,stderr:f.stderr,exitCode:1};else if(f instanceof k&&e.commands.length>1)l={stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode};else throw f}o.push(l.exitCode),l.exitCode!==0&&(s=l.exitCode),c?r=l:(n=l.stdout,r={stdout:"",stderr:l.stderr,exitCode:l.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&&s!==0&&(r={...r,exitCode:s}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,n){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return $n(this.ctx,e);case"For":return Pn(this.ctx,e);case"CStyleFor":return In(this.ctx,e);case"While":return kn(this.ctx,e,n);case"Until":return Rn(this.ctx,e);case"Case":return Dn(this.ctx,e);case"Subshell":return this.executeSubshell(e,n);case"Group":return this.executeGroup(e,n);case"FunctionDef":return On(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return N}}async executeSimpleCommand(e,n){try{return await this.executeSimpleCommandInner(e,n)}catch(r){if(r instanceof W)return S(r.stderr);throw r}}async executeSimpleCommandInner(e,n){e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.expansionStderr="";let r={};for(let c of e.assignments){let l=c.name;if(c.array){if(/\[.+\]$/.test(l))return x("",`bash: ${l}: cannot assign list to array member
125
- `,1);let E=fe(this.ctx,l);if(E)return E;let p=[];for(let g of c.array){let b=await Te(this.ctx,g);p.push(...b.values)}let w=0;if(c.append){let g=T(this.ctx,l);g.length>0&&(w=Math.max(...g.map(([C])=>typeof C=="number"?C:0))+1)}else{let g=`${l}_`;for(let b of Object.keys(this.ctx.state.env))b.startsWith(g)&&!b.includes("__")&&delete this.ctx.state.env[b]}for(let g=0;g<p.length;g++)this.ctx.state.env[`${l}_${w+g}`]=p[g];c.append||(this.ctx.state.env[`${l}__length`]=String(p.length));continue}let f=c.value?await P(this.ctx,c.value):"";if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return x("",`bash: ${l}: bad array subscript
126
- `,1);let h=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let E=h[1],p=h[2],w=fe(this.ctx,E);if(w)return w;let g=this.ctx.state.associativeArrays?.has(E),b;if(g){let I;if(p.startsWith("'")&&p.endsWith("'"))I=p.slice(1,-1);else if(p.startsWith('"')&&p.endsWith('"')){let R=p.slice(1,-1),_=new M().parseWordFromString(R,!0,!1);I=await P(this.ctx,_)}else if(p.includes("$")){let he=new M().parseWordFromString(p,!1,!1);I=await P(this.ctx,he)}else I=p;b=`${E}_${I}`}else{let I;if(/^-?\d+$/.test(p))I=Number.parseInt(p,10);else{try{let R=new M,he=L(R,p);I=v(this.ctx,he.expression)}catch{let R=this.ctx.state.env[p];I=R?Number.parseInt(R,10):0}Number.isNaN(I)&&(I=0)}if(I<0){let R=T(this.ctx,E);if(R.length===0)return x("",`bash: ${E}[${p}]: bad array subscript
127
- `,1);if(I=Math.max(...R.map(([_])=>typeof _=="number"?_:0))+1+I,I<0)return x("",`bash: ${E}[${p}]: bad array subscript
128
- `,1)}b=`${E}_${I}`}let C=c.append?(this.ctx.state.env[b]||"")+f:f;e.name?(r[b]=this.ctx.state.env[b],this.ctx.state.env[b]=C):this.ctx.state.env[b]=C;continue}let m=fe(this.ctx,l);if(m)return m;let y=c.append?(this.ctx.state.env[l]||"")+f:f;e.name?(r[l]=this.ctx.state.env[l],this.ctx.state.env[l]=y):this.ctx.state.env[l]=y}if(!e.name)return x("","",this.ctx.state.lastExitCode);for(let c of e.redirections){if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let l=c.target,f=await P(this.ctx,l.content);l.stripTabs&&(f=f.split(`
116
+ `)),a=d}else if(c.operator==="<<<"&&c.target.type==="Word")a=`${await P(t,c.target)}
117
+ `;else if(c.operator==="<"&&c.target.type==="Word")try{let f=await P(t,c.target),d=t.fs.resolvePath(t.state.cwd,f);a=await t.fs.readFile(d)}catch{let f=await P(t,c.target);return x(`bash: ${f}: No such file or directory
118
+ `)}let l=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ne(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,s);let c=0,f=!1,d=!1,h=t.state.inCondition;t.state.inCondition=!0;try{for(let m of e.condition){let y=await t.executeStatement(m);r+=y.stdout,s+=y.stderr,c=y.exitCode}}catch(m){if(m instanceof z){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=h,m;f=!0}else if(m instanceof K){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=h,m;d=!0}else throw t.state.inCondition=h,m}finally{t.state.inCondition=h}if(f)break;if(!d){if(c!==0)break;try{for(let m of e.body){let y=await t.executeStatement(m);r+=y.stdout,s+=y.stderr,o=y.exitCode}}catch(m){let y=We(m,r,s,t.state.loopDepth);if(r=y.stdout,s=y.stderr,y.action==="break")break;if(y.action==="continue")continue;if(y.action==="error")return S(r,s,y.exitCode??1);throw y.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=l}return S(r,s,o)}async function Rn(t,e){let n="",r="",s=0,o=0;t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&ne(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r);let i=await fr(t,e.condition);if(n+=i.stdout,r+=i.stderr,i.exitCode===0)break;try{for(let a of e.body){let l=await t.executeStatement(a);n+=l.stdout,r+=l.stderr,s=l.exitCode}}catch(a){let l=We(a,n,r,t.state.loopDepth);if(n=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return S(n,r,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return S(n,r,s)}async function Dn(t,e){let n="",r="",s=0,o=await P(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 d=await P(t,f);if(sn(f)&&(d=on(d)),ut(o,d)){c=!0;break}}if(c){let f=await yt(t,l.body,n,r);if(n=f.stdout,r=f.stderr,s=f.exitCode,l.terminator===";;")break;l.terminator===";&"?i=!0:i=!1}else i=!1}return S(n,r,s)}function On(t,e){return t.state.functions.set(e.name,e),N}async function _n(t,e,n){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,ne(`${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<n.length;o++)r[String(o+1)]=t.state.env[String(o+1)],t.state.env[String(o+1)]=n[o];r["@"]=t.state.env["@"],r["#"]=t.state.env["#"],t.state.env["@"]=n.join(" "),t.state.env["#"]=String(n.length);let s=()=>{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 s(),o}catch(o){if(s(),o instanceof U)return S(o.stdout,o.stderr,o.exitCode);throw o}}async function Ln(t,e,n){let{stdout:r,stderr:s,exitCode:o}=e;for(let i of n){if(i.target.type==="HereDoc")continue;let a=await P(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){s+=`bash: ${a}: Is a directory
119
+ `,o=1,r="";break}}catch{}await t.fs.writeFile(c,r,"binary"),r=""}else if(l===2)if(a==="/dev/null")s="";else{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${a}: Is a directory
120
+ `,o=1;break}}catch{}await t.fs.writeFile(c,s,"binary"),s=""}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){s+=`bash: ${a}: Is a directory
121
+ `,o=1,r="";break}}catch{}await t.fs.appendFile(c,r,"binary"),r=""}else if(l===2){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${a}: Is a directory
122
+ `,o=1;break}}catch{}await t.fs.appendFile(c,s,"binary"),s=""}break}case">&":{let l=i.fd??1;a==="2"||a==="&2"?l===1&&(s+=r,r=""):(a==="1"||a==="&1")&&(r+=s,s="");break}case"&>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${a}: Is a directory
123
+ `,o=1,r="";break}}catch{}await t.fs.writeFile(l,r+s,"binary"),r="",s="";break}case"&>>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${a}: Is a directory
124
+ `,o=1,r="";break}}catch{}await t.fs.appendFile(l,r+s,"binary"),r="",s="";break}}}return S(r,s,o)}var Fe=class{ctx;constructor(e,n){this.ctx={state:n,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,trace:e.trace}}async executeScript(e){let n="",r="",s=0;for(let o of e.statements)try{let i=await this.executeStatement(o);n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(i){if(i instanceof k)throw i.prependOutput(n,r),i;if(i instanceof B)throw i;if(i instanceof Y)return n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof X)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof me)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof z||i instanceof K){if(this.ctx.state.loopDepth>0)throw i.prependOutput(n,r),i;n+=i.stdout,r+=i.stderr;continue}throw i instanceof U&&i.prependOutput(n,r),i}return{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ne(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let n="",r="",s=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==="&&"&&s!==0||c==="||"&&s===0)continue;let f=await this.executePipeline(l);n+=f.stdout,r+=f.stderr,s=f.exitCode,o=a,i=l.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new Y(s,n,r);return S(n,r,s)}async executePipeline(e){let n="",r=N,s=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,n)}catch(f){if(f instanceof me)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&&(s=c.exitCode),l?r=c:(n=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&&s!==0&&(r={...r,exitCode:s}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,n){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return $n(this.ctx,e);case"For":return Pn(this.ctx,e);case"CStyleFor":return In(this.ctx,e);case"While":return kn(this.ctx,e,n);case"Until":return Rn(this.ctx,e);case"Case":return Dn(this.ctx,e);case"Subshell":return this.executeSubshell(e,n);case"Group":return this.executeGroup(e,n);case"FunctionDef":return On(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return N}}async executeSimpleCommand(e,n){try{return await this.executeSimpleCommandInner(e,n)}catch(r){if(r instanceof W)return x(r.stderr);throw r}}async executeSimpleCommandInner(e,n){e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.expansionStderr="";let r={};for(let l of e.assignments){let c=l.name;if(l.array){if(/\[.+\]$/.test(c))return S("",`bash: ${c}: cannot assign list to array member
125
+ `,1);let E=fe(this.ctx,c);if(E)return E;let p=[];for(let g of l.array){let b=await Te(this.ctx,g);p.push(...b.values)}let w=0;if(l.append){let g=T(this.ctx,c);g.length>0&&(w=Math.max(...g.map(([C])=>typeof C=="number"?C:0))+1)}else{let g=`${c}_`;for(let b of Object.keys(this.ctx.state.env))b.startsWith(g)&&!b.includes("__")&&delete this.ctx.state.env[b]}for(let g=0;g<p.length;g++)this.ctx.state.env[`${c}_${w+g}`]=p[g];l.append||(this.ctx.state.env[`${c}__length`]=String(p.length));continue}let f=l.value?await P(this.ctx,l.value):"";if(c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return S("",`bash: ${c}: bad array subscript
126
+ `,1);let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let E=h[1],p=h[2],w=fe(this.ctx,E);if(w)return w;let g=this.ctx.state.associativeArrays?.has(E),b;if(g){let I;if(p.startsWith("'")&&p.endsWith("'"))I=p.slice(1,-1);else if(p.startsWith('"')&&p.endsWith('"')){let R=p.slice(1,-1),_=new M().parseWordFromString(R,!0,!1);I=await P(this.ctx,_)}else if(p.includes("$")){let he=new M().parseWordFromString(p,!1,!1);I=await P(this.ctx,he)}else I=p;b=`${E}_${I}`}else{let I;if(/^-?\d+$/.test(p))I=Number.parseInt(p,10);else{try{let R=new M,he=L(R,p);I=v(this.ctx,he.expression)}catch{let R=this.ctx.state.env[p];I=R?Number.parseInt(R,10):0}Number.isNaN(I)&&(I=0)}if(I<0){let R=T(this.ctx,E);if(R.length===0)return S("",`bash: ${E}[${p}]: bad array subscript
127
+ `,1);if(I=Math.max(...R.map(([_])=>typeof _=="number"?_:0))+1+I,I<0)return S("",`bash: ${E}[${p}]: bad array subscript
128
+ `,1)}b=`${E}_${I}`}let C=l.append?(this.ctx.state.env[b]||"")+f:f;e.name?(r[b]=this.ctx.state.env[b],this.ctx.state.env[b]=C):this.ctx.state.env[b]=C;continue}let m=fe(this.ctx,c);if(m)return m;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 S("","",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 P(this.ctx,c.content);c.stripTabs&&(f=f.split(`
129
129
  `).map(d=>d.replace(/^\t+/,"")).join(`
130
- `)),n=f;continue}if(c.operator==="<<<"&&c.target.type==="Word"){n=`${await P(this.ctx,c.target)}
131
- `;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await P(this.ctx,c.target),f=this.ctx.fs.resolvePath(this.ctx.state.cwd,l);n=await this.ctx.fs.readFile(f)}catch{let l=await P(this.ctx,c.target);for(let[f,d]of Object.entries(r))d===void 0?delete this.ctx.state.env[f]:this.ctx.state.env[f]=d;return S(`bash: ${l}: No such file or directory
132
- `)}}let s=await P(this.ctx,e.name),o=[],i=[];for(let c of e.args){let l=await Te(this.ctx,c);for(let f of l.values)o.push(f),i.push(l.quoted)}if(!s){if(e.name.parts.every(l=>l.type==="CommandSubstitution"||l.type==="ParameterExpansion"||l.type==="ArithmeticExpansion")){if(o.length>0){let l=o.shift();return i.shift(),await this.runCommand(l,o,i,n)}return x("","",this.ctx.state.lastExitCode)}return S(`bash: : command not found
133
- `,127)}let a=await this.runCommand(s,o,i,n);a=await Ln(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:s;for(let[c,l]of Object.entries(r))l===void 0?delete this.ctx.state.env[c]:this.ctx.state.env[c]=l;return this.ctx.state.expansionStderr&&(a={...a,stderr:this.ctx.state.expansionStderr+a.stderr},this.ctx.state.expansionStderr=""),a}async runCommand(e,n,r,s,o=!1){if(e==="cd")return await jt(this.ctx,n);if(e==="export")return Kt(this.ctx,n);if(e==="unset")return or(this.ctx,n);if(e==="exit")return Qt(this.ctx,n);if(e==="local")return Yt(this.ctx,n);if(e==="set")return nr(this.ctx,n);if(e==="break")return Ut(this.ctx,n);if(e==="continue")return Gt(this.ctx,n);if(e==="return")return tr(this.ctx,n);if(e==="eval")return Zt(this.ctx,n);if(e==="shift")return sr(this.ctx,n);if(e==="source"||e===".")return ir(this.ctx,n);if(e==="read")return er(this.ctx,n,s);if(e==="mapfile"||e==="readarray")return Jt(this.ctx,n,s);if(e==="declare"||e==="typeset")return Vt(this.ctx,n);if(e==="readonly")return qt(this.ctx,n);if(!o){let f=this.ctx.state.functions.get(e);if(f)return _n(this.ctx,f,n)}if(e===":"||e==="true")return N;if(e==="false")return O(!1);if(e==="let")return Xt(this.ctx,n);if(e==="command"){if(n.length===0)return N;let f=n;for(;f.length>0&&f[0].startsWith("-");)f=f.slice(1);if(f.length===0)return N;let[d,...h]=f;return this.runCommand(d,h,[],s,!0)}if(e==="builtin"){if(n.length===0)return N;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="shopt")return N;if(e==="exec"){if(n.length===0)return N;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="wait")return N;if(e==="type")return this.handleType(n);if(e==="[["){let f=n.lastIndexOf("]]");if(f!==-1){let d=n.slice(0,f);return $e(this.ctx,d)}return S("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let f=n;if(e==="["){if(n[n.length-1]!=="]")return S("[: missing `]'\n",2);f=n.slice(0,-1)}return $e(this.ctx,f)}let i=await this.resolveCommand(e);if(!i)return br(e)?S(`bash: ${e}: command not available in browser environments. Exclude '${e}' from your commands or use the Node.js bundle.
134
- `,127):S(`bash: ${e}: command not found
135
- `,127);let{cmd:a,path:c}=i,l={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep,trace:this.ctx.trace};try{return await a.execute(n,l)}catch(f){return S(`${e}: ${se(f)}
130
+ `)),n=f;continue}if(l.operator==="<<<"&&l.target.type==="Word"){n=`${await P(this.ctx,l.target)}
131
+ `;continue}if(l.operator==="<"&&l.target.type==="Word")try{let c=await P(this.ctx,l.target),f=this.ctx.fs.resolvePath(this.ctx.state.cwd,c);n=await this.ctx.fs.readFile(f)}catch{let c=await P(this.ctx,l.target);for(let[f,d]of Object.entries(r))d===void 0?delete this.ctx.state.env[f]:this.ctx.state.env[f]=d;return x(`bash: ${c}: No such file or directory
132
+ `)}}let s=await P(this.ctx,e.name),o=[],i=[];for(let l of e.args){let c=await Te(this.ctx,l);for(let f of c.values)o.push(f),i.push(c.quoted)}if(!s){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,n)}return S("","",this.ctx.state.lastExitCode)}return x(`bash: : command not found
133
+ `,127)}let a=await this.runCommand(s,o,i,n);a=await Ln(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:s;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,n,r,s,o=!1){if(e==="cd")return await jt(this.ctx,n);if(e==="export")return Kt(this.ctx,n);if(e==="unset")return or(this.ctx,n);if(e==="exit")return Qt(this.ctx,n);if(e==="local")return Yt(this.ctx,n);if(e==="set")return nr(this.ctx,n);if(e==="break")return Ut(this.ctx,n);if(e==="continue")return Gt(this.ctx,n);if(e==="return")return tr(this.ctx,n);if(e==="eval")return Zt(this.ctx,n);if(e==="shift")return sr(this.ctx,n);if(e==="source"||e===".")return ir(this.ctx,n);if(e==="read")return er(this.ctx,n,s);if(e==="mapfile"||e==="readarray")return Jt(this.ctx,n,s);if(e==="declare"||e==="typeset")return Vt(this.ctx,n);if(e==="readonly")return qt(this.ctx,n);if(!o){let f=this.ctx.state.functions.get(e);if(f)return _n(this.ctx,f,n)}if(e===":"||e==="true")return N;if(e==="false")return O(!1);if(e==="let")return Xt(this.ctx,n);if(e==="command"){if(n.length===0)return N;let f=n;for(;f.length>0&&f[0].startsWith("-");)f=f.slice(1);if(f.length===0)return N;let[d,...h]=f;return this.runCommand(d,h,[],s,!0)}if(e==="builtin"){if(n.length===0)return N;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="shopt")return N;if(e==="exec"){if(n.length===0)return N;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="wait")return N;if(e==="type")return this.handleType(n);if(e==="[["){let f=n.lastIndexOf("]]");if(f!==-1){let d=n.slice(0,f);return $e(this.ctx,d)}return x("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let f=n;if(e==="["){if(n[n.length-1]!=="]")return x("[: missing `]'\n",2);f=n.slice(0,-1)}return $e(this.ctx,f)}let i=await this.resolveCommand(e);if(!i)return br(e)?x(`bash: ${e}: command not available in browser environments. Exclude '${e}' from your commands or use the Node.js bundle.
134
+ `,127):x(`bash: ${e}: command not found
135
+ `,127);let{cmd:a,path:l}=i,c={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep,trace:this.ctx.trace};try{return await a.execute(n,c)}catch(f){return x(`${e}: ${se(f)}
136
136
  `)}}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 n=[],s=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of s){if(!o)continue;let i=`${o}/${e}`;await this.ctx.fs.exists(i)&&n.push(i)}return n}handleType(e){let n=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"]),s="",o="",i=0;for(let a of e)n.has(a)?s+=`${a} is a shell keyword
137
137
  `:r.has(a)?s+=`${a} is a shell builtin
138
138
  `:this.ctx.state.functions.has(a)?s+=`${a} is a function
139
139
  `:this.ctx.commands.has(a)?s+=`${a} is /bin/${a}
140
140
  `:(o+=`bash: type: ${a}: not found
141
- `,i=1);return x(s,o,i)}async executeSubshell(e,n=""){let r={...this.ctx.state.env},s=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;n&&(this.ctx.state.groupStdin=n);let c="",l="",f=0;try{for(let d of e.body){let h=await this.executeStatement(d);c+=h.stdout,l+=h.stderr,f=h.exitCode}}catch(d){if(this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,d instanceof B)throw d;if(d instanceof ie)return c+=d.stdout,l+=d.stderr,x(c,l,0);if(d instanceof z||d instanceof K)return c+=d.stdout,l+=d.stderr,x(c,l,0);if(d instanceof k)return c+=d.stdout,l+=d.stderr,x(c,l,d.exitCode);if(d instanceof U)return c+=d.stdout,l+=d.stderr,x(c,l,d.exitCode);if(d instanceof Y)throw d.stdout=c+d.stdout,d.stderr=l+d.stderr,d;return x(c,`${l}${se(d)}
142
- `,1)}return this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,x(c,l,f)}async executeGroup(e,n=""){let r="",s="",o=0,i=this.ctx.state.groupStdin;n&&(this.ctx.state.groupStdin=n);try{for(let a of e.body){let c=await this.executeStatement(a);r+=c.stdout,s+=c.stderr,o=c.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof B)throw a;if(Ue(a)||a instanceof Y||a instanceof k)throw a.prependOutput(r,s),a;return x(r,`${s}${se(a)}
143
- `,1)}return this.ctx.state.groupStdin=i,x(r,s,o)}async executeArithmeticCommand(e){try{let n=await $(this.ctx,e.expression.expression);return O(n!==0)}catch(n){return S(`bash: arithmetic expression: ${n.message}
144
- `)}}async executeConditionalCommand(e){try{let n=await ue(this.ctx,e.expression);return O(n)}catch(n){return S(`bash: conditional expression: ${n.message}
145
- `,2)}}};var de={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3};function Tn(t){return t?{maxCallDepth:t.maxCallDepth??de.maxCallDepth,maxCommandCount:t.maxCommandCount??de.maxCommandCount,maxLoopIterations:t.maxLoopIterations??de.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??de.maxAwkIterations,maxSedIterations:t.maxSedIterations??de.maxSedIterations,maxJqIterations:t.maxJqIterations??de.maxJqIterations,maxSqliteTimeoutMs:t.maxSqliteTimeoutMs??de.maxSqliteTimeoutMs}:{...de}}function Wn(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function Ks(t){let e=Wn(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function Xs(t,e){let n=Wn(t);if(!n)return!1;let r=Ks(e);return!r||n.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:n.pathname.startsWith(r.pathPrefix)}function ur(t,e){return!e||e.length===0?!1:e.some(n=>Xs(t,n))}var Me=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Be=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},ze=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},wt=class extends Error{constructor(e,n){super(`HTTP method '${e}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}};var Ys=20,Js=3e4,ei=["GET","HEAD"],ti=new Set(["GET","HEAD","OPTIONS"]),ri=new Set([301,302,303,307,308]);function dr(t){let e=t.maxRedirects??Ys,n=t.timeoutMs??Js,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ei;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!ur(a,t.allowedUrlPrefixes??[]))throw new Me(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let c=a.toUpperCase();if(!r.includes(c))throw new wt(c,r)}async function i(a,c={}){let l=c.method?.toUpperCase()??"GET";s(a),o(l);let f=a,d=0,h=c.followRedirects??!0,m=c.timeoutMs!==void 0?Math.min(c.timeoutMs,n):n;for(;;){let y=new AbortController,E=setTimeout(()=>y.abort(),m);try{let p={method:l,headers:c.headers,signal:y.signal,redirect:"manual"};c.body&&!ti.has(l)&&(p.body=c.body);let w=await fetch(f,p);if(ri.has(w.status)&&h){let g=w.headers.get("location");if(!g)return await Fn(w,f);let b=new URL(g,f).href;if(!t.dangerouslyAllowFullInternetAccess&&!ur(b,t.allowedUrlPrefixes??[]))throw new ze(b);if(d++,d>e)throw new Be(e);f=b;continue}return await Fn(w,f)}finally{clearTimeout(E)}}}return i}async function Fn(t,e){let n={};return t.headers.forEach((r,s)=>{n[s.toLowerCase()]=r}),{status:t.status,statusText:t.statusText,headers:n,body:await t.text(),url:e}}var Et=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;state;constructor(e={}){let n=e.fs??new ke(e.files);this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
146
- `,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=Tn({...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=dr(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.state={env:s,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},Sr(n,this.useDefaultLayout),r!=="/"&&n instanceof ke)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of pr(e.commands))this.registerCommand(o);if(e.network)for(let o of yr())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)wr(o)?this.registerCommand(Er(o)):this.registerCommand(o)}registerCommand(e){this.commands.set(e.name,e);let n=this.fs;if(typeof n.writeFileSync=="function")try{n.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
141
+ `,i=1);return S(s,o,i)}async executeSubshell(e,n=""){let r={...this.ctx.state.env},s=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;n&&(this.ctx.state.groupStdin=n);let l="",c="",f=0;try{for(let d of e.body){let h=await this.executeStatement(d);l+=h.stdout,c+=h.stderr,f=h.exitCode}}catch(d){if(this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,d instanceof B)throw d;if(d instanceof ie)return l+=d.stdout,c+=d.stderr,S(l,c,0);if(d instanceof z||d instanceof K)return l+=d.stdout,c+=d.stderr,S(l,c,0);if(d instanceof k)return l+=d.stdout,c+=d.stderr,S(l,c,d.exitCode);if(d instanceof U)return l+=d.stdout,c+=d.stderr,S(l,c,d.exitCode);if(d instanceof Y)throw d.stdout=l+d.stdout,d.stderr=c+d.stderr,d;return S(l,`${c}${se(d)}
142
+ `,1)}return this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,S(l,c,f)}async executeGroup(e,n=""){let r="",s="",o=0,i=this.ctx.state.groupStdin;n&&(this.ctx.state.groupStdin=n);try{for(let a of e.body){let l=await this.executeStatement(a);r+=l.stdout,s+=l.stderr,o=l.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof B)throw a;if(Ue(a)||a instanceof Y||a instanceof k)throw a.prependOutput(r,s),a;return S(r,`${s}${se(a)}
143
+ `,1)}return this.ctx.state.groupStdin=i,S(r,s,o)}async executeArithmeticCommand(e){try{let n=await $(this.ctx,e.expression.expression);return O(n!==0)}catch(n){return x(`bash: arithmetic expression: ${n.message}
144
+ `)}}async executeConditionalCommand(e){try{let n=await ue(this.ctx,e.expression);return O(n)}catch(n){return x(`bash: conditional expression: ${n.message}
145
+ `,2)}}};var de={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3};function Tn(t){return t?{maxCallDepth:t.maxCallDepth??de.maxCallDepth,maxCommandCount:t.maxCommandCount??de.maxCommandCount,maxLoopIterations:t.maxLoopIterations??de.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??de.maxAwkIterations,maxSedIterations:t.maxSedIterations??de.maxSedIterations,maxJqIterations:t.maxJqIterations??de.maxJqIterations,maxSqliteTimeoutMs:t.maxSqliteTimeoutMs??de.maxSqliteTimeoutMs}:{...de}}function Wn(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function Ks(t){let e=Wn(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function Xs(t,e){let n=Wn(t);if(!n)return!1;let r=Ks(e);return!r||n.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:n.pathname.startsWith(r.pathPrefix)}function ur(t,e){return!e||e.length===0?!1:e.some(n=>Xs(t,n))}var Me=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Be=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},ze=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},wt=class extends Error{constructor(e,n){super(`HTTP method '${e}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}};var Ys=20,Js=3e4,ei=["GET","HEAD"],ti=new Set(["GET","HEAD","OPTIONS"]),ri=new Set([301,302,303,307,308]);function dr(t){let e=t.maxRedirects??Ys,n=t.timeoutMs??Js,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ei;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!ur(a,t.allowedUrlPrefixes??[]))throw new Me(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let l=a.toUpperCase();if(!r.includes(l))throw new wt(l,r)}async function i(a,l={}){let c=l.method?.toUpperCase()??"GET";s(a),o(c);let f=a,d=0,h=l.followRedirects??!0,m=l.timeoutMs!==void 0?Math.min(l.timeoutMs,n):n;for(;;){let y=new AbortController,E=setTimeout(()=>y.abort(),m);try{let p={method:c,headers:l.headers,signal:y.signal,redirect:"manual"};l.body&&!ti.has(c)&&(p.body=l.body);let w=await fetch(f,p);if(ri.has(w.status)&&h){let g=w.headers.get("location");if(!g)return await Fn(w,f);let b=new URL(g,f).href;if(!t.dangerouslyAllowFullInternetAccess&&!ur(b,t.allowedUrlPrefixes??[]))throw new ze(b);if(d++,d>e)throw new Be(e);f=b;continue}return await Fn(w,f)}finally{clearTimeout(E)}}}return i}async function Fn(t,e){let n={};return t.headers.forEach((r,s)=>{n[s.toLowerCase()]=r}),{status:t.status,statusText:t.statusText,headers:n,body:await t.text(),url:e}}var Et=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;state;constructor(e={}){let n=e.fs??new ke(e.files);this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
146
+ `,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=Tn({...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=dr(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.state={env:s,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},xr(n,this.useDefaultLayout),r!=="/"&&n instanceof ke)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of pr(e.commands))this.registerCommand(o);if(e.network)for(let o of yr())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)wr(o)?this.registerCommand(Er(o)):this.registerCommand(o)}registerCommand(e){this.commands.set(e.name,e);let n=this.fs;if(typeof n.writeFileSync=="function")try{n.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
147
147
  # Built-in command: ${e.name}
148
148
  `)}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,n){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.
149
149
  `,exitCode:1,env:{...this.state.env,...n?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...n?.env}};this.logger?.info("exec",{command:e});let r=n?.cwd??this.state.cwd,s={...this.state,env:{...this.state.env,...n?.env,...n?.cwd?{PWD:n.cwd}:{}},cwd:r,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},o=e;n?.rawScript||(o=e.split(`
150
150
  `).map(a=>a.trimStart()).join(`
151
- `));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,trace:this.traceFn},l=await new Fe(a,s).executeScript(i);return this.logResult(l)}catch(i){if(i instanceof k)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...n?.env}});if(i instanceof W)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...n?.env}});if(i instanceof B)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:B.EXIT_CODE,env:{...this.state.env,...n?.env}});if(i.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${i.message}
151
+ `));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,trace:this.traceFn},c=await new Fe(a,s).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,...n?.env}});if(i instanceof W)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...n?.env}});if(i instanceof B)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:B.EXIT_CODE,env:{...this.state.env,...n?.env}});if(i.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${i.message}
152
152
  `,exitCode:2,env:{...this.state.env,...n?.env}});if(i instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${i.message}
153
- `,exitCode:1,env:{...this.state.env,...n?.env}});throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),n)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};import*as F from"node:fs";import*as Pe from"node:path";var ni="/home/user/project",Ie=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Pe.resolve(e.root);let n=e.mountPoint??ni;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=e.readOnly??!1,!F.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!F.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),n="";for(let r of e)n+=`/${r}`,this.memory.has(n)||this.memory.set(n,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(e,n){let s=this.normalizePath(e).split("/").filter(Boolean),o="";for(let i of s)o+=`/${i}`,this.memory.has(o)||this.memory.set(o,{type:"directory",mode:493,mtime:new Date})}writeFileSync(e,n){let r=this.normalizePath(e),s=this.getDirname(r);s!=="/"&&this.mkdirSync(s);let o=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.memory.set(r,{type:"file",content:o,mode:420,mtime:new Date})}getDirname(e){let n=e.lastIndexOf("/");return n===0?"/":e.slice(0,n)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let n=this.normalizePath(e),r=this.getRelativeToMount(n);if(r===null)return null;let s=Pe.join(this.root,r),o=Pe.resolve(s);return!o.startsWith(this.root)&&o!==this.root.replace(/\/$/,"")?null:o}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.memory.has(n)||(this.ensureParentDirs(n),this.memory.set(n,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(n))}async existsInOverlay(e){let n=this.normalizePath(e);if(this.deleted.has(n))return!1;if(this.memory.has(n))return!0;let r=this.toRealPath(n);if(!r)return!1;try{return await F.promises.access(r),!0}catch{return!1}}async readFile(e,n){let r=await this.readFileBuffer(e),s=oe(n);return je(r,s)}async readFileBuffer(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let i=this.resolveSymlink(r,s.target);return this.readFileBuffer(i,n)}if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return s.content}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let i=await F.promises.lstat(o);if(i.isSymbolicLink()){let c=await F.promises.readlink(o),l=this.resolveSymlink(r,c);return this.readFileBuffer(l,n)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await F.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,n,r){this.assertWritable(`write '${e}'`);let s=this.normalizePath(e);this.ensureParentDirs(s);let o=oe(r),i=Ae(n,o);this.memory.set(s,{type:"file",content:i,mode:420,mtime:new Date}),this.deleted.delete(s)}async appendFile(e,n,r){this.assertWritable(`append '${e}'`);let s=this.normalizePath(e),o=oe(r),i=Ae(n,o),a;try{a=await this.readFileBuffer(s)}catch{a=new Uint8Array(0)}let c=new Uint8Array(a.length+i.length);c.set(a),c.set(i,a.length),this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:c,mode:420,mtime:new Date}),this.deleted.delete(s)}async exists(e){return this.existsInOverlay(e)}async stat(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let a=this.resolveSymlink(r,s.target);return this.stat(a,n)}let i=0;return s.type==="file"&&(i=s.content.length),{isFile:s.type==="file",isDirectory:s.type==="directory",isSymbolicLink:!1,mode:s.mode,size:i,mtime:s.mtime}}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let i=await F.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 n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);let r=this.memory.get(n);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 s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let o=await F.promises.lstat(s);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,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let o=this.dirname(r);if(o!=="/"&&!await this.existsInOverlay(o))if(n?.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 readdirCore(e,n){if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Map,s=new Set,o=n==="/"?"/":`${n}/`;for(let a of this.deleted)if(a.startsWith(o)){let c=a.slice(o.length),l=c.split("/")[0];l&&!c.includes("/",l.length)&&s.add(l)}for(let[a,c]of this.memory)if(a!==n&&a.startsWith(o)){let l=a.slice(o.length),f=l.split("/")[0];f&&!s.has(f)&&!l.includes("/",1)&&r.set(f,{name:f,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}let i=this.toRealPath(n);if(i)try{let a=await F.promises.readdir(i,{withFileTypes:!0});for(let c of a)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async resolveForReaddir(e,n=!1){let r=this.normalizePath(e),s=new Set,o=n,i=this.memory.get(r);for(;i&&i.type==="symlink";){if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);s.add(r),o=!0,r=this.resolveSymlink(r,i.target),i=this.memory.get(r)}if(i)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let c=this.toRealPath(r);if(!c)return{normalized:r,outsideOverlay:!0};try{if((await F.promises.lstat(c)).isSymbolicLink()){let f=await F.promises.readlink(c),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return o?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(e){let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.keys()).sort((o,i)=>o<i?-1:o>i?1:0)}async readdirWithFileTypes(e){let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.values()).sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}async rm(e,n){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(n?.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(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let c=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(c,n)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,n,r){this.assertWritable(`cp '${n}'`);let s=this.normalizePath(e),o=this.normalizePath(n);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(s);if(a.isFile){let c=await this.readFileBuffer(s);await this.writeFile(o,c)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let c=await this.readdir(s);for(let l of c){let f=s==="/"?`/${l}`:`${s}/${l}`,d=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(f,d,r)}}}async mv(e,n){this.assertWritable(`mv '${n}'`),await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let n of this.deleted)e.delete(n);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,n){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let s=F.readdirSync(r);for(let o of s){let i=e==="/"?`/${o}`:`${e}/${o}`;if(this.deleted.has(i))continue;n.add(i);let a=Pe.join(r,o);F.statSync(a).isDirectory()&&this.scanRealFs(i,n)}}catch{}}async chmod(e,n){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=n;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:n,mtime:new Date})}else i.isDirectory&&this.memory.set(r,{type:"directory",mode:n,mtime:new Date})}async symlink(e,n){this.assertWritable(`symlink '${n}'`);let r=this.normalizePath(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,n){this.assertWritable(`link '${n}'`);let r=this.normalizePath(e),s=this.normalizePath(n);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(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let c=await this.readFileBuffer(r);this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:c,mode:i.mode,mtime:new Date}),this.deleted.delete(s)}async readlink(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(n);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await F.promises.readlink(s)}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 Bn(){console.log(`just-bash - A secure bash environment for AI agents
153
+ `,exitCode:1,env:{...this.state.env,...n?.env}});throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),n)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};import*as F from"node:fs";import*as Pe from"node:path";var ni="/home/user/project",Ie=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Pe.resolve(e.root);let n=e.mountPoint??ni;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=e.readOnly??!1,!F.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!F.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),n="";for(let r of e)n+=`/${r}`,this.memory.has(n)||this.memory.set(n,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(e,n){let s=this.normalizePath(e).split("/").filter(Boolean),o="";for(let i of s)o+=`/${i}`,this.memory.has(o)||this.memory.set(o,{type:"directory",mode:493,mtime:new Date})}writeFileSync(e,n){let r=this.normalizePath(e),s=this.getDirname(r);s!=="/"&&this.mkdirSync(s);let o=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.memory.set(r,{type:"file",content:o,mode:420,mtime:new Date})}getDirname(e){let n=e.lastIndexOf("/");return n===0?"/":e.slice(0,n)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let n=this.normalizePath(e),r=this.getRelativeToMount(n);if(r===null)return null;let s=Pe.join(this.root,r),o=Pe.resolve(s);return!o.startsWith(this.root)&&o!==this.root.replace(/\/$/,"")?null:o}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.memory.has(n)||(this.ensureParentDirs(n),this.memory.set(n,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(n))}async existsInOverlay(e){let n=this.normalizePath(e);if(this.deleted.has(n))return!1;if(this.memory.has(n))return!0;let r=this.toRealPath(n);if(!r)return!1;try{return await F.promises.access(r),!0}catch{return!1}}async readFile(e,n){let r=await this.readFileBuffer(e),s=oe(n);return je(r,s)}async readFileBuffer(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let i=this.resolveSymlink(r,s.target);return this.readFileBuffer(i,n)}if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return s.content}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let i=await F.promises.lstat(o);if(i.isSymbolicLink()){let l=await F.promises.readlink(o),c=this.resolveSymlink(r,l);return this.readFileBuffer(c,n)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await F.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,n,r){this.assertWritable(`write '${e}'`);let s=this.normalizePath(e);this.ensureParentDirs(s);let o=oe(r),i=Ae(n,o);this.memory.set(s,{type:"file",content:i,mode:420,mtime:new Date}),this.deleted.delete(s)}async appendFile(e,n,r){this.assertWritable(`append '${e}'`);let s=this.normalizePath(e),o=oe(r),i=Ae(n,o),a;try{a=await this.readFileBuffer(s)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+i.length);l.set(a),l.set(i,a.length),this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(s)}async exists(e){return this.existsInOverlay(e)}async stat(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let a=this.resolveSymlink(r,s.target);return this.stat(a,n)}let i=0;return s.type==="file"&&(i=s.content.length),{isFile:s.type==="file",isDirectory:s.type==="directory",isSymbolicLink:!1,mode:s.mode,size:i,mtime:s.mtime}}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let i=await F.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 n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);let r=this.memory.get(n);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 s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let o=await F.promises.lstat(s);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,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let o=this.dirname(r);if(o!=="/"&&!await this.existsInOverlay(o))if(n?.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 readdirCore(e,n){if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Map,s=new Set,o=n==="/"?"/":`${n}/`;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)&&s.add(c)}for(let[a,l]of this.memory)if(a!==n&&a.startsWith(o)){let c=a.slice(o.length),f=c.split("/")[0];f&&!s.has(f)&&!c.includes("/",1)&&r.set(f,{name:f,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let i=this.toRealPath(n);if(i)try{let a=await F.promises.readdir(i,{withFileTypes:!0});for(let l of a)!s.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async resolveForReaddir(e,n=!1){let r=this.normalizePath(e),s=new Set,o=n,i=this.memory.get(r);for(;i&&i.type==="symlink";){if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);s.add(r),o=!0,r=this.resolveSymlink(r,i.target),i=this.memory.get(r)}if(i)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.toRealPath(r);if(!l)return{normalized:r,outsideOverlay:!0};try{if((await F.promises.lstat(l)).isSymbolicLink()){let f=await F.promises.readlink(l),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return o?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(e){let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.keys()).sort((o,i)=>o<i?-1:o>i?1:0)}async readdirWithFileTypes(e){let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.values()).sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}async rm(e,n){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(n?.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(!n?.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,n)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,n,r){this.assertWritable(`cp '${n}'`);let s=this.normalizePath(e),o=this.normalizePath(n);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);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(s);for(let c of l){let f=s==="/"?`/${c}`:`${s}/${c}`,d=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(f,d,r)}}}async mv(e,n){this.assertWritable(`mv '${n}'`),await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let n of this.deleted)e.delete(n);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,n){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let s=F.readdirSync(r);for(let o of s){let i=e==="/"?`/${o}`:`${e}/${o}`;if(this.deleted.has(i))continue;n.add(i);let a=Pe.join(r,o);F.statSync(a).isDirectory()&&this.scanRealFs(i,n)}}catch{}}async chmod(e,n){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=n;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:n,mtime:new Date})}else i.isDirectory&&this.memory.set(r,{type:"directory",mode:n,mtime:new Date})}async symlink(e,n){this.assertWritable(`symlink '${n}'`);let r=this.normalizePath(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,n){this.assertWritable(`link '${n}'`);let r=this.normalizePath(e),s=this.normalizePath(n);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(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:l,mode:i.mode,mtime:new Date}),this.deleted.delete(s)}async readlink(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(n);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await F.promises.readlink(s)}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 Bn(){console.log(`just-bash - A secure bash environment for AI agents
154
154
 
155
155
  Usage:
156
156
  just-bash [options] [script-file]
@@ -195,5 +195,5 @@ Examples:
195
195
 
196
196
  # Allow write operations (writes stay in memory)
197
197
  just-bash -c 'echo test > /tmp/file.txt && cat /tmp/file.txt' --allow-write
198
- `)}function si(){console.log("just-bash 1.0.0")}function ii(t){let e={root:process.cwd(),cwd:"/",cwdOverridden:!1,errexit:!1,allowWrite:!1,json:!1,help:!1,version:!1},n=0;for(;n<t.length;){let r=t[n];if(r==="-h"||r==="--help")e.help=!0,n++;else if(r==="-v"||r==="--version")e.version=!0,n++;else if(r==="-c")n+1>=t.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),e.script=t[n+1],n+=2;else if(r==="-e"||r==="--errexit")e.errexit=!0,n++;else if(r==="--root")n+1>=t.length&&(console.error("Error: --root requires a path argument"),process.exit(1)),e.root=Mn(t[n+1]),n+=2;else if(r==="--cwd")n+1>=t.length&&(console.error("Error: --cwd requires a path argument"),process.exit(1)),e.cwd=t[n+1],e.cwdOverridden=!0,n+=2;else if(r==="--json")e.json=!0,n++;else if(r==="--allow-write")e.allowWrite=!0,n++;else if(r.startsWith("-"))if(r.length>2&&!r.startsWith("--")){let s=r.slice(1);for(let o of s)if(o==="e")e.errexit=!0;else if(o==="h")e.help=!0;else if(o==="v")e.version=!0;else if(o==="c"){n+1>=t.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),e.script=t[n+1],n++;break}else console.error(`Error: Unknown option: -${o}`),process.exit(1);n++}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=Mn(r)),n++}return e}async function oi(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function ai(){let t=process.argv.slice(2),e=ii(t);e.help&&(Bn(),process.exit(0)),e.version&&(si(),process.exit(0));let n;if(e.script)n=e.script;else if(e.scriptFile){let a=new Ie({root:e.root}),c=a.getMountPoint();try{let l=e.scriptFile.startsWith("/")?e.scriptFile:`${c}/${e.scriptFile}`;n=await a.readFile(l,"utf-8")}catch(l){console.error(`Error: Cannot read script file: ${e.scriptFile}`),console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}else process.stdin.isTTY?(Bn(),process.exit(1)):n=await oi();n.trim()||(e.json&&console.log(JSON.stringify({stdout:"",stderr:"",exitCode:0})),process.exit(0));let r=new Ie({root:e.root,readOnly:!e.allowWrite}),s=r.getMountPoint(),o=e.cwdOverridden?e.cwd:s,i=new Et({fs:r,cwd:o});e.errexit&&(n=`set -e
198
+ `)}function si(){console.log("just-bash 1.0.0")}function ii(t){let e={root:process.cwd(),cwd:"/",cwdOverridden:!1,errexit:!1,allowWrite:!1,json:!1,help:!1,version:!1},n=0;for(;n<t.length;){let r=t[n];if(r==="-h"||r==="--help")e.help=!0,n++;else if(r==="-v"||r==="--version")e.version=!0,n++;else if(r==="-c")n+1>=t.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),e.script=t[n+1],n+=2;else if(r==="-e"||r==="--errexit")e.errexit=!0,n++;else if(r==="--root")n+1>=t.length&&(console.error("Error: --root requires a path argument"),process.exit(1)),e.root=Mn(t[n+1]),n+=2;else if(r==="--cwd")n+1>=t.length&&(console.error("Error: --cwd requires a path argument"),process.exit(1)),e.cwd=t[n+1],e.cwdOverridden=!0,n+=2;else if(r==="--json")e.json=!0,n++;else if(r==="--allow-write")e.allowWrite=!0,n++;else if(r.startsWith("-"))if(r.length>2&&!r.startsWith("--")){let s=r.slice(1);for(let o of s)if(o==="e")e.errexit=!0;else if(o==="h")e.help=!0;else if(o==="v")e.version=!0;else if(o==="c"){n+1>=t.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),e.script=t[n+1],n++;break}else console.error(`Error: Unknown option: -${o}`),process.exit(1);n++}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=Mn(r)),n++}return e}async function oi(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function ai(){let t=process.argv.slice(2),e=ii(t);e.help&&(Bn(),process.exit(0)),e.version&&(si(),process.exit(0));let n;if(e.script)n=e.script;else if(e.scriptFile){let a=new Ie({root:e.root}),l=a.getMountPoint();try{let c=e.scriptFile.startsWith("/")?e.scriptFile:`${l}/${e.scriptFile}`;n=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?(Bn(),process.exit(1)):n=await oi();n.trim()||(e.json&&console.log(JSON.stringify({stdout:"",stderr:"",exitCode:0})),process.exit(0));let r=new Ie({root:e.root,readOnly:!e.allowWrite}),s=r.getMountPoint(),o=e.cwdOverridden?e.cwd:s,i=new Et({fs:r,cwd:o});e.errexit&&(n=`set -e
199
199
  ${n}`);try{let a=await i.exec(n);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)}}ai().catch(t=>{console.error("Fatal error:",t),process.exit(1)});