just-bash 3.0.3 → 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 +26 -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/{shell/chunks/yq-KU5YTNAK.js → chunks/yq-OB6PB5GY.js} +1 -1
- package/dist/bin/just-bash.js +1 -1
- 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/{chunks/yq-KU5YTNAK.js → shell/chunks/yq-OB6PB5GY.js} +1 -1
- package/dist/bin/shell/shell.js +1 -1
- package/dist/bundle/browser.js +184 -182
- 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 +274 -272
- package/dist/bundle/index.js +2 -2
- 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/shell/chunks/chunk-GXX3QUMM.js +0 -34
- package/dist/bin/shell/chunks/chunk-LMA4D2KK.js +0 -7
- package/dist/bundle/chunks/chunk-LZUPLYFM.js +0 -6
- package/dist/bundle/chunks/chunk-Z3KJQD7F.js +0 -33
package/dist/bundle/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{createRequire} from"node:module";const require=createRequire(import.meta.url);
|
|
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-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__)&&(Rt.push({name:"tar",load:async()=>(await import("./chunks/tar-WIZ3PDF4.js")).tarCommand}),Rt.push({name:"yq",load:async()=>(await import("./chunks/yq-ZBXLBSXV.js")).yqCommand}),Rt.push({name:"xan",load:async()=>(await import("./chunks/xan-U6654PZR.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-TRYUZMPS.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
|
|
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
3
|
State: R (running)
|
|
4
4
|
Pid: ${t}
|
|
5
5
|
PPid: ${s}
|
|
@@ -778,7 +778,7 @@ ${e.terminator}`}function oh(e){return`(${Ue(e.body)})${Ye(e.redirections)}`}fun
|
|
|
778
778
|
`,exitCode:2,env:qe(this.state.env,s?.env)});if(f instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${ut(f.message)}
|
|
779
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
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});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:",`
|
|
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:",`
|
|
782
782
|
Type: ${e.type}`,`
|
|
783
783
|
Path: ${e.path}`,`
|
|
784
784
|
Message: ${e.message}`,e.executionId?`
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { Writable } from "node:stream";
|
|
2
|
-
import { Bash } from "../Bash.js";
|
|
2
|
+
import { Bash, type JavaScriptConfig } from "../Bash.js";
|
|
3
|
+
import type { CommandName } from "../commands/registry.js";
|
|
4
|
+
import type { CustomCommand } from "../custom-commands.js";
|
|
3
5
|
import type { IFileSystem } from "../fs/interface.js";
|
|
4
|
-
import type { NetworkConfig } from "../network/index.js";
|
|
6
|
+
import type { NetworkConfig, SecureFetch } from "../network/index.js";
|
|
5
7
|
import type { DefenseInDepthConfig } from "../security/types.js";
|
|
6
8
|
import type { CommandFinished } from "./Command.js";
|
|
7
9
|
import { Command } from "./Command.js";
|
|
@@ -33,6 +35,35 @@ export interface SandboxOptions {
|
|
|
33
35
|
* Monkey-patches dangerous JavaScript globals during bash execution.
|
|
34
36
|
*/
|
|
35
37
|
defenseInDepth?: DefenseInDepthConfig | boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Enable the python3/python commands. Disabled by default: Python adds
|
|
40
|
+
* security surface (arbitrary code execution via CPython). Forwarded to
|
|
41
|
+
* the underlying `Bash`.
|
|
42
|
+
*/
|
|
43
|
+
python?: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Enable the js-exec command (sandboxed JavaScript via QuickJS). Accepts a
|
|
46
|
+
* boolean or a {@link JavaScriptConfig} (bootstrap code / `invokeTool`
|
|
47
|
+
* hook). Disabled by default. Forwarded to the underlying `Bash`.
|
|
48
|
+
*/
|
|
49
|
+
javascript?: boolean | JavaScriptConfig;
|
|
50
|
+
/**
|
|
51
|
+
* Restrict the registered command set. When omitted, all built-in commands
|
|
52
|
+
* are available; pass a list to allow only those. Forwarded to the
|
|
53
|
+
* underlying `Bash`.
|
|
54
|
+
*/
|
|
55
|
+
commands?: CommandName[];
|
|
56
|
+
/**
|
|
57
|
+
* Custom commands registered alongside the built-ins (these take precedence
|
|
58
|
+
* over built-ins with the same name). Forwarded to the underlying `Bash`.
|
|
59
|
+
*/
|
|
60
|
+
customCommands?: CustomCommand[];
|
|
61
|
+
/**
|
|
62
|
+
* Custom secure fetch implementation used instead of one derived from
|
|
63
|
+
* `network`. Providing either `fetch` or `network` registers the network
|
|
64
|
+
* commands (curl, wget). Forwarded to the underlying `Bash`.
|
|
65
|
+
*/
|
|
66
|
+
fetch?: SecureFetch;
|
|
36
67
|
}
|
|
37
68
|
export interface RunCommandParams {
|
|
38
69
|
cmd: string;
|
package/package.json
CHANGED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire} from"node:module";const require=createRequire(import.meta.url);
|
|
3
|
-
import{f as G}from"./chunk-MLUOPG3W.js";import{a as q}from"./chunk-3MRB66F4.js";import{a as z,b as E,c as U}from"./chunk-UI7CV277.js";import{a as $}from"./chunk-52FZYTIX.js";import{a as L}from"./chunk-DHIKZU63.js";import{a as B,b as _,c as D}from"./chunk-MUFNRCMY.js";var H=G({js:{extensions:[".js",".mjs",".cjs",".jsx"],globs:[]},ts:{extensions:[".ts",".tsx",".mts",".cts"],globs:[]},html:{extensions:[".html",".htm",".xhtml"],globs:[]},css:{extensions:[".css",".scss",".sass",".less"],globs:[]},json:{extensions:[".json",".jsonc",".json5"],globs:[]},xml:{extensions:[".xml",".xsl",".xslt"],globs:[]},c:{extensions:[".c",".h"],globs:[]},cpp:{extensions:[".cpp",".cc",".cxx",".hpp",".hh",".hxx",".h"],globs:[]},rust:{extensions:[".rs"],globs:[]},go:{extensions:[".go"],globs:[]},zig:{extensions:[".zig"],globs:[]},java:{extensions:[".java"],globs:[]},kotlin:{extensions:[".kt",".kts"],globs:[]},scala:{extensions:[".scala",".sc"],globs:[]},clojure:{extensions:[".clj",".cljc",".cljs",".edn"],globs:[]},py:{extensions:[".py",".pyi",".pyw"],globs:[]},rb:{extensions:[".rb",".rake",".gemspec"],globs:["Rakefile","Gemfile"]},php:{extensions:[".php",".phtml",".php3",".php4",".php5"],globs:[]},perl:{extensions:[".pl",".pm",".pod",".t"],globs:[]},lua:{extensions:[".lua"],globs:[]},sh:{extensions:[".sh",".bash",".zsh",".fish"],globs:[".bashrc",".zshrc",".profile"]},bat:{extensions:[".bat",".cmd"],globs:[]},ps:{extensions:[".ps1",".psm1",".psd1"],globs:[]},yaml:{extensions:[".yaml",".yml"],globs:[]},toml:{extensions:[".toml"],globs:["Cargo.toml","pyproject.toml"]},ini:{extensions:[".ini",".cfg",".conf"],globs:[]},csv:{extensions:[".csv",".tsv"],globs:[]},md:{extensions:[".md",".mdx",".markdown",".mdown",".mkd"],globs:[]},markdown:{extensions:[".md",".mdx",".markdown",".mdown",".mkd"],globs:[]},rst:{extensions:[".rst"],globs:[]},txt:{extensions:[".txt",".text"],globs:[]},tex:{extensions:[".tex",".ltx",".sty",".cls"],globs:[]},sql:{extensions:[".sql"],globs:[]},graphql:{extensions:[".graphql",".gql"],globs:[]},proto:{extensions:[".proto"],globs:[]},make:{extensions:[".mk",".mak"],globs:["Makefile","GNUmakefile","makefile"]},docker:{extensions:[],globs:["Dockerfile","Dockerfile.*","*.dockerfile"]},tf:{extensions:[".tf",".tfvars"],globs:[]}}),M=class{types;constructor(){this.types=new Map(Object.entries(H).map(([t,n])=>[t,{extensions:[...n.extensions],globs:[...n.globs]}]))}addType(t){let n=t.indexOf(":");if(n===-1)return;let s=t.slice(0,n),r=t.slice(n+1);if(r.startsWith("include:")){let l=r.slice(8),i=this.types.get(l);if(i){let a=this.types.get(s)||{extensions:[],globs:[]};a.extensions.push(...i.extensions),a.globs.push(...i.globs),this.types.set(s,a)}}else{let l=this.types.get(s)||{extensions:[],globs:[]};if(r.startsWith("*.")&&!r.slice(2).includes("*")){let i=r.slice(1);l.extensions.includes(i)||l.extensions.push(i)}else l.globs.includes(r)||l.globs.push(r);this.types.set(s,l)}}clearType(t){let n=this.types.get(t);n&&(n.extensions=[],n.globs=[])}getType(t){return this.types.get(t)}getAllTypes(){return this.types}matchesType(t,n){let s=t.toLowerCase();for(let r of n){if(r==="all"){if(this.matchesAnyType(t))return!0;continue}let l=this.types.get(r);if(l){for(let i of l.extensions)if(s.endsWith(i))return!0;for(let i of l.globs)if(i.includes("*")){let a=i.replace(/\./g,"\\.").replace(/\*/g,".*");if($(`^${a}$`,"i").test(t))return!0}else if(s===i.toLowerCase())return!0}}return!1}matchesAnyType(t){let n=t.toLowerCase();for(let s of this.types.values()){for(let r of s.extensions)if(n.endsWith(r))return!0;for(let r of s.globs)if(r.includes("*")){let l=r.replace(/\./g,"\\.").replace(/\*/g,".*");if($(`^${l}$`,"i").test(t))return!0}else if(n===r.toLowerCase())return!0}return!1}};function V(){let e=[];for(let[t,n]of Object.entries(H).sort()){let s=[];for(let r of n.extensions)s.push(`*${r}`);for(let r of n.globs)s.push(r);e.push(`${t}: ${s.join(", ")}`)}return`${e.join(`
|
|
4
|
-
`)}
|
|
5
|
-
`}function Z(){return{ignoreCase:!1,caseSensitive:!1,smartCase:!0,fixedStrings:!1,wordRegexp:!1,lineRegexp:!1,invertMatch:!1,multiline:!1,multilineDotall:!1,patterns:[],patternFiles:[],count:!1,countMatches:!1,files:!1,filesWithMatches:!1,filesWithoutMatch:!1,stats:!1,onlyMatching:!1,maxCount:0,lineNumber:!0,noFilename:!1,withFilename:!1,nullSeparator:!1,byteOffset:!1,column:!1,vimgrep:!1,replace:null,afterContext:0,beforeContext:0,contextSeparator:"--",quiet:!1,heading:!1,passthru:!1,includeZero:!1,sort:"path",json:!1,globs:[],iglobs:[],globCaseInsensitive:!1,types:[],typesNot:[],typeAdd:[],typeClear:[],hidden:!1,noIgnore:!1,noIgnoreDot:!1,noIgnoreVcs:!1,ignoreFiles:[],maxDepth:256,maxFilesize:0,followSymlinks:!1,searchZip:!1,searchBinary:!1,preprocessor:null,preprocessorGlobs:[]}}function se(e){let t=e.match(/^(\d+)([KMG])?$/i);if(!t)return 0;let n=parseInt(t[1],10);switch((t[2]||"").toUpperCase()){case"K":return n*1024;case"M":return n*1024*1024;case"G":return n*1024*1024*1024;default:return n}}function ne(e){return/^\d+[KMG]?$/i.test(e)?null:{stdout:"",stderr:`rg: invalid --max-filesize value: ${e}
|
|
6
|
-
`,exitCode:1}}function J(e){return null}var Y=[{short:"g",long:"glob",target:"globs",multi:!0},{long:"iglob",target:"iglobs",multi:!0},{short:"t",long:"type",target:"types",multi:!0,validate:J},{short:"T",long:"type-not",target:"typesNot",multi:!0,validate:J},{long:"type-add",target:"typeAdd",multi:!0},{long:"type-clear",target:"typeClear",multi:!0},{short:"m",long:"max-count",target:"maxCount",parse:parseInt},{short:"e",long:"regexp",target:"patterns",multi:!0},{short:"f",long:"file",target:"patternFiles",multi:!0},{short:"r",long:"replace",target:"replace"},{short:"d",long:"max-depth",target:"maxDepth",parse:parseInt},{long:"max-filesize",target:"maxFilesize",parse:se,validate:ne},{long:"context-separator",target:"contextSeparator"},{short:"j",long:"threads",ignored:!0},{long:"ignore-file",target:"ignoreFiles",multi:!0},{long:"pre",target:"preprocessor"},{long:"pre-glob",target:"preprocessorGlobs",multi:!0}],re=new Map([["i",e=>{e.ignoreCase=!0,e.caseSensitive=!1,e.smartCase=!1}],["--ignore-case",e=>{e.ignoreCase=!0,e.caseSensitive=!1,e.smartCase=!1}],["s",e=>{e.caseSensitive=!0,e.ignoreCase=!1,e.smartCase=!1}],["--case-sensitive",e=>{e.caseSensitive=!0,e.ignoreCase=!1,e.smartCase=!1}],["S",e=>{e.smartCase=!0,e.ignoreCase=!1,e.caseSensitive=!1}],["--smart-case",e=>{e.smartCase=!0,e.ignoreCase=!1,e.caseSensitive=!1}],["F",e=>{e.fixedStrings=!0}],["--fixed-strings",e=>{e.fixedStrings=!0}],["w",e=>{e.wordRegexp=!0}],["--word-regexp",e=>{e.wordRegexp=!0}],["x",e=>{e.lineRegexp=!0}],["--line-regexp",e=>{e.lineRegexp=!0}],["v",e=>{e.invertMatch=!0}],["--invert-match",e=>{e.invertMatch=!0}],["U",e=>{e.multiline=!0}],["--multiline",e=>{e.multiline=!0}],["--multiline-dotall",e=>{e.multilineDotall=!0,e.multiline=!0}],["c",e=>{e.count=!0}],["--count",e=>{e.count=!0}],["--count-matches",e=>{e.countMatches=!0}],["l",e=>{e.filesWithMatches=!0}],["--files",e=>{e.files=!0}],["--files-with-matches",e=>{e.filesWithMatches=!0}],["--files-without-match",e=>{e.filesWithoutMatch=!0}],["--stats",e=>{e.stats=!0}],["o",e=>{e.onlyMatching=!0}],["--only-matching",e=>{e.onlyMatching=!0}],["q",e=>{e.quiet=!0}],["--quiet",e=>{e.quiet=!0}],["N",e=>{e.lineNumber=!1}],["--no-line-number",e=>{e.lineNumber=!1}],["H",e=>{e.withFilename=!0}],["--with-filename",e=>{e.withFilename=!0}],["I",e=>{e.noFilename=!0}],["--no-filename",e=>{e.noFilename=!0}],["0",e=>{e.nullSeparator=!0}],["--null",e=>{e.nullSeparator=!0}],["b",e=>{e.byteOffset=!0}],["--byte-offset",e=>{e.byteOffset=!0}],["--column",e=>{e.column=!0,e.lineNumber=!0}],["--no-column",e=>{e.column=!1}],["--vimgrep",e=>{e.vimgrep=!0,e.column=!0,e.lineNumber=!0}],["--json",e=>{e.json=!0}],["--hidden",e=>{e.hidden=!0}],["--no-ignore",e=>{e.noIgnore=!0}],["--no-ignore-dot",e=>{e.noIgnoreDot=!0}],["--no-ignore-vcs",e=>{e.noIgnoreVcs=!0}],["L",e=>{e.followSymlinks=!0}],["--follow",e=>{e.followSymlinks=!0}],["z",e=>{e.searchZip=!0}],["--search-zip",e=>{e.searchZip=!0}],["a",e=>{e.searchBinary=!0}],["--text",e=>{e.searchBinary=!0}],["--heading",e=>{e.heading=!0}],["--passthru",e=>{e.passthru=!0}],["--include-zero",e=>{e.includeZero=!0}],["--glob-case-insensitive",e=>{e.globCaseInsensitive=!0}]]),ie=new Set(["n","--line-number"]);function le(e){e.hidden?e.searchBinary=!0:e.noIgnore?e.hidden=!0:e.noIgnore=!0}function oe(e,t,n){let s=e[t];for(let r of Y){if(s.startsWith(`--${r.long}=`)){let l=s.slice(`--${r.long}=`.length),i=P(n,r,l);return i?{newIndex:t,error:i}:{newIndex:t}}if(r.short&&s.startsWith(`-${r.short}`)&&s.length>2){let l=s.slice(2),i=P(n,r,l);return i?{newIndex:t,error:i}:{newIndex:t}}if(r.short&&s===`-${r.short}`||s===`--${r.long}`){if(t+1>=e.length)return null;let l=e[t+1],i=P(n,r,l);return i?{newIndex:t+1,error:i}:{newIndex:t+1}}}return null}function ae(e){return Y.find(t=>t.short===e)}function P(e,t,n){if(t.validate){let r=t.validate(n);if(r)return r}if(t.ignored||!t.target)return;let s=t.parse?t.parse(n):n;t.multi?e[t.target].push(s):e[t.target]=s}function ce(e,t){let n=e[t];if(n==="--sort"&&t+1<e.length){let s=e[t+1];if(s==="path"||s==="none")return{value:s,newIndex:t+1}}if(n.startsWith("--sort=")){let s=n.slice(7);if(s==="path"||s==="none")return{value:s,newIndex:t}}return null}function fe(e,t){let n=e[t],s=n.match(/^-([ABC])(\d+)$/);return s?{flag:s[1],value:parseInt(s[2],10),newIndex:t}:(n==="-A"||n==="-B"||n==="-C")&&t+1<e.length?{flag:n[1],value:parseInt(e[t+1],10),newIndex:t+1}:null}function ue(e){let t=e.match(/^-m(\d+)$/);return t?parseInt(t[1],10):null}function K(e){let t=Z(),n=null,s=[],r=-1,l=-1,i=-1,a=!1;for(let c=0;c<e.length;c++){let o=e[c];if(o.startsWith("-")&&o!=="-"){let u=fe(e,c);if(u){let{flag:f,value:x,newIndex:b}=u;f==="A"?r=Math.max(r,x):f==="B"?l=Math.max(l,x):i=x,c=b;continue}let d=ue(o);if(d!==null){t.maxCount=d;continue}let p=oe(e,c,t);if(p){if(p.error)return{success:!1,error:p.error};c=p.newIndex;continue}let g=ce(e,c);if(g){t.sort=g.value,c=g.newIndex;continue}let w=o.startsWith("--")?[o]:o.slice(1).split(""),m=!1;for(let f of w){if(ie.has(f)){t.lineNumber=!0,a=!0;continue}if(f==="u"||f==="--unrestricted"){le(t);continue}if(f==="P"||f==="--pcre2")return{success:!1,error:{stdout:"",stderr:`rg: PCRE2 is not supported. Use standard regex syntax instead.
|
|
7
|
-
`,exitCode:1}};if(f.length===1){let b=ae(f);if(b){if(c+1>=e.length)return{success:!1,error:D("rg",`-${f}`)};let h=P(t,b,e[c+1]);if(h)return{success:!1,error:h};c++,m=!0;continue}}let x=re.get(f);if(x){x(t);continue}if(f.startsWith("--"))return{success:!1,error:D("rg",f)};if(f.length===1)return{success:!1,error:D("rg",`-${f}`)}}}else n===null&&t.patterns.length===0&&t.patternFiles.length===0?n=o:s.push(o)}return(r>=0||i>=0)&&(t.afterContext=Math.max(r>=0?r:0,i>=0?i:0)),(l>=0||i>=0)&&(t.beforeContext=Math.max(l>=0?l:0,i>=0?i:0)),n!==null&&t.patterns.push(n),(t.column||t.vimgrep)&&(a=!0),{success:!0,options:t,paths:s,explicitLineNumbers:a}}import{gunzipSync as he}from"node:zlib";var T=class{patterns=[];basePath;constructor(t="/"){this.basePath=t}parse(t){let n=t.split(`
|
|
8
|
-
`);for(let s of n){let r=s.replace(/\s+$/,"");if(!r||r.startsWith("#"))continue;let l=!1;r.startsWith("!")&&(l=!0,r=r.slice(1));let i=!1;r.endsWith("/")&&(i=!0,r=r.slice(0,-1));let a=!1;r.startsWith("/")?(a=!0,r=r.slice(1)):r.includes("/")&&!r.startsWith("**/")&&(a=!0);let c=this.patternToRegex(r,a);this.patterns.push({pattern:s,regex:c,negated:l,directoryOnly:i,rooted:a})}}patternToRegex(t,n){let s="";n?s="^":s="(?:^|/)";let r=0;for(;r<t.length;){let l=t[r];if(l==="*")t[r+1]==="*"?t[r+2]==="/"?(s+="(?:.*/)?",r+=3):(r+2>=t.length,s+=".*",r+=2):(s+="[^/]*",r++);else if(l==="?")s+="[^/]",r++;else if(l==="["){let i=r+1;for(i<t.length&&t[i]==="!"&&i++,i<t.length&&t[i]==="]"&&i++;i<t.length&&t[i]!=="]";)i++;if(i<t.length){let a=t.slice(r,i+1);a.startsWith("[!")&&(a=`[^${a.slice(2)}`),s+=a,r=i+1}else s+="\\[",r++}else l==="/"?(s+="/",r++):(s+=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r++)}return s+="(?:/.*)?$",$(s)}matches(t,n){let s=t.replace(/^\.\//,"");s=s.replace(/^\//,"");let r=!1;for(let l of this.patterns)l.directoryOnly&&!n||l.regex.test(s)&&(r=!l.negated);return r}isWhitelisted(t,n){let s=t.replace(/^\.\//,"");s=s.replace(/^\//,"");for(let r of this.patterns)if(!(r.directoryOnly&&!n)&&r.negated&&r.regex.test(s))return!0;return!1}getBasePath(){return this.basePath}},k=class{parsers=[];fs;skipDotIgnore;skipVcsIgnore;loadedDirs=new Set;constructor(t,n,s=!1,r=!1){this.fs=t,this.skipDotIgnore=s,this.skipVcsIgnore=r}async load(t){let n=[],s=t;for(;;){n.unshift(s);let l=this.fs.resolvePath(s,"..");if(l===s)break;s=l}let r=[];this.skipVcsIgnore||r.push(".gitignore"),this.skipDotIgnore||r.push(".rgignore",".ignore");for(let l of n){this.loadedDirs.add(l);for(let i of r){let a=this.fs.resolvePath(l,i);try{let c=await this.fs.readFile(a),o=new T(l);o.parse(c),this.parsers.push(o)}catch{}}}}async loadForDirectory(t){if(this.loadedDirs.has(t))return;this.loadedDirs.add(t);let n=[];this.skipVcsIgnore||n.push(".gitignore"),this.skipDotIgnore||n.push(".rgignore",".ignore");for(let s of n){let r=this.fs.resolvePath(t,s);try{let l=await this.fs.readFile(r),i=new T(t);i.parse(l),this.parsers.push(i)}catch{}}}addPatternsFromContent(t,n){let s=new T(n);s.parse(t),this.parsers.push(s)}matches(t,n){for(let s of this.parsers){let r=s.getBasePath();if(!t.startsWith(r))continue;let l=t.slice(r.length).replace(/^\//,"");if(s.matches(l,n))return!0}return!1}isWhitelisted(t,n){for(let s of this.parsers){let r=s.getBasePath();if(!t.startsWith(r))continue;let l=t.slice(r.length).replace(/^\//,"");if(s.isWhitelisted(l,n))return!0}return!1}static isCommonIgnored(t){return new Set(["node_modules",".git",".svn",".hg","__pycache__",".pytest_cache",".mypy_cache","venv",".venv",".next",".nuxt",".cargo"]).has(t)}};async function A(e,t,n=!1,s=!1,r=[]){let l=new k(e,t,n,s);await l.load(t);for(let i of r)try{let a=e.resolvePath(t,i),c=await e.readFile(a);l.addPatternsFromContent(c,t)}catch{}return l}function ge(e){return e.length>=2&&e[0]===31&&e[1]===139}function pe(e){let t=!1;for(let n=0;n<e.length;n++){let s=e[n];s==="["&&!t?t=!0:s==="]"&&t&&(t=!1)}return t?`rg: glob '${e}' has an unclosed character class`:null}async function X(e){let{ctx:t,options:n,paths:s,explicitLineNumbers:r}=e;for(let f of n.globs){let x=f.startsWith("!")?f.slice(1):f,b=pe(x);if(b)return{stdout:"",stderr:`${b}
|
|
9
|
-
`,exitCode:1}}if(n.files){let f=[...n.patterns,...s];return xe(t,f,n)}let l=[...n.patterns];for(let f of n.patternFiles)try{let x;if(f==="-")x=L(t.stdin);else{let h=t.fs.resolvePath(t.cwd,f);x=await t.fs.readFile(h)}let b=x.split(`
|
|
10
|
-
`).filter(h=>h.length>0);l.push(...b)}catch{return{stdout:"",stderr:`rg: ${f}: No such file or directory
|
|
11
|
-
`,exitCode:2}}if(l.length===0)return n.patternFiles.length>0?{stdout:"",stderr:"",exitCode:1}:{stdout:"",stderr:`rg: no pattern given
|
|
12
|
-
`,exitCode:2};let i=s.length===0?["."]:s,a=me(n,l),c,o;try{let f=de(l,n,a);c=f.regex,o=f.kResetGroup}catch{return{stdout:"",stderr:`rg: invalid regex: ${l.join(", ")}
|
|
13
|
-
`,exitCode:2}}let u=null;n.noIgnore||(u=await A(t.fs,t.cwd,n.noIgnoreDot,n.noIgnoreVcs,n.ignoreFiles));let d=new M;for(let f of n.typeClear)d.clearType(f);for(let f of n.typeAdd)d.addType(f);let{files:p,singleExplicitFile:g}=await Q(t,i,n,u,d);if(p.length===0)return{stdout:"",stderr:"",exitCode:1};let w=!n.noFilename&&(n.withFilename||!g||p.length>1),m=n.lineNumber;return r||(g&&p.length===1&&(m=!1),n.onlyMatching&&(m=!1)),we(t,p,c,n,w,m,o)}function me(e,t){return e.caseSensitive?!1:e.ignoreCase?!0:e.smartCase?!t.some(n=>/[A-Z]/.test(n)):!1}function de(e,t,n){let s;return e.length===1?s=e[0]:s=e.map(r=>t.fixedStrings?r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):`(?:${r})`).join("|"),E(s,{mode:t.fixedStrings&&e.length===1?"fixed":"perl",ignoreCase:n,wholeWord:t.wordRegexp,lineRegexp:t.lineRegexp,multiline:t.multiline,multilineDotall:t.multilineDotall})}async function Q(e,t,n,s,r){let l=[],i=0,a=0;for(let o of t){let u=e.fs.resolvePath(e.cwd,o);try{let d=await e.fs.stat(u);if(d.isFile){if(i++,n.maxFilesize>0&&d.size>n.maxFilesize)continue;te(o,n,s,u,r)&&l.push(o)}else d.isDirectory&&(a++,await ee(e,o,u,0,n,s,r,l))}catch{}}return{files:n.sort==="path"?l.sort():l,singleExplicitFile:i===1&&a===0}}async function ee(e,t,n,s,r,l,i,a){if(!(s>=r.maxDepth)){l&&await l.loadForDirectory(n);try{let c=e.fs.readdirWithFileTypes?await e.fs.readdirWithFileTypes(n):(await e.fs.readdir(n)).map(o=>({name:o,isFile:void 0}));for(let o of c){let u=o.name;if(!r.noIgnore&&k.isCommonIgnored(u))continue;let d=u.startsWith("."),p=t==="."?u:t==="./"?`./${u}`:t.endsWith("/")?`${t}${u}`:`${t}/${u}`,g=e.fs.resolvePath(n,u),w,m,f=!1;if(o.isFile!==void 0&&"isDirectory"in o){let h=o;if(f=h.isSymbolicLink===!0,f&&!r.followSymlinks)continue;if(f&&r.followSymlinks)try{let y=await e.fs.stat(g);w=y.isFile,m=y.isDirectory}catch{continue}else w=h.isFile,m=h.isDirectory}else try{let h=e.fs.lstat?await e.fs.lstat(g):await e.fs.stat(g);if(f=h.isSymbolicLink===!0,f&&!r.followSymlinks)continue;let y=f&&r.followSymlinks?await e.fs.stat(g):h;w=y.isFile,m=y.isDirectory}catch{continue}if(!l?.matches(g,m)&&!(d&&!r.hidden&&!l?.isWhitelisted(g,m))){if(m)await ee(e,p,g,s+1,r,l,i,a);else if(w){if(r.maxFilesize>0)try{if((await e.fs.stat(g)).size>r.maxFilesize)continue}catch{continue}te(p,r,l,g,i)&&a.push(p)}}}}catch{}}}function te(e,t,n,s,r){let l=e.split("/").pop()||e;if(n?.matches(s,!1)||t.types.length>0&&!r.matchesType(l,t.types)||t.typesNot.length>0&&r.matchesType(l,t.typesNot))return!1;if(t.globs.length>0){let i=t.globCaseInsensitive,a=t.globs.filter(o=>!o.startsWith("!")),c=t.globs.filter(o=>o.startsWith("!")).map(o=>o.slice(1));if(a.length>0){let o=!1;for(let u of a)if(v(l,u,i)||v(e,u,i)){o=!0;break}if(!o)return!1}for(let o of c)if(o.startsWith("/")){let u=o.slice(1);if(v(e,u,i))return!1}else if(v(l,o,i)||v(e,o,i))return!1}if(t.iglobs.length>0){let i=t.iglobs.filter(c=>!c.startsWith("!")),a=t.iglobs.filter(c=>c.startsWith("!")).map(c=>c.slice(1));if(i.length>0){let c=!1;for(let o of i)if(v(l,o,!0)||v(e,o,!0)){c=!0;break}if(!c)return!1}for(let c of a)if(c.startsWith("/")){let o=c.slice(1);if(v(e,o,!0))return!1}else if(v(l,c,!0)||v(e,c,!0))return!1}return!0}function v(e,t,n=!1){let s="^";for(let r=0;r<t.length;r++){let l=t[r];if(l==="*")t[r+1]==="*"?(s+=".*",r++):s+="[^/]*";else if(l==="?")s+="[^/]";else if(l==="["){let i=r+1;for(i<t.length&&t[i]==="!"&&i++,i<t.length&&t[i]==="]"&&i++;i<t.length&&t[i]!=="]";)i++;if(i<t.length){let a=t.slice(r,i+1);a.startsWith("[!")&&(a=`[^${a.slice(2)}`),s+=a,r=i}else s+="\\["}else s+=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}return s+="$",$(s,n?"i":"").test(e)}async function xe(e,t,n){let s=null;n.noIgnore||(s=await A(e.fs,e.cwd,n.noIgnoreDot,n.noIgnoreVcs,n.ignoreFiles));let r=new M;for(let o of n.typeClear)r.clearType(o);for(let o of n.typeAdd)r.addType(o);let l=t.length===0?["."]:t,{files:i}=await Q(e,l,n,s,r);if(i.length===0)return{stdout:"",stderr:"",exitCode:1};if(n.quiet)return{stdout:"",stderr:"",exitCode:0};let a=n.nullSeparator?"\0":`
|
|
14
|
-
`;return{stdout:i.map(o=>o+a).join(""),stderr:"",exitCode:0}}function ye(e,t){if(t.length===0)return!0;for(let n of t)if(v(e,n,!1))return!0;return!1}async function be(e,t,n,s){try{if(s.preprocessor&&e.exec){let i=n.split("/").pop()||n;if(ye(i,s.preprocessorGlobs)){let a=await e.exec(q([s.preprocessor]),{cwd:e.cwd,signal:e.signal,args:[t]});if(a.exitCode===0&&a.stdout){let c=L(a.stdout),o=c.slice(0,8192);return{content:c,isBinary:o.includes("\0")}}}}if(s.searchZip&&n.endsWith(".gz")){let i=await e.fs.readFileBuffer(t);if(ge(i))try{let a=he(i),c=new TextDecoder().decode(a),o=c.slice(0,8192);return{content:c,isBinary:o.includes("\0")}}catch{return null}}let r=await e.fs.readFile(t),l=r.slice(0,8192);return{content:r,isBinary:l.includes("\0")}}catch{return null}}async function we(e,t,n,s,r,l,i){let a="",c=!1,o=[],u=0,d=0,p=0,g=50;e:for(let f=0;f<t.length;f+=g){let x=t.slice(f,f+g),b=await Promise.all(x.map(async h=>{let y=e.fs.resolvePath(e.cwd,h),F=await be(e,y,h,s);if(!F)return null;let{content:C,isBinary:N}=F;if(p+=C.length,N&&!s.searchBinary)return null;let W=r&&!s.heading?h:"",S=z(C,n,{invertMatch:s.invertMatch,showLineNumbers:l,countOnly:s.count,countMatches:s.countMatches,filename:W,onlyMatching:s.onlyMatching,beforeContext:s.beforeContext,afterContext:s.afterContext,maxCount:s.maxCount,contextSeparator:s.contextSeparator,showColumn:s.column,vimgrep:s.vimgrep,showByteOffset:s.byteOffset,replace:s.replace!==null?U(s.replace):null,passthru:s.passthru,multiline:s.multiline,kResetGroup:i});return s.json&&S.matched?{file:h,result:S,content:C,isBinary:!1}:{file:h,result:S}}));for(let h of b){if(!h)continue;let{file:y,result:F}=h;if(F.matched){if(c=!0,d++,u+=F.matchCount,s.quiet&&!s.json)break e;if(s.json&&!s.quiet){let C=h.content||"";o.push(JSON.stringify({type:"begin",data:{path:{text:y}}}));let N=C.split(`
|
|
15
|
-
`);n.lastIndex=0;let W=0;for(let S=0;S<N.length;S++){let j=N[S];n.lastIndex=0;let O=[];for(let I=n.exec(j);I!==null;I=n.exec(j)){let R={match:{text:I[0]},start:I.index,end:I.index+I[0].length};s.replace!==null&&(R.replacement={text:s.replace}),O.push(R),I[0].length===0&&n.lastIndex++}if(O.length>0){let I={type:"match",data:{path:{text:y},lines:{text:`${j}
|
|
16
|
-
`},line_number:S+1,absolute_offset:W,submatches:O}};o.push(JSON.stringify(I))}W+=j.length+1}o.push(JSON.stringify({type:"end",data:{path:{text:y},binary_offset:null,stats:{elapsed:{secs:0,nanos:0,human:"0s"},searches:1,searches_with_match:1,bytes_searched:C.length,bytes_printed:0,matched_lines:F.matchCount,matches:F.matchCount}}}))}else if(s.filesWithMatches){let C=s.nullSeparator?"\0":`
|
|
17
|
-
`;a+=`${y}${C}`}else s.filesWithoutMatch||(s.heading&&!s.noFilename&&(a+=`${y}
|
|
18
|
-
`),a+=F.output)}else if(s.filesWithoutMatch){let C=s.nullSeparator?"\0":`
|
|
19
|
-
`;a+=`${y}${C}`}else s.includeZero&&(s.count||s.countMatches)&&(a+=F.output)}}s.json&&(o.push(JSON.stringify({type:"summary",data:{elapsed_total:{secs:0,nanos:0,human:"0s"},stats:{elapsed:{secs:0,nanos:0,human:"0s"},searches:t.length,searches_with_match:d,bytes_searched:p,bytes_printed:0,matched_lines:u,matches:u}}})),a=`${o.join(`
|
|
20
|
-
`)}
|
|
21
|
-
`);let w=s.quiet&&!s.json?"":a;if(s.stats&&!s.json){let f=["",`${u} matches`,`${u} matched lines`,`${d} files contained matches`,`${t.length} files searched`,`${p} bytes searched`].join(`
|
|
22
|
-
`);w+=`${f}
|
|
23
|
-
`}let m;return s.filesWithoutMatch?m=a.length>0?0:1:m=c?0:1,{stdout:w,stderr:"",exitCode:m}}var ve={name:"rg",summary:"recursively search for a pattern",usage:"rg [OPTIONS] PATTERN [PATH ...]",description:`rg (ripgrep) recursively searches directories for a regex pattern.
|
|
24
|
-
Unlike grep, rg is recursive by default and respects .gitignore files.
|
|
25
|
-
|
|
26
|
-
EXAMPLES:
|
|
27
|
-
rg foo Search for 'foo' in current directory
|
|
28
|
-
rg foo src/ Search in src/ directory
|
|
29
|
-
rg -i foo Case-insensitive search
|
|
30
|
-
rg -w foo Match whole words only
|
|
31
|
-
rg -t js foo Search only JavaScript files
|
|
32
|
-
rg -g '*.ts' foo Search files matching glob
|
|
33
|
-
rg --hidden foo Include hidden files
|
|
34
|
-
rg -l foo List files with matches only`,options:["-e, --regexp PATTERN search for PATTERN (can be used multiple times)","-f, --file FILE read patterns from FILE, one per line","-i, --ignore-case case-insensitive search","-s, --case-sensitive case-sensitive search (overrides smart-case)","-S, --smart-case smart case (default: case-insensitive unless pattern has uppercase)","-F, --fixed-strings treat pattern as literal string","-w, --word-regexp match whole words only","-x, --line-regexp match whole lines only","-v, --invert-match select non-matching lines","-r, --replace TEXT replace matches with TEXT","-c, --count print count of matching lines per file"," --count-matches print count of individual matches per file","-l, --files-with-matches print only file names with matches"," --files-without-match print file names without matches"," --files list files that would be searched","-o, --only-matching print only matching parts","-m, --max-count NUM stop after NUM matches per file","-q, --quiet suppress output, exit 0 on match"," --stats print search statistics","-n, --line-number print line numbers (default: on)","-N, --no-line-number do not print line numbers","-I, --no-filename suppress the prefixing of file names","-0, --null use NUL as filename separator","-b, --byte-offset show byte offset of each match"," --column show column number of first match"," --vimgrep show results in vimgrep format"," --json show results in JSON Lines format","-A NUM print NUM lines after each match","-B NUM print NUM lines before each match","-C NUM print NUM lines before and after each match"," --context-separator SEP separator for context groups (default: --)","-U, --multiline match patterns across lines","-z, --search-zip search in compressed files (gzip only)","-g, --glob GLOB include files matching GLOB","-t, --type TYPE only search files of TYPE (e.g., js, py, ts)","-T, --type-not TYPE exclude files of TYPE","-L, --follow follow symbolic links","-u, --unrestricted reduce filtering (-u: no ignore, -uu: +hidden, -uuu: +binary)","-a, --text search binary files as text"," --hidden search hidden files and directories"," --no-ignore don't respect .gitignore/.ignore files","-d, --max-depth NUM maximum search depth"," --sort TYPE sort files (path, none)"," --heading show file path above matches"," --passthru print all lines (non-matches use - separator)"," --include-zero include files with 0 matches in count output"," --type-list list all available file types"," --help display this help and exit"]},Ge={name:"rg",async execute(e,t){if(_(e))return B(ve);if(e.includes("--type-list"))return{stdout:V(),stderr:"",exitCode:0};let n=K(e);return n.success?X({ctx:t,options:n.options,paths:n.paths,explicitLineNumbers:n.explicitLineNumbers}):n.error}},qe={name:"rg",flags:[{flag:"-i",type:"boolean"},{flag:"-s",type:"boolean"},{flag:"-S",type:"boolean"},{flag:"-F",type:"boolean"},{flag:"-w",type:"boolean"},{flag:"-x",type:"boolean"},{flag:"-v",type:"boolean"},{flag:"-c",type:"boolean"},{flag:"-l",type:"boolean"},{flag:"-o",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-N",type:"boolean"},{flag:"--hidden",type:"boolean"},{flag:"--no-ignore",type:"boolean"},{flag:"-m",type:"value",valueHint:"number"},{flag:"-A",type:"value",valueHint:"number"},{flag:"-B",type:"value",valueHint:"number"},{flag:"-C",type:"value",valueHint:"number"},{flag:"-g",type:"value",valueHint:"pattern"},{flag:"-t",type:"value",valueHint:"string"},{flag:"-T",type:"value",valueHint:"string"}],needsArgs:!0};export{Ge as a,qe as b};
|