just-bash 3.0.2 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +86 -0
- package/dist/bin/chunks/{chunk-4J4UC7OD.js → chunk-63LSI3D6.js} +1 -1
- package/dist/bin/chunks/chunk-BKQLXMS6.js +36 -0
- package/dist/bin/{shell/chunks/chunk-J7XTZ47D.js → chunks/chunk-HZR3FOJM.js} +1 -1
- package/dist/bin/chunks/chunk-ISLENKSH.js +7 -0
- package/dist/bin/chunks/{chunk-FJABJBIW.js → chunk-RO3XCUVQ.js} +1 -1
- package/dist/bin/chunks/{flag-coverage-H6NG6ZQL.js → flag-coverage-CAST5CDE.js} +1 -1
- package/dist/bin/chunks/{jq-33GJJXTL.js → jq-3V5HDGLJ.js} +1 -1
- package/dist/bin/{shell/chunks/rg-2YWJS6TE.js → chunks/rg-DZKA632H.js} +1 -1
- package/dist/bin/{shell/chunks/xan-TSDTZVY3.js → chunks/xan-TCTFON2Q.js} +1 -1
- package/dist/bin/chunks/{yq-KU5YTNAK.js → yq-OB6PB5GY.js} +1 -1
- package/dist/bin/just-bash.js +378 -304
- package/dist/bin/shell/chunks/{chunk-4J4UC7OD.js → chunk-63LSI3D6.js} +1 -1
- package/dist/bin/shell/chunks/chunk-BKQLXMS6.js +36 -0
- package/dist/bin/{chunks/chunk-J7XTZ47D.js → shell/chunks/chunk-HZR3FOJM.js} +1 -1
- package/dist/bin/shell/chunks/chunk-ISLENKSH.js +7 -0
- package/dist/bin/shell/chunks/{chunk-FJABJBIW.js → chunk-RO3XCUVQ.js} +1 -1
- package/dist/bin/shell/chunks/{flag-coverage-H6NG6ZQL.js → flag-coverage-CAST5CDE.js} +1 -1
- package/dist/bin/shell/chunks/{jq-33GJJXTL.js → jq-3V5HDGLJ.js} +1 -1
- package/dist/bin/{chunks/rg-2YWJS6TE.js → shell/chunks/rg-DZKA632H.js} +1 -1
- package/dist/bin/{chunks/xan-TSDTZVY3.js → shell/chunks/xan-TCTFON2Q.js} +1 -1
- package/dist/bin/shell/chunks/{yq-KU5YTNAK.js → yq-OB6PB5GY.js} +1 -1
- package/dist/bin/shell/shell.js +383 -309
- package/dist/bundle/browser.js +580 -581
- package/dist/bundle/chunks/{chunk-DJ7QC6LC.js → chunk-6Y4TGEZL.js} +1 -1
- package/dist/bundle/chunks/chunk-J3LJZWL2.js +6 -0
- package/dist/bundle/chunks/{chunk-AFQAPVZ3.js → chunk-JA7M2FXG.js} +1 -1
- package/dist/bundle/chunks/chunk-JNYYVLEL.js +35 -0
- package/dist/bundle/chunks/{chunk-EUCNMMRD.js → chunk-QM4DZQWX.js} +1 -1
- package/dist/bundle/chunks/{flag-coverage-TRYUZMPS.js → flag-coverage-OHLSWDU5.js} +1 -1
- package/dist/bundle/chunks/{jq-3FAAQVR6.js → jq-OPEF5OPR.js} +1 -1
- package/dist/bundle/chunks/{rg-N5WLPMSA.js → rg-EBMD72T4.js} +1 -1
- package/dist/bundle/chunks/{xan-U6654PZR.js → xan-LKYWG2QQ.js} +1 -1
- package/dist/bundle/chunks/{yq-ZBXLBSXV.js → yq-TVZ7R3O7.js} +1 -1
- package/dist/bundle/index.cjs +755 -756
- package/dist/bundle/index.js +382 -308
- package/dist/sandbox/Sandbox.d.ts +33 -2
- package/package.json +1 -1
- package/dist/bin/chunks/chunk-GXX3QUMM.js +0 -34
- package/dist/bin/chunks/chunk-LMA4D2KK.js +0 -7
- package/dist/bin/chunks/chunk-PDS5TEMS.js +0 -80
- package/dist/bin/chunks/expansion-PCODPDNZ.js +0 -3
- package/dist/bin/shell/chunks/chunk-GXX3QUMM.js +0 -34
- package/dist/bin/shell/chunks/chunk-LMA4D2KK.js +0 -7
- package/dist/bin/shell/chunks/chunk-PDS5TEMS.js +0 -80
- package/dist/bin/shell/chunks/expansion-PCODPDNZ.js +0 -3
- package/dist/bundle/chunks/chunk-LZUPLYFM.js +0 -6
- package/dist/bundle/chunks/chunk-STFC2ZJT.js +0 -79
- package/dist/bundle/chunks/chunk-Z3KJQD7F.js +0 -33
- package/dist/bundle/chunks/expansion-CDGKP4VC.js +0 -2
package/dist/bundle/index.js
CHANGED
|
@@ -1,158 +1,232 @@
|
|
|
1
1
|
import{createRequire} from"node:module";const require=createRequire(import.meta.url);
|
|
2
|
-
import{B as cn,C as un,D as de,E as et,F as se,G as ke,H as Xt,I as fn,J as L,K as dn,L as hn,M as xe,N as Zs,O as Yt,P as H,a as en,b as zs,c as tn,d as Gt,e as ee,f as B,g as fe,h as ne,i as Oe,j as He,k as Vs,l as Kt,m as sn,n as Bs,o as rn,p as $e,q as We,r as nn,s as on,t as js,u as Us,v as Ze,w as an,x as ln,y as Ae,z as Hs}from"./chunks/chunk-STFC2ZJT.js";import{a as Fe,b as Me,c as Ee}from"./chunks/chunk-WNH3HOQA.js";import{c as Ws}from"./chunks/chunk-HBVMHTO5.js";import{a as Wt,b as zt}from"./chunks/chunk-SY4HAUHP.js";import{a as Ms}from"./chunks/chunk-L2UW7DWF.js";import{a as Ue,b as be,c as Ct}from"./chunks/chunk-DLL7UR66.js";import{a as _t,b as Jr}from"./chunks/chunk-KAPG5ONA.js";import{a as Ve,b as me}from"./chunks/chunk-VACKIICN.js";import{a as kt}from"./chunks/chunk-7CSMHFIJ.js";import{a as At,b as Vt,c as lo,d as Be,e as co,f as Bt,g as uo,h as jt,i as Fs,j as fo,k as ho}from"./chunks/chunk-XEKXHOPO.js";import{a as ye,b as ge,c as ue,d as we,e as Yr,f as j,g as Je,h as Ut,i as Ht,j as Qr,k as J,l as Zt,m as je,n as qt,o as ve}from"./chunks/chunk-SAI2SPQQ.js";import"./chunks/chunk-STHBFACM.js";import{a as Le}from"./chunks/chunk-FOCWZZDE.js";import{a as Ie}from"./chunks/chunk-W5DWRFSU.js";import{a as Ls}from"./chunks/chunk-BZUGFHVS.js";var tt=[{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-N5WLPMSA.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-3FAAQVR6.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__)&&(tt.push({name:"tar",load:async()=>(await import("./chunks/tar-WIZ3PDF4.js")).tarCommand}),tt.push({name:"yq",load:async()=>(await import("./chunks/yq-ZBXLBSXV.js")).yqCommand}),tt.push({name:"xan",load:async()=>(await import("./chunks/xan-U6654PZR.js")).xanCommand}),tt.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-UE3PJTDQ.js")).sqlite3Command}));var Qt=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Qt.push({name:"python3",load:async()=>(await import("./chunks/python3-JPCH6LLN.js")).python3Command}),Qt.push({name:"python",load:async()=>(await import("./chunks/python3-JPCH6LLN.js")).pythonCommand}));var Jt=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Jt.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-SR6IMNWM.js")).jsExecCommand}),Jt.push({name:"node",load:async()=>(await import("./chunks/js-exec-SR6IMNWM.js")).nodeStubCommand}));var mn=[{name:"curl",load:async()=>(await import("./chunks/curl-PAWGO3EH.js")).curlCommand}],pn=new Map;function es(e){return{name:e.name,async execute(t,s){let r=pn.get(e.name);if(r||(r=await me.runTrustedAsync(()=>e.load()),pn.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-TRYUZMPS.js");n(s.coverage,e.name,t)}return r.execute(t,s)}}}function po(){return tt.map(e=>e.name)}function mo(){return mn.map(e=>e.name)}function yn(e){return(e?tt.filter(s=>e.includes(s.name)):tt).map(es)}function gn(){return mn.map(es)}function yo(){return Qt.map(e=>e.name)}function wn(){return Qt.map(es)}function go(){return Jt.map(e=>e.name)}function vn(){return Jt.map(es)}function bn(e){return"load"in e&&typeof e.load=="function"}function wo(e,t){return{name:e,trusted:!0,execute:t}}function En(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 O(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 x(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}function st(e){let t=O(e);if(t==="/")return"/";let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}function qe(e,t){if(t.startsWith("/"))return O(t);let s=e==="/"?`/${t}`:`${e}/${t}`;return O(s)}function Ge(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function ct(e,t){if(t.startsWith("/"))return O(t);let s=st(e);return O(Ge(s,t))}var ut=new TextEncoder;function vo(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var ze=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):vo(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}ensureParentDirs(t){let s=st(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){x(t,"write");let i=O(t);this.ensureParentDirs(i);let o=Ee(r),a=Fe(s,o);this.data.set(i,{type:"file",content:a,mode:n?.mode??420,mtime:n?.mtime??new Date})}writeFileLazy(t,s,r){x(t,"write");let n=O(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"?ut.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=Ee(s);return Me(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return Me(s,"binary")}async readFileBuffer(t){x(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:ut.encode(n.content)}return r.content instanceof Uint8Array?r.content:ut.encode(r.content)}async writeFile(t,s,r){this.writeFileSync(t,s,r)}async appendFile(t,s,r){x(t,"append");let n=O(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let o=Ee(r),a=Fe(s,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(n,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:ut.encode("content"in l?l.content:""),u=new Uint8Array(c.length+a.length);u.set(c),u.set(a,c.length),this.data.set(n,{type:"file",content:u,mode:l.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){x(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=ut.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){x(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=ut.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=O(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];n=`${n}/${a}`;let l=this.data.get(n),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=ct(n,l.target),l=this.data.get(n),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=O(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let o of r){n=`${n}/${o}`;let a=this.data.get(n),l=0,c=40;for(;a&&a.type==="symlink"&&l<c;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=ct(n,a.target),a=this.data.get(n),l++}if(l>=c)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){x(t,"mkdir");let r=O(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=st(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){x(t,"scandir");let s=O(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=ct(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==s&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(t,s){x(t,"rm");let r=O(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of i){let a=Ge(r,o);await this.rm(a,s)}}}this.data.delete(r)}async cp(t,s,r){x(t,"cp"),x(s,"cp");let n=O(t),i=O(s),o=this.data.get(n);if(!o)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.data.set(i,{...o,content:a})}else this.data.set(i,{...o});else if(o.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(n);for(let l of a){let c=Ge(n,l),u=Ge(i,l);await this.cp(c,u,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 qe(t,s)}async chmod(t,s){x(t,"chmod");let r=O(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){x(s,"symlink");let r=O(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){x(t,"link"),x(s,"link");let r=O(t),n=O(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 o=i;"lazy"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(n),this.data.set(n,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(t){x(t,"readlink");let s=O(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){x(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){x(t,"utimes");let n=O(t),i=this.resolvePathWithSymlinks(n),o=this.data.get(i);if(!o)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);o.mtime=r}};function bo(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function Eo(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 $o(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 So(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${en}
|
|
2
|
+
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<r.length-1;a++){let l=r[a];n=`${n}/${l}`;let o=this.data.get(n),u=0,c=40;for(;o&&o.type==="symlink"&&u<c;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=zt(n,o.target),o=this.data.get(n),u++}if(u>=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;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=zt(n,l.target),l=this.data.get(n),o++}if(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.name<o.name?-1:l.name>o.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
|
|
3
|
+
State: R (running)
|
|
4
|
+
Pid: ${t}
|
|
5
|
+
PPid: ${s}
|
|
6
|
+
Uid: ${r} ${r} ${r} ${r}
|
|
7
|
+
Gid: ${n} ${n} ${n} ${n}
|
|
8
|
+
`}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}
|
|
3
9
|
`),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
|
|
4
|
-
`),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`,
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
`),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(;r<s&&n>0;){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!(o<s&&e[o]===")")}if(n===0)return!1;r++;continue}if(n===1&&(l==="|"&&r+1<s&&e[r+1]==="|"||l==="&"&&r+1<s&&e[r+1]==="&"||l==="|"&&r+1<s&&e[r+1]!=="|"))return!0;r++}return!1}function Hn(e,t){let s="",r=t,n=i=>i===" "||i===" "||i===`
|
|
11
|
+
`||i===";"||i==="&"||i==="|"||i==="<"||i===">"||i==="("||i===")";for(;r<e.length;){let i=e[r];if(i==="'"){for(r++;r<e.length&&e[r]!=="'";)s+=e[r],r++;r<e.length&&r++;continue}if(i==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length&&r++,s+=e[r],r++;r<e.length&&r++;continue}if(i==="\\"&&r+1<e.length){s+=e[r+1],r+=2;continue}if(n(i))break;s+=i,r++}return{delim:s,endPos:r}}function Gc(e,t,s){let r=t+1;for(let{delim:n,stripTabs:i}of s)for(;;){if(r>=e.length)return e.length;let a=e.indexOf(`
|
|
12
|
+
`,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(;a<e.length&&i>0;){let b=e[a];if(l)b==="'"&&(l=!1);else if(o)b==="\\"&&a+1<e.length?a++:b==='"'&&(o=!1);else{if(b==="("&&e[a+1]==="("?h++:b===")"&&e[a+1]===")"&&h>0&&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===`
|
|
13
|
+
`&&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+1<e.length?(a++,f=""):/[a-zA-Z_]/.test(b)?f+=b:(f==="case"?(u++,c=!1):f==="in"&&u>0?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+1<e.length&&e[a+1]===";"&&(c=!0))}i>0&&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&&e[a]!=="`";)if(e[a]==="\\"){let c=e[a+1];c==="$"||c==="`"||c==="\\"||c===`
|
|
14
|
+
`||s&&c==='"'?(c!==`
|
|
15
|
+
`&&(l+=c),a+=2):(l+=e[a],a++)}else l+=e[a],a++;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;n++)if(s[n]==="[")r++;else if(s[n]==="]"&&(r--,r===0))break;if(r!==0||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<e.length;s++){let r=e[s];if(r==="[")t++;else if(r==="]")t--;else{if(t===0&&r==="=")return s;if(t===0&&r==="+"&&e[s+1]==="=")return s+1}}return-1}var Qc=[[";",";","&",g.SEMI_SEMI_AND],["<","<","<",g.TLESS],["&",">",">",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===`
|
|
16
|
+
`||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.pos<s;){if(n.length>0&&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(;r<s;){let a=t[r];if(a===" "||a===" ")r++,n++;else if(a==="\\"&&t[r+1]===`
|
|
17
|
+
`)r+=2,i++,n=1;else break}this.pos=r,this.column=n,this.line=i}nextToken(){let t=this.input,s=this.pos,r=this.line,n=this.column,i=t[s],a=t[s+1],l=t[s+2];if(i==="#"&&this.dparenDepth===0)return this.readComment(s,r,n);if(i===`
|
|
18
|
+
`)return this.pos=s+1,this.line++,this.column=1,{type:g.NEWLINE,value:`
|
|
19
|
+
`,start:s,end:s+1,line:r,column:n};if(i==="<"&&a==="<"&&l==="-")return this.pos=s+3,this.column=n+3,this.registerHeredocFromLookahead(!0),this.makeToken(g.DLESSDASH,"<<-",s,r,n);for(let[u,c,f,d]of Qc)if(i===u&&a===c&&l===f)return this.pos=s+3,this.column=n+3,this.makeToken(d,u+c+f,s,r,n);if(i==="<"&&a==="<")return this.pos=s+2,this.column=n+2,this.registerHeredocFromLookahead(!1),this.makeToken(g.DLESS,"<<",s,r,n);if(i==="("&&a==="(")return this.dparenDepth>0?(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!==`
|
|
20
|
+
`&&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!==`
|
|
21
|
+
`?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&&(s[n]===" "||s[n]===" ");)n++;if(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&&/[a-zA-Z0-9_\-.]/.test(s[o]);)o++;if(o===n)return l;let u=o;for(;u<r&&(s[u]===" "||s[u]===" ");)u++;if(u>=r)return!1;let c=s[u];if(c==="="&&s[u+1]!=="="||c===`
|
|
22
|
+
`||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<r&&s[f]!==`
|
|
23
|
+
`;){if(s[f]===")")return!0;f++}return!1}if(c===")"){let f=u+1;for(;f<r&&(s[f]===" "||s[f]===" ");)f++;if(s[f]==="|"&&s[f+1]==="|"||s[f]==="&"&&s[f+1]==="&"||s[f]===";"||s[f]==="|"&&s[f+1]!=="|")return!0}return!1}makeToken(t,s,r,n,i){return{type:t,value:s,start:r,end:this.pos,line:n,column:i}}readComment(t,s,r){let n=this.input,i=n.length,a=this.pos;for(;a<i&&n[a]!==`
|
|
24
|
+
`;)a++;let l=n.slice(t,a);return this.pos=a,this.column=r+(a-t),{type:g.COMMENT,value:l,start:t,end:a,line:s,column:r}}readWord(t,s,r){let n=this.input,i=n.length,a=this.pos,l=a;for(;a<i;){let E=n[a];if(E===" "||E===" "||E===`
|
|
25
|
+
`||E===";"||E==="&"||E==="|"||E==="("||E===")"||E==="<"||E===">"||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===`
|
|
26
|
+
`||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(;a<i;){let E=n[a];if(!h&&!m){if(E==="("&&c.length>0&&"@*+?!".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+1<i?n[a+1]:"";if(w==="^"||w==="!"){c+=E,a++,o++;continue}b=1,c+=E,a++,o++;continue}}else if(E==="["&&b>0){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===`
|
|
27
|
+
`)break;c+=E,a++,o++;continue}if(E===" "||E===" "||E===`
|
|
28
|
+
`||E===";"||E==="&"||E==="|"||E==="("||E===")"||E==="<"||E===">")break}if(E==="$"&&a+1<i&&n[a+1]==="'"&&!h&&!m){for(c+="$'",a+=2,o+=2;a<i&&n[a]!=="'";)n[a]==="\\"&&a+1<i?(c+=n[a]+n[a+1],a+=2,o+=2):(c+=n[a],a++,o++);a<i&&(c+="'",a++,o++);continue}if(E==="$"&&a+1<i&&n[a+1]==='"'&&!h&&!m){a++,o++,m=!0,f=!0,c===""&&(p=!0),a++,o++;continue}if(E==="'"&&!m){if(h)if(h=!1,!p||y)c+=E;else{let w=a+1<i?n[a+1]:"";w&&!Qi(w)&&w!=="'"&&(w==='"'?(y=!0,c+=E,d=!1,f=!1):(y=!0,c+=E))}else h=!0,p&&!y?(d=!0,f=!0):c+=E;a++,o++;continue}if(E==='"'&&!h){if(m)if(m=!1,!p||y)c+=E;else{let w=a+1<i?n[a+1]:"";w&&!Qi(w)&&w!=='"'&&(w==="'"?(y=!0,c+=E,d=!1,f=!1):(y=!0,c+=E))}else m=!0,p&&!y?f=!0:c+=E;a++,o++;continue}if(E==="\\"&&!h&&a+1<i){let w=n[a+1];if(w===`
|
|
29
|
+
`){a+=2,u++,o=1;continue}if(m){if(w==='"'||w==="\\"||w==="$"||w==="`"||w===`
|
|
30
|
+
`){if(w===`
|
|
31
|
+
`){a+=2,o=1,u++;continue}c+=E+w,a+=2,o+=2;continue}}else{w==="\\"||w==='"'||w==="'"||w==="`"||w==="*"||w==="?"||w==="["||w==="]"||w==="("||w===")"||w==="$"||w==="-"||w==="."||w==="^"||w==="+"||w==="{"||w==="}"?c+=E+w:c+=w,a+=2,o+=2;continue}}if(E==="$"&&a+1<i&&n[a+1]==="("&&!h){c+=E,a++,o++,c+=n[a],a++,o++;let w=1,S=!1,A=!1,$=0,R=!1,C="",F=[],k=n[a]==="("&&!this.dollarDparenIsSubshell(a),x=k?1:0;for(;w>0&&a<i;){let D=n[a];if(c+=D,S)D==="'"&&(S=!1);else if(A)D==="\\"&&a+1<i?(c+=n[a+1],a++,o++):D==='"'&&(A=!1);else{if(D==="("&&n[a+1]==="("?x++:D===")"&&n[a+1]===")"&&x>0&&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===`
|
|
32
|
+
`&&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(`
|
|
33
|
+
`,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&&u++;let ge=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+1<i)c+=n[a+1],a++,o++,C="";else if(D==="$"&&a+1<i&&n[a+1]==="{"){a++,o++,c+=n[a],a++,o++;let P=1,O=!1,z=!1;for(;P>0&&a<i;){let U=n[a];if(U==="\\"&&a+1<i&&!O){c+=U,a++,o++,c+=n[a],a++,o++;continue}c+=U,O?U==="'"&&(O=!1):z?U==='"'&&(z=!1):U==="'"?O=!0:U==='"'?z=!0:U==="{"?P++:U==="}"&&P--,U===`
|
|
34
|
+
`?(u++,o=0):o++,a++}C="";continue}else if(D==="#"&&!k&&(C===""||/\s/.test(n[a-1]||""))){for(;a+1<i&&n[a+1]!==`
|
|
35
|
+
`;)a++,o++,c+=n[a];C=""}else/[a-zA-Z_]/.test(D)?C+=D:(C==="case"?($++,R=!1):C==="in"&&$>0?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+1<i&&n[a+1]===";"||a+1<i&&n[a+1]==="&")&&(R=!0))}D===`
|
|
36
|
+
`&&(u++,o=0,C=""),a++,o++}continue}if(E==="$"&&a+1<i&&n[a+1]==="["&&!h){c+=E,a++,o++,c+=n[a],a++,o++;let w=1;for(;w>0&&a<i;){let S=n[a];c+=S,S==="["?w++:S==="]"?w--:S===`
|
|
37
|
+
`&&(u++,o=0),a++,o++}continue}if(E==="$"&&a+1<i&&n[a+1]==="{"&&!h){c+=E,a++,o++,c+=n[a],a++,o++;let w=1,S=!1,A=!1,$=u,R=o,C=u,F=o;for(;w>0&&a<i;){let k=n[a];if(k==="\\"&&a+1<i&&n[a+1]===`
|
|
38
|
+
`){a+=2,u++,o=1;continue}if(k==="\\"&&a+1<i&&!S){c+=k,a++,o++,c+=n[a],a++,o++;continue}c+=k,S?k==="'"&&(S=!1):A?k==='"'&&(A=!1):k==="'"?(S=!0,$=u,R=o):k==='"'?(A=!0,C=u,F=o):k==="{"?w++:k==="}"&&w--,k===`
|
|
39
|
+
`&&(u++,o=0),a++,o++}if(S)throw new At("unexpected EOF while looking for matching `''",$,R);if(A)throw new At("unexpected EOF while looking for matching `\"'",C,F);continue}if(E==="$"&&a+1<i&&!h){let w=n[a+1];if(w==="#"||w==="?"||w==="$"||w==="!"||w==="@"||w==="*"||w==="-"||w>="0"&&w<="9"){c+=E+w,a+=2,o+=2;continue}}if(E==="`"&&!h){for(c+=E,a++,o++;a<i&&n[a]!=="`";){let w=n[a];c+=w,w==="\\"&&a+1<i&&(c+=n[a+1],a++,o++),w===`
|
|
40
|
+
`&&(u++,o=0),a++,o++}a<i&&(c+=n[a],a++,o++);continue}c+=E,a++,E===`
|
|
41
|
+
`?(u++,o=1):o++}if(this.pos=a,this.column=o,this.line=u,y&&p&&(c=n[t]+c,f=!1,d=!1),h||m){let E=h?"'":'"';throw new At(`unexpected EOF while looking for matching \`${E}'`,s,r)}if(!p&&c.length>=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;S<E.length;S++){if(E[S]==='"'){w=!0;break}E[S]==="\\"&&S+1<E.length&&S++}w||(c=E,f=!0,d=!1)}}if(c==="")return{type:g.WORD,value:"",start:t,end:a,line:s,column:r,quoted:f,singleQuoted:d};let v=Zi.get(c);if(!f&&v!==void 0)return{type:v,value:c,start:t,end:a,line:s,column:r};if(!p){let E=Hi(c);if(E>0&&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.pos<this.input.length;){let a="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
|
|
42
|
+
`;)a+=this.input[this.pos],this.pos++,this.column++;if((t.stripTabs?a.replace(/^\t+/,""):a)===t.delimiter){this.pos<this.input.length&&this.input[this.pos]===`
|
|
43
|
+
`&&(this.pos++,this.line++,this.column=1);break}if(i+=a,i.length>this.maxHeredocSize)throw new At(`Heredoc size limit exceeded (${this.maxHeredocSize} bytes)`,r,n);this.pos<this.input.length&&this.input[this.pos]===`
|
|
44
|
+
`&&(i+=`
|
|
45
|
+
`,this.pos++,this.line++,this.column=1)}this.tokens.push({type:g.HEREDOC_CONTENT,value:i,start:s,end:this.pos,line:r,column:n})}}addPendingHeredoc(t,s,r){this.pendingHeredocs.push({delimiter:t,stripTabs:s,quoted:r})}registerHeredocFromLookahead(t){let s=this.pos,r=this.column;for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]===" ");)this.pos++,this.column++;let n="",i=!1;for(;this.pos<this.input.length;){let a=this.input[this.pos];if(/[\s;<>&|()]/.test(a))break;if(a==="'"||a==='"'){i=!0;let l=a;for(this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]!==l;)n+=this.input[this.pos],this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]===l&&(this.pos++,this.column++)}else a==="\\"?(i=!0,this.pos++,this.column++,this.pos<this.input.length&&(n+=this.input[this.pos],this.pos++,this.column++)):(n+=a,this.pos++,this.column++)}this.pos=s,this.column=r,n&&this.pendingHeredocs.push({delimiter:n,stripTabs:t,quoted:i})}isWordCharFollowing(t){if(t>=this.input.length)return!1;let s=this.input[t];return!(s===" "||s===" "||s===`
|
|
46
|
+
`||s===";"||s==="&"||s==="|"||s==="("||s===")"||s==="<"||s===">")}readWordWithBraceExpansion(t,s,r){let n=this.input,i=n.length,a=t,l=r;for(;a<i;){let u=n[a];if(u===" "||u===" "||u===`
|
|
47
|
+
`||u===";"||u==="&"||u==="|"||u==="("||u===")"||u==="<"||u===">")break;if(u==="{"){if(this.scanBraceExpansion(a)!==null){let f=1;for(a++,l++;a<i&&f>0;)n[a]==="{"?f++:n[a]==="}"&&f--,a++,l++;continue}a++,l++;continue}if(u==="}"){a++,l++;continue}if(u==="$"&&a+1<i&&n[a+1]==="("){a++,l++,a++,l++;let c=1;for(;c>0&&a<i;)n[a]==="("?c++:n[a]===")"&&c--,a++,l++;continue}if(u==="$"&&a+1<i&&n[a+1]==="{"){a++,l++,a++,l++;let c=1;for(;c>0&&a<i;)n[a]==="{"?c++:n[a]==="}"&&c--,a++,l++;continue}if(u==="`"){for(a++,l++;a<i&&n[a]!=="`";)n[a]==="\\"&&a+1<i?(a+=2,l+=2):(a++,l++);a<i&&(a++,l++);continue}a++,l++}let o=n.slice(t,a);return this.pos=a,this.column=l,{type:g.WORD,value:o,start:t,end:a,line:s,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(t){let s=this.input,r=s.length,n=t+1,i=1,a=!1,l=!1;for(;n<r&&i>0;){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+1<r&&s[n+1]===".")l=!0,n+=2;else{if(o===" "||o===" "||o===`
|
|
48
|
+
`||o===";"||o==="&"||o==="|")return null;n++}}return i===0&&(a||l)?s.slice(t,n):null}scanLiteralBraceWord(t){let s=this.input,r=s.length,n=t+1,i=1;for(;n<r&&i>0;){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===`
|
|
49
|
+
`||a===";"||a==="&"||a==="|")return null;n++}}return null}scanExtglobPattern(t){let s=this.input,r=s.length,n=t+1,i=1;for(;n<r&&i>0;){let a=s[n];if(a==="\\"&&n+1<r){n+=2;continue}if("@*+?!".includes(a)&&n+1<r&&s[n+1]==="("){n++,i++,n++;continue}if(a==="(")i++,n++;else if(a===")")i--,n++;else{if(a===`
|
|
50
|
+
`)return null;n++}}return i===0?{content:s.slice(t,n),end:n}:null}scanFdVariable(t){let s=this.input,r=s.length,n=t+1,i=n;for(;n<r;){let c=s[n];if(n===i){if(!(c>="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<r?s[n+1]:"";return l===">"||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(;n<r&&i>0;){let u=s[n];if(a){u==="'"&&(a=!1),u===`
|
|
51
|
+
`&&(o=!0),n++;continue}if(l){if(u==="\\"){n+=2;continue}u==='"'&&(l=!1),u===`
|
|
52
|
+
`&&(o=!0),n++;continue}if(u==="'"){a=!0,n++;continue}if(u==='"'){l=!0,n++;continue}if(u==="\\"){n+=2;continue}if(u===`
|
|
53
|
+
`&&(o=!0),u==="("){i++,n++;continue}if(u===")"){if(i--,i===1){let c=n+1;if(c<r&&s[c]===")")return!1;let f=c,d=!1;for(;f<r&&(s[f]===" "||s[f]===" "||s[f]===`
|
|
54
|
+
`);)d=!0,f++;if(d&&f<r&&s[f]===")"||o)return!0}if(i===0)return!1;n++;continue}n++}return!1}dparenClosesWithSpacedParens(t){let s=this.input,r=s.length,n=t,i=2,a=!1,l=!1;for(;n<r&&i>0;){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<r&&s[u]===")")return!1;let c=u,f=!1;for(;c<r&&(s[c]===" "||s[c]===" "||s[c]===`
|
|
55
|
+
`);)f=!0,c++;if(f&&c<r&&s[c]===")")return!0}if(i===0)return!1;n++;continue}if(i===1&&(o==="|"&&n+1<r&&s[n+1]==="|"||o==="&"&&n+1<r&&s[n+1]==="&"||o==="|"&&n+1<r&&s[n+1]!=="|"))return!0;n++}return!1}};var Qn=1e6,Kn=1e5,Ki=1e6,Xn=200,Xi=new Set([g.LESS,g.GREAT,g.DLESS,g.DGREAT,g.LESSAND,g.GREATAND,g.LESSGREAT,g.DLESSDASH,g.CLOBBER,g.TLESS,g.AND_GREAT,g.AND_DGREAT]),Yi=new Set([g.LESS,g.GREAT,g.DLESS,g.DGREAT,g.LESSAND,g.GREATAND,g.LESSGREAT,g.DLESSDASH,g.CLOBBER,g.TLESS]),Ji=new Set([g.LESS,g.GREAT,g.DLESS,g.DGREAT,g.LESSAND,g.GREATAND,g.LESSGREAT,g.DLESSDASH,g.CLOBBER,g.TLESS,g.AND_GREAT,g.AND_DGREAT]),Ee=class extends Error{line;column;token;constructor(t,s,r,n=void 0){super(`Parse error at ${s}:${r}: ${t}`),this.line=s,this.column=r,this.token=n,this.name="ParseException"}};function ce(e,t){for(;t<e.length;){if(e[t]==="\\"&&e[t+1]===`
|
|
56
|
+
`){t+=2;continue}if(/\s/.test(e[t])){t++;continue}break}return t}var Fs=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];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(;n<s.length-1&&i>0;)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&&e[s]!=="'";)if(e[s]==="\\"&&s+1<e.length){let i=e[s+1];switch(i){case"n":r+=`
|
|
57
|
+
`;break;case"t":r+=" ";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"'":r+="'";break;default:r+=i}s+=2}else r+=e[s],s++;e[s]==="'"&&s++;let n=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(n)?0:n},pos:s}}function sa(e,t){if(e.slice(t,t+2)!=='$"')return null;let s=t+2,r="";for(;s<e.length&&e[s]!=='"';)e[s]==="\\"&&s+1<e.length?(r+=e[s+1],s+=2):(r+=e[s],s++);e[s]==='"'&&s++;let n=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(n)?0:n},pos:s}}function Jc(e){let t="",s=0;for(;s<e.length;)if(e[s]==='"'){for(s++;s<e.length&&e[s]!=='"';)e[s]==="\\"&&s+1<e.length?(t+=e[s+1],s+=2):(t+=e[s],s++);s<e.length&&s++}else t+=e[s],s++;return t}function Y(e,t){let s=Jc(t),{expr:r,pos:n}=We(e,s,0),i=ce(s,n);if(i<s.length){let a=t.slice(i).trim();if(a)return{type:"ArithmeticExpression",originalText:t,expression:{type:"ArithSyntaxError",errorToken:a,message:`${a}: syntax error: invalid arithmetic operator (error token is "${a}")`}}}return{type:"ArithmeticExpression",expression:r,originalText:t}}function _e(e,t){return{expr:{type:"ArithSyntaxError",errorToken:e,message:`syntax error: operand expected (error token is "${e}")`},pos:t}}function xe(e,t){return ce(e,t)>=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(;n<t.length&&u>0;)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(;n<t.length&&t[n]!=="`";)n++;let c=t.slice(u,n);return t[n]==="`"&&n++,{expr:{type:"ArithCommandSubst",command:c},pos:n}}if(t[n]==="("){n++;let{expr:u,pos:c}=We(e,t,n);return n=ce(t,c),t[n]===")"&&n++,{expr:{type:"ArithGroup",expression:u},pos:n}}if(t[n]==="'"){n++;let u="";for(;n<t.length&&t[n]!=="'";)u+=t[n],n++;t[n]==="'"&&n++;let c=Number.parseInt(u,10);return{expr:{type:"ArithSingleQuote",content:u,value:Number.isNaN(c)?0:c},pos:n}}if(t[n]==='"'){n++;let u="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length?(u+=t[n+1],n+=2):(u+=t[n],n++);t[n]==='"'&&n++;let c=u.trim();if(!c)return{expr:{type:"ArithNumber",value:0},pos:n};let{expr:f}=We(e,c,0);return{expr:f,pos:n}}if(/[0-9]/.test(t[n])){let u="",c=!1,f=!1;for(;n<t.length;){let h=t[n];if(c)if(/[0-9a-zA-Z@_]/.test(h))u+=h,n++;else break;else if(h==="#")c=!0,u+=h,n++;else if(u==="0"&&(h==="x"||h==="X")&&n+1<t.length&&/[0-9a-fA-F]/.test(t[n+1]))f=!0,u+=h,n++;else if(f&&/[0-9a-fA-F]/.test(h))u+=h,n++;else if(!f&&/[0-9]/.test(h))u+=h,n++;else break}if(n<t.length&&/[a-zA-Z_]/.test(t[n])){let h=u;for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)h+=t[n],n++;return{expr:{type:"ArithSyntaxError",errorToken:h,message:`${h}: value too great for base (error token is "${h}")`},pos:n}}if(t[n]==="."&&/[0-9]/.test(t[n+1]))throw new se(`${u}.${t[n+1]}...: syntax error: invalid arithmetic operator`);if(t[n]==="["){let h=t.slice(n).trim();return{expr:{type:"ArithNumberSubscript",number:u,errorToken:h},pos:t.length}}return{expr:{type:"ArithNumber",value:us(u)},pos:n}}if(t[n]==="$"&&t[n+1]==="{"){let u=n+2,c=1,f=u;for(;f<t.length&&c>0;)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<t.length&&/[0-9a-zA-Z@_]/.test(t[m]);)m++;let p=t.slice(h+1,m);return{expr:{type:"ArithDynamicBase",baseExpr:d,value:p},pos:m}}if(/[0-9]/.test(t[h])||t[h]==="x"||t[h]==="X"){let m=h;if(t[h]==="x"||t[h]==="X")for(m++;m<t.length&&/[0-9a-fA-F]/.test(t[m]);)m++;else for(;m<t.length&&/[0-9]/.test(t[m]);)m++;let p=t.slice(h,m);return{expr:{type:"ArithDynamicNumber",prefix:d,suffix:p},pos:m}}return n=h,{expr:{type:"ArithBracedExpansion",content:d},pos:n}}if(t[n]==="$"&&n+1<t.length&&/[0-9]/.test(t[n+1])){n++;let u="";for(;n<t.length&&/[0-9]/.test(t[n]);)u+=t[n],n++;return{expr:{type:"ArithVariable",name:u,hasDollarPrefix:!0},pos:n}}if(t[n]==="$"&&n+1<t.length&&/[*@#?\-!$]/.test(t[n+1])){let u=t[n+1];return n+=2,{expr:{type:"ArithSpecialVar",name:u},pos:n}}let o=!1;if(t[n]==="$"&&n+1<t.length&&/[a-zA-Z_]/.test(t[n+1])&&(o=!0,n++),n<t.length&&/[a-zA-Z_]/.test(t[n])){let u="";for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)u+=t[n],n++;if(t[n]==="["&&!r){n++;let c;if(t[n]==="'"||t[n]==='"'){let d=t[n];for(n++,c="";n<t.length&&t[n]!==d;)c+=t[n],n++;t[n]===d&&n++,n=ce(t,n),t[n]==="]"&&n++}let f;if(c===void 0){let{expr:d,pos:h}=We(e,t,n);f=d,n=h,t[n]==="]"&&n++}if(n=ce(t,n),t[n]==="["&&f)return{expr:{type:"ArithDoubleSubscript",array:u,index:f},pos:n};if(!r){for(let d of Fs)if(t.slice(n,n+d.length)===d&&t.slice(n,n+d.length+1)!=="=="){n+=d.length;let{expr:h,pos:m}=fs(e,t,n);return{expr:{type:"ArithAssignment",operator:d,variable:u,subscript:f,stringKey:c,value:h},pos:m}}}return{expr:{type:"ArithArrayElement",array:u,index:f,stringKey:c},pos:n}}if(n=ce(t,n),!r){for(let c of Fs)if(t.slice(n,n+c.length)===c&&t.slice(n,n+c.length+1)!=="=="){n+=c.length;let{expr:f,pos:d}=fs(e,t,n);return{expr:{type:"ArithAssignment",operator:c,variable:u,value:f},pos:d}}}return{expr:{type:"ArithVariable",name:u,hasDollarPrefix:o},pos:n}}if(t[n]==="#"){let u=n+1;for(;u<t.length&&t[u]!==`
|
|
58
|
+
`;)u++;let c=t.slice(n,u).trim()||"#";return{expr:{type:"ArithSyntaxError",errorToken:c,message:`${c}: syntax error: invalid arithmetic operator (error token is "${c}")`},pos:t.length}}return{expr:{type:"ArithNumber",value:0},pos:n}}function ru(e){let t="",s=0;for(;s<e.length;){let r=e[s];if(r<128){t+=String.fromCharCode(r),s++;continue}if((r&224)===192){if(s+1<e.length&&(e[s+1]&192)===128&&r>=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<e.length&&(e[s+1]&192)===128&&(e[s+2]&192)===128){if(r===224&&e[s+1]<160){t+=String.fromCharCode(r),s++;continue}let n=(r&15)<<12|(e[s+1]&63)<<6|e[s+2]&63;if(n>=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+3<e.length&&(e[s+1]&192)===128&&(e[s+2]&192)===128&&(e[s+3]&192)===128){if(r===240&&e[s+1]<144){t+=String.fromCharCode(r),s++;continue}let n=(r&7)<<18|(e[s+1]&63)<<12|(e[s+2]&63)<<6|e[s+3]&63;if(n>1114111){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(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;return r}function er(e,t,s,r,n){let i=1,a=s+1;for(;a<t.length&&i>0;)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(;r<t.length&&n>0;){let i=t[r];if(i==="\\"&&r+1<t.length){r+=2;continue}if(i==="'"){let a=t.indexOf("'",r+1);if(a!==-1){r=a+1;continue}}if(i==='"'){for(r++;r<t.length&&t[r]!=='"';)t[r]==="\\"&&r+1<t.length?r+=2:r++;r<t.length&&r++;continue}i==="{"?n++:i==="}"&&n--,n>0&&r++}return r}function ma(e,t,s){let r=s,n=!1;for(;r<t.length;){let i=t[r];if(i==="/"&&n||i==="}")break;if(i==="'"){let a=t.indexOf("'",r+1);if(a!==-1){r=a+1,n=!0;continue}}if(i==='"'){for(r++;r<t.length&&t[r]!=='"';)t[r]==="\\"&&r+1<t.length?r+=2:r++;r<t.length&&r++,n=!0;continue}i==="\\"?(r+=2,n=!0):(r++,n=!0)}return r}function ga(e,t,s){let r=s,n="";for(;r<t.length;){let i=t[r];if(i==="*"||i==="?")n+=i,r++;else if(i==="["){let a=iu(t,r);a===-1?(n+=i,r++):(n+=t.slice(r,a+1),r=a+1)}else break}return{pattern:n,endIndex:r}}function iu(e,t){let s=t+1;for(s<e.length&&e[s]==="^"&&s++,s<e.length&&e[s]==="]"&&s++;s<e.length;){let r=e[s];if(r==="\\"&&s+1<e.length){let n=e[s+1];if(n==='"'||n==="'")return-1;s+=2;continue}if(r==="]")return s;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let n=e.indexOf("'",s+1);if(n!==-1){s=n+1;continue}}if(r==="["&&s+1<e.length&&e[s+1]===":"){let n=e.indexOf(":]",s+2);if(n!==-1){s=n+2;continue}}if(r==="["&&s+1<e.length&&(e[s+1]==="."||e[s+1]==="=")){let i=`${e[s+1]}]`,a=e.indexOf(i,s+2);if(a!==-1){s=a+2;continue}}s++}return-1}function ya(e,t,s){let r="",n=s;for(;n<t.length&&t[n]!=="'";){let i=t[n];if(i==="\\"&&n+1<t.length)switch(t[n+1]){case"n":r+=`
|
|
59
|
+
`,n+=2;break;case"t":r+=" ",n+=2;break;case"r":r+="\r",n+=2;break;case"\\":r+="\\",n+=2;break;case"'":r+="'",n+=2;break;case'"':r+='"',n+=2;break;case"a":r+="\x07",n+=2;break;case"b":r+="\b",n+=2;break;case"e":case"E":r+="\x1B",n+=2;break;case"f":r+="\f",n+=2;break;case"v":r+="\v",n+=2;break;case"x":{let l=[],o=n;for(;o+1<t.length&&t[o]==="\\"&&t[o+1]==="x";){let u=t.slice(o+2,o+4),c=parseInt(u,16);if(!Number.isNaN(c)&&u.length>0)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<t.length){let o=t[n+2].charCodeAt(0)&31;r+=String.fromCharCode(o),n+=3}else r+="\\c",n+=2;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let l="",o=n+1;for(;o<t.length&&o<n+4&&/[0-7]/.test(t[o]);)l+=t[o],o++;let u=parseInt(l,8);r+=String.fromCharCode(u),n=o;break}default:r+=i,n++}else r+=i,n++}return n<t.length&&t[n]==="'"&&n++,{part:I.literal(r),endIndex:n}}function tr(e,t){let s=t.trim();return s===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:Y(e,s)}function ha(e){let t=[],s="",r=0;for(let n=0;n<e.length;n++){let i=e[n];i==="{"?(r++,s+=i):i==="}"?(r--,s+=i):i===","&&r===0?(t.push(s),s=""):s+=i}return t.push(s),t}function wa(e,t,s,r){let n=er(e,t,s,"{","}");if(n===-1)return null;let i=t.slice(s+1,n),a=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(a)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(a[1],10),end:Number.parseInt(a[2],10),step:a[3]?Number.parseInt(a[3],10):void 0,startStr:a[1],endStr:a[2]}]},endIndex:n+1};let l=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return l?{part:{type:"BraceExpansion",items:[{type:"Range",start:l[1],end:l[2],step:l[3]?Number.parseInt(l[3],10):void 0}]},endIndex:n+1}:i.includes(",")&&r?{part:{type:"BraceExpansion",items:ha(i).map(c=>({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(;a<s.length;a++)if(s[a]==="[")f++;else if(s[a]==="]"&&(f--,f===0))break;f!==0&&e.error(`Invalid assignment: ${s}`),i=s.slice(d,a),a++}let l=s[a]==="+";l&&a++,s[a]!=="="&&e.error(`Invalid assignment: ${s}`),a++;let o=s.slice(a);if(o==="("){let f=nr(e);e.expect(g.RPAREN);let d=i!==void 0?`${n}[${i}]`:n;return I.assignment(d,null,l,f)}if(o===""&&e.check(g.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let d=nr(e);e.expect(g.RPAREN);let h=i!==void 0?`${n}[${i}]`:n;return I.assignment(h,null,l,d)}}let u=o?e.parseWordFromString(o,t.quoted,t.singleQuoted,!0):null,c=i!==void 0?`${n}[${i}]`:n;return I.assignment(c,u,l,null)}var lu=new Set([g.AMP,g.PIPE,g.PIPE_AMP,g.SEMICOLON,g.AND_AND,g.OR_OR,g.DSEMI,g.SEMI_AND,g.SEMI_SEMI_AND]);function nr(e){let t=[];for(e.skipNewlines();!e.check(g.RPAREN,g.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):lu.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function rr(e,t){e.expect(g.IF);let s=[],r=e.parseCompoundList();e.expect(g.THEN);let n=e.parseCompoundList();if(n.length===0){let l=e.check(g.FI)?"fi":e.check(g.ELSE)?"else":e.check(g.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${l}'`)}for(s.push({condition:r,body:n});e.check(g.ELIF);){e.advance();let l=e.parseCompoundList();e.expect(g.THEN);let o=e.parseCompoundList();if(o.length===0){let u=e.check(g.FI)?"fi":e.check(g.ELSE)?"else":e.check(g.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${u}'`)}s.push({condition:l,body:o})}let i=null;e.check(g.ELSE)&&(e.advance(),i=e.parseCompoundList(),i.length===0&&e.error("syntax error near unexpected token `fi'")),e.expect(g.FI);let a=t?.skipRedirections?[]:e.parseOptionalRedirections();return I.ifNode(s,i,a)}function ir(e,t){let s=e.expect(g.FOR);if(e.check(g.DPAREN_START))return uu(e,t,s.line);e.isWord()||e.error("Expected variable name in for loop");let n=e.advance().value,i=null;if(e.skipNewlines(),e.check(g.IN))for(e.advance(),i=[];!e.check(g.SEMICOLON,g.NEWLINE,g.DO,g.EOF)&&e.isWord();)i.push(e.parseWord());e.check(g.SEMICOLON)&&e.advance(),e.skipNewlines(),e.expect(g.DO);let a=e.parseCompoundList();e.expect(g.DONE);let l=t?.skipRedirections?[]:e.parseOptionalRedirections();return I.forNode(n,i,a,l)}function uu(e,t,s){e.expect(g.DPAREN_START);let r=null,n=null,i=null,a=["","",""],l=0,o=0;for(;!e.check(g.DPAREN_END,g.EOF);){let f=e.advance();if(f.type===g.SEMICOLON&&o===0){if(l++,l>2)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(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if("@*+?!".includes(n)&&r+1<e.length&&e[r+1]==="("){r++,s++,r++;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function bu(e,t,s){let r=s+1,n=t[r];if("@*#?$!-0123456789".includes(n))return{part:I.parameterExpansion(n),endIndex:r+1};let i="";for(;r<t.length&&/[a-zA-Z0-9_]/.test(t[r]);)i+=t[r],r++;return{part:I.parameterExpansion(i),endIndex:r}}function vu(e,t,s,r=!1){let n=s+2,i=!1;t[n]==="!"&&(i=!0,n++);let a=!1;t[n]==="#"&&!/[}:#%/^,]/.test(t[n+1]||"}")&&(a=!0,n++);let l="",o=t[n];if(/[@*#?$!-]/.test(o)&&!/[a-zA-Z0-9_]/.test(t[n+1]||""))l=o,n++;else for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)l+=t[n],n++;if(t[n]==="["){let c=er(e,t,n,"[","]");if(l+=t.slice(n,c+1),n=c+1,t[n]==="["){let f=1,d=n;for(;d<t.length&&f>0;)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(;f<t.length&&c>0;)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&&t[n]!=="}"&&/[:=\-+?#%/^,@]/.test(t[n])){let f=hr(e,t,n,l,r);f.operation?(u={type:"Indirection",innerOp:f.operation},n=f.endIndex):(u={type:"ArrayKeys",array:c[1],star:c[2]==="*"},l="")}else u={type:"ArrayKeys",array:c[1],star:c[2]==="*"},l="";else if(t[n]==="*"||t[n]==="@"&&!/[QPaAEKkuUL]/.test(t[n+1]||"")){let f=t[n];n++,u={type:"VarNamePrefix",prefix:l,star:f==="*"},l=""}else if(n<t.length&&t[n]!=="}"&&/[:=\-+?#%/^,@]/.test(t[n])){let f=hr(e,t,n,l,r);f.operation?(u={type:"Indirection",innerOp:f.operation},n=f.endIndex):u={type:"Indirection"}}else u={type:"Indirection"}}else if(a)if(t[n]===":")for(u={type:"LengthSliceError"};n<t.length&&t[n]!=="}";)n++;else t[n]!=="}"&&/[-+=?]/.test(t[n])?e.error(`\${#${l}${t.slice(n,t.indexOf("}",n))}}: bad substitution`):t[n]==="/"?e.error(`\${#${l}${t.slice(n,t.indexOf("}",n))}}: bad substitution`):u={type:"Length"};if(!u&&n<t.length&&t[n]!=="}"){let c=hr(e,t,n,l,r);u=c.operation,n=c.endIndex}if(n<t.length&&t[n]!=="}"){let c=t[n];if(!/[:\-+=?#%/^,@[]/.test(c)){let f=n;for(;f<t.length&&t[f]!=="}";)f++;let d=t.slice(s,f+1);e.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;n<t.length&&t[n]!=="}";)n++;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;y<c.length;y++){let b=c[y];if(b==="("||b==="[")d++;else if(b===")"||b==="]")d--;else if(b==="?"&&d===0)h++;else if(b===":"&&d===0)if(h>0)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(;l<t.length&&a>0;)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<t.length;){let a=t[r];if(a==="\\"&&r+1<t.length){let l=t[r+1];if(l==="$"||l==="`"||l==='"'||l==="\\"){n+=l,r+=2;continue}n+=a,r++;continue}if(a==="$"){i();let{part:l,endIndex:o}=pr(e,t,r,!0);l&&s.push(l),r=o;continue}if(a==="`"){i();let{part:l,endIndex:o}=e.parseBacktickSubstitution(t,r,!0);s.push(l),r=o;continue}n+=a,r++}return i(),s}function Su(e,t,s){let r=[],n=s,i="",a=()=>{i&&(r.push(I.literal(i)),i="")};for(;n<t.length&&t[n]!=='"';){let l=t[n];if(l==="\\"&&n+1<t.length){let o=t[n+1];if('"\\$`\n'.includes(o)){i+=o,n+=2;continue}i+=l,n++;continue}if(l==="$"){a();let{part:o,endIndex:u}=pr(e,t,n,!0);o&&r.push(o),n=u;continue}if(l==="`"){a();let{part:o,endIndex:u}=e.parseBacktickSubstitution(t,n,!0);r.push(o),n=u;continue}i+=l,n++}return a(),{part:I.doubleQuoted(r),endIndex:n}}function $t(e,t,s=!1,r=!1,n=!1,i=!1,a=!1,l=!1,o=!1,u=!1){if(r)return[I.singleQuoted(t)];if(s){let m=Pa(e,t);return[I.doubleQuoted(m)]}if(t.length>=2&&t[0]==='"'&&t[t.length-1]==='"'){let m=t.slice(1,-1),p=!1;for(let y=0;y<m.length;y++){if(m[y]==='"'){p=!0;break}m[y]==="\\"&&y+1<m.length&&y++}if(!p){let y=Pa(e,m);return[I.doubleQuoted(y)]}}let c=[],f=0,d="",h=()=>{d&&(c.push(I.literal(d)),d="")};for(;f<t.length;){let m=t[f];if(m==="\\"&&f+1<t.length){let p=t[f+1];if(o){h(),c.push(I.escaped(p)),f+=2;continue}let y=i?p==="$"||p==="`"||p===`
|
|
60
|
+
`:p==="$"||p==="`"||p==='"'||p==="'"||p===`
|
|
61
|
+
`||u&&p==="}",b=a?"*?[]\\".includes(p):"*?[]\\(){}.^+".includes(p);y?d+=p:b?(h(),c.push(I.escaped(p))):d+=`\\${p}`,f+=2;continue}if(m==="'"&&!a&&!i){h();let p=t.indexOf("'",f+1);if(p===-1){d+=t.slice(f);break}c.push(I.singleQuoted(t.slice(f+1,p))),f=p+1;continue}if(m==='"'&&!i){h();let{part:p,endIndex:y}=Su(e,t,f+1);c.push(p),f=y+1;continue}if(m==="$"&&t[f+1]==="'"){h();let{part:p,endIndex:y}=ya(e,t,f+2);c.push(p),f=y;continue}if(m==="$"){h();let{part:p,endIndex:y}=pr(e,t,f);p&&c.push(p),f=y;continue}if(m==="`"){h();let{part:p,endIndex:y}=e.parseBacktickSubstitution(t,f);c.push(p),f=y;continue}if(m==="~"){let p=f>0?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+1<t.length&&t[f+1]==="("){let p=Eu(t,f+1);if(p!==-1){h();let y=t.slice(f,p+1);c.push({type:"Glob",pattern:y}),f=p+1;continue}}if(m==="*"||m==="?"||m==="["){h();let{pattern:p,endIndex:y}=ga(e,t,f);c.push({type:"Glob",pattern:p}),f=y;continue}if(m==="{"&&!n&&!l&&!i){let p=wa(e,t,f,$t);if(p){h(),c.push(p.part),f=p.endIndex;continue}}d+=m,f++}return h(),c}var q=class e{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;parseDepth=0;_input="";getInput(){return this._input}checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Ki)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.pos<this.tokens.length-1&&this.pos++,t}getPos(){return this.pos}check(t,s,r,n,...i){let a=this.tokens[this.pos]?.type;return a===t||s!==void 0&&a===s||r!==void 0&&a===r||n!==void 0&&a===n?!0:i.length>0?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(;s<this.tokens.length-this.pos;){let r=this.peek(s);if(r.type===g.EOF)return!1;if(r.type===g.DPAREN_START||r.type===g.LPAREN)t++;else if(r.type===g.DPAREN_END){if(t-=2,t<=0)return!1}else if(r.type===g.RPAREN&&(t--,t===0&&this.peek(s+1).type===g.RPAREN))return!0;s++}return!1}parseNestedSubshellsFromDparen(){this.advance();let t=this.parseCompoundList();this.expect(g.RPAREN),this.expect(g.RPAREN);let s=this.parseOptionalRedirections(),r=I.subshell(t,[]);return I.subshell([I.statement([I.pipeline([r],!1,!1,!1)])],s)}isWord(){let t=this.current().type;return t===g.WORD||t===g.NAME||t===g.NUMBER||t===g.IF||t===g.FOR||t===g.WHILE||t===g.UNTIL||t===g.CASE||t===g.FUNCTION||t===g.ELSE||t===g.ELIF||t===g.FI||t===g.THEN||t===g.DO||t===g.DONE||t===g.ESAC||t===g.IN||t===g.SELECT||t===g.TIME||t===g.COPROC||t===g.BANG}parseWord(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted)}parseWordNoBraceExpansion(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0)}parseWordForRegex(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0,!0)}parseWordFromString(t,s=!1,r=!1,n=!1,i=!1,a=!1,l=!1){let o=$t(this,t,s,r,n,i,!1,a,l);return I.word(o)}parseCommandSubstitution(t,s){return ji(t,s,()=>new 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(;a<t.length-1&&n>0;)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(;r<e.length;){let n=e[r];if(n==="["){for(s+=n,r++,r<e.length&&(e[r]==="!"||e[r]==="^")&&(s+=e[r],r++),r<e.length&&e[r]==="]"&&(s+=e[r],r++);r<e.length&&e[r]!=="]";){if(e[r]==="["&&r+1<e.length&&e[r+1]===":"){let i=e.indexOf(":]",r+2);if(i!==-1){s+=e.slice(r,i+2),r=i+2;continue}}if(e[r]==="\\"&&r+1<e.length){s+=e[r]+e[r+1],r+=2;continue}s+=e[r],r++}r<e.length&&e[r]==="]"&&(s+=e[r],r++)}else n===":"?(s!==""&&t.push(s),s="",r++):n==="\\"&&r+1<e.length?(s+=n+e[r+1],r+=2):(s+=n,r++)}return s!==""&&t.push(s),t}function Ra(e){let t="^";for(let s=0;s<e.length;s++){let r=e[s];if(r==="*")t+="[^/]*";else if(r==="?")t+="[^/]";else if(r==="["){let n=s+1,i="[";n<e.length&&(e[n]==="^"||e[n]==="!")&&(i+="^",n++),n<e.length&&e[n]==="]"&&(i+="\\]",n++);let a=n;for(;a<e.length;){if(e[a]==="\\"&&a+1<e.length){a+=2;continue}if(e[a]==="["&&a+1<e.length&&e[a+1]===":"){let o=e.indexOf(":]",a+2);if(o!==-1){a=o+2;continue}}if(e[a]==="]")break;a++}let l=n;for(;n<e.length&&e[n]!=="]";){if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let o=e.indexOf(":]",n+2);if(o!==-1){let u=e.slice(n+2,o),c=gr(u);i+=c,n=o+2;continue}}if(e[n]==="\\"&&n+1<e.length){i+=`\\${e[n+1]}`,n+=2;continue}if(e[n]==="-"){let o=n===l,u=n+1===a;o||u?i+="\\-":i+="-"}else i+=e[n];n++}i+="]",t+=i,s=n}else if(r==="\\"&&s+1<e.length){let n=e[s+1];/[.+^${}()|\\*?[\]]/.test(n)?t+=`\\${n}`:t+=n,s++}else/[.+^${}()|]/.test(r)?t+=`\\${r}`:t+=r}return t+="$",le(t)}function yr(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function wr(e){let t=[],s="",r=0,n=!1,i=0;for(;i<e.length;){let a=e[i];if(a==="'"&&!n){n=!0,s+="\0QUOTE_START\0",i++;continue}if(a==="'"&&n){n=!1,s+="\0QUOTE_END\0",i++;continue}if(n){s+=a,i++;continue}if(a==="\\"){s+=a,i+1<e.length?(s+=e[i+1],i+=2):i++;continue}a==="("?(r++,s+=a):a===")"?(r--,s+=a):a==="|"&&r===0?(t.push(s),s=""):s+=a,i++}return t.push(s),t}var Ia=5,Pt=class{fs;cwd;globignorePatterns=[];hasGlobignore=!1;globstar=!1;nullglob=!1;failglob=!1;dotglob=!1;extglob=!1;globskipdots=!0;ops={count:0};maxOps;constructor(t,s,r,n){this.fs=t,this.cwd=s,typeof n=="boolean"?(this.globstar=n,this.maxOps=1e5):n?(this.globstar=n.globstar??!1,this.nullglob=n.nullglob??!1,this.failglob=n.failglob??!1,this.dotglob=n.dotglob??!1,this.extglob=n.extglob??!1,this.globskipdots=n.globskipdots??!0,this.maxOps=n.maxGlobOperations??1e5):this.maxOps=1e5;let i=r?.get("GLOBIGNORE");i!==void 0&&i!==""&&(this.hasGlobignore=!0,this.globignorePatterns=Da(i))}checkOpsLimit(){if(++this.ops.count>this.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;a<t.length;a++){let l=n[a];l===null?i.push(t[a]):l.length>0?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;u<r.length;u++)if(this.hasGlobChars(r[u])){n=u;break}if(n===-1)return[t];let i,a;if(n===0)s?(i="/",a="/"):(i=this.cwd,a="");else{let u=r.slice(0,n);s?(i=`/${u.join("/")}`,a=`/${u.join("/")}`):(i=this.fs.resolvePath(this.cwd,u.join("/")),a=u.join("/"))}let l=r.slice(n);return(await this.expandSegments(i,a,l)).sort()}async expandSegments(t,s,r){if(this.checkOpsLimit(),r.length===0)return[s];let[n,...i]=r,a=[];try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let l=await this.fs.readdirWithFileTypes(t),o=[],u=[...l],c=this.dotglob||this.hasGlobignore;if(n.startsWith(".")||this.dotglob){let d=l.some(m=>m.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;u<a.length;u+=100){let c=a.slice(u,u+100);await Promise.all(c.map(f=>this.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;c<l.length;c+=100){let f=l.slice(c,c+100);await Promise.all(f.map(d=>this.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;o<l.length;o+=100){let u=l.slice(o,o+100);await Promise.all(u.map(c=>this.walkDirectory(c,s,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(n),a=[];for(let o=0;o<i.length;o+=100){let u=i.slice(o,o+100),c=await Promise.all(u.map(async f=>{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;o<l.length;o+=100){let u=l.slice(o,o+100);await Promise.all(u.map(c=>this.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;n<t.length;n++){if(t.slice(n,n+13)==="\0QUOTE_START\0"){r=!0,n+=12;continue}if(t.slice(n,n+11)==="\0QUOTE_END\0"){r=!1,n+=10;continue}let i=t[n];if(r){/[.+^${}()|\\*?[\]]/.test(i)?s+=`\\${i}`:s+=i;continue}if(this.extglob&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&n+1<t.length&&t[n+1]==="("){let a=yr(t,n+1);if(a!==-1){let l=t.slice(n+2,a),o=wr(l),u=o.map(f=>this.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(a<t.length-1){let d=o.map(m=>this.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="[";a<t.length&&(t[a]==="^"||t[a]==="!")&&(l+="^",a++),a<t.length&&t[a]==="]"&&(l+="\\]",a++);let o=a;for(;o<t.length;){if(t[o]==="\\"&&o+1<t.length){o+=2;continue}if(t[o]==="["&&o+1<t.length&&t[o+1]===":"){let c=t.indexOf(":]",o+2);if(c!==-1){o=c+2;continue}}if(t[o]==="]")break;o++}let u=a;for(;a<t.length&&t[a]!=="]";){if(t[a]==="["&&a+1<t.length&&t[a+1]===":"){let c=t.indexOf(":]",a+2);if(c!==-1){let f=t.slice(a+2,c),d=gr(f);l+=d,a=c+2;continue}}if(t[a]==="\\"&&a+1<t.length){l+=`\\${t[a+1]}`,a+=2;continue}if(t[a]==="-"){let c=a===u,f=a+1===o;c||f?l+="\\-":l+="-"}else l+=t[a];a++}l+="]",s+=l,n=a}else if(i==="\\"&&n+1<t.length){let a=t[n+1];/[.+^${}()|\\*?[\]]/.test(a)?s+=`\\${a}`:s+=a,n++}else/[.+^${}()|]/.test(i)?s+=`\\${i}`:s+=i}return s}computePatternLength(t){let s=0,r=0,n=!1;for(;r<t.length;){if(t.slice(r,r+13)==="\0QUOTE_START\0"){n=!0,r+=13;continue}if(t.slice(r,r+11)==="\0QUOTE_END\0"){n=!1,r+=11;continue}let i=t[r];if(n){s+=1,r++;continue}if((i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&r+1<t.length&&t[r+1]==="("){let a=yr(t,r+1);if(a!==-1){if(i==="@"){let l=t.slice(r+2,a),u=wr(l).map(c=>this.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;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==="$"){let s=e[t+1];if(s==="{"||s&&/[a-zA-Z_]/.test(s))return!0}}return!1}function ku(e){if(!e.operation)return!1;let t=e.operation,s;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(s=t.word?.parts),!s)return!1;for(let r of s)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Oa(e){if(!e.operation)return!1;let t=e.operation,s;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(s=t.word?.parts),!s||s.length===0)return!1;for(let r of s)if(r.type!=="DoubleQuoted"&&r.type!=="SingleQuoted")return!1;return!0}function hs(e){let t=!1,s=!1,r=!1,n=!1,i=!1,a=!1,l=!1;for(let o of e){if((o.type==="SingleQuoted"||o.type==="DoubleQuoted")&&(t=!0,o.type==="DoubleQuoted"))for(let u of o.parts)u.type==="ParameterExpansion"&&(u.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&(!u.operation||u.operation.type==="PatternRemoval"||u.operation.type==="PatternReplacement")&&(n=!0),(u.operation?.type==="VarNamePrefix"||u.operation?.type==="ArrayKeys")&&(a=!0),u.operation?.type==="Indirection"&&(l=!0));o.type==="CommandSubstitution"&&(s=!0),o.type==="ParameterExpansion"&&(i=!0,(o.parameter==="@"||o.parameter==="*")&&(r=!0),ku(o)&&(t=!0),(o.operation?.type==="VarNamePrefix"||o.operation?.type==="ArrayKeys")&&(a=!0),o.operation?.type==="Indirection"&&(l=!0)),o.type==="Glob"&&Er(o.pattern)&&(i=!0)}return{hasQuoted:t,hasCommandSub:s,hasArrayVar:r,hasArrayAtExpansion:n,hasParamExpansion:i,hasVarNamePrefixExpansion:a,hasIndirection:l}}function he(e,t){let s=`${t}_`,r=[];for(let n of e.state.env.keys())if(n.startsWith(s)){let i=n.slice(s.length),a=Number.parseInt(i,10);!Number.isNaN(a)&&String(a)===i&&r.push(a)}return r.sort((n,i)=>n-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<e.parts.length;f++){let d=e.parts[f];d.type==="BraceExpansion"?o.push({type:"Literal",value:Nu(d)}):o.push(d)}return{key:r,valueParts:o,append:l}}function Nu(e){return`{${e.items.map(s=>{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")??`
|
|
62
|
+
`}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!==`
|
|
63
|
+
`)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===`
|
|
64
|
+
`?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=`
|
|
65
|
+
`;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&&n.has(e[o]);)o++;if(o>=e.length)return{words:[],wordStarts:[]};if(i.has(e[o]))for(a.push(""),l.push(o),o++;o<e.length&&n.has(e[o]);)o++;for(;o<e.length&&!(s!==void 0&&a.length>=s);){let u=o;for(l.push(u);o<e.length;){let c=e[o];if(!r&&c==="\\"){o++,o<e.length&&o++;continue}if(n.has(c)||i.has(c))break;o++}if(a.push(e.substring(u,o)),o>=e.length)break;for(;o<e.length&&n.has(e[o]);)o++;if(o<e.length&&i.has(e[o])){for(o++;o<e.length&&n.has(e[o]);)o++;for(;o<e.length&&i.has(e[o])&&!(s!==void 0&&a.length>=s);)for(a.push(""),l.push(o),o++;o<e.length&&n.has(e[o]);)o++}}return{words:a,wordStarts:l}}function Us(e,t){if(t==="")return{words:e?[e]:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};if(e==="")return{words:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};let{whitespace:s,nonWhitespace:r}=vr(t),n=[],i=0,a=!1,l=!1,o=i;for(;i<e.length&&s.has(e[i]);)i++;if(i>o&&(a=!0),i>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(r.has(e[i]))for(n.push(""),i++;i<e.length&&s.has(e[i]);)i++;for(;i<e.length;){let u=i;for(;i<e.length;){let f=e[i];if(s.has(f)||r.has(f))break;i++}if(n.push(e.substring(u,i)),i>=e.length){l=!1;break}let c=i;for(;i<e.length&&s.has(e[i]);)i++;if(i<e.length&&r.has(e[i])){for(i++;i<e.length&&s.has(e[i]);)i++;for(;i<e.length&&r.has(e[i]);)for(n.push(""),i++;i<e.length&&s.has(e[i]);)i++}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
|
|
66
|
+
`,"";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
|
|
67
|
+
`,""):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(;r<t.length;){if(t[r]==="$"){if(t[r+1]==="{"){let n=1,i=r+2;for(;i<t.length&&n>0;)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(;i<t.length&&n>0;)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(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)n++;let i=t.slice(r+1,n),a=await J(e,i);s+=a,r=n;continue}if(/[0-9]/.test(t[r+1]||"")){let n=r+1;for(;n<t.length&&/[0-9]/.test(t[n]);)n++;let i=t.slice(r+1,n),a=await J(e,i);s+=a,r=n;continue}if(/[*@#?\-!$]/.test(t[r+1]||"")){let n=t[r+1],i=await J(e,n);s+=i,r+=2;continue}}if(t[r]==='"'){for(s+='"',r++;r<t.length&&t[r]!=='"';)if(t[r]==="$"&&/[a-zA-Z_]/.test(t[r+1]||"")){let n=r+1;for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)n++;let i=t.slice(r+1,n),a=await J(e,i);s+=a,r=n}else t[r]==="\\"?(s+=t[r],r++,r<t.length&&(s+=t[r],r++)):(s+=t[r],r++);r<t.length&&(s+='"',r++);continue}s+=t[r],r++}return s}async function $r(e,t){let s=t,r=t.startsWith('"')&&t.endsWith('"'),n=t.startsWith("'")&&t.endsWith("'");if((r||n)&&(s=t.slice(1,-1)),n)return s;let i="",a=0;for(;a<s.length;)if(s[a]==="$")if(s[a+1]==="("){let l=1,o=a+2;for(;o<s.length&&l>0;)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(;o<s.length&&l>0;)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<s.length&&/[a-zA-Z0-9_]/.test(s[l]);)l++;let o=s.slice(a+1,l),u=await J(e,o);i+=u,a=l}else i+=s[a],a++;else if(s[a]==="`"){let l=a+1;for(;l<s.length&&s[l]!=="`";)l++;let o=s.slice(a+1,l);if(e.execFn){let u=await e.execFn(o,{signal:e.state.signal});i+=u.stdout.replace(/\n+$/,""),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.stderr)}a=l+1}else i+=s[a],a++;return i}var Gs=1e4;function Ru(e,t,s,r,n){let i=s??1;i===0&&(i=1);let a=Math.abs(i),l=[],o=0;r?.match(/^-?0\d/)&&(o=Math.max(o,r.replace(/^-/,"").length)),n?.match(/^-?0\d/)&&(o=Math.max(o,n.replace(/^-/,"").length));let u=c=>{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<Gs;c+=a,f++)l.push(u(c));else for(let c=e,f=0;c>=t&&f<Gs;c-=a,f++)l.push(u(c));return l}function Iu(e,t,s){let r=s??1;r===0&&(r=1);let n=e.charCodeAt(0),i=t.charCodeAt(0),a=Math.abs(r),l=e>="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<Gs;d+=a,h++)f.push(String.fromCharCode(d));else for(let d=n,h=0;d>=i&&h<Gs;d-=a,h++)f.push(String.fromCharCode(d));return f}function Pr(e,t,s,r,n){let i=s!==void 0?`..${s}`:"";return typeof e=="number"&&typeof t=="number"?{expanded:Ru(e,t,s,r,n),literal:`{${e}..${t}${i}}`}:typeof e=="string"&&typeof t=="string"?{expanded:Iu(e,t,s),literal:`{${e}..${t}${i}}`}:{expanded:null,literal:`{${e}..${t}${i}}`}}function Ba(e){if(e.statements.length!==1)return null;let t=e.statements[0];if(t.operators.length!==0||t.pipelines.length!==1)return null;let s=t.pipelines[0];if(s.negated||s.commands.length!==1)return null;let r=s.commands[0];if(r.type!=="SimpleCommand")return null;let n=r;if(n.name!==null||n.args.length!==0||n.assignments.length!==0||n.redirections.length!==1)return null;let i=n.redirections[0];return i.operator!=="<"||i.target.type!=="Word"?null:{target:i.target}}function nt(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\(/.test(e))}function kr(e){let t="",s=0;for(;s<e.length;)e[s]==="\\"&&s+1<e.length?(t+=e[s+1],s+=2):(t+=e[s],s++);return t}function Fe(e){return e.replace(/([*?[\]\\()|])/g,"\\$1")}function ps(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}function Q(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G(e,t,s=!1){let r="",n=0;for(;n<e.length;){let i=e[n];if(s&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&n+1<e.length&&e[n+1]==="("){let a=Ou(e,n+1);if(a!==-1){let l=e.slice(n+2,a),u=Tu(l).map(f=>G(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+1<e.length){let a=e[n+1];/[\\^$.|+(){}[\]*?]/.test(a)?r+=`\\${a}`:r+=a,n+=2}else r+="\\\\",n++;else if(i==="*")r+=t?".*":".*?",n++;else if(i==="?")r+=".",n++;else if(i==="["){let a=Lu(e,n);if(a===-1)r+="\\[",n++;else{let l=e.slice(n+1,a);r+=Mu(l),n=a+1}}else/[\^$.|+(){}]/.test(i)?(r+=`\\${i}`,n++):(r+=i,n++)}return r}function Ou(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function Tu(e){let t=[],s="",r=0,n=0;for(;n<e.length;){let i=e[n];if(i==="\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i==="("?(r++,s+=i):i===")"?(r--,s+=i):i==="|"&&r===0?(t.push(s),s=""):s+=i,n++}return t.push(s),t}function Lu(e,t){let s=t+1;for(s<e.length&&e[s]==="^"&&s++,s<e.length&&e[s]==="]"&&s++;s<e.length;){if(e[s]==="\\"&&s+1<e.length){s+=2;continue}if(e[s]==="]")return s;if(e[s]==="'"){let r=e.indexOf("'",s+1);if(r!==-1){s=r+1;continue}}if(e[s]==="["&&s+1<e.length&&e[s+1]===":"){let r=e.indexOf(":]",s+2);if(r!==-1){s=r+2;continue}}s++}return-1}function Mu(e){let t="[",s=0;for((e[0]==="^"||e[0]==="!")&&(t+="^",s++);s<e.length;){if(e[s]==="'"){let n=e.indexOf("'",s+1);if(n!==-1){let i=e.slice(s+1,n);for(let a of i)a==="\\"?t+="\\\\":a==="]"?t+="\\]":a==="^"&&t==="["?t+="\\^":t+=a;s=n+1;continue}}if(e[s]==="["&&s+1<e.length&&e[s+1]===":"){let n=e.indexOf(":]",s+2);if(n!==-1){let i=e.slice(s+2,n);t+=Fu(i),s=n+2;continue}}let r=e[s];r==="\\"?s+1<e.length?(t+=`\\${e[s+1]}`,s+=2):(t+="\\\\",s++):r==="-"&&s>0&&s<e.length-1?(t+="-",s++):r==="^"&&s===0?(t+="^",s++):(r==="]"&&s===0?t+="\\]":t+=r,s++)}return t+="]",t}var Wu=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 Fu(e){return Wu.get(e)??""}function mt(e,t,s,r){if(s==="prefix")return le(`^${t}`,"s").replace(e,"");let n=le(`${t}$`,"s");if(r)return n.replace(e,"");for(let i=e.length;i>=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;)if(e[n]==="%"){if(n+1>=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;){let p=t[r];if(p==="\\"){if(r+1>=t.length){s+="\\",r++;continue}let y=t[r+1];if(y>="0"&&y<="7"){let b="",v=r+1;for(;v<t.length&&v<r+4&&t[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+=`
|
|
68
|
+
`,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+2<t.length&&t[r+2]==="{"){let b=t.indexOf("}",r+3);if(b!==-1){let v=t.slice(r+3,b);s+=Vu(v,f),r=b+1}else s+="\\D",r+=2}else s+="\\D",r+=2;break;case"s":s+="bash",r+=2;break;case"v":s+="5.0",r+=2;break;case"V":s+="5.0.0",r+=2;break;case"j":s+="0",r+=2;break;case"l":s+="tty",r+=2;break;case"#":s+=m,r+=2;break;case"!":s+=m,r+=2;break;case"x":s+="\\x",r+=2;break;default:s+=`\\${y}`,r+=2}}else s+=p,r++}return s}function kt(e){if(e==="")return"''";if(/[\n\r\t\x00-\x1f\x7f']/.test(e)){let s="$'";for(let r of e)switch(r){case"'":s+="\\'";break;case"\\":s+="\\\\";break;case`
|
|
69
|
+
`:s+="\\n";break;case"\r":s+="\\r";break;case" ":s+="\\t";break;default:{let n=r.charCodeAt(0);n<32||n===127?s+=`\\${n.toString(8).padStart(3,"0")}`:s+=r}}return`${s}'`}return`'${e}'`}function De(e,t){e.state.readonlyVars=e.state.readonlyVars||new Set,e.state.readonlyVars.add(t)}function rt(e,t){return e.state.readonlyVars?.has(t)??!1}function ye(e,t,s="bash"){if(rt(e,t)){let r=`${s}: ${t}: readonly variable
|
|
70
|
+
`;throw new Z(1,"",r)}return null}function Qe(e,t){let s=e.state.exportedVars?.has(t)??!1;if(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t),e.state.localScopes.length>0&&e.state.localScopes[e.state.localScopes.length-1].has(t)&&!s){for(e.state.localExportedVars||(e.state.localExportedVars=[]);e.state.localExportedVars.length<e.state.localScopes.length;)e.state.localExportedVars.push(new Set);e.state.localExportedVars[e.state.localExportedVars.length-1].add(t)}}function Hs(e,t){e.state.exportedVars?.delete(t)}function Nt(e,t){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))return"";let s="",r=e.state.env.has(`${t}__length`)||Array.from(e.state.env.keys()).some(i=>i.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}
|
|
71
|
+
`)}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
|
|
72
|
+
`);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`
|
|
73
|
+
`;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(;t<e.length;){let s=e[t];if(s==="\\"&&t+1<e.length){t+=2;continue}if(s==="'"){let r=e.indexOf("'",t+1);if(r!==-1){t=r+1;continue}}if(s==="$"&&t+1<e.length&&e[t+1]==="("||s==="`")return!0;t++}return!1}function ro(e,t){let s=1,r=t,n=!1,i=!1;for(;r<e.length&&s>0;){let a=e[r];if(a==="\\"&&!n&&r+1<e.length){r+=2;continue}if(a==="'"&&!i){n=!n,r++;continue}if(a==='"'&&!n){i=!i,r++;continue}if(!n&&!i){if(a==="(")s++;else if(a===")"&&(s--,s===0))return r}r++}return-1}async function Qs(e,t){let s=new q,r;try{r=s.parse(t)}catch{return""}let n=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let i=new Map(e.state.env),a=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let o=await e.executeScript(r),u=o.exitCode;return e.state.env=i,e.state.cwd=a,e.state.suppressVerbose=l,e.state.lastExitCode=u,e.state.env.set("?",String(u)),o.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+o.stderr),e.state.bashPid=n,o.stdout.replace(/\n+$/,"")}catch(o){if(e.state.env=i,e.state.cwd=a,e.state.bashPid=n,e.state.suppressVerbose=l,o instanceof X)throw o;return o instanceof Z?(e.state.lastExitCode=o.exitCode,e.state.env.set("?",String(o.exitCode)),o.stdout?.replace(/\n+$/,"")??""):""}}function Nr(e,t){let s="",r=0;for(;r<t.length;){let n=t[r];if(n==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let a=t.slice(r+1,i);s+=Fe(a),r=i+1;continue}}if(n==='"'){let i=-1,a=r+1;for(;a<t.length;){if(t[a]==="\\"){a+=2;continue}if(t[a]==='"'){i=a;break}a++}if(i!==-1){let l=t.slice(r+1,i),o=zu(e,l);s+=Fe(o),r=i+1;continue}}if(n==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let l=t.slice(r+2,a);s+=e.state.env.get(l)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let l=t.slice(r+1,a);s+=e.state.env.get(l)??"",r=a;continue}}if(n==="\\"&&r+1<t.length){s+=n+t[r+1],r+=2;continue}s+=n,r++}return s}function zu(e,t){let s="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){s+=i,r+=2;continue}s+=n,r++;continue}if(n==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let l=t.slice(r+2,a);s+=e.state.env.get(l)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let l=t.slice(r+1,a);s+=e.state.env.get(l)??"",r=a;continue}}s+=n,r++}return s}async function io(e,t){let s="",r=0;for(;r<t.length;){let n=t[r];if(n==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let a=t.slice(r+1,i);s+=Fe(a),r=i+1;continue}}if(n==='"'){let i=-1,a=r+1;for(;a<t.length;){if(t[a]==="\\"){a+=2;continue}if(t[a]==='"'){i=a;break}a++}if(i!==-1){let l=t.slice(r+1,i),o=await Bu(e,l);s+=Fe(o),r=i+1;continue}}if(n==="$"&&r+1<t.length&&t[r+1]==="("){let i=ro(t,r+2);if(i!==-1){let a=t.slice(r+2,i),l=await Qs(e,a);s+=l,r=i+1;continue}}if(n==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let a=t.slice(r+1,i),l=await Qs(e,a);s+=l,r=i+1;continue}}if(n==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let l=t.slice(r+2,a);s+=e.state.env.get(l)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let l=t.slice(r+1,a);s+=e.state.env.get(l)??"",r=a;continue}}if(n==="\\"&&r+1<t.length){s+=n+t[r+1],r+=2;continue}s+=n,r++}return s}async function Bu(e,t){let s="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){s+=i,r+=2;continue}s+=n,r++;continue}if(n==="$"&&r+1<t.length&&t[r+1]==="("){let i=ro(t,r+2);if(i!==-1){let a=t.slice(r+2,i),l=await Qs(e,a);s+=l,r=i+1;continue}}if(n==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let a=t.slice(r+1,i),l=await Qs(e,a);s+=l,r=i+1;continue}}if(n==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let l=t.slice(r+2,a);s+=e.state.env.get(l)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let l=t.slice(r+1,a);s+=e.state.env.get(l)??"",r=a;continue}}s+=n,r++}return s}function ao(e,t){if(!t.startsWith("~"))return t;e.coverage?.hit("bash:expansion:tilde");let s=e.state.env.get("HOME")!==void 0?e.state.env.get("HOME"):"/home/user";if(t==="~"||t.startsWith("~/"))return s+t.slice(1);let r=1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;let n=t.slice(1,r),i=t.slice(r);return i!==""&&!i.startsWith("/")?t:n==="root"?`/root${i}`:t}async function qu(e,t,s,r){let n="";for(let i of t.parts)if(i.type==="Glob")n+=G(i.pattern,!0,e.state.shoptOptions.extglob);else if(i.type==="Literal")n+=G(i.value,!0,e.state.shoptOptions.extglob);else if(i.type==="SingleQuoted"||i.type==="Escaped")n+=Q(i.value);else if(i.type==="DoubleQuoted"){let a=await s(e,i.parts);n+=Q(a)}else if(i.type==="ParameterExpansion"){let a=await r(e,i);n+=G(a,!0,e.state.shoptOptions.extglob)}else{let a=await r(e,i);n+=Q(a)}return n}async function oo(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!=="PatternReplacement")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(([,y])=>y);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;p<i.parts.length;p++){let y=i.parts[p];if(y.type==="ParameterExpansion"&&(y.operation?.type==="PatternRemoval"||y.operation?.type==="PatternReplacement")){let b=y.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(b){a=p,l=b[1],o=b[2]==="*",u=y.operation;break}}}if(a===-1||a===0&&a===i.parts.length-1)return null;let c="";for(let p=0;p<a;p++)c+=await r(e,i.parts[p]);let f="";for(let p=a+1;p<i.parts.length;p++)f+=await r(e,i.parts[p]);let d=B(e,l),h=d.map(([,p])=>p);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;h<n.parts.length;h++){let m=n.parts[h];if(m.type==="ParameterExpansion"&&!m.operation){let p=m.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(p){i=h,a=p[1],l=p[2]==="*";break}}}if(i===-1)return null;let o="";for(let h=0;h<i;h++)o+=await r(e,n.parts[h]);let u="";for(let h=i+1;h<n.parts.length;h++)u+=await r(e,n.parts[h]);let c=B(e,a),f=c.map(([,h])=>h);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
|
|
74
|
+
`);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<n.parts.length;v++){let E=n.parts[v];if(E.type==="ParameterExpansion"&&(E.parameter==="@"||E.parameter==="*")&&E.operation?.type==="Substring"){i=v,a=E.parameter==="*";break}}if(i===-1)return null;let o=n.parts[i].operation,u=o.offset?await s(e,o.offset.expression):0,c=o.length?await s(e,o.length.expression):void 0,f=Number.parseInt(e.state.env.get("#")||"0",10),d=[];for(let v=1;v<=f;v++)d.push(e.state.env.get(String(v))||"");let h=e.state.env.get("0")||"bash",m;if(u<=0){let v=[h,...d],E=v.length+u;if(E<0)m=[];else{let w=u<0?E:0;if(c!==void 0){let S=c<0?v.length+c:w+c;m=v.slice(w,Math.max(w,S))}else m=v.slice(w)}}else{let v=u-1;if(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;v<i;v++)p+=await r(e,n.parts[v]);let y="";for(let v=i+1;v<n.parts.length;v++)y+=await r(e,n.parts[v]);if(m.length===0){let v=p+y;return{values:v?[v]:[],quoted:!0}}if(a){let v=j(e.state.env);return{values:[p+m.join(v)+y],quoted:!0}}return m.length===1?{values:[p+m[0]+y],quoted:!0}:{values:[p+m[0],...m.slice(1,-1),m[m.length-1]+y],quoted:!0}}async function So(e,t,s,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0],i=-1,a=!1;for(let b=0;b<n.parts.length;b++){let v=n.parts[b];if(v.type==="ParameterExpansion"&&(v.parameter==="@"||v.parameter==="*")&&v.operation?.type==="PatternReplacement"){i=b,a=v.parameter==="*";break}}if(i===-1)return null;let o=n.parts[i].operation,u=bo(e),c="";for(let b=0;b<i;b++)c+=await s(e,n.parts[b]);let f="";for(let b=i+1;b<n.parts.length;b++)f+=await s(e,n.parts[b]);if(u.length===0){let b=c+f;return{values:b?[b]:[],quoted:!0}}let d="";if(o.pattern)for(let b of o.pattern.parts)if(b.type==="Glob")d+=G(b.pattern,!0,e.state.shoptOptions.extglob);else if(b.type==="Literal")d+=G(b.value,!0,e.state.shoptOptions.extglob);else if(b.type==="SingleQuoted"||b.type==="Escaped")d+=Q(b.value);else if(b.type==="DoubleQuoted"){let v=await r(e,b.parts);d+=Q(v)}else if(b.type==="ParameterExpansion"){let v=await s(e,b);d+=G(v,!0,e.state.shoptOptions.extglob)}else{let v=await s(e,b);d+=Q(v)}let h=o.replacement?await r(e,o.replacement.parts):"",m=d;o.anchor==="start"?m=`^${d}`:o.anchor==="end"&&(m=`${d}$`);let p=[];try{let b=le(m,o.all?"g":"");for(let v of u)p.push(b.replace(v,h))}catch{p.push(...u)}if(a){let b=j(e.state.env);return{values:[c+p.join(b)+f],quoted:!0}}return p.length===1?{values:[c+p[0]+f],quoted:!0}:{values:[c+p[0],...p.slice(1,-1),p[p.length-1]+f],quoted:!0}}async function Ao(e,t,s,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0],i=-1,a=!1;for(let y=0;y<n.parts.length;y++){let b=n.parts[y];if(b.type==="ParameterExpansion"&&(b.parameter==="@"||b.parameter==="*")&&b.operation?.type==="PatternRemoval"){i=y,a=b.parameter==="*";break}}if(i===-1)return null;let o=n.parts[i].operation,u=bo(e),c="";for(let y=0;y<i;y++)c+=await s(e,n.parts[y]);let f="";for(let y=i+1;y<n.parts.length;y++)f+=await s(e,n.parts[y]);if(u.length===0){let y=c+f;return{values:y?[y]:[],quoted:!0}}let d="",h=e.state.shoptOptions.extglob;if(o.pattern)for(let y of o.pattern.parts)if(y.type==="Glob")d+=G(y.pattern,o.greedy,h);else if(y.type==="Literal")d+=G(y.value,o.greedy,h);else if(y.type==="SingleQuoted"||y.type==="Escaped")d+=Q(y.value);else if(y.type==="DoubleQuoted"){let b=await r(e,y.parts);d+=Q(b)}else if(y.type==="ParameterExpansion"){let b=await s(e,y);d+=G(b,o.greedy,h)}else{let b=await s(e,y);d+=Q(b)}let m=[];for(let y of u)m.push(mt(y,d,o.side,o.greedy));if(a){let y=j(e.state.env);return{values:[c+m.join(y)+f],quoted:!0}}return m.length===1?{values:[c+m[0]+f],quoted:!0}:{values:[c+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function $o(e,t,s){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0],n=-1,i=!1;for(let d=0;d<r.parts.length;d++){let h=r.parts[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")){n=d,i=h.parameter==="*";break}}if(n===-1)return null;let a=r.parts[n];if(a.type==="ParameterExpansion"&&a.operation)return null;let l=Number.parseInt(e.state.env.get("#")||"0",10),o="";for(let d=0;d<n;d++)o+=await s(e,r.parts[d]);let u="";for(let d=n+1;d<r.parts.length;d++)u+=await s(e,r.parts[d]);if(l===0){if(i)return{values:[o+u],quoted:!0};let d=o+u;return{values:d?[d]:[],quoted:!0}}let c=[];for(let d=1;d<=l;d++)c.push(e.state.env.get(String(d))||"");if(i){let d=j(e.state.env);return{values:[o+c.join(d)+u],quoted:!0}}return c.length===1?{values:[o+c[0]+u],quoted:!0}:{values:[o+c[0],...c.slice(1,-1),c[c.length-1]+u],quoted:!0}}function Zu(e){return 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})}async function Ks(e,t){if(e.state.options.noglob)return t;let s=Zu(e),r=[];for(let n of t)if(nt(n,e.state.shoptOptions.extglob)){let i=await s.expand(n);if(i.length>0)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;v<t.length;v++){let E=t[v];if(E.type==="ParameterExpansion"&&E.operation?.type==="PatternReplacement"){let w=E.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(w){n=v,i=w[1],a=w[2]==="*";break}}}if(n===-1)return null;let o=t[n].operation,u=B(e,i),c=u.map(([,v])=>v);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;b<t.length;b++){let v=t[b];if(v.type==="ParameterExpansion"&&v.operation?.type==="PatternRemoval"){let E=v.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(E){n=b,i=E[1],a=E[2]==="*";break}}}if(n===-1)return null;let o=t[n].operation,u=B(e,i),c=u.map(([,b])=>b);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<t.length;y++){let b=t[y];if(b.type==="ParameterExpansion"&&(b.parameter==="@"||b.parameter==="*")&&b.operation?.type==="PatternRemoval"){n=y,i=b.parameter==="*";break}}if(n===-1)return null;let l=t[n].operation,o=Number.parseInt(e.state.env.get("#")||"0",10),u=[];for(let y=1;y<=o;y++)u.push(e.state.env.get(String(y))||"");if(u.length===0)return{values:[],quoted:!1};let c="",f=e.state.shoptOptions.extglob;if(l.pattern)for(let y of l.pattern.parts)if(y.type==="Glob")c+=G(y.pattern,l.greedy,f);else if(y.type==="Literal")c+=G(y.value,l.greedy,f);else if(y.type==="SingleQuoted"||y.type==="Escaped")c+=Q(y.value);else if(y.type==="DoubleQuoted"){let b=await s(e,y.parts);c+=Q(b)}else if(y.type==="ParameterExpansion"){let b=await r(e,y);c+=G(b,l.greedy,f)}else{let b=await r(e,y);c+=Q(b)}let d=[];for(let y of u)d.push(mt(y,c,l.side,l.greedy));let h=me(e.state.env),m=ve(e.state.env);if(i){let y=j(e.state.env),b=d.join(y);return m?{values:b?[b]:[],quoted:!1}:{values:re(b,h),quoted:!1}}if(m)return{values:d,quoted:!1};let p=[];for(let y of d)y===""?p.push(""):p.push(...re(y,h));return{values:p,quoted:!1}}async function _o(e,t,s,r){let n=-1,i=!1;for(let E=0;E<t.length;E++){let w=t[E];if(w.type==="ParameterExpansion"&&(w.parameter==="@"||w.parameter==="*")&&w.operation?.type==="Substring"){n=E,i=w.parameter==="*";break}}if(n===-1)return null;let l=t[n].operation,o=l.offset?await s(e,l.offset.expression):0,u=l.length?await s(e,l.length.expression):void 0,c=Number.parseInt(e.state.env.get("#")||"0",10),f=[];for(let E=1;E<=c;E++)f.push(e.state.env.get(String(E))||"");let d=e.state.env.get("0")||"bash",h;if(o<=0){let E=[d,...f],w=E.length+o;if(w<0)h=[];else{let S=o<0?w:0;if(u!==void 0){let A=u<0?E.length+u:S+u;h=E.slice(S,Math.max(S,A))}else h=E.slice(S)}}else{let E=o-1;if(E>=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;E<n;E++)m+=await r(e,t[E]);let p="";for(let E=n+1;E<t.length;E++)p+=await r(e,t[E]);let y=me(e.state.env),b=ve(e.state.env);if(h.length===0){let E=m+p;return E?b?{values:[E],quoted:!1}:{values:re(E,y),quoted:!1}:{values:[],quoted:!1}}let v;if(i){let E=j(e.state.env),w=m+h.join(E)+p;b?v=w?[w]:[]:v=re(w,y)}else if(b)h.length===1?v=[m+h[0]+p]:v=[m+h[0],...h.slice(1,-1),h[h.length-1]+p];else{v=[];for(let E=0;E<h.length;E++){let w=h[E];if(E===0&&(w=m+w),E===h.length-1&&(w=w+p),w==="")v.push("");else{let S=re(w,y);v.push(...S)}}}return{values:await Ks(e,v),quoted:!1}}async function xo(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].parameter!=="@"&&t[0].parameter!=="*"||t[0].operation)return null;let s=t[0].parameter==="*",r=Number.parseInt(e.state.env.get("#")||"0",10);if(r===0)return{values:[],quoted:!1};let n=[];for(let u=1;u<=r;u++)n.push(e.state.env.get(String(u))||"");let i=me(e.state.env),a=ve(e.state.env),l=js(e.state.env),o;if(s)if(a)o=n.filter(u=>u!=="");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;d<t.length;d++){let h=t[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")&&!h.operation){r=d;break}}if(r===-1||t.length<=1)return null;let n=Number.parseInt(e.state.env.get("#")||"0",10),i=[];for(let d=1;d<=n;d++)i.push(e.state.env.get(String(d))||"");let a="";for(let d=0;d<r;d++)a+=await s(e,t[d]);let l="";for(let d=r+1;d<t.length;d++)l+=await s(e,t[d]);let o=me(e.state.env),u=ve(e.state.env),c=js(e.state.env);if(n===0){let d=a+l;return{values:d?[d]:[],quoted:!1}}let f;{let d=[];for(let h=0;h<i.length;h++){let m=i[h];h===0&&(m=a+m),h===i.length-1&&(m=m+l),d.push(m)}if(u)f=d.filter(h=>h!=="");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;t<e.parts.length;t++){let s=e.parts[t];if(s.type!=="ParameterExpansion"||s.operation)continue;let r=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(r)return{type:"array",name:r[1],atIndex:t,isStar:r[2]==="*"};if(s.parameter==="@"||s.parameter==="*")return{type:"positional",atIndex:t,isStar:s.parameter==="*"}}return null}async function Yu(e,t,s,r){let n="";for(let l=0;l<s.atIndex;l++)n+=await r(e,t.parts[l]);let i="";for(let l=s.atIndex+1;l<t.parts.length;l++)i+=await r(e,t.parts[l]);let a;if(s.type==="array"){if(a=B(e,s.name).map(([,o])=>o),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;c<o.length;c++)l.push(o[c])}return l}async function To(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let s=[];for(let r of t)if(nt(r,e.state.shoptOptions.extglob)){let n=await Xs(e,r);s.push(...n)}else s.push(r);return{values:s,quoted:!1}}async function Xs(e,t){let s=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}),r=await s.expand(t);if(r.length>0)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;m<h.length-1;m++)l.push(h[m]);o=h[h.length-1]}c=!1,f=!1}else{let{words:h,hadLeadingDelimiter:m,hadTrailingDelimiter:p}=Us(d.value,s);if(f&&m&&o===""&&(l.push(""),u=!0),h.length===0)p&&(c=!0);else if(h.length===1)o+=h[0],u=!0,c=p;else{o+=h[0],l.push(o),u=!0;for(let y=1;y<h.length-1;y++)l.push(h[y]);o=h[h.length-1],c=p}f=!1}return o!==""?l.push(o):l.length===0&&u&&l.push(""),l}function rf(e,t){return e.length>0&&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;m<d.length-1;m++)a.push(d[m]);l=d[d.length-1],u=h}}return l!==""?a.push(l):a.length===0&&o&&a.push(""),a}function Vo(e){switch(e.type){case"Literal":return e.value;case"SingleQuoted":return e.value;case"Escaped":return e.value;default:return null}}function zo(e){switch(e.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return e.value==="";default:return!1}}function _t(e,t,s){if(e.length>t)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
|
|
75
|
+
`};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
|
|
76
|
+
`};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
|
|
77
|
+
`}}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}
|
|
78
|
+
`}:{target:n}:c.length===1?{target:c[0]}:{error:`bash: ${n}: ambiguous redirect
|
|
79
|
+
`}}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<r;a++)n.push(await Ve(e,s[a]));let i=n.join("");return _t(i,e.limits.maxStringLength,"word expansion"),i}async function Ve(e,t,s=!1){if(t.type==="ParameterExpansion")return Ys(e,t,s);let r=of(e,t,s);if(r!==null)return r;switch(t.type){case"DoubleQuoted":{let n=[];for(let i of t.parts)n.push(await Ve(e,i,!0));return n.join("")}case"CommandSubstitution":{let n=Ba(t.body);if(n)try{let d=await V(e,n.target),h=d.startsWith("/")?d:`${e.state.cwd}/${d}`,m=await e.fs.readFile(h);e.state.lastExitCode=0,e.state.env.set("?","0");let p=m.replace(/\n+$/,"");return _t(p,e.limits.maxStringLength,"command substitution"),p}catch(d){if(d instanceof X)throw d;return e.state.lastExitCode=1,e.state.env.set("?","1"),""}let i=e.substitutionDepth??0,a=e.limits.maxSubstitutionDepth;if(i>=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<<t;case">>":return e>>t;case"<":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?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<<t;case">>=":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(i<s.length){let a=s.slice(i).trim().split(/\s+/)[0];throw new se(`${s}: syntax error in expression (error token is "${a}")`)}return n.type==="ArithNumber"?n.value:t||0}catch(r){if(r instanceof se)throw r;let n=s.split(/\s+/).slice(1)[0]||s;throw new se(`${s}: syntax error in expression (error token is "${n}")`)}}async function Cr(e,t){if(!t)return 0;let s=Number.parseInt(t,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(t.trim()))return s;let r=t.trim();if(!r)return 0;let n=new q,{expr:i,pos:a}=We(n,r,0);if(a<r.length){let l=r.slice(a).trim(),o=l.split(/\s+/)[0]||l;throw new se(`syntax error in expression (error token is "${o}")`,"","")}return await T(e,i)}async function Dr(e,t,s=new Set,r=0){if(r>100)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(u<a.length){let c=a.slice(u).trim(),f=c.split(/\s+/)[0]||c;throw new se(`${a}: syntax error in expression (error token is "${f}")`)}return await T(e,o)}async function sn(e,t){if(t.startsWith("#")){let f=t.slice(1),d=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let m=d[1],p=B(e,m);return String(p.length)}let h=e.state.env.get(f)||"";return String(h.length)}if(t.startsWith("!")){let f=t.slice(1),d=e.state.env.get(f)||"";return e.state.env.get(d)||""}let s=[":-",":=",":?",":+","-","=","?","+"],r=-1,n="";for(let f of s){let d=t.indexOf(f);d>0&&(r===-1||d<r)&&(r=d,n=f)}if(r===-1)return await J(e,t);let i=t.slice(0,r),a=t.slice(r+n.length),l=e.state.env.get(i),o=l===void 0,u=l==="",c=n.startsWith(":");switch(n){case":-":case"-":return o||c&&u?a:l||"";case":=":case"=":return o||c&&u?(e.state.env.set(i,a),a):l||"";case":+":case"+":return!(o||c&&u)?a:"";case":?":case"?":{if(o||c&&u)throw new Error(a||`${i}: parameter null or not set`);return l||""}default:return l||""}}async function T(e,t,s=!1){switch(t.type){case"ArithNumber":if(Number.isNaN(t.value))throw new se("value too great for base");return t.value;case"ArithVariable":return await Dr(e,t.name);case"ArithSpecialVar":{let n=(await J(e,t.name)).trim();if(!n)return 0;let i=Number.parseInt(n,10);if(!Number.isNaN(i)&&/^-?\d+$/.test(n))return i;let a=new q,{expr:l}=We(a,n,0);return await T(e,l)}case"ArithNested":return await T(e,t.expression);case"ArithCommandSubst":{if(e.execFn){let r=await e.execFn(t.command,{signal:e.state.signal});r.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+r.stderr);let n=r.stdout.trim();return Number.parseInt(n,10)||0}return 0}case"ArithBracedExpansion":{let r=await sn(e,t.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=await sn(e,t.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)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
|
|
80
|
+
`,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
|
|
81
|
+
`,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;p<t.parts.length;p++){let y=t.parts[p];if(y.type==="Literal"){let b=y.value.indexOf("+=");if(b!==-1){let E=y.value.slice(0,b);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)){s=p,r=b,n=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(E)){s=p,r=b,n=!0;break}}let v=y.value.indexOf("=");if(v!==-1&&(v===0||y.value[v-1]!=="+")){let E=y.value.slice(0,v);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(E)){s=p,r=v;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),a=t.parts[s];if(a.type!=="Literal")return null;let l=n?2:1,o=a.value.slice(0,r),u=a.value.slice(r+l),c=t.parts.slice(s+1),f="";for(let p of i)f+=await V(e,{type:"Word",parts:[p]});f+=o;let d={type:"Word",parts:u!==""?[{type:"Literal",value:u},...c]:c},h=d.parts.length>0?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
|
|
82
|
+
`);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
|
|
83
|
+
`);s=r}throw new Oe(s)}async function Ir(e,t){let s,r=!1,n=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")n=!1,i++;else if(t[i]==="-P")n=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let a=t.slice(i);if(a.length===0||a[0]==="~"?s=e.state.env.get("HOME")||"/":a[0]==="-"?(s=e.state.previousDir,r=!0):s=a[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let f=e.state.env.get("CDPATH");if(f){let d=f.split(":").filter(h=>h);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
|
|
84
|
+
`)}catch{return N(`bash: cd: ${s}: No such file or directory
|
|
85
|
+
`)}}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}
|
|
86
|
+
`:"")}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.mtime<l.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(n)||!await e.fs.exists(i))return!1;let a=e.fs.resolvePath(e.state.cwd,n),l=e.fs.resolvePath(e.state.cwd,i);return a===l}catch{return!1}default:return!1}}var yf=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function ln(e){return yf.has(e)}function cn(e,t,s){switch(e){case"-eq":return t===s;case"-ne":return t!==s;case"-lt":return t<s;case"-le":return t<=s;case"-gt":return t>s;case"-ge":return t>=s}}function 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
|
|
87
|
+
`,!1;if(a=Math.max(...l)+1+a,a<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${o}: ${r}: bad array subscript
|
|
88
|
+
`,!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<o.length;u++)e.state.env.set(`BASH_REMATCH_${u}`,o[u]||"");return o!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<n;case">":return s>n;default:return!1}}case"CondUnary":{let s=await 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 ')'
|
|
89
|
+
`,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
|
|
90
|
+
`,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(r<i)}if(r==="!"){let a=await ys(e,[n,i]);return _("",a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(r==="("&&i===")")return pe(n!=="")}if(t.length===4){if(t[0]==="!"){let r=await ys(e,t.slice(1));return _("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return ys(e,[t[1],t[2]])}let s=await tl(e,t,0);return s.pos<t.length?N(`test: too many arguments
|
|
91
|
+
`,2):pe(s.value)}async function tl(e,t,s){return Ef(e,t,s)}async function Ef(e,t,s){let{value:r,pos:n}=await Yo(e,t,s);for(;t[n]==="-o";){let i=await Yo(e,t,n+1);r=r||i.value,n=i.pos}return{value:r,pos:n}}async function Yo(e,t,s){let{value:r,pos:n}=await Tr(e,t,s);for(;t[n]==="-a";){let i=await Tr(e,t,n+1);r=r&&i.value,n=i.pos}return{value:r,pos:n}}async function Tr(e,t,s){if(t[s]==="!"){let{value:r,pos:n}=await Tr(e,t,s+1);return{value:!r,pos:n}}return bf(e,t,s)}async function bf(e,t,s){let r=t[s];if(r==="("){let{value:i,pos:a}=await tl(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let n=t[s+1];if(gs(n)){let i=r,a=t[s+2]??"";return{value:un(n,i,a),pos:s+3}}if(ln(n)){let i=pn(r),a=pn(t[s+2]??"0");return!i.valid||!a.valid?{value:!1,pos:s+3}:{value:cn(n,i.value,a.value),pos:s+3}}if(an(n)){let i=r,a=t[s+2]??"";return{value:await on(e,n,i,a),pos:s+3}}if(nn(r)){let i=t[s+1]??"";return{value:await rn(e,r,i),pos:s+2}}if(fn(r)){let i=t[s+1]??"";return{value:dn(r,i),pos:s+2}}if(r==="-v"){let i=t[s+1]??"";return{value:await hn(e,i),pos:s+2}}if(r==="-o"){let i=t[s+1]??"";return{value:Lr(e,i),pos:s+2}}return{value:r!==void 0&&r!=="",pos:s+1}}function Ht(e,t,s=!1,r=!1){let n=`^${sl(t,r)}$`;return le(n,s?"is":"s").test(e)}function sl(e,t){let s="";for(let r=0;r<e.length;r++){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=nl(e,r+1);if(i!==-1){let a=e.slice(r+2,i),l=rl(a),o=l.map(c=>sl(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(i<e.length-1){let f=l.map(h=>il(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+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let i=e.indexOf("]",r+1);i!==-1?(s+=e.slice(r,i+1),r=i):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s}function nl(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function rl(e){let t=[],s="",r=0,n=0;for(;n<e.length;){let i=e[n];if(i==="\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i==="("?(r++,s+=i):i===")"?(r--,s+=i):i==="|"&&r===0?(t.push(s),s=""):s+=i,n++}return t.push(s),t}function il(e,t){let s=0,r=0;for(;r<e.length;){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=nl(e,r+1);if(i!==-1){if(n==="@"){let a=e.slice(r+2,i),o=rl(a).map(u=>il(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;)if(e[s]==="\\"&&s+1<e.length)t+=e[s]+e[s+1],s+=2;else if(e[s]==="["){let r=Af(e,s);t+=r.converted,s=r.endIndex}else t+=e[s],s++;return t}function Af(e,t){let s=t+1,r="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(r+="^",s++);let n=!1;s<e.length&&e[s]==="]"&&(n=!0,s++);let i=!1;s<e.length&&e[s]==="["&&s+1<e.length&&e[s+1]!==":"&&(i=!0,s++);let a="",l=!1;for(;s<e.length;){let o=e[s];if(o==="]"){l=!0,s++;break}if(o==="["&&s+1<e.length&&e[s+1]===":"){let u=e.indexOf(":]",s+2);if(u!==-1){let c=e.slice(s+2,u);a+=$f(c),s=u+2;continue}}if(o==="["&&s+1<e.length){let u=e[s+1];if(u==="."||u==="="){let c=`${u}]`,f=e.indexOf(c,s+2);if(f!==-1){let d=e.slice(s+2,f);a+=d,s=f+2;continue}}}if(o==="\\"&&s+1<e.length){a+=o+e[s+1],s+=2;continue}a+=o,s++}return l?(n&&(r+="\\]"),i&&(r+="\\["),r+=a,r+="]",{converted:r,endIndex:s}):{converted:"\\[",endIndex:t+1}}function $f(e){return new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]).get(e)??""}function ot(e){let t=[],s="",r=!1,n=!1,i=!1,a=!1;for(let l of e){if(i){s+=l,i=!1,a=!0;continue}if(l==="\\"){i=!0;continue}if(l==="'"&&!n){r||(a=!0),r=!r;continue}if(l==='"'&&!r){n||(a=!0),n=!n;continue}if((l===" "||l===" "||l===`
|
|
92
|
+
`)&&!r&&!n){a&&(t.push(s),s="",a=!1);continue}s+=l,a=!0}return a&&t.push(s),t}function mn(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!=="["){s++;continue}s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)r+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function al(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:ot(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes("=")){let r=e.indexOf("=");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function Pf(e,t){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}}async function ol(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:a,arrayIndex:l}=t,{makeReadonly:o=!1,checkReadonly:u=!0}=s;if(u){let c=ye(e,r);if(c)return c}if(n&&i){for(let c=0;c<i.length;c++)e.state.env.set(`${r}_${c}`,i[c]);e.state.env.set(`${r}__length`,String(i.length))}else if(l!==void 0&&a!==void 0){let c=await Pf(e,l);e.state.env.set(`${r}_${c}`,a);let f=parseInt(e.state.env.get(`${r}__length`)??"0",10);c>=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
|
|
16
93
|
`;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&s!=="/dev/null")return`bash: ${s}: cannot overwrite existing file
|
|
17
|
-
`}catch{}return null}function
|
|
18
|
-
`};s.set(r,await
|
|
19
|
-
`);else if(s.operator==="<"||s.operator==="<>")try{let i=e.fs.resolvePath(e.state.cwd,n),
|
|
20
|
-
`,1)}}}return null}async function
|
|
21
|
-
`,1);try{let
|
|
22
|
-
`,1);if(e.state.options.noclobber&&!
|
|
94
|
+
`}catch{}return null}function Xt(e){let s=Math.min(e.length,8192);for(let r=0;r<s;r++)if(e.charCodeAt(r)>127)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<t.length;r++){let n=t[r];if(n.target.type==="HereDoc")continue;if(n.operator===">&"||n.operator==="<&"){if(en(e,n.target))return{targets:s,error:`bash: $@: ambiguous redirect
|
|
95
|
+
`};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}
|
|
96
|
+
`);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
|
|
97
|
+
`,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
|
|
98
|
+
`,1);try{let l=await e.fs.stat(i);if(l.isDirectory)return _("",`bash: ${n}: Is a directory
|
|
99
|
+
`,1);if(e.state.options.noclobber&&!a&&!l.isDirectory&&n!=="/dev/null")return _("",`bash: ${n}: cannot overwrite existing file
|
|
23
100
|
`,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
|
|
24
|
-
`,1)}return null}async function
|
|
25
|
-
`,
|
|
26
|
-
`,
|
|
27
|
-
`,
|
|
28
|
-
`,
|
|
29
|
-
`,
|
|
30
|
-
`,
|
|
31
|
-
`,
|
|
32
|
-
`,
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
`;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
`,2);
|
|
41
|
-
`,2);
|
|
42
|
-
`,2);
|
|
43
|
-
`,2)
|
|
44
|
-
`,2);
|
|
45
|
-
`,2);
|
|
46
|
-
`,2)}else if(
|
|
47
|
-
`,2);
|
|
48
|
-
|
|
49
|
-
`,2);
|
|
50
|
-
|
|
51
|
-
`);for(let
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
`,2);
|
|
57
|
-
`,2);
|
|
58
|
-
`,2);
|
|
59
|
-
`,2)
|
|
60
|
-
`,2)
|
|
61
|
-
`,2)
|
|
62
|
-
`,2)}else if(d==="-
|
|
63
|
-
`,2)}
|
|
64
|
-
|
|
65
|
-
`,2)}else if(d==="--"){u.push(...t.slice(f+1));break}else d.startsWith("-")||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),W("");for(let f of u)e.state.completionSpecs.delete(f);return W("")}if(s)return u.length===0?lr(e):lr(e,u);if(t.length===0||u.length===0&&!i&&!o&&!a&&l.length===0&&c.length===0&&!n)return lr(e);if(o&&u.length===0&&!n)return A(`complete: -F: option requires a command name
|
|
66
|
-
`,2);if(n){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),o!==void 0&&(f.function=o),a!==void 0&&(f.command=a),l.length>0&&(f.options=l),c.length>0&&(f.actions=c),e.state.completionSpecs.set("__default__",f),W("")}for(let f of u){let d=Object.create(null);i!==void 0&&(d.wordlist=i),o!==void 0&&(d.function=o),a!==void 0&&(d.command=a),l.length>0&&(d.options=l),c.length>0&&(d.actions=c),e.state.completionSpecs.set(f,d)}return W("")}function lr(e,t){let s=e.state.completionSpecs;if(!s||s.size===0){if(t&&t.length>0){let i="";for(let o of t)i+=`complete: ${o}: no completion specification
|
|
67
|
-
`;return _("",i,1)}return W("")}let r=[],n=t||Array.from(s.keys());for(let i of n){if(i==="__default__")continue;let o=s.get(i);if(!o){if(t)return _(r.join(`
|
|
101
|
+
`,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<s.length;p++){let y=s[p];if(y.target.type==="HereDoc")continue;let b,v=r?.get(p);if(v!==void 0)b=v;else if(y.operator===">&"||y.operator==="<&"){if(en(e,y.target)){i+=`bash: $@: ambiguous redirect
|
|
102
|
+
`,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
|
|
103
|
+
`,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
|
|
104
|
+
`,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
|
|
105
|
+
`,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
|
|
106
|
+
`,a=1,n=""):w>=3&&(i+=`bash: ${w}: Bad file descriptor
|
|
107
|
+
`,a=1,n="")}}break}case"&>":{if(b==="/dev/full"){i=`bash: echo: write error: No space left on device
|
|
108
|
+
`,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
|
|
109
|
+
`,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
|
|
110
|
+
`;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(`
|
|
111
|
+
`).map(l=>l.replace(/^\t+/,"")).join(`
|
|
112
|
+
`)),(r.fd??0)===0&&(s=i)}else if(r.operator==="<<<"&&r.target.type==="Word")s=`${await V(e,r.target)}
|
|
113
|
+
`;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<s.length;u++)i.set(String(u+1),e.state.env.get(String(u+1))),e.state.env.set(String(u+1),s[u]);i.set("@",e.state.env.get("@")),i.set("#",e.state.env.get("#")),e.state.env.set("@",s.join(" ")),e.state.env.set("#",String(s.length));let a=()=>{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;w++){let S=t[w];if(S==="-v")s.push("variable");else if(S==="-e")s.push("export");else if(S==="-f")s.push("file");else if(S==="-d")s.push("directory");else if(S==="-k")s.push("keyword");else if(S==="-A"){if(w++,w>=t.length)return N(`compgen: -A: option requires an argument
|
|
114
|
+
`,2);let A=t[w];if(!m.includes(A))return N(`compgen: ${A}: invalid action name
|
|
115
|
+
`,2);s.push(A)}else if(S==="-W"){if(w++,w>=t.length)return N(`compgen: -W: option requires an argument
|
|
116
|
+
`,2);r=t[w]}else if(S==="-P"){if(w++,w>=t.length)return N(`compgen: -P: option requires an argument
|
|
117
|
+
`,2);n=t[w]}else if(S==="-S"){if(w++,w>=t.length)return N(`compgen: -S: option requires an argument
|
|
118
|
+
`,2);i=t[w]}else if(S==="-o"){if(w++,w>=t.length)return N(`compgen: -o: option requires an argument
|
|
119
|
+
`,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
|
|
120
|
+
`,2)}else if(S==="-F"){if(w++,w>=t.length)return N(`compgen: -F: option requires an argument
|
|
121
|
+
`,2);f=t[w]}else if(S==="-C"){if(w++,w>=t.length)return N(`compgen: -C: option requires an argument
|
|
122
|
+
`,2);d=t[w]}else if(S==="-X"){if(w++,w>=t.length)return N(`compgen: -X: option requires an argument
|
|
123
|
+
`,2);c=t[w]}else if(S==="-G"){if(w++,w>=t.length)return N(`compgen: -G: option requires an argument
|
|
124
|
+
`,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(`
|
|
125
|
+
`);for(let $ of A)$.length>0&&p.push($)}}catch(w){if(w.name==="ParseException")return N(`compgen: -C: ${w.message}
|
|
126
|
+
`,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(`
|
|
127
|
+
`),E=y+(v?`${v}
|
|
128
|
+
`:"");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")??`
|
|
129
|
+
`;if(s.length===0)return[t];let r=new Set(s.split("")),n=[],i="",a=0;for(;a<t.length;){let l=t[a];if(l==="\\"&&a+1<t.length){let o=t[a+1];i+=o,a+=2}else r.has(l)?(i.length>0&&(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;f++){let d=t[f];if(d==="-p")s=!0;else if(d==="-r")r=!0;else if(d==="-D")n=!0;else if(d==="-W"){if(f++,f>=t.length)return N(`complete: -W: option requires an argument
|
|
130
|
+
`,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return N(`complete: -F: option requires an argument
|
|
131
|
+
`,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return N(`complete: -o: option requires an argument
|
|
132
|
+
`,2);let h=t[f];if(!jf.includes(h))return N(`complete: ${h}: invalid option name
|
|
133
|
+
`,2);o.push(h)}else if(d==="-A"){if(f++,f>=t.length)return N(`complete: -A: option requires an argument
|
|
134
|
+
`,2);u.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return N(`complete: -C: option requires an argument
|
|
135
|
+
`,2);l=t[f]}else if(d==="-G"){if(f++,f>=t.length)return N(`complete: -G: option requires an argument
|
|
136
|
+
`,2)}else if(d==="-P"){if(f++,f>=t.length)return N(`complete: -P: option requires an argument
|
|
137
|
+
`,2)}else if(d==="-S"){if(f++,f>=t.length)return N(`complete: -S: option requires an argument
|
|
138
|
+
`,2)}else if(d==="-X"){if(f++,f>=t.length)return N(`complete: -X: option requires an argument
|
|
139
|
+
`,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
|
|
140
|
+
`,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
|
|
141
|
+
`;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(`
|
|
68
142
|
`)+(r.length>0?`
|
|
69
143
|
`:""),`complete: ${i}: no completion specification
|
|
70
|
-
`,1);continue}let
|
|
144
|
+
`,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(`
|
|
71
145
|
`)}
|
|
72
|
-
`)}var
|
|
73
|
-
`,2);let
|
|
74
|
-
`,2);n.push(
|
|
75
|
-
`,2);let
|
|
76
|
-
`,2);i.push(
|
|
77
|
-
`,1)}function
|
|
78
|
-
`);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new
|
|
79
|
-
`);s=r}throw new
|
|
80
|
-
`;else{let f=
|
|
81
|
-
`}continue}let
|
|
146
|
+
`)}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;l++){let o=t[l];if(o==="-D")s=!0;else if(o==="-E")r=!0;else if(o==="-o"){if(l++,l>=t.length)return N(`compopt: -o: option requires an argument
|
|
147
|
+
`,2);let u=t[l];if(!ml.includes(u))return N(`compopt: ${u}: invalid option name
|
|
148
|
+
`,2);n.push(u)}else if(o==="+o"){if(l++,l>=t.length)return N(`compopt: +o: option requires an argument
|
|
149
|
+
`,2);let u=t[l];if(!ml.includes(u))return N(`compopt: ${u}: invalid option name
|
|
150
|
+
`,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
|
|
151
|
+
`,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
|
|
152
|
+
`);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
|
|
153
|
+
`);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<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function Gr(e){let t="$'";for(let s=0;s<e.length;s++){let r=e[s],n=e.charCodeAt(s);n===7?t+="\\a":n===8?t+="\\b":n===9?t+="\\t":n===10?t+="\\n":n===11?t+="\\v":n===12?t+="\\f":n===13?t+="\\r":n===27?t+="\\e":n===39?t+="\\'":n===92?t+="\\\\":n<32||n===127?t+=`\\${n.toString(8).padStart(3,"0")}`:t+=r}return t+="'",t}function vn(e){return Zr(e)?Gr(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Lt(e){return Zr(e)?Gr(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Hr(e){return Zr(e)?Gr(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gl(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),te(e,t)&&(s+="n"),e.state.readonlyVars?.has(t)&&(s+="r"),e.state.uppercaseVars?.has(t)&&(s+="u"),e.state.exportedVars?.has(t)&&(s+="x"),s===""?"--":`-${s}`}function Qr(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function yl(e,t){let s="",r="",n=!1;for(let i of t){let a=gl(e,i);if(e.state.associativeArrays?.has(i)){let c=Ge(e,i);if(c.length===0)s+=`declare -A ${i}=()
|
|
154
|
+
`;else{let f=c.map(d=>{let h=e.state.env.get(`${i}_${d}`)??"",m=Qr(h);return`['${d}']=${m}`});s+=`declare -A ${i}=(${f.join(" ")})
|
|
155
|
+
`}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(" ")})
|
|
82
156
|
`;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=()
|
|
83
|
-
`;continue}let
|
|
84
|
-
`;else{let
|
|
157
|
+
`;continue}let u=e.state.env.get(i);if(u!==void 0)s+=`declare ${a} ${i}=${Hr(u)}
|
|
158
|
+
`;else{let c=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);c||f?s+=`declare ${a} ${i}
|
|
85
159
|
`:(r+=`bash: declare: ${i}: not found
|
|
86
|
-
`,n=!0)}}return _(s,r,n?1:0)}function
|
|
87
|
-
`;else{let
|
|
88
|
-
`}continue}if(
|
|
89
|
-
`;continue}if(e.state.env.has(`${f}__length`)){
|
|
90
|
-
`;continue}let
|
|
91
|
-
`)}return
|
|
92
|
-
`;else{let i=n.map(
|
|
93
|
-
`}}return
|
|
94
|
-
`;else{let
|
|
95
|
-
`}}return
|
|
96
|
-
`)}return
|
|
97
|
-
`,2)}}}else if(F==="-i")f=!0;else if(F==="-l")d=!0;else if(F==="-u")h=!0;else if(F==="-f")
|
|
98
|
-
`,2);else
|
|
99
|
-
`;return
|
|
100
|
-
`:
|
|
160
|
+
`,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}=()
|
|
161
|
+
`;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(" ")})
|
|
162
|
+
`}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(" ")})
|
|
163
|
+
`;continue}if(e.state.env.has(`${f}__length`)){o+=`declare -a ${f}=()
|
|
164
|
+
`;continue}let y=e.state.env.get(f);y!==void 0&&(o+=`declare ${d} ${f}=${Hr(y)}
|
|
165
|
+
`)}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}=()
|
|
166
|
+
`;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(" ")})
|
|
167
|
+
`}}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}=()
|
|
168
|
+
`;else{let a=i.map(l=>{let o=e.state.env.get(`${n}_${l}`)??"";return`[${l}]=${Lt(o)}`});t+=`declare -a ${n}=(${a.join(" ")})
|
|
169
|
+
`}}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)}
|
|
170
|
+
`)}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(;r<e.length;r++)if(e[r]==="[")n++;else if(e[r]==="]"&&(n--,n===0))break;if(n!==0)return null;let a=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let l=e.slice(r);return{name:s,indexExpr:a,value:l}}async function Jr(e,t){let s=!1,r=!1,n=!1,i=!1,a=!1,l=!1,o=!1,u=!1,c=!1,f=!1,d=!1,h=!1,m=!1,p=!1,y=!1,b=[];for(let C=0;C<t.length;C++){let F=t[C];if(F==="-a")s=!0;else if(F==="-A")r=!0;else if(F==="-r")n=!0;else if(F==="-x")i=!0;else if(F==="-p")a=!0;else if(F==="-n")l=!0;else if(F==="+n")o=!0;else if(F==="+a")u=!0;else if(F==="+x")c=!0;else if(F==="--"){b.push(...t.slice(C+1));break}else if(F.startsWith("+")){for(let k of F.slice(1))if(k==="n")o=!0;else if(k==="a")u=!0;else if(k==="x")c=!0;else if(k!=="r"){if(k!=="i"){if(!(k==="f"||k==="F"))return _("",`bash: typeset: +${k}: invalid option
|
|
171
|
+
`,2)}}}else if(F==="-i")f=!0;else if(F==="-l")d=!0;else if(F==="-u")h=!0;else if(F==="-f")m=!0;else if(F==="-F")p=!0;else if(F==="-g")y=!0;else if(F.startsWith("-"))for(let k of F.slice(1))if(k==="a")s=!0;else if(k==="A")r=!0;else if(k==="r")n=!0;else if(k==="x")i=!0;else if(k==="p")a=!0;else if(k==="n")l=!0;else if(k==="i")f=!0;else if(k==="l")d=!0;else if(k==="u")h=!0;else if(k==="f")m=!0;else if(k==="F")p=!0;else if(k==="g")y=!0;else return _("",`bash: typeset: -${k}: invalid option
|
|
172
|
+
`,2);else b.push(F)}let E=e.state.localScopes.length>0&&!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}
|
|
173
|
+
`;return H(x)}let C=!0,F="";for(let k of b)e.state.functions.has(k)?F+=`${k}
|
|
174
|
+
`: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} ()
|
|
101
175
|
{
|
|
102
176
|
# function body
|
|
103
177
|
}
|
|
104
|
-
`;return
|
|
105
|
-
`,
|
|
106
|
-
`,
|
|
107
|
-
`,
|
|
108
|
-
`,
|
|
109
|
-
`,
|
|
110
|
-
`,
|
|
111
|
-
`}}return
|
|
112
|
-
`,2);r=t[
|
|
113
|
-
`,2);if(r!==void 0)return
|
|
114
|
-
`,2);r=
|
|
115
|
-
`,1);let
|
|
116
|
-
`,1)}catch{return
|
|
117
|
-
`,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")||"",
|
|
118
|
-
`;return
|
|
119
|
-
`,2):
|
|
120
|
-
`,2);if(s.length===0)return
|
|
121
|
-
`,1);let r=s.shift();if(!r)return
|
|
122
|
-
`,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(
|
|
123
|
-
`;return
|
|
124
|
-
`,2);else return
|
|
125
|
-
`,1);if(r)return e.state.directoryStack=[],
|
|
126
|
-
`),
|
|
127
|
-
`):i?
|
|
178
|
+
`;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
|
|
179
|
+
`,R=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has(P)){$+=`bash: declare: ${P}: cannot convert associative to indexed array
|
|
180
|
+
`,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<z.length;U+=2){let ee=z[U],fe=U+1<z.length?de(e,z[U+1]):"";e.state.env.set(`${P}_${ee}`,fe)}}else{let z=ot(O);if(z.some(ee=>/^\[[^\]]+\]=/.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<z.length;ee++)e.state.env.set(`${P}_${ee}`,z[ee]);e.state.env.set(`${P}__length`,String(z.length))}}A(P),n&&De(e,P),i&&Qe(e,P);continue}if(o){let P=C.includes("=")?C.slice(0,C.indexOf("=")):C;if(Ma(e,P),!C.includes("="))continue}if(c){let P=C.includes("=")?C.slice(0,C.indexOf("=")):C;if(Hs(e,P),!C.includes("="))continue}let k=Gf(C);if(k){let{name:P,indexExpr:O,value:z}=k,U=ye(e,P);if(U)return U;S(P);let ee;try{let ge=new q,Re=Y(ge,O);ee=await T(e,Re.expression)}catch{let ge=parseInt(O,10);ee=Number.isNaN(ge)?0:ge}e.state.env.set(`${P}_${ee}`,z);let fe=parseInt(e.state.env.get(`${P}__length`)??"0",10);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;Vt<U.length;Vt++)e.state.env.set(`${P}_${fe+Vt}`,de(e,U[Vt]));let Re=fe+U.length;e.state.env.set(`${P}__length`,String(Re))}A(P),n&&De(e,P),i&&Qe(e,P);continue}let D=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(D){let P=D[1],O=de(e,D[2]),z=ye(e,P);if(z)return z;w(P),f&&Kr(e,P),d&&Xr(e,P),h&&Yr(e,P);let ee=he(e,P).length>0||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
|
|
181
|
+
`,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
|
|
182
|
+
`,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
|
|
183
|
+
`,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
|
|
184
|
+
`,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;a<t.length;a++){let l=t[a];if(l==="-a")s=!0;else if(l==="-A")r=!0;else if(l==="-p")n=!0;else if(l==="--"){i.push(...t.slice(a+1));break}else l.startsWith("-")||i.push(l)}if(i.length===0){let a="",l=Array.from(e.state.readonlyVars||[]).sort();for(let o of l){let u=e.state.env.get(o);if(u!==void 0){let c=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${o}="${c}"
|
|
185
|
+
`}}return H(a)}for(let a of i){let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(l){let f=l[1],d=l[2],h=ye(e,f);if(h)return h;let m=ot(d);if(e.state.associativeArrays?.has(f)){let p=mn(d);for(let[y,b]of p){let v=de(e,b);e.state.env.set(`${f}_${y}`,v)}}else{let p=he(e,f),y=0,b=e.state.env.get(f);p.length===0&&b!==void 0?(e.state.env.set(`${f}_0`,b),e.state.env.delete(f),y=1):p.length>0&&(y=Math.max(...p)+1);for(let E=0;E<m.length;E++)e.state.env.set(`${f}_${y+E}`,de(e,m[E]));let v=y+m.length;e.state.env.set(`${f}__length`,String(v))}De(e,f);continue}let o=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(o){let f=o[1],d=de(e,o[2]),h=ye(e,f);if(h)return h;let m=e.state.env.get(f)??"";e.state.env.set(f,m+d),De(e,f);continue}let u=al(a);if(u.value===void 0&&!u.isArray){De(e,u.name);continue}let c=await ol(e,u,{makeReadonly:!0});if(c)return c}return K}function ti(e){return e.state.directoryStack??=[],e.state.directoryStack}function Es(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Hf(e){let t=e.split("/").filter(r=>r&&r!=="."),s=[];for(let r of t)r===".."?s.pop():s.push(r);return`/${s.join("/")}`}async function si(e,t){let s=ti(e),r;for(let l=0;l<t.length;l++){let o=t[l];if(o==="--"){if(l+1<t.length){if(r!==void 0)return N(`bash: pushd: too many arguments
|
|
186
|
+
`,2);r=t[l+1],l++}}else{if(o.startsWith("-")&&o!=="-")return N(`bash: pushd: ${o}: invalid option
|
|
187
|
+
`,2);if(r!==void 0)return N(`bash: pushd: too many arguments
|
|
188
|
+
`,2);r=o}}if(r===void 0){if(s.length<2)return N(`bash: pushd: no other directory
|
|
189
|
+
`,1);let l=s[0];s[0]=s[1],s[1]=l,r=s[0]}let n;if(r.startsWith("/"))n=r;else if(r===".."){let l=e.state.cwd.split("/").filter(o=>o);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
|
|
190
|
+
`,1)}catch{return N(`bash: pushd: ${r}: No such file or directory
|
|
191
|
+
`,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(" ")}
|
|
192
|
+
`;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
|
|
193
|
+
`,2):N(`bash: popd: too many arguments
|
|
194
|
+
`,2);if(s.length===0)return N(`bash: popd: directory stack empty
|
|
195
|
+
`,1);let r=s.shift();if(!r)return N(`bash: popd: directory stack empty
|
|
196
|
+
`,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(" ")}
|
|
197
|
+
`;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
|
|
198
|
+
`,2);else return N(`bash: dirs: too many arguments
|
|
199
|
+
`,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(`
|
|
200
|
+
`),u+=`
|
|
201
|
+
`):i?u=l.map(c=>n?c:Es(c,o)).join(`
|
|
128
202
|
`)+`
|
|
129
|
-
`:
|
|
130
|
-
`,
|
|
203
|
+
`:u=l.map(c=>n?c:Es(c,o)).join(" ")+`
|
|
204
|
+
`,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
|
|
131
205
|
eval: usage: eval [arg ...]
|
|
132
|
-
`,2)}if(r.length===0)return
|
|
133
|
-
`);throw
|
|
134
|
-
`,s=2):s=(i%256+256)%256}throw new
|
|
135
|
-
`}}return
|
|
136
|
-
`,i=1;continue}if(
|
|
137
|
-
`);let s=t[0],r=t[1],n=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=s.startsWith(":"),
|
|
138
|
-
`,n||e.state.env.set(r,"?"),f+1<
|
|
139
|
-
`,n||e.state.env.set(r,"?")),e.state.env.set("OPTIND",String(
|
|
140
|
-
`,1);
|
|
141
|
-
`,1):
|
|
142
|
-
`,1);
|
|
143
|
-
`,1);let
|
|
144
|
-
`,
|
|
145
|
-
`,1);let
|
|
146
|
-
`:
|
|
147
|
-
`:(
|
|
148
|
-
`,p=!0)}return p?{exitCode:1,stdout:
|
|
149
|
-
`,1);let
|
|
150
|
-
`);let
|
|
151
|
-
`;else{
|
|
152
|
-
`;for(let[,p]of e.state.hashTable)
|
|
153
|
-
`}return
|
|
154
|
-
`,
|
|
155
|
-
`,
|
|
206
|
+
`,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}
|
|
207
|
+
`);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
|
|
208
|
+
`,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}"
|
|
209
|
+
`}}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
|
|
210
|
+
`,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 ...]
|
|
211
|
+
`);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}
|
|
212
|
+
`,n||e.state.env.set(r,"?"),f+1<c.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(o))):(e.state.env.set("OPTIND",String(o+1)),e.state.env.set("__GETOPTS_CHARINDEX","0")),{exitCode:n?2:0,stdout:"",stderr:p}}if(h+1<a.length&&a[h+1]===":")if(f+1<c.length)e.state.env.set("OPTARG",c.slice(f+1)),e.state.env.set("OPTIND",String(o+1)),e.state.env.set("__GETOPTS_CHARINDEX","0");else{if(o>=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}
|
|
213
|
+
`,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<c.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(o))):(e.state.env.set("OPTIND",String(o+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"));return n||e.state.env.set(r,d),{exitCode:n?2:0,stdout:"",stderr:""}}async function oi(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,r=!1,n=!1,i=!1,a=!1,l="",o=[],u=0;for(;u<t.length;){let m=t[u];if(m==="--"){u++,o.push(...t.slice(u));break}if(m==="-r")s=!0,u++;else if(m==="-d")r=!0,u++;else if(m==="-l")n=!0,u++;else if(m==="-t")a=!0,u++;else if(m==="-p"){if(i=!0,u++,u>=t.length)return N(`bash: hash: -p: option requires an argument
|
|
214
|
+
`,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
|
|
215
|
+
`,1):N(`bash: hash: -${p}: invalid option
|
|
216
|
+
`,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
|
|
217
|
+
`,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
|
|
218
|
+
`,m=!0);return m?N(p,1):K}if(a){if(o.length===0)return N(`bash: hash: -t: option requires an argument
|
|
219
|
+
`,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}
|
|
220
|
+
`:m+=`${v}
|
|
221
|
+
`:(y+=`bash: hash: ${b}: not found
|
|
222
|
+
`,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 ...]
|
|
223
|
+
`,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
|
|
224
|
+
`);let m="";if(n)for(let[p,y]of e.state.hashTable)m+=`builtin hash -p ${y} ${p}
|
|
225
|
+
`;else{m=`hits command
|
|
226
|
+
`;for(let[,p]of e.state.hashTable)m+=` 1 ${p}
|
|
227
|
+
`}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
|
|
228
|
+
`,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
|
|
229
|
+
`,c=!0)}return c?N(f,1):K}var Al=new Map([[":",[": [arguments]",`Null command.
|
|
156
230
|
No effect; the command does nothing.
|
|
157
231
|
Exit Status:
|
|
158
232
|
Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
|
|
@@ -497,32 +571,32 @@ eval: usage: eval [arg ...]
|
|
|
497
571
|
job specification, and reports its termination status.
|
|
498
572
|
Exit Status:
|
|
499
573
|
Returns the status of the last ID; fails if ID is invalid or an invalid
|
|
500
|
-
option is given.`]]])
|
|
501
|
-
`,2)}n++}else r.push(
|
|
502
|
-
`,
|
|
503
|
-
`:i+=`${
|
|
574
|
+
option is given.`]]]),$l=[...Al.keys()].sort();function li(e,t){let s=!1,r=[],n=0;for(;n<t.length;){let o=t[n];if(o==="--"){for(n++;n<t.length;)r.push(t[n]),n++;break}if(o.startsWith("-")&&o.length>1){for(let u=1;u<o.length;u++){let c=o[u];if(c==="s")s=!0;else return N(`bash: help: -${c}: invalid option
|
|
575
|
+
`,2)}n++}else r.push(o),n++}if(r.length===0)return Kf();let i="",a=!1,l="";for(let o of r){let u=Qf(o);if(u.length===0){l+=`bash: help: no help topics match \`${o}'. Try \`help help' or \`man -k ${o}' or \`info ${o}'.
|
|
576
|
+
`,a=!0;continue}for(let c of u){let f=Al.get(c);if(!f)continue;let[d,h]=f;s?i+=`${c}: ${d}
|
|
577
|
+
`:i+=`${c}: ${d}
|
|
504
578
|
${h}
|
|
505
|
-
`}}return{exitCode:
|
|
579
|
+
`}}return{exitCode:a?1:0,stdout:i,stderr:l}}function Qf(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=le(`^${t}$`);return $l.filter(r=>s.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;n<r;n++){let i=s[n]||"",a=s[n+r]||"",l=i.padEnd(t);e.push(a?`${l}${a}`:i)}return H(`${e.join(`
|
|
506
580
|
`)}
|
|
507
|
-
`)}function
|
|
508
|
-
`);let s=
|
|
509
|
-
`)}return _("","",r===0?1:0)}async function
|
|
510
|
-
`);let s=e.state.localScopes[e.state.localScopes.length-1],r="",n=0,i=!1,
|
|
511
|
-
`)}return _(
|
|
512
|
-
`,n=1;continue}if(
|
|
513
|
-
`,n=1;continue}let
|
|
514
|
-
`,n=1;continue}e.state.env.set(
|
|
515
|
-
`,n=0,i=0,
|
|
516
|
-
`,
|
|
517
|
-
`,1);let
|
|
518
|
-
`,1);f.push(
|
|
519
|
-
`,
|
|
520
|
-
`){
|
|
521
|
-
`){k+=2;continue}if(D===
|
|
522
|
-
`&&
|
|
523
|
-
`)&&(
|
|
524
|
-
`,1);
|
|
525
|
-
`,2);s=(n%256+256)%256}throw new
|
|
581
|
+
`)}function Xf(e){let t=[],s="",r=0;for(let n of e){for(let i of n)i==="("?r++:i===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(t.push(s),s="")}return s&&t.push(s),t}async function ci(e,t){if(t.length===0)return N(`bash: let: expression expected
|
|
582
|
+
`);let s=Xf(t),r=0;for(let n of s)try{let a=Ce(`(( ${n} ))`).statements[0];if(a&&a.pipelines.length>0&&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}
|
|
583
|
+
`)}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
|
|
584
|
+
`);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}
|
|
585
|
+
`)}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
|
|
586
|
+
`,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;w<E.length;w++)e.state.env.set(`${c}_${w}`,E[w]);e.state.env.set(`${c}__length`,String(E.length)),Ct(e,c),i&&pt(e,c);continue}let h=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(h){c=h[1];let b=h[2];if(ye(e,c,"bash"),!s.has(c)){s.set(c,e.state.env.get(c));let $=`${c}_`;for(let C of e.state.env.keys())C.startsWith($)&&!C.includes("__")&&(s.has(C)||s.set(C,e.state.env.get(C)));let R=`${c}__length`;e.state.env.has(R)&&!s.has(R)&&s.set(R,e.state.env.get(R))}let v=ot(b),E=he(e,c),w=0,S=e.state.env.get(c);E.length===0&&S!==void 0?(e.state.env.set(`${c}_0`,S),e.state.env.delete(c),w=1):E.length>0&&(w=Math.max(...E)+1);for(let $=0;$<v.length;$++)e.state.env.set(`${c}_${w+$}`,de(e,v[$]));let A=w+v.length;e.state.env.set(`${c}__length`,String(A)),Ct(e,c),i&&pt(e,c);continue}let m=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){c=m[1];let b=de(e,m[2]);ye(e,c,"bash"),s.has(c)||s.set(c,e.state.env.get(c));let v=e.state.env.get(c)??"";e.state.env.set(c,v+b),Ct(e,c),i&&pt(e,c);continue}let p=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(p){c=p[1];let b=p[2],v=de(e,p[3]);if(ye(e,c,"bash"),!s.has(c)){s.set(c,e.state.env.get(c));let S=`${c}_`;for(let $ of e.state.env.keys())$.startsWith(S)&&!$.includes("__")&&(s.has($)||s.set($,e.state.env.get($)));let A=`${c}__length`;e.state.env.has(A)&&!s.has(A)&&s.set(A,e.state.env.get(A))}let E;try{let S=new q,A=Y(S,b);E=await T(e,A.expression)}catch{let S=parseInt(b,10);E=Number.isNaN(S)?0:S}e.state.env.set(`${c}_${E}`,v);let w=parseInt(e.state.env.get(`${c}__length`)??"0",10);E>=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
|
|
587
|
+
`,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
|
|
588
|
+
`,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=`
|
|
589
|
+
`,n=0,i=0,a=0,l=!1,o="MAPFILE",u=0;for(;u<t.length;){let v=t[u];v==="-d"&&u+1<t.length?(r=t[u+1]===""?"\0":t[u+1]||`
|
|
590
|
+
`,u+=2):v==="-n"&&u+1<t.length?(n=Number.parseInt(t[u+1],10)||0,u+=2):v==="-O"&&u+1<t.length?(i=Number.parseInt(t[u+1],10)||0,u+=2):v==="-s"&&u+1<t.length?(a=Number.parseInt(t[u+1],10)||0,u+=2):v==="-t"?(l=!0,u++):v==="-u"||v==="-C"||v==="-c"?u+=2:(v.startsWith("-")||(o=v),u++)}let c=s;!c&&e.state.groupStdin!==void 0&&(c=e.state.groupStdin);let f=[],d=c,h=0,m=0,p=e.limits?.maxArrayElements??1e5;for(;d.length>0;){let v=d.indexOf(r);if(v===-1){if(d.length>0){if(m<a)m++;else if(n===0||h<n){if(i+h>=p)return _("",`mapfile: array element limit exceeded (${p})
|
|
591
|
+
`,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),m<a){m++;continue}if(n>0&&h>=n)break;if(i+h>=p)return _("",`mapfile: array element limit exceeded (${p})
|
|
592
|
+
`,1);f.push(E),h++}i===0&&tt(e,o);for(let v=0;v<f.length;v++)e.state.env.set(`${o}_${i+v}`,f[v]);let y=parseInt(e.state.env.get(`${o}__length`)||"0",10),b=i+f.length;return e.state.env.set(`${o}__length`,String(Math.max(y,b))),e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=""),_("","",0)}function Yf(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}}function Jf(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}function di(e,t,s,r=-1){let n=!1,i=`
|
|
593
|
+
`,a="",l=-1,o=-1,u=null,c=-1,f=-1,d=[],h=0,m=!1,p=(k,x)=>{let D=1;for(;D<k.length;){let P=k[D];if(P==="r")n=!0,D++;else if(P==="s")D++;else{if(P==="d")return D+1<k.length?(i=k.substring(D+1),{nextArgIndex:x+1}):x+1<t.length?(i=t[x+1],{nextArgIndex:x+2}):{nextArgIndex:x+1};if(P==="n"){if(D+1<k.length){let O=k.substring(D+1);return l=Number.parseInt(O,10),(Number.isNaN(l)||l<0)&&(m=!0,l=0),{nextArgIndex:x+1}}else if(x+1<t.length)return l=Number.parseInt(t[x+1],10),(Number.isNaN(l)||l<0)&&(m=!0,l=0),{nextArgIndex:x+2};return{nextArgIndex:x+1}}else if(P==="N"){if(D+1<k.length){let O=k.substring(D+1);return o=Number.parseInt(O,10),(Number.isNaN(o)||o<0)&&(m=!0,o=0),{nextArgIndex:x+1}}else if(x+1<t.length)return o=Number.parseInt(t[x+1],10),(Number.isNaN(o)||o<0)&&(m=!0,o=0),{nextArgIndex:x+2};return{nextArgIndex:x+1}}else{if(P==="a")return D+1<k.length?(u=k.substring(D+1),{nextArgIndex:x+1}):x+1<t.length?(u=t[x+1],{nextArgIndex:x+2}):{nextArgIndex:x+1};if(P==="p")return D+1<k.length?(a=k.substring(D+1),{nextArgIndex:x+1}):x+1<t.length?(a=t[x+1],{nextArgIndex:x+2}):{nextArgIndex:x+1};if(P==="u"){if(D+1<k.length){let O=k.substring(D+1);return c=Number.parseInt(O,10),Number.isNaN(c)||c<0?{nextArgIndex:-2}:{nextArgIndex:x+1}}else if(x+1<t.length)return c=Number.parseInt(t[x+1],10),Number.isNaN(c)||c<0?{nextArgIndex:-2}:{nextArgIndex:x+2};return{nextArgIndex:x+1}}else if(P==="t"){if(D+1<k.length){let O=k.substring(D+1);return f=Number.parseFloat(O),Number.isNaN(f)&&(f=0),{nextArgIndex:x+1}}else if(x+1<t.length)return f=Number.parseFloat(t[x+1]),Number.isNaN(f)&&(f=0),{nextArgIndex:x+2};return{nextArgIndex:x+1}}else if(P==="e"||P==="i"||P==="P"){if(P==="i"&&x+1<t.length)return{nextArgIndex:x+2};D++}else D++}}}return{nextArgIndex:x+1}};for(;h<t.length;){let k=t[h];if(k.startsWith("-")&&k.length>1&&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<t.length;)d.push(t[h]),h++;else d.push(k),h++}if(m)return _("","",1);if(d.length===0&&u===null&&d.push("REPLY"),f===0){if(u)tt(e,u);else{for(let k of d)e.state.env.set(k,"");d.length===0&&e.state.env.set("REPLY","")}return _("","",0)}if(f<0&&f!==-1)return _("","",1);let y=s;c>=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<d.length;D++)e.state.env.set(d[D],"");return _("","",w?0:1)}else if(l>=0){let k=0,x=0,D=!1;for(;x<y.length&&k<l;){let P=y[x];if(P===b){E=x+1,D=!0;break}if(!n&&P==="\\"&&x+1<y.length){let O=y[x+1];if(O===b&&b===`
|
|
594
|
+
`){x+=2,E=x;continue}if(O===b){x+=2,k++,v+=O,E=x;continue}v+=O,x+=2,k++,E=x}else v+=P,x++,k++,E=x}w=k>=l||D,S(E)}else{E=0;let k=0;for(;k<y.length;){let x=y[k];if(x===b){E=k+b.length,w=!0;break}if(!n&&x==="\\"&&k+1<y.length){let D=y[k+1];if(D===`
|
|
595
|
+
`){k+=2;continue}if(D===b){v+=D,k+=2;continue}v+=x,v+=D,k+=2;continue}v+=x,k++}if(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===`
|
|
596
|
+
`&&v.endsWith(`
|
|
597
|
+
`)&&(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})
|
|
598
|
+
`,1);tt(e,u);for(let D=0;D<k.length;D++)e.state.env.set(`${u}_${D}`,A(k[D]));return _("","",w?0:1)}let R=d.length,{words:C,wordStarts:F}=Sr(v,$,R,n);for(let k=0;k<d.length;k++){let x=d[k];if(k<d.length-1)e.state.env.set(x,A(C[k]??""));else if(k<F.length){let D=v.substring(F[k]);D=La(D,$,n),D=A(D),e.state.env.set(x,D)}else e.state.env.set(x,"")}return _("","",w?0:1)}function hi(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return N("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let r=t[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return N(`bash: return: ${r}: numeric argument required
|
|
599
|
+
`,2);s=(n%256+256)%256}throw new ke(s)}var bs=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
526
600
|
Options:
|
|
527
601
|
-e Exit immediately if a command exits with non-zero status
|
|
528
602
|
+e Disable -e
|
|
@@ -538,174 +612,174 @@ Options:
|
|
|
538
612
|
+o pipefail Disable pipefail
|
|
539
613
|
-o xtrace Same as -x
|
|
540
614
|
+o xtrace Disable xtrace
|
|
541
|
-
`,
|
|
615
|
+
`,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<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function td(e,t){let s=he(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{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(`
|
|
542
616
|
`)}
|
|
543
|
-
`}function
|
|
617
|
+
`}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(`
|
|
544
618
|
`)}
|
|
545
|
-
`}function
|
|
619
|
+
`}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])=>d<h?-1:d>h?1:0))u.push(`${c}=${vn(f)}`);for(let c of[...i].sort((f,d)=>f<d?-1:f>d?1:0))u.push(td(e,c));for(let c of[...a].sort((f,d)=>f<d?-1:f>d?1:0))u.push(nd(e,c));return u.sort((c,f)=>{let d=c.split("=")[0],h=f.split("=")[0];return d<h?-1:d>h?1:0}),H(u.length>0?`${u.join(`
|
|
546
620
|
`)}
|
|
547
|
-
`:"")}let s=[],r=()=>s.length>0?
|
|
548
|
-
${
|
|
549
|
-
${
|
|
550
|
-
${
|
|
551
|
-
${
|
|
552
|
-
`;if(e.state.options.posix)throw new
|
|
553
|
-
`;if(e.state.options.posix)throw new
|
|
554
|
-
`,2);let r=s[0],n=null,i=null;if(r.includes("/")){let
|
|
555
|
-
`);let
|
|
556
|
-
`);throw
|
|
557
|
-
`,n=1;continue}let
|
|
558
|
-
`,n=1;continue}if(
|
|
559
|
-
`,n=1;continue}let
|
|
560
|
-
`,n=1;continue}let
|
|
561
|
-
`,n=1;continue}let
|
|
562
|
-
`,n=1;continue}let f=
|
|
563
|
-
`,n=1;continue}let
|
|
564
|
-
`,n=1;continue}if(
|
|
565
|
-
`,n=1;continue}let
|
|
566
|
-
`,n=1;continue}let
|
|
567
|
-
`,n=1;continue}let
|
|
568
|
-
`,n=1;continue}let
|
|
569
|
-
`}}}
|
|
570
|
-
`};if(
|
|
621
|
+
`:"")}let s=[],r=()=>s.length>0?H(s.join("")):K,n=0;for(;n<t.length;){let i=t[n];if((i==="-o"||i==="+o")&&ed(t,n)){let a=t[n+1];if(!$n.has(a)){let l=`bash: set: ${a}: invalid option name
|
|
622
|
+
${bs}`;if(e.state.options.posix)throw new Be(1,"",l);return N(l)}pi(e,$n.get(a)??null,i==="-o"),n+=2;continue}if(i==="-o"){s.push(kl(e)),n++;continue}if(i==="+o"){s.push(Nl(e)),n++;continue}if(i.length>1&&(i[0]==="-"||i[0]==="+")&&i[1]!=="-"){let a=i[0]==="-",l=0;for(let o=1;o<i.length;o++){let u=i[o];if(u==="o"){let c=n+1+l;if(c<t.length&&!t[c].startsWith("-")&&!t[c].startsWith("+")){let d=t[c];if(!$n.has(d)){let h=`bash: set: ${d}: invalid option name
|
|
623
|
+
${bs}`;if(e.state.options.posix)throw new Be(1,"",h);return N(h)}pi(e,$n.get(d)??null,a),l++;continue}s.push(a?kl(e):Nl(e));continue}if(!Pl.has(u)){let c=`bash: set: ${i[0]}${u}: invalid option
|
|
624
|
+
${bs}`;if(e.state.options.posix)throw new Be(1,"",c);return N(c)}pi(e,Pl.get(u)??null,a)}n+=1+l;continue}if(i==="--")return mi(e,t.slice(n+1)),r();if(i==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,jt(e),n+1<t.length)return mi(e,t.slice(n+1)),r();n++;continue}if(i==="+"){n++;continue}if(i.startsWith("-")||i.startsWith("+")){let a=`bash: set: ${i}: invalid option
|
|
625
|
+
${bs}`;if(e.state.options.posix)throw new Be(1,"",a);return N(a)}return mi(e,t.slice(n)),r()}return r()}function mi(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let r=0;r<t.length;r++)e.state.env.set(String(r+1),t[r]);e.state.env.set("#",String(t.length)),e.state.env.set("@",t.join(" ")),e.state.env.set("*",t.join(" "))}function yi(e,t){let s=1;if(t.length>0){let a=Number.parseInt(t[0],10);if(Number.isNaN(a)||a<0){let l=`bash: shift: ${t[0]}: numeric argument required
|
|
626
|
+
`;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
|
|
627
|
+
`;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;a<i.length;a++)e.state.env.set(String(a+1),i[a]);return e.state.env.set("#",String(i.length)),e.state.env.set("@",i.join(" ")),K}async function wi(e,t){let s=t;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return _("",`bash: source: filename argument required
|
|
628
|
+
`,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
|
|
629
|
+
`);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<u.length&&c<9;c++)e.state.env.set(String(c+1),u[c]);for(let c=u.length+1;c<=9;c++)e.state.env.delete(String(c))}let l=e.state.currentSource,o=()=>{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}
|
|
630
|
+
`);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
|
|
631
|
+
`,n=1;continue}let v=await Dl(e,h);if(v===null&&p){r+=`bash: unset: ${h}: not a valid identifier
|
|
632
|
+
`,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
|
|
633
|
+
`,n=1;continue}let A=w+v;if(A<0){r+=`bash: line ${S}: unset: [${v}]: bad array subscript
|
|
634
|
+
`,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
|
|
635
|
+
`,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
|
|
636
|
+
`,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
|
|
637
|
+
`,n=1;continue}let m=await Dl(e,c);if(m===null&&d){r+=`bash: unset: ${c}: not a valid identifier
|
|
638
|
+
`,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
|
|
639
|
+
`,n=1;continue}let v=y+m;if(v<0){r+=`bash: line ${b}: unset: [${m}]: bad array subscript
|
|
640
|
+
`,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
|
|
641
|
+
`,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
|
|
642
|
+
`,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(;o<t.length;){let d=t[o];if(d==="--"){o++;break}if(d.startsWith("-")&&d.length>1){for(let h=1;h<d.length;h++){let m=d[h];switch(m){case"s":s=!0;break;case"u":r=!0;break;case"p":n=!0;break;case"q":i=!0;break;case"o":a=!0;break;default:return{exitCode:2,stdout:"",stderr:`shopt: -${m}: invalid option
|
|
643
|
+
`}}}o++}else break}for(;o<t.length;)l.push(t[o]),o++;if(a)return cd(e,l,s,r,n,i);if(s&&r)return{exitCode:1,stdout:"",stderr:`shopt: cannot set and unset shell options simultaneously
|
|
644
|
+
`};if(l.length===0){if(s||r){let h=[];for(let m of vi){let p=e.state.shoptOptions[m];s&&p?h.push(n?`shopt -s ${m}`:`${m} on`):r&&!p&&h.push(n?`shopt -u ${m}`:`${m} off`)}return{exitCode:0,stdout:h.length>0?`${h.join(`
|
|
571
645
|
`)}
|
|
572
|
-
`:"",stderr:""}}let d=[];for(let h of
|
|
646
|
+
`:"",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(`
|
|
573
647
|
`)}
|
|
574
|
-
`,stderr:""}}let
|
|
575
|
-
`,
|
|
648
|
+
`,stderr:""}}let u=!1,c="",f=[];for(let d of l){if(!Pn(d)&&!ld(d)){c+=`shopt: ${d}: invalid shell option name
|
|
649
|
+
`,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(`
|
|
576
650
|
`)}
|
|
577
|
-
`:"",stderr:
|
|
651
|
+
`:"",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(`
|
|
578
652
|
`)}
|
|
579
|
-
`:"",stderr:""}}let
|
|
580
|
-
`,
|
|
653
|
+
`:"",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
|
|
654
|
+
`,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(`
|
|
581
655
|
`)}
|
|
582
|
-
`:"",stderr:
|
|
583
|
-
`;h=!0,
|
|
584
|
-
`,h=!0,
|
|
585
|
-
`;else{let
|
|
586
|
-
`;
|
|
587
|
-
`:
|
|
588
|
-
`),
|
|
589
|
-
`:
|
|
590
|
-
`),
|
|
591
|
-
`;else{let
|
|
592
|
-
`;
|
|
593
|
-
`:
|
|
594
|
-
`),
|
|
595
|
-
`:n?
|
|
596
|
-
`:
|
|
597
|
-
`,h=!0,
|
|
598
|
-
`:n?
|
|
599
|
-
`:
|
|
600
|
-
`,h=!0,
|
|
601
|
-
`)}}}return i?d=
|
|
656
|
+
`:"",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+=`${$}
|
|
657
|
+
`;h=!0,y=!0}}else{let A=await s(p);A&&(c+=`${A}
|
|
658
|
+
`,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
|
|
659
|
+
`;else{let A=e.state.functions.get(p),$=A?Ml(p,A):`${p} is a function
|
|
660
|
+
`;c+=$}y=!0}let v=e.state.env.get(`BASH_ALIAS_${p}`);if(v!==void 0&&(l||!y)&&(i||(n?c+=`alias
|
|
661
|
+
`:c+=`${p} is aliased to \`${v}'
|
|
662
|
+
`),y=!0,!l)||Wr.has(p)&&(l||!y)&&(i||(n?c+=`keyword
|
|
663
|
+
`:c+=`${p} is a shell keyword
|
|
664
|
+
`),y=!0,!l))continue;if(!l&&b&&!y){if(!i)if(n)c+=`function
|
|
665
|
+
`;else{let A=e.state.functions.get(p),$=A?Ml(p,A):`${p} is a function
|
|
666
|
+
`;c+=$}y=!0;continue}if(!(Kt.has(p)&&(l||!y)&&(i||(n?c+=`builtin
|
|
667
|
+
`:c+=`${p} is a shell builtin
|
|
668
|
+
`),y=!0,!l))){if(l){let A=await r(p);for(let $ of A)i?c+=`${$}
|
|
669
|
+
`:n?c+=`file
|
|
670
|
+
`:c+=`${p} is ${$}
|
|
671
|
+
`,h=!0,y=!0}else if(!y){let A=await s(p);A&&(i?c+=`${A}
|
|
672
|
+
`:n?c+=`file
|
|
673
|
+
`:c+=`${p} is ${A}
|
|
674
|
+
`,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
|
|
675
|
+
`)}}}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
|
|
602
676
|
${e} ()
|
|
603
677
|
{
|
|
604
678
|
${s}
|
|
605
679
|
}
|
|
606
|
-
`}function
|
|
607
|
-
`:n+=`alias ${
|
|
608
|
-
`;else if(
|
|
609
|
-
`:n+=`${
|
|
610
|
-
`;else if(
|
|
611
|
-
`:n+=`${
|
|
612
|
-
`;else if(e.state.functions.has(
|
|
613
|
-
`:n+=`${
|
|
614
|
-
`;else if(
|
|
615
|
-
`:n+=`${
|
|
616
|
-
`,
|
|
617
|
-
`),
|
|
680
|
+
`}function vs(e){if(Array.isArray(e))return e.map(t=>vs(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let r=e.pipelines[s];t.push(dd(r)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(Wl(t.name));for(let r of t.args)s.push(Wl(r));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>vs(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}"
|
|
681
|
+
`:n+=`alias ${l}='${o}'
|
|
682
|
+
`;else if(Wr.has(l))r?n+=`${l} is a shell keyword
|
|
683
|
+
`:n+=`${l}
|
|
684
|
+
`;else if(Kt.has(l))r?n+=`${l} is a shell builtin
|
|
685
|
+
`:n+=`${l}
|
|
686
|
+
`;else if(e.state.functions.has(l))r?n+=`${l} is a function
|
|
687
|
+
`:n+=`${l}
|
|
688
|
+
`;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}
|
|
689
|
+
`:n+=`${l}
|
|
690
|
+
`,c=!0)}catch{}c||(r&&(i+=`${l}: not found
|
|
691
|
+
`),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}
|
|
618
692
|
`:n+=`${f}
|
|
619
|
-
`}else r&&(i+=`${
|
|
620
|
-
`),
|
|
621
|
-
`);let[,...
|
|
622
|
-
`,127):
|
|
623
|
-
`,127);if("error"in
|
|
624
|
-
`,126):
|
|
625
|
-
`,127);if("script"in
|
|
626
|
-
`)}}async function
|
|
627
|
-
`,exitCode:1}}async function
|
|
628
|
-
`,exitCode:1}}return{stdout:n,stderr:i,exitCode:
|
|
629
|
-
`);let
|
|
693
|
+
`}else r&&(i+=`${l}: not found
|
|
694
|
+
`),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
|
|
695
|
+
`);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.
|
|
696
|
+
`,127):N(`bash: ${t}: command not found
|
|
697
|
+
`,127);if("error"in u)return u.error==="permission_denied"?N(`bash: ${t}: Permission denied
|
|
698
|
+
`,126):N(`bash: ${t}: No such file or directory
|
|
699
|
+
`,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))}
|
|
700
|
+
`)}}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}
|
|
701
|
+
`,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)}
|
|
702
|
+
`,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
|
|
703
|
+
`);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(`
|
|
630
704
|
`).map(d=>d.replace(/^\t+/,"")).join(`
|
|
631
|
-
`)),
|
|
632
|
-
`;else if(
|
|
633
|
-
`)}let
|
|
634
|
-
`,t||
|
|
635
|
-
`),n=e.includes(" "),i=e.includes("\\"),
|
|
636
|
-
`?
|
|
637
|
-
`}async function
|
|
638
|
-
`:""}async function
|
|
705
|
+
`)),l=f}else if(u.operator==="<<<"&&u.target.type==="Word")l=`${await V(e,u.target)}
|
|
706
|
+
`;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
|
|
707
|
+
`)}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;u<t.items.length;u++){let c=t.items[u],f=l;if(!l)for(let d of c.patterns){let h=await V(e,d);Bo(d)&&(h=Fe(h));let m=e.state.shoptOptions.nocasematch,p=e.state.shoptOptions.extglob;if(Ht(a,h,m,p)){f=!0;break}}if(f){let d=await Nn(e,c.body,r,n);if(r=d.stdout,n=d.stderr,i=d.exitCode,c.terminator===";;")break;c.terminator===";&"?l=!0:l=!1}else l=!1}let o=_(r,n,i);return ue(e,o,t.redirections)}function Ai(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function Xl(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}}var Yl="+ ";async function Jl(e){let t=e.state.env.get("PS4");if(t===void 0)return Yl;if(t==="")return"";try{let r=new q().parseWordFromString(t,!1,!1);return await V(e,r)}catch{return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${t}: bad substitution
|
|
708
|
+
`,t||Yl}}function md(e){return e.map(t=>gd(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(`
|
|
709
|
+
`),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===`
|
|
710
|
+
`?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}
|
|
711
|
+
`}async function tc(e,t,s){return e.state.options.xtrace?`${await Jl(e)}${t}=${s}
|
|
712
|
+
`:""}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;d<t.commands.length;d++){let h=t.commands[d],m=d===t.commands.length-1,p=d===0;u&&(e.state.lastArg="",p||(e.state.groupStdin=void 0));let b=u&&(!m||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,v;try{v=await s(h,n)}catch(E){if(E instanceof Me)v={stdout:E.stdout,stderr:E.stderr,exitCode:1};else if(E instanceof Z&&t.commands.length>1)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<l.length;d++)e.state.env.set(`PIPESTATUS_${d}`,String(l[d]));e.state.env.set("PIPESTATUS__length",String(l.length))}if(e.state.options.pipefail&&a!==0&&(i={...i,exitCode:a}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let h=(Bn()-r)/1e3,m=Math.floor(h/60),p=h%60,y;t.timePosix?y=`real ${h.toFixed(2)}
|
|
639
713
|
user 0.00
|
|
640
714
|
sys 0.00
|
|
641
|
-
`:
|
|
642
|
-
real ${`${
|
|
715
|
+
`:y=`
|
|
716
|
+
real ${`${m}m${p.toFixed(3)}s`}
|
|
643
717
|
user 0m0.000s
|
|
644
718
|
sys 0m0.000s
|
|
645
|
-
`,i={...i,stderr:i.stderr+
|
|
646
|
-
`,1)};let
|
|
647
|
-
`,1)};if(
|
|
648
|
-
`,1)}}if(
|
|
649
|
-
`,{continueToNext:!0,xtraceOutput:
|
|
650
|
-
`)}}async function
|
|
651
|
-
`,1)};
|
|
652
|
-
`;if(i.fatal)throw new
|
|
653
|
-
`,1)}}if(n=Math.max(...i.map(([
|
|
654
|
-
`,1)}}}return{index:n}}async function
|
|
655
|
-
`,1)};if(f===null)return{continueToNext:!0,xtraceOutput:""};
|
|
656
|
-
`,{continueToNext:!0,xtraceOutput:
|
|
657
|
-
`,1);return
|
|
719
|
+
`,i={...i,stderr:i.stderr+y}}return u&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=c),i}async function nc(e,t){let s=new Map,r="";for(let n of t.assignments){let i=n.name;if(n.array){let c=await yd(e,t,i,n.array,n.append,s);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:c.error};if(r+=c.xtraceOutput,c.continueToNext)continue}let a=n.value?await V(e,n.value):"";if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:_("",`bash: ${i}: bad array subscript
|
|
720
|
+
`,1)};let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let c=await Sd(e,t,o[1],o[2],a,n.append,s);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:c.error};if(c.continueToNext)continue}let u=await $d(e,t,i,a,n.append,s);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:u.error};r+=u.xtraceOutput,u.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:s}}async function yd(e,t,s,r,n,i){let a="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:_("",`bash: ${s}: cannot assign list to array member
|
|
721
|
+
`,1)};if(te(e,s)){let c=Tt(e,s);if(c===void 0||c==="")throw new Z(1,"","");let f=$e(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:_("",`bash: ${s}: cannot assign list to array member
|
|
722
|
+
`,1)}}if(rt(e,s)){if(t.name)return a+=`bash: ${s}: readonly variable
|
|
723
|
+
`,{continueToNext:!0,xtraceOutput:a};let c=ye(e,s);if(c)return{continueToNext:!1,xtraceOutput:"",error:c}}let l=e.state.associativeArrays?.has(s),o=wd(r),u=()=>{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
|
|
724
|
+
`)}}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;l<i.length;l++)e.state.env.set(`${t}_${a+l}`,i[l]);r||e.state.env.set(`${t}__length`,String(i.length))}async function Sd(e,t,s,r,n,i,a){let l=s;if(te(e,s)){let f=$e(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:_("",`bash: \`${f}': not a valid identifier
|
|
725
|
+
`,1)};l=f}}if(rt(e,l)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=ye(e,l);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let o=e.state.associativeArrays?.has(l),u;if(o)u=await rc(e,l,r);else{let f=await Ad(e,l,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};u=`${l}_${f.index}`}let c=i?(e.state.env.get(u)||"")+n:n;if(t.name)a.set(u,e.state.env.get(u)),e.state.env.set(u,c);else{let f=Qt(e,l);if(f!==void 0&&f===e.state.callDepth&&e.state.localScopes.length>0){let d=e.state.localScopes[e.state.localScopes.length-1];d.has(u)||d.set(u,e.state.env.get(u))}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}
|
|
726
|
+
`;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
|
|
727
|
+
`,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
|
|
728
|
+
`,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
|
|
729
|
+
`,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
|
|
730
|
+
`,{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($)}
|
|
731
|
+
`,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(`
|
|
658
732
|
`).map(p=>p.replace(/^\t+/,"")).join(`
|
|
659
|
-
`));let
|
|
660
|
-
`;else if(f.operator==="<"&&f.target.type==="Word")try{let d=await
|
|
661
|
-
`,1)}let
|
|
662
|
-
`,1)}e.state.groupStdin=
|
|
663
|
-
`,127)}if(i.startsWith("#!")){let
|
|
664
|
-
`);
|
|
665
|
-
`);throw
|
|
666
|
-
`);let n=0,i=-1,
|
|
667
|
-
`).map(
|
|
668
|
-
`))
|
|
669
|
-
`);continue}if(
|
|
670
|
-
`)}if(
|
|
671
|
-
`,127)}if(
|
|
672
|
-
`)}break}case"<>":{let
|
|
673
|
-
`);return
|
|
674
|
-
`,n);return
|
|
733
|
+
`));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)}
|
|
734
|
+
`;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
|
|
735
|
+
`,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)}
|
|
736
|
+
`,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
|
|
737
|
+
`,127)}if(i.startsWith("#!")){let y=i.indexOf(`
|
|
738
|
+
`);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<s.length&&y<9;y++)e.state.env.set(String(y+1),s[y]);for(let y=s.length+1;y<=9;y++)e.state.env.delete(String(y));let p=()=>{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}
|
|
739
|
+
`);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}
|
|
740
|
+
`);let n=0,i=-1,a=!1;for(let u=0;u<t.pipelines.length;u++){let c=t.pipelines[u],f=u>0?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=i<t.pipelines.length-1,o=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=l||a||o,this.ctx.state.options.errexit&&n!==0&&i===t.pipelines.length-1&&!a&&!this.ctx.state.inCondition&&!o)throw new ze(n,s,r);return _(s,r,n)}async executePipeline(t){return sc(this.ctx,t,(s,r)=>this.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(`
|
|
741
|
+
`).map(R=>R.replace(/^\t+/,"")).join(`
|
|
742
|
+
`)),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)}
|
|
743
|
+
`);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
|
|
744
|
+
`)}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
|
|
745
|
+
`,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
|
|
746
|
+
`)}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;w<this.ctx.state.extraArgs.length;w++)d.push(!0);this.ctx.state.extraArgs=void 0}let m=await ec(this.ctx,c,f);n.size>0&&(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}
|
|
747
|
+
`);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}
|
|
748
|
+
`,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:
|
|
675
749
|
${h.join(`
|
|
676
|
-
`)}`)}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
|
|
677
|
-
`)}function
|
|
678
|
-
${n}${s.delimiter}`}return e.operator==="<<<"?`${t}<<< ${
|
|
679
|
-
`)}function
|
|
680
|
-
${
|
|
681
|
-
${
|
|
750
|
+
`)}`)}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(`
|
|
751
|
+
`)}function yc(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(jd(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let s=t.join(" ");return e.background&&(s+=" &"),s}function jd(e){let t=[];e.timed&&t.push(e.timePosix?"time -p":"time"),e.negated&&t.push("!");let s=[];for(let n=0;n<e.commands.length;n++)if(s.push(wc(e.commands[n])),n<e.commands.length-1){let i=e.pipeStderr?.[n];s.push(i?"|&":"|")}return(t.length>0?`${t.join(" ")} `:"")+s.join(" ")}function 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}
|
|
752
|
+
${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(`
|
|
753
|
+
`)}function eh(e){let t=[];for(let s=0;s<e.clauses.length;s++){let r=e.clauses[s],n=s===0?"if":"elif";t.push(`${n} ${Ue(r.condition)}; then
|
|
754
|
+
${Ue(r.body)}`)}return e.elseBody&&t.push(`else
|
|
755
|
+
${Ue(e.elseBody)}`),`${t.join(`
|
|
682
756
|
`)}
|
|
683
|
-
fi${
|
|
684
|
-
${
|
|
685
|
-
done${
|
|
686
|
-
${
|
|
687
|
-
done${
|
|
688
|
-
${
|
|
689
|
-
done${
|
|
690
|
-
${
|
|
691
|
-
done${
|
|
692
|
-
`);return`case ${
|
|
757
|
+
fi${Ye(e.redirections)}`}function th(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let s=e.words.map(be).join(" ");t=`for ${e.variable} in ${s}`}return`${t}; do
|
|
758
|
+
${Ue(e.body)}
|
|
759
|
+
done${Ye(e.redirections)}`}function sh(e){let t=e.init?ie(e.init.expression):"",s=e.condition?ie(e.condition.expression):"",r=e.update?ie(e.update.expression):"";return`for ((${t}; ${s}; ${r})); do
|
|
760
|
+
${Ue(e.body)}
|
|
761
|
+
done${Ye(e.redirections)}`}function nh(e){return`while ${Ue(e.condition)}; do
|
|
762
|
+
${Ue(e.body)}
|
|
763
|
+
done${Ye(e.redirections)}`}function rh(e){return`until ${Ue(e.condition)}; do
|
|
764
|
+
${Ue(e.body)}
|
|
765
|
+
done${Ye(e.redirections)}`}function ih(e){let t=e.items.map(ah).join(`
|
|
766
|
+
`);return`case ${be(e.word)} in
|
|
693
767
|
${t}
|
|
694
|
-
esac${
|
|
768
|
+
esac${Ye(e.redirections)}`}function ah(e){let t=e.patterns.map(be).join(" | "),s=Ue(e.body);return s?`${t})
|
|
695
769
|
${s}
|
|
696
770
|
${e.terminator}`:`${t})
|
|
697
|
-
${e.terminator}`}function
|
|
698
|
-
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(this.limits=
|
|
771
|
+
${e.terminator}`}function oh(e){return`(${Ue(e.body)})${Ye(e.redirections)}`}function lh(e){return`{ ${Ue(e.body)}; }${Ye(e.redirections)}`}function ch(e){return`((${ie(e.expression.expression)}))${Ye(e.redirections)}`}function uh(e){return`[[ ${Mt(e.expression)} ]]${Ye(e.redirections)}`}function fh(e){let t=wc(e.body);return`${e.name}() ${t}${Ye(e.redirections)}`}function ie(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${ie(e.left)} ${e.operator} ${ie(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${ie(e.operand)}`:`${ie(e.operand)}${e.operator}`;case"ArithTernary":return`${ie(e.condition)} ? ${ie(e.consequent)} : ${ie(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${ie(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${ie(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${ie(e.target)}[${ie(e.subscript)}]`:ie(e.target)} ${e.operator} ${ie(e.value)}`;case"ArithDynamicElement":return`${ie(e.nameExpr)}[${ie(e.subscript)}]`;case"ArithGroup":return`(${ie(e.expression)})`;case"ArithNested":return`$((${ie(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${ie(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(ie).join("");case"ArithDoubleSubscript":return`${e.array}[${ie(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function Mt(e){switch(e.type){case"CondBinary":return`${be(e.left)} ${e.operator} ${be(e.right)}`;case"CondUnary":return`${e.operator} ${be(e.operand)}`;case"CondNot":return`! ${Mt(e.operand)}`;case"CondAnd":return`${Mt(e.left)} && ${Mt(e.right)}`;case"CondOr":return`${Mt(e.left)} || ${Mt(e.right)}`;case"CondGroup":return`( ${Mt(e.expression)} )`;case"CondWord":return be(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var Ps=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;invokeToolFn;transformPlugins=[];state;constructor(t={}){let s=t.fs??new ht(t.files);this.fs=s,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),n=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
772
|
+
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(this.limits=lc({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=Ni(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth??!0,this.coverageWriter=t.coverage,this.state={env:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:t.processInfo?.pid??1,virtualPpid:t.processInfo?.ppid??0,virtualUid:t.processInfo?.uid??1e3,virtualGid:t.processInfo?.gid??1e3,bashPid:t.processInfo?.pid??1,nextVirtualPid:(t.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",Un(this.state.options)),this.state.env.set("BASHOPTS",Zn(this.state.shoptOptions)),Bi(s,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&s instanceof ht)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let a of Oi(t.commands))this.registerCommand(a);if(t.fetch||t.network)for(let a of Ti())this.registerCommand(a);if(t.python)for(let a of Li())this.registerCommand(a);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);if(t.javascript||i.invokeTool){for(let a of Mi())this.registerCommand(a);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(t.customCommands)for(let a of t.customCommands)Wi(a)?this.registerCommand(Fi(a)):this.registerCommand({...a,trusted:a.trusted??!0})}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let r=`#!/bin/bash
|
|
699
773
|
# Built-in command: ${t.name}
|
|
700
|
-
`;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=
|
|
701
|
-
`,exitCode:1,env:
|
|
702
|
-
`,exitCode:1,env:
|
|
703
|
-
`,exitCode:2,env:
|
|
704
|
-
`,exitCode:2,env:
|
|
705
|
-
`,exitCode:1,env:
|
|
706
|
-
`),s=[],r=[];for(let
|
|
707
|
-
`)}var kl=new TextDecoder("utf-8",{fatal:!0});function so(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);try{return kl.decode(s)}catch{return e}}function _l(e,t){if(e!==void 0)return t==="bytes"?e:Be(e)}var Ns=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new ze,t?.mounts)for(let{mountPoint:s,filesystem:r}of t.mounts)this.mount(s,r)}mount(t,s){this.validateMountPath(t);let r=O(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(t){let s=O(t);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=O(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){x(t,"access");let s=O(t),r=null,n=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(s===o)return{fs:i.filesystem,relativePath:"/"};s.startsWith(`${o}/`)&&o.length>n&&(r=i,n=o.length)}if(r){let i=s.slice(n);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(t){let s=O(t),r=s==="/"?"/":`${s}/`,n=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!n.includes(a)&&n.push(a)}return n}async readFile(t,s){let{fs:r,relativePath:n}=this.routePath(t);return r.readFile(n,s)}async readFileBytes(t){let{fs:s,relativePath:r}=this.routePath(t);return Bt(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=O(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=O(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.stat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.stat(o)}async lstat(t){let s=O(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.lstat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.lstat(o)}async mkdir(t,s){let r=O(t);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:i,relativePath:o}=this.routePath(t);return i.mkdir(o,s)}async readdir(t){let s=O(t),r=new Set,n=null,{fs:i,relativePath:o}=this.routePath(t);try{let l=await i.readdir(o);for(let c of l)r.add(c)}catch(l){let c=l.code,u=l.message||"";if(c!=="ENOENT"&&!u.includes("ENOENT"))throw l;n=l}let a=this.getChildMountPoints(s);for(let l of a)r.add(l);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(t,s){let r=O(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:o}=this.routePath(t);return i.rm(o,s)}async cp(t,s,r){let n=this.routePath(t),i=this.routePath(s);return n.fs===i.fs?n.fs.cp(n.relativePath,i.relativePath,r):this.crossMountCopy(t,s,r)}async mv(t,s){let r=O(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 qe(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 o of r)n=`${n}/${o}`,t.add(n);let i=this.mounts.get(s);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?t.add(s):t.add(`${s}${o}`)}return Array.from(t).sort()}async chmod(t,s){let r=O(t),n=this.mounts.get(r);if(n)return n.filesystem.chmod("/",s);let{fs:i,relativePath:o}=this.routePath(t);return i.chmod(o,s)}async symlink(t,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(t,n)}async link(t,s){let r=this.routePath(t),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readlink(r)}async realpath(t){let s=O(t);if(this.mounts.get(s))return s;let{fs:n,relativePath:i}=this.routePath(t),o=await n.realpath(i);for(let[a,l]of this.mounts)if(s===a||s.startsWith(`${a}/`))return o==="/"?a:`${a}${o}`;return o}async crossMountCopy(t,s,r){let n=await this.lstat(t);if(n.isFile){let i=await this.readFileBuffer(t);await this.writeFile(s,i),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let i=await this.readdir(t);for(let o of i){let a=Ge(t,o),l=Ge(s,o);await this.crossMountCopy(a,l,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 q from"node:fs";import*as ae from"node:path";import*as Pe from"node:fs";import*as ce from"node:path";function Ne(e,t){if(e===t)return!0;let s=e[t.length];return(s==="/"||s==="\\")&&e.startsWith(t)}function at(e,t){try{let s=Pe.realpathSync(e);return Ne(s,t)?s:null}catch(s){if(s.code==="ENOENT"){let r=ce.dirname(e);if(r===e)return null;let n=at(r,t);if(n===null)return null;try{if(Pe.lstatSync(e).isSymbolicLink()){let o=Pe.readlinkSync(e),a=ce.isAbsolute(o)?o:ce.resolve(ce.dirname(e),o);if(at(a,t)===null)return null}}catch{}return ce.join(n,ce.basename(e))}return null}}function Os(e,t,s){let r=at(e,s);if(r===null)return null;let n=ce.resolve(e),i=n.slice(t.length),o=r.slice(s.length);if(i!==o)return null;try{if(Pe.lstatSync(n).isSymbolicLink())return null}catch{}return r}function xs(e,t){if(!Pe.existsSync(e))throw new Error(`${t} root does not exist`);if(!Pe.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function ro(e,t){if(!ce.isAbsolute(e))return{withinRoot:!0,relativePath:e};let s;try{s=Pe.realpathSync(e)}catch{s=ce.resolve(e)}return Ne(s,t)?{withinRoot:!0,relativePath:s.slice(t.length).replace(/\\/g,"/")||"/"}:{withinRoot:!1,safeName:ce.basename(e)}}function Ts(e,t,s,r){let n=e;if(n.path===void 0){for(let o of r)if(n.message?.includes(o))throw e}let i=n.code||"EIO";throw new Error(`${i}: ${s} '${t}'`)}var Cl=["ELOOP","EFBIG","EPERM"],Nl="/home/user/project",$t=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;allowSymlinks;memory=new Map;deleted=new Set;constructor(t){this.root=ae.resolve(t.root);let s=t.mountPoint??Nl;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,xs(this.root,"OverlayFs"),this.canonicalRoot=q.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=O(t).split("/").filter(Boolean),i="";for(let o of n)i+=`/${o}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=O(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=O(t),r=this.getRelativeToMount(s);if(r===null)return null;let n=ae.join(this.root,r),i=ae.resolve(n);return Ne(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?at(t,this.canonicalRoot):Os(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let s=ae.dirname(t),r=this.resolveRealPath_(s);return r===null?null:ae.join(r,ae.basename(t))}sanitizeError(t,s,r){Ts(t,s,r,Cl)}ensureParentDirs(t){let s=st(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=O(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 q.promises.lstat(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=Ee(s);return Me(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return Me(s,"binary")}async readFileBuffer(t,s=new Set){x(t,"open");let r=O(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target);return this.readFileBuffer(o,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.content}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let o=await q.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let c=await q.promises.readlink(i),u=this.realTargetToVirtual(r,c),f=this.resolveSymlink(r,u);return this.readFileBuffer(f,s)}if(o.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&o.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${o.size} bytes, max ${this.maxFileReadSize})`);let a=this.allowSymlinks?q.constants.O_RDONLY:q.constants.O_RDONLY|q.constants.O_NOFOLLOW,l=await q.promises.open(i,a);try{let c=await l.readFile();return new Uint8Array(c)}finally{await l.close()}}catch(o){let a=o.code;if(a==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(a==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(o,t,"open")}}async writeFile(t,s,r){x(t,"write"),this.assertWritable(`write '${t}'`);let n=O(t);this.ensureParentDirs(n);let i=Ee(r),o=Fe(s,i);this.memory.set(n,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){x(t,"append"),this.assertWritable(`append '${t}'`);let n=O(t),i=Ee(r),o=Fe(s,i),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+o.length);l.set(a),l.set(o,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){x(t,"stat");let r=O(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.stat(a,s)}let o=0;return n.type==="file"&&(o=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:o,mtime:n.mtime}}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await q.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let a=await q.promises.readlink(i),l=this.realTargetToVirtual(r,a),c=this.resolveSymlink(r,l);return this.stat(c,s)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){x(t,"lstat");let s=O(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 q.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 ct(t,s)}realTargetToVirtual(t,s){let r=ro(s,this.canonicalRoot);if(r.withinRoot){if(!ae.isAbsolute(s))return s;let n=r.relativePath;return this.mountPoint==="/"?n:`${this.mountPoint}${n}`}return r.safeName}async mkdir(t,s){x(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=O(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=st(r);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let a of this.deleted)if(a.startsWith(i)){let l=a.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let[a,l]of this.memory)if(a!==s&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!n.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let o=this.resolveRealPath_(this.toRealPath(s));if(o)try{if(!this.allowSymlinks&&(await q.promises.lstat(o)).isSymbolicLink()){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let a=await q.promises.readdir(o,{withFileTypes:!0});for(let l of a)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else a.code!=="ENOTDIR"&&this.sanitizeError(a,t,"scandir")}return r}async resolveForReaddir(t,s=!1){let r=O(t),n=new Set,i=s,o=this.memory.get(r);for(;o&&o.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,o.target),o=this.memory.get(r)}if(o)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await q.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await q.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){x(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){x(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,s){x(t,"rm"),this.assertWritable(`rm '${t}'`);let r=O(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let o=await this.readdir(r);if(o.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of o){let l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,s)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.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 q.lstatSync(r),!0}catch{return!1}}async cp(t,s,r){x(t,"cp"),x(s,"cp"),this.assertWritable(`cp '${s}'`);let n=O(t),i=O(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let a=await this.stat(n);if(a.isFile){let l=await this.readFileBuffer(n);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let c of l){let u=n==="/"?`/${c}`:`${n}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){return qe(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=q.readdirSync(r);for(let i of n){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(o))continue;s.add(o);let a=ae.join(r,i);q.lstatSync(a).isDirectory()&&this.scanRealFs(o,s)}}catch{}}async chmod(t,s){x(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=O(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let o=await this.stat(r);if(o.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:s,mtime:new Date})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);x(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=O(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){x(t,"link"),x(s,"link"),this.assertWritable(`link '${s}'`);let r=O(t),n=O(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:o.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){x(t,"readlink");let s=O(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 q.promises.readlink(n);if(!ae.isAbsolute(i)){let o=ae.resolve(ae.dirname(n),i),a;try{a=q.realpathSync(o)}catch{a=o}if(!Ne(a,this.canonicalRoot))return ae.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){x(t,"realpath");let s=O(t),r=new Set,n=async a=>{let l=a==="/"?[]:a.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let y=this.toRealPath(c),p=this.resolveRealPath_(y);if(p)try{if((await q.promises.lstat(p)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let E=await q.promises.readlink(p),g=this.realTargetToVirtual(c,E);return r.add(c),c=this.resolveSymlink(c,g),n(c)}}catch(w){if(w.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(w,t,"realpath")}else if(!this.allowSymlinks){let w=this.resolveRealPathParent_(y);if(w)try{if((await q.promises.lstat(w)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(E){if(E.message?.includes("ENOENT")||E.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(E,t,"realpath")}}}}return c||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){x(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=O(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let o=this.memory.get(n);if(o){o.mtime=r;return}let a=await this.stat(n);if(a.isFile){let l=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:l,mode:a.mode,mtime:r})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:a.mode,mtime:r})}};import*as I from"node:fs";import*as U from"node:path";var Ol=["EACCES","escaping sandbox","EFBIG"],Ds=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(t){this.root=U.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,xs(this.root,"ReadWriteFs"),this.canonicalRoot=I.realpathSync(this.root)}resolveAndValidate(t,s){let r=this.allowSymlinks?at(t,this.canonicalRoot):Os(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=U.dirname(t),n=this.resolveAndValidate(r,s);return U.join(n,U.basename(t))}toRealPath(t){let s=O(t),r=U.join(this.root,s);return U.resolve(r)}async readFile(t,s){let r=await this.readFileBuffer(t),n=Ee(s);return Me(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return Me(s,"binary")}async readFileBuffer(t){x(t,"open");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{let n=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,i=await I.promises.open(r,n);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}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){x(t,"write");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t),o=Ee(r),a=Fe(s,o),l=U.dirname(i);try{await I.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(n,t);let c=this.allowSymlinks?0:I.constants.O_NOFOLLOW,u=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_TRUNC|c,f=await I.promises.open(i,u,438);try{await f.writeFile(a)}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"write")}}async appendFile(t,s,r){x(t,"append");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t),o=Ee(r),a=Fe(s,o),l=U.dirname(i);try{await I.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(n,t);let c=this.allowSymlinks?0:I.constants.O_NOFOLLOW,u=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_APPEND|c,f=await I.promises.open(i,u,438);try{await f.writeFile(a)}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,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 I.promises.access(r),!0}catch{return!1}}async stat(t){x(t,"stat");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{let n=await I.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){x(t,"lstat");let s=this.toRealPath(t),r=this.validateParent(s,t);try{let n=await I.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){x(t,"mkdir");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{await I.promises.mkdir(n,{recursive:s?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(o.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){x(t,"scandir");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{if(!this.allowSymlinks&&(await I.promises.lstat(r)).isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return(await I.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.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){x(t,"rm");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{await I.promises.rm(n,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"&&!s?.force)throw new Error(`ENOENT: no such file or directory, rm '${t}'`);if(o.code==="ENOTEMPTY")throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,s,r){x(t,"cp"),x(s,"cp");let n=this.toRealPath(t),i=this.toRealPath(s),o=this.resolveAndValidate(n,t),a=this.resolveAndValidate(i,s);try{await I.promises.cp(o,a,{recursive:r?.recursive??!1,filter:async l=>{try{if(I.lstatSync(l).isSymbolicLink()){let u=await I.promises.realpath(l).catch(()=>null);return u===null?!1:Ne(u,this.canonicalRoot)}return!0}catch(c){return c.code==="ENOENT"}}})}catch(l){let c=l;if(c.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(c.code==="EISDIR")throw new Error(`EISDIR: is a directory, cp '${t}'`);this.sanitizeError(l,t,"cp")}}async mv(t,s){x(t,"mv"),x(s,"mv");let r=this.toRealPath(t),n=this.toRealPath(s),i=this.validateParent(r,t),o=this.validateParent(n,s);try{if((await I.promises.lstat(i)).isSymbolicLink()){let c=await I.promises.readlink(i),u=U.resolve(U.dirname(o),c),f=await I.promises.realpath(u).catch(()=>u);if(!Ne(f,this.canonicalRoot))throw new Error(`EACCES: permission denied, mv '${t}' -> '${s}' would create symlink escaping sandbox`)}}catch(l){let c=l;if(c.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(c.message?.includes("EACCES")||c.message?.includes("escaping sandbox"))throw l}let a=U.dirname(o);try{await I.promises.mkdir(a,{recursive:!0})}catch(l){this.sanitizeError(l,s,"mv")}try{await I.promises.rename(i,o)}catch(l){let c=l;if(c.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(c.code==="EXDEV"){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0});return}this.sanitizeError(l,t,"mv")}try{if(I.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await I.promises.rename(o,i),new Error(`EACCES: permission denied, mv '${t}' -> '${s}' would create symlinks escaping sandbox`)}catch(l){if(l.message?.includes("EACCES")||l.message?.includes("escaping sandbox"))throw l}}resolvePath(t,s){return qe(t,s)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,s,r){Ts(t,s,r,Ol)}findEscapingSymlinks(t){let s=[];try{let r=I.readdirSync(t);for(let n of r){let i=U.join(t,n);try{let o=I.lstatSync(i);if(o.isSymbolicLink()){let a=I.readlinkSync(i),l=U.resolve(t,a),c;try{c=I.realpathSync(l)}catch{c=l}Ne(c,this.canonicalRoot)||s.push(i)}else o.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=I.readdirSync(n);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`;s.push(a);let l=U.join(n,o);I.lstatSync(l).isDirectory()&&this.scanDir(a,s)}}catch{}}async chmod(t,s){x(t,"chmod");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{let i=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,o=await I.promises.open(n,i);try{await o.chmod(s)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);if(o.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}'`);x(s,"symlink");let r=this.toRealPath(s),n=this.validateParent(r,s),i=O(s),o=O(U.dirname(i)),a=t.startsWith("/")?O(t):O(o==="/"?`/${t}`:`${o}/${t}`),l=U.join(this.canonicalRoot,a),c=U.dirname(n),u=t.startsWith("/")?l:U.relative(c,l)||".";try{await I.promises.symlink(u,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){x(t,"link"),x(s,"link");let r=this.toRealPath(t),n=this.toRealPath(s),i=this.resolveAndValidate(r,t),o=this.resolveAndValidate(n,s);try{await I.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(l.code==="EEXIST")throw new Error(`EEXIST: file already exists, link '${s}'`);if(l.code==="EPERM")throw new Error(`EPERM: operation not permitted, link '${t}'`);this.sanitizeError(a,t,"link")}}async readlink(t){x(t,"readlink");let s=this.toRealPath(t),r=this.validateParent(s,t);try{let n=await I.promises.readlink(r),i=O(t),o=U.dirname(i),a=U.isAbsolute(n)?n:U.resolve(U.dirname(r),n),l=await I.promises.realpath(a).catch(()=>a);if(Ne(l,this.canonicalRoot)){let c=l.slice(this.canonicalRoot.length)||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:U.relative(o,c)}return U.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){x(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 I.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(Ne(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){x(t,"utimes");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t);try{let o=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,a=await I.promises.open(i,o);try{await a.utimes(s,r)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);if(a.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(o,t,"utimes")}}};var St=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,s,r,n,i=!1,o,a){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=o,this.timeoutMs=a,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=Wt(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(zt(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 Rs=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 $t({root:t.overlayRoot})}let r=new Mt({env:t?.env,cwd:t?.cwd,fs:s,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network,defenseInDepth:t?.defenseInDepth});return new e(r,t?.timeoutMs)}async runCommand(t,s,r){let n,i,o,a,l=!1,c,u;if(typeof t=="object"){let p=t,w=[p.cmd,...p.args??[]];n=Ms(w),i=p.cwd,o=p.env,a=p.signal,l=p.detached??!1,c=p.stdout,u=p.stderr}else if(Array.isArray(s)){let p=r;n=Ms([t,...s]),a=p?.signal}else{n=t;let p=s;i=p?.cwd,o=p?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new St(this.bashEnv,n,f,o,d,a,this.timeoutMs);if(l)return h;let y=await h.wait();if(c){let p=await h.stdout();p&&c.write(p)}if(u){let p=await h.stderr();p&&u.write(p)}return y}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 o=this.bashEnv.fs.resolvePath(s,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,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 Is=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.length<this.options.maxViolationsPerType&&r.push(s),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(s)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[s,r]of this.violationsByType){if(r.length===0)continue;let n=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)n.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:s,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(n)})}return t.sort((s,r)=>r.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function no(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
|
|
774
|
+
`;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=Ac(t.stdout),t.stderr=Ac(t.stderr),t}async exec(t,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
775
|
+
`,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)}
|
|
776
|
+
`,exitCode:1,env:qe(this.state.env,s?.env)});if(f.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${ut(f.message)}
|
|
777
|
+
`,exitCode:2,env:qe(this.state.env,s?.env)});if(f instanceof At)return this.logResult({stdout:"",stderr:`bash: ${ut(f.message)}
|
|
778
|
+
`,exitCode:2,env:qe(this.state.env,s?.env)});if(f instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${ut(f.message)}
|
|
779
|
+
`,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;r<e.length;r++){let n=e[r];if(s==="single")n==="'"&&(s="none");else if(s==="double")n==="\\"?r++:n==='"'&&(s="none");else if(n==="'")s="single";else if(n==='"')s="double";else if(n==="\\")r++;else if(n==="#"&&(r===0||/\s/.test(e[r-1])))break}return s}function Sc(e){let t=e.split(`
|
|
780
|
+
`),s=[],r=[],n="none";for(let i=0;i<t.length;i++){let a=t[i];if(r.length>0){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(`
|
|
781
|
+
`)}var hh=new TextDecoder("utf-8",{fatal:!0});function Ac(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);try{return hh.decode(s)}catch{return e}}function ph(e,t){if(e!==void 0)return t==="bytes"?e:yt(e)}var Rn=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new ht,t?.mounts)for(let{mountPoint:s,filesystem:r}of t.mounts)this.mount(s,r)}mount(t,s){this.validateMountPath(t);let r=L(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(t){let s=L(t);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=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)=>i<a?-1:i>a?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.name<a.name?-1:i.name>a.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;){if(r.add(u),u=this.resolveSymlink(u,f.target),d++,r.has(u))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(u))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(u)}if(d>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let 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.name<a.name?-1:i.name>a.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.length<this.options.maxViolationsPerType&&r.push(s),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(s)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[s,r]of this.violationsByType){if(r.length===0)continue;let n=new Set,i=Number.POSITIVE_INFINITY,a=0;for(let l of r)n.add(l.path),i=Math.min(i,l.timestamp),a=Math.max(a,l.timestamp);t.push({type:s,count:r.length,firstSeen:i,lastSeen:a,paths:Array.from(n)})}return t.sort((s,r)=>r.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function Pc(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
|
|
708
782
|
Type: ${e.type}`,`
|
|
709
783
|
Path: ${e.path}`,`
|
|
710
784
|
Message: ${e.message}`,e.executionId?`
|
|
711
|
-
ExecutionId: ${e.executionId}`:"")}}var
|
|
785
|
+
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;a<t.pipelines.length;a++){let l=t.pipelines[a];a>0&&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;o<t.commands.length;o++){let u=t.commands[o],c=o===t.commands.length-1;if(u.type!=="SimpleCommand"||!u.name||!this.shouldTarget(u)){a.push(n.length),n.push(u),c||i.push(t.pipeStderr?.[o]??!1);continue}let f=this.getCommandName(u.name)??"unknown",d=this.counter++,h=this.generateStdoutPath(d,f,r),m=this.makeTeeCommand(h),p=this.serializeCommand(u);s.push({commandIndex:d,commandName:f,command:p,stdoutFile:h}),a.push(n.length),n.push(u),i.push(t.pipeStderr?.[o]??!1),n.push(m),c||i.push(!1),l=!0}return l?{pipeline:{...t,negated:!1,commands:n,pipeStderr:i.length>0?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<t;n++)r.push({type:"Subshell",body:[{type:"Statement",pipelines:[{type:"Pipeline",commands:[{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"exit"}]},args:[{type:"Word",parts:[{type:"ParameterExpansion",parameter:`__tps${n}`,operation:null}]}],redirections:[]}],negated:!1}],operators:[],background:!1}],redirections:[]});return{type:"Pipeline",commands:r,negated:s}}shouldTarget(t){if(!this.options.targetCommandPattern)return!0;let s=this.getCommandName(t.name);return s!==null&&this.options.targetCommandPattern.test(s)}getCommandName(t){return t&&t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}serializeCommand(t){let s=[];t.name&&s.push(be(t.name));for(let r of t.args)s.push(be(r));return s.join(" ")}makeTeeCommand(t){return{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"tee"}]},args:[{type:"Word",parts:[{type:"Literal",value:t}]}],redirections:[]}}};export{Ps as Bash,_i as BashTransformPipeline,xi as CommandCollectorPlugin,Ie as DefenseInDepthBox,Cc as EMPTY_BYTES,ht as InMemoryFs,Rn as MountableFs,Xe as NetworkAccessDeniedError,rs as OverlayFs,Ln as ReadWriteFs,ss as RedirectNotAllowedError,Mn as Sandbox,is as SandboxCommand,gt as SecurityViolationError,Wn as SecurityViolationLogger,Ci as TeePlugin,ts as TooManyRedirectsError,Ic as bytesOutput,Pc as createConsoleViolationCallback,xc as decodeBytesToUtf8,Wc as defineCommand,yt as encodeUtf8ToBytes,Oc as getCommandNames,Mc as getJavaScriptCommandNames,Tc as getNetworkCommandNames,Lc as getPythonCommandNames,_s as latin1FromBytes,Ce as parse,$s as serialize,Cs as stdoutAsBytes,Dc as stdoutKind,Rc as textOutput,os as unsafeBytesFromLatin1};
|