import{createRequire} from"node:module";const require=createRequire(import.meta.url); import{a as ft,b as dt,c as je}from"./chunks/chunk-WNH3HOQA.js";import{c as Bn}from"./chunks/chunk-HBVMHTO5.js";import{a as ks,b as Ns}from"./chunks/chunk-SY4HAUHP.js";import{a as zn}from"./chunks/chunk-L2UW7DWF.js";import{a as bt,b as qe,c as cs}from"./chunks/chunk-DLL7UR66.js";import{a as ls,b as Di}from"./chunks/chunk-KAPG5ONA.js";import{a as gt,b as Ie}from"./chunks/chunk-VACKIICN.js";import{a as le}from"./chunks/chunk-7CSMHFIJ.js";import{a as os,b as _s,c as xc,d as yt,e as Cc,f as xs,g as Dc,h as Cs,i as Vn,j as Rc,k as Ic}from"./chunks/chunk-XEKXHOPO.js";import{a as Oe,b as Te,c as ke,d as ze,e as Le,f as Z,g as se,h as Me,i as wt,j as Ds,k as X,l as Rs,m as Et,n as Is,o as Be}from"./chunks/chunk-SAI2SPQQ.js";import"./chunks/chunk-STHBFACM.js";import{a as ut}from"./chunks/chunk-FOCWZZDE.js";import{a as ct}from"./chunks/chunk-W5DWRFSU.js";import{a as Fn}from"./chunks/chunk-BZUGFHVS.js";var Rt=[{name:"echo",load:async()=>(await import("./chunks/echo-NDWZZHPO.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-LPZ6XNHG.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-JPOOWRJC.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-ZJGQER7M.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-MEPGZOB6.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-OC4ZLPYA.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-UA33VN3N.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-SSGETQVQ.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-BISAAS7A.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-W5BIQ646.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-4LGSXXGD.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-TFEPA42X.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-WE6EN5AV.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-OPJF4DL5.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-AEMOMQSZ.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-GJMTLMNE.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-TZFYWFLA.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-CD34IZ4P.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-VUESTEZ7.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-VUESTEZ7.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-VUESTEZ7.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-EBMD72T4.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-DX2SGXMF.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-SREAOJRG.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-VW2NIZHW.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-DMFKT3AB.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-5QMYEAJL.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-NDMV7SPO.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-ABCY7E6C.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-JNNR5JMS.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-GCV6X22K.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-Q2L5XQWZ.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-XR2JMFCW.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-T2TH4TBQ.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-2TKXAENW.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-MCXFXPDL.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-NBMH43M2.js")).split},{name:"column",load:async()=>(await import("./chunks/column-PVOEF65J.js")).column},{name:"join",load:async()=>(await import("./chunks/join-YIABB6WR.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-SGANDVNY.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-T5TGGXUU.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-UB3CIYNI.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-MPHRFUTI.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-YLD52CNT.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-572XNP42.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-DLFRY633.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-DLFRY633.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-RTYYYW3D.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-RTYYYW3D.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-WYYKSLSZ.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-VDP7DLOU.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-FHQXJXBE.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-FHQXJXBE.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-HKGFEOF6.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-F4KHPMTX.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-F4KHPMTX.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-OPEF5OPR.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-WIGL46P3.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-TT4M7WM3.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-XKUEQ4WF.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-HZ4QEFOK.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-VDIEAB4R.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-FCZCDIAM.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-M5EC7Q57.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-YLACLCSM.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-LU7RVIB7.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-O6DM3TPQ.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-WPVZLZPS.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-IPZJC3FQ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-LXXMVQ3V.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-HZ6M2CKN.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-XEM24D5D.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-BQ7EDZW2.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-C4HQXXUP.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-XMTX52VE.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-RDSM4TQJ.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-HF3D26QX.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-HF3D26QX.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-HF3D26QX.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Rt.push({name:"tar",load:async()=>(await import("./chunks/tar-WIZ3PDF4.js")).tarCommand}),Rt.push({name:"yq",load:async()=>(await import("./chunks/yq-TVZ7R3O7.js")).yqCommand}),Rt.push({name:"xan",load:async()=>(await import("./chunks/xan-LKYWG2QQ.js")).xanCommand}),Rt.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-UE3PJTDQ.js")).sqlite3Command}));var Os=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Os.push({name:"python3",load:async()=>(await import("./chunks/python3-JPCH6LLN.js")).python3Command}),Os.push({name:"python",load:async()=>(await import("./chunks/python3-JPCH6LLN.js")).pythonCommand}));var Ts=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Ts.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-SR6IMNWM.js")).jsExecCommand}),Ts.push({name:"node",load:async()=>(await import("./chunks/js-exec-SR6IMNWM.js")).nodeStubCommand}));var Ii=[{name:"curl",load:async()=>(await import("./chunks/curl-PAWGO3EH.js")).curlCommand}],Ri=new Map;function Ls(e){return{name:e.name,async execute(t,s){let r=Ri.get(e.name);if(r||(r=await Ie.runTrustedAsync(()=>e.load()),Ri.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-OHLSWDU5.js");n(s.coverage,e.name,t)}return r.execute(t,s)}}}function Oc(){return Rt.map(e=>e.name)}function Tc(){return Ii.map(e=>e.name)}function Oi(e){return(e?Rt.filter(s=>e.includes(s.name)):Rt).map(Ls)}function Ti(){return Ii.map(Ls)}function Lc(){return Os.map(e=>e.name)}function Li(){return Os.map(Ls)}function Mc(){return Ts.map(e=>e.name)}function Mi(){return Ts.map(Ls)}function Wi(e){return"load"in e&&typeof e.load=="function"}function Wc(e,t){return{name:e,trusted:!0,execute:t}}function Fi(e){let t=null;return{name:e.name,trusted:!0,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}function L(e){if(!e||e==="/")return"/";let t=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;t.startsWith("/")||(t=`/${t}`);let s=t.split("/").filter(n=>n&&n!=="."),r=[];for(let n of s)n===".."?r.pop():r.push(n);return`/${r.join("/")}`||"/"}function M(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}function It(e){let t=L(e);if(t==="/")return"/";let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}function vt(e,t){if(t.startsWith("/"))return L(t);let s=e==="/"?`/${t}`:`${e}/${t}`;return L(s)}function St(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function zt(e,t){if(t.startsWith("/"))return L(t);let s=It(e);return L(St(s,t))}var Bt=new TextEncoder;function Fc(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var ht=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))typeof r=="function"?this.writeFileLazy(s,r):Fc(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}ensureParentDirs(t){let s=It(t);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,s,r,n){M(t,"write");let i=L(t);this.ensureParentDirs(i);let a=je(r),l=ft(s,a);this.data.set(i,{type:"file",content:l,mode:n?.mode??420,mtime:n?.mtime??new Date})}writeFileLazy(t,s,r){M(t,"write");let n=L(t);this.ensureParentDirs(n),this.data.set(n,{type:"file",lazy:s,mode:r?.mode??420,mtime:r?.mtime??new Date})}async materializeLazy(t,s){let r=await s.lazy(),i={type:"file",content:typeof r=="string"?Bt.encode(r):r,mode:s.mode,mtime:s.mtime};return this.data.set(t,i),i}async readFile(t,s){let r=await this.readFileBuffer(t),n=je(s);return dt(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return dt(s,"binary")}async readFileBuffer(t){M(t,"open");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if("lazy"in r){let n=await this.materializeLazy(s,r);return n.content instanceof Uint8Array?n.content:Bt.encode(n.content)}return r.content instanceof Uint8Array?r.content:Bt.encode(r.content)}async writeFile(t,s,r){this.writeFileSync(t,s,r)}async appendFile(t,s,r){M(t,"append");let n=L(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=je(r),l=ft(s,a);if(i?.type==="file"){let o=i;"lazy"in o&&(o=await this.materializeLazy(n,o));let u="content"in o&&o.content instanceof Uint8Array?o.content:Bt.encode("content"in o?o.content:""),c=new Uint8Array(u.length+l.length);c.set(u),c.set(l,u.length),this.data.set(n,{type:"file",content:c,mode:o.mode,mtime:new Date})}else this.writeFileSync(t,s,r)}async exists(t){if(t.includes("\0"))return!1;try{let s=this.resolvePathWithSymlinks(t);return this.data.has(s)}catch{return!1}}async stat(t){M(t,"stat");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Bt.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){M(t,"lstat");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Bt.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveIntermediateSymlinks(t){let s=L(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let a=0;a=c)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=L(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let a of r){n=`${n}/${a}`;let l=this.data.get(n),o=0,u=40;for(;l&&l.type==="symlink"&&o=u)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){M(t,"mkdir");let r=L(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let n=It(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){M(t,"scandir");let s=L(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=zt(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,a=new Map;for(let[l,o]of this.data.entries())if(l!==s&&l.startsWith(i)){let u=l.slice(i.length),c=u.split("/")[0];c&&!u.includes("/",c.length)&&!a.has(c)&&a.set(c,{name:c,isFile:o.type==="file",isDirectory:o.type==="directory",isSymbolicLink:o.type==="symlink"})}return Array.from(a.values()).sort((l,o)=>l.nameo.name?1:0)}async rm(t,s){M(t,"rm");let r=L(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let l=St(r,a);await this.rm(l,s)}}}this.data.delete(r)}async cp(t,s,r){M(t,"cp"),M(s,"cp");let n=L(t),i=L(s),a=this.data.get(n);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")if(this.ensureParentDirs(i),"content"in a){let l=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:l})}else this.data.set(i,{...a});else if(a.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let o of l){let u=St(n,o),c=St(i,o);await this.cp(u,c,r)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){return vt(t,s)}async chmod(t,s){M(t,"chmod");let r=L(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){M(s,"symlink");let r=L(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){M(t,"link"),M(s,"link");let r=L(t),n=L(s),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let a=i;"lazy"in a&&(a=await this.materializeLazy(r,a)),this.ensureParentDirs(n),this.data.set(n,{type:"file",content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(t){M(t,"readlink");let s=L(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){M(t,"realpath");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,r){M(t,"utimes");let n=L(t),i=this.resolvePathWithSymlinks(n),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=r}};var Vi="5.1.0(1)-release",zi="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function jn(e){let{pid:t,ppid:s,uid:r,gid:n}=e;return`Name: bash State: R (running) Pid: ${t} PPid: ${s} Uid: ${r} ${r} ${r} ${r} Gid: ${n} ${n} ${n} ${n} `}function Vc(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function zc(e,t){e.mkdirSync("/bin",{recursive:!0}),e.mkdirSync("/usr/bin",{recursive:!0}),t&&(e.mkdirSync("/home/user",{recursive:!0}),e.mkdirSync("/tmp",{recursive:!0}))}function Bc(e){e.mkdirSync("/dev",{recursive:!0}),e.writeFileSync("/dev/null",""),e.writeFileSync("/dev/zero",new Uint8Array(0)),e.writeFileSync("/dev/stdin",""),e.writeFileSync("/dev/stdout",""),e.writeFileSync("/dev/stderr","")}function qc(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${zi} `),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash `),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>jn(t)):e.writeFileSync("/proc/self/status",jn(t)),e.writeFileSync("/proc/self/fd/0","/dev/stdin"),e.writeFileSync("/proc/self/fd/1","/dev/stdout"),e.writeFileSync("/proc/self/fd/2","/dev/stderr")}function Bi(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){Vc(e)&&(zc(e,t),Bc(e),qc(e,s))}var jc=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],Uc=["braceexpand","hashall","interactive-comments"];function Un(e){let t=[],s=[...Uc.map(r=>({name:r,enabled:!0})),...jc.map(r=>({name:r,enabled:e[r]}))].sort((r,n)=>r.name.localeCompare(n.name));for(let r of s)r.enabled&&t.push(r.name);return t.join(":")}function jt(e){e.state.env.set("SHELLOPTS",Un(e.state.options))}var Zc=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function Zn(e){let t=[];for(let s of Zc)e[s]&&t.push(s);return t.join(":")}function Gn(e){e.state.env.set("BASHOPTS",Zn(e.state.shoptOptions))}var I={script(e){return{type:"Script",statements:e}},statement(e,t=[],s=!1,r,n){let i={type:"Statement",pipelines:e,operators:t,background:s};return r&&(i.deferredError=r),n!==void 0&&(i.sourceText=n),i},pipeline(e,t=!1,s=!1,r=!1,n){return{type:"Pipeline",commands:e,negated:t,timed:s,timePosix:r,pipeStderr:n}},simpleCommand(e,t=[],s=[],r=[]){return{type:"SimpleCommand",name:e,args:t,assignments:s,redirections:r}},word(e){return{type:"Word",parts:e}},literal(e){return{type:"Literal",value:e}},singleQuoted(e){return{type:"SingleQuoted",value:e}},doubleQuoted(e){return{type:"DoubleQuoted",parts:e}},escaped(e){return{type:"Escaped",value:e}},parameterExpansion(e,t=null){return{type:"ParameterExpansion",parameter:e,operation:t}},commandSubstitution(e,t=!1){return{type:"CommandSubstitution",body:e,legacy:t}},arithmeticExpansion(e){return{type:"ArithmeticExpansion",expression:e}},assignment(e,t,s=!1,r=null){return{type:"Assignment",name:e,value:t,append:s,array:r}},redirection(e,t,s=null,r){let n={type:"Redirection",fd:s,operator:e,target:t};return r&&(n.fdVariable=r),n},hereDoc(e,t,s=!1,r=!1){return{type:"HereDoc",delimiter:e,content:t,stripTabs:s,quoted:r}},ifNode(e,t=null,s=[]){return{type:"If",clauses:e,elseBody:t,redirections:s}},forNode(e,t,s,r=[]){return{type:"For",variable:e,words:t,body:s,redirections:r}},whileNode(e,t,s=[]){return{type:"While",condition:e,body:t,redirections:s}},untilNode(e,t,s=[]){return{type:"Until",condition:e,body:t,redirections:s}},caseNode(e,t,s=[]){return{type:"Case",word:e,items:t,redirections:s}},caseItem(e,t,s=";;"){return{type:"CaseItem",patterns:e,body:t,terminator:s}},subshell(e,t=[]){return{type:"Subshell",body:e,redirections:t}},group(e,t=[]){return{type:"Group",body:e,redirections:t}},functionDef(e,t,s=[],r){return{type:"FunctionDef",name:e,body:t,redirections:s,sourceFile:r}},conditionalCommand(e,t=[],s){return{type:"ConditionalCommand",expression:e,redirections:t,line:s}},arithmeticCommand(e,t=[],s){return{type:"ArithmeticCommand",expression:e,redirections:t,line:s}}};function qi(e,t){let s=e.length,r=t+3,n=2,i=!1,a=!1;for(;r0;){let l=e[r];if(i){l==="'"&&(i=!1),r++;continue}if(a){if(l==="\\"){r+=2;continue}l==='"'&&(a=!1),r++;continue}if(l==="'"){i=!0,r++;continue}if(l==='"'){a=!0,r++;continue}if(l==="\\"){r+=2;continue}if(l==="("){n++,r++;continue}if(l===")"){if(n--,n===1){let o=r+1;return!(oi===" "||i===" "||i===` `||i===";"||i==="&"||i==="|"||i==="<"||i===">"||i==="("||i===")";for(;r=e.length)return e.length;let a=e.indexOf(` `,r);a===-1&&(a=e.length);let l=e.slice(r,a);if(i&&(l=l.replace(/^\t+/,"")),l===n){r=a+1;break}if(a>=e.length)return e.length;r=a+1}return Math.min(r,e.length)}function ji(e,t,s,r){let n=t+2,i=1,a=n,l=!1,o=!1,u=0,c=!1,f="",d=[],h=0;for(;a0;){let b=e[a];if(l)b==="'"&&(l=!1);else if(o)b==="\\"&&a+10&&h--,h===0&&b==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){let v=a+2,E=!1;for(e[v]==="-"&&(E=!0,v++);e[v]===" "||e[v]===" ";)v++;let{delim:w,endPos:S}=Hn(e,v);if(w.length>0){d.push({delim:w,stripTabs:E}),f="",a=S;continue}}if(b===` `&&d.length>0){let v=Gc(e,a,d);d.length=0,f="",a=v;continue}b==="'"?(l=!0,f=""):b==='"'?(o=!0,f=""):b==="\\"&&a+10?c=!0:f==="esac"&&u>0&&(u--,c=!1),f="",b==="("?a>0&&e[a-1]==="$"?i++:c||i++:b===")"?c?c=!1:i--:b===";"&&u>0&&a+10&&a++}i>0&&r("unexpected EOF while looking for matching `)'");let m=e.slice(n,a),y=s().parse(m);return{part:I.commandSubstitution(y,!1),endIndex:a+1}}function Ui(e,t,s,r,n){let a=t+1,l="";for(;a=e.length&&n("unexpected EOF while looking for matching ``'");let u=r().parse(l);return{part:I.commandSubstitution(u,!0),endIndex:a+1}}var Hc=10485760,g;(function(e){e.EOF="EOF",e.NEWLINE="NEWLINE",e.SEMICOLON="SEMICOLON",e.AMP="AMP",e.PIPE="PIPE",e.PIPE_AMP="PIPE_AMP",e.AND_AND="AND_AND",e.OR_OR="OR_OR",e.BANG="BANG",e.LESS="LESS",e.GREAT="GREAT",e.DLESS="DLESS",e.DGREAT="DGREAT",e.LESSAND="LESSAND",e.GREATAND="GREATAND",e.LESSGREAT="LESSGREAT",e.DLESSDASH="DLESSDASH",e.CLOBBER="CLOBBER",e.TLESS="TLESS",e.AND_GREAT="AND_GREAT",e.AND_DGREAT="AND_DGREAT",e.LPAREN="LPAREN",e.RPAREN="RPAREN",e.LBRACE="LBRACE",e.RBRACE="RBRACE",e.DSEMI="DSEMI",e.SEMI_AND="SEMI_AND",e.SEMI_SEMI_AND="SEMI_SEMI_AND",e.DBRACK_START="DBRACK_START",e.DBRACK_END="DBRACK_END",e.DPAREN_START="DPAREN_START",e.DPAREN_END="DPAREN_END",e.IF="IF",e.THEN="THEN",e.ELSE="ELSE",e.ELIF="ELIF",e.FI="FI",e.FOR="FOR",e.WHILE="WHILE",e.UNTIL="UNTIL",e.DO="DO",e.DONE="DONE",e.CASE="CASE",e.ESAC="ESAC",e.IN="IN",e.FUNCTION="FUNCTION",e.SELECT="SELECT",e.TIME="TIME",e.COPROC="COPROC",e.WORD="WORD",e.NAME="NAME",e.NUMBER="NUMBER",e.ASSIGNMENT_WORD="ASSIGNMENT_WORD",e.FD_VARIABLE="FD_VARIABLE",e.COMMENT="COMMENT",e.HEREDOC_CONTENT="HEREDOC_CONTENT"})(g||(g={}));var At=class extends Error{line;column;constructor(t,s,r){super(`line ${s}: ${t}`),this.line=s,this.column=r,this.name="LexerError"}},Zi=new Map([["if",g.IF],["then",g.THEN],["else",g.ELSE],["elif",g.ELIF],["fi",g.FI],["for",g.FOR],["while",g.WHILE],["until",g.UNTIL],["do",g.DO],["done",g.DONE],["case",g.CASE],["esac",g.ESAC],["in",g.IN],["function",g.FUNCTION],["select",g.SELECT],["time",g.TIME],["coproc",g.COPROC]]);function Gi(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return!1;let s=e.slice(t[0].length);if(s===""||s==="+")return!0;if(s[0]==="["){let r=0,n=0;for(;n=s.length)return!1;let i=s.slice(n+1);return i===""||i==="+"}return!1}function Hi(e){let t=0;for(let s=0;s",">",g.AND_DGREAT]],Kc=[["[","[",g.DBRACK_START],["]","]",g.DBRACK_END],["(","(",g.DPAREN_START],[")",")",g.DPAREN_END],["&","&",g.AND_AND],["|","|",g.OR_OR],[";",";",g.DSEMI],[";","&",g.SEMI_AND],["|","&",g.PIPE_AMP],[">",">",g.DGREAT],["<","&",g.LESSAND],[">","&",g.GREATAND],["<",">",g.LESSGREAT],[">","|",g.CLOBBER],["&",">",g.AND_GREAT]],Xc=new Map([["|",g.PIPE],["&",g.AMP],[";",g.SEMICOLON],["(",g.LPAREN],[")",g.RPAREN],["<",g.LESS],[">",g.GREAT]]);function Yc(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Qi(e){return e===" "||e===" "||e===` `||e===";"||e==="&"||e==="|"||e==="("||e===")"||e==="<"||e===">"}var Ws=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];dparenDepth=0;maxHeredocSize;constructor(t,s){this.input=t,this.maxHeredocSize=s?.maxHeredocSize??Hc}tokenize(){let s=this.input.length,r=this.tokens,n=this.pendingHeredocs;for(;this.pos0&&r.length>0&&r[r.length-1].type===g.NEWLINE){this.readHeredocContent();continue}if(this.skipWhitespace(),this.pos>=s)break;let i=this.nextToken();i&&r.push(i)}return r.push({type:g.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),r}skipWhitespace(){let t=this.input,s=t.length,r=this.pos,n=this.column,i=this.line;for(;r0?(this.pos=s+1,this.column=n+1,this.dparenDepth++,this.makeToken(g.LPAREN,"(",s,r,n)):this.looksLikeNestedSubshells(s+2)||this.dparenClosesWithSpacedParens(s+2)?(this.pos=s+1,this.column=n+1,this.makeToken(g.LPAREN,"(",s,r,n)):(this.pos=s+2,this.column=n+2,this.dparenDepth=1,this.makeToken(g.DPAREN_START,"((",s,r,n));if(i===")"&&a===")")return this.dparenDepth===1?(this.pos=s+2,this.column=n+2,this.dparenDepth=0,this.makeToken(g.DPAREN_END,"))",s,r,n)):this.dparenDepth>1?(this.pos=s+1,this.column=n+1,this.dparenDepth--,this.makeToken(g.RPAREN,")",s,r,n)):(this.pos=s+1,this.column=n+1,this.makeToken(g.RPAREN,")",s,r,n));for(let[u,c,f]of Kc)if(!(u==="("&&c==="("||u===")"&&c===")")&&!(this.dparenDepth>0&&u===";"&&(f===g.DSEMI||f===g.SEMI_AND||f===g.SEMI_SEMI_AND))&&i===u&&a===c){if(f===g.DBRACK_START||f===g.DBRACK_END){let d=t[s+2];if(d!==void 0&&d!==" "&&d!==" "&&d!==` `&&d!==";"&&d!=="&"&&d!=="|"&&d!=="("&&d!==")"&&d!=="<"&&d!==">")break}return this.pos=s+2,this.column=n+2,this.makeToken(f,u+c,s,r,n)}if(i==="("&&this.dparenDepth>0)return this.pos=s+1,this.column=n+1,this.dparenDepth++,this.makeToken(g.LPAREN,"(",s,r,n);if(i===")"&&this.dparenDepth>1)return this.pos=s+1,this.column=n+1,this.dparenDepth--,this.makeToken(g.RPAREN,")",s,r,n);let o=Xc.get(i);if(o!==void 0)return this.pos=s+1,this.column=n+1,this.makeToken(o,i,s,r,n);if(i==="{"){let u=this.scanFdVariable(s);return u!==null?(this.pos=u.end,this.column=n+(u.end-s),{type:g.FD_VARIABLE,value:u.varname,start:s,end:u.end,line:r,column:n}):a==="}"?(this.pos=s+2,this.column=n+2,{type:g.WORD,value:"{}",start:s,end:s+2,line:r,column:n,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(s)!==null?this.readWordWithBraceExpansion(s,r,n):this.scanLiteralBraceWord(s)!==null?this.readWordWithBraceExpansion(s,r,n):a!==void 0&&a!==" "&&a!==" "&&a!==` `?this.readWord(s,r,n):(this.pos=s+1,this.column=n+1,this.makeToken(g.LBRACE,"{",s,r,n))}return i==="}"?this.isWordCharFollowing(s+1)?this.readWord(s,r,n):(this.pos=s+1,this.column=n+1,this.makeToken(g.RBRACE,"}",s,r,n)):i==="!"?a==="="?(this.pos=s+2,this.column=n+2,this.makeToken(g.WORD,"!=",s,r,n)):(this.pos=s+1,this.column=n+1,this.makeToken(g.BANG,"!",s,r,n)):this.readWord(s,r,n)}looksLikeNestedSubshells(t){let s=this.input,r=s.length,n=t;for(;n=r)return!1;let i=s[n];if(i==="(")return this.looksLikeNestedSubshells(n+1);let a=/[a-zA-Z_]/.test(i),l=i==="!"||i==="[";if(!a&&!l)return!1;let o=n;for(;o=r)return!1;let c=s[u];if(c==="="&&s[u+1]!=="="||c===` `||o===u&&/[+\-*/%<>&|^!~?:]/.test(c)&&c!=="-"||c===")"&&s[u+1]===")")return!1;if(u>o&&(c==="-"||c==='"'||c==="'"||c==="$"||/[a-zA-Z_/.]/.test(c))){let f=u;for(;f"||E==="'"||E==='"'||E==="\\"||E==="$"||E==="`"||E==="{"||E==="}"||E==="~"||E==="*"||E==="?"||E==="[")break;a++}if(a>l){let E=n[a];if(!(E==="("&&a>l&&"@*+?!".includes(n[a-1]))){if(a>=i||E===" "||E===" "||E===` `||E===";"||E==="&"||E==="|"||E==="("||E===")"||E==="<"||E===">"){let w=n.slice(l,a);this.pos=a,this.column=r+(a-l);let S=Zi.get(w);if(S!==void 0)return{type:S,value:w,start:t,end:a,line:s,column:r};let A=Hi(w);return A>0&&Gi(w.slice(0,A))?{type:g.ASSIGNMENT_WORD,value:w,start:t,end:a,line:s,column:r}:/^[0-9]+$/.test(w)?{type:g.NUMBER,value:w,start:t,end:a,line:s,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)?{type:g.NAME,value:w,start:t,end:a,line:s,column:r,quoted:!1,singleQuoted:!1}:{type:g.WORD,value:w,start:t,end:a,line:s,column:r,quoted:!1,singleQuoted:!1}}}}a=this.pos;let o=this.column,u=this.line,c="",f=!1,d=!1,h=!1,m=!1,p=n[a]==='"'||n[a]==="'",y=!1,b=0;for(;a0&&"@*+?!".includes(c[c.length-1])){let w=this.scanExtglobPattern(a);if(w!==null){c+=w.content,a=w.end,o+=w.content.length;continue}}if(E==="["&&b===0){if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){let w=a+10){c.length>0&&c[c.length-1]!=="\\"&&b++,c+=E,a++,o++;continue}else if(E==="]"&&b>0){c.length>0&&c[c.length-1]!=="\\"&&b--,c+=E,a++,o++;continue}if(b>0){if(E===` `)break;c+=E,a++,o++;continue}if(E===" "||E===" "||E===` `||E===";"||E==="&"||E==="|"||E==="("||E===")"||E==="<"||E===">")break}if(E==="$"&&a+10&&a0&&x--,x===0&&D==="<"&&n[a+1]==="<"&&n[a+2]!=="<"){let P=a+2,O=!1;for(n[P]==="-"&&(O=!0,P++);n[P]===" "||n[P]===" ";)P++;let{delim:z,endPos:U}=Hn(n,P);if(z.length>0){c+=n.slice(a+1,U),o+=U-a,F.push({delim:z,stripTabs:O}),a=U;continue}}if(D===` `&&F.length>0){u++,o=0;let P=a+1;for(let{delim:O,stripTabs:z}of F)for(;!(P>=i);){let U=n.indexOf(` `,P);U===-1&&(U=i);let ee=n.slice(P,U),fe=z?ee.replace(/^\t+/,""):ee;c+=n.slice(P,Math.min(U+1,i)),U=i;if(P=U+1,fe===O||ge)break}F.length=0,o=0,a=Math.min(P,i);continue}if(D==="'")S=!0,C="";else if(D==='"')A=!0,C="";else if(D==="\\"&&a+10&&a0?R=!0:C==="esac"&&$>0&&($--,R=!1),C="",D==="("?a>0&&n[a-1]==="$"?w++:R||w++:D===")"?R?R=!1:w--:D===";"&&$>0&&(a+10&&a0&&a="0"&&w<="9"){c+=E+w,a+=2,o+=2;continue}}if(E==="`"&&!h){for(c+=E,a++,o++;a=2){if(c[0]==="'"&&c[c.length-1]==="'"){let E=c.slice(1,-1);!E.includes("'")&&!E.includes('"')&&(c=E,f=!0,d=!0)}else if(c[0]==='"'&&c[c.length-1]==='"'){let E=c.slice(1,-1),w=!1;for(let S=0;S0&&Gi(c.slice(0,E)))return{type:g.ASSIGNMENT_WORD,value:c,start:t,end:a,line:s,column:r,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(c)?{type:g.NUMBER,value:c,start:t,end:a,line:s,column:r}:Yc(c)?{type:g.NAME,value:c,start:t,end:a,line:s,column:r,quoted:f,singleQuoted:d}:{type:g.WORD,value:c,start:t,end:a,line:s,column:r,quoted:f,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let t=this.pendingHeredocs.shift();if(!t)break;let s=this.pos,r=this.line,n=this.column,i="";for(;this.posthis.maxHeredocSize)throw new At(`Heredoc size limit exceeded (${this.maxHeredocSize} bytes)`,r,n);this.pos&|()]/.test(a))break;if(a==="'"||a==='"'){i=!0;let l=a;for(this.pos++,this.column++;this.pos=this.input.length)return!1;let s=this.input[t];return!(s===" "||s===" "||s===` `||s===";"||s==="&"||s==="|"||s==="("||s===")"||s==="<"||s===">")}readWordWithBraceExpansion(t,s,r){let n=this.input,i=n.length,a=t,l=r;for(;a")break;if(u==="{"){if(this.scanBraceExpansion(a)!==null){let f=1;for(a++,l++;a0;)n[a]==="{"?f++:n[a]==="}"&&f--,a++,l++;continue}a++,l++;continue}if(u==="}"){a++,l++;continue}if(u==="$"&&a+10&&a0&&a0;){let o=s[n];if(o==="{")i++,n++;else if(o==="}")i--,n++;else if(o===","&&i===1)a=!0,n++;else if(o==="."&&n+10;){let a=s[n];if(a==="{")i++,n++;else if(a==="}"){if(i--,i===0)return s.slice(t,n+1);n++}else{if(a===" "||a===" "||a===` `||a===";"||a==="&"||a==="|")return null;n++}}return null}scanExtglobPattern(t){let s=this.input,r=s.length,n=t+1,i=1;for(;n0;){let a=s[n];if(a==="\\"&&n+1="a"&&c<="z"||c>="A"&&c<="Z"||c==="_"))return null}else if(!(c>="a"&&c<="z"||c>="A"&&c<="Z"||c>="0"&&c<="9"||c==="_"))break;n++}if(n===i)return null;let a=s.slice(i,n);if(n>=r||s[n]!=="}"||(n++,n>=r))return null;let l=s[n],o=n+1"||l==="<"||l==="&"&&(o===">"||o==="<")?{varname:a,end:n}:null}dollarDparenIsSubshell(t){let s=this.input,r=s.length,n=t+1,i=2,a=!1,l=!1,o=!1;for(;n0;){let u=s[n];if(a){u==="'"&&(a=!1),u===` `&&(o=!0),n++;continue}if(l){if(u==="\\"){n+=2;continue}u==='"'&&(l=!1),u===` `&&(o=!0),n++;continue}if(u==="'"){a=!0,n++;continue}if(u==='"'){l=!0,n++;continue}if(u==="\\"){n+=2;continue}if(u===` `&&(o=!0),u==="("){i++,n++;continue}if(u===")"){if(i--,i===1){let c=n+1;if(c0;){let o=s[n];if(a){o==="'"&&(a=!1),n++;continue}if(l){if(o==="\\"){n+=2;continue}o==='"'&&(l=!1),n++;continue}if(o==="'"){a=!0,n++;continue}if(o==='"'){l=!0,n++;continue}if(o==="\\"){n+=2;continue}if(o==="("){i++,n++;continue}if(o===")"){if(i--,i===1){let u=n+1;if(u>=","&=","|=","^="];function us(e){if(e.includes("#")){let[s,r]=e.split("#"),n=Number.parseInt(s,10);if(n<2||n>64)return Number.NaN;if(n<=36){let a=Number.parseInt(r,n);return a>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:a}let i=0;for(let a of r){let l;if(/[0-9]/.test(a))l=a.charCodeAt(0)-48;else if(/[a-z]/.test(a))l=a.charCodeAt(0)-97+10;else if(/[A-Z]/.test(a))l=a.charCodeAt(0)-65+36;else if(a==="@")l=62;else if(a==="_")l=63;else return Number.NaN;if(l>=n)return Number.NaN;if(i=i*n+l,i>Number.MAX_SAFE_INTEGER)return Number.MAX_SAFE_INTEGER}return i}if(e.startsWith("0x")||e.startsWith("0X")){let s=Number.parseInt(e.slice(2),16);return s>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:s}if(e.startsWith("0")&&e.length>1&&/^[0-9]+$/.test(e)){if(/[89]/.test(e))return Number.NaN;let s=Number.parseInt(e,8);return s>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:s}let t=Number.parseInt(e,10);return t>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:t}function ea(e,t,s,r){if(s.slice(r,r+3)!=="$((")return null;let n=r+3,i=1,a=n;for(;n0;)s[n]==="("&&s[n+1]==="("?(i++,n+=2):s[n]===")"&&s[n+1]===")"?(i--,i>0&&(n+=2)):n++;let l=s.slice(a,n),{expr:o}=e(t,l,0);return n+=2,{expr:{type:"ArithNested",expression:o},pos:n}}function ta(e,t){if(e.slice(t,t+2)!=="$'")return null;let s=t+2,r="";for(;s=e.length}function We(e,t,s){return eu(e,t,s)}function eu(e,t,s){let{expr:r,pos:n}=fs(e,t,s);for(n=ce(t,n);t[n]===",";){if(n++,xe(t,n))return _e(",",n);let{expr:a,pos:l}=fs(e,t,n);r={type:"ArithBinary",operator:",",left:r,right:a},n=ce(t,l)}return{expr:r,pos:n}}function fs(e,t,s){let{expr:r,pos:n}=tu(e,t,s);if(n=ce(t,n),t[n]==="?"){n++;let{expr:i,pos:a}=We(e,t,n);if(n=ce(t,a),t[n]===":"){n++;let{expr:l,pos:o}=We(e,t,n);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:l},pos:o}}}return{expr:r,pos:n}}function tu(e,t,s){let{expr:r,pos:n}=na(e,t,s);for(;n=ce(t,n),t.slice(n,n+2)==="||";){if(n+=2,xe(t,n))return _e("||",n);let{expr:a,pos:l}=na(e,t,n);r={type:"ArithBinary",operator:"||",left:r,right:a},n=l}return{expr:r,pos:n}}function na(e,t,s){let{expr:r,pos:n}=ra(e,t,s);for(;n=ce(t,n),t.slice(n,n+2)==="&&";){if(n+=2,xe(t,n))return _e("&&",n);let{expr:a,pos:l}=ra(e,t,n);r={type:"ArithBinary",operator:"&&",left:r,right:a},n=l}return{expr:r,pos:n}}function ra(e,t,s){let{expr:r,pos:n}=ia(e,t,s);for(;n=ce(t,n),t[n]==="|"&&t[n+1]!=="|";){if(n++,xe(t,n))return _e("|",n);let{expr:a,pos:l}=ia(e,t,n);r={type:"ArithBinary",operator:"|",left:r,right:a},n=l}return{expr:r,pos:n}}function ia(e,t,s){let{expr:r,pos:n}=aa(e,t,s);for(;n=ce(t,n),t[n]==="^";){if(n++,xe(t,n))return _e("^",n);let{expr:a,pos:l}=aa(e,t,n);r={type:"ArithBinary",operator:"^",left:r,right:a},n=l}return{expr:r,pos:n}}function aa(e,t,s){let{expr:r,pos:n}=oa(e,t,s);for(;n=ce(t,n),t[n]==="&"&&t[n+1]!=="&";){if(n++,xe(t,n))return _e("&",n);let{expr:a,pos:l}=oa(e,t,n);r={type:"ArithBinary",operator:"&",left:r,right:a},n=l}return{expr:r,pos:n}}function oa(e,t,s){let{expr:r,pos:n}=la(e,t,s);for(;n=ce(t,n),t.slice(n,n+2)==="=="||t.slice(n,n+2)==="!=";){let i=t.slice(n,n+2);if(n+=2,xe(t,n))return _e(i,n);let{expr:a,pos:l}=la(e,t,n);r={type:"ArithBinary",operator:i,left:r,right:a},n=l}return{expr:r,pos:n}}function la(e,t,s){let{expr:r,pos:n}=Yn(e,t,s);for(;;)if(n=ce(t,n),t.slice(n,n+2)==="<="||t.slice(n,n+2)===">="){let i=t.slice(n,n+2);if(n+=2,xe(t,n))return _e(i,n);let{expr:a,pos:l}=Yn(e,t,n);r={type:"ArithBinary",operator:i,left:r,right:a},n=l}else if(t[n]==="<"||t[n]===">"){let i=t[n];if(n++,xe(t,n))return _e(i,n);let{expr:a,pos:l}=Yn(e,t,n);r={type:"ArithBinary",operator:i,left:r,right:a},n=l}else break;return{expr:r,pos:n}}function Yn(e,t,s){let{expr:r,pos:n}=ca(e,t,s);for(;n=ce(t,n),t.slice(n,n+2)==="<<"||t.slice(n,n+2)===">>";){let i=t.slice(n,n+2);if(n+=2,xe(t,n))return _e(i,n);let{expr:a,pos:l}=ca(e,t,n);r={type:"ArithBinary",operator:i,left:r,right:a},n=l}return{expr:r,pos:n}}function ca(e,t,s){let{expr:r,pos:n}=ua(e,t,s);for(;n=ce(t,n),(t[n]==="+"||t[n]==="-")&&t[n+1]!==t[n];){let i=t[n];if(n++,xe(t,n))return _e(i,n);let{expr:a,pos:l}=ua(e,t,n);r={type:"ArithBinary",operator:i,left:r,right:a},n=l}return{expr:r,pos:n}}function ua(e,t,s){let{expr:r,pos:n}=Vs(e,t,s);for(;;)if(n=ce(t,n),t[n]==="*"&&t[n+1]!=="*"){if(n++,xe(t,n))return _e("*",n);let{expr:a,pos:l}=Vs(e,t,n);r={type:"ArithBinary",operator:"*",left:r,right:a},n=l}else if(t[n]==="/"||t[n]==="%"){let i=t[n];if(n++,xe(t,n))return _e(i,n);let{expr:a,pos:l}=Vs(e,t,n);r={type:"ArithBinary",operator:i,left:r,right:a},n=l}else break;return{expr:r,pos:n}}function Vs(e,t,s){let{expr:r,pos:n}=Jn(e,t,s),i=ce(t,n);if(t.slice(i,i+2)==="**"){if(i+=2,xe(t,i))return _e("**",i);let{expr:l,pos:o}=Vs(e,t,i);return{expr:{type:"ArithBinary",operator:"**",left:r,right:l},pos:o}}return{expr:r,pos:n}}function Jn(e,t,s){let r=ce(t,s);if(t.slice(r,r+2)==="++"||t.slice(r,r+2)==="--"){let n=t.slice(r,r+2);r+=2;let{expr:i,pos:a}=Jn(e,t,r);return{expr:{type:"ArithUnary",operator:n,operand:i,prefix:!0},pos:a}}if(t[r]==="+"||t[r]==="-"||t[r]==="!"||t[r]==="~"){let n=t[r];r++;let{expr:i,pos:a}=Jn(e,t,r);return{expr:{type:"ArithUnary",operator:n,operand:i,prefix:!0},pos:a}}return nu(e,t,r)}function su(e,t){let s=e[t];return s==="$"||s==="`"}function nu(e,t,s){let{expr:r,pos:n}=fa(e,t,s,!1),i=[r];for(;su(t,n);){let{expr:l,pos:o}=fa(e,t,n,!0);i.push(l),n=o}i.length>1&&(r={type:"ArithConcat",parts:i});let a;if(t[n]==="["&&r.type==="ArithConcat"){n++;let{expr:l,pos:o}=We(e,t,n);a=l,n=o,t[n]==="]"&&n++}if(a&&r.type==="ArithConcat"&&(r={type:"ArithDynamicElement",nameExpr:r,subscript:a},a=void 0),n=ce(t,n),r.type==="ArithConcat"||r.type==="ArithVariable"||r.type==="ArithDynamicElement"){for(let l of Fs)if(t.slice(n,n+l.length)===l&&t.slice(n,n+l.length+1)!=="=="){n+=l.length;let{expr:o,pos:u}=fs(e,t,n);return r.type==="ArithDynamicElement"?{expr:{type:"ArithDynamicAssignment",operator:l,target:r.nameExpr,subscript:r.subscript,value:o},pos:u}:r.type==="ArithConcat"?{expr:{type:"ArithDynamicAssignment",operator:l,target:r,value:o},pos:u}:{expr:{type:"ArithAssignment",operator:l,variable:r.name,value:o},pos:u}}}if(t.slice(n,n+2)==="++"||t.slice(n,n+2)==="--"){let l=t.slice(n,n+2);return n+=2,{expr:{type:"ArithUnary",operator:l,operand:r,prefix:!1},pos:n}}return{expr:r,pos:n}}function fa(e,t,s,r=!1){let n=ce(t,s),i=ea(We,e,t,n);if(i)return i;let a=ta(t,n);if(a)return a;let l=sa(t,n);if(l)return l;if(t.slice(n,n+2)==="$("&&t[n+2]!=="("){n+=2;let u=1,c=n;for(;n0;)t[n]==="("?u++:t[n]===")"&&u--,u>0&&n++;let f=t.slice(c,n);return n++,{expr:{type:"ArithCommandSubst",command:f},pos:n}}if(t[n]==="`"){n++;let u=n;for(;n0;)t[f]==="{"?c++:t[f]==="}"&&c--,c>0&&f++;let d=t.slice(u,f),h=f+1;if(t[h]==="#"){let m=h+1;for(;m=194){let n=(r&31)<<6|e[s+1]&63;t+=String.fromCharCode(n),s+=2;continue}t+=String.fromCharCode(r),s++;continue}if((r&240)===224){if(s+2=55296&&n<=57343){t+=String.fromCharCode(r),s++;continue}t+=String.fromCharCode(n),s+=3;continue}t+=String.fromCharCode(r),s++;continue}if((r&248)===240&&r<=244){if(s+31114111){t+=String.fromCharCode(r),s++;continue}t+=String.fromCodePoint(n),s+=4;continue}t+=String.fromCharCode(r),s++;continue}t+=String.fromCharCode(r),s++}return t}function pa(e,t,s){let r=s+1;for(;r0;)t[a]===r?i++:t[a]===n&&i--,i>0&&a++;return i===0?a:-1}function Ot(e,t,s){let r=s,n=1;for(;r0;){let i=t[r];if(i==="\\"&&r+10&&r++}return r}function ma(e,t,s){let r=s,n=!1;for(;r0)l.push(c),o+=2+u.length;else break}l.length>0?(r+=ru(l),n=o):(r+="\\x",n+=2);break}case"u":{let l=t.slice(n+2,n+6),o=parseInt(l,16);Number.isNaN(o)?(r+="\\u",n+=2):(r+=String.fromCharCode(o),n+=6);break}case"c":{if(n+2({type:"Word",word:I.word(r(e,c,!1,!1,!1))}))},endIndex:n+1}:i.includes(",")?{part:{type:"BraceExpansion",items:ha(i).map(c=>({type:"Word",word:I.word([I.literal(c)])}))},endIndex:n+1}:null}function sr(e,t){let s="";for(let r of t.parts)switch(r.type){case"Literal":s+=r.value;break;case"SingleQuoted":s+=`'${r.value}'`;break;case"Escaped":s+=r.value;break;case"DoubleQuoted":s+='"';for(let n of r.parts)n.type==="Literal"||n.type==="Escaped"?s+=n.value:n.type==="ParameterExpansion"&&(s+=`\${${n.parameter}}`);s+='"';break;case"ParameterExpansion":s+=`\${${r.parameter}}`;break;case"Glob":s+=r.pattern;break;case"TildeExpansion":s+="~",r.user&&(s+=r.user);break;case"BraceExpansion":{s+="{";let n=[];for(let i of r.items)if(i.type==="Range"){let a=i.startStr??String(i.start),l=i.endStr??String(i.end);i.step!==void 0?n.push(`${a}..${l}..${i.step}`):n.push(`${a}..${l}`)}else n.push(sr(e,i.word));n.length===1&&r.items[0].type==="Range"?s+=n[0]:s+=n.join(","),s+="}";break}default:s+=r.type}return s}function Ea(e,t){return{[g.LESS]:"<",[g.GREAT]:">",[g.DGREAT]:">>",[g.LESSAND]:"<&",[g.GREATAND]:">&",[g.LESSGREAT]:"<>",[g.CLOBBER]:">|",[g.TLESS]:"<<<",[g.AND_GREAT]:"&>",[g.AND_DGREAT]:"&>>",[g.DLESS]:"<",[g.DLESSDASH]:"<"}[t]||">"}function zs(e){let t=e.current(),s=t.type;if(s===g.NUMBER){let r=e.peek(1);return t.end!==r.start?!1:Yi.has(r.type)}if(s===g.FD_VARIABLE){let r=e.peek(1);return Ji.has(r.type)}return Xi.has(s)}function Bs(e){let t=null,s;e.check(g.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(g.FD_VARIABLE)&&(s=e.advance().value);let r=e.advance(),n=Ea(e,r.type);if(r.type===g.DLESS||r.type===g.DLESSDASH)return au(e,n,t,r.type===g.DLESSDASH);e.isWord()||e.error("Expected redirection target");let i=e.parseWord();return I.redirection(n,i,t,s)}function au(e,t,s,r){e.isWord()||e.error("Expected here-document delimiter");let n=e.advance(),i=n.value,a=n.quoted||!1;(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.slice(1,-1));let l=I.redirection(r?"<<-":"<<",I.hereDoc(i,I.word([]),r,a),s);return e.addPendingHeredoc(l,i,r,a),l}function va(e){let t=e.current().line,s=[],r=null,n=[],i=[];for(;e.check(g.ASSIGNMENT_WORD)||zs(e);)e.checkIterationLimit(),e.check(g.ASSIGNMENT_WORD)?s.push(ou(e)):i.push(Bs(e));if(e.isWord())r=e.parseWord();else if(s.length>0&&(e.check(g.DBRACK_START)||e.check(g.DPAREN_START))){let l=e.advance();r=I.word([I.literal(l.value)])}for(;(!e.isStatementEnd()||e.check(g.RBRACE))&&!e.check(g.PIPE,g.PIPE_AMP);)if(e.checkIterationLimit(),zs(e))i.push(Bs(e));else if(e.check(g.RBRACE)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.check(g.LBRACE)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.check(g.DBRACK_END)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.isWord())n.push(e.parseWord());else if(e.check(g.ASSIGNMENT_WORD)){let l=e.advance(),o=l.value,u=o.endsWith("="),c=o.endsWith("=(");if((u||c)&&(c||e.check(g.LPAREN))){let f=c?o.slice(0,-2):o.slice(0,-1);c||e.expect(g.LPAREN);let d=nr(e);e.expect(g.RPAREN);let h=d.map(p=>sr(e,p)),m=`${f}=(${h.join(" ")})`;n.push(e.parseWordFromString(m,!1,!1))}else n.push(e.parseWordFromString(o,l.quoted,l.singleQuoted))}else if(e.check(g.LPAREN))e.error("syntax error near unexpected token `('");else break;let a=I.simpleCommand(r,n,s,i);return a.line=t,a}function ou(e){let t=e.expect(g.ASSIGNMENT_WORD),s=t.value,r=s.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||e.error(`Invalid assignment: ${s}`);let n=r[0],i,a=n.length;if(s[a]==="["){let f=0,d=a+1;for(;a2)break}else f.value==="("&&o++,f.value===")"&&o--,a[l]+=f.value}e.expect(g.DPAREN_END),a[0].trim()&&(r=Y(e,a[0].trim())),a[1].trim()&&(n=Y(e,a[1].trim())),a[2].trim()&&(i=Y(e,a[2].trim())),e.skipNewlines(),e.check(g.SEMICOLON)&&e.advance(),e.skipNewlines();let u;e.check(g.LBRACE)?(e.advance(),u=e.parseCompoundList(),e.expect(g.RBRACE)):(e.expect(g.DO),u=e.parseCompoundList(),e.expect(g.DONE));let c=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:r,condition:n,update:i,body:u,redirections:c,line:s}}function ar(e,t){e.expect(g.WHILE);let s=e.parseCompoundList();e.expect(g.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(g.DONE);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return I.whileNode(s,r,n)}function or(e,t){e.expect(g.UNTIL);let s=e.parseCompoundList();e.expect(g.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(g.DONE);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return I.untilNode(s,r,n)}function lr(e,t){e.expect(g.CASE),e.isWord()||e.error("Expected word after 'case'");let s=e.parseWord();e.skipNewlines(),e.expect(g.IN),e.skipNewlines();let r=[];for(;!e.check(g.ESAC,g.EOF);){e.checkIterationLimit();let i=e.getPos(),a=fu(e);if(a&&r.push(a),e.skipNewlines(),e.getPos()===i&&!a)break}e.expect(g.ESAC);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return I.caseNode(s,r,n)}function fu(e){e.check(g.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(g.PIPE));)e.advance();if(t.length===0)return null;e.expect(g.RPAREN),e.skipNewlines();let s=[];for(;!e.check(g.DSEMI,g.SEMI_AND,g.SEMI_SEMI_AND,g.ESAC,g.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===g.RPAREN&&e.error("syntax error near unexpected token `)'"),e.check(g.LPAREN)&&e.peek(1).type===g.WORD&&e.error(`syntax error near unexpected token \`${e.peek(1).value}'`);let n=e.getPos(),i=e.parseStatement();if(i&&s.push(i),e.skipSeparators(!1),e.getPos()===n&&!i)break}let r=";;";return e.check(g.DSEMI)?(e.advance(),r=";;"):e.check(g.SEMI_AND)?(e.advance(),r=";&"):e.check(g.SEMI_SEMI_AND)&&(e.advance(),r=";;&"),I.caseItem(t,s,r)}function cr(e,t){e.expect(g.LPAREN);let s=e.parseCompoundList();e.expect(g.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return I.subshell(s,r)}function ur(e,t){e.expect(g.LBRACE);let s=e.parseCompoundList();e.expect(g.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return I.group(s,r)}var hu=["-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"],pu=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function Sa(e){return e.isWord()||e.check(g.LBRACE)||e.check(g.RBRACE)||e.check(g.ASSIGNMENT_WORD)}function Aa(e){if(e.check(g.BANG)&&e.peek(1).type===g.LPAREN){e.advance(),e.advance();let t=1,s="!(";for(;t>0&&!e.check(g.EOF);)if(e.check(g.LPAREN))t++,s+="(",e.advance();else if(e.check(g.RPAREN))t--,t>0&&(s+=")"),e.advance();else if(e.isWord())s+=e.advance().value;else if(e.check(g.PIPE))s+="|",e.advance();else break;return s+=")",e.parseWordFromString(s,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function dr(e){return e.skipNewlines(),mu(e)}function mu(e){let t=$a(e);for(e.skipNewlines();e.check(g.OR_OR);){e.advance(),e.skipNewlines();let s=$a(e);t={type:"CondOr",left:t,right:s},e.skipNewlines()}return t}function $a(e){let t=fr(e);for(e.skipNewlines();e.check(g.AND_AND);){e.advance(),e.skipNewlines();let s=fr(e);t={type:"CondAnd",left:t,right:s},e.skipNewlines()}return t}function fr(e){return e.skipNewlines(),e.check(g.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:fr(e)}):gu(e)}function gu(e){if(e.check(g.LPAREN)){e.advance();let t=dr(e);return e.expect(g.RPAREN),{type:"CondGroup",expression:t}}if(Sa(e)){let t=e.current(),s=t.value;if(hu.includes(s)&&!t.quoted){if(e.advance(),e.check(g.DBRACK_END)&&e.error(`Expected operand after ${s}`),Sa(e)){let i=e.parseWordNoBraceExpansion();return{type:"CondUnary",operator:s,operand:i}}let n=e.current();e.error(`unexpected argument \`${n.value}' to conditional unary operator`)}let r=e.parseWordNoBraceExpansion();if(e.isWord()&&pu.includes(e.current().value)){let n=e.advance().value,i;return n==="=~"?i=yu(e):n==="=="||n==="!="?i=Aa(e):i=e.parseWordNoBraceExpansion(),{type:"CondBinary",operator:n,left:r,right:i}}if(e.check(g.LESS)){e.advance();let n=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:"<",left:r,right:n}}if(e.check(g.GREAT)){e.advance();let n=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:">",left:r,right:n}}if(e.isWord()&&e.current().value==="="){e.advance();let n=Aa(e);return{type:"CondBinary",operator:"==",left:r,right:n}}return{type:"CondWord",word:r}}e.error("Expected conditional expression")}function yu(e){let t=[],s=0,r=-1,n=e.getInput(),i=()=>e.check(g.DBRACK_END)||e.check(g.AND_AND)||e.check(g.OR_OR)||e.check(g.NEWLINE)||e.check(g.EOF);for(;!i();){let a=e.current(),l=r>=0&&a.start>r;if(s===0&&l)break;if(s>0&&l){let o=n.slice(r,a.start);t.push({type:"Literal",value:o})}if(e.isWord()||e.check(g.ASSIGNMENT_WORD)){let o=e.parseWordForRegex();t.push(...o.parts),r=e.peek(-1).end}else if(e.check(g.LPAREN)){let o=e.advance();t.push({type:"Literal",value:"("}),s++,r=o.end}else if(e.check(g.DPAREN_START)){let o=e.advance();t.push({type:"Literal",value:"(("}),s+=2,r=o.end}else if(e.check(g.DPAREN_END))if(s>=2){let o=e.advance();t.push({type:"Literal",value:"))"}),s-=2,r=o.end}else{if(s===1)break;break}else if(e.check(g.RPAREN))if(s>0){let o=e.advance();t.push({type:"Literal",value:")"}),s--,r=o.end}else break;else if(e.check(g.PIPE)){let o=e.advance();t.push({type:"Literal",value:"|"}),r=o.end}else if(e.check(g.SEMICOLON))if(s>0){let o=e.advance();t.push({type:"Literal",value:";"}),r=o.end}else break;else if(s>0&&e.check(g.LESS)){let o=e.advance();t.push({type:"Literal",value:"<"}),r=o.end}else if(s>0&&e.check(g.GREAT)){let o=e.advance();t.push({type:"Literal",value:">"}),r=o.end}else if(s>0&&e.check(g.DGREAT)){let o=e.advance();t.push({type:"Literal",value:">>"}),r=o.end}else if(s>0&&e.check(g.DLESS)){let o=e.advance();t.push({type:"Literal",value:"<<"}),r=o.end}else if(s>0&&e.check(g.LESSAND)){let o=e.advance();t.push({type:"Literal",value:"<&"}),r=o.end}else if(s>0&&e.check(g.GREATAND)){let o=e.advance();t.push({type:"Literal",value:">&"}),r=o.end}else if(s>0&&e.check(g.LESSGREAT)){let o=e.advance();t.push({type:"Literal",value:"<>"}),r=o.end}else if(s>0&&e.check(g.CLOBBER)){let o=e.advance();t.push({type:"Literal",value:">|"}),r=o.end}else if(s>0&&e.check(g.TLESS)){let o=e.advance();t.push({type:"Literal",value:"<<<"}),r=o.end}else if(s>0&&e.check(g.AMP)){let o=e.advance();t.push({type:"Literal",value:"&"}),r=o.end}else if(s>0&&e.check(g.LBRACE)){let o=e.advance();t.push({type:"Literal",value:"{"}),r=o.end}else if(s>0&&e.check(g.RBRACE)){let o=e.advance();t.push({type:"Literal",value:"}"}),r=o.end}else break}return t.length===0&&e.error("Expected regex pattern after =~"),{type:"Word",parts:t}}function ds(e){return e.length>0?e:[I.literal("")]}function Eu(e,t){let s=1,r=t+1;for(;r0;){let n=e[r];if(n==="\\"){r+=2;continue}if("@*+?!".includes(n)&&r+10;)t[d]==="{"?f++:t[d]==="}"&&f--,f>0&&d++;let h=t.slice(s+2,d);return{part:I.parameterExpansion("",{type:"BadSubstitution",text:h}),endIndex:d+1}}}if(l===""&&!i&&!a&&t[n]!=="}"){let c=1,f=n;for(;f0;)t[f]==="{"?c++:t[f]==="}"&&c--,c>0&&f++;if(c>0)throw new Ee("unexpected EOF while looking for matching '}'",0,0);let d=t.slice(s+2,f);return{part:I.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:f+1}}let u=null;if(i){let c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(c)if(n=t.length)throw new Ee("unexpected EOF while looking for matching '}'",0,0);return{part:I.parameterExpansion(l,u),endIndex:n+1}}function hr(e,t,s,r,n=!1){let i=s,a=t[i],l=t[i+1]||"";if(a===":"){let o=l;if("-=?+".includes(o)){i+=2;let b=Ot(e,t,i),v=t.slice(i,b),E=$t(e,v,!1,!1,!0,!1,n,!1,!1,!0),w=I.word(ds(E));if(o==="-")return{operation:{type:"DefaultValue",word:w,checkEmpty:!0},endIndex:b};if(o==="=")return{operation:{type:"AssignDefault",word:w,checkEmpty:!0},endIndex:b};if(o==="?")return{operation:{type:"ErrorIfUnset",word:w,checkEmpty:!0},endIndex:b};if(o==="+")return{operation:{type:"UseAlternative",word:w,checkEmpty:!0},endIndex:b}}i++;let u=Ot(e,t,i),c=t.slice(i,u),f=-1,d=0,h=0;for(let y=0;y0)h--;else{f=y;break}}let m=f>=0?c.slice(0,f):c,p=f>=0?c.slice(f+1):null;return{operation:{type:"Substring",offset:tr(e,m),length:p!==null?tr(e,p):null},endIndex:u}}if("-=?+".includes(a)){i++;let o=Ot(e,t,i),u=t.slice(i,o),c=$t(e,u,!1,!1,!0,!1,n,!1,!1,!0),f=I.word(ds(c));if(a==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:o};if(a==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:o};if(a==="?")return{operation:{type:"ErrorIfUnset",word:u?f:null,checkEmpty:!1},endIndex:o};if(a==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:o}}if(a==="#"||a==="%"){let o=l===a,u=a==="#"?"prefix":"suffix";i+=o?2:1;let c=Ot(e,t,i),f=t.slice(i,c),d=$t(e,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:I.word(ds(d)),side:u,greedy:o},endIndex:c}}if(a==="/"){let o=l==="/";i+=o?2:1;let u=null;t[i]==="#"?(u="start",i++):t[i]==="%"&&(u="end",i++);let c;u!==null&&(t[i]==="/"||t[i]==="}")?c=i:c=ma(e,t,i);let f=t.slice(i,c),d=$t(e,f,!1,!1,!1),h=I.word(ds(d)),m=null,p=c;if(t[c]==="/"){let y=c+1,b=Ot(e,t,y),v=t.slice(y,b),E=$t(e,v,!1,!1,!1);m=I.word(ds(E)),p=b}return{operation:{type:"PatternReplacement",pattern:h,replacement:m,all:o,anchor:u},endIndex:p}}if(a==="^"||a===","){let o=l===a,u=a==="^"?"upper":"lower";i+=o?2:1;let c=Ot(e,t,i),f=t.slice(i,c),d=f?I.word([I.literal(f)]):null;return{operation:{type:"CaseModification",direction:u,all:o,pattern:d},endIndex:c}}return a==="@"&&/[QPaAEKkuUL]/.test(l)?{operation:{type:"Transform",operator:l},endIndex:i+2}:{operation:null,endIndex:i}}function pr(e,t,s,r=!1){let n=s+1;if(n>=t.length)return{part:I.literal("$"),endIndex:n};let i=t[n];if(i==="("&&t[n+1]==="(")return e.isDollarDparenSubshell(t,s)?e.parseCommandSubstitution(t,s):e.parseArithmeticExpansion(t,s);if(i==="["){let a=1,l=n+1;for(;l0;)t[l]==="["?a++:t[l]==="]"&&a--,a>0&&l++;if(a===0){let o=t.slice(n+1,l),u=Y(e,o);return{part:I.arithmeticExpansion(u),endIndex:l+1}}}return i==="("?e.parseCommandSubstitution(t,s):i==="{"?vu(e,t,s,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?bu(e,t,s):{part:I.literal("$"),endIndex:n}}function Pa(e,t){let s=[],r=0,n="",i=()=>{n&&(s.push(I.literal(n)),n="")};for(;r{i&&(r.push(I.literal(i)),i="")};for(;n=2&&t[0]==='"'&&t[t.length-1]==='"'){let m=t.slice(1,-1),p=!1;for(let y=0;y{d&&(c.push(I.literal(d)),d="")};for(;f0?t[f-1]:"";if(f===0||p==="="||n&&p===":"){let b=pa(e,t,f),v=t[b];if(v===void 0||v==="/"||v===":"){h();let E=t.slice(f+1,b)||null;c.push({type:"TildeExpansion",user:E}),f=b;continue}}}if("@*+?!".includes(m)&&f+1Ki)throw new Ee("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}enterDepth(){if(this.parseDepth++,this.parseDepth>Xn)throw new Ee(`Maximum parser nesting depth exceeded (${Xn})`,this.current().line,this.current().column);return()=>{this.parseDepth--}}parse(t,s){if(t.length>Qn)throw new Ee(`Input too large: ${t.length} bytes exceeds limit of ${Qn}`,1,1);this._input=t;let r=new Ws(t,s);if(this.tokens=r.tokenize(),this.tokens.length>Kn)throw new Ee(`Too many tokens: ${this.tokens.length} exceeds limit of ${Kn}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseDepth=0,this.parseScript()}parseTokens(t){return this.tokens=t,this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseDepth=0,this.parseScript()}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(t=0){return this.tokens[this.pos+t]||this.tokens[this.tokens.length-1]}advance(){let t=this.current();return this.pos0?i.includes(a):!1}expect(t,s){if(this.check(t))return this.advance();let r=this.current();throw new Ee(s||`Expected ${t}, got ${r.type}`,r.line,r.column,r)}error(t){let s=this.current();throw new Ee(t,s.line,s.column,s)}skipNewlines(){for(;this.check(g.NEWLINE,g.COMMENT);)this.check(g.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(t=!0){for(;;){if(this.check(g.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(g.SEMICOLON,g.COMMENT)){this.advance();continue}if(t&&this.check(g.DSEMI,g.SEMI_AND,g.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(t,s,r,n){this.pendingHeredocs.push({redirect:t,delimiter:s,stripTabs:r,quoted:n})}processHeredocs(){for(let t of this.pendingHeredocs)if(this.check(g.HEREDOC_CONTENT)){let s=this.advance(),r;t.quoted?r=I.word([I.literal(s.value)]):r=this.parseWordFromString(s.value,!1,!1,!1,!0),t.redirect.target=I.hereDoc(t.delimiter,r,t.stripTabs,t.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(g.EOF,g.NEWLINE,g.SEMICOLON,g.AMP,g.AND_AND,g.OR_OR,g.RPAREN,g.RBRACE,g.DSEMI,g.SEMI_AND,g.SEMI_SEMI_AND)}isCommandStart(){let t=this.current().type;return t===g.WORD||t===g.NAME||t===g.NUMBER||t===g.ASSIGNMENT_WORD||t===g.IF||t===g.FOR||t===g.WHILE||t===g.UNTIL||t===g.CASE||t===g.LPAREN||t===g.LBRACE||t===g.DPAREN_START||t===g.DBRACK_START||t===g.FUNCTION||t===g.BANG||t===g.TIME||t===g.IN||t===g.LESS||t===g.GREAT||t===g.DLESS||t===g.DGREAT||t===g.LESSAND||t===g.GREATAND||t===g.LESSGREAT||t===g.DLESSDASH||t===g.CLOBBER||t===g.TLESS||t===g.AND_GREAT||t===g.AND_DGREAT}parseScript(){let t=[],r=0;for(this.skipNewlines();!this.check(g.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)");let n=this.checkUnexpectedToken();if(n){t.push(n),this.skipSeparators(!1);continue}let i=this.pos,a=this.parseStatement();a&&t.push(a),this.skipSeparators(!1),this.check(g.DSEMI,g.SEMI_AND,g.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===i&&!this.check(g.EOF)&&this.advance()}return I.script(t)}checkUnexpectedToken(){let t=this.current().type,s=this.current().value;if((t===g.DO||t===g.DONE||t===g.THEN||t===g.ELSE||t===g.ELIF||t===g.FI||t===g.ESAC)&&this.error(`syntax error near unexpected token \`${s}'`),t===g.RBRACE||t===g.RPAREN){let r=`syntax error near unexpected token \`${s}'`;return this.advance(),I.statement([I.pipeline([I.simpleCommand(null,[],[],[])])],[],!1,{message:r,token:s})}return(t===g.DSEMI||t===g.SEMI_AND||t===g.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${s}'`),t===g.SEMICOLON&&this.error(`syntax error near unexpected token \`${s}'`),(t===g.PIPE||t===g.PIPE_AMP)&&this.error(`syntax error near unexpected token \`${s}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let t=this.current().start,s=[],r=[],n=!1,i=this.parsePipeline();for(s.push(i);this.check(g.AND_AND,g.OR_OR);){let o=this.advance();r.push(o.type===g.AND_AND?"&&":"||"),this.skipNewlines();let u=this.parsePipeline();s.push(u)}this.check(g.AMP)&&(this.advance(),n=!0);let a=this.pos>0?this.tokens[this.pos-1].end:t,l=this._input.slice(t,a);return I.statement(s,r,n,void 0,l)}parsePipeline(){let t=!1,s=!1;this.check(g.TIME)&&(this.advance(),t=!0,this.check(g.WORD,g.NAME)&&this.current().value==="-p"&&(this.advance(),s=!0));let r=0;for(;this.check(g.BANG);)this.advance(),r++;let n=r%2===1,i=[],a=[],l=this.parseCommand();for(i.push(l);this.check(g.PIPE,g.PIPE_AMP);){let o=this.advance();this.skipNewlines(),a.push(o.type===g.PIPE_AMP);let u=this.parseCommand();i.push(u)}return I.pipeline(i,n,t,s,a.length>0?a:void 0)}parseCommand(){return this.check(g.IF)?rr(this):this.check(g.FOR)?ir(this):this.check(g.WHILE)?ar(this):this.check(g.UNTIL)?or(this):this.check(g.CASE)?lr(this):this.check(g.LPAREN)?cr(this):this.check(g.LBRACE)?ur(this):this.check(g.DPAREN_START)?this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand():this.check(g.DBRACK_START)?this.parseConditionalCommand():this.check(g.FUNCTION)?this.parseFunctionDef():this.check(g.NAME,g.WORD)&&this.peek(1).type===g.LPAREN&&this.peek(2).type===g.RPAREN?this.parseFunctionDef():va(this)}dparenClosesWithSpacedParens(){let t=1,s=1;for(;snew e,r=>this.error(r))}parseBacktickSubstitution(t,s,r=!1){return Ui(t,s,r,()=>new e,n=>this.error(n))}isDollarDparenSubshell(t,s){return qi(t,s)}parseArithmeticExpansion(t,s){let r=s+3,n=1,i=0,a=r;for(;a0;)t[a]==="$"&&t[a+1]==="("?t[a+2]==="("?(n++,a+=3):(i++,a+=2):t[a]==="("&&t[a+1]==="("?(n++,a+=2):t[a]===")"&&t[a+1]===")"?i>0?(i--,a++):(n--,n>0&&(a+=2)):t[a]==="("?(i++,a++):(t[a]===")"&&i>0&&i--,a++);let l=t.slice(r,a),o=this.parseArithmeticExpression(l);return{part:I.arithmeticExpansion(o),endIndex:a+2}}parseArithmeticCommand(){let t=this.expect(g.DPAREN_START),s="",r=1,n=0,i=!1,a=!1;for(;r>0&&!this.check(g.EOF);){if(i){if(i=!1,n>0){n--,s+=")";continue}if(this.check(g.RPAREN)){r--,a=!0,this.advance();continue}if(this.check(g.DPAREN_END)){r--,a=!0;continue}s+=")";continue}if(this.check(g.DPAREN_START))r++,s+="((",this.advance();else if(this.check(g.DPAREN_END))n>=2?(n-=2,s+="))",this.advance()):n===1?(n--,s+=")",i=!0,this.advance()):(r--,a=!0,r>0&&(s+="))"),this.advance());else if(this.check(g.LPAREN))n++,s+="(",this.advance();else if(this.check(g.RPAREN))n>0&&n--,s+=")",this.advance();else{let u=this.current().value,c=s.length>0?s[s.length-1]:"";s.length>0&&!s.endsWith(" ")&&!(u==="="&&/[|&^+\-*/%<>]$/.test(s))&&!(u==="<"&&c==="<")&&!(u===">"&&c===">")&&(s+=" "),s+=u,this.advance()}}a||this.expect(g.DPAREN_END);let l=this.parseArithmeticExpression(s.trim()),o=this.parseOptionalRedirections();return I.arithmeticCommand(l,o,t.line)}parseConditionalCommand(){let t=this.expect(g.DBRACK_START),s=dr(this);this.expect(g.DBRACK_END);let r=this.parseOptionalRedirections();return I.conditionalCommand(s,r,t.line)}parseFunctionDef(){let t;if(this.check(g.FUNCTION)){if(this.advance(),this.check(g.NAME)||this.check(g.WORD))t=this.advance().value;else{let n=this.current();throw new Ee("Expected function name",n.line,n.column,n)}this.check(g.LPAREN)&&(this.advance(),this.expect(g.RPAREN))}else t=this.advance().value,t.includes("$")&&this.error(`\`${t}': not a valid identifier`),this.expect(g.LPAREN),this.expect(g.RPAREN);this.skipNewlines();let s=this.parseCompoundCommandBody({forFunctionBody:!0}),r=this.parseOptionalRedirections();return I.functionDef(t,s,r)}parseCompoundCommandBody(t){let s=t?.forFunctionBody;if(this.check(g.LBRACE))return ur(this,{skipRedirections:s});if(this.check(g.LPAREN))return cr(this,{skipRedirections:s});if(this.check(g.IF))return rr(this,{skipRedirections:s});if(this.check(g.FOR))return ir(this,{skipRedirections:s});if(this.check(g.WHILE))return ar(this,{skipRedirections:s});if(this.check(g.UNTIL))return or(this,{skipRedirections:s});if(this.check(g.CASE))return lr(this,{skipRedirections:s});this.error("Expected compound command for function body")}parseCompoundList(){let t=this.enterDepth(),s=[];for(this.skipNewlines();!this.check(g.EOF,g.FI,g.ELSE,g.ELIF,g.THEN,g.DO,g.DONE,g.ESAC,g.RPAREN,g.RBRACE,g.DSEMI,g.SEMI_AND,g.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,n=this.parseStatement();if(n&&s.push(n),this.skipSeparators(),this.pos===r&&!n)break}return t(),s}parseOptionalRedirections(){let t=[];for(;zs(this);){this.checkIterationLimit();let s=this.pos;if(t.push(Bs(this)),this.pos===s)break}return t}parseArithmeticExpression(t){return Y(this,t)}};function Ce(e,t){return new q().parse(e,t)}var $u="BASH_ALIAS_";function ka(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Na(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function _a(e,t){return e.env.get(`${$u}${t}`)}function mr(e,t,s){if(!t.name||!ka(t.name))return t;let r=Na(t.name);if(!r)return t;let n=_a(e,r);if(!n||s.has(r))return t;try{s.add(r);let i=new q,a=n,l=n.endsWith(" ");if(!l)for(let f of t.args){let d=Ca(f);a+=` ${d}`}let o;try{o=i.parse(a)}catch(f){if(f instanceof Ee)throw f;return t}if(o.statements.length!==1||o.statements[0].pipelines.length!==1||o.statements[0].pipelines[0].commands.length!==1)return xa(t,n);let u=o.statements[0].pipelines[0].commands[0];if(u.type!=="SimpleCommand")return xa(t,n);let c={...u,assignments:[...t.assignments,...u.assignments],redirections:[...u.redirections,...t.redirections],line:t.line};if(l&&t.args.length>0&&(c={...c,args:[...c.args,...t.args]},c.args.length>0)){let f=c.args[0];if(ka(f)){let d=Na(f);if(d&&_a(e,d)){let h={type:"SimpleCommand",name:f,args:c.args.slice(1),assignments:[],redirections:[]},m=mr(e,h,s);m!==h&&(c={...c,name:m.name,args:[...m.args]})}}}return c}catch(i){throw s.delete(r),i}}function xa(e,t){let s=t;for(let a of e.args){let l=Ca(a);s+=` ${l}`}let r=new q,n=r.parseWordFromString("eval",!1,!1),i=r.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:n,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Ca(e){let t="";for(let s of e.parts)switch(s.type){case"Literal":t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,"\\$1");break;case"SingleQuoted":t+=`'${s.value}'`;break;case"DoubleQuoted":t+=`"${s.parts.map(r=>r.type==="Literal"?r.value:`$${r.type}`).join("")}"`;break;case"ParameterExpansion":t+=`\${${s.parameter}}`;break;case"CommandSubstitution":t+="$(...)";break;case"ArithmeticExpansion":t+=`$((${s.expression}))`;break;case"Glob":t+=s.pattern;break;default:break}return t}var Pu=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9a-fA-F"]]);function gr(e){return Pu.get(e)??""}function Da(e){let t=[],s="",r=0;for(;r0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function wr(e){let t=[],s="",r=0,n=!1,i=0;for(;ithis.maxOps)throw new X(`Glob operation limit exceeded (${this.maxOps})`,"glob_operations")}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(t){return!this.hasGlobignore&&!this.globskipdots?t:t.filter(s=>{let r=s.split("/").pop()||s;if((this.hasGlobignore||this.globskipdots)&&(r==="."||r===".."))return!1;if(this.hasGlobignore){for(let n of this.globignorePatterns)if(this.matchGlobignorePattern(s,n))return!1}return!0})}matchGlobignorePattern(t,s){return Ra(s).test(t)}isGlobPattern(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandArgs(t,s){let r=t.map((a,l)=>(s?.[l]??!1)||!this.isGlobPattern(a)?null:this.expand(a)),n=await Promise.all(r.map(a=>a||Promise.resolve(null))),i=[];for(let a=0;a0?i.push(...l):i.push(t[a])}return i}async expand(t){if(this.globstar){let r=t.split("/"),n=0;for(let i of r)if(i==="**"&&(n++,n>Ia))throw new X(`Glob pattern has too many ** segments (max ${Ia})`,"glob_operations")}let s;if(t.includes("**")&&this.globstar&&this.isGlobstarValid(t))s=await this.expandRecursive(t);else{let r=t.replace(/\*\*+/g,"*");s=await this.expandSimple(r)}return this.filterGlobignore(s)}isGlobstarValid(t){let s=t.split("/");for(let r of s)if(r.includes("**")&&r!=="**")return!1;return!0}hasGlobChars(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandSimple(t){let s=t.startsWith("/"),r=t.split("/").filter(u=>u!==""),n=-1;for(let u=0;um.name==="."),h=l.some(m=>m.name==="..");d||u.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),h||u.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let d of u)if(!(d.name.startsWith(".")&&!n.startsWith(".")&&!c)&&this.matchPattern(d.name,n)){let h=t==="/"?`/${d.name}`:`${t}/${d.name}`,m;s===""?m=d.name:s==="/"?m=`/${d.name}`:m=`${s}/${d.name}`,i.length===0?o.push(Promise.resolve([m])):d.isDirectory&&o.push(this.expandSegments(h,m,i))}let f=await Promise.all(o);for(let d of f)a.push(...d)}else{this.checkOpsLimit();let l=await this.fs.readdir(t),o=[],u=[...l],c=this.dotglob||this.hasGlobignore;(n.startsWith(".")||this.dotglob)&&(l.includes(".")||u.push("."),l.includes("..")||u.push(".."));for(let d of u)if(!(d.startsWith(".")&&!n.startsWith(".")&&!c)&&this.matchPattern(d,n)){let h=t==="/"?`/${d}`:`${t}/${d}`,m;s===""?m=d:s==="/"?m=`/${d}`:m=`${s}/${d}`,i.length===0?o.push(Promise.resolve([m])):o.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(h)).isDirectory)return this.expandSegments(h,m,i)}catch(p){if(p instanceof X)throw p}return[]})())}let f=await Promise.all(o);for(let d of f)a.push(...d)}}catch(l){if(l instanceof X)throw l}return a}async expandRecursive(t){let s=[],r=t.indexOf("**"),n=t.slice(0,r).replace(/\/$/,"")||".",a=t.slice(r+2).replace(/^\//,"");return a.includes("**")&&this.isGlobstarValid(a)?(await this.walkDirectoryMultiGlobstar(n,a,s),[...new Set(s)].sort()):(await this.walkDirectory(n,a,s),s.sort())}async walkDirectoryMultiGlobstar(t,s,r){this.checkOpsLimit();let n=this.fs.resolvePath(this.cwd,t);try{this.checkOpsLimit();let i=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(n):null;if(i){let a=[];for(let u of i){let c=t==="."?u.name:`${t}/${u.name}`;u.isDirectory&&a.push(c)}let l=t==="."?s:`${t}/${s}`,o=await this.expandRecursive(l);r.push(...o);for(let u=0;uthis.walkDirectoryMultiGlobstar(f,s,r)))}}else{this.checkOpsLimit();let a=await this.fs.readdir(n),l=[];for(let c of a){let f=t==="."?c:`${t}/${c}`,d=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory&&l.push(f)}catch(h){if(h instanceof X)throw h}}let o=t==="."?s:`${t}/${s}`,u=await this.expandRecursive(o);r.push(...u);for(let c=0;cthis.walkDirectoryMultiGlobstar(d,s,r)))}}}catch(i){if(i instanceof X)throw i}}async walkDirectory(t,s,r){this.checkOpsLimit();let n=this.fs.resolvePath(this.cwd,t);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let i=await this.fs.readdirWithFileTypes(n),a=[],l=[];for(let o of i){let u=t==="."?o.name:`${t}/${o.name}`;o.isDirectory?l.push(u):s&&this.matchPattern(o.name,s)&&a.push(u)}r.push(...a);for(let o=0;othis.walkDirectory(c,s,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(n),a=[];for(let o=0;o{let d=t==="."?f:`${t}/${f}`,h=this.fs.resolvePath(this.cwd,d);try{this.checkOpsLimit();let m=await this.fs.stat(h);return{name:f,path:d,isDirectory:m.isDirectory}}catch(m){if(m instanceof X)throw m;return null}}));a.push(...c.filter(f=>f!==null))}for(let o of a)!o.isDirectory&&s&&this.matchPattern(o.name,s)&&r.push(o.path);let l=a.filter(o=>o.isDirectory);for(let o=0;othis.walkDirectory(c.path,s,r)))}}}catch(i){if(i instanceof X)throw i}}matchPattern(t,s){return this.patternToRegex(s).test(t)}patternToRegex(t){let s=this.patternToRegexStr(t);return le(`^${s}$`)}patternToRegexStr(t){let s="",r=!1;for(let n=0;nthis.patternToRegexStr(f)),c=u.length>0?u.join("|"):"(?:)";if(i==="@")s+=`(?:${c})`;else if(i==="*")s+=`(?:${c})*`;else if(i==="+")s+=`(?:${c})+`;else if(i==="?")s+=`(?:${c})?`;else if(i==="!")if(athis.computePatternLength(m));if(d.every(m=>m!==null)&&d.every(m=>m===d[0])&&d[0]!==null){let m=d[0];if(m===0)s+="(?:.+)";else{let p=[];m>0&&p.push(`.{0,${m-1}}`),p.push(`.{${m+1},}`),p.push(`(?!(?:${c})).{${m}}`),s+=`(?:${p.join("|")})`}}else s+=`(?:(?!(?:${c})).)*?`}else s+=`(?!(?:${c})$).*`;n=a;continue}}if(i==="*")s+=".*";else if(i==="?")s+=".";else if(i==="["){let a=n+1,l="[";athis.computePatternLength(c));if(u.every(c=>c!==null)&&u.every(c=>c===u[0])){s+=u[0],r=a+1;continue}return null}return null}}if(i==="*")return null;if(i==="?"){s+=1,r++;continue}if(i==="["){let a=t.indexOf("]",r+1);if(a!==-1){s+=1,r=a+1;continue}s+=1,r++;continue}if(i==="\\"){s+=1,r+=2;continue}s+=1,r++}return s}};function Er(e){for(let t=0;tn-i)}function tt(e,t){let s=`${t}_`;for(let r of e.state.env.keys())r.startsWith(s)&&e.state.env.delete(r)}function Ge(e,t){let s=`${t}_`,r=`${t}__length`,n=[];for(let i of e.state.env.keys())if(i!==r&&i.startsWith(s)){let a=i.slice(s.length);if(a.startsWith("_length"))continue;n.push(a)}return n.sort()}function qs(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function br(e){if(e.parts.length<2)return null;let t=e.parts[0],s=e.parts[1];if(t.type!=="Glob"||!t.pattern.startsWith("["))return null;let r,n=s,i=1;if(s.type==="Literal"&&s.value.startsWith("]")){let f=s.value.slice(1);if(f.startsWith("+=")||f.startsWith("="))r=t.pattern.slice(1);else if(f===""){if(e.parts.length<3)return null;let d=e.parts[2];if(d.type!=="Literal"||!d.value.startsWith("=")&&!d.value.startsWith("+="))return null;r=t.pattern.slice(1),n=d,i=2}else return null}else if(t.pattern==="["&&(s.type==="DoubleQuoted"||s.type==="SingleQuoted")){if(e.parts.length<3)return null;let f=e.parts[2];if(f.type!=="Literal"||!f.value.startsWith("]=")&&!f.value.startsWith("]+="))return null;if(s.type==="SingleQuoted")r=s.value;else{r="";for(let d of s.parts)(d.type==="Literal"||d.type==="Escaped")&&(r+=d.value)}n=f,i=2}else if(t.pattern.endsWith("]")){if(s.type!=="Literal"||!s.value.startsWith("=")&&!s.value.startsWith("+="))return null;r=t.pattern.slice(1,-1)}else return null;r=qs(r);let a;if(n.type!=="Literal")return null;n.value.startsWith("]=")||n.value.startsWith("]+=")?a=n.value.slice(1):a=n.value;let l=a.startsWith("+=");if(!l&&!a.startsWith("="))return null;let o=[],u=l?2:1,c=a.slice(u);c&&o.push({type:"Literal",value:c});for(let f=i+1;f{if(s.type==="Range"){let r=s.startStr??String(s.start),n=s.endStr??String(s.end),i=`${r}..${n}`;return s.step&&(i+=`..${s.step}`),i}return Ut(s.word)}).join(",")}}`}function Ut(e){let t="";for(let s of e.parts)switch(s.type){case"Literal":t+=s.value;break;case"Glob":t+=s.pattern;break;case"SingleQuoted":t+=s.value;break;case"DoubleQuoted":for(let r of s.parts)(r.type==="Literal"||r.type==="Escaped")&&(t+=r.value);break;case"Escaped":t+=s.value;break;case"BraceExpansion":t+="{",t+=s.items.map(r=>r.type==="Range"?`${r.startStr}..${r.endStr}${r.step?`..${r.step}`:""}`:Ut(r.word)).join(","),t+="}";break;case"TildeExpansion":t+="~",s.user&&(t+=s.user);break}return t}function me(e){return e.get("IFS")??` `}function ve(e){return e.get("IFS")===""}function js(e){let t=me(e);if(t==="")return!0;for(let s of t)if(s!==" "&&s!==" "&&s!==` `)return!1;return!0}function Ta(e){let t=!1,s=[];for(let r of e.split(""))r==="-"?t=!0:/[\\^$.*+?()[\]{}|]/.test(r)?s.push(`\\${r}`):r===" "?s.push("\\t"):r===` `?s.push("\\n"):s.push(r);return t&&s.push("\\-"),s.join("")}function j(e){let t=e.get("IFS");return t===void 0?" ":t[0]||""}var _u=` `;function xu(e){return _u.includes(e)}function vr(e){let t=new Set,s=new Set;for(let r of e)xu(r)?t.add(r):s.add(r);return{whitespace:t,nonWhitespace:s}}function Sr(e,t,s,r){if(t==="")return e===""?{words:[],wordStarts:[]}:{words:[e],wordStarts:[0]};let{whitespace:n,nonWhitespace:i}=vr(t),a=[],l=[],o=0;for(;o=e.length)return{words:[],wordStarts:[]};if(i.has(e[o]))for(a.push(""),l.push(o),o++;o=s);){let u=o;for(l.push(u);o=e.length)break;for(;o=s);)for(a.push(""),l.push(o),o++;oo&&(a=!0),i>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(r.has(e[i]))for(n.push(""),i++;i=e.length){l=!1;break}let c=i;for(;i=e.length&&i>c&&(l=!0)}return{words:n,hadLeadingDelimiter:a,hadTrailingDelimiter:l}}function re(e,t){return Us(e,t).words}function Cu(e,t){for(let s of e)if(t.has(s))return!0;return!1}function La(e,t,s){if(t==="")return e;let{whitespace:r,nonWhitespace:n}=vr(t),i=e.length;for(;i>0&&r.has(e[i-1]);){if(!s&&i>=2){let l=0,o=i-2;for(;o>=0&&e[o]==="\\";)l++,o--;if(l%2===1)break}i--}let a=e.substring(0,i);if(a.length>=1&&n.has(a[a.length-1])){if(!s&&a.length>=2){let o=0,u=a.length-2;for(;u>=0&&a[u]==="\\";)o++,u--;if(o%2===1)return a}let l=a.substring(0,a.length-1);if(!Cu(l,n))return l}return a}function te(e,t){return e.state.namerefs?.has(t)??!1}function pt(e,t){e.state.namerefs??=new Set,e.state.namerefs.add(t)}function Ma(e,t){e.state.namerefs?.delete(t),e.state.boundNamerefs?.delete(t),e.state.invalidNamerefs?.delete(t)}function Wa(e,t){e.state.invalidNamerefs??=new Set,e.state.invalidNamerefs.add(t)}function Fa(e,t){return e.state.invalidNamerefs?.has(t)??!1}function Ar(e,t){e.state.boundNamerefs??=new Set,e.state.boundNamerefs.add(t)}function Zs(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let n=s[1],i=Array.from(e.state.env.keys()).some(l=>l.startsWith(`${n}_`)&&!l.includes("__")),a=e.state.associativeArrays?.has(n)??!1;return i||a}return Array.from(e.state.env.keys()).some(n=>n.startsWith(`${t}_`)&&!n.includes("__"))?!0:e.state.env.has(t)}function $e(e,t,s=100){if(!te(e,t)||Fa(e,t))return t;let r=new Set,n=t;for(;s-- >0;){if(r.has(n))return;if(r.add(n),!te(e,n))return n;let i=e.state.env.get(n);if(i===void 0||i===""||!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(i))return n;n=i}}function Tt(e,t){if(te(e,t))return e.state.env.get(t)}function Va(e,t,s,r=100){if(!te(e,t)||Fa(e,t))return t;let n=new Set,i=t;for(;r-- >0;){if(n.has(i))return;if(n.add(i),!te(e,i))return i;let a=e.state.env.get(i);if(a===void 0||a==="")return s!==void 0?/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)&&Zs(e,s)?i:null:i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(a))return i;i=a}}function Du(e,t){let s=t.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g,(r,n)=>e.state.env.get(n)??"");return s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,n)=>e.state.env.get(n)??""),s}function B(e,t){return t==="FUNCNAME"?(e.state.funcNameStack??[]).map((i,a)=>[a,i]):t==="BASH_LINENO"?(e.state.callLineStack??[]).map((i,a)=>[a,String(i)]):t==="BASH_SOURCE"?(e.state.sourceStack??[]).map((i,a)=>[a,i]):e.state.associativeArrays?.has(t)?Ge(e,t).map(i=>[i,e.state.env.get(`${t}_${i}`)??""]):he(e,t).map(n=>[n,e.state.env.get(`${t}_${n}`)??""])}function He(e,t){return t==="FUNCNAME"?(e.state.funcNameStack?.length??0)>0:t==="BASH_LINENO"?(e.state.callLineStack?.length??0)>0:t==="BASH_SOURCE"?(e.state.sourceStack?.length??0)>0:e.state.associativeArrays?.has(t)?Ge(e,t).length>0:he(e,t).length>0}async function J(e,t,s=!0,r=!1){switch(t){case"?":return String(e.state.lastExitCode);case"$":return String(e.state.virtualPid);case"#":return e.state.env.get("#")||"0";case"@":return e.state.env.get("@")||"";case"_":return e.state.lastArg;case"-":{let a="";return a+="h",e.state.options.errexit&&(a+="e"),e.state.options.noglob&&(a+="f"),e.state.options.nounset&&(a+="u"),e.state.options.verbose&&(a+="v"),e.state.options.xtrace&&(a+="x"),a+="B",e.state.options.noclobber&&(a+="C"),a+="s",a}case"*":{let a=Number.parseInt(e.state.env.get("#")||"0",10);if(a===0)return"";let l=[];for(let o=1;o<=a;o++)l.push(e.state.env.get(String(o))||"");return l.join(j(e.state.env))}case"0":return e.state.env.get("0")||"bash";case"PWD":return e.state.env.get("PWD")??"";case"OLDPWD":return e.state.env.get("OLDPWD")??"";case"PPID":return String(e.state.virtualPpid);case"UID":return String(e.state.virtualUid);case"EUID":return String(e.state.virtualUid);case"RANDOM":return String(Math.floor(Math.random()*32768));case"SECONDS":return String(Math.floor((Date.now()-e.state.startTime)/1e3));case"BASH_VERSION":return Vi;case"!":return String(e.state.lastBackgroundPid);case"BASHPID":return String(e.state.bashPid);case"LINENO":return String(e.state.currentLine);case"FUNCNAME":{let a=e.state.funcNameStack?.[0];if(a!==void 0)return a;if(s&&e.state.options.nounset)throw new Le("FUNCNAME");return""}case"BASH_LINENO":{let a=e.state.callLineStack?.[0];if(a!==void 0)return String(a);if(s&&e.state.options.nounset)throw new Le("BASH_LINENO");return""}case"BASH_SOURCE":{let a=e.state.sourceStack?.[0];if(a!==void 0)return a;if(s&&e.state.options.nounset)throw new Le("BASH_SOURCE");return""}}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(t))throw new Me(`\${${t}}`);let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let a=n[1],l=n[2];if(te(e,a)){let f=$e(e,a);if(f&&f!==a){if(f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return"";a=f}}if(l==="@"||l==="*"){let f=B(e,a);if(f.length>0)return f.map(([,h])=>h).join(" ");let d=e.state.env.get(a);return d!==void 0?d:""}if(a==="FUNCNAME"){let f=Number.parseInt(l,10);return!Number.isNaN(f)&&f>=0?e.state.funcNameStack?.[f]??"":""}if(a==="BASH_LINENO"){let f=Number.parseInt(l,10);if(!Number.isNaN(f)&&f>=0){let d=e.state.callLineStack?.[f];return d!==void 0?String(d):""}return""}if(a==="BASH_SOURCE"){let f=Number.parseInt(l,10);return!Number.isNaN(f)&&f>=0?e.state.sourceStack?.[f]??"":""}if(e.state.associativeArrays?.has(a)){let f=qs(l);f=Du(e,f);let d=e.state.env.get(`${a}_${f}`);if(d===void 0&&s&&e.state.options.nounset)throw new Le(`${a}[${l}]`);return d||""}let u;if(/^-?\d+$/.test(l))u=Number.parseInt(l,10);else try{let f=new q,d=Y(f,l);u=await T(e,d.expression)}catch{let f=e.state.env.get(l);u=f?Number.parseInt(f,10):0,Number.isNaN(u)&&(u=0)}if(u<0){let f=B(e,a),d=e.state.currentLine;if(f.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${a}: bad array subscript `,"";let m=Math.max(...f.map(([y])=>typeof y=="number"?y:0))+1+u;return m<0?(e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${a}: bad array subscript `,""):e.state.env.get(`${a}_${m}`)||""}let c=e.state.env.get(`${a}_${u}`);if(c!==void 0)return c;if(u===0){let f=e.state.env.get(a);if(f!==void 0)return f}if(s&&e.state.options.nounset)throw new Le(`${a}[${u}]`);return""}if(/^[1-9][0-9]*$/.test(t)){let a=e.state.env.get(t);if(a===void 0&&s&&e.state.options.nounset)throw new Le(t);return a||""}if(te(e,t)){let a=$e(e,t);if(a===void 0)return"";if(a!==t)return await J(e,a,s,r);let l=e.state.env.get(t);if((l===void 0||l==="")&&s&&e.state.options.nounset)throw new Le(t);return l||""}let i=e.state.env.get(t);if(i!==void 0)return e.state.tempEnvBindings?.some(a=>a.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),i;if(He(e,t)){let a=e.state.env.get(`${t}_0`);return a!==void 0?a:""}if(s&&e.state.options.nounset)throw new Le(t);return""}async function st(e,t){if(new Set(["?","$","#","_","-","0","PPID","UID","EUID","RANDOM","SECONDS","BASH_VERSION","!","BASHPID","LINENO"]).has(t))return!0;if(t==="@"||t==="*")return Number.parseInt(e.state.env.get("#")||"0",10)>0;if(t==="PWD"||t==="OLDPWD")return e.state.env.has(t);let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let n=r[1],i=r[2];if(te(e,n)){let o=$e(e,n);if(o&&o!==n){if(o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;n=o}}if(i==="@"||i==="*")return B(e,n).length>0?!0:e.state.env.has(n);if(e.state.associativeArrays?.has(n)){let o=qs(i);return e.state.env.has(`${n}_${o}`)}let l;if(/^-?\d+$/.test(i))l=Number.parseInt(i,10);else try{let o=new q,u=Y(o,i);l=await T(e,u.expression)}catch{let o=e.state.env.get(i);l=o?Number.parseInt(o,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let o=B(e,n);if(o.length===0)return!1;let c=Math.max(...o.map(([f])=>typeof f=="number"?f:0))+1+l;return c<0?!1:e.state.env.has(`${n}_${c}`)}return e.state.env.has(`${n}_${l}`)}if(te(e,t)){let n=$e(e,t);return n===void 0||n===t?e.state.env.has(t):st(e,n)}return!!(e.state.env.has(t)||He(e,t))}async function za(e,t){let s="",r=0;for(;r0;)t[i]==="{"?n++:t[i]==="}"&&n--,i++;s+=t.slice(r,i),r=i;continue}if(t[r+1]==="("){let n=1,i=r+2;for(;i0;)t[i]==="("?n++:t[i]===")"&&n--,i++;s+=t.slice(r,i),r=i;continue}if(/[a-zA-Z_]/.test(t[r+1]||"")){let n=r+1;for(;n0;)s[o]==="("&&s[o-1]==="$"||s[o]==="("?l++:s[o]===")"&&l--,o++;let u=s.slice(a+2,o-1);if(e.execFn){let c=await e.execFn(u,{signal:e.state.signal});i+=c.stdout.replace(/\n+$/,""),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr)}a=o}else if(s[a+1]==="{"){let l=1,o=a+2;for(;o0;)s[o]==="{"?l++:s[o]==="}"&&l--,o++;let u=s.slice(a+2,o-1),c=await J(e,u);i+=c,a=o}else if(/[a-zA-Z_]/.test(s[a+1]||"")){let l=a+1;for(;l{if(o>0){let f=c<0,d=String(Math.abs(c)).padStart(o,"0");return f?`-${d}`:d}return String(c)};if(e<=t)for(let c=e,f=0;c<=t&&f=t&&f="A"&&e<="Z",o=e>="a"&&e<="z",u=t>="A"&&t<="Z",c=t>="a"&&t<="z";if(l&&c||o&&u){let d=s!==void 0?`..${s}`:"";throw new Ds(`{${e}..${t}${d}}: invalid sequence`)}let f=[];if(n<=i)for(let d=n,h=0;d<=i&&h=i&&hG(f,t,s)),c=u.length>0?u.join("|"):"(?:)";i==="@"?r+=`(?:${c})`:i==="*"?r+=`(?:${c})*`:i==="+"?r+=`(?:${c})+`:i==="?"?r+=`(?:${c})?`:i==="!"&&(r+=`(?!(?:${c})$).*`),n=a+1;continue}}if(i==="\\")if(n+10;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function Tu(e){let t=[],s="",r=0,n=0;for(;n0&&s=0;i--){let a=e.slice(i);if(n.test(a))return e.slice(0,i)}return e}function Zt(e,t){let s=Array.from(e.state.env.keys()),r=new Set,n=e.state.associativeArrays??new Set,i=new Set;for(let l of s){let o=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_\d+$/);o&&i.add(o[1]);let u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);u&&i.add(u[1])}let a=l=>{for(let o of n){let u=`${o}_`;if(l.startsWith(u)&&l!==o)return!0}return!1};for(let l of s)if(l.startsWith(t))if(l.includes("__")){let o=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);o?.[1].startsWith(t)&&r.add(o[1])}else if(/_\d+$/.test(l)){let o=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_\d+$/);o?.[1].startsWith(t)&&r.add(o[1])}else a(l)||r.add(l);return[...r].sort()}function Vu(e,t){let s=(i,a=2)=>String(i).padStart(a,"0");if(e===""){let i=s(t.getHours()),a=s(t.getMinutes()),l=s(t.getSeconds());return`${i}:${a}:${l}`}let r="",n=0;for(;n=e.length){r+="%",n++;continue}let i=e[n+1];switch(i){case"H":r+=s(t.getHours());break;case"M":r+=s(t.getMinutes());break;case"S":r+=s(t.getSeconds());break;case"d":r+=s(t.getDate());break;case"m":r+=s(t.getMonth()+1);break;case"Y":r+=t.getFullYear();break;case"y":r+=s(t.getFullYear()%100);break;case"I":{let a=t.getHours()%12;a===0&&(a=12),r+=s(a);break}case"p":r+=t.getHours()<12?"AM":"PM";break;case"P":r+=t.getHours()<12?"am":"pm";break;case"%":r+="%";break;case"a":{r+=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()];break}case"b":{r+=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()];break}default:r+=`%${i}`}n+=2}else r+=e[n],n++;return r}function ms(e,t){let s="",r=0,n=e.state.env.get("USER")||e.state.env.get("LOGNAME")||"user",i=e.state.env.get("HOSTNAME")||"localhost",a=i.split(".")[0],l=e.state.env.get("PWD")||"/",o=e.state.env.get("HOME")||"/",u=l.startsWith(o)?`~${l.slice(o.length)}`:l,c=l.split("/").pop()||l,f=new Date,d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],m=e.state.env.get("__COMMAND_NUMBER")||"1";for(;r=t.length){s+="\\",r++;continue}let y=t[r+1];if(y>="0"&&y<="7"){let b="",v=r+1;for(;v="0"&&t[v]<="7";)b+=t[v],v++;let E=Number.parseInt(b,8)%256;s+=String.fromCharCode(E),r=v;continue}switch(y){case"\\":s+="\\",r+=2;break;case"a":s+="\x07",r+=2;break;case"e":s+="\x1B",r+=2;break;case"n":s+=` `,r+=2;break;case"r":s+="\r",r+=2;break;case"$":s+="$",r+=2;break;case"[":case"]":r+=2;break;case"u":s+=n,r+=2;break;case"h":s+=a,r+=2;break;case"H":s+=i,r+=2;break;case"w":s+=u,r+=2;break;case"W":s+=c,r+=2;break;case"d":{let b=String(f.getDate()).padStart(2," ");s+=`${d[f.getDay()]} ${h[f.getMonth()]} ${b}`,r+=2;break}case"t":{let b=String(f.getHours()).padStart(2,"0"),v=String(f.getMinutes()).padStart(2,"0"),E=String(f.getSeconds()).padStart(2,"0");s+=`${b}:${v}:${E}`,r+=2;break}case"T":{let b=f.getHours()%12;b===0&&(b=12);let v=String(b).padStart(2,"0"),E=String(f.getMinutes()).padStart(2,"0"),w=String(f.getSeconds()).padStart(2,"0");s+=`${v}:${E}:${w}`,r+=2;break}case"@":{let b=f.getHours()%12;b===0&&(b=12);let v=String(b).padStart(2,"0"),E=String(f.getMinutes()).padStart(2,"0"),w=f.getHours()<12?"AM":"PM";s+=`${v}:${E} ${w}`,r+=2;break}case"A":{let b=String(f.getHours()).padStart(2,"0"),v=String(f.getMinutes()).padStart(2,"0");s+=`${b}:${v}`,r+=2;break}case"D":if(r+20&&e.state.localScopes[e.state.localScopes.length-1].has(t)&&!s){for(e.state.localExportedVars||(e.state.localExportedVars=[]);e.state.localExportedVars.lengthi.startsWith(`${t}_`)&&/^[0-9]+$/.test(i.slice(t.length+1))),n=e.state.associativeArrays?.has(t)??!1;return r&&!n&&(s+="a"),n&&(s+="A"),e.state.integerVars?.has(t)&&(s+="i"),te(e,t)&&(s+="n"),rt(e,t)&&(s+="r"),e.state.exportedVars?.has(t)&&(s+="x"),s}async function qa(e,t,s,r){return e.coverage?.hit("bash:expansion:default_value"),(s.isUnset||t.checkEmpty&&s.isEmpty)&&t.word?r(e,t.word.parts,s.inDoubleQuotes):s.effectiveValue}async function ja(e,t,s,r,n){if(e.coverage?.hit("bash:expansion:assign_default"),(r.isUnset||s.checkEmpty&&r.isEmpty)&&s.word){let a=await n(e,s.word.parts,r.inDoubleQuotes),l=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let[,o,u]=l,c;if(/^\d+$/.test(u))c=Number.parseInt(u,10);else{try{let d=new q,h=Y(d,u);c=await T(e,h.expression)}catch{let d=e.state.env.get(u);c=d?Number.parseInt(d,10):0}Number.isNaN(c)&&(c=0)}e.state.env.set(`${o}_${c}`,a);let f=Number.parseInt(e.state.env.get(`${o}__length`)||"0",10);c>=f&&e.state.env.set(`${o}__length`,String(c+1))}else e.state.env.set(t,a);return a}return r.effectiveValue}async function Ua(e,t,s,r,n){if(e.coverage?.hit("bash:expansion:error_if_unset"),r.isUnset||s.checkEmpty&&r.isEmpty){let a=s.word?await n(e,s.word.parts,r.inDoubleQuotes):`${t}: parameter null or not set`;throw new Z(1,"",`bash: ${a} `)}return r.effectiveValue}async function Za(e,t,s,r){return e.coverage?.hit("bash:expansion:use_alternative"),!(s.isUnset||t.checkEmpty&&s.isEmpty)&&t.word?r(e,t.word.parts,s.inDoubleQuotes):""}async function Ga(e,t,s,r,n){e.coverage?.hit("bash:expansion:pattern_removal");let i="",a=e.state.shoptOptions.extglob;if(s.pattern)for(let o of s.pattern.parts)if(o.type==="Glob")i+=G(o.pattern,s.greedy,a);else if(o.type==="Literal")i+=G(o.value,s.greedy,a);else if(o.type==="SingleQuoted"||o.type==="Escaped")i+=Q(o.value);else if(o.type==="DoubleQuoted"){let u=await r(e,o.parts);i+=Q(u)}else if(o.type==="ParameterExpansion"){let u=await n(e,o);i+=G(u,s.greedy,a)}else{let u=await n(e,o);i+=Q(u)}if(s.side==="prefix")return le(`^${i}`,"s").replace(t,"");let l=le(`${i}$`,"s");if(s.greedy)return l.replace(t,"");for(let o=t.length;o>=0;o--){let u=t.slice(o);if(l.test(u))return t.slice(0,o)}return t}async function Ha(e,t,s,r,n){e.coverage?.hit("bash:expansion:pattern_replacement");let i="",a=e.state.shoptOptions.extglob;if(s.pattern)for(let u of s.pattern.parts)if(u.type==="Glob")i+=G(u.pattern,!0,a);else if(u.type==="Literal")i+=G(u.value,!0,a);else if(u.type==="SingleQuoted"||u.type==="Escaped")i+=Q(u.value);else if(u.type==="DoubleQuoted"){let c=await r(e,u.parts);i+=Q(c)}else if(u.type==="ParameterExpansion"){let c=await n(e,u);i+=G(c,!0,a)}else{let c=await n(e,u);i+=Q(c)}let l=s.replacement?await r(e,s.replacement.parts):"";if(s.anchor==="start"?i=`^${i}`:s.anchor==="end"&&(i=`${i}$`),i==="")return t;let o=s.all?"gs":"s";try{let u=le(i,o);if(s.all){let c="",f=0,d=0,h=e.limits.maxStringLength,m=u.exec(t);for(;m!==null&&!(m[0].length===0&&m.index===t.length);){if(c+=t.slice(f,m.index)+l,f=m.index+m[0].length,m[0].length===0&&f++,d++,d%100===0&&c.length>h)throw new X(`pattern replacement: string length limit exceeded (${h} bytes)`,"string_length");m=u.exec(t)}return c+=t.slice(f),c}return u.replace(t,l)}catch(u){if(u instanceof X)throw u;return t}}function Qa(e,t,s){e.coverage?.hit("bash:expansion:length");let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(r){let n=r[1],i=B(e,n);return i.length>0?String(i.length):e.state.env.get(n)!==void 0?"1":"0"}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&He(e,t)){if(t==="FUNCNAME"){let i=e.state.funcNameStack?.[0]||"";return String([...i].length)}if(t==="BASH_LINENO"){let i=e.state.callLineStack?.[0];return String(i!==void 0?[...String(i)].length:0)}let n=e.state.env.get(`${t}_0`)||"";return String([...n].length)}return String([...s].length)}async function Ka(e,t,s,r){e.coverage?.hit("bash:expansion:substring");let n=await T(e,r.offset.expression),i=r.length?await T(e,r.length.expression):void 0;if(t==="@"||t==="*"){let u=Number.parseInt(e.state.env.get("#")||"0",10),c=[];for(let m=1;m<=u;m++)c.push(e.state.env.get(String(m))||"");let f=e.state.env.get("0")||"bash",d,h;if(n<=0)if(d=[f,...c],n<0){if(h=d.length+n,h<0)return""}else h=0;else d=c,h=n-1;if(h<0||h>=d.length)return"";if(i!==void 0){let m=i<0?d.length+i:h+i;return d.slice(h,Math.max(h,m)).join(" ")}return d.slice(h).join(" ")}let a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(a){let u=a[1];if(e.state.associativeArrays?.has(u))throw new Z(1,"",`bash: \${${u}[@]: 0: 3}: bad substitution `);let c=B(e,u),f=0;if(n<0){if(c.length>0){let d=c[c.length-1][0],m=(typeof d=="number"?d:0)+1+n;if(m<0||(f=c.findIndex(([p])=>typeof p=="number"&&p>=m),f<0))return""}}else if(f=c.findIndex(([d])=>typeof d=="number"&&d>=n),f<0)return"";if(i!==void 0){if(i<0)throw new se(`${a[1]}[@]: substring expression < 0`);return c.slice(f,f+i).map(([,d])=>d).join(" ")}return c.slice(f).map(([,d])=>d).join(" ")}let l=[...s],o=n;if(o<0&&(o=Math.max(0,l.length+o)),i!==void 0){if(i<0){let u=l.length+i;return l.slice(o,Math.max(o,u)).join("")}return l.slice(o,o+i).join("")}return l.slice(o).join("")}async function Xa(e,t,s,r,n){if(e.coverage?.hit("bash:expansion:case_modification"),s.pattern){let i=e.state.shoptOptions.extglob,a="";for(let f of s.pattern.parts)if(f.type==="Glob")a+=G(f.pattern,!0,i);else if(f.type==="Literal")a+=G(f.value,!0,i);else if(f.type==="SingleQuoted"||f.type==="Escaped")a+=Q(f.value);else if(f.type==="DoubleQuoted"){let d=await r(e,f.parts);a+=Q(d)}else if(f.type==="ParameterExpansion"){let d=await n(e,f);a+=G(d,!0,i)}let l=le(`^(?:${a})$`),o=s.direction==="upper"?f=>f.toUpperCase():f=>f.toLowerCase(),u="",c=!1;for(let f of t)!s.all&&c?u+=f:l.test(f)?(u+=o(f),c=!0):u+=f;return u}return s.direction==="upper"?s.all?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1):s.all?t.toLowerCase():t.charAt(0).toLowerCase()+t.slice(1)}function Ya(e,t,s,r,n){e.coverage?.hit("bash:expansion:transform");let i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(i&&n.operator==="Q")return B(e,i[1]).map(([,u])=>kt(u)).join(" ");if(i&&n.operator==="a")return Nt(e,i[1]);let a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[.+\]$/);if(a&&n.operator==="a")return Nt(e,a[1]);switch(n.operator){case"Q":return r?"":kt(s);case"P":return ms(e,s);case"a":return Nt(e,t);case"A":return r?"":`${t}=${kt(s)}`;case"E":return s.replace(/\\([\\abefnrtv'"?])/g,(l,o)=>{switch(o){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return` `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return o}});case"K":case"k":return r?"":kt(s);case"u":return s.charAt(0).toUpperCase()+s.slice(1);case"U":return s.toUpperCase();case"L":return s.toLowerCase();default:return s}}async function Ja(e,t,s,r,n,i,a=!1){if(e.coverage?.hit("bash:expansion:indirection"),te(e,t))return Tt(e,t)||"";let l=/^[a-zA-Z_][a-zA-Z0-9_]*\[([@*])\]$/.test(t);if(r){if(n.innerOp?.type==="UseAlternative")return"";throw new Me(`\${!${t}}`)}let o=s;if(l&&(o===""||o.includes(" ")))throw new Me(`\${!${t}}`);let u=o.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(u&&u[1].includes("~"))throw new Me(`\${!${t}}`);if(n.innerOp){let c={type:"ParameterExpansion",parameter:o,operation:n.innerOp};return i(e,c,a)}return await J(e,o)}function eo(e,t){e.coverage?.hit("bash:expansion:array_keys");let r=B(e,t.array).map(([n])=>String(n));return t.star?r.join(j(e.state.env)):r.join(" ")}function to(e,t){e.coverage?.hit("bash:expansion:var_name_prefix");let s=Zt(e,t.prefix);return t.star?s.join(j(e.state.env)):s.join(" ")}function so(e,t,s,r){let n=Number.parseInt(e.state.env.get("#")||"0",10),i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(t==="*")return{isEmpty:n===0,effectiveValue:s};if(t==="@")return{isEmpty:n===0||n===1&&e.state.env.get("1")==="",effectiveValue:s};if(i){let[,a,l]=i,o=B(e,a);if(o.length===0)return{isEmpty:!0,effectiveValue:""};if(l==="*"){let u=j(e.state.env),c=o.map(([,f])=>f).join(u);return{isEmpty:r?c==="":!1,effectiveValue:c}}return{isEmpty:o.length===1&&o.every(([,u])=>u===""),effectiveValue:o.map(([,u])=>u).join(" ")}}return{isEmpty:s==="",effectiveValue:s}}function no(e){let t=0;for(;t0;){let a=e[r];if(a==="\\"&&!n&&r+1y);if(c.length===0){let y=e.state.env.get(l);y!==void 0&&f.push(y)}if(f.length===0)return{values:[],quoted:!0};let d="";u.pattern&&(d=await qu(e,u.pattern,s,r));let h=u.replacement?await s(e,u.replacement.parts):"",m=d;u.anchor==="start"?m=`^${d}`:u.anchor==="end"&&(m=`${d}$`);let p=[];try{let y=le(m,u.all?"g":"");for(let b of f)p.push(y.replace(b,h))}catch{p.push(...f)}if(o){let y=j(e.state.env);return{values:[p.join(y)],quoted:!0}}return{values:p,quoted:!0}}async function lo(e,t,s,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="PatternRemoval")return null;let i=n.parts[0],a=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!a)return null;let l=a[1],o=a[2]==="*",u=i.operation,c=B(e,l),f=c.map(([,p])=>p);if(c.length===0){let p=e.state.env.get(l);p!==void 0&&f.push(p)}if(f.length===0)return{values:[],quoted:!0};let d="",h=e.state.shoptOptions.extglob;if(u.pattern)for(let p of u.pattern.parts)if(p.type==="Glob")d+=G(p.pattern,u.greedy,h);else if(p.type==="Literal")d+=G(p.value,u.greedy,h);else if(p.type==="SingleQuoted"||p.type==="Escaped")d+=Q(p.value);else if(p.type==="DoubleQuoted"){let y=await s(e,p.parts);d+=Q(y)}else if(p.type==="ParameterExpansion"){let y=await r(e,p);d+=G(y,u.greedy,h)}else{let y=await r(e,p);d+=Q(y)}let m=[];for(let p of f)m.push(mt(p,d,u.side,u.greedy));if(o){let p=j(e.state.env);return{values:[m.join(p)],quoted:!0}}return{values:m,quoted:!0}}async function co(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="DefaultValue"&&s.parts[0].operation?.type!=="UseAlternative"&&s.parts[0].operation?.type!=="AssignDefault")return null;let r=s.parts[0],n=r.operation,i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/),a,l=!1;if(i){let o=i[1];l=i[2]==="*";let u=B(e,o),c=u.length>0||e.state.env.has(o),f=u.length===0||u.length===1&&u.every(([,h])=>h===""),d=n.checkEmpty??!1;if(n.type==="UseAlternative"?a=c&&!(d&&f):a=!c||d&&f,!a){if(u.length>0){let m=u.map(([,p])=>p);if(l){let p=j(e.state.env);return{values:[m.join(p)],quoted:!0}}return{values:m,quoted:!0}}let h=e.state.env.get(o);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}}else{let o=r.parameter,u=await st(e,o),c=await J(e,o),f=c==="",d=n.checkEmpty??!1;if(n.type==="UseAlternative"?a=u&&!(d&&f):a=!u||d&&f,!a)return{values:[c],quoted:!0}}if(a&&n.word){let o=n.word.parts,u=null,c=!1;for(let f of o)if(f.type==="ParameterExpansion"&&!f.operation){let d=f.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(d){u=d[1],c=d[2]==="*";break}}if(u){let f=B(e,u);if(f.length>0){let h=f.map(([,m])=>m);if(c||l){let m=j(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}let d=e.state.env.get(u);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}return null}async function uo(e,t,s,r,n){if(!s||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0],a=-1,l="",o=!1,u=null;for(let p=0;pp);if(d.length===0){let p=e.state.env.get(l);if(p!==void 0)h=[p];else{if(o)return{values:[c+f],quoted:!0};let y=c+f;return{values:y?[y]:[],quoted:!0}}}if(u?.type==="PatternRemoval"){let p=u,y="",b=e.state.shoptOptions.extglob;if(p.pattern)for(let v of p.pattern.parts)if(v.type==="Glob")y+=G(v.pattern,p.greedy,b);else if(v.type==="Literal")y+=G(v.value,p.greedy,b);else if(v.type==="SingleQuoted"||v.type==="Escaped")y+=Q(v.value);else if(v.type==="DoubleQuoted"){let E=await n(e,v.parts);y+=Q(E)}else if(v.type==="ParameterExpansion"){let E=await r(e,v);y+=G(E,p.greedy,b)}else{let E=await r(e,v);y+=Q(E)}h=h.map(v=>mt(v,y,p.side,p.greedy))}else if(u?.type==="PatternReplacement"){let p=u,y="";if(p.pattern)for(let E of p.pattern.parts)if(E.type==="Glob")y+=G(E.pattern,!0,e.state.shoptOptions.extglob);else if(E.type==="Literal")y+=G(E.value,!0,e.state.shoptOptions.extglob);else if(E.type==="SingleQuoted"||E.type==="Escaped")y+=Q(E.value);else if(E.type==="DoubleQuoted"){let w=await n(e,E.parts);y+=Q(w)}else if(E.type==="ParameterExpansion"){let w=await r(e,E);y+=G(w,!0,e.state.shoptOptions.extglob)}else{let w=await r(e,E);y+=Q(w)}let b=p.replacement?await n(e,p.replacement.parts):"",v=y;p.anchor==="start"?v=`^${y}`:p.anchor==="end"&&(v=`${y}$`);try{let E=le(v,p.all?"g":"");h=h.map(w=>E.replace(w,b))}catch{}}if(o){let p=j(e.state.env);return{values:[c+h.join(p)+f],quoted:!0}}return h.length===1?{values:[c+h[0]+f],quoted:!0}:{values:[c+h[0],...h.slice(1,-1),h[h.length-1]+f],quoted:!0}}async function fo(e,t,s,r){if(!s||t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0],i=-1,a="",l=!1;for(let h=0;hh);if(c.length===0){let h=e.state.env.get(a);if(h!==void 0)return{values:[o+h+u],quoted:!0};if(l)return{values:[o+u],quoted:!0};let m=o+u;return{values:m?[m]:[],quoted:!0}}if(l){let h=j(e.state.env);return{values:[o+f.join(h)+u],quoted:!0}}return f.length===1?{values:[o+f[0]+u],quoted:!0}:{values:[o+f[0],...f.slice(1,-1),f[f.length-1]+u],quoted:!0}}async function ho(e,t,s){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!=="ParameterExpansion"||r.parts[0].operation?.type!=="Substring")return null;let n=r.parts[0],i=n.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!i)return null;let a=i[1],l=i[2]==="*",o=n.operation;if(e.state.associativeArrays?.has(a))throw new Z(1,"",`bash: \${${a}[@]: 0: 3}: bad substitution `);let u=o.offset?await s(e,o.offset.expression):0,c=o.length?await s(e,o.length.expression):void 0,f=B(e,a),d=0;if(u<0){if(f.length>0){let m=f[f.length-1][0],y=(typeof m=="number"?m:0)+1+u;if(y<0)return{values:[],quoted:!0};d=f.findIndex(([b])=>typeof b=="number"&&b>=y),d<0&&(d=f.length)}}else d=f.findIndex(([m])=>typeof m=="number"&&m>=u),d<0&&(d=f.length);let h;if(c!==void 0){if(c<0)throw new se(`${a}[@]: substring expression < 0`);h=f.slice(d,d+c).map(([,m])=>m)}else h=f.slice(d).map(([,m])=>m);if(h.length===0)return{values:[],quoted:!0};if(l){let m=j(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}function po(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="Transform")return null;let r=s.parts[0],n=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!n)return null;let i=n[1],a=n[2]==="*",l=r.operation,o=B(e,i);if(o.length===0){let f=e.state.env.get(i);if(f!==void 0){let d;switch(l.operator){case"a":d="";break;case"P":d=ms(e,f);break;case"Q":d=kt(f);break;default:d=f}return{values:[d],quoted:!0}}return a?{values:[""],quoted:!0}:{values:[],quoted:!0}}let u=Nt(e,i),c;switch(l.operator){case"a":c=o.map(()=>u);break;case"P":c=o.map(([,f])=>ms(e,f));break;case"Q":c=o.map(([,f])=>kt(f));break;case"u":c=o.map(([,f])=>f.charAt(0).toUpperCase()+f.slice(1));break;case"U":c=o.map(([,f])=>f.toUpperCase());break;case"L":c=o.map(([,f])=>f.toLowerCase());break;default:c=o.map(([,f])=>f)}if(a){let f=j(e.state.env);return{values:[c.join(f)],quoted:!0}}return{values:c,quoted:!0}}function mo(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion")return null;let r=s.parts[0];if(r.operation)return null;let n=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!n)return null;let i=n[1];if(te(e,i)){let o=Tt(e,i);if(o?.endsWith("[@]")||o?.endsWith("[*]"))return{values:[],quoted:!0}}let a=B(e,i);if(a.length>0)return{values:a.map(([,o])=>o),quoted:!0};let l=e.state.env.get(i);return l!==void 0?{values:[l],quoted:!0}:{values:[],quoted:!0}}function go(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation)return null;let n=s.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)||!te(e,n))return null;let i=Tt(e,n);if(!i)return null;let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!a)return null;let l=a[1],o=B(e,l);if(o.length>0)return{values:o.map(([,c])=>c),quoted:!0};let u=e.state.env.get(l);return u!==void 0?{values:[u],quoted:!0}:{values:[],quoted:!0}}async function yo(e,t,s,r,n){if(!s||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let a=i.parts[0],l=a.operation,o=await J(e,a.parameter),u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!u){if(!l.innerOp&&(o==="@"||o==="*")){let m=Number.parseInt(e.state.env.get("#")||"0",10),p=[];for(let y=1;y<=m;y++)p.push(e.state.env.get(String(y))||"");return o==="*"?{values:[p.join(j(e.state.env))],quoted:!0}:{values:p,quoted:!0}}return null}let c=u[1],f=u[2]==="*",d=B(e,c);if(l.innerOp){if(l.innerOp.type==="Substring")return ju(e,d,c,f,l.innerOp);if(l.innerOp.type==="DefaultValue"||l.innerOp.type==="UseAlternative"||l.innerOp.type==="AssignDefault"||l.innerOp.type==="ErrorIfUnset")return Uu(e,d,c,f,l.innerOp,n);if(l.innerOp.type==="Transform"&&l.innerOp.operator==="a"){let p=Nt(e,c),y=d.map(()=>p);return f?{values:[y.join(j(e.state.env))],quoted:!0}:{values:y,quoted:!0}}let m=[];for(let[,p]of d){let y={type:"ParameterExpansion",parameter:"_indirect_elem_",operation:l.innerOp},b=e.state.env.get("_indirect_elem_");e.state.env.set("_indirect_elem_",p);try{let v=await r(e,y,!0);m.push(v)}finally{b!==void 0?e.state.env.set("_indirect_elem_",b):e.state.env.delete("_indirect_elem_")}}return f?{values:[m.join(j(e.state.env))],quoted:!0}:{values:m,quoted:!0}}if(d.length>0){let m=d.map(([,p])=>p);return f?{values:[m.join(j(e.state.env))],quoted:!0}:{values:m,quoted:!0}}let h=e.state.env.get(c);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}async function ju(e,t,s,r,n){let i=n.offset?await T(e,n.offset.expression):0,a=n.length?await T(e,n.length.expression):void 0,l=0;if(i<0){if(t.length>0){let c=t[t.length-1][0],d=(typeof c=="number"?c:0)+1+i;if(d<0)return{values:[],quoted:!0};if(l=t.findIndex(([h])=>typeof h=="number"&&h>=d),l<0)return{values:[],quoted:!0}}}else if(l=t.findIndex(([c])=>typeof c=="number"&&c>=i),l<0)return{values:[],quoted:!0};let o;if(a!==void 0){if(a<0)throw new se(`${s}[@]: substring expression < 0`);o=t.slice(l,l+a)}else o=t.slice(l);let u=o.map(([,c])=>c);return r?{values:[u.join(j(e.state.env))],quoted:!0}:{values:u,quoted:!0}}async function Uu(e,t,s,r,n,i){let a=n.checkEmpty??!1,l=t.map(([,c])=>c),o=t.length===0,u=t.length===0;if(n.type==="UseAlternative")return!u&&!(a&&o)&&n.word?{values:[await i(e,n.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(n.type==="DefaultValue")return(u||a&&o)&&n.word?{values:[await i(e,n.word.parts,!0)],quoted:!0}:r?{values:[l.join(j(e.state.env))],quoted:!0}:{values:l,quoted:!0};if(n.type==="AssignDefault"){if((u||a&&o)&&n.word){let f=await i(e,n.word.parts,!0);return e.state.env.set(`${s}_0`,f),e.state.env.set(`${s}__length`,"1"),{values:[f],quoted:!0}}return r?{values:[l.join(j(e.state.env))],quoted:!0}:{values:l,quoted:!0}}return r?{values:[l.join(j(e.state.env))],quoted:!0}:{values:l,quoted:!0}}async function wo(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="UseAlternative"&&t[0].operation?.type!=="DefaultValue")return null;let s=t[0],r=s.operation,n=r?.word;if(!n||n.parts.length!==1||n.parts[0].type!=="DoubleQuoted")return null;let i=n.parts[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let a=i.parts[0],o=(await J(e,a.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!o)return null;let u=await st(e,s.parameter),c=await J(e,s.parameter)==="",f=r.checkEmpty??!1,d;if(r.type==="UseAlternative"?d=u&&!(f&&c):d=!u||f&&c,d){let h=o[1],m=o[2]==="*",p=B(e,h);if(p.length>0){let b=p.map(([,v])=>v);return m?{values:[b.join(j(e.state.env))],quoted:!0}:{values:b,quoted:!0}}let y=e.state.env.get(h);return y!==void 0?{values:[y],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function Eo(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="Indirection")return null;let s=t[0],n=s.operation.innerOp;if(!n||n.type!=="UseAlternative"&&n.type!=="DefaultValue")return null;let i=n.word;if(!i||i.parts.length!==1||i.parts[0].type!=="DoubleQuoted")return null;let a=i.parts[0];if(a.parts.length!==1||a.parts[0].type!=="ParameterExpansion"||a.parts[0].operation?.type!=="Indirection")return null;let l=a.parts[0],u=(await J(e,l.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!u)return null;let c=await J(e,s.parameter),f=await st(e,s.parameter),d=c==="",h=n.checkEmpty??!1,m;if(n.type==="UseAlternative"?m=f&&!(h&&d):m=!f||h&&d,m){let p=u[1],y=u[2]==="*",b=B(e,p);if(b.length>0){let E=b.map(([,w])=>w);return y?{values:[E.join(j(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let v=e.state.env.get(p);return v!==void 0?{values:[v],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}function bo(e){let t=Number.parseInt(e.state.env.get("#")||"0",10),s=[];for(let r=1;r<=t;r++)s.push(e.state.env.get(String(r))||"");return s}async function vo(e,t,s,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0],i=-1,a=!1;for(let v=0;v=d.length)m=[];else if(c!==void 0){let E=c<0?d.length+c:v+c;m=d.slice(v,Math.max(v,E))}else m=d.slice(v)}let p="";for(let v=0;v0)r.push(...i);else{if(s.hasFailglob())throw new wt(n);s.hasNullglob()||r.push(n)}}else r.push(n);return r}async function Po(e,t,s,r){let n=-1,i="",a=!1;for(let v=0;vv);if(u.length===0){let v=e.state.env.get(i);v!==void 0&&(c=[v])}if(c.length===0)return{values:[],quoted:!1};let f="";if(o.pattern)for(let v of o.pattern.parts)if(v.type==="Glob")f+=G(v.pattern,!0,e.state.shoptOptions.extglob);else if(v.type==="Literal")f+=G(v.value,!0,e.state.shoptOptions.extglob);else if(v.type==="SingleQuoted"||v.type==="Escaped")f+=Q(v.value);else if(v.type==="DoubleQuoted"){let E=await s(e,v.parts);f+=Q(E)}else if(v.type==="ParameterExpansion"){let E=await r(e,v);f+=G(E,!0,e.state.shoptOptions.extglob)}else{let E=await r(e,v);f+=Q(E)}let d=o.replacement?await s(e,o.replacement.parts):"",h=f;o.anchor==="start"?h=`^${f}`:o.anchor==="end"&&(h=`${f}$`);let m=[];try{let v=le(h,o.all?"g":"");for(let E of c)m.push(v.replace(E,d))}catch{m.push(...c)}let p=me(e.state.env),y=ve(e.state.env);if(a){let v=j(e.state.env),E=m.join(v);return y?{values:E?[E]:[],quoted:!1}:{values:re(E,p),quoted:!1}}if(y)return{values:m,quoted:!1};let b=[];for(let v of m)v===""?b.push(""):b.push(...re(v,p));return{values:b,quoted:!1}}async function ko(e,t,s,r){let n=-1,i="",a=!1;for(let b=0;bb);if(u.length===0){let b=e.state.env.get(i);b!==void 0&&(c=[b])}if(c.length===0)return{values:[],quoted:!1};let f="",d=e.state.shoptOptions.extglob;if(o.pattern)for(let b of o.pattern.parts)if(b.type==="Glob")f+=G(b.pattern,o.greedy,d);else if(b.type==="Literal")f+=G(b.value,o.greedy,d);else if(b.type==="SingleQuoted"||b.type==="Escaped")f+=Q(b.value);else if(b.type==="DoubleQuoted"){let v=await s(e,b.parts);f+=Q(v)}else if(b.type==="ParameterExpansion"){let v=await r(e,b);f+=G(v,o.greedy,d)}else{let v=await r(e,b);f+=Q(v)}let h=[];for(let b of c)h.push(mt(b,f,o.side,o.greedy));let m=me(e.state.env),p=ve(e.state.env);if(a){let b=j(e.state.env),v=h.join(b);return p?{values:v?[v]:[],quoted:!1}:{values:re(v,m),quoted:!1}}if(p)return{values:h,quoted:!1};let y=[];for(let b of h)b===""?y.push(""):y.push(...re(b,m));return{values:y,quoted:!1}}async function No(e,t,s,r){let n=-1,i=!1;for(let y=0;y=f.length)h=[];else if(u!==void 0){let w=u<0?f.length+u:E+u;h=f.slice(E,Math.max(E,w))}else h=f.slice(E)}let m="";for(let E=0;Eu!=="");else{let u=j(e.state.env),c=n.join(u);o=re(c,i)}else if(a)o=n.filter(u=>u!=="");else if(l){o=[];for(let u of n){if(u==="")continue;let c=re(u,i);o.push(...c)}}else{o=[];for(let u of n)if(u==="")o.push("");else{let c=re(u,i);o.push(...c)}for(;o.length>0&&o[o.length-1]==="";)o.pop()}return{values:await Ks(e,o),quoted:!1}}async function Co(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation)return null;let s=t[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!s)return null;let r=s[1],n=s[2]==="*",i=B(e,r),a;if(i.length===0){let f=e.state.env.get(r);if(f!==void 0)a=[f];else return{values:[],quoted:!1}}else a=i.map(([,f])=>f);let l=me(e.state.env),o=ve(e.state.env),u=js(e.state.env),c;if(n)if(o)c=a.filter(f=>f!=="");else{let f=j(e.state.env),d=a.join(f);c=re(d,l)}else if(o)c=a.filter(f=>f!=="");else if(u){c=[];for(let f of a){if(f==="")continue;let d=re(f,l);c.push(...d)}}else{c=[];for(let f of a)if(f==="")c.push("");else{let d=re(f,l);c.push(...d)}for(;c.length>0&&c[c.length-1]==="";)c.pop()}return{values:await Ks(e,c),quoted:!1}}function Do(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="VarNamePrefix")return null;let s=t[0].operation,r=Zt(e,s.prefix);if(r.length===0)return{values:[],quoted:!1};let n=me(e.state.env),i=ve(e.state.env),a;if(s.star)if(i)a=r;else{let l=j(e.state.env),o=r.join(l);a=re(o,n)}else if(i)a=r;else{a=[];for(let l of r){let o=re(l,n);a.push(...o)}}return{values:a,quoted:!1}}function Ro(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="ArrayKeys")return null;let s=t[0].operation,n=B(e,s.array).map(([o])=>String(o));if(n.length===0)return{values:[],quoted:!1};let i=me(e.state.env),a=ve(e.state.env),l;if(s.star)if(a)l=n;else{let o=j(e.state.env),u=n.join(o);l=re(u,i)}else if(a)l=n;else{l=[];for(let o of n){let u=re(o,i);l.push(...u)}}return{values:l,quoted:!1}}async function Io(e,t,s){let r=-1;for(let d=0;dh!=="");else if(c){f=[];for(let h of d){if(h==="")continue;let m=re(h,o);f.push(...m)}}else{f=[];for(let h of d)if(h==="")f.push("");else{let m=re(h,o);f.push(...m)}for(;f.length>0&&f[f.length-1]==="";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await Ks(e,f),quoted:!1}}async function Lo(e,t,s){e.coverage?.hit("bash:expansion:word_glob");let r=t.parts,{hasQuoted:n,hasCommandSub:i,hasArrayVar:a,hasArrayAtExpansion:l,hasParamExpansion:o,hasVarNamePrefixExpansion:u,hasIndirection:c}=hs(r),d=s.hasBraceExpansion(r)?await s.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return Gu(e,d,n);let h=await Hu(e,r,l,u,c,s);if(h!==null)return h;let m=await Ku(e,r,s);if(m!==null)return m;let p=await Xu(e,r,s);if(p!==null)return p;let y=await Ju(e,r,s.expandPart);if(y!==null)return To(e,y);if((i||a||o)&&!ve(e.state.env)){let v=me(e.state.env),E=s.buildIfsCharClassPattern(v),w=await s.smartWordSplit(e,r,v,E,s.expandPart);return To(e,w)}let b=await s.expandWordAsync(e,t);return ef(e,t,r,b,n,s.expandWordForGlobbing)}async function Gu(e,t,s){let r=[];for(let n of t)if(!(!s&&n===""))if(!s&&!e.state.options.noglob&&nt(n,e.state.shoptOptions.extglob)){let i=await Xs(e,n);r.push(...i)}else r.push(n);return{values:r,quoted:!1}}async function Hu(e,t,s,r,n,i){if(s){let a=mo(e,t);if(a!==null)return a}{let a=go(e,t);if(a!==null)return a}{let a=await co(e,t);if(a!==null)return a}{let a=await uo(e,t,s,i.expandPart,i.expandWordPartsAsync);if(a!==null)return a}{let a=await fo(e,t,s,i.expandPart);if(a!==null)return a}{let a=await ho(e,t,i.evaluateArithmetic);if(a!==null)return a}{let a=po(e,t);if(a!==null)return a}{let a=await oo(e,t,i.expandWordPartsAsync,i.expandPart);if(a!==null)return a}{let a=await lo(e,t,i.expandWordPartsAsync,i.expandPart);if(a!==null)return a}if(r&&t.length===1&&t[0].type==="DoubleQuoted"){let a=Qu(e,t);if(a!==null)return a}{let a=await yo(e,t,n,i.expandParameterAsync,i.expandWordPartsAsync);if(a!==null)return a}{let a=await wo(e,t);if(a!==null)return a}{let a=await Eo(e,t);if(a!==null)return a}return null}function Qu(e,t){let s=t[0];if(s.type!=="DoubleQuoted")return null;if(s.parts.length===1&&s.parts[0].type==="ParameterExpansion"&&s.parts[0].operation?.type==="VarNamePrefix"){let r=s.parts[0].operation,n=Zt(e,r.prefix);return r.star?{values:[n.join(j(e.state.env))],quoted:!0}:{values:n,quoted:!0}}if(s.parts.length===1&&s.parts[0].type==="ParameterExpansion"&&s.parts[0].operation?.type==="ArrayKeys"){let r=s.parts[0].operation,i=B(e,r.array).map(([a])=>String(a));return r.star?{values:[i.join(j(e.state.env))],quoted:!0}:{values:i,quoted:!0}}return null}async function Ku(e,t,s){{let r=await vo(e,t,s.evaluateArithmetic,s.expandPart);if(r!==null)return r}{let r=await So(e,t,s.expandPart,s.expandWordPartsAsync);if(r!==null)return r}{let r=await Ao(e,t,s.expandPart,s.expandWordPartsAsync);if(r!==null)return r}{let r=await $o(e,t,s.expandPart);if(r!==null)return r}return null}async function Xu(e,t,s){{let r=await Po(e,t,s.expandWordPartsAsync,s.expandPart);if(r!==null)return r}{let r=await ko(e,t,s.expandWordPartsAsync,s.expandPart);if(r!==null)return r}{let r=await No(e,t,s.expandWordPartsAsync,s.expandPart);if(r!==null)return r}{let r=await _o(e,t,s.evaluateArithmetic,s.expandPart);if(r!==null)return r}{let r=await xo(e,t);if(r!==null)return r}{let r=await Co(e,t);if(r!==null)return r}{let r=Do(e,t);if(r!==null)return r}{let r=Ro(e,t);if(r!==null)return r}{let r=await Io(e,t,s.expandPart);if(r!==null)return r}return null}function Oo(e){if(e.type!=="DoubleQuoted")return null;for(let t=0;to),a.length===0){let o=e.state.env.get(s.name);o!==void 0&&(a=[o])}}else{let l=Number.parseInt(e.state.env.get("#")||"0",10);a=[];for(let o=1;o<=l;o++)a.push(e.state.env.get(String(o))||"")}if(s.isStar){let l=j(e.state.env),o=a.join(l);return[n+o+i]}if(a.length===0){let l=n+i;return l?[l]:[]}return a.length===1?[n+a[0]+i]:[n+a[0],...a.slice(1,-1),a[a.length-1]+i]}async function Ju(e,t,s){if(t.length<2)return null;let r=!1;for(let o of t)if(Oo(o)){r=!0;break}if(!r)return null;let n=me(e.state.env),i=ve(e.state.env),a=[];for(let o of t){let u=Oo(o);if(u&&o.type==="DoubleQuoted"){let c=await Yu(e,o,u,s);a.push(c)}else if(o.type==="DoubleQuoted"||o.type==="SingleQuoted"){let c=await s(e,o);a.push([c])}else if(o.type==="Literal")a.push([o.value]);else if(o.type==="ParameterExpansion"){let c=await s(e,o);if(i)a.push(c?[c]:[]);else{let f=re(c,n);a.push(f)}}else{let c=await s(e,o);if(i)a.push(c?[c]:[]);else{let f=re(c,n);a.push(f)}}}let l=[];for(let o of a)if(o.length!==0)if(l.length===0)l.push(...o);else{let u=l.length-1;l[u]=l[u]+o[0];for(let c=1;c0)return r;if(s.hasFailglob())throw new wt(t);return s.hasNullglob()?[]:[t]}async function ef(e,t,s,r,n,i){let a=s.some(l=>l.type==="Glob");if(!e.state.options.noglob&&a){let l=await i(e,t);if(nt(l,e.state.shoptOptions.extglob)){let u=await Xs(e,l);if(u.length>0&&u[0]!==l)return{values:u,quoted:!1};if(u.length===0)return{values:[],quoted:!1}}let o=kr(r);if(!ve(e.state.env)){let u=me(e.state.env);return{values:re(o,u),quoted:!1}}return{values:[o],quoted:!1}}if(!n&&!e.state.options.noglob&&nt(r,e.state.shoptOptions.extglob)){let l=await i(e,t);if(nt(l,e.state.shoptOptions.extglob)){let o=await Xs(e,l);if(o.length>0&&o[0]!==l)return{values:o,quoted:!1}}}if(r===""&&!n)return{values:[],quoted:!1};if(a&&!n){let l=kr(r);if(!ve(e.state.env)){let o=me(e.state.env);return{values:re(l,o),quoted:!1}}return{values:[l],quoted:!1}}return{values:[r],quoted:n}}async function Wo(e,t){let s=t.operation;if(!s||s.type!=="DefaultValue"&&s.type!=="AssignDefault"&&s.type!=="UseAlternative")return null;let r=s.word;if(!r||r.parts.length===0)return null;let n=await st(e,t.parameter),a=await J(e,t.parameter,!1)==="",l=s.checkEmpty??!1,o;return s.type==="UseAlternative"?o=n&&!(l&&a):o=!n||l&&a,o?r.parts:null}function tf(e){return e.type==="SingleQuoted"?!0:e.type==="DoubleQuoted"?e.parts.every(s=>s.type==="Literal"):!1}async function sf(e,t){if(t.type!=="ParameterExpansion")return null;let s=await Wo(e,t);if(!s||s.length<=1)return null;let r=s.some(i=>tf(i)),n=s.some(i=>i.type==="Literal"||i.type==="ParameterExpansion"||i.type==="CommandSubstitution"||i.type==="ArithmeticExpansion");return r&&n?s:null}function nf(e){return e.type==="DoubleQuoted"||e.type==="SingleQuoted"||e.type==="Literal"?!1:e.type==="Glob"?Er(e.pattern):!(!(e.type==="ParameterExpansion"||e.type==="CommandSubstitution"||e.type==="ArithmeticExpansion")||e.type==="ParameterExpansion"&&Oa(e))}async function Fo(e,t,s,r,n){if(e.coverage?.hit("bash:expansion:word_split"),t.length===1&&t[0].type==="ParameterExpansion"){let d=t[0],h=await Wo(e,d);if(h&&h.length>0&&h.length>1&&h.some(p=>p.type==="DoubleQuoted"||p.type==="SingleQuoted")&&h.some(p=>p.type==="Literal"||p.type==="ParameterExpansion"||p.type==="CommandSubstitution"||p.type==="ArithmeticExpansion"))return Mo(e,h,s,r,n)}let i=[],a=!1;for(let d of t){let h=nf(d),m=d.type==="DoubleQuoted"||d.type==="SingleQuoted",p=h?await sf(e,d):null,y=await n(e,d);i.push({value:y,isSplittable:h,isQuoted:m,mixedDefaultParts:p??void 0}),h&&(a=!0)}if(!a){let d=i.map(h=>h.value).join("");return d?[d]:[]}let l=[],o="",u=!1,c=!1,f=!1;for(let d of i)if(!d.isSplittable)c?d.isQuoted&&d.value===""?(o!==""&&l.push(o),l.push(""),u=!0,o="",c=!1,f=!0):d.value!==""?(o!==""&&l.push(o),o=d.value,c=!1,f=!1):(o+=d.value,f=!1):(o+=d.value,f=d.isQuoted&&d.value==="");else if(d.mixedDefaultParts){let h=await Mo(e,d.mixedDefaultParts,s,r,n);if(h.length!==0)if(h.length===1)o+=h[0],u=!0;else{o+=h[0],l.push(o),u=!0;for(let m=1;m0&&t.includes(e[0])}async function Mo(e,t,s,r,n){let i=[];for(let c of t){let d=!(c.type==="DoubleQuoted"||c.type==="SingleQuoted"),h=await n(e,c);i.push({value:h,isSplittable:d})}let a=[],l="",o=!1,u=!1;for(let c of i)if(!c.isSplittable)u&&c.value!==""?(l!==""&&a.push(l),l=c.value,u=!1):l+=c.value;else{rf(c.value,s)&&l!==""&&(a.push(l),l="",o=!0);let{words:d,hadTrailingDelimiter:h}=Us(c.value,s);if(d.length===0)h&&(u=!0);else if(d.length===1)l+=d[0],o=!0,u=h;else{l+=d[0],a.push(l),o=!0;for(let m=1;mt)throw new X(`${s}: string length limit exceeded (${t} bytes)`,"string_length")}async function Ke(e,t,s=!1){let r=[];for(let n of t)r.push(await Ve(e,n,s));return r.join("")}function af(e){return zo(e)}function Bo(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!af(t))return!1;return!0}function of(e,t,s=!1){let r=Vo(t);if(r!==null)return r;switch(t.type){case"TildeExpansion":return s?t.user===null?"~":`~${t.user}`:(e.coverage?.hit("bash:expansion:tilde"),t.user===null?e.state.env.get("HOME")??"/home/user":t.user==="root"?"/root":`~${t.user}`);case"Glob":return Nr(e,t.pattern);default:return null}}async function V(e,t){return xr(e,t)}async function qo(e,t){let s=[];for(let r of t.parts)if(r.type==="Escaped")s.push(`\\${r.value}`);else if(r.type==="SingleQuoted")s.push(r.value);else if(r.type==="DoubleQuoted"){let n=await Ke(e,r.parts);s.push(n)}else if(r.type==="TildeExpansion"){let n=await Ve(e,r);s.push(ps(n))}else s.push(await Ve(e,r));return s.join("")}async function jo(e,t){let s=[];for(let r of t.parts)if(r.type==="Escaped"){let n=r.value;"()|*?[]".includes(n)?s.push(`\\${n}`):s.push(n)}else if(r.type==="SingleQuoted")s.push(Fe(r.value));else if(r.type==="DoubleQuoted"){let n=await Ke(e,r.parts);s.push(Fe(n))}else s.push(await Ve(e,r));return s.join("")}async function Uo(e,t){let s=[];for(let r of t.parts)if(r.type==="SingleQuoted")s.push(Fe(r.value));else if(r.type==="Escaped"){let n=r.value;"*?[]\\()|".includes(n)?s.push(`\\${n}`):s.push(n)}else if(r.type==="DoubleQuoted"){let n=await Ke(e,r.parts);s.push(Fe(n))}else r.type==="Glob"?no(r.pattern)?s.push(await io(e,r.pattern)):s.push(Nr(e,r.pattern)):r.type==="Literal"?s.push(r.value):s.push(await Ve(e,r));return s.join("")}function Js(e){for(let t of e)if(t.type==="BraceExpansion"||t.type==="DoubleQuoted"&&Js(t.parts))return!0;return!1}var _r=1e5;async function Zo(e,t,s={count:0}){if(s.count>_r)return[[]];let r=[[]];for(let n of t)if(n.type==="BraceExpansion"){let i=[],a=!1,l="";for(let c of n.items)if(c.type==="Range"){let f=Pr(c.start,c.end,c.step,c.startStr,c.endStr);if(f.expanded)for(let d of f.expanded)s.count++,i.push(d);else{a=!0,l=f.literal;break}}else{let f=await Zo(e,c.word.parts,s);for(let d of f){s.count++;let h=[];for(let m of d)typeof m=="string"?h.push(m):h.push(await Ve(e,m));i.push(h.join(""))}}if(a){for(let c of r)s.count++,c.push(l);continue}if(r.length*i.length>e.limits.maxBraceExpansionResults||s.count>_r)return r;let u=[];for(let c of r)for(let f of i){if(s.count++,s.count>_r)return u.length>0?u:r;u.push([...c,f])}r=u}else for(let i of r)s.count++,i.push(n);return r}async function Go(e,t){let s=t.parts;if(!Js(s))return[await V(e,t)];let r=await Zo(e,s),n=[];for(let i of r){let a=[];for(let l of i)typeof l=="string"?a.push(l):a.push(await Ve(e,l));n.push(ao(e,a.join("")))}return n}function lf(){return{expandWordAsync:xr,expandWordForGlobbing:Uo,expandWordWithBracesAsync:Go,expandWordPartsAsync:Ke,expandPart:Ve,expandParameterAsync:Ys,hasBraceExpansion:Js,evaluateArithmetic:T,buildIfsCharClassPattern:Ta,smartWordSplit:Fo}}async function it(e,t){return Lo(e,t,lf())}function cf(e){for(let t of e){if(t.type==="ParameterExpansion")return t.parameter;if(t.type==="Literal")return t.value}return""}function en(e,t){if(Number.parseInt(e.state.env.get("#")||"0",10)<2)return!1;function r(n){for(let i of n)if(i.type==="DoubleQuoted"){for(let a of i.parts)if(a.type==="ParameterExpansion"&&a.parameter==="@"&&!a.operation)return!0}return!1}return r(t.parts)}async function tn(e,t){if(en(e,t))return{error:`bash: $@: ambiguous redirect `};let s=t.parts,{hasQuoted:r}=hs(s);if(Js(s)&&(await Go(e,t)).length>1)return{error:`bash: ${s.map(h=>h.type==="Literal"?h.value:h.type==="BraceExpansion"?`{${h.items.map(p=>{if(p.type==="Range"){let y=p.step?`..${p.step}`:"";return`${p.startStr??p.start}..${p.endStr??p.end}${y}`}return p.word.parts.map(y=>y.type==="Literal"?y.value:"").join("")}).join(",")}}`:"").join("")}: ambiguous redirect `};let n=await xr(e,t),{hasParamExpansion:i,hasCommandSub:a}=hs(s);if((i||a)&&!r&&!ve(e.state.env)){let f=me(e.state.env);if(re(n,f).length>1)return{error:`bash: $${cf(s)}: ambiguous redirect `}}if(r||e.state.options.noglob)return{target:n};let o=await Uo(e,t);if(!nt(o,e.state.shoptOptions.extglob))return{target:n};let u=new Pt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations}),c=await u.expand(o);return c.length===0?u.hasFailglob()?{error:`bash: no match: ${n} `}:{target:n}:c.length===1?{target:c[0]}:{error:`bash: ${n}: ambiguous redirect `}}async function xr(e,t){let s=t.parts,r=s.length;if(r===1){let a=await Ve(e,s[0]);return _t(a,e.limits.maxStringLength,"word expansion"),a}let n=[];for(let a=0;a=a)throw new X(`Command substitution nesting limit exceeded (${a})`,"substitution_depth");let l=e.substitutionDepth;e.substitutionDepth=i+1;let o=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let u=new Map(e.state.env),c=e.state.cwd,f=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let d=await e.executeScript(t.body),h=d.exitCode;e.state.env=u,e.state.cwd=c,e.state.suppressVerbose=f,e.state.lastExitCode=h,e.state.env.set("?",String(h)),d.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+d.stderr),e.state.bashPid=o,e.substitutionDepth=l;let m=d.stdout.replace(/\n+$/,"");return _t(m,e.limits.maxStringLength,"command substitution"),m}catch(d){if(e.state.env=u,e.state.cwd=c,e.state.bashPid=o,e.substitutionDepth=l,e.state.suppressVerbose=f,d instanceof X)throw d;if(d instanceof Z){e.state.lastExitCode=d.exitCode,e.state.env.set("?",String(d.exitCode)),d.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+d.stderr);let h=d.stdout.replace(/\n+$/,"");return _t(h,e.limits.maxStringLength,"command substitution"),h}throw d}}case"ArithmeticExpansion":{let n=t.expression.originalText;if(n&&/\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(n)){let a=await za(e,n),l=new q,o=Y(l,a);return String(await T(e,o.expression,!0))}return String(await T(e,t.expression.expression,!0))}case"BraceExpansion":{let n=[];for(let i of t.items)if(i.type==="Range"){let a=Pr(i.start,i.end,i.step,i.startStr,i.endStr);if(a.expanded)n.push(...a.expanded);else return a.literal}else n.push(await V(e,i.word));return n.join(" ")}default:return""}}async function Ys(e,t,s=!1){let{parameter:r}=t,{operation:n}=t,i=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let[,d,h]=i;if(e.state.associativeArrays?.has(d)||h.includes("$(")||h.includes("`")||h.includes("${")){let p=await $r(e,h);r=`${d}[${p}]`}}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&te(e,r)){let d=$e(e,r);if(d&&d!==r){let h=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,m,p]=h;if(e.state.associativeArrays?.has(m)||p.includes("$(")||p.includes("`")||p.includes("${")){let b=await $r(e,p);r=`${m}[${b}]`}}}}let a=n&&(n.type==="DefaultValue"||n.type==="AssignDefault"||n.type==="UseAlternative"||n.type==="ErrorIfUnset"),l=await J(e,r,!a);if(!n)return l;let o=!await st(e,r),{isEmpty:u,effectiveValue:c}=so(e,r,l,s),f={value:l,isUnset:o,isEmpty:u,effectiveValue:c,inDoubleQuotes:s};switch(n.type){case"DefaultValue":return qa(e,n,f,Ke);case"AssignDefault":return ja(e,r,n,f,Ke);case"ErrorIfUnset":return Ua(e,r,n,f,Ke);case"UseAlternative":return Za(e,n,f,Ke);case"PatternRemoval":{let d=await Ga(e,l,n,Ke,Ve);return _t(d,e.limits.maxStringLength,"pattern removal"),d}case"PatternReplacement":{let d=await Ha(e,l,n,Ke,Ve);return _t(d,e.limits.maxStringLength,"pattern replacement"),d}case"Length":return Qa(e,r,l);case"LengthSliceError":throw new Me(r);case"BadSubstitution":throw new Me(n.text);case"Substring":return Ka(e,r,l,n);case"CaseModification":{let d=await Xa(e,l,n,Ke,Ys);return _t(d,e.limits.maxStringLength,"case modification"),d}case"Transform":return Ya(e,r,l,o,n);case"Indirection":return Ja(e,r,l,o,n,Ys,s);case"ArrayKeys":return eo(e,n);case"VarNamePrefix":return to(e,n);default:return l}}function uf(e,t,s){switch(s){case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":if(t===0)throw new se("division by 0");return Math.trunc(e/t);case"%":if(t===0)throw new se("division by 0");return e%t;case"**":if(t<0)throw new se("exponent less than 0");return e**t;case"<<":return e<>":return e>>t;case"<":return e":return e>t?1:0;case">=":return e>=t?1:0;case"==":return e===t?1:0;case"!=":return e!==t?1:0;case"&":return e&t;case"|":return e|t;case"^":return e^t;case",":return t;default:return 0}}function Ho(e,t,s){switch(s){case"=":return t;case"+=":return e+t;case"-=":return e-t;case"*=":return e*t;case"/=":return t!==0?Math.trunc(e/t):0;case"%=":return t!==0?e%t:0;case"<<=":return e<>=":return e>>t;case"&=":return e&t;case"|=":return e|t;case"^=":return e^t;default:return t}}function ff(e,t){switch(t){case"-":return-e;case"+":return+e;case"!":return e===0?1:0;case"~":return~e;default:return e}}async function df(e,t){let s=e.state.env.get(t);if(s!==void 0)return s;let r=e.state.env.get(`${t}_0`);return r!==void 0?r:await J(e,t)}function hf(e){if(!e)return 0;let t=Number.parseInt(e,10);if(!Number.isNaN(t)&&/^-?\d+$/.test(e.trim()))return t;let s=e.trim();if(!s)return 0;try{let r=new q,{expr:n,pos:i}=We(r,s,0);if(i100)throw new se("maximum variable indirection depth exceeded");if(s.has(t))return 0;s.add(t);let n=await df(e,t);if(!n)return 0;let i=Number.parseInt(n,10);if(!Number.isNaN(i)&&/^-?\d+$/.test(n.trim()))return i;let a=n.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return await Dr(e,a,s,r+1);let l=new q,{expr:o,pos:u}=We(l,a,0);if(u0&&(r===-1||d64)return 0;let i=`${n}#${t.value}`;return us(i)}case"ArithDynamicNumber":{let n=await sn(e,t.prefix)+t.suffix;return us(n)}case"ArithArrayElement":{let r=e.state.associativeArrays?.has(t.array),n=async i=>{let a=e.state.env.get(i);return a!==void 0?await Cr(e,a):0};if(t.stringKey!==void 0)return await n(`${t.array}_${t.stringKey}`);if(r&&t.index?.type==="ArithVariable"&&!t.index.hasDollarPrefix)return await n(`${t.array}_${t.index.name}`);if(r&&t.index?.type==="ArithVariable"&&t.index.hasDollarPrefix){let i=await J(e,t.index.name);return await n(`${t.array}_${i}`)}if(t.index){let i=await T(e,t.index,s);if(i<0){let o=B(e,t.array),u=e.state.currentLine;if(o.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${u}: ${t.array}: bad array subscript `,0;let f=Math.max(...o.map(([d])=>typeof d=="number"?d:0))+1+i;if(f<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${u}: ${t.array}: bad array subscript `,0;i=f}let a=`${t.array}_${i}`,l=e.state.env.get(a);if(l!==void 0)return Cr(e,l);if(i===0){let o=e.state.env.get(t.array);if(o!==void 0)return Cr(e,o)}if(e.state.options.nounset&&!Array.from(e.state.env.keys()).some(u=>u===t.array||u.startsWith(`${t.array}_`)))throw new Le(`${t.array}[${i}]`);return 0}return 0}case"ArithDoubleSubscript":throw new se("double subscript","","");case"ArithNumberSubscript":throw new se(`${t.number}${t.errorToken}: syntax error: invalid arithmetic operator (error token is "${t.errorToken}")`);case"ArithSyntaxError":throw new se(t.message,"","",!0);case"ArithSingleQuote":{if(s)throw new se(`syntax error: operand expected (error token is "'${t.content}'")`);return t.value}case"ArithBinary":{if(t.operator==="||")return await T(e,t.left,s)||await T(e,t.right,s)?1:0;if(t.operator==="&&")return await T(e,t.left,s)&&await T(e,t.right,s)?1:0;let r=await T(e,t.left,s),n=await T(e,t.right,s);return uf(r,n,t.operator)}case"ArithUnary":{let r=await T(e,t.operand,s);if(t.operator==="++"||t.operator==="--"){if(t.operand.type==="ArithVariable"){let n=t.operand.name,i=Number.parseInt(await J(e,n),10)||0,a=t.operator==="++"?i+1:i-1;return e.state.env.set(n,String(a)),t.prefix?a:i}if(t.operand.type==="ArithArrayElement"){let n=t.operand.array,i=e.state.associativeArrays?.has(n),a;if(t.operand.stringKey!==void 0)a=`${n}_${t.operand.stringKey}`;else if(i&&t.operand.index?.type==="ArithVariable"&&!t.operand.index.hasDollarPrefix)a=`${n}_${t.operand.index.name}`;else if(i&&t.operand.index?.type==="ArithVariable"&&t.operand.index.hasDollarPrefix){let u=await J(e,t.operand.index.name);a=`${n}_${u}`}else if(t.operand.index){let u=await T(e,t.operand.index,s);a=`${n}_${u}`}else return r;let l=Number.parseInt(e.state.env.get(a)||"0",10)||0,o=t.operator==="++"?l+1:l-1;return e.state.env.set(a,String(o)),t.prefix?o:l}if(t.operand.type==="ArithConcat"){let n="";for(let i of t.operand.parts)n+=await Gt(e,i,s);if(n&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){let i=Number.parseInt(e.state.env.get(n)||"0",10)||0,a=t.operator==="++"?i+1:i-1;return e.state.env.set(n,String(a)),t.prefix?a:i}}if(t.operand.type==="ArithDynamicElement"){let n="";if(t.operand.nameExpr.type==="ArithConcat")for(let i of t.operand.nameExpr.parts)n+=await Gt(e,i,s);else t.operand.nameExpr.type==="ArithVariable"&&(n=t.operand.nameExpr.hasDollarPrefix?await J(e,t.operand.nameExpr.name):t.operand.nameExpr.name);if(n&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){let i=await T(e,t.operand.subscript,s),a=`${n}_${i}`,l=Number.parseInt(e.state.env.get(a)||"0",10)||0,o=t.operator==="++"?l+1:l-1;return e.state.env.set(a,String(o)),t.prefix?o:l}}return r}return ff(r,t.operator)}case"ArithTernary":return await T(e,t.condition,s)?await T(e,t.consequent,s):await T(e,t.alternate,s);case"ArithAssignment":{let r=t.variable,n=r;if(t.stringKey!==void 0)n=`${r}_${t.stringKey}`;else if(t.subscript){let o=e.state.associativeArrays?.has(r);if(o&&t.subscript.type==="ArithVariable"&&!t.subscript.hasDollarPrefix)n=`${r}_${t.subscript.name}`;else if(o&&t.subscript.type==="ArithVariable"&&t.subscript.hasDollarPrefix){let u=await J(e,t.subscript.name);n=`${r}_${u||"\\"}`}else if(o){let u=await T(e,t.subscript,s);n=`${r}_${u}`}else{let u=await T(e,t.subscript,s);if(u<0){let c=B(e,r);c.length>0&&(u=Math.max(...c.map(([d])=>typeof d=="number"?d:0))+1+u)}n=`${r}_${u}`}}let i=Number.parseInt(e.state.env.get(n)||"0",10)||0,a=await T(e,t.value,s),l=Ho(i,a,t.operator);return e.state.env.set(n,String(l)),l}case"ArithGroup":return await T(e,t.expression,s);case"ArithConcat":{let r="";for(let n of t.parts)r+=await Gt(e,n,s);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)?await Dr(e,r):Number.parseInt(r,10)||0}case"ArithDynamicAssignment":{let r="";if(t.target.type==="ArithConcat")for(let o of t.target.parts)r+=await Gt(e,o,s);else t.target.type==="ArithVariable"&&(r=t.target.hasDollarPrefix?await J(e,t.target.name):t.target.name);if(!r||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r))return 0;let n=r;if(t.subscript){let o=await T(e,t.subscript,s);n=`${r}_${o}`}let i=Number.parseInt(e.state.env.get(n)||"0",10)||0,a=await T(e,t.value,s),l=Ho(i,a,t.operator);return e.state.env.set(n,String(l)),l}case"ArithDynamicElement":{let r="";if(t.nameExpr.type==="ArithConcat")for(let l of t.nameExpr.parts)r+=await Gt(e,l,s);else t.nameExpr.type==="ArithVariable"&&(r=t.nameExpr.hasDollarPrefix?await J(e,t.nameExpr.name):t.nameExpr.name);if(!r||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r))return 0;let n=await T(e,t.subscript,s),i=`${r}_${n}`,a=e.state.env.get(i);return a!==void 0?hf(a):0}default:return 0}}async function Gt(e,t,s=!1){switch(t.type){case"ArithNumber":return String(t.value);case"ArithSingleQuote":return String(await T(e,t,s));case"ArithVariable":return t.hasDollarPrefix?await J(e,t.name):t.name;case"ArithSpecialVar":return await J(e,t.name);case"ArithBracedExpansion":return await sn(e,t.content);case"ArithCommandSubst":return e.execFn?(await e.execFn(t.command,{signal:e.state.signal})).stdout.trim():"0";case"ArithConcat":{let r="";for(let n of t.parts)r+=await Gt(e,n,s);return r}default:return String(await T(e,t,s))}}async function Qo(e,t){let s=t.parts.map(c=>c.type==="Literal"?c.value:"\0").join(""),r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!s.endsWith(")"))return null;let n=r[1],i=[],a=!1,l="",o=!1;for(let c of t.parts)if(c.type==="Literal"){let f=c.value;if(!a){let d=f.indexOf("=(");d!==-1&&(a=!0,f=f.slice(d+2))}if(a){f.endsWith(")")&&(f=f.slice(0,-1));let d=f.split(/(\s+)/);for(let h of d)/^\s+$/.test(h)?(l||o)&&(i.push(l),l="",o=!1):h&&(l+=h)}}else if(a)if(c.type==="BraceExpansion")if(/^\[.+\]=/.test(l))l+=Ut({type:"Word",parts:[c]});else{(l||o)&&(i.push(l),l="",o=!1);let d=await it(e,{type:"Word",parts:[c]});i.push(...d.values)}else{(c.type==="SingleQuoted"||c.type==="DoubleQuoted"||c.type==="Escaped")&&(o=!0);let f=await V(e,{type:"Word",parts:[c]});l+=f}(l||o)&&i.push(l);let u=i.map(c=>/^\[.+\]=/.test(c)?c:c===""?"''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(c)&&!c.startsWith("'")&&!c.startsWith('"')?`'${c.replace(/'/g,"'\\''")}'`:c);return`${n}=(${u.join(" ")})`}async function Ko(e,t){let s=-1,r=-1,n=!1;for(let p=0;p0?await V(e,d):"";return`${f}${n?"+=":"="}${h}`}var pf=["tar","yq","xan","sqlite3","python3","python"];function Xo(e){return pf.includes(e)}var K=Object.freeze({stdout:"",stderr:"",exitCode:0});function H(e=""){return{stdout:e,stderr:"",exitCode:0}}function N(e,t=1){return{stdout:"",stderr:e,exitCode:t}}function _(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function pe(e){return{stdout:"",stderr:"",exitCode:e?0:1}}function at(e,t,s="",r=""){throw new X(e,t,s,r)}function Ae(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new X(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors")}function Rr(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Et;return K}if(t.length>1)throw new Z(1,"",`bash: break: too many arguments `);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new Z(128,"",`bash: break: ${t[0]}: numeric argument required `);s=r}throw new Oe(s)}async function Ir(e,t){let s,r=!1,n=!1,i=0;for(;ih);for(let h of d){let m=h.startsWith("/")?`${h}/${s}`:`${e.state.cwd}/${h}/${s}`;try{if((await e.fs.stat(m)).isDirectory){s=m,r=!0;break}}catch{}}}}let o=(s.startsWith("/")?s:`${e.state.cwd}/${s}`).split("/").filter(f=>f&&f!=="."),u="";for(let f of o)if(f==="..")u=u.split("/").slice(0,-1).join("/")||"/";else{u=u?`${u}/${f}`:`/${f}`;try{if(!(await e.fs.stat(u)).isDirectory)return N(`bash: cd: ${s}: Not a directory `)}catch{return N(`bash: cd: ${s}: No such file or directory `)}}let c=u||"/";if(n)try{c=await e.fs.realpath(c)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=c,e.state.env.set("PWD",e.state.cwd),e.state.env.set("OLDPWD",e.state.previousDir),H(r?`${c} `:"")}function Or(e,t){return e.fs.resolvePath(e.state.cwd,t)}var mf=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function nn(e){return mf.includes(e)}async function rn(e,t,s){let r=Or(e,s);switch(t){case"-e":case"-a":return e.fs.exists(r);case"-f":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case"-d":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case"-r":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case"-w":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case"-x":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case"-s":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case"-g":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(r);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].includes(r);case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(r);default:return!1}}var gf=["-nt","-ot","-ef"];function an(e){return gf.includes(e)}async function on(e,t,s,r){let n=Or(e,s),i=Or(e,r);switch(t){case"-nt":try{let a=await e.fs.stat(n),l=await e.fs.stat(i);return a.mtime>l.mtime}catch{return!1}case"-ot":try{let a=await e.fs.stat(n),l=await e.fs.stat(i);return a.mtimes;case"-ge":return t>=s}}function gs(e){return e==="="||e==="=="||e==="!="}function un(e,t,s,r=!1,n=!1,i=!1){if(r){let l=Ht(t,s,n,i);return e==="!="?!l:l}if(n){let l=t.toLowerCase()===s.toLowerCase();return e==="!="?!l:l}let a=t===s;return e==="!="?!a:a}var wf=new Set(["-z","-n"]);function fn(e){return wf.has(e)}function dn(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function hn(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let r=s[1],n=s[2];if(e.state.associativeArrays?.has(r)){let l=n;return(l.startsWith("'")&&l.endsWith("'")||l.startsWith('"')&&l.endsWith('"'))&&(l=l.slice(1,-1)),l=l.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(o,u)=>e.state.env.get(u)||""),e.state.env.has(`${r}_${l}`)}let a;try{let l=new q,o=Y(l,n);a=await T(e,o.expression)}catch{if(/^-?\d+$/.test(n))a=Number.parseInt(n,10);else{let l=e.state.env.get(n);a=l?Number.parseInt(l,10):0}}if(a<0){let l=he(e,r),o=e.state.currentLine;if(l.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${o}: ${r}: bad array subscript `,!1;if(a=Math.max(...l)+1+a,a<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${o}: ${r}: bad array subscript `,!1}return e.state.env.has(`${r}_${a}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Ge(e,t).length>0:he(e,t).length>0}async function xt(e,t){switch(t.type){case"CondBinary":{let s=await V(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),n;if(t.operator==="=~")if(r){let i=await V(e,t.right);n=ps(i)}else n=await qo(e,t.right);else gs(t.operator)&&!r?n=await jo(e,t.right):n=await V(e,t.right);if(gs(t.operator)){let i=e.state.shoptOptions.nocasematch;return un(t.operator,s,n,!r,i,!0)}if(ln(t.operator))return cn(t.operator,await Jo(e,s),await Jo(e,n));if(an(t.operator))return on(e,t.operator,s,n);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,a=Sf(n),o=le(a,i?"i":"").match(s);if(tt(e,"BASH_REMATCH"),o)for(let u=0;u":return s>n;default:return!1}}case"CondUnary":{let s=await V(e,t.operand);return nn(t.operator)?rn(e,t.operator,s):fn(t.operator)?dn(t.operator,s):t.operator==="-v"?await hn(e,s):t.operator==="-o"?Lr(e,s):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await V(e,t.operand.expression.word)})`!=="":!await xt(e,t.operand);case"CondAnd":return await xt(e,t.left)?await xt(e,t.right):!1;case"CondOr":return await xt(e,t.left)?!0:await xt(e,t.right);case"CondGroup":return await xt(e,t.expression);case"CondWord":return await V(e,t.word)!=="";default:return!1}}async function ys(e,t){if(t.length===0)return _("","",1);if(t.length===1)return pe(!!t[0]);if(t.length===2){let r=t[0],n=t[1];return r==="("?N(`test: '(' without matching ')' `,2):nn(r)?pe(await rn(e,r,n)):fn(r)?pe(dn(r,n)):r==="!"?pe(!n):r==="-v"?pe(await hn(e,n)):r==="-o"?pe(Lr(e,n)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?N(`test: ${r}: unary operator expected `,2):_("","",1)}if(t.length===3){let r=t[0],n=t[1],i=t[2];if(gs(n))return pe(un(n,r,i));if(ln(n)){let a=pn(r),l=pn(i);return!a.valid||!l.valid?_("","",2):pe(cn(n,a.value,l.value))}if(an(n))return pe(await on(e,n,r,i));switch(n){case"-a":return pe(r!==""&&i!=="");case"-o":return pe(r!==""||i!=="");case">":return pe(r>i);case"<":return pe(rsl(c,t)),u=o.length>0?o.join("|"):"(?:)";if(n==="@")s+=`(?:${u})`;else if(n==="*")s+=`(?:${u})*`;else if(n==="+")s+=`(?:${u})+`;else if(n==="?")s+=`(?:${u})?`;else if(n==="!")if(iil(h,t));if(f.every(h=>h!==null)&&f.every(h=>h===f[0])&&f[0]!==null){let h=f[0];if(h===0)s+="(?:.+)";else{let m=[];h>0&&m.push(`.{0,${h-1}}`),m.push(`.{${h+1},}`),m.push(`(?!(?:${u})).{${h}}`),s+=`(?:${m.join("|")})`}}else s+=`(?:(?!(?:${u})).)*?`}else s+=`(?!(?:${u})$).*`;r=i;continue}}if(n==="\\")if(r+10;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function rl(e){let t=[],s="",r=0,n=0;for(;nil(u,t));if(o.every(u=>u!==null)&&o.every(u=>u===o[0])){s+=o[0],r=i+1;continue}return null}return null}}if(n==="*")return null;if(n==="?"){s+=1,r++;continue}if(n==="["){let i=e.indexOf("]",r+1);if(i!==-1){s+=1,r=i+1;continue}s+=1,r++;continue}if(n==="\\"){s+=1,r+=2;continue}s+=1,r++}return s}function Lr(e,t){let r=new Map([["errexit",()=>e.state.options.errexit===!0],["nounset",()=>e.state.options.nounset===!0],["pipefail",()=>e.state.options.pipefail===!0],["xtrace",()=>e.state.options.xtrace===!0],["e",()=>e.state.options.errexit===!0],["u",()=>e.state.options.nounset===!0],["x",()=>e.state.options.xtrace===!0]]).get(t);return r?r():!1}async function Jo(e,t){if(t=t.trim(),t==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return el(t);try{let s=new q,r=Y(s,t);return await T(e,r.expression)}catch{return el(t)}}function vf(e,t){let s=0;for(let r of e){let n;if(r>="0"&&r<="9")n=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")n=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")n=r.charCodeAt(0)-65+36;else if(r==="@")n=62;else if(r==="_")n=63;else return Number.NaN;if(n>=t)return Number.NaN;s=s*t+n}return s}function el(e){if(e=e.trim(),e==="")return 0;let t=!1;e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1));let s,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=vf(r[2],n):s=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?s=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?s=Number.parseInt(e,8):s=Number.parseInt(e,10);return Number.isNaN(s)&&(s=0),t?-s:s}function pn(e){if(e=e.trim(),e==="")return{value:0,valid:!0};let t=!1;if(e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let s=Number.parseInt(e,10);return Number.isNaN(s)?{value:0,valid:!1}:{value:t?-s:s,valid:!0}}function Sf(e){let t="",s=0;for(;s=e.length)break;if(e[s]!=="["){s++;continue}s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s=f&&e.state.env.set(`${r}__length`,String(c+1))}else a!==void 0&&e.state.env.set(r,a);return o&&De(e,r),null}function Ct(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function Qt(e,t){return e.state.localVarDepth?.get(t)}function gn(e,t){e.state.localVarDepth?.delete(t)}function ll(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function yn(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function cl(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var Mr=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function ul(e){return Mr.has(e)}var Wr=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),Kt=new Set([":","true","false","cd","export","unset","exit","local","set","break","continue","return","eval","shift","getopts","compgen","complete","compopt","pushd","popd","dirs","source",".","read","mapfile","readarray","declare","typeset","readonly","let","command","shopt","exec","test","[","echo","printf","pwd","alias","unalias","type","hash","ulimit","umask","trap","times","wait","kill","jobs","fg","bg","disown","suspend","fc","history","help","enable","builtin","caller"]);async function wn(e,t,s,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory `;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&s!=="/dev/null")return`bash: ${s}: cannot overwrite existing file `}catch{}return null}function Xt(e){let s=Math.min(e.length,8192);for(let r=0;r127)return"utf8";return"binary"}function kf(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),a=n+r+1,l=t.slice(a),o=l.indexOf(":");if(o===-1)return null;let u=Number.parseInt(l.slice(0,o),10);if(Number.isNaN(u)||u<0)return null;let c=l.slice(o+1);return{path:i,position:u,content:c}}async function fl(e,t){let s=new Map;for(let r=0;r&"||n.operator==="<&"){if(en(e,n.target))return{targets:s,error:`bash: $@: ambiguous redirect `};s.set(r,await V(e,n.target))}else{let a=await tn(e,n.target);if("error"in a)return{targets:s,error:a.error};s.set(r,a.target)}}return{targets:s}}function Nf(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd,s=e.limits.maxFileDescriptors;if(t>=s)throw new Error(`bash: cannot allocate file descriptor: too many open files (max ${s})`);return e.state.nextFd++,t}async function En(e,t){for(let s of t){if(!s.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(s.operator===">&"||s.operator==="<&")&&s.target.type==="Word"&&await V(e,s.target)==="-"){let i=e.state.env.get(s.fdVariable);if(i!==void 0){let a=Number.parseInt(i,10);Number.isNaN(a)||e.state.fileDescriptors.delete(a)}continue}let r=Nf(e);if(e.state.env.set(s.fdVariable,String(r)),s.target.type==="Word"){let n=await V(e,s.target);if(s.operator===">&"||s.operator==="<&"){let i=Number.parseInt(n,10);if(!Number.isNaN(i)){let a=e.state.fileDescriptors.get(i);a!==void 0&&(Ae(e),e.state.fileDescriptors.set(r,a));continue}}if(s.operator===">"||s.operator===">>"||s.operator===">|"||s.operator==="&>"||s.operator==="&>>"){let i=e.fs.resolvePath(e.state.cwd,n);(s.operator===">"||s.operator===">|"||s.operator==="&>")&&await e.fs.writeFile(i,"","binary"),Ae(e),e.state.fileDescriptors.set(r,`__file__:${i}`)}else if(s.operator==="<<<")Ae(e),e.state.fileDescriptors.set(r,`${n} `);else if(s.operator==="<"||s.operator==="<>")try{let i=e.fs.resolvePath(e.state.cwd,n),a=await e.fs.readFile(i);Ae(e),e.state.fileDescriptors.set(r,a)}catch{return _("",`bash: ${n}: No such file or directory `,1)}}}return null}async function lt(e,t){for(let s of t){if(s.target.type==="HereDoc")continue;let r=s.operator===">&";if(s.operator!==">"&&s.operator!==">|"&&s.operator!=="&>"&&!r)continue;let n;if(r){if(n=await V(e,s.target),n==="-"||!Number.isNaN(Number.parseInt(n,10))||s.fd!=null)continue}else{let l=await tn(e,s.target);if("error"in l)return _("",l.error,1);n=l.target}let i=e.fs.resolvePath(e.state.cwd,n),a=s.operator===">|";if(i.includes("\0"))return _("",`bash: ${n}: No such file or directory `,1);try{let l=await e.fs.stat(i);if(l.isDirectory)return _("",`bash: ${n}: Is a directory `,1);if(e.state.options.noclobber&&!a&&!l.isDirectory&&n!=="/dev/null")return _("",`bash: ${n}: cannot overwrite existing file `,1)}catch{}if(n!=="/dev/null"&&n!=="/dev/stdout"&&n!=="/dev/stderr"&&n!=="/dev/full"&&await e.fs.writeFile(i,"","binary"),n==="/dev/full")return _("",`bash: /dev/full: No space left on device `,1)}return null}async function ue(e,t,s,r){let{stdout:n,stderr:i,exitCode:a}=t,o=t.stdoutKind==="bytes"||t.stdoutKind===void 0&&t.stdoutEncoding==="binary"?"binary":"utf8",u=p=>o,c={kind:"live-stdout"},f={kind:"live-stderr"};for(let p=0;p&"||y.operator==="<&"){if(en(e,y.target)){i+=`bash: $@: ambiguous redirect `,a=1,n="";continue}b=await V(e,y.target)}else{let w=await tn(e,y.target);if("error"in w){i+=w.error,a=1,n="";continue}b=w.target}if(!y.fdVariable){if(b.includes("\0")){i+=`bash: ${b.replace(/\0/g,"")}: No such file or directory `,a=1,n="";continue}switch(y.operator){case">":case">|":case">>":{let E=y.fd??1;if(E!==1&&E!==2)break;let w=y.operator===">>",S=y.operator===">|";if(b==="/dev/stdout"){E===2&&(f=c);break}if(b==="/dev/stderr"){E===1&&(c=f);break}if(b==="/dev/full"){i+=`bash: echo: write error: No space left on device `,a=1,E===1&&(n="");break}if(b==="/dev/null"&&E===2){f={kind:"discard"};break}let A=e.fs.resolvePath(e.state.cwd,b),$=await wn(e,A,b,{...w?{}:{checkNoclobber:!0,isClobber:S}});if($){i+=$,a=1,E===1&&(n="");break}w?await e.fs.appendFile(A,"","binary"):await e.fs.writeFile(A,"","binary"),E===1?c={kind:"file",path:A,append:w}:f={kind:"file",path:A,append:w};break}case">&":case"<&":{let E=y.fd??1;if(b==="-")break;if(b.endsWith("-")){let w=b.slice(0,-1),S=Number.parseInt(w,10);if(!Number.isNaN(S)){let A=e.state.fileDescriptors?.get(S);A!==void 0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(E,A),S>=3&&e.state.fileDescriptors?.delete(S)):S===1||S===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(E,`__dupout__:${S}`)):S===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(E,`__dupin__:${S}`)):S>=3&&(i+=`bash: ${S}: Bad file descriptor `,a=1)}break}if(b==="2"||b==="&2")E===1&&(c=f);else if(b==="1"||b==="&1")E===2?f=c:(n+=i,i="");else{let w=Number.parseInt(b,10);if(Number.isNaN(w)){if(y.operator===">&"){let S=e.fs.resolvePath(e.state.cwd,b),A=await wn(e,S,b,{checkNoclobber:!0});if(A){i=A,a=1,n="";break}await e.fs.writeFile(S,"","binary"),y.fd==null?(c={kind:"file",path:S,append:!1},f=c):E===1?c={kind:"file",path:S,append:!1}:E===2&&(f={kind:"file",path:S,append:!1})}}else{let S=e.state.fileDescriptors?.get(w);if(S?.startsWith("__file__:")){let A=S.slice(9);E===1?(await e.fs.appendFile(A,n,u(n)),n=""):E===2&&(await e.fs.appendFile(A,i,Xt(i)),i="")}else if(S?.startsWith("__rw__:")){let A=kf(S);A&&(E===1?(await e.fs.appendFile(A.path,n,u(n)),n=""):E===2&&(await e.fs.appendFile(A.path,i,Xt(i)),i=""))}else if(S?.startsWith("__dupout__:")){let A=Number.parseInt(S.slice(11),10);if(A!==1)if(A===2)E===1&&(i+=n,n="");else{let $=e.state.fileDescriptors?.get(A);if($?.startsWith("__file__:")){let R=$.slice(9);E===1?(await e.fs.appendFile(R,n,u(n)),n=""):E===2&&(await e.fs.appendFile(R,i,Xt(i)),i="")}}}else S?.startsWith("__dupin__:")?(i+=`bash: ${w}: Bad file descriptor `,a=1,n=""):w>=3&&(i+=`bash: ${w}: Bad file descriptor `,a=1,n="")}}break}case"&>":{if(b==="/dev/full"){i=`bash: echo: write error: No space left on device `,a=1,n="";break}let E=e.fs.resolvePath(e.state.cwd,b),w=await wn(e,E,b,{checkNoclobber:!0});if(w){i=w,a=1,n="";break}await e.fs.writeFile(E,"","binary"),c={kind:"file",path:E,append:!1},f=c;break}case"&>>":{if(b==="/dev/full"){i=`bash: echo: write error: No space left on device `,a=1,n="";break}let E=e.fs.resolvePath(e.state.cwd,b),w=await wn(e,E,b,{});if(w){i=w,a=1,n="";break}await e.fs.appendFile(E,"","binary"),c={kind:"file",path:E,append:!0},f=c;break}}}}if(n!==""||i!==""){let p=n,y=i;n="",i="";let b=async(v,E,w)=>{v.append?await e.fs.appendFile(v.path,E,w):await e.fs.writeFile(v.path,E,w)};if(c===f&&c.kind==="file"){let v=p+y;v!==""&&await b(c,v,u(v))}else for(let[v,E,w]of[[p,c,!0],[y,f,!1]])if(v!=="")switch(E.kind){case"live-stdout":n+=v;break;case"live-stderr":i+=v;break;case"file":await b(E,v,w?u(v):Xt(v));break;case"discard":break}}let d=e.state.fileDescriptors?.get(1);if(d){if(d==="__dupout__:2")i+=n,n="";else if(d.startsWith("__file__:")){let p=d.slice(9);await e.fs.appendFile(p,n,u(n)),n=""}else if(d.startsWith("__file_append__:")){let p=d.slice(16);await e.fs.appendFile(p,n,u(n)),n=""}}let h=e.state.fileDescriptors?.get(2);if(h){if(h==="__dupout__:1")n+=i,i="";else if(h.startsWith("__file__:")){let p=h.slice(9);await e.fs.appendFile(p,i,Xt(i)),i=""}else if(h.startsWith("__file_append__:")){let p=h.slice(16);await e.fs.appendFile(p,i,Xt(i)),i=""}}let m=_(n,i,a);return t.stdoutKind&&(m.stdoutKind=t.stdoutKind),t.stdoutEncoding==="binary"&&(m.stdoutEncoding="binary"),m}function dl(e,t){if(e.state.options.posix&&Mr.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin `;throw new Z(2,"",r)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),K}async function _f(e,t){let s="";for(let r of t)if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let n=r.target,i=await V(e,n.content);n.stripTabs&&(i=i.split(` `).map(l=>l.replace(/^\t+/,"")).join(` `)),(r.fd??0)===0&&(s=i)}else if(r.operator==="<<<"&&r.target.type==="Word")s=`${await V(e,r.target)} `;else if(r.operator==="<"&&r.target.type==="Word"){let n=await V(e,r.target),i=e.fs.resolvePath(e.state.cwd,n);try{s=await e.fs.readFile(i)}catch{}}return s}async function bn(e,t,s,r="",n){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,at(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(n??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??"main"),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let i=new Map;for(let u=0;u{let u=e.state.localScopes.length-1,c=e.state.localScopes.pop();if(c)for(let[f,d]of c)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);if(cl(e,u),e.state.fullyUnsetLocals)for(let[f,d]of e.state.fullyUnsetLocals.entries())d===u&&e.state.fullyUnsetLocals.delete(f);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let f=e.state.localExportedVars.pop();if(f)for(let d of f)e.state.exportedVars?.delete(d)}for(let[f,d]of i)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:l,error:o}=await fl(e,t.redirections);if(o)return a(),_("",o,1);try{let u=await _f(e,t.redirections),c=r||u,f=await e.executeCommand(t.body,c);return a(),ue(e,f,t.redirections,l)}catch(u){if(a(),u instanceof ke){let c=_(u.stdout,u.stderr,u.exitCode);return ue(e,c,t.redirections,l)}throw u}}var pl=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],Vr=[".",":","[","alias","bg","bind","break","builtin","caller","cd","command","compgen","complete","compopt","continue","declare","dirs","disown","echo","enable","eval","exec","exit","export","false","fc","fg","getopts","hash","help","history","jobs","kill","let","local","logout","mapfile","popd","printf","pushd","pwd","read","readarray","readonly","return","set","shift","shopt","source","suspend","test","times","trap","true","type","typeset","ulimit","umask","unalias","unset","wait"],xf=["autocd","assoc_expand_once","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","dotglob","execfail","expand_aliases","extdebug","extglob","extquote","failglob","force_fignore","globasciiranges","globstar","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lastpipe","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","nocaseglob","nocasematch","nullglob","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath","xpg_echo"],Cf=Vr;async function zr(e,t){let s=[],r=null,n="",i="",a=null,l=!1,o=!1,u=!1,c=null,f=null,d=null,h=[],m=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let w=0;w=t.length)return N(`compgen: -A: option requires an argument `,2);let A=t[w];if(!m.includes(A))return N(`compgen: ${A}: invalid action name `,2);s.push(A)}else if(S==="-W"){if(w++,w>=t.length)return N(`compgen: -W: option requires an argument `,2);r=t[w]}else if(S==="-P"){if(w++,w>=t.length)return N(`compgen: -P: option requires an argument `,2);n=t[w]}else if(S==="-S"){if(w++,w>=t.length)return N(`compgen: -S: option requires an argument `,2);i=t[w]}else if(S==="-o"){if(w++,w>=t.length)return N(`compgen: -o: option requires an argument `,2);let A=t[w];if(A==="plusdirs")l=!0;else if(A==="dirnames")o=!0;else if(A==="default")u=!0;else if(!(A==="filenames"||A==="nospace"||A==="bashdefault"||A==="noquote"))return N(`compgen: ${A}: invalid option name `,2)}else if(S==="-F"){if(w++,w>=t.length)return N(`compgen: -F: option requires an argument `,2);f=t[w]}else if(S==="-C"){if(w++,w>=t.length)return N(`compgen: -C: option requires an argument `,2);d=t[w]}else if(S==="-X"){if(w++,w>=t.length)return N(`compgen: -X: option requires an argument `,2);c=t[w]}else if(S==="-G"){if(w++,w>=t.length)return N(`compgen: -G: option requires an argument `,2)}else if(S==="--"){h.push(...t.slice(w+1));break}else S.startsWith("-")||h.push(S)}a=h[0]??null;let p=[];if(o){let w=await Fr(e,a);p.push(...w)}if(u){let w=await hl(e,a);p.push(...w)}for(let w of s)if(w==="variable"){let S=Df(e,a);p.push(...S)}else if(w==="export"){let S=Rf(e,a);p.push(...S)}else if(w==="function"){let S=If(e,a);p.push(...S)}else if(w==="builtin"){let S=Of(a);p.push(...S)}else if(w==="keyword"){let S=Tf(a);p.push(...S)}else if(w==="alias"){let S=Lf(e,a);p.push(...S)}else if(w==="shopt"){let S=Mf(a);p.push(...S)}else if(w==="helptopic"){let S=Wf(a);p.push(...S)}else if(w==="directory"){let S=await Fr(e,a);p.push(...S)}else if(w==="file"){let S=await hl(e,a);p.push(...S)}else if(w==="user"){let S=Ff(a);p.push(...S)}else if(w==="command"){let S=await Vf(e,a);p.push(...S)}if(r!==null)try{let w=await zf(e,r),S=Bf(e,w);for(let A of S)(a===null||A.startsWith(a))&&p.push(A)}catch{return _("","",1)}if(l){let w=await Fr(e,a);for(let S of w)p.includes(S)||p.push(S)}let y="";if(f!==null){let w=e.state.functions.get(f);if(w){let S=new Map;S.set("COMP_WORDS__length",e.state.env.get("COMP_WORDS__length")),e.state.env.set("COMP_WORDS__length","0"),S.set("COMP_CWORD",e.state.env.get("COMP_CWORD")),e.state.env.set("COMP_CWORD","-1"),S.set("COMP_LINE",e.state.env.get("COMP_LINE")),e.state.env.set("COMP_LINE",""),S.set("COMP_POINT",e.state.env.get("COMP_POINT")),e.state.env.set("COMP_POINT","0");let A=new Map;for(let R of e.state.env.keys())(R==="COMPREPLY"||R.startsWith("COMPREPLY_")||R==="COMPREPLY__length")&&(A.set(R,e.state.env.get(R)),e.state.env.delete(R));let $=["compgen",h[0]??"",""];try{let R=await bn(e,w,$,"");if(R.exitCode!==0)return Yt(e,S),Yt(e,A),_("",R.stderr,1);y=R.stdout;let C=qf(e);p.push(...C)}catch{return Yt(e,S),Yt(e,A),_("","",1)}Yt(e,S),Yt(e,A)}}if(d!==null)try{let w=Ce(d),S=await e.executeScript(w);if(S.exitCode!==0)return _("",S.stderr,S.exitCode);if(S.stdout){let A=S.stdout.split(` `);for(let $ of A)$.length>0&&p.push($)}}catch(w){if(w.name==="ParseException")return N(`compgen: -C: ${w.message} `,2);throw w}let b=p;if(c!==null){let w=c.startsWith("!"),S=w?c.slice(1):c;b=p.filter(A=>{let $=Ht(A,S,!1,!0);return w?$:!$})}if(b.length===0&&a!==null)return _(y,"",1);let v=b.map(w=>`${n}${w}${i}`).join(` `),E=y+(v?`${v} `:"");return H(E)}function Df(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length"))continue;let i=n.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Rf(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length")?!1:e.state.env.has(n)),r.sort()}function If(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function Of(e){let t=[...Vr];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Tf(e){let t=[...pl];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Lf(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith("BASH_ALIAS_")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Mf(e){let t=[...xf];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Wf(e){let t=[...Cf];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function Fr(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let l=t.slice(0,a)||"/";n=t.slice(a+1),l.startsWith("/")?r=l:r=`${e.state.cwd}/${l}`}}let i=await e.fs.readdir(r);for(let a of i){let l=`${r}/${a}`;try{if((await e.fs.stat(l)).isDirectory&&(!n||a.startsWith(n)))if(t?.includes("/")){let u=t.lastIndexOf("/"),c=t.slice(0,u+1);s.push(c+a)}else s.push(a)}catch{}}}catch{}return s.sort()}async function hl(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let l=t.slice(0,a)||"/";n=t.slice(a+1),l.startsWith("/")?r=l:r=`${e.state.cwd}/${l}`}}let i=await e.fs.readdir(r);for(let a of i)if(!n||a.startsWith(n))if(t?.includes("/")){let l=t.lastIndexOf("/"),o=t.slice(0,l+1);s.push(o+a)}else s.push(a)}catch{}return s.sort()}function Ff(e){return["root","nobody"]}async function Vf(e,t){let s=new Set;for(let i of Vr)s.add(i);for(let i of e.state.functions.keys())s.add(i);for(let i of e.state.env.keys())i.startsWith("BASH_ALIAS_")&&s.add(i.slice(11));for(let i of pl)s.add(i);let r=e.state.env.get("PATH")??"/usr/bin:/bin";for(let i of r.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let l of a)s.add(l)}catch{}let n=Array.from(s);return t!==null&&(n=n.filter(i=>i.startsWith(t))),n.sort()}async function zf(e,t){let r=new q().parseWordFromString(t,!1,!1);return await V(e,r)}function Bf(e,t){let s=e.state.env.get("IFS")??` `;if(s.length===0)return[t];let r=new Set(s.split("")),n=[],i="",a=0;for(;a0&&(n.push(i),i=""),a++):(i+=l,a++)}return i.length>0&&n.push(i),n}function Yt(e,t){for(let[s,r]of t)r===void 0?e.state.env.delete(s):e.state.env.set(s,r)}function qf(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let n=B(e,"COMPREPLY");for(let[,i]of n)t.push(i)}else{let n=e.state.env.get("COMPREPLY");n!==void 0&&t.push(n)}return t}var jf=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function qr(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=!1,i,a,l,o=[],u=[],c=[];for(let f=0;f=t.length)return N(`complete: -W: option requires an argument `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return N(`complete: -F: option requires an argument `,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return N(`complete: -o: option requires an argument `,2);let h=t[f];if(!jf.includes(h))return N(`complete: ${h}: invalid option name `,2);o.push(h)}else if(d==="-A"){if(f++,f>=t.length)return N(`complete: -A: option requires an argument `,2);u.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return N(`complete: -C: option requires an argument `,2);l=t[f]}else if(d==="-G"){if(f++,f>=t.length)return N(`complete: -G: option requires an argument `,2)}else if(d==="-P"){if(f++,f>=t.length)return N(`complete: -P: option requires an argument `,2)}else if(d==="-S"){if(f++,f>=t.length)return N(`complete: -S: option requires an argument `,2)}else if(d==="-X"){if(f++,f>=t.length)return N(`complete: -X: option requires an argument `,2)}else if(d==="--"){c.push(...t.slice(f+1));break}else d.startsWith("-")||c.push(d)}if(r){if(c.length===0)return e.state.completionSpecs.clear(),H("");for(let f of c)e.state.completionSpecs.delete(f);return H("")}if(s)return c.length===0?Br(e):Br(e,c);if(t.length===0||c.length===0&&!i&&!a&&!l&&o.length===0&&u.length===0&&!n)return Br(e);if(a&&c.length===0&&!n)return N(`complete: -F: option requires a command name `,2);if(n){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),a!==void 0&&(f.function=a),l!==void 0&&(f.command=l),o.length>0&&(f.options=o),u.length>0&&(f.actions=u),e.state.completionSpecs.set("__default__",f),H("")}for(let f of c){let d=Object.create(null);i!==void 0&&(d.wordlist=i),a!==void 0&&(d.function=a),l!==void 0&&(d.command=l),o.length>0&&(d.options=o),u.length>0&&(d.actions=u),e.state.completionSpecs.set(f,d)}return H("")}function Br(e,t){let s=e.state.completionSpecs;if(!s||s.size===0){if(t&&t.length>0){let i="";for(let a of t)i+=`complete: ${a}: no completion specification `;return _("",i,1)}return H("")}let r=[],n=t||Array.from(s.keys());for(let i of n){if(i==="__default__")continue;let a=s.get(i);if(!a){if(t)return _(r.join(` `)+(r.length>0?` `:""),`complete: ${i}: no completion specification `,1);continue}let l="complete";if(a.options)for(let o of a.options)l+=` -o ${o}`;if(a.actions)for(let o of a.actions)l+=` -A ${o}`;a.wordlist!==void 0&&(a.wordlist.includes(" ")||a.wordlist.includes("'")?l+=` -W '${a.wordlist}'`:l+=` -W ${a.wordlist}`),a.function!==void 0&&(l+=` -F ${a.function}`),a.isDefault&&(l+=" -D"),l+=` ${i}`,r.push(l)}return r.length===0?H(""):H(`${r.join(` `)} `)}var ml=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function jr(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=[],i=[],a=[];for(let l=0;l=t.length)return N(`compopt: -o: option requires an argument `,2);let u=t[l];if(!ml.includes(u))return N(`compopt: ${u}: invalid option name `,2);n.push(u)}else if(o==="+o"){if(l++,l>=t.length)return N(`compopt: +o: option requires an argument `,2);let u=t[l];if(!ml.includes(u))return N(`compopt: ${u}: invalid option name `,2);i.push(u)}else if(o==="--"){a.push(...t.slice(l+1));break}else!o.startsWith("-")&&!o.startsWith("+")&&a.push(o)}if(s){let l=e.state.completionSpecs.get("__default__")??{isDefault:!0},o=new Set(l.options??[]);for(let u of n)o.add(u);for(let u of i)o.delete(u);return l.options=o.size>0?Array.from(o):void 0,e.state.completionSpecs.set("__default__",l),H("")}if(r){let l=e.state.completionSpecs.get("__empty__")??{},o=new Set(l.options??[]);for(let u of n)o.add(u);for(let u of i)o.delete(u);return l.options=o.size>0?Array.from(o):void 0,e.state.completionSpecs.set("__empty__",l),H("")}if(a.length>0){for(let l of a){let o=e.state.completionSpecs.get(l)??{},u=new Set(o.options??[]);for(let c of n)u.add(c);for(let c of i)u.delete(c);o.options=u.size>0?Array.from(u):void 0,e.state.completionSpecs.set(l,o)}return H("")}return N(`compopt: not currently executing completion function `,1)}function Ur(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Et;return K}if(t.length>1)throw new Z(1,"",`bash: continue: too many arguments `);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new Z(1,"",`bash: continue: ${t[0]}: numeric argument required `);s=r}throw new Te(s)}function de(e,t){let s=e.state.env.get("HOME")||"/home/user";return t.split(":").map(i=>i==="~"?s:i==="~root"?"/root":i.startsWith("~/")?s+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function Zr(e){for(let t=0;t{let h=e.state.env.get(`${i}_${d}`)??"",m=Qr(h);return`['${d}']=${m}`});s+=`declare -A ${i}=(${f.join(" ")}) `}continue}let o=he(e,i);if(o.length>0){let c=o.map(f=>{let d=e.state.env.get(`${i}_${f}`)??"";return`[${f}]=${Lt(d)}`});s+=`declare -a ${i}=(${c.join(" ")}) `;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=() `;continue}let u=e.state.env.get(i);if(u!==void 0)s+=`declare ${a} ${i}=${Hr(u)} `;else{let c=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);c||f?s+=`declare ${a} ${i} `:(r+=`bash: declare: ${i}: not found `,n=!0)}}return _(s,r,n?1:0)}function wl(e,t){let{filterExport:s,filterReadonly:r,filterNameref:n,filterIndexedArray:i,filterAssocArray:a}=t,l=s||r||n||i||a,o="",u=new Set;for(let f of e.state.env.keys()){if(f.startsWith("BASH_"))continue;if(f.endsWith("__length")){let h=f.slice(0,-8);u.add(h);continue}let d=f.lastIndexOf("_");if(d>0){let h=f.slice(0,d),m=f.slice(d+1);if(/^\d+$/.test(m)||e.state.associativeArrays?.has(h)){u.add(h);continue}}u.add(f)}if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())u.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)u.add(f);let c=Array.from(u).sort();for(let f of c){let d=gl(e,f),h=e.state.associativeArrays?.has(f),m=he(e,f),p=!h&&(m.length>0||e.state.env.has(`${f}__length`));if(l&&(a&&!h||i&&!p||s&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||n&&!te(e,f)))continue;if(h){let b=Ge(e,f);if(b.length===0)o+=`declare -A ${f}=() `;else{let v=b.map(E=>{let w=e.state.env.get(`${f}_${E}`)??"",S=Qr(w);return`['${E}']=${S}`});o+=`declare -A ${f}=(${v.join(" ")}) `}continue}if(m.length>0){let b=m.map(v=>{let E=e.state.env.get(`${f}_${v}`)??"";return`[${v}]=${Lt(E)}`});o+=`declare -a ${f}=(${b.join(" ")}) `;continue}if(e.state.env.has(`${f}__length`)){o+=`declare -a ${f}=() `;continue}let y=e.state.env.get(f);y!==void 0&&(o+=`declare ${d} ${f}=${Hr(y)} `)}return H(o)}function El(e){let t="",s=Array.from(e.state.associativeArrays??[]).sort();for(let r of s){let n=Ge(e,r);if(n.length===0)t+=`declare -A ${r}=() `;else{let i=n.map(a=>{let l=e.state.env.get(`${r}_${a}`)??"",o=Qr(l);return`['${a}']=${o}`});t+=`declare -A ${r}=(${i.join(" ")}) `}}return H(t)}function bl(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let a=n.slice(0,-8);e.state.associativeArrays?.has(a)||s.add(a);continue}let i=n.lastIndexOf("_");if(i>0){let a=n.slice(0,i),l=n.slice(i+1);/^\d+$/.test(l)&&(e.state.associativeArrays?.has(a)||s.add(a))}}let r=Array.from(s).sort();for(let n of r){let i=he(e,n);if(i.length===0)t+=`declare -a ${n}=() `;else{let a=i.map(l=>{let o=e.state.env.get(`${n}_${l}`)??"";return`[${l}]=${Lt(o)}`});t+=`declare -a ${n}=(${a.join(" ")}) `}}return H(t)}function vl(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let a=n.slice(0,-8);s.add(a);continue}let i=n.lastIndexOf("_");if(i>0){let a=n.slice(0,i),l=n.slice(i+1);if(/^\d+$/.test(l)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(n)}let r=Array.from(s).sort();for(let n of r){if(e.state.associativeArrays?.has(n)||he(e,n).length>0||e.state.env.has(`${n}__length`))continue;let l=e.state.env.get(n);l!==void 0&&(t+=`${n}=${vn(l)} `)}return H(t)}function Kr(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function ws(e,t){return e.state.integerVars?.has(t)??!1}function Xr(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Uf(e,t){return e.state.lowercaseVars?.has(t)??!1}function Yr(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Zf(e,t){return e.state.uppercaseVars?.has(t)??!1}function Jt(e,t,s){return Uf(e,t)?s.toLowerCase():Zf(e,t)?s.toUpperCase():s}async function Sl(e,t){try{let s=new q,r=Y(s,t),n=await T(e,r.expression);return String(n)}catch{return"0"}}function Gf(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],r=s.length;if(e[r]!=="[")return null;let n=0,i=r+1;for(;r0&&!y,w=C=>{if(!E)return;let F=e.state.localScopes[e.state.localScopes.length-1];F.has(C)||F.set(C,e.state.env.get(C))},S=C=>{if(!E)return;let F=e.state.localScopes[e.state.localScopes.length-1];F.has(C)||F.set(C,e.state.env.get(C));let k=`${C}_`;for(let D of e.state.env.keys())D.startsWith(k)&&!D.includes("__")&&(F.has(D)||F.set(D,e.state.env.get(D)));let x=`${C}__length`;e.state.env.has(x)&&!F.has(x)&&F.set(x,e.state.env.get(x))},A=C=>{E&&Ct(e,C)};if(p){if(b.length===0){let k=Array.from(e.state.functions.keys()).sort(),x="";for(let D of k)x+=`declare -f ${D} `;return H(x)}let C=!0,F="";for(let k of b)e.state.functions.has(k)?F+=`${k} `:C=!1;return _(F,"",C?0:1)}if(m){if(b.length===0){let F="",k=Array.from(e.state.functions.keys()).sort();for(let x of k)F+=`${x} () { # function body } `;return H(F)}let C=!0;for(let F of b)e.state.functions.has(F)||(C=!1);return _("","",C?0:1)}if(a&&b.length>0)return yl(e,b);if(a&&b.length===0)return wl(e,{filterExport:i,filterReadonly:n,filterNameref:l,filterIndexedArray:s,filterAssocArray:r});if(b.length===0&&r&&!a)return El(e);if(b.length===0&&s&&!a)return bl(e);if(b.length===0&&!a)return vl(e);let $="",R=0;for(let C of b){let F=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(F&&!u){let P=F[1],O=F[2];if(r&&he(e,P).length>0){$+=`bash: declare: ${P}: cannot convert indexed to associative array `,R=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has(P)){$+=`bash: declare: ${P}: cannot convert associative to indexed array `,R=1;continue}if(S(P),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(P)),tt(e,P),e.state.env.delete(P),e.state.env.delete(`${P}__length`),r&&O.includes("[")){let z=mn(O);for(let[U,ee]of z){let fe=de(e,ee);e.state.env.set(`${P}_${U}`,fe)}}else if(r){let z=ot(O);for(let U=0;U/^\[[^\]]+\]=/.test(ee))){let ee=0;for(let fe of z){let ge=fe.match(/^\[([^\]]+)\]=(.*)$/);if(ge){let Re=ge[1],Vt=ge[2],kc=de(e,Vt),as;if(/^-?\d+$/.test(Re))as=Number.parseInt(Re,10);else try{let Nc=new q,_c=Y(Nc,Re);as=await T(e,_c.expression)}catch{as=0}e.state.env.set(`${P}_${as}`,kc),ee=as+1}else{let Re=de(e,fe);e.state.env.set(`${P}_${ee}`,Re),ee++}}}else{for(let ee=0;ee=fe&&e.state.env.set(`${P}__length`,String(ee+1)),A(P),n&&De(e,P),i&&Qe(e,P);continue}let x=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(x&&!u){let P=x[1],O=x[2],z=ye(e,P);if(z)return z;S(P);let U=ot(O);if(e.state.associativeArrays?.has(P)){let ee=mn(O);for(let[fe,ge]of ee){let Re=de(e,ge);e.state.env.set(`${P}_${fe}`,Re)}}else{let ee=he(e,P),fe=0,ge=e.state.env.get(P);ee.length===0&&ge!==void 0?(e.state.env.set(`${P}_0`,ge),e.state.env.delete(P),fe=1):ee.length>0&&(fe=Math.max(...ee)+1);for(let Vt=0;Vt0||e.state.associativeArrays?.has(P);if(ws(e,P)){let fe=e.state.env.get(P)??"0",ge=parseInt(fe,10)||0,Re=parseInt(await Sl(e,O),10)||0;O=String(ge+Re),e.state.env.set(P,O)}else if(ee){O=Jt(e,P,O);let fe=`${P}_0`,ge=e.state.env.get(fe)??"";e.state.env.set(fe,ge+O)}else{O=Jt(e,P,O);let fe=e.state.env.get(P)??"";e.state.env.set(P,fe+O)}A(P),n&&De(e,P),i&&Qe(e,P),e.state.options.allexport&&!c&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(P));continue}if(C.includes("=")){let P=C.indexOf("="),O=C.slice(0,P),z=C.slice(P+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(O)){$+=`bash: typeset: \`${O}': not a valid identifier `,R=1;continue}let U=ye(e,O);if(U)return U;if(w(O),l){if(z!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(z)){$+=`bash: declare: \`${z}': invalid variable name for name reference `,R=1;continue}e.state.env.set(O,z),pt(e,O),z!==""&&Zs(e,z)&&Ar(e,O),A(O),n&&De(e,O),i&&Qe(e,O);continue}if(f&&Kr(e,O),d&&Xr(e,O),h&&Yr(e,O),ws(e,O)&&(z=await Sl(e,z)),z=Jt(e,O,z),te(e,O)){let ee=$e(e,O);ee&&ee!==O?e.state.env.set(ee,z):e.state.env.set(O,z)}else e.state.env.set(O,z);A(O),n&&De(e,O),i&&Qe(e,O),e.state.options.allexport&&!c&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(O))}else{let P=C;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(P)){$+=`bash: typeset: \`${P}': not a valid identifier `,R=1;continue}if(s||r?S(P):w(P),l){pt(e,P);let z=e.state.env.get(P);z!==void 0&&z!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(z)?Wa(e,P):z&&Zs(e,z)&&Ar(e,P),A(P),n&&De(e,P),i&&Qe(e,P);continue}if(f&&Kr(e,P),d&&Xr(e,P),h&&Yr(e,P),r){if(he(e,P).length>0){$+=`bash: declare: ${P}: cannot convert indexed to associative array `,R=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(P)}let O=Array.from(e.state.env.keys()).some(z=>z.startsWith(`${P}_`)&&!z.startsWith(`${P}__length`));!e.state.env.has(P)&&!O&&(s||r?e.state.env.set(`${P}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(P))),A(P),n&&De(e,P),i&&Qe(e,P)}}return _("",$,R)}async function ei(e,t){let s=!1,r=!1,n=!1,i=[];for(let a=0;a0&&(y=Math.max(...p)+1);for(let E=0;Er&&r!=="."),s=[];for(let r of t)r===".."?s.pop():s.push(r);return`/${s.join("/")}`}async function si(e,t){let s=ti(e),r;for(let l=0;lo);l.pop(),n=`/${l.join("/")}`}else r==="."?n=e.state.cwd:r.startsWith("~")?n=(e.state.env.get("HOME")||"/")+r.slice(1):n=`${e.state.cwd}/${r}`;n=Hf(n);try{if(!(await e.fs.stat(n)).isDirectory)return N(`bash: pushd: ${r}: Not a directory `,1)}catch{return N(`bash: pushd: ${r}: No such file or directory `,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=n,e.state.env.set("PWD",n),e.state.env.set("OLDPWD",e.state.previousDir);let i=e.state.env.get("HOME")||"",a=`${[n,...s].map(l=>Es(l,i)).join(" ")} `;return H(a)}function ni(e,t){let s=ti(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?N(`bash: popd: ${a}: invalid option `,2):N(`bash: popd: too many arguments `,2);if(s.length===0)return N(`bash: popd: directory stack empty `,1);let r=s.shift();if(!r)return N(`bash: popd: directory stack empty `,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set("PWD",r),e.state.env.set("OLDPWD",e.state.previousDir);let n=e.state.env.get("HOME")||"",i=`${[r,...s].map(a=>Es(a,n)).join(" ")} `;return H(i)}function ri(e,t){let s=ti(e),r=!1,n=!1,i=!1,a=!1;for(let c of t)if(c!=="--")if(c.startsWith("-"))for(let f of c.slice(1))if(f==="c")r=!0;else if(f==="l")n=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,a=!0;else return N(`bash: dirs: -${f}: invalid option `,2);else return N(`bash: dirs: too many arguments `,1);if(r)return e.state.directoryStack=[],K;let l=[e.state.cwd,...s],o=e.state.env.get("HOME")||"",u;return a?(u=l.map((c,f)=>{let d=n?c:Es(c,o);return` ${f} ${d}`}).join(` `),u+=` `):i?u=l.map(c=>n?c:Es(c,o)).join(` `)+` `:u=l.map(c=>n?c:Es(c,o)).join(" ")+` `,H(u)}async function Sn(e,t,s){let r=t;if(r.length>0){let l=r[0];if(l==="--")r=r.slice(1);else if(l.startsWith("-")&&l!=="-"&&l.length>1)return N(`bash: eval: ${l}: invalid option eval: usage: eval [arg ...] `,2)}if(r.length===0)return K;let n=r.join(" ");if(n.trim()==="")return K;let i=e.state.groupStdin,a=s??e.state.groupStdin;a!==void 0&&(e.state.groupStdin=a);try{let l=Ce(n);return await e.executeScript(l)}catch(l){if(l instanceof Oe||l instanceof Te||l instanceof ke||l instanceof Z)throw l;if(l.name==="ParseException")return N(`bash: eval: ${l.message} `);throw l}finally{e.state.groupStdin=i}}function ii(e,t){let s,r="";if(t.length===0)s=e.state.lastExitCode;else{let n=t[0],i=Number.parseInt(n,10);n===""||Number.isNaN(i)||!/^-?\d+$/.test(n)?(r=`bash: exit: ${n}: numeric argument required `,s=2):s=(i%256+256)%256}throw new Z(s,"",r)}function ai(e,t){let s=!1,r=[];for(let a of t)a==="-n"?s=!0:a==="-p"||a==="--"||r.push(a);if(r.length===0&&!s){let a="",l=e.state.exportedVars??new Set,o=Array.from(l).sort();for(let u of o){let c=e.state.env.get(u);if(c!==void 0){let f=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -x ${u}="${f}" `}}return H(a)}if(s){for(let a of r){let l,o;if(a.includes("=")){let u=a.indexOf("=");l=a.slice(0,u),o=de(e,a.slice(u+1)),e.state.env.set(l,o)}else l=a;Hs(e,l)}return K}let n="",i=0;for(let a of r){let l,o,u=!1,c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c)l=c[1],o=de(e,c[2]),u=!0;else if(a.includes("=")){let f=a.indexOf("=");l=a.slice(0,f),o=de(e,a.slice(f+1))}else l=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)){n+=`bash: export: \`${a}': not a valid identifier `,i=1;continue}if(o!==void 0)if(u){let f=e.state.env.get(l)??"";e.state.env.set(l,f+o)}else e.state.env.set(l,o);else e.state.env.has(l)||e.state.env.set(l,"");Qe(e,l)}return _("",n,i)}function An(e,t){if(t.length<2)return N(`bash: getopts: usage: getopts optstring name [arg ...] `);let s=t[0],r=t[1],n=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=s.startsWith(":"),a=i?s.slice(1):s,l;if(t.length>2)l=t.slice(2);else{let p=Number.parseInt(e.state.env.get("#")||"0",10);l=[];for(let y=1;y<=p;y++)l.push(e.state.env.get(String(y))||"")}let o=Number.parseInt(e.state.env.get("OPTIND")||"1",10);o<1&&(o=1);let u=Number.parseInt(e.state.env.get("__GETOPTS_CHARINDEX")||"0",10);if(e.state.env.set("OPTARG",""),o>l.length)return n||e.state.env.set(r,"?"),e.state.env.set("OPTIND",String(l.length+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:n?2:1,stdout:"",stderr:""};let c=l[o-1];if(!c||c==="-"||!c.startsWith("-"))return n||e.state.env.set(r,"?"),{exitCode:n?2:1,stdout:"",stderr:""};if(c==="--")return e.state.env.set("OPTIND",String(o+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),n||e.state.env.set(r,"?"),{exitCode:n?2:1,stdout:"",stderr:""};let f=u===0?1:u,d=c[f];if(!d)return e.state.env.set("OPTIND",String(o+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),An(e,t);let h=a.indexOf(d);if(h===-1){let p="";return i?e.state.env.set("OPTARG",d):p=`bash: illegal option -- ${d} `,n||e.state.env.set(r,"?"),f+1=l.length){let p="";return i?(e.state.env.set("OPTARG",d),n||e.state.env.set(r,":")):(p=`bash: option requires an argument -- ${d} `,n||e.state.env.set(r,"?")),e.state.env.set("OPTIND",String(o+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:n?2:0,stdout:"",stderr:p}}e.state.env.set("OPTARG",l[o]),e.state.env.set("OPTIND",String(o+2)),e.state.env.set("__GETOPTS_CHARINDEX","0")}else f+1=t.length)return N(`bash: hash: -p: option requires an argument `,1);l=t[u],u++}else if(m.startsWith("-")&&m.length>1){for(let p of m.slice(1))if(p==="r")s=!0;else if(p==="d")r=!0;else if(p==="l")n=!0;else if(p==="t")a=!0;else return p==="p"?N(`bash: hash: -p: option requires an argument `,1):N(`bash: hash: -${p}: invalid option `,1);u++}else o.push(m),u++}if(s)return e.state.hashTable.clear(),K;if(r){if(o.length===0)return N(`bash: hash: -d: option requires an argument `,1);let m=!1,p="";for(let y of o)e.state.hashTable.has(y)?e.state.hashTable.delete(y):(p+=`bash: hash: ${y}: not found `,m=!0);return m?N(p,1):K}if(a){if(o.length===0)return N(`bash: hash: -t: option requires an argument `,1);let m="",p=!1,y="";for(let b of o){let v=e.state.hashTable.get(b);v?o.length>1?m+=`${b} ${v} `:m+=`${v} `:(y+=`bash: hash: ${b}: not found `,p=!0)}return p?{exitCode:1,stdout:m,stderr:y}:H(m)}if(i){if(o.length===0)return N(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...] `,1);let m=o[0];return e.state.hashTable.set(m,l),K}if(o.length===0){if(e.state.hashTable.size===0)return H(`hash: hash table empty `);let m="";if(n)for(let[p,y]of e.state.hashTable)m+=`builtin hash -p ${y} ${p} `;else{m=`hits command `;for(let[,p]of e.state.hashTable)m+=` 1 ${p} `}return H(m)}let c=!1,f="",h=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let m of o){if(m.includes("/")){f+=`bash: hash: ${m}: cannot use / in name `,c=!0;continue}let p=!1;for(let y of h){if(!y)continue;let b=`${y}/${m}`;if(await e.fs.exists(b)){e.state.hashTable.set(m,b),p=!0;break}}p||(f+=`bash: hash: ${m}: not found `,c=!0)}return c?N(f,1):K}var Al=new Map([[":",[": [arguments]",`Null command. No effect; the command does nothing. Exit Status: Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME. Exit Status: Returns the status of the last command executed in FILENAME.`]],["[",["[ arg... ]",`Evaluate conditional expression. This is a synonym for the "test" builtin, but the last argument must be a literal \`]', to match the opening \`['.`]],["alias",["alias [-p] [name[=value] ... ]",`Define or display aliases. Without arguments, \`alias' prints the list of aliases in the reusable form \`alias NAME=VALUE' on standard output. Exit Status: alias returns true unless a NAME is supplied for which no alias has been defined.`]],["bg",["bg [job_spec ...]",`Move jobs to the background. Place the jobs identified by each JOB_SPEC in the background, as if they had been started with \`&'.`]],["break",["break [n]",`Exit for, while, or until loops. Exit a FOR, WHILE or UNTIL loop. If N is specified, break N enclosing loops. Exit Status: The exit status is 0 unless N is not greater than or equal to 1.`]],["builtin",["builtin [shell-builtin [arg ...]]",`Execute shell builtins. Execute SHELL-BUILTIN with arguments ARGs without performing command lookup. This is useful when you wish to reimplement a shell builtin as a shell function, but need to execute the builtin within the function. Exit Status: Returns the exit status of SHELL-BUILTIN, or false if SHELL-BUILTIN is not a shell builtin.`]],["caller",["caller [expr]",`Return the context of the current subroutine call. Without EXPR, returns "$line $filename". With EXPR, returns "$line $subroutine $filename"; this extra information can be used to provide a stack trace. Exit Status: Returns 0 unless the shell is not executing a subroutine call or EXPR is invalid.`]],["cd",["cd [-L|-P] [dir]",`Change the shell working directory. Change the current directory to DIR. The default DIR is the value of the HOME shell variable. The variable CDPATH defines the search path for the directory containing DIR. Alternative directory names in CDPATH are separated by a colon (:). A null directory name is the same as the current directory. If DIR begins with a slash (/), then CDPATH is not used. If the directory is not found, and the shell option \`cdable_vars' is set, the word is assumed to be a variable name. If that variable has a value, its value is used for DIR. Options: -L force symbolic links to be followed -P use the physical directory structure without following symbolic links The default is to follow symbolic links, as if \`-L' were specified. Exit Status: Returns 0 if the directory is changed; non-zero otherwise.`]],["command",["command [-pVv] command [arg ...]",`Execute a simple command or display information about commands. Runs COMMAND with ARGS suppressing shell function lookup, or display information about the specified COMMANDs. Options: -p use a default value for PATH that is guaranteed to find all of the standard utilities -v print a description of COMMAND similar to the \`type' builtin -V print a more verbose description of each COMMAND Exit Status: Returns exit status of COMMAND, or failure if COMMAND is not found.`]],["compgen",["compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]",`Display possible completions depending on the options. Intended to be used from within a shell function generating possible completions. If the optional WORD argument is supplied, matches against WORD are generated. Exit Status: Returns success unless an invalid option is supplied or an error occurs.`]],["complete",["complete [-abcdefgjksuv] [-pr] [-DEI] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [name ...]",`Specify how arguments are to be completed. For each NAME, specify how arguments are to be completed. Exit Status: Returns success unless an invalid option is supplied or an error occurs.`]],["continue",["continue [n]",`Resume for, while, or until loops. Resumes the next iteration of the enclosing FOR, WHILE or UNTIL loop. If N is specified, resumes the Nth enclosing loop. Exit Status: The exit status is 0 unless N is not greater than or equal to 1.`]],["declare",["declare [-aAfFgilnrtux] [-p] [name[=value] ...]",`Set variable values and attributes. Declare variables and give them attributes. If no NAMEs are given, display the attributes and values of all variables. Options: -a to make NAMEs indexed arrays (if supported) -A to make NAMEs associative arrays (if supported) -i to make NAMEs have the \`integer' attribute -l to convert the value of each NAME to lower case on assignment -n make NAME a reference to the variable named by its value -r to make NAMEs readonly -t to make NAMEs have the \`trace' attribute -u to convert the value of each NAME to upper case on assignment -x to make NAMEs export Exit Status: Returns success unless an invalid option is supplied or a variable assignment error occurs.`]],["dirs",["dirs [-clpv] [+N] [-N]",`Display directory stack. Display the list of currently remembered directories. Directories find their way onto the list with the \`pushd' command; you can get back up through the list with the \`popd' command. Exit Status: Returns success unless an invalid option is supplied or an error occurs.`]],["disown",["disown [-h] [-ar] [jobspec ...]",`Remove jobs from current shell. Without any JOBSPECs, remove the current job.`]],["echo",["echo [-neE] [arg ...]",`Write arguments to the standard output. Display the ARGs, separated by a single space character and followed by a newline, on the standard output. Options: -n do not append a newline -e enable interpretation of the following backslash escapes -E explicitly suppress interpretation of backslash escapes Exit Status: Returns success unless a write error occurs.`]],["enable",["enable [-a] [-dnps] [-f filename] [name ...]",`Enable and disable shell builtins. Enables and disables builtin shell commands. Exit Status: Returns success unless NAME is not a shell builtin or an error occurs.`]],["eval",["eval [arg ...]",`Execute arguments as a shell command. Combine ARGs into a single string, use the result as input to the shell, and execute the resulting commands. Exit Status: Returns exit status of command or success if command is null.`]],["exec",["exec [-cl] [-a name] [command [arguments ...]] [redirection ...]",`Replace the shell with the given command. Execute COMMAND, replacing this shell with the specified program. ARGUMENTS become the arguments to COMMAND. If COMMAND is not specified, any redirections take effect in the current shell. Exit Status: Returns success unless COMMAND is not found or a redirection error occurs.`]],["exit",["exit [n]",`Exit the shell. Exits the shell with a status of N. If N is omitted, the exit status is that of the last command executed.`]],["export",["export [-fn] [name[=value] ...] or export -p",`Set export attribute for shell variables. Marks each NAME for automatic export to the environment of subsequently executed commands. If VALUE is supplied, assign VALUE before exporting. Options: -f refer to shell functions -n remove the export property from each NAME -p display a list of all exported variables and functions Exit Status: Returns success unless an invalid option is given or NAME is invalid.`]],["false",["false",`Return an unsuccessful result. Exit Status: Always fails.`]],["fc",["fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command]",`Display or execute commands from the history list. Exit Status: Returns success or status of executed command.`]],["fg",["fg [job_spec]",`Move job to the foreground. Place the job identified by JOB_SPEC in the foreground, making it the current job.`]],["getopts",["getopts optstring name [arg]",`Parse option arguments. Getopts is used by shell procedures to parse positional parameters as options. OPTSTRING contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. Exit Status: Returns success if an option is found; fails if the end of options is encountered or an error occurs.`]],["hash",["hash [-lr] [-p pathname] [-dt] [name ...]",`Remember or display program locations. Determine and remember the full pathname of each command NAME. Exit Status: Returns success unless NAME is not found or an invalid option is given.`]],["help",["help [-s] [pattern ...]",`Display information about builtin commands. Displays brief summaries of builtin commands. If PATTERN is specified, gives detailed help on all commands matching PATTERN, otherwise the list of help topics is printed. Options: -s output only a short usage synopsis for each topic matching PATTERN Exit Status: Returns success unless PATTERN is not found.`]],["history",["history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]",`Display or manipulate the history list. Display the history list with line numbers, prefixing each modified entry with a \`*'. Exit Status: Returns success unless an invalid option is given or an error occurs.`]],["jobs",["jobs [-lnprs] [jobspec ...] or jobs -x command [args]",`Display status of jobs. Lists the active jobs. Exit Status: Returns success unless an invalid option is given or an error occurs.`]],["kill",["kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]",`Send a signal to a job. Send the processes identified by PID or JOBSPEC the signal named by SIGSPEC or SIGNUM. Exit Status: Returns success unless an invalid option is given or an error occurs.`]],["let",["let arg [arg ...]",`Evaluate arithmetic expressions. Evaluate each ARG as an arithmetic expression. Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error. Exit Status: If the last ARG evaluates to 0, let returns 1; 0 is returned otherwise.`]],["local",["local [option] name[=value] ...",`Define local variables. Create a local variable called NAME, and give it VALUE. OPTION can be any option accepted by \`declare'. Local can only be used within a function; it makes the variable NAME have a visible scope restricted to that function and its children. Exit Status: Returns success unless an invalid option is supplied, a variable assignment error occurs, or the shell is not executing a function.`]],["logout",["logout [n]",`Exit a login shell. Exits a login shell with exit status N. Returns an error if not executed in a login shell.`]],["mapfile",["mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]",`Read lines from the standard input into an indexed array variable. Read lines from the standard input into the indexed array variable ARRAY, or from file descriptor FD if the -u option is supplied. Options: -d delim Use DELIM to terminate lines, instead of newline -n count Copy at most COUNT lines -O origin Begin assigning to ARRAY at index ORIGIN -s count Discard the first COUNT lines read -t Remove a trailing DELIM from each line read (default newline) -u fd Read lines from file descriptor FD instead of standard input Exit Status: Returns success unless an invalid option is given or ARRAY is readonly.`]],["popd",["popd [-n] [+N | -N]",`Remove directories from stack. Removes entries from the directory stack. Exit Status: Returns success unless an invalid argument is supplied or the directory change fails.`]],["printf",["printf [-v var] format [arguments]",`Formats and prints ARGUMENTS under control of the FORMAT. Options: -v var assign the output to shell variable VAR rather than display it on the standard output FORMAT is a character string which contains three types of objects: plain characters, which are simply copied to standard output; character escape sequences, which are converted and copied to the standard output; and format specifications, each of which causes printing of the next successive argument. Exit Status: Returns success unless an invalid option is given or a write or assignment error occurs.`]],["pushd",["pushd [-n] [+N | -N | dir]",`Add directories to stack. Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the current working directory. Exit Status: Returns success unless an invalid argument is supplied or the directory change fails.`]],["pwd",["pwd [-LP]",`Print the name of the current working directory. Options: -L print the value of $PWD if it names the current working directory -P print the physical directory, without any symbolic links By default, \`pwd' behaves as if \`-L' were specified. Exit Status: Returns 0 unless an invalid option is given or the current directory cannot be read.`]],["read",["read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]",`Read a line from the standard input and split it into fields. Reads a single line from the standard input, or from file descriptor FD if the -u option is supplied. The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on, with any leftover words assigned to the last NAME. Exit Status: The return code is zero, unless end-of-file is encountered, read times out, or an invalid file descriptor is supplied as the argument to -u.`]],["readarray",["readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]","Read lines from a file into an array variable.\n A synonym for `mapfile'."]],["readonly",["readonly [-aAf] [name[=value] ...] or readonly -p",`Mark shell variables as unchangeable. Mark each NAME as read-only; the values of these NAMEs may not be changed by subsequent assignment. Exit Status: Returns success unless an invalid option is given or NAME is invalid.`]],["return",["return [n]",`Return from a shell function. Causes a function or sourced script to exit with the return value specified by N. If N is omitted, the return status is that of the last command executed within the function or script. Exit Status: Returns N, or failure if the shell is not executing a function or script.`]],["set",["set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]",`Set or unset values of shell options and positional parameters. Change the value of shell attributes and positional parameters, or display the names and values of shell variables. Options: -e Exit immediately if a command exits with a non-zero status. -u Treat unset variables as an error when substituting. -x Print commands and their arguments as they are executed. -o option-name Set the variable corresponding to option-name Exit Status: Returns success unless an invalid option is given.`]],["shift",["shift [n]",`Shift positional parameters. Rename the positional parameters $N+1,$N+2 ... to $1,$2 ... If N is not given, it is assumed to be 1. Exit Status: Returns success unless N is negative or greater than $#.`]],["shopt",["shopt [-pqsu] [-o] [optname ...]",`Set and unset shell options. Change the setting of each shell option OPTNAME. Without any option arguments, list each supplied OPTNAME, or all shell options if no OPTNAMEs are given, with an indication of whether or not each is set. Options: -o restrict OPTNAMEs to those defined for use with \`set -o' -p print each shell option with an indication of its status -q suppress output -s enable (set) each OPTNAME -u disable (unset) each OPTNAME Exit Status: Returns success if OPTNAME is enabled; fails if an invalid option is given or OPTNAME is disabled.`]],["source",["source filename [arguments]",`Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME. Exit Status: Returns the status of the last command executed in FILENAME.`]],["suspend",["suspend [-f]",`Suspend shell execution. Suspend the execution of this shell until it receives a SIGCONT signal.`]],["test",["test [expr]",`Evaluate conditional expression. Exits with a status of 0 (true) or 1 (false) depending on the evaluation of EXPR. Expressions may be unary or binary. Exit Status: Returns success if EXPR evaluates to true; fails if EXPR evaluates to false or an invalid argument is given.`]],["times",["times",`Display process times. Prints the accumulated user and system times for the shell and all of its child processes. Exit Status: Always succeeds.`]],["trap",["trap [-lp] [[arg] signal_spec ...]",`Trap signals and other events. Defines and activates handlers to be run when the shell receives signals or other conditions. Exit Status: Returns success unless a SIGSPEC is invalid or an invalid option is given.`]],["true",["true",`Return a successful result. Exit Status: Always succeeds.`]],["type",["type [-afptP] name [name ...]",`Display information about command type. For each NAME, indicate how it would be interpreted if used as a command name. Options: -a display all locations containing an executable named NAME -f suppress shell function lookup -P force a PATH search for each NAME, even if it is an alias, builtin, or function, and returns the name of the disk file that would be executed -p returns either the name of the disk file that would be executed, or nothing if \`type -t NAME' would not return \`file' -t output a single word which is one of \`alias', \`keyword', \`function', \`builtin', \`file' or \`', if NAME is an alias, shell reserved word, shell function, shell builtin, disk file, or not found, respectively Exit Status: Returns success if all of the NAMEs are found; fails if any are not found.`]],["typeset",["typeset [-aAfFgilnrtux] [-p] name[=value] ...","Set variable values and attributes.\n A synonym for `declare'."]],["ulimit",["ulimit [-SHabcdefiklmnpqrstuvxPT] [limit]",`Modify shell resource limits. Provides control over the resources available to the shell and processes it creates, on systems that allow such control. Exit Status: Returns success unless an invalid option is supplied or an error occurs.`]],["umask",["umask [-p] [-S] [mode]",`Display or set file mode mask. Sets the user file-creation mask to MODE. If MODE is omitted, prints the current value of the mask. Exit Status: Returns success unless MODE is invalid or an invalid option is given.`]],["unalias",["unalias [-a] name [name ...]",`Remove each NAME from the list of defined aliases. Exit Status: Returns success unless a NAME is not an existing alias.`]],["unset",["unset [-f] [-v] [-n] [name ...]",`Unset values and attributes of shell variables and functions. For each NAME, remove the corresponding variable or function. Options: -f treat each NAME as a shell function -v treat each NAME as a shell variable -n treat each NAME as a name reference and unset the variable itself rather than the variable it references Without options, unset first tries to unset a variable, and if that fails, tries to unset a function. Exit Status: Returns success unless an invalid option is given or a NAME is read-only.`]],["wait",["wait [-fn] [id ...]",`Wait for job completion and return exit status. Waits for each process identified by an ID, which may be a process ID or a job specification, and reports its termination status. Exit Status: Returns the status of the last ID; fails if ID is invalid or an invalid option is given.`]]]),$l=[...Al.keys()].sort();function li(e,t){let s=!1,r=[],n=0;for(;n1){for(let u=1;us.test(r))}function Kf(){let e=[];e.push("just-bash shell builtins"),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push("");let t=36,s=$l.slice(),r=Math.ceil(s.length/2);for(let n=0;n0&&a.pipelines[0].commands.length>0){let l=a.pipelines[0].commands[0];l.type==="ArithmeticCommand"&&(r=await T(e,l.expression.expression))}}catch(i){return N(`bash: let: ${n}: ${i.message} `)}return _("","",r===0?1:0)}async function ui(e,t){if(e.state.localScopes.length===0)return N(`bash: local: can only be used in a function `);let s=e.state.localScopes[e.state.localScopes.length-1],r="",n=0,i=!1,a=!1,l=!1,o=[];for(let u of t)if(u==="-n")i=!0;else if(u==="-a")a=!0;else if(u==="-p")l=!0;else if(u.startsWith("-")&&!u.includes("="))for(let c of u.slice(1))c==="n"?i=!0:c==="a"?a=!0:c==="p"&&(l=!0);else o.push(u);if(o.length===0){let u="",c=Array.from(s.keys()).filter(f=>!f.includes("_")||!f.match(/_\d+$/)).filter(f=>!f.includes("__length")).sort();for(let f of c){let d=e.state.env.get(f);d!==void 0&&(u+=`${f}=${d} `)}return _(u,"",0)}for(let u of o){let c,f,d=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(d){c=d[1];let b=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){r+=`bash: local: \`${u}': not a valid identifier `,n=1;continue}if(ye(e,c,"bash"),!s.has(c)){s.set(c,e.state.env.get(c));let w=`${c}_`;for(let S of e.state.env.keys())S.startsWith(w)&&!S.includes("__")&&(s.has(S)||s.set(S,e.state.env.get(S)))}let v=`${c}_`;for(let w of e.state.env.keys())w.startsWith(v)&&!w.includes("__")&&e.state.env.delete(w);let E=ot(b);for(let w=0;w0&&(w=Math.max(...E)+1);for(let $=0;$=w&&e.state.env.set(`${c}__length`,String(E+1)),Ct(e,c),i&&pt(e,c);continue}if(u.includes("=")){let b=u.indexOf("=");c=u.slice(0,b),f=de(e,u.slice(b+1))}else c=u;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){r+=`bash: local: \`${u}': not a valid identifier `,n=1;continue}let y=s.has(c);if(f!==void 0){let b=e.state.env.get(c);if(e.state.tempEnvBindings){let v=e.state.accessedTempEnvVars?.has(c),E=e.state.mutatedTempEnvVars?.has(c);if(!v&&!E)for(let w=e.state.tempEnvBindings.length-1;w>=0;w--){let S=e.state.tempEnvBindings[w];if(S.has(c)){b=S.get(c);break}}}ll(e,c,b)}if(!y){let b=e.state.env.get(c);if(e.state.tempEnvBindings)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let E=e.state.tempEnvBindings[v];if(E.has(c)){b=E.get(c);break}}if(s.set(c,b),a){let v=`${c}_`;for(let w of e.state.env.keys())w.startsWith(v)&&!w.includes("__")&&(s.has(w)||s.set(w,e.state.env.get(w)));let E=`${c}__length`;e.state.env.has(E)&&!s.has(E)&&s.set(E,e.state.env.get(E))}}if(a&&f===void 0){let b=`${c}_`;for(let v of e.state.env.keys())v.startsWith(b)&&!v.includes("__")&&e.state.env.delete(v);e.state.env.set(`${c}__length`,"0")}else if(f!==void 0){if(ye(e,c,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){r+=`bash: local: \`${f}': invalid variable name for name reference `,n=1;continue}e.state.env.set(c,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(c))}else{let b=e.state.tempEnvBindings?.some(v=>v.has(c));!y&&!b&&e.state.env.delete(c)}Ct(e,c),i&&pt(e,c)}return _("",r,n)}function fi(e,t,s){let r=` `,n=0,i=0,a=0,l=!1,o="MAPFILE",u=0;for(;u0;){let v=d.indexOf(r);if(v===-1){if(d.length>0){if(m=p)return _("",`mapfile: array element limit exceeded (${p}) `,1);let S=d,A=S.indexOf("\0");A!==-1&&(S=S.substring(0,A)),f.push(S),h++}}break}let E=d.substring(0,v),w=E.indexOf("\0");if(w!==-1&&(E=E.substring(0,w)),!l&&r!=="\0"&&(E+=r),d=d.substring(v+r.length),m0&&h>=n)break;if(i+h>=p)return _("",`mapfile: array element limit exceeded (${p}) `,1);f.push(E),h++}i===0&&tt(e,o);for(let v=0;v{let D=1;for(;D1&&k!=="--"){let x=p(k,h);if(x.nextArgIndex===-1)return{stdout:"",stderr:"",exitCode:2};if(x.nextArgIndex===-2)return{stdout:"",stderr:"",exitCode:1};h=x.nextArgIndex}else if(k==="--")for(h++;h=0?e.state.fileDescriptors?y=e.state.fileDescriptors.get(c)||"":y="":!y&&e.state.groupStdin!==void 0&&(y=e.state.groupStdin);let b=i===""?"\0":i,v="",E=0,w=!0,S=k=>{if(c>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(c,y.substring(k));else if(r>=0&&e.state.fileDescriptors){let x=e.state.fileDescriptors.get(r);if(x?.startsWith("__rw__:")){let D=Yf(x);if(D){let P=D.position+k;e.state.fileDescriptors.set(r,Jf(D.path,P,D.content))}}}else e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=y.substring(k))};if(o>=0){let k=Math.min(o,y.length);v=y.substring(0,k),E=k,w=k>=o,S(E);let x=d[0]||"REPLY";e.state.env.set(x,v);for(let D=1;D=0){let k=0,x=0,D=!1;for(;x=l||D,S(E)}else{E=0;let k=0;for(;k=y.length&&(w=!1,E=k,v.length===0&&y.length===0)){for(let x of d)e.state.env.set(x,"");return u&&tt(e,u),_("","",1)}S(E)}b===` `&&v.endsWith(` `)&&(v=v.slice(0,-1));let A=k=>n?k:k.replace(/\\(.)/g,"$1");if(d.length===1&&d[0]==="REPLY")return e.state.env.set("REPLY",A(v)),_("","",w?0:1);let $=me(e.state.env);if(u){let{words:k}=Sr(v,$,void 0,n),x=e.limits?.maxArrayElements??1e5;if(k.length>x)return _("",`read: array element limit exceeded (${x}) `,1);tt(e,u);for(let D=0;D0){let r=t[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return N(`bash: return: ${r}: numeric argument required `,2);s=(n%256+256)%256}throw new ke(s)}var bs=`set: usage: set [-eux] [+eux] [-o option] [+o option] Options: -e Exit immediately if a command exits with non-zero status +e Disable -e -u Treat unset variables as an error when substituting +u Disable -u -x Print commands and their arguments as they are executed +x Disable -x -o errexit Same as -e +o errexit Disable errexit -o nounset Same as -u +o nounset Disable nounset -o pipefail Return status of last failing command in pipeline +o pipefail Disable pipefail -o xtrace Same as -x +o xtrace Disable xtrace `,Pl=new Map([["e","errexit"],["u","nounset"],["x","xtrace"],["v","verbose"],["f","noglob"],["C","noclobber"],["a","allexport"],["n","noexec"],["h",null],["b",null],["m",null],["B",null],["H",null],["P",null],["T",null],["E",null],["p",null]]),$n=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["noclobber","noclobber"],["noglob","noglob"],["allexport","allexport"],["noexec","noexec"],["posix","posix"],["vi","vi"],["emacs","emacs"],["notify",null],["monitor",null],["braceexpand",null],["histexpand",null],["physical",null],["functrace",null],["errtrace",null],["privileged",null],["hashall",null],["ignoreeof",null],["interactive-comments",null],["keyword",null],["onecmd",null]]),_l=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],xl=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function pi(e,t,s){t!==null&&(s&&(t==="vi"?e.state.options.emacs=!1:t==="emacs"&&(e.state.options.vi=!1)),e.state.options[t]=s,jt(e))}function ed(e,t){return t+1{let i=e.state.env.get(`${t}_${n}`)??"";return`[${n}]=${Lt(i)}`});return`${t}=(${r.join(" ")})`}function sd(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function nd(e,t){let s=Ge(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=e.state.env.get(`${t}_${n}`)??"";return`[${sd(n)}]=${Lt(i)}`});return`${t}=(${r.join(" ")} )`}function rd(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let n=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(n){let i=n[1];s.has(i)||t.add(i)}}return t}function id(e){return e.state.associativeArrays??new Set}function kl(e){let t=_l.map(r=>`${r.padEnd(16)}${e.state.options[r]?"on":"off"}`),s=xl.map(r=>`${r.padEnd(16)}off`);return`${[...t,...s].sort().join(` `)} `}function Nl(e){let t=_l.map(r=>`set ${e.state.options[r]?"-o":"+o"} ${r}`),s=xl.map(r=>`set +o ${r}`);return`${[...t,...s].sort().join(` `)} `}function gi(e,t){if(t.includes("--help"))return H(bs);if(t.length===0){let i=rd(e),a=id(e),l=c=>{for(let f of a){let d=`${f}_`,h=`${f}__length`;if(c!==h&&c.startsWith(d)){if(c.slice(d.length).startsWith("_length"))continue;return!0}}return!1},o=[];for(let[c,f]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)||i.has(c)||a.has(c))continue;let d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(d&&i.has(d[1]))continue;let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);h&&i.has(h[1])||l(c)||h&&a.has(h[1])||o.push([c,f])}let u=[];for(let[c,f]of o.sort(([d],[h])=>dh?1:0))u.push(`${c}=${vn(f)}`);for(let c of[...i].sort((f,d)=>fd?1:0))u.push(td(e,c));for(let c of[...a].sort((f,d)=>fd?1:0))u.push(nd(e,c));return u.sort((c,f)=>{let d=c.split("=")[0],h=f.split("=")[0];return dh?1:0}),H(u.length>0?`${u.join(` `)} `:"")}let s=[],r=()=>s.length>0?H(s.join("")):K,n=0;for(;n1&&(i[0]==="-"||i[0]==="+")&&i[1]!=="-"){let a=i[0]==="-",l=0;for(let o=1;o0){let a=Number.parseInt(t[0],10);if(Number.isNaN(a)||a<0){let l=`bash: shift: ${t[0]}: numeric argument required `;if(e.state.options.posix)throw new Be(1,"",l);return N(l)}s=a}let r=Number.parseInt(e.state.env.get("#")||"0",10);if(s>r){let a=`bash: shift: shift count out of range `;if(e.state.options.posix)throw new Be(1,"",a);return N(a)}if(s===0)return K;let n=[];for(let a=1;a<=r;a++)n.push(e.state.env.get(String(a))||"");let i=n.slice(s);for(let a=1;a<=r;a++)e.state.env.delete(String(a));for(let a=0;a0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return _("",`bash: source: filename argument required `,2);let r=s[0],n=null,i=null;if(r.includes("/")){let u=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(u),n=u}catch{}}else{let c=(e.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of c){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFile(d),n=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(f),n=f}catch{}}}if(i===null)return N(`bash: ${r}: No such file or directory `);let a=new Map;if(s.length>1){for(let c=1;c<=9;c++)a.set(String(c),e.state.env.get(String(c)));a.set("#",e.state.env.get("#")),a.set("@",e.state.env.get("@"));let u=s.slice(1);e.state.env.set("#",String(u.length)),e.state.env.set("@",u.join(" "));for(let c=0;c{if(e.state.sourceDepth--,e.state.currentSource=l,s.length>1)for(let[u,c]of a)c===void 0?e.state.env.delete(u):e.state.env.set(u,c)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new X(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,"recursion");e.state.currentSource=r;try{let u=Ce(i),c=await e.executeScript(u);return o(),c}catch(u){if(o(),u instanceof Z)throw u;if(u instanceof ke)return _(u.stdout,u.stderr,u.exitCode);if(u.name==="ParseException")return N(`bash: ${r}: ${u.message} `);throw u}}function Cl(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function ad(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function Dl(e,t){if(ad(t))return null;try{let s=new q,r=Y(s,t);return await T(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function Rl(e,t){if(e.state.localVarStack?.has(t)){let r=yn(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let n=e.state.localVarStack?.get(t);if(!n||n.length===0)gn(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),Ei(e,t);else{let i=n[n.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,i.scopeIndex+1)}return!0}return e.state.env.delete(t),gn(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let n=e.state.localScopes[r];if(n.has(t)){let i=n.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),n.delete(t);let a=!1;for(let l=r-1;l>=0;l--)if(e.state.localScopes[l].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,l+1),a=!0;break}return a||gn(e,t),!0}}return!1}function Ei(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let r=e.state.tempEnvBindings[s];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function Il(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),n=new q().parseWordFromString(s,!0,!1);return V(e,n)}if(t.includes("$")){let r=new q().parseWordFromString(t,!1,!1);return V(e,r)}return t}async function bi(e,t){let s="both",r="",n=0;for(let i of t){if(i==="-v"){s="variable";continue}if(i==="-f"){s="function";continue}if(s==="function"){e.state.functions.delete(i);continue}if(s==="variable"){let u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let d=u[1],h=u[2];if(h==="@"||h==="*"){let E=B(e,d);for(let[w]of E)e.state.env.delete(`${d}_${w}`);e.state.env.delete(d);continue}let m=e.state.associativeArrays?.has(d);if(m){let E=await Il(e,h);e.state.env.delete(`${d}_${E}`);continue}let p=He(e,d),y=e.state.declaredVars?.has(d);if((e.state.env.has(d)||y)&&!p&&!m){r+=`bash: unset: ${d}: not an array variable `,n=1;continue}let v=await Dl(e,h);if(v===null&&p){r+=`bash: unset: ${h}: not a valid identifier `,n=1;continue}if(v===null)continue;if(v<0){let E=B(e,d),w=E.length,S=e.state.currentLine;if(w===0){r+=`bash: line ${S}: unset: [${v}]: bad array subscript `,n=1;continue}let A=w+v;if(A<0){r+=`bash: line ${S}: unset: [${v}]: bad array subscript `,n=1;continue}let $=E[A][0];e.state.env.delete(`${d}_${$}`);continue}e.state.env.delete(`${d}_${v}`);continue}if(!Cl(i)){r+=`bash: unset: \`${i}': not a valid identifier `,n=1;continue}let c=i;if(te(e,i)){let d=$e(e,i);d&&d!==i&&(c=d)}if(rt(e,c)){r+=`bash: unset: ${c}: cannot unset: readonly variable `,n=1;continue}let f=Qt(e,c);if(f!==void 0&&f!==e.state.callDepth)Rl(e,c);else if(e.state.fullyUnsetLocals?.has(c))e.state.env.delete(c);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(c),h=e.state.mutatedTempEnvVars?.has(c);if((d||h)&&e.state.localVarStack?.has(c)){let m=yn(e,c);m?m.value===void 0?e.state.env.delete(c):e.state.env.set(c,m.value):e.state.env.delete(c)}else e.state.env.delete(c)}else Ei(e,c)||e.state.env.delete(c);e.state.exportedVars?.delete(c);continue}let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let u=a[1],c=a[2];if(c==="@"||c==="*"){let p=B(e,u);for(let[y]of p)e.state.env.delete(`${u}_${y}`);e.state.env.delete(u);continue}let f=e.state.associativeArrays?.has(u);if(f){let p=await Il(e,c);e.state.env.delete(`${u}_${p}`);continue}let d=He(e,u);if(e.state.env.has(u)&&!d&&!f){r+=`bash: unset: ${u}: not an array variable `,n=1;continue}let m=await Dl(e,c);if(m===null&&d){r+=`bash: unset: ${c}: not a valid identifier `,n=1;continue}if(m===null)continue;if(m<0){let p=B(e,u),y=p.length,b=e.state.currentLine;if(y===0){r+=`bash: line ${b}: unset: [${m}]: bad array subscript `,n=1;continue}let v=y+m;if(v<0){r+=`bash: line ${b}: unset: [${m}]: bad array subscript `,n=1;continue}let E=p[v][0];e.state.env.delete(`${u}_${E}`);continue}e.state.env.delete(`${u}_${m}`);continue}if(!Cl(i)){r+=`bash: unset: \`${i}': not a valid identifier `,n=1;continue}let l=i;if(te(e,i)){let u=$e(e,i);u&&u!==i&&(l=u)}if(rt(e,l)){r+=`bash: unset: ${l}: cannot unset: readonly variable `,n=1;continue}let o=Qt(e,l);if(o!==void 0&&o!==e.state.callDepth)Rl(e,l);else if(e.state.fullyUnsetLocals?.has(l))e.state.env.delete(l);else if(o!==void 0){let u=e.state.accessedTempEnvVars?.has(l),c=e.state.mutatedTempEnvVars?.has(l);if((u||c)&&e.state.localVarStack?.has(l)){let f=yn(e,l);f?f.value===void 0?e.state.env.delete(l):e.state.env.set(l,f.value):e.state.env.delete(l)}else e.state.env.delete(l)}else Ei(e,l)||e.state.env.delete(l);e.state.exportedVars?.delete(l),e.state.functions.delete(i)}return _("",r,n)}var vi=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],od=["autocd","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","execfail","extdebug","extquote","force_fignore","globasciiranges","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath"];function Pn(e){return vi.includes(e)}function ld(e){return od.includes(e)}function Ol(e,t){let s=!1,r=!1,n=!1,i=!1,a=!1,l=[],o=0;for(;o1){for(let h=1;h0?`${h.join(` `)} `:"",stderr:""}}let d=[];for(let h of vi){let m=e.state.shoptOptions[h];d.push(n?`shopt ${m?"-s":"-u"} ${h}`:`${h} ${m?"on":"off"}`)}return{exitCode:0,stdout:`${d.join(` `)} `,stderr:""}}let u=!1,c="",f=[];for(let d of l){if(!Pn(d)&&!ld(d)){c+=`shopt: ${d}: invalid shell option name `,u=!0;continue}if(s)Pn(d)&&(e.state.shoptOptions[d]=!0,Gn(e));else if(r)Pn(d)&&(e.state.shoptOptions[d]=!1,Gn(e));else if(Pn(d)){let h=e.state.shoptOptions[d];i?h||(u=!0):n?(f.push(`shopt ${h?"-s":"-u"} ${d}`),h||(u=!0)):(f.push(`${d} ${h?"on":"off"}`),h||(u=!0))}else i?u=!0:n?(f.push(`shopt -u ${d}`),u=!0):(f.push(`${d} off`),u=!0)}return{exitCode:u?1:0,stdout:f.length>0?`${f.join(` `)} `:"",stderr:c}}function cd(e,t,s,r,n,i){let a=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),l=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],o=[...a.keys(),...l].sort();if(t.length===0){let d=[];for(let h of o){let m=l.includes(h),p=a.get(h),y=m||!p?!1:e.state.options[p];s&&!y||r&&y||d.push(n?`set ${y?"-o":"+o"} ${h}`:`${h} ${y?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?`${d.join(` `)} `:"",stderr:""}}let u=!1,c="",f=[];for(let d of t){let h=a.has(d),m=l.includes(d);if(!h&&!m){c+=`shopt: ${d}: invalid option name `,u=!0;continue}if(m){s||r||(i?u=!0:n?(f.push(`set +o ${d}`),u=!0):(f.push(`${d} off`),u=!0));continue}let p=a.get(d);if(p)if(s)p==="vi"?e.state.options.emacs=!1:p==="emacs"&&(e.state.options.vi=!1),e.state.options[p]=!0,jt(e);else if(r)e.state.options[p]=!1,jt(e);else{let y=e.state.options[p];i?y||(u=!0):n?(f.push(`set ${y?"-o":"+o"} ${d}`),y||(u=!0)):(f.push(`${d} ${y?"on":"off"}`),y||(u=!0))}}return{exitCode:u?1:0,stdout:f.length>0?`${f.join(` `)} `:"",stderr:c}}async function Tl(e,t,s){if(t.includes("/")){let a=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(a))return{error:"not_found",path:a};let l=a.split("/").pop()||t,o=e.commands.get(l);try{let u=await e.fs.stat(a);return u.isDirectory?{error:"permission_denied",path:a}:o?{cmd:o,path:a}:(u.mode&73)!==0?{script:!0,path:a}:{error:"permission_denied",path:a}}catch{return{error:"not_found",path:a}}}if(!s&&e.state.hashTable){let a=e.state.hashTable.get(t);if(a)if(await e.fs.exists(a)){let l=e.commands.get(t);if(l)return{cmd:l,path:a};try{let o=await e.fs.stat(a);if(!o.isDirectory&&(o.mode&73)!==0)return{script:!0,path:a}}catch{}}else e.state.hashTable.delete(t)}let n=(s??e.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let a of n){if(!a)continue;let o=`${a.startsWith("/")?a:e.fs.resolvePath(e.state.cwd,a)}/${t}`;if(await e.fs.exists(o))try{let u=await e.fs.stat(o);if(u.isDirectory)continue;let c=(u.mode&73)!==0,f=e.commands.get(t),d=a==="/bin"||a==="/usr/bin";if(f&&d)return{cmd:f,path:o};if(c){if(f&&!d)return{script:!0,path:o};if(!f)return{script:!0,path:o}}}catch{}}if(!await e.fs.exists("/usr/bin")){let a=e.commands.get(t);if(a)return{cmd:a,path:`/usr/bin/${t}`}}return null}async function kn(e,t){let s=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let a=await e.fs.stat(i);a.isDirectory||(a.mode&73)!==0&&s.push(t)}catch{}return s}let n=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let i of n){if(!i)continue;let l=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(l)){try{if((await e.fs.stat(l)).isDirectory)continue}catch{continue}s.push(i.startsWith("/")?l:`${i}/${t}`)}}return s}function ud(e){return e!==null&&typeof e=="object"&&"then"in e&&typeof e.then=="function"}function oe(e,t,s,r){return((...n)=>{ls(t,s,`${r} call`);let i=e(...n);return ud(i)?i.then(a=>(ls(t,s,`${r} post-await`),a),a=>{throw ls(t,s,`${r} post-await`),a}):(ls(t,s,`${r} return`),i)})}function fd(e,t,s){let r={readFile:oe(e.readFile.bind(e),t,s,"fs.readFile"),...typeof e.readFileBytes=="function"?{readFileBytes:oe(e.readFileBytes.bind(e),t,s,"fs.readFileBytes")}:Object.create(null),readFileBuffer:oe(e.readFileBuffer.bind(e),t,s,"fs.readFileBuffer"),writeFile:oe(e.writeFile.bind(e),t,s,"fs.writeFile"),appendFile:oe(e.appendFile.bind(e),t,s,"fs.appendFile"),exists:oe(e.exists.bind(e),t,s,"fs.exists"),stat:oe(e.stat.bind(e),t,s,"fs.stat"),mkdir:oe(e.mkdir.bind(e),t,s,"fs.mkdir"),readdir:oe(e.readdir.bind(e),t,s,"fs.readdir"),rm:oe(e.rm.bind(e),t,s,"fs.rm"),cp:oe(e.cp.bind(e),t,s,"fs.cp"),mv:oe(e.mv.bind(e),t,s,"fs.mv"),resolvePath:oe(e.resolvePath.bind(e),t,s,"fs.resolvePath"),getAllPaths:oe(e.getAllPaths.bind(e),t,s,"fs.getAllPaths"),chmod:oe(e.chmod.bind(e),t,s,"fs.chmod"),symlink:oe(e.symlink.bind(e),t,s,"fs.symlink"),link:oe(e.link.bind(e),t,s,"fs.link"),readlink:oe(e.readlink.bind(e),t,s,"fs.readlink"),lstat:oe(e.lstat.bind(e),t,s,"fs.lstat"),realpath:oe(e.realpath.bind(e),t,s,"fs.realpath"),utimes:oe(e.utimes.bind(e),t,s,"fs.utimes")};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=oe(e.readdirWithFileTypes.bind(e),t,s,"fs.readdirWithFileTypes")),r}function Ll(e,t){if(!e.requireDefenseContext)return e;let s=`command:${t}`,r={...e,fs:fd(e.fs,e.requireDefenseContext,s)};return e.exec&&(r.exec=oe(e.exec,e.requireDefenseContext,s,"exec")),e.fetch&&(r.fetch=oe(e.fetch,e.requireDefenseContext,s,"fetch")),e.sleep&&(r.sleep=oe(e.sleep,e.requireDefenseContext,s,"sleep")),e.getRegisteredCommands&&(r.getRegisteredCommands=oe(e.getRegisteredCommands,e.requireDefenseContext,s,"getRegisteredCommands")),r}async function Vl(e,t,s,r){let n=!1,i=!1,a=!1,l=!1,o=!1,u=[];for(let p of t)if(p.startsWith("-")&&p.length>1)for(let y of p.slice(1))y==="t"?n=!0:y==="p"?i=!0:y==="P"?a=!0:y==="a"?l=!0:y==="f"&&(o=!0);else u.push(p);let c="",f="",d=0,h=!1,m=!1;for(let p of u){let y=!1;if(a){if(l){let A=await r(p);if(A.length>0){for(let $ of A)c+=`${$} `;h=!0,y=!0}}else{let A=await s(p);A&&(c+=`${A} `,h=!0,y=!0)}y||(m=!0);continue}let b=!o&&e.state.functions.has(p);if(l&&b){if(!i)if(n)c+=`function `;else{let A=e.state.functions.get(p),$=A?Ml(p,A):`${p} is a function `;c+=$}y=!0}let v=e.state.env.get(`BASH_ALIAS_${p}`);if(v!==void 0&&(l||!y)&&(i||(n?c+=`alias `:c+=`${p} is aliased to \`${v}' `),y=!0,!l)||Wr.has(p)&&(l||!y)&&(i||(n?c+=`keyword `:c+=`${p} is a shell keyword `),y=!0,!l))continue;if(!l&&b&&!y){if(!i)if(n)c+=`function `;else{let A=e.state.functions.get(p),$=A?Ml(p,A):`${p} is a function `;c+=$}y=!0;continue}if(!(Kt.has(p)&&(l||!y)&&(i||(n?c+=`builtin `:c+=`${p} is a shell builtin `),y=!0,!l))){if(l){let A=await r(p);for(let $ of A)i?c+=`${$} `:n?c+=`file `:c+=`${p} is ${$} `,h=!0,y=!0}else if(!y){let A=await s(p);A&&(i?c+=`${A} `:n?c+=`file `:c+=`${p} is ${A} `,h=!0,y=!0)}if(!y&&(m=!0,!n&&!i)){let A=!0;if(p.includes("/")){let $=e.fs.resolvePath(e.state.cwd,p);await e.fs.exists($)&&(A=!1)}A&&(f+=`bash: type: ${p}: not found `)}}}return i?d=m&&!h?1:0:d=m?1:0,_(c,f,d)}function Ml(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(n=>vs(n)).join("; "):s=vs(t.body),`${e} is a function ${e} () { ${s} } `}function vs(e){if(Array.isArray(e))return e.map(t=>vs(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;svs(r)).join("; ")}; }`:"..."}function dd(e){let t=e.commands.map(s=>vs(s));return(e.negated?"! ":"")+t.join(" | ")}function Wl(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(r=>Fl(r)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=Fl(s);return t}function Fl(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function zl(e,t,s,r){let n="",i="",a=0;for(let l of t){if(!l){a=1;continue}let o=e.state.env.get(`BASH_ALIAS_${l}`);if(o!==void 0)r?n+=`${l} is an alias for "${o}" `:n+=`alias ${l}='${o}' `;else if(Wr.has(l))r?n+=`${l} is a shell keyword `:n+=`${l} `;else if(Kt.has(l))r?n+=`${l} is a shell builtin `:n+=`${l} `;else if(e.state.functions.has(l))r?n+=`${l} is a function `:n+=`${l} `;else if(l.includes("/")){let u=e.fs.resolvePath(e.state.cwd,l),c=!1;if(await e.fs.exists(u))try{let f=await e.fs.stat(u);f.isDirectory||(f.mode&73)!==0&&(r?n+=`${l} is ${l} `:n+=`${l} `,c=!0)}catch{}c||(r&&(i+=`${l}: not found `),a=1)}else if(e.commands.has(l)){let c=(e.state.env.get("PATH")??"/usr/bin:/bin").split(":"),f=null;for(let d of c){if(!d)continue;let h=`${d}/${l}`;try{let m=await e.fs.stat(h);if(!m.isDirectory&&(m.mode&73)!==0){f=h;break}}catch{}}f||(f=`/usr/bin/${l}`),r?n+=`${l} is ${f} `:n+=`${f} `}else r&&(i+=`${l}: not found `),a=1}return _(n,i,a)}async function Bl(e,t){if(t.includes("/")){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let i=await e.fs.stat(n);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=(e.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let n of r){if(!n)continue;let a=`${n.startsWith("/")?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}return`${n}/${t}`}}if(e.commands.has(t)){for(let n of r)if(n==="/usr/bin"||n==="/bin")return`${n}/${t}`;return`/usr/bin/${t}`}return null}async function ql(e,t,s,r,n,i,a,l){let{ctx:o,runCommand:u}=e;if(o.coverage&&Kt.has(t)&&o.coverage.hit(`bash:builtin:${t}`),t==="export")return ai(o,s);if(t==="unset")return bi(o,s);if(t==="exit")return ii(o,s);if(t==="local")return ui(o,s);if(t==="set")return gi(o,s);if(t==="break")return Rr(o,s);if(t==="continue")return Ur(o,s);if(t==="return")return hi(o,s);if(t==="eval"&&o.state.options.posix)return Sn(o,s,n);if(t==="shift")return yi(o,s);if(t==="getopts")return An(o,s);if(t==="compgen")return zr(o,s);if(t==="complete")return qr(o,s);if(t==="compopt")return jr(o,s);if(t==="pushd")return await si(o,s);if(t==="popd")return ni(o,s);if(t==="dirs")return ri(o,s);if(t==="source"||t===".")return wi(o,s);if(t==="read")return di(o,s,n,l);if(t==="mapfile"||t==="readarray")return fi(o,s,n);if(t==="declare"||t==="typeset")return Jr(o,s);if(t==="readonly")return ei(o,s);if(!i){let c=o.state.functions.get(t);if(c)return bn(o,c,s,n)}if(t==="eval")return Sn(o,s,n);if(t==="cd")return await Ir(o,s);if(t===":"||t==="true")return K;if(t==="false")return pe(!1);if(t==="let")return ci(o,s);if(t==="command")return hd(e,s,n);if(t==="builtin")return pd(e,s,n);if(t==="shopt")return Ol(o,s);if(t==="exec"){if(s.length===0)return K;let[c,...f]=s;return u(c,f,[],n,!1,!1,-1)}if(t==="wait")return K;if(t==="type")return await Vl(o,s,c=>Bl(o,c),c=>kn(o,c));if(t==="hash")return oi(o,s);if(t==="help")return li(o,s);if(t==="["||t==="test"){let c=s;if(t==="["){if(s[s.length-1]!=="]")return N("[: missing `]'\n",2);c=s.slice(0,-1)}return ys(o,c)}return null}async function hd(e,t,s){let{ctx:r,runCommand:n}=e;if(t.length===0)return K;let i=!1,a=!1,l=!1,o=t;for(;o.length>0&&o[0].startsWith("-");){let f=o[0];if(f==="--"){o=o.slice(1);break}for(let d of f.slice(1))d==="p"?i=!0:d==="V"?a=!0:d==="v"&&(l=!0);o=o.slice(1)}if(o.length===0)return K;if(l||a)return await zl(r,o,l,a);let[u,...c]=o;return n(u,c,[],s,!0,i,-1)}async function pd(e,t,s){let{runCommand:r}=e;if(t.length===0)return K;let n=t;if(n[0]==="--"&&(n=n.slice(1),n.length===0))return K;let i=n[0];if(!Kt.has(i))return N(`bash: builtin: ${i}: not a shell builtin `);let[,...a]=n;return r(i,a,[],s,!0,!1,-1)}async function jl(e,t,s,r,n){let{ctx:i,buildExportedEnv:a,executeUserScript:l}=e,u=await Tl(i,t,n?"/usr/bin:/bin":void 0);if(!u)return Xo(t)?N(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle. `,127):N(`bash: ${t}: command not found `,127);if("error"in u)return u.error==="permission_denied"?N(`bash: ${t}: Permission denied `,126):N(`bash: ${t}: No such file or directory `,127);if("script"in u)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,u.path)),await l(u.path,s,r);let{cmd:c,path:f}=u;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||"",h=a(),m={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:h,stdin:d,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,invokeTool:i.invokeTool},p=Ll(m,t);try{let y=()=>Di(i.requireDefenseContext,"command",`${t} execution`,()=>c.execute(s,p));return c.trusted?await Ie.runTrustedAsync(()=>y()):await y()}catch(y){if(y instanceof X||y instanceof gt)throw y;return N(`${t}: ${ut(ct(y))} `)}}async function Si(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let r="",n="",i=0;try{for(let a of t){let l=await e.executeStatement(a);r+=l.stdout,n+=l.stderr,i=l.exitCode}}finally{e.state.inCondition=s}return{stdout:r,stderr:n,exitCode:i}}function Ss(e,t,s,r){if(e instanceof Oe)return t+=e.stdout,s+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:"rethrow",stdout:t,stderr:s,error:e}):{action:"break",stdout:t,stderr:s};if(e instanceof Te)return t+=e.stdout,s+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:"rethrow",stdout:t,stderr:s,error:e}):{action:"continue",stdout:t,stderr:s};if(e instanceof ke||e instanceof ze||e instanceof Z||e instanceof X)return e.prependOutput(t,s),{action:"rethrow",stdout:t,stderr:s,error:e};let n=ct(e);return{action:"error",stdout:t,stderr:`${s}${n} `,exitCode:1}}async function Nn(e,t,s="",r=""){let n=s,i=r,a=0;try{for(let l of t){let o=await e.executeStatement(l);n+=o.stdout,i+=o.stderr,a=o.exitCode}}catch(l){if(Is(l)||l instanceof ze||l instanceof Z||l instanceof X||l instanceof Et)throw l.prependOutput(n,i),l;return{stdout:n,stderr:`${i}${ct(l)} `,exitCode:1}}return{stdout:n,stderr:i,exitCode:a}}async function Ul(e,t){let s="",r="";for(let n of t.clauses){let i=await Si(e,n.condition);if(s+=i.stdout,r+=i.stderr,i.exitCode===0)return Nn(e,n.body,s,r)}return t.elseBody?Nn(e,t.elseBody,s,r):_(s,r,0)}async function Zl(e,t){let s=await lt(e,t.redirections);if(s)return s;let r="",n="",i=0,a=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return N(`bash: \`${t.variable}': not a valid identifier `);let l=[];if(t.words===null)l=(e.state.env.get("@")||"").split(" ").filter(Boolean);else if(t.words.length===0)l=[];else try{for(let u of t.words){let c=await it(e,u);l.push(...c.values)}}catch(u){if(u instanceof wt)return{stdout:"",stderr:u.stderr,exitCode:1};throw u}e.state.loopDepth++;try{for(let u of l){a++,a>e.limits.maxLoopIterations&&at(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),e.state.env.set(t.variable,u);try{for(let c of t.body){let f=await e.executeStatement(c);r+=f.stdout,n+=f.stderr,i=f.exitCode}}catch(c){let f=Ss(c,r,n,e.state.loopDepth);if(r=f.stdout,n=f.stderr,f.action==="break")break;if(f.action==="continue")continue;if(f.action==="error"){let d=_(r,n,f.exitCode??1);return ue(e,d,t.redirections)}throw f.error}}}finally{e.state.loopDepth--}let o=_(r,n,i);return ue(e,o,t.redirections)}async function Gl(e,t){let s=await lt(e,t.redirections);if(s)return s;let r=t.line;r!==void 0&&(e.state.currentLine=r);let n="",i="",a=0,l=0;t.init&&await T(e,t.init.expression),e.state.loopDepth++;try{for(;l++,l>e.limits.maxLoopIterations&&at(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,i),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await T(e,t.condition.expression)===0));){try{for(let u of t.body){let c=await e.executeStatement(u);n+=c.stdout,i+=c.stderr,a=c.exitCode}}catch(u){let c=Ss(u,n,i,e.state.loopDepth);if(n=c.stdout,i=c.stderr,c.action==="break")break;if(c.action==="continue"){t.update&&await T(e,t.update.expression);continue}if(c.action==="error"){let f=_(n,i,c.exitCode??1);return ue(e,f,t.redirections)}throw c.error}t.update&&await T(e,t.update.expression)}}finally{e.state.loopDepth--}let o=_(n,i,a);return ue(e,o,t.redirections)}async function Hl(e,t,s=""){let r="",n="",i=0,a=0,l=s;for(let u of t.redirections)if((u.operator==="<<"||u.operator==="<<-")&&u.target.type==="HereDoc"){let c=u.target,f=await V(e,c.content);c.stripTabs&&(f=f.split(` `).map(d=>d.replace(/^\t+/,"")).join(` `)),l=f}else if(u.operator==="<<<"&&u.target.type==="Word")l=`${await V(e,u.target)} `;else if(u.operator==="<"&&u.target.type==="Word")try{let c=await V(e,u.target),f=e.fs.resolvePath(e.state.cwd,c);l=await e.fs.readFile(f)}catch{let c=await V(e,u.target);return N(`bash: ${c}: No such file or directory `)}let o=e.state.groupStdin;l&&(e.state.groupStdin=l),e.state.loopDepth++;try{for(;;){a++,a>e.limits.maxLoopIterations&&at(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let u=0,c=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let h of t.condition){let m=await e.executeStatement(h);r+=m.stdout,n+=m.stderr,u=m.exitCode}}catch(h){if(h instanceof Oe){if(r+=h.stdout,n+=h.stderr,h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;c=!0}else if(h instanceof Te){if(r+=h.stdout,n+=h.stderr,h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=r,h.stderr=n,e.state.inCondition=d,h;f=!0}else throw e.state.inCondition=d,h}finally{e.state.inCondition=d}if(c)break;if(!f){if(u!==0)break;try{for(let h of t.body){let m=await e.executeStatement(h);r+=m.stdout,n+=m.stderr,i=m.exitCode}}catch(h){let m=Ss(h,r,n,e.state.loopDepth);if(r=m.stdout,n=m.stderr,m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return _(r,n,m.exitCode??1);throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=o}return _(r,n,i)}async function Ql(e,t){let s="",r="",n=0,i=0;e.state.loopDepth++;try{for(;;){i++,i>e.limits.maxLoopIterations&&at(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r);let a=await Si(e,t.condition);if(s+=a.stdout,r+=a.stderr,a.exitCode===0)break;try{for(let l of t.body){let o=await e.executeStatement(l);s+=o.stdout,r+=o.stderr,n=o.exitCode}}catch(l){let o=Ss(l,s,r,e.state.loopDepth);if(s=o.stdout,r=o.stderr,o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return _(s,r,o.exitCode??1);throw o.error}}}finally{e.state.loopDepth--}return _(s,r,n)}async function Kl(e,t){let s=await lt(e,t.redirections);if(s)return s;let r="",n="",i=0,a=await V(e,t.word),l=!1;for(let u=0;ugd(t)).join(" ")}function gd(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),r=e.includes(` `),n=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(s||r||n||i){let o="";for(let u of e){let c=u.charCodeAt(0);u===` `?o+="\\n":u===" "?o+="\\t":u==="\\"?o+="\\\\":u==="'"?o+="'":u==='"'?o+='"':c<32||c===127?c<256?o+=`\\x${c.toString(16).padStart(2,"0")}`:o+=`\\u${c.toString(16).padStart(4,"0")}`:o+=u}return`$'${o}'`}return a?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function ec(e,t,s){if(!e.state.options.xtrace)return"";let r=await Jl(e),n=[t,...s],i=md(n);return`${r}${i} `}async function tc(e,t,s){return e.state.options.xtrace?`${await Jl(e)}${t}=${s} `:""}async function sc(e,t,s){let r=t.timed?Bn():0,n="",i=K,a=0,l=[],o="",u=t.commands.length>1,c=e.state.lastArg;for(let d=0;d1)v={stdout:E.stdout,stderr:E.stderr,exitCode:E.exitCode};else if(E instanceof ze&&t.commands.length>1)v={stdout:E.stdout,stderr:E.stderr,exitCode:E.exitCode};else throw b&&(e.state.env=b),E}b&&(e.state.env=b),l.push(v.exitCode),v.exitCode!==0&&(a=v.exitCode),m?i=v:(t.pipeStderr?.[d]??!1?n=yt(v.stderr)+Cs(v):(n=Cs(v),o+=v.stderr),i={stdout:"",stderr:"",exitCode:v.exitCode})}if(o&&(i={...i,stderr:o+i.stderr}),t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand"){for(let d of e.state.env.keys())d.startsWith("PIPESTATUS_")&&e.state.env.delete(d);for(let d=0;d{let c=`${s}_`;for(let f of e.state.env.keys())f.startsWith(c)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(l&&o?await Ed(e,t,s,r,n,u,c=>{a+=c}):o?await bd(e,s,r,n,u):await vd(e,s,r,n,u),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>Ut(d)).join(" ")})`;e.state.env.set(s,f)}return{continueToNext:!0,xtraceOutput:a}}function wd(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],r=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let n=t.parts[2];return n.type!=="Literal"?!1:n.value.startsWith("]=")||n.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):s.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function Ed(e,t,s,r,n,i,a){let l=[];for(let o of r){let u=br(o);if(u){let{key:c,valueParts:f,append:d}=u,h;f.length>0?h=await V(e,{type:"Word",parts:f}):h="",h=de(e,h),l.push({type:"keyed",key:c,value:h,append:d})}else{let c=await V(e,o);l.push({type:"invalid",expandedValue:c})}}n||i();for(let o of l)if(o.type==="keyed")if(o.append){let u=e.state.env.get(`${s}_${o.key}`)??"";e.state.env.set(`${s}_${o.key}`,u+o.value)}else e.state.env.set(`${s}_${o.key}`,o.value);else{let u=t.line??e.state.currentLine??1;a(`bash: line ${u}: ${s}: ${o.expandedValue}: must use subscript when assigning associative array `)}}async function bd(e,t,s,r,n){let i=[];for(let l of s){let o=br(l);if(o){let{key:u,valueParts:c,append:f}=o,d;c.length>0?d=await V(e,{type:"Word",parts:c}):d="",d=de(e,d),i.push({type:"keyed",indexExpr:u,value:d,append:f})}else{let u=await it(e,l);i.push({type:"non-keyed",values:u.values})}}r||n();let a=0;for(let l of i)if(l.type==="keyed"){let o;try{let u=new q,c=Y(u,l.indexExpr);o=await T(e,c.expression,!1)}catch{if(/^-?\d+$/.test(l.indexExpr))o=Number.parseInt(l.indexExpr,10);else{let u=e.state.env.get(l.indexExpr);o=u?Number.parseInt(u,10):0,Number.isNaN(o)&&(o=0)}}if(l.append){let u=e.state.env.get(`${t}_${o}`)??"";e.state.env.set(`${t}_${o}`,u+l.value)}else e.state.env.set(`${t}_${o}`,l.value);a=o+1}else for(let o of l.values)e.state.env.set(`${t}_${a++}`,o)}async function vd(e,t,s,r,n){let i=[];for(let l of s){let o=await it(e,l);i.push(...o.values)}let a=0;if(r){let l=B(e,t);if(l.length>0)a=Math.max(...l.map(([u])=>typeof u=="number"?u:0))+1;else{let o=e.state.env.get(t);o!==void 0&&(e.state.env.set(`${t}_0`,o),e.state.env.delete(t),a=1)}}else n();for(let l=0;l0){let d=e.state.localScopes[e.state.localScopes.length-1];d.has(u)||d.set(u,e.state.env.get(u))}e.state.env.set(u,c)}return{continueToNext:!0,xtraceOutput:""}}async function rc(e,t,s){let r;if(s.startsWith("'")&&s.endsWith("'"))r=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let n=s.slice(1,-1),a=new q().parseWordFromString(n,!0,!1);r=await V(e,a)}else if(s.includes("$")){let i=new q().parseWordFromString(s,!1,!1);r=await V(e,i)}else r=s;return`${t}_${r}`}async function Ad(e,t,s){let r=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(r=s.slice(1,-1));let n;if(/^-?\d+$/.test(r))n=Number.parseInt(r,10);else{try{let i=new q,a=Y(i,r);n=await T(e,a.expression,!1)}catch(i){if(i instanceof se){let o=`bash: line ${e.state.currentLine}: ${s}: ${i.message} `;if(i.fatal)throw new Z(1,"",o);return{index:0,error:_("",o,1)}}let a=e.state.env.get(s);n=a?Number.parseInt(a,10):0}Number.isNaN(n)&&(n=0)}if(n<0){let i=B(e,t);if(i.length===0){let l=e.state.currentLine;return{index:0,error:_("",`bash: line ${l}: ${t}[${s}]: bad array subscript `,1)}}if(n=Math.max(...i.map(([l])=>typeof l=="number"?l:0))+1+n,n<0){let l=e.state.currentLine;return{index:0,error:_("",`bash: line ${l}: ${t}[${s}]: bad array subscript `,1)}}}return{index:n}}async function $d(e,t,s,r,n,i){let a="",l=s,o=null;if(te(e,s)){let f=Va(e,s,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:"",error:_("",`bash: ${s}: circular name reference `,1)};if(f===null)return{continueToNext:!0,xtraceOutput:""};l=f;let d=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);d&&(o={arrayName:d[1],subscriptExpr:d[2]},l=d[1])}if(rt(e,l)){if(t.name)return a+=`bash: ${l}: readonly variable `,{continueToNext:!0,xtraceOutput:a};let f=ye(e,l);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let u;if(ws(e,l))try{let f=new q;if(n){let h=`(${e.state.env.get(l)||"0"}) + (${r})`,m=Y(f,h);u=String(await T(e,m.expression))}else{let d=Y(f,r);u=String(await T(e,d.expression))}}catch{u="0"}else{let f=He(e,l)?`${l}_0`:l;u=n?(e.state.env.get(f)||"")+r:r}u=Jt(e,l,u),a+=await tc(e,l,u);let c=l;return o?c=await Pd(e,o):He(e,l)&&(c=`${l}_0`),t.name?(i.set(c,e.state.env.get(c)),e.state.env.set(c,u)):(e.state.env.set(c,u),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(l)),e.state.tempEnvBindings?.some(f=>f.has(l))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(l))),{continueToNext:!1,xtraceOutput:a}}async function Pd(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return rc(e,s,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let a=new q,l=Y(a,r);i=await T(e,l.expression,!1)}catch{let a=e.state.env.get(r);i=a?Number.parseInt(a,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let a=B(e,s);a.length>0&&(i=Math.max(...a.map(o=>o[0]))+1+i)}return`${s}_${i}`}async function ic(e,t,s,r){let n=await lt(e,t.redirections);if(n)return n;let i=new Map(e.state.env),a=e.state.cwd,l={...e.state.options},o=new Map(e.state.functions),u=e.state.localScopes,c=e.state.localVarStack,f=e.state.localVarDepth,d=e.state.fullyUnsetLocals;if(e.state.localScopes=u.map($=>new Map($)),c){e.state.localVarStack=new Map;for(let[$,R]of c.entries())e.state.localVarStack.set($,R.map(C=>({...C})))}f&&(e.state.localVarDepth=new Map(f)),d&&(e.state.fullyUnsetLocals=new Map(d));let h=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let p=e.state.lastArg,y=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let b=e.state.groupStdin;s&&(e.state.groupStdin=s);let v="",E="",w=0,S=()=>{e.state.env=i,e.state.cwd=a,e.state.options=l,e.state.functions=o,e.state.localScopes=u,e.state.localVarStack=c,e.state.localVarDepth=f,e.state.fullyUnsetLocals=d,e.state.loopDepth=h,e.state.parentHasLoopContext=m,e.state.groupStdin=b,e.state.bashPid=y,e.state.lastArg=p};try{for(let $ of t.body){let R=await r($);v+=R.stdout,E+=R.stderr,w=R.exitCode}}catch($){if(S(),$ instanceof X)throw $;if($ instanceof Et){v+=$.stdout,E+=$.stderr;let C=_(v,E,0);return ue(e,C,t.redirections)}if($ instanceof Oe||$ instanceof Te){v+=$.stdout,E+=$.stderr;let C=_(v,E,0);return ue(e,C,t.redirections)}if($ instanceof Z){v+=$.stdout,E+=$.stderr;let C=_(v,E,$.exitCode);return ue(e,C,t.redirections)}if($ instanceof ke){v+=$.stdout,E+=$.stderr;let C=_(v,E,$.exitCode);return ue(e,C,t.redirections)}if($ instanceof ze){let C=_(v+$.stdout,E+$.stderr,$.exitCode);return ue(e,C,t.redirections)}let R=_(v,`${E}${ct($)} `,1);return ue(e,R,t.redirections)}S();let A=_(v,E,w);return ue(e,A,t.redirections)}async function ac(e,t,s,r){let n="",i="",a=0,l=await En(e,t.redirections);if(l)return l;let o=s;for(let f of t.redirections)if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,h=await V(e,d.content);d.stripTabs&&(h=h.split(` `).map(p=>p.replace(/^\t+/,"")).join(` `));let m=f.fd??0;m!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),Ae(e),e.state.fileDescriptors.set(m,h)):o=h}else if(f.operator==="<<<"&&f.target.type==="Word")o=`${await V(e,f.target)} `;else if(f.operator==="<"&&f.target.type==="Word")try{let d=await V(e,f.target),h=e.fs.resolvePath(e.state.cwd,d);o=await e.fs.readFile(h)}catch{let d=await V(e,f.target);return _("",`bash: ${d}: No such file or directory `,1)}let u=e.state.groupStdin;o&&(e.state.groupStdin=o);try{for(let f of t.body){let d=await r(f);n+=d.stdout,i+=d.stderr,a=d.exitCode}}catch(f){if(e.state.groupStdin=u,f instanceof X)throw f;if(Is(f)||f instanceof ze||f instanceof Z)throw f.prependOutput(n,i),f;return _(n,`${i}${ct(f)} `,1)}e.state.groupStdin=u;let c=_(n,i,a);return ue(e,c,t.redirections)}async function oc(e,t,s,r,n){let i;try{i=await e.fs.readFile(t)}catch{return N(`bash: ${t}: No such file or directory `,127)}if(i.startsWith("#!")){let y=i.indexOf(` `);y!==-1&&(i=i.slice(y+1))}let a=new Map(e.state.env),l=e.state.cwd,o={...e.state.options},u=e.state.loopDepth,c=e.state.parentHasLoopContext,f=e.state.lastArg,d=e.state.bashPid,h=e.state.groupStdin,m=e.state.currentSource;e.state.parentHasLoopContext=u>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set("0",t),e.state.env.set("#",String(s.length)),e.state.env.set("@",s.join(" ")),e.state.env.set("*",s.join(" "));for(let y=0;y{e.state.env=a,e.state.cwd=l,e.state.options=o,e.state.loopDepth=u,e.state.parentHasLoopContext=c,e.state.lastArg=f,e.state.bashPid=d,e.state.groupStdin=h,e.state.currentSource=m};try{let b=new q().parse(i),v=await n(b);return p(),v}catch(y){if(p(),y instanceof Z||y instanceof X)throw y;if(y.name==="ParseException")return N(`bash: ${t}: ${y.message} `);throw y}}var As=class{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,limits:t.limits,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,invokeTool:t.invokeTool}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||Ie.isInSandboxedContext())return;let s=`interpreter ${t} attempted outside defense context`;throw new gt(s,{timestamp:Date.now(),type:"missing_defense_context",message:s,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:Ie.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r){let a=this.ctx.state.env.get(i);a!==void 0&&(n[i]=a)}return n}async executeScript(t){this.assertDefenseContext("execution");let s="",r="",n=0,i=this.ctx.limits.maxOutputSize,a=(l,o)=>{s.length+r.length+l.length+o.length>i&&at(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,"output_size"),s+=l,r+=o};for(let l of t.statements)try{let o=await this.executeStatement(l);a(Vn(o),o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(o){if(o instanceof Z)throw o.prependOutput(s,r),o;if(o instanceof Be)return a(o.stdout,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:bt(this.ctx.state.env)};if(o instanceof X)throw o;if(o instanceof ze)return a(o.stdout,o.stderr),n=o.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:bt(this.ctx.state.env)};if(o instanceof Le)return a(o.stdout,o.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:bt(this.ctx.state.env)};if(o instanceof Me)return a(o.stdout,o.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:bt(this.ctx.state.env)};if(o instanceof se){a(o.stdout,o.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(o instanceof Ds){a(o.stdout,o.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(o instanceof Oe||o instanceof Te){if(this.ctx.state.loopDepth>0)throw o.prependOutput(s,r),o;a(o.stdout,o.stderr);continue}throw o instanceof ke&&o.prependOutput(s,r),o}return{stdout:s,stderr:r,exitCode:n,env:bt(this.ctx.state.env)}}async executeUserScript(t,s,r=""){return oc(this.ctx,t,s,r,n=>this.executeScript(n))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new Rs;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&at(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),t.deferredError)throw new Ee(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return K;this.ctx.state.errexitSafe=!1;let s="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r+=`${t.sourceText} `);let n=0,i=-1,a=!1;for(let u=0;u0?t.operators[u-1]:null;if(f==="&&"&&n!==0||f==="||"&&n===0)continue;let d=await this.executePipeline(c);s+=Vn(d),r+=d.stderr,n=d.exitCode,i=u,a=c.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}let l=ithis.executeCommand(s,r))}async executeCommand(t,s){switch(this.assertDefenseContext("command"),this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,s);case"If":return Ul(this.ctx,t);case"For":return Zl(this.ctx,t);case"CStyleFor":return Gl(this.ctx,t);case"While":return Hl(this.ctx,t,s);case"Until":return Ql(this.ctx,t);case"Case":return Kl(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return dl(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return K}}async executeSimpleCommand(t,s){try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof wt)return N(r.stderr);throw r}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let w=t,S=100;for(;S>0;){let A=this.expandAlias(w);if(A===w)break;w=A,S--}this.aliasExpansionStack.clear(),w!==t&&(t=w)}this.ctx.state.expansionStderr="";let r=await nc(this.ctx,t);if(r.error)return r.error;let n=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(t.redirections.length>0){let S=await lt(this.ctx,t.redirections);if(S)return S;let A=_("",i,0);return ue(this.ctx,A,t.redirections)}this.ctx.state.lastArg="";let w=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",_("",w,this.ctx.state.lastExitCode)}let a=t.name&&Ai(t.name,["local","declare","typeset","export","readonly"]),l=Array.from(n.keys());if(l.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let w of l)this.ctx.state.tempExportedVars.add(w)}let o=await En(this.ctx,t.redirections);if(o){for(let[w,S]of n)S===void 0?this.ctx.state.env.delete(w):this.ctx.state.env.set(w,S);return o}let u=-1;for(let w of t.redirections){if((w.operator==="<<"||w.operator==="<<-")&&w.target.type==="HereDoc"){let S=w.target,A=await V(this.ctx,S.content);S.stripTabs&&(A=A.split(` `).map(R=>R.replace(/^\t+/,"")).join(` `)),A=yt(A);let $=w.fd??0;$!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),Ae(this.ctx),this.ctx.state.fileDescriptors.set($,A)):s=A;continue}if(w.operator==="<<<"&&w.target.type==="Word"){s=yt(`${await V(this.ctx,w.target)} `);continue}if(w.operator==="<"&&w.target.type==="Word")try{let S=await V(this.ctx,w.target),A=this.ctx.fs.resolvePath(this.ctx.state.cwd,S);s=await xs(this.ctx.fs,A)}catch{let S=await V(this.ctx,w.target);for(let[A,$]of n)$===void 0?this.ctx.state.env.delete(A):this.ctx.state.env.set(A,$);return N(`bash: ${S}: No such file or directory `)}if(w.operator==="<&"&&w.target.type==="Word"){let S=await V(this.ctx,w.target),A=Number.parseInt(S,10);if(!Number.isNaN(A)&&this.ctx.state.fileDescriptors){let $=this.ctx.state.fileDescriptors.get(A);if($!==void 0)if($.startsWith("__rw__:")){let R=Xl($);R&&(s=R.content.slice(R.position),u=A)}else $.startsWith("__file__:")||$.startsWith("__file_append__:")||(s=$)}}}let c=await V(this.ctx,t.name),f=[],d=[];if(Ai(t.name,["local","declare","typeset","export","readonly"])&&(c==="local"||c==="declare"||c==="typeset"||c==="export"||c==="readonly"))for(let w of t.args){let S=await Qo(this.ctx,w);if(S)f.push(S),d.push(!0);else{let A=await Ko(this.ctx,w);if(A!==null)f.push(A),d.push(!0);else{let $=await it(this.ctx,w);for(let R of $.values)f.push(R),d.push($.quoted)}}}else for(let w of t.args){let S=await it(this.ctx,w);for(let A of S.values)f.push(A),d.push(S.quoted)}if(!c){if(t.name.parts.every(S=>S.type==="CommandSubstitution"||S.type==="ParameterExpansion"||S.type==="ArithmeticExpansion")){if(f.length>0){let S=f.shift();return d.shift(),await this.runCommand(S,f,d,s,!1,!1,u)}return _("","",this.ctx.state.lastExitCode)}return N(`bash: : command not found `,127)}if(c==="exec"&&(f.length===0||f[0]==="--")){for(let w of t.redirections){if(w.target.type==="HereDoc"||w.fdVariable)continue;let S=await V(this.ctx,w.target),A=w.fd??(w.operator==="<"||w.operator==="<>"?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),w.operator){case">":case">|":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,S);await this.ctx.fs.writeFile($,"","utf8"),Ae(this.ctx),this.ctx.state.fileDescriptors.set(A,`__file__:${$}`);break}case">>":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,S);Ae(this.ctx),this.ctx.state.fileDescriptors.set(A,`__file_append__:${$}`);break}case"<":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,S);try{let R=await this.ctx.fs.readFile($);Ae(this.ctx),this.ctx.state.fileDescriptors.set(A,R)}catch{return N(`bash: ${S}: No such file or directory `)}break}case"<>":{let $=this.ctx.fs.resolvePath(this.ctx.state.cwd,S);try{let R=await this.ctx.fs.readFile($);Ae(this.ctx),this.ctx.state.fileDescriptors.set(A,`__rw__:${$.length}:${$}:0:${R}`)}catch{await this.ctx.fs.writeFile($,"","utf8"),Ae(this.ctx),this.ctx.state.fileDescriptors.set(A,`__rw__:${$.length}:${$}:0:`)}break}case">&":{if(S==="-")this.ctx.state.fileDescriptors.delete(A);else if(S.endsWith("-")){let $=S.slice(0,-1),R=Number.parseInt($,10);if(!Number.isNaN(R)){let C=this.ctx.state.fileDescriptors.get(R);C!==void 0?this.ctx.state.fileDescriptors.set(A,C):this.ctx.state.fileDescriptors.set(A,`__dupout__:${R}`),this.ctx.state.fileDescriptors.delete(R)}}else{let $=Number.parseInt(S,10);Number.isNaN($)||(Ae(this.ctx),this.ctx.state.fileDescriptors.set(A,`__dupout__:${$}`))}break}case"<&":{if(S==="-")this.ctx.state.fileDescriptors.delete(A);else if(S.endsWith("-")){let $=S.slice(0,-1),R=Number.parseInt($,10);if(!Number.isNaN(R)){let C=this.ctx.state.fileDescriptors.get(R);C!==void 0?this.ctx.state.fileDescriptors.set(A,C):this.ctx.state.fileDescriptors.set(A,`__dupin__:${R}`),this.ctx.state.fileDescriptors.delete(R)}}else{let $=Number.parseInt(S,10);Number.isNaN($)||(Ae(this.ctx),this.ctx.state.fileDescriptors.set(A,`__dupin__:${$}`))}break}}}for(let[w,S]of n)S===void 0?this.ctx.state.env.delete(w):this.ctx.state.env.set(w,S);if(this.ctx.state.tempExportedVars)for(let w of n.keys())this.ctx.state.tempExportedVars.delete(w);return K}if(this.ctx.state.extraArgs){f.push(...this.ctx.state.extraArgs);for(let w=0;w0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let p,y=null;try{p=await this.runCommand(c,f,d,s,!1,!1,u)}catch(w){if(w instanceof Oe||w instanceof Te)y=w,p=K;else throw w}let b=i+m;if(b&&(p={...p,stderr:b+p.stderr}),p=await ue(this.ctx,p,t.redirections),y)throw y;if(f.length>0){let w=f[f.length-1];if((c==="declare"||c==="local"||c==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(w)){let S=w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);S&&(w=S[1])}this.ctx.state.lastArg=w}else this.ctx.state.lastArg=c;let v=ul(c)&&c!=="unset"&&c!=="eval";if(!this.ctx.state.options.posix||!v)for(let[w,S]of n)this.ctx.state.fullyUnsetLocals?.has(w)||(S===void 0?this.ctx.state.env.delete(w):this.ctx.state.env.set(w,S));if(this.ctx.state.tempExportedVars)for(let w of n.keys())this.ctx.state.tempExportedVars.delete(w);return n.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(p={...p,stderr:this.ctx.state.expansionStderr+p.stderr},this.ctx.state.expansionStderr=""),p}async runCommand(t,s,r,n,i=!1,a=!1,l=-1){let o={ctx:this.ctx,runCommand:(c,f,d,h,m,p,y)=>this.runCommand(c,f,d,h,m,p,y),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(c,f,d)=>this.executeUserScript(c,f,d)},u=await ql(o,t,s,r,n,i,a,l);return u!==null?u:jl(o,t,s,n,a)}aliasExpansionStack=new Set;expandAlias(t){return mr(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return kn(this.ctx,t)}async executeSubshell(t,s=""){return ic(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=""){return ac(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await lt(this.ctx,t.redirections);if(s)return s;try{let r=await T(this.ctx,t.expression.expression),n=pe(r!==0);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=""),ue(this.ctx,n,t.redirections)}catch(r){let n=N(`bash: arithmetic expression: ${r.message} `);return ue(this.ctx,n,t.redirections)}}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await lt(this.ctx,t.redirections);if(s)return s;try{let r=await xt(this.ctx,t.expression),n=pe(r);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=""),ue(this.ctx,n,t.redirections)}catch(r){let n=r instanceof se?1:2,i=N(`bash: conditional expression: ${r.message} `,n);return ue(this.ctx,i,t.redirections)}}};var we={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function lc(e){return e?{maxCallDepth:e.maxCallDepth??we.maxCallDepth,maxCommandCount:e.maxCommandCount??we.maxCommandCount,maxLoopIterations:e.maxLoopIterations??we.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??we.maxAwkIterations,maxSedIterations:e.maxSedIterations??we.maxSedIterations,maxJqIterations:e.maxJqIterations??we.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??we.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??we.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??we.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??we.maxGlobOperations,maxStringLength:e.maxStringLength??we.maxStringLength,maxArrayElements:e.maxArrayElements??we.maxArrayElements,maxHeredocSize:e.maxHeredocSize??we.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??we.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??we.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??we.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??we.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??we.maxSourceDepth}:{...we}}import{lookup as Td}from"node:dns";function $i(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function kd(e){let t=$i(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function cc(e){if(e.includes("\\"))return!0;let t=e.toLowerCase();return t.includes("%2f")||t.includes("%5c")}function Nd(e,t){return t==="/"||t===""?!0:t.endsWith("/")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function Pi(e,t){let s=$i(e);if(!s)return!1;let r=kd(t);return!r||s.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&cc(s.pathname)?!1:Nd(s.pathname,r.pathPrefix)}function uc(e){return typeof e=="string"?e:e.url}function fc(e,t){return!t||t.length===0?!1:t.some(s=>Pi(e,uc(s)))}function ki(e){let t=_d(e);if(t==="localhost"||t.endsWith(".localhost"))return!0;let s=dc(t);if(s)return _n(s);let r=Cd(t);return r?Dd(r):!1}function _d(e){let t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function xd(e){if(!e)return null;let t=10,s=e;if(s.startsWith("0x")||s.startsWith("0X")?(t=16,s=s.slice(2)):s.length>1&&s.startsWith("0")&&(t=8),!s||t===16&&!/^[0-9a-fA-F]+$/.test(s)||t===10&&!/^\d+$/.test(s)||t===8&&!/^[0-7]+$/.test(s))return null;let r=Number.parseInt(s,t);return!Number.isFinite(r)||r<0?null:r}function dc(e){let t=e.split(".");if(t.length===0||t.length>4)return null;let s=t.map(o=>xd(o));if(s.some(o=>o===null))return null;let r=s;if(t.length===1){let o=r[0];return o>4294967295?null:[o>>>24&255,o>>>16&255,o>>>8&255,o&255]}if(t.length===2){let[o,u]=r;return o>255||u>16777215?null:[o,u>>>16&255,u>>>8&255,u&255]}if(t.length===3){let[o,u,c]=r;return o>255||u>255||c>65535?null:[o,u,c>>>8&255,c&255]}let[n,i,a,l]=r;return n>255||i>255||a>255||l>255?null:[n,i,a,l]}function Cd(e){let t=e,s=null;if(t.includes(".")){let p=t.lastIndexOf(":");if(p<0)return null;let y=t.slice(p+1),b=dc(y);if(!b)return null;s=b,t=t.slice(0,p)}let r=t.includes("::")?t.split("::").length-1:0;if(r>1)return null;let[n,i]=t.split("::"),a=n?n.split(":").filter(Boolean):[],l=i?i.split(":").filter(Boolean):[],o=p=>/^[0-9a-f]{1,4}$/i.test(p)?Number.parseInt(p,16):null,u=a.map(o),c=l.map(o);if(u.some(p=>p===null)||c.some(p=>p===null))return null;let f=s?2:0,d=u.length+c.length+f,h=0;if(r===1){if(h=8-d,h<0)return null}else if(d!==8)return null;let m=[...u,...new Array(h).fill(0),...c];return s&&(m.push(s[0]<<8|s[1]),m.push(s[2]<<8|s[3])),m.length===8?m:null}function _n(e){let[t,s]=e;return t===127||t===10||t===172&&s>=16&&s<=31||t===192&&s===168||t===169&&s===254||t===0||t===100&&s>=64&&s<=127||t===198&&(s===18||s===19)||t===192&&s===0&&e[2]===0||t===192&&s===0&&e[2]===2||t===198&&s===51&&e[2]===100||t===203&&s===0&&e[2]===113||t>=240}function Dd(e){if(e.every(n=>n===0)||e.slice(0,7).every(n=>n===0)&&e[7]===1||(e[0]&65472)===65152||(e[0]&65024)===64512)return!0;if(e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535){let n=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return _n(n)}if(e[0]===8193&&e[1]===3512)return!0;if(e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0){let n=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return _n(n)}if(e[0]===100&&e[1]===65435&&e[2]===1)return!0;if(e[0]===8194){let n=[e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255];return _n(n)}return!1}function hc(e){let t=[];for(let s of e){if(typeof s!="string"&&(s===null||typeof s!="object"||!("url"in s)||typeof s.url!="string")){t.push('Invalid allow-list entry: must be a string URL or an object with a "url" string property');continue}let r=uc(s);if(!$i(r)){t.push(`Invalid URL in allow-list: "${r}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let i=new URL(r);if(i.protocol!=="http:"&&i.protocol!=="https:"){t.push(`Only http and https URLs are allowed in allow-list: "${r}"`);continue}if(!i.hostname){t.push(`Allow-list entry must include a hostname: "${r}"`);continue}if(i.pathname!=="/"&&i.pathname!==""&&cc(i.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${r}"`);continue}(i.search||i.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${r}"`)}return t}var Rd=typeof __BROWSER__<"u"&&__BROWSER__,es=null,xn=null,pc=!1;function Id(){if(es===null&&!Rd)try{let e=Fn("node:async_hooks");xn=Fn("node:dns"),es=new e.AsyncLocalStorage}catch{}}function Od(){if(pc||(Id(),!es||!xn))return;pc=!0;let e=es,t=xn.lookup;function s(...r){let n=r[0],i=e.getStore();if(typeof n!="string"||!i||i.hostname.toLowerCase()!==n.toLowerCase())return t.apply(this,r);let a={},l;if(r.length===2)l=r[1];else if(r.length>=3){let u=r[1];typeof u=="number"?a={family:u}:u&&typeof u=="object"&&(a=u),l=r[2]}if(typeof l!="function")return t.apply(this,r);let o=l;if(a.family!==void 0&&a.family!==0&&a.family!==i.family){let u=new Error(`ENOTFOUND ${n}`);u.code="ENOTFOUND",u.errno=-3008,u.syscall="getaddrinfo",u.hostname=n,process.nextTick(()=>o(u));return}process.nextTick(()=>{a.all?o(null,[{address:i.address,family:i.family}]):o(null,i.address,i.family)})}Object.defineProperty(xn,"lookup",{value:s,writable:!0,configurable:!0})}function mc(e,t){return Od(),es?es.run(e,t):t()}var Xe=class extends Error{constructor(t,s){let r=s??"URL not in allow-list";super(`Network access denied: ${r}: ${t}`),this.name="NetworkAccessDeniedError"}},ts=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},ss=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Cn=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},ns=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};function Ld(e){return new Promise((t,s)=>{Td(e,{all:!0},(r,n)=>{r?s(r):t(n)})})}var Md=20,Wd=3e4,Fd=10485760,Vd=["GET","HEAD"],zd=new Set(["GET","HEAD","OPTIONS"]),Bd=new Set([301,302,303,307,308]);function Ni(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let h=hc(t);if(h.length>0)throw new Error(`Invalid network allow-list: ${h.join(` `)}`)}let s=[];for(let h of t)typeof h=="object"&&h.transform&&h.transform.length>0&&s.push(h);function r(h){if(s.length===0)return null;let m=null;for(let p of s)if(Pi(h,p.url)&&p.transform){m||(m=new Headers);for(let y of p.transform)for(let[b,v]of Object.entries(y.headers))m.set(b,v)}return m}let n=e.maxRedirects??Md,i=e.timeoutMs??Wd,a=e.maxResponseSize??Fd,l=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??Vd,o=e.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),u=e._dnsResolve??Ld;async function c(h){if(!e.dangerouslyAllowFullInternetAccess&&!fc(h,t))throw new Xe(h);if(o)try{let m=new URL(h);if(ki(m.hostname))throw new Xe(h,"private/loopback IP address blocked");let p=m.hostname;if(/[a-zA-Z]/.test(p))try{let b=await u(p);for(let{address:E}of b)if(ki(E))throw new Xe(h,"hostname resolves to private/loopback IP address");let v=b[0];if(v)return{hostname:p,address:v.address,family:v.family===6?6:4}}catch(b){if(b instanceof Xe)throw b;let v=b?.code;if(!(v==="ENOTFOUND"||v==="ENODATA"))throw new Xe(h,"DNS resolution failed for private IP check")}}catch(m){if(m instanceof Xe)throw m}return null}function f(h){if(e.dangerouslyAllowFullInternetAccess)return;let m=h.toUpperCase();if(!l.includes(m))throw new Cn(m,l)}async function d(h,m={}){let p=m.method?.toUpperCase()??"GET",y=await c(h);f(p);let b=h,v=0,E=m.followRedirects??!0,w=m.timeoutMs!==void 0?Math.min(m.timeoutMs,i):i;for(;;){let S=new AbortController,A=ks(()=>S.abort(),w);try{let $=await Ie.runTrustedAsync(()=>{let R=r(b),C=qd(m.headers,R),F={method:p,headers:C,signal:S.signal,redirect:"manual"};return m.body&&!zd.has(p)&&(F.body=m.body),y?mc(y,()=>fetch(b,F)):fetch(b,F)});if(Bd.has($.status)&&E){let R=$.headers.get("location");if(!R)return await gc($,b,a);let C=new URL(R,b).href;try{y=await c(C)}catch{throw new ss(C)}if(v++,v>n)throw new ts(n);b=C;continue}return await gc($,b,a)}finally{Ns(A)}}}return d}function qd(e,t){if(!e&&!t)return;if(!t)return e;let s=e instanceof Headers?new Headers(e):new Headers(e);for(let[r,n]of t)s.set(r,n);return s}async function gc(e,t,s){let r=Object.create(null);if(e.headers.forEach((i,a)=>{r[a.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let a=parseInt(i,10);if(!Number.isNaN(a)&&a>s)throw new ns(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),a=[],l=0;for(;;){let{done:u,value:c}=await i.read();if(u)break;if(c){if(l+=c.byteLength,l>s)throw i.cancel(),new ns(s);a.push(c)}}n=new Uint8Array(l);let o=0;for(let u of a)n.set(u,o),o+=u.byteLength}else{let i=await e.arrayBuffer();if(s>0&&i.byteLength>s)throw new ns(s);n=new Uint8Array(i)}return{status:e.status,statusText:e.statusText,headers:r,body:n,url:t}}function $s(e){return Wt(e)}function Wt(e){return e.statements.map(yc).join(` `)}function yc(e){let t=[];for(let r=0;r0?`${t.join(" ")} `:"")+s.join(" ")}function wc(e){switch(e.type){case"SimpleCommand":return Ud(e);case"If":return eh(e);case"For":return th(e);case"CStyleFor":return sh(e);case"While":return nh(e);case"Until":return rh(e);case"Case":return ih(e);case"Subshell":return oh(e);case"Group":return lh(e);case"ArithmeticCommand":return ch(e);case"ConditionalCommand":return uh(e);case"FunctionDef":return fh(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function Ud(e){let t=[];for(let s of e.assignments)t.push(Zd(s));e.name&&t.push(be(e.name));for(let s of e.args)t.push(be(s));for(let s of e.redirections)t.push(vc(s));return t.join(" ")}function Zd(e){let t=e.append?"+=":"=";if(e.array){let s=e.array.map(be).join(" ");return`${e.name}${t}(${s})`}return e.value?`${e.name}${t}${be(e.value)}`:`${e.name}${t}`}function be(e){return e.parts.map(t=>Dn(t,!1)).join("")}function Dt(e){return e.parts.map(t=>Dn(t,!0)).join("")}function Dn(e,t){switch(e.type){case"Literal":return t?Hd(e.value):Gd(e.value);case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(s=>Dn(s,!0)).join("")}"`;case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return Ec(e);case"CommandSubstitution":return e.legacy?`\`${Wt(e.body)}\``:`$(${Wt(e.body)})`;case"ArithmeticExpansion":return`$((${ie(e.expression.expression)}))`;case"ProcessSubstitution":return e.direction==="input"?`<(${Wt(e.body)})`:`>(${Wt(e.body)})`;case"BraceExpansion":return Yd(e);case"TildeExpansion":return e.user!==null?`~${e.user}`:"~";case"Glob":return e.pattern;default:{let s=e;throw new Error(`Unsupported word part type: ${s.type}`)}}}function Gd(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,"\\$&")}function Hd(e){return e.replace(/[$`"\\]/g,"\\$&")}function Qd(e,t){return e.parts.map(s=>Kd(s,t)).join("")}function Kd(e,t){switch(e.type){case"Literal":return t?e.value:e.value.replace(/[$`]/g,"\\$&");case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return Ec(e);case"CommandSubstitution":return e.legacy?`\`${Wt(e.body)}\``:`$(${Wt(e.body)})`;case"ArithmeticExpansion":return`$((${ie(e.expression.expression)}))`;default:return Dn(e,!1)}}function Ec(e){return e.operation?`\${${bc(e.parameter,e.operation)}}`:Xd(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function Xd(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function bc(e,t){switch(t.type){case"Length":return`#${e}`;case"LengthSliceError":return`#${e}:`;case"BadSubstitution":return t.text;case"DefaultValue":return`${e}${t.checkEmpty?":":""}-${Dt(t.word)}`;case"AssignDefault":return`${e}${t.checkEmpty?":":""}=${Dt(t.word)}`;case"ErrorIfUnset":return`${e}${t.checkEmpty?":":""}?${t.word?Dt(t.word):""}`;case"UseAlternative":return`${e}${t.checkEmpty?":":""}+${Dt(t.word)}`;case"Substring":{let s=ie(t.offset.expression);return t.length?`${e}:${s}:${ie(t.length.expression)}`:`${e}:${s}`}case"PatternRemoval":{let s=t.side==="prefix"?"#":"%",r=t.greedy?`${s}${s}`:s;return`${e}${r}${Dt(t.pattern)}`}case"PatternReplacement":{let s="/";t.all?s="//":t.anchor==="start"?s="/#":t.anchor==="end"&&(s="/%");let r=t.replacement?`/${Dt(t.replacement)}`:"";return`${e}${s}${Dt(t.pattern)}${r}`}case"CaseModification":{let s=t.direction==="upper"?"^":",",r=t.all?`${s}${s}`:s,n=t.pattern?Dt(t.pattern):"";return`${e}${r}${n}`}case"Transform":return`${e}@${t.operator}`;case"Indirection":return t.innerOp?`!${bc(e,t.innerOp)}`:`!${e}`;case"ArrayKeys":return`!${t.array}[${t.star?"*":"@"}]`;case"VarNamePrefix":return`!${t.prefix}${t.star?"*":"@"}`;default:{let s=t;throw new Error(`Unsupported parameter operation type: ${s.type}`)}}}function Yd(e){return`{${e.items.map(Jd).join(",")}}`}function Jd(e){if(e.type==="Word")return be(e.word);let t=e.startStr??String(e.start),s=e.endStr??String(e.end);return e.step!==void 0?`${t}..${s}..${e.step}`:`${t}..${s}`}function vc(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd!==null?String(e.fd):"";if(e.operator==="<<"||e.operator==="<<-"){let s=e.target,r=s.quoted?`'${s.delimiter}'`:s.delimiter,n=Qd(s.content,s.quoted);return`${t}${e.operator}${r} ${n}${s.delimiter}`}return e.operator==="<<<"?`${t}<<< ${be(e.target)}`:e.operator==="&>"||e.operator==="&>>"?`${e.operator} ${be(e.target)}`:`${t}${e.operator} ${be(e.target)}`}function Ye(e){return e.length===0?"":` ${e.map(vc).join(" ")}`}function Ue(e){return e.map(yc).join(` `)}function eh(e){let t=[];for(let s=0;sthis.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option. `,exitCode:1,env:qe(this.state.env,s?.env)};if(!t.trim())return{stdout:"",stderr:"",exitCode:0,env:qe(this.state.env,s?.env)};this.logger?.info("exec",{command:t});let r=s?.cwd??this.state.cwd,n,i=r;if(s?.cwd)if(s.env&&"PWD"in s.env)n=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{n=await this.fs.realpath(r),i=n}catch{n=r}else n=r;let a=s?.replaceEnv?new Map:new Map(this.state.env);if(s?.env)for(let[f,d]of Object.entries(s.env))a.set(f,d);n!==void 0&&a.set("PWD",n);let l={...this.state,env:a,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:ph(s?.stdin,s?.stdinKind),signal:s?.signal,extraArgs:s?.args},o=t;s?.rawScript||(o=Sc(t));let u=this.defenseInDepthConfig?Ie.getInstance(this.defenseInDepthConfig):null,c=u?.activate();try{let f=async()=>{let d=Ce(o,{maxHeredocSize:this.limits.maxHeredocSize}),h;if(this.transformPlugins.length>0){let v=Object.create(null);for(let E of this.transformPlugins){let w=E.transform({ast:d,metadata:v});d=w.ast,w.metadata&&(v=cs(v,w.metadata))}h=v}let m={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:u?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},b=await new As(m,l).executeScript(d);return h&&(b.metadata=h),this.logResult(b)};return c?await c.run(f):await f()}catch(f){if(f instanceof Z)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:qe(this.state.env,s?.env)});if(f instanceof Be)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:qe(this.state.env,s?.env)});if(f instanceof se)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:qe(this.state.env,s?.env)});if(f instanceof Rs)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:qe(this.state.env,s?.env)});if(f instanceof X)return this.logResult({stdout:f.stdout,stderr:ut(f.stderr),exitCode:X.EXIT_CODE,env:qe(this.state.env,s?.env)});if(f instanceof gt)return this.logResult({stdout:"",stderr:`bash: security violation: ${ut(f.message)} `,exitCode:1,env:qe(this.state.env,s?.env)});if(f.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${ut(f.message)} `,exitCode:2,env:qe(this.state.env,s?.env)});if(f instanceof At)return this.logResult({stdout:"",stderr:`bash: ${ut(f.message)} `,exitCode:2,env:qe(this.state.env,s?.env)});if(f instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${ut(f.message)} `,exitCode:1,env:qe(this.state.env,s?.env)});throw f}finally{c?.deactivate()}}async readFile(t){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,s){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),s)}getCwd(){return this.state.cwd}getEnv(){return bt(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){let s=Sc(t),r=Ce(s,{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let i of this.transformPlugins){let a=i.transform({ast:r,metadata:n});r=a.ast,a.metadata&&(n=cs(n,a.metadata))}return{script:$s(r),ast:r,metadata:n}}};function dh(e,t){let s=t;for(let r=0;r0){let c=r[r.length-1];if((c.stripTabs?a.replace(/^\t+/,""):a)===c.delimiter){s.push(a.trimStart()),r.pop();continue}s.push(a);continue}let l=n,o=l==="none"?a.trimStart():a;if(s.push(o),n=dh(a,l),l!=="none")continue;let u=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let c of o.matchAll(u)){let f=c[1]==="-",d=c[3];r.push({delimiter:d,stripTabs:f})}}return s.join(` `)}var hh=new TextDecoder("utf-8",{fatal:!0});function Ac(e){if(!e)return e;let t=!1;for(let r=0;r255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=L(t);return this.mounts.has(s)}validateMountPath(t){let s=t.split("/");for(let r of s)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let s of this.mounts.keys())if(s!==t){if(t.startsWith(`${s}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${s}'`);if(s.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${s}'`)}}routePath(t){M(t,"access");let s=L(t),r=null,n=0;for(let i of this.mounts.values()){let a=i.mountPoint;if(s===a)return{fs:i.filesystem,relativePath:"/"};s.startsWith(`${a}/`)&&a.length>n&&(r=i,n=a.length)}if(r){let i=s.slice(n);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(t){let s=L(t),r=s==="/"?"/":`${s}/`,n=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let l=i.slice(r.length).split("/")[0];l&&!n.includes(l)&&n.push(l)}return n}async readFile(t,s){let{fs:r,relativePath:n}=this.routePath(t);return r.readFile(n,s)}async readFileBytes(t){let{fs:s,relativePath:r}=this.routePath(t);return xs(s,r)}async readFileBuffer(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readFileBuffer(r)}async writeFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.writeFile(i,s,r)}async appendFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.appendFile(i,s,r)}async exists(t){let s=L(t);if(this.mounts.has(s)||this.getChildMountPoints(s).length>0)return!0;let{fs:n,relativePath:i}=this.routePath(t);return n.exists(i)}async stat(t){let s=L(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.stat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.stat(a)}async lstat(t){let s=L(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.lstat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.lstat(a)}async mkdir(t,s){let r=L(t);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:i,relativePath:a}=this.routePath(t);return i.mkdir(a,s)}async readdir(t){let s=L(t),r=new Set,n=null,{fs:i,relativePath:a}=this.routePath(t);try{let o=await i.readdir(a);for(let u of o)r.add(u)}catch(o){let u=o.code,c=o.message||"";if(u!=="ENOENT"&&!c.includes("ENOENT"))throw o;n=o}let l=this.getChildMountPoints(s);for(let o of l)r.add(o);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(t,s){let r=L(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:a}=this.routePath(t);return i.rm(a,s)}async cp(t,s,r){let n=this.routePath(t),i=this.routePath(s);return n.fs===i.fs?n.fs.cp(n.relativePath,i.relativePath,r):this.crossMountCopy(t,s,r)}async mv(t,s){let r=L(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let n=this.routePath(t),i=this.routePath(s);if(n.fs===i.fs)return n.fs.mv(n.relativePath,i.relativePath);await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){return vt(t,s)}getAllPaths(){let t=new Set;for(let s of this.baseFs.getAllPaths())t.add(s);for(let s of this.mounts.keys()){let r=s.split("/").filter(Boolean),n="";for(let a of r)n=`${n}/${a}`,t.add(n);let i=this.mounts.get(s);if(i)for(let a of i.filesystem.getAllPaths())a==="/"?t.add(s):t.add(`${s}${a}`)}return Array.from(t).sort()}async chmod(t,s){let r=L(t),n=this.mounts.get(r);if(n)return n.filesystem.chmod("/",s);let{fs:i,relativePath:a}=this.routePath(t);return i.chmod(a,s)}async symlink(t,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(t,n)}async link(t,s){let r=this.routePath(t),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readlink(r)}async realpath(t){let s=L(t);if(this.mounts.get(s))return s;let{fs:n,relativePath:i}=this.routePath(t),a=await n.realpath(i);for(let[l,o]of this.mounts)if(s===l||s.startsWith(`${l}/`))return a==="/"?l:`${l}${a}`;return a}async crossMountCopy(t,s,r){let n=await this.lstat(t);if(n.isFile){let i=await this.readFileBuffer(t);await this.writeFile(s,i),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let i=await this.readdir(t);for(let a of i){let l=St(t,a),o=St(s,a);await this.crossMountCopy(l,o,r)}}else if(n.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,s)}}async utimes(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.utimes(i,s,r)}};import*as ae from"node:fs";import*as Se from"node:path";import*as Ze from"node:fs";import*as Pe from"node:path";function Je(e,t){if(e===t)return!0;let s=e[t.length];return(s==="/"||s==="\\")&&e.startsWith(t)}function Ft(e,t){try{let s=Ze.realpathSync(e);return Je(s,t)?s:null}catch(s){if(s.code==="ENOENT"){let r=Pe.dirname(e);if(r===e)return null;let n=Ft(r,t);if(n===null)return null;try{if(Ze.lstatSync(e).isSymbolicLink()){let a=Ze.readlinkSync(e),l=Pe.isAbsolute(a)?a:Pe.resolve(Pe.dirname(e),a);if(Ft(l,t)===null)return null}}catch{}return Pe.join(n,Pe.basename(e))}return null}}function In(e,t,s){let r=Ft(e,s);if(r===null)return null;let n=Pe.resolve(e),i=n.slice(t.length),a=r.slice(s.length);if(i!==a)return null;try{if(Ze.lstatSync(n).isSymbolicLink())return null}catch{}return r}function On(e,t){if(!Ze.existsSync(e))throw new Error(`${t} root does not exist`);if(!Ze.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function $c(e,t){if(!Pe.isAbsolute(e))return{withinRoot:!0,relativePath:e};let s;try{s=Ze.realpathSync(e)}catch{s=Pe.resolve(e)}return Je(s,t)?{withinRoot:!0,relativePath:s.slice(t.length).replace(/\\/g,"/")||"/"}:{withinRoot:!1,safeName:Pe.basename(e)}}function Tn(e,t,s,r){let n=e;if(n.path===void 0){for(let a of r)if(n.message?.includes(a))throw e}let i=n.code||"EIO";throw new Error(`${i}: ${s} '${t}'`)}var mh=["ELOOP","EFBIG","EPERM"],gh="/home/user/project",rs=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;allowSymlinks;memory=new Map;deleted=new Set;constructor(t){this.root=Se.resolve(t.root);let s=t.mountPoint??gh;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,On(this.root,"OverlayFs"),this.canonicalRoot=ae.realpathSync(this.root),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split("/").filter(Boolean),s="";for(let r of t)s+=`/${r}`,this.memory.has(s)||this.memory.set(s,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,s){let n=L(t).split("/").filter(Boolean),i="";for(let a of n)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=L(t),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let i=s instanceof Uint8Array?s:new TextEncoder().encode(s);this.memory.set(r,{type:"file",content:i,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=L(t),r=this.getRelativeToMount(s);if(r===null)return null;let n=Se.join(this.root,r),i=Se.resolve(n);return Je(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?Ft(t,this.canonicalRoot):In(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let s=Se.dirname(t),r=this.resolveRealPath_(s);return r===null?null:Se.join(r,Se.basename(t))}sanitizeError(t,s,r){Tn(t,s,r,mh)}ensureParentDirs(t){let s=It(t);s!=="/"&&(this.memory.has(s)||(this.ensureParentDirs(s),this.memory.set(s,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(s))}async existsInOverlay(t){let s=L(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.resolveRealPathParent_(this.toRealPath(s));if(!r)return!1;try{return await ae.promises.lstat(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=je(s);return dt(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return dt(s,"binary")}async readFileBuffer(t,s=new Set){M(t,"open");let r=L(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.readFileBuffer(a,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.content}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ae.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let u=await ae.promises.readlink(i),c=this.realTargetToVirtual(r,u),f=this.resolveSymlink(r,c);return this.readFileBuffer(f,s)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);let l=this.allowSymlinks?ae.constants.O_RDONLY:ae.constants.O_RDONLY|ae.constants.O_NOFOLLOW,o=await ae.promises.open(i,l);try{let u=await o.readFile();return new Uint8Array(u)}finally{await o.close()}}catch(a){let l=a.code;if(l==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(l==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(a,t,"open")}}async writeFile(t,s,r){M(t,"write"),this.assertWritable(`write '${t}'`);let n=L(t);this.ensureParentDirs(n);let i=je(r),a=ft(s,i);this.memory.set(n,{type:"file",content:a,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){M(t,"append"),this.assertWritable(`append '${t}'`);let n=L(t),i=je(r),a=ft(s,i),l;try{l=await this.readFileBuffer(n)}catch{l=new Uint8Array(0)}let o=new Uint8Array(l.length+a.length);o.set(l),o.set(a,l.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){M(t,"stat");let r=L(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let l=this.resolveSymlink(r,n.target);return this.stat(l,s)}let a=0;return n.type==="file"&&(a=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:a,mtime:n.mtime}}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await ae.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let l=await ae.promises.readlink(i),o=this.realTargetToVirtual(r,l),u=this.resolveSymlink(r,o);return this.stat(u,s)}return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime}}catch(a){if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(a,t,"stat")}}async lstat(t){M(t,"lstat");let s=L(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ae.promises.lstat(n);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}resolveSymlink(t,s){return zt(t,s)}realTargetToVirtual(t,s){let r=$c(s,this.canonicalRoot);if(r.withinRoot){if(!Se.isAbsolute(s))return s;let n=r.relativePath;return this.mountPoint==="/"?n:`${this.mountPoint}${n}`}return r.safeName}async mkdir(t,s){M(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=L(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=It(r);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let l of this.deleted)if(l.startsWith(i)){let o=l.slice(i.length),u=o.split("/")[0];u&&!o.includes("/",u.length)&&n.add(u)}for(let[l,o]of this.memory)if(l!==s&&l.startsWith(i)){let u=l.slice(i.length),c=u.split("/")[0];c&&!n.has(c)&&!u.includes("/",1)&&r.set(c,{name:c,isFile:o.type==="file",isDirectory:o.type==="directory",isSymbolicLink:o.type==="symlink"})}let a=this.resolveRealPath_(this.toRealPath(s));if(a)try{if(!this.allowSymlinks&&(await ae.promises.lstat(a)).isSymbolicLink()){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let l=await ae.promises.readdir(a,{withFileTypes:!0});for(let o of l)!n.has(o.name)&&!r.has(o.name)&&r.set(o.name,{name:o.name,isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:o.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,t,"scandir")}return r}async resolveForReaddir(t,s=!1){let r=L(t),n=new Set,i=s,a=this.memory.get(r);for(;a&&a.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,a.target),a=this.memory.get(r)}if(a)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let o=this.resolveRealPath_(this.toRealPath(r));if(!o)return{normalized:r,outsideOverlay:!0};try{if((await ae.promises.lstat(o)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let c=await ae.promises.readlink(o),f=this.realTargetToVirtual(r,c),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){M(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,a)=>ia?1:0)}async readdirWithFileTypes(t){M(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,a)=>i.namea.name?1:0)}async rm(t,s){M(t,"rm"),this.assertWritable(`rm '${t}'`);let r=L(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let a=await this.readdir(r);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let l of a){let o=r==="/"?`/${l}`:`${r}/${l}`;await this.rm(o,s)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.memory.delete(r),this.existsOnRealFs(r)&&this.deleted.add(r)}existsOnRealFs(t){let s=this.toRealPath(t),r=this.resolveRealPathParent_(s);if(!r)return!1;try{return ae.lstatSync(r),!0}catch{return!1}}async cp(t,s,r){M(t,"cp"),M(s,"cp"),this.assertWritable(`cp '${s}'`);let n=L(t),i=L(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let l=await this.stat(n);if(l.isFile){let o=await this.readFileBuffer(n);await this.writeFile(i,o)}else if(l.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(n);for(let u of o){let c=n==="/"?`/${u}`:`${n}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(c,f,r)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){return vt(t,s)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let n=ae.readdirSync(r);for(let i of n){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let l=Se.join(r,i);ae.lstatSync(l).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){M(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=L(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let a=await this.stat(r);if(a.isFile){let l=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:l,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);M(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=L(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){M(t,"link"),M(s,"link"),this.assertWritable(`link '${s}'`);let r=L(t),n=L(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(r);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let o=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:o,mode:a.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){M(t,"readlink");let s=L(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await ae.promises.readlink(n);if(!Se.isAbsolute(i)){let a=Se.resolve(Se.dirname(n),i),l;try{l=ae.realpathSync(a)}catch{l=a}if(!Je(l,this.canonicalRoot))return Se.basename(i)}return this.realTargetToVirtual(s,i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){M(t,"realpath");let s=L(t),r=new Set,n=async l=>{let o=l==="/"?[]:l.slice(1).split("/"),u="";for(let c of o){if(u=`${u}/${c}`,r.has(u))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(u))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(u),d=0,h=40;for(;f&&f.type==="symlink"&&d=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let m=this.toRealPath(u),p=this.resolveRealPath_(m);if(p)try{if((await ae.promises.lstat(p)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let b=await ae.promises.readlink(p),v=this.realTargetToVirtual(u,b);return r.add(u),u=this.resolveSymlink(u,v),n(u)}}catch(y){if(y.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(y,t,"realpath")}else if(!this.allowSymlinks){let y=this.resolveRealPathParent_(m);if(y)try{if((await ae.promises.lstat(y)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(b){if(b.message?.includes("ENOENT")||b.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(b,t,"realpath")}}}}return u||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){M(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=L(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(n);if(a){a.mtime=r;return}let l=await this.stat(n);if(l.isFile){let o=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:o,mode:l.mode,mtime:r})}else l.isDirectory&&this.memory.set(n,{type:"directory",mode:l.mode,mtime:r})}};import*as W from"node:fs";import*as ne from"node:path";var yh=["EACCES","escaping sandbox","EFBIG"],Ln=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(t){this.root=ne.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,On(this.root,"ReadWriteFs"),this.canonicalRoot=W.realpathSync(this.root)}resolveAndValidate(t,s){let r=this.allowSymlinks?Ft(t,this.canonicalRoot):In(t,this.root,this.canonicalRoot);if(r===null)throw new Error(`EACCES: permission denied, '${s}' resolves outside sandbox`);return r}validateParent(t,s){let r=ne.dirname(t),n=this.resolveAndValidate(r,s);return ne.join(n,ne.basename(t))}toRealPath(t){let s=L(t),r=ne.join(this.root,s);return ne.resolve(r)}async readFile(t,s){let r=await this.readFileBuffer(t),n=je(s);return dt(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return dt(s,"binary")}async readFileBuffer(t){M(t,"open");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{let n=this.allowSymlinks?W.constants.O_RDONLY:W.constants.O_RDONLY|W.constants.O_NOFOLLOW,i=await W.promises.open(r,n);try{if(this.maxFileReadSize>0){let l=await i.stat();if(l.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${l.size} bytes, max ${this.maxFileReadSize})`)}let a=await i.readFile();return new Uint8Array(a)}finally{await i.close()}}catch(n){let i=n;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.code==="EISDIR")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(i.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(n,t,"open")}}async writeFile(t,s,r){M(t,"write");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t),a=je(r),l=ft(s,a),o=ne.dirname(i);try{await W.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(n,t);let u=this.allowSymlinks?0:W.constants.O_NOFOLLOW,c=W.constants.O_WRONLY|W.constants.O_CREAT|W.constants.O_TRUNC|u,f=await W.promises.open(i,c,438);try{await f.writeFile(l)}finally{await f.close()}}catch(u){if(u.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(u,t,"write")}}async appendFile(t,s,r){M(t,"append");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t),a=je(r),l=ft(s,a),o=ne.dirname(i);try{await W.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(n,t);let u=this.allowSymlinks?0:W.constants.O_NOFOLLOW,c=W.constants.O_WRONLY|W.constants.O_CREAT|W.constants.O_APPEND|u,f=await W.promises.open(i,c,438);try{await f.writeFile(l)}finally{await f.close()}}catch(u){if(u.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(u,t,"append")}}async exists(t){if(t.includes("\0"))return!1;let s=this.toRealPath(t);try{let r=this.resolveAndValidate(s,t);return await W.promises.access(r),!0}catch{return!1}}async stat(t){M(t,"stat");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{let n=await W.promises.lstat(r);if(!this.allowSymlinks&&n.isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return{isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink(),mode:n.mode,size:n.size,mtime:n.mtime}}catch(n){if(n.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(n,t,"stat")}}async lstat(t){M(t,"lstat");let s=this.toRealPath(t),r=this.validateParent(s,t);try{let n=await W.promises.lstat(r);return{isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink(),mode:n.mode,size:n.size,mtime:n.mtime}}catch(n){if(n.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(n,t,"lstat")}}async mkdir(t,s){M(t,"mkdir");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{await W.promises.mkdir(n,{recursive:s?.recursive})}catch(i){let a=i;if(a.code==="EEXIST")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.sanitizeError(i,t,"mkdir")}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){M(t,"scandir");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{if(!this.allowSymlinks&&(await W.promises.lstat(r)).isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return(await W.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,a)=>i.namea.name?1:0)}catch(n){let i=n;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(i.code==="ENOTDIR")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);this.sanitizeError(n,t,"scandir")}}async rm(t,s){M(t,"rm");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{await W.promises.rm(n,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(i){let a=i;if(a.code==="ENOENT"&&!s?.force)throw new Error(`ENOENT: no such file or directory, rm '${t}'`);if(a.code==="ENOTEMPTY")throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,s,r){M(t,"cp"),M(s,"cp");let n=this.toRealPath(t),i=this.toRealPath(s),a=this.resolveAndValidate(n,t),l=this.resolveAndValidate(i,s);try{await W.promises.cp(a,l,{recursive:r?.recursive??!1,filter:async o=>{try{if(W.lstatSync(o).isSymbolicLink()){let c=await W.promises.realpath(o).catch(()=>null);return c===null?!1:Je(c,this.canonicalRoot)}return!0}catch(u){return u.code==="ENOENT"}}})}catch(o){let u=o;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(u.code==="EISDIR")throw new Error(`EISDIR: is a directory, cp '${t}'`);this.sanitizeError(o,t,"cp")}}async mv(t,s){M(t,"mv"),M(s,"mv");let r=this.toRealPath(t),n=this.toRealPath(s),i=this.validateParent(r,t),a=this.validateParent(n,s);try{if((await W.promises.lstat(i)).isSymbolicLink()){let u=await W.promises.readlink(i),c=ne.resolve(ne.dirname(a),u),f=await W.promises.realpath(c).catch(()=>c);if(!Je(f,this.canonicalRoot))throw new Error(`EACCES: permission denied, mv '${t}' -> '${s}' would create symlink escaping sandbox`)}}catch(o){let u=o;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(u.message?.includes("EACCES")||u.message?.includes("escaping sandbox"))throw o}let l=ne.dirname(a);try{await W.promises.mkdir(l,{recursive:!0})}catch(o){this.sanitizeError(o,s,"mv")}try{await W.promises.rename(i,a)}catch(o){let u=o;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(u.code==="EXDEV"){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0});return}this.sanitizeError(o,t,"mv")}try{if(W.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await W.promises.rename(a,i),new Error(`EACCES: permission denied, mv '${t}' -> '${s}' would create symlinks escaping sandbox`)}catch(o){if(o.message?.includes("EACCES")||o.message?.includes("escaping sandbox"))throw o}}resolvePath(t,s){return vt(t,s)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,s,r){Tn(t,s,r,yh)}findEscapingSymlinks(t){let s=[];try{let r=W.readdirSync(t);for(let n of r){let i=ne.join(t,n);try{let a=W.lstatSync(i);if(a.isSymbolicLink()){let l=W.readlinkSync(i),o=ne.resolve(t,l),u;try{u=W.realpathSync(o)}catch{u=o}Je(u,this.canonicalRoot)||s.push(i)}else a.isDirectory()&&s.push(...this.findEscapingSymlinks(i))}catch{}}}catch{}return s}scanDir(t,s){let r=this.toRealPath(t),n;try{n=this.resolveAndValidate(r,t)}catch{return}try{let i=W.readdirSync(n);for(let a of i){let l=t==="/"?`/${a}`:`${t}/${a}`;s.push(l);let o=ne.join(n,a);W.lstatSync(o).isDirectory()&&this.scanDir(l,s)}}catch{}}async chmod(t,s){M(t,"chmod");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{let i=this.allowSymlinks?W.constants.O_RDONLY:W.constants.O_RDONLY|W.constants.O_NOFOLLOW,a=await W.promises.open(n,i);try{await a.chmod(s)}finally{await a.close()}}catch(i){let a=i;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);if(a.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,"chmod")}}async symlink(t,s){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);M(s,"symlink");let r=this.toRealPath(s),n=this.validateParent(r,s),i=L(s),a=L(ne.dirname(i)),l=t.startsWith("/")?L(t):L(a==="/"?`/${t}`:`${a}/${t}`),o=ne.join(this.canonicalRoot,l),u=ne.dirname(n),c=t.startsWith("/")?o:ne.relative(u,o)||".";try{await W.promises.symlink(c,n)}catch(f){if(f.code==="EEXIST")throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.sanitizeError(f,s,"symlink")}}async link(t,s){M(t,"link"),M(s,"link");let r=this.toRealPath(t),n=this.toRealPath(s),i=this.resolveAndValidate(r,t),a=this.resolveAndValidate(n,s);try{await W.promises.link(i,a)}catch(l){let o=l;if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(o.code==="EEXIST")throw new Error(`EEXIST: file already exists, link '${s}'`);if(o.code==="EPERM")throw new Error(`EPERM: operation not permitted, link '${t}'`);this.sanitizeError(l,t,"link")}}async readlink(t){M(t,"readlink");let s=this.toRealPath(t),r=this.validateParent(s,t);try{let n=await W.promises.readlink(r),i=L(t),a=ne.dirname(i),l=ne.isAbsolute(n)?n:ne.resolve(ne.dirname(r),n),o=await W.promises.realpath(l).catch(()=>l);if(Je(o,this.canonicalRoot)){let u=o.slice(this.canonicalRoot.length)||"/";return a==="/"?u.startsWith("/")?u.slice(1)||".":u:ne.relative(a,u)}return ne.basename(n)}catch(n){let i=n;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(n,t,"readlink")}}async realpath(t){M(t,"realpath");let s=this.toRealPath(t);try{this.resolveAndValidate(s,t)}catch{throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}let r;try{r=await W.promises.realpath(s)}catch(n){let i=n;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);if(i.code==="ELOOP")throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(n,t,"realpath")}if(Je(r,this.canonicalRoot))return r.slice(this.canonicalRoot.length)||"/";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}async utimes(t,s,r){M(t,"utimes");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t);try{let a=this.allowSymlinks?W.constants.O_RDONLY:W.constants.O_RDONLY|W.constants.O_NOFOLLOW,l=await W.promises.open(i,a);try{await l.utimes(s,r)}finally{await l.close()}}catch(a){let l=a;if(l.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);if(l.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(a,t,"utimes")}}};var is=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,s,r,n,i=!1,a,l){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=s,this.env=n,this.explicitCwd=i,this.signal=a,this.timeoutMs=l,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=ks(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(Ns(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener("abort",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let t={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let s=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=s.exitCode,s}finally{this.cleanupCancellation()}}async*logs(){let t=await this.resultPromise;t.stdout&&(yield{type:"stdout",data:t.stdout,timestamp:new Date}),t.stderr&&(yield{type:"stderr",data:t.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdout+t.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error("command killed"))}};var Mn=class e{bashEnv;timeoutMs;constructor(t,s){this.bashEnv=t,this.timeoutMs=s}static async create(t){let s=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");s=new rs({root:t.overlayRoot})}let r=new Ps({env:t?.env,cwd:t?.cwd,fs:s,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network,defenseInDepth:t?.defenseInDepth,python:t?.python,javascript:t?.javascript,commands:t?.commands,customCommands:t?.customCommands,fetch:t?.fetch});return new e(r,t?.timeoutMs)}async runCommand(t,s,r){let n,i,a,l,o=!1,u,c;if(typeof t=="object"){let p=t,y=[p.cmd,...p.args??[]];n=zn(y),i=p.cwd,a=p.env,l=p.signal,o=p.detached??!1,u=p.stdout,c=p.stderr}else if(Array.isArray(s)){let p=r;n=zn([t,...s]),l=p?.signal}else{n=t;let p=s;i=p?.cwd,a=p?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new is(this.bashEnv,n,f,a,d,l,this.timeoutMs);if(o)return h;let m=await h.wait();if(u){let p=await h.stdout();p&&u.write(p)}if(c){let p=await h.stderr();p&&c.write(p)}return m}async writeFiles(t){let s=this.bashEnv.getCwd();for(let[r,n]of Object.entries(t)){let i;typeof n=="string"?i=n:n.encoding==="base64"?i=Buffer.from(n.content,"base64").toString("utf-8"):i=n.content;let a=this.bashEnv.fs.resolvePath(s,r),l=a.substring(0,a.lastIndexOf("/"))||"/";l!=="/"&&await this.bashEnv.fs.mkdir(l,{recursive:!0}),await this.bashEnv.writeFile(a,i)}}async readFile(t,s){let r=await this.bashEnv.readFile(t);return s==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,s){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:s?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Wn=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,maxViolationsTotal:t.maxViolationsTotal??1e3,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let s=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(s),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.lengthr.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function Pc(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",` Type: ${e.type}`,` Path: ${e.path}`,` Message: ${e.message}`,e.executionId?` ExecutionId: ${e.executionId}`:"")}}var _i=class{plugins=[];use(t){return this.plugins.push(t),this}transform(t){let s=Ce(t),r=Object.create(null);for(let n of this.plugins){let i=n.transform({ast:s,metadata:r});s=i.ast,i.metadata&&(r=cs(r,i.metadata))}return{script:$s(s),ast:s,metadata:r}}};var xi=class{name="command-collector";transform(t){let s=new Set;return this.walkScript(t.ast,s),{ast:t.ast,metadata:{commands:[...s].sort()}}}walkScript(t,s){for(let r of t.statements)this.walkStatement(r,s)}walkStatement(t,s){for(let r of t.pipelines)this.walkPipeline(r,s)}walkPipeline(t,s){for(let r of t.commands)this.walkCommand(r,s)}walkCommand(t,s){switch(t.type){case"SimpleCommand":if(t.name){let r=this.extractName(t.name);r&&s.add(r)}t.name&&this.walkWordParts(t.name.parts,s);for(let r of t.args)this.walkWordParts(r.parts,s);for(let r of t.assignments)if(r.value&&this.walkWordParts(r.value.parts,s),r.array)for(let n of r.array)this.walkWordParts(n.parts,s);break;case"If":for(let r of t.clauses){for(let n of r.condition)this.walkStatement(n,s);for(let n of r.body)this.walkStatement(n,s)}if(t.elseBody)for(let r of t.elseBody)this.walkStatement(r,s);break;case"For":if(t.words)for(let r of t.words)this.walkWordParts(r.parts,s);for(let r of t.body)this.walkStatement(r,s);break;case"CStyleFor":for(let r of t.body)this.walkStatement(r,s);break;case"While":case"Until":for(let r of t.condition)this.walkStatement(r,s);for(let r of t.body)this.walkStatement(r,s);break;case"Case":this.walkWordParts(t.word.parts,s);for(let r of t.items)for(let n of r.body)this.walkStatement(n,s);break;case"Subshell":case"Group":for(let r of t.body)this.walkStatement(r,s);break;case"ArithmeticCommand":case"ConditionalCommand":break;case"FunctionDef":this.walkCommand(t.body,s);break}}walkWordParts(t,s){for(let r of t)switch(r.type){case"CommandSubstitution":this.walkScript(r.body,s);break;case"ProcessSubstitution":this.walkScript(r.body,s);break;case"DoubleQuoted":this.walkWordParts(r.parts,s);break;case"ParameterExpansion":r.operation&&this.walkParameterOp(r.operation,s);break}}walkParameterOp(t,s){switch(t.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":this.walkWordParts(t.word.parts,s);break;case"ErrorIfUnset":t.word&&this.walkWordParts(t.word.parts,s);break;case"PatternRemoval":this.walkWordParts(t.pattern.parts,s);break;case"PatternReplacement":this.walkWordParts(t.pattern.parts,s),t.replacement&&this.walkWordParts(t.replacement.parts,s);break;case"CaseModification":t.pattern&&this.walkWordParts(t.pattern.parts,s);break;case"Indirection":t.innerOp&&this.walkParameterOp(t.innerOp,s);break}}extractName(t){return t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}};var Ci=class{name="tee";options;counter=0;constructor(t){this.options=t}transform(t){let s=[],r=this.options.timestamp??new Date;return{ast:this.transformScript(t.ast,s,r),metadata:{teeFiles:s}}}formatTimestamp(t){return t.toISOString().replace(/:/g,"-")}generateStdoutPath(t,s,r){let n=this.formatTimestamp(r),i=String(t).padStart(3,"0");return`${this.options.outputDir}/${n}-${i}-${s}.stdout.txt`}transformScript(t,s,r){return{...t,statements:t.statements.map(n=>this.transformStatement(n,s,r))}}transformStatement(t,s,r){let n=[],i=[];for(let a=0;a0&&i.push(t.operators[a-1]);let o=this.transformPipeline(l,s,r);if(n.push(o.pipeline),o.origCmdNewIndices!==null){let u=o.origCmdNewIndices;i.push(";"),n.push(this.makePipestatusSave(u)),i.push(";"),n.push(this.makePipestatusRestore(u.length,o.negated))}}return{...t,pipelines:n,operators:i}}transformPipeline(t,s,r){if(t.commands.length<=1)return{pipeline:t,origCmdNewIndices:null,negated:!1};let n=[],i=[],a=[],l=!1;for(let o=0;o0?i:void 0},origCmdNewIndices:a,negated:t.negated}:{pipeline:t,origCmdNewIndices:null,negated:!1}}makePipestatusSave(t){return{type:"Pipeline",commands:[{type:"SimpleCommand",assignments:t.map((s,r)=>({type:"Assignment",name:`__tps${r}`,value:{type:"Word",parts:[{type:"ParameterExpansion",parameter:`PIPESTATUS[${s}]`,operation:null}]},append:!1,array:null})),name:null,args:[],redirections:[]}],negated:!1}}makePipestatusRestore(t,s){let r=[];for(let n=0;n