@jerryan/just-bash 3.8.0 → 3.9.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +5 -15
  3. package/dist/AGENTS.md +2 -2
  4. package/dist/Bash.d.ts +2 -4
  5. package/dist/bin/chunks/{chunk-7WBCA2BB.js → chunk-3DWQCLNP.js} +1 -1
  6. package/dist/bin/{shell/chunks/chunk-MPFNZYEA.js → chunks/chunk-6JEDM6CZ.js} +1 -1
  7. package/dist/bin/chunks/{chunk-QFTZKD5O.js → chunk-6TUILMPB.js} +1 -1
  8. package/dist/bin/chunks/chunk-E54Z6VIE.js +12 -0
  9. package/dist/bin/chunks/chunk-GBKR5KTT.js +44 -0
  10. package/dist/bin/{shell/chunks/chunk-MF3GVFLC.js → chunks/chunk-L345YZ6R.js} +1 -1
  11. package/dist/bin/chunks/chunk-QKJAAJ7J.js +3 -0
  12. package/dist/bin/chunks/{diff-JSJ56EOK.js → diff-DM47S5PT.js} +1 -1
  13. package/dist/bin/{shell/chunks/flag-coverage-2H5CPEM6.js → chunks/flag-coverage-LLAQBVIG.js} +1 -1
  14. package/dist/bin/chunks/js-exec-ZAAIZQWI.js +99 -0
  15. package/dist/bin/chunks/js-exec-worker.js +4995 -0
  16. package/dist/bin/chunks/python3-TJ6DCPIA.js +14 -0
  17. package/dist/bin/chunks/{sleep-DVFE2GSF.js → sleep-MOJQBZMY.js} +1 -1
  18. package/dist/bin/{shell/chunks/sqlite3-KNN6V2W6.js → chunks/sqlite3-CXQTZRPZ.js} +1 -1
  19. package/dist/bin/chunks/{timeout-YGFHQJKX.js → timeout-RQOWSWYG.js} +1 -1
  20. package/dist/bin/just-bash.js +1 -1
  21. package/dist/bin/shell/chunks/{chunk-7WBCA2BB.js → chunk-3DWQCLNP.js} +1 -1
  22. package/dist/bin/{chunks/chunk-MPFNZYEA.js → shell/chunks/chunk-6JEDM6CZ.js} +1 -1
  23. package/dist/bin/shell/chunks/{chunk-QFTZKD5O.js → chunk-6TUILMPB.js} +1 -1
  24. package/dist/bin/shell/chunks/chunk-E54Z6VIE.js +12 -0
  25. package/dist/bin/shell/chunks/chunk-GBKR5KTT.js +44 -0
  26. package/dist/bin/{chunks/chunk-MF3GVFLC.js → shell/chunks/chunk-L345YZ6R.js} +1 -1
  27. package/dist/bin/shell/chunks/chunk-QKJAAJ7J.js +3 -0
  28. package/dist/bin/shell/chunks/{diff-JSJ56EOK.js → diff-DM47S5PT.js} +1 -1
  29. package/dist/bin/{chunks/flag-coverage-2H5CPEM6.js → shell/chunks/flag-coverage-LLAQBVIG.js} +1 -1
  30. package/dist/bin/shell/chunks/js-exec-ZAAIZQWI.js +99 -0
  31. package/dist/bin/shell/chunks/python3-TJ6DCPIA.js +14 -0
  32. package/dist/bin/shell/chunks/{sleep-DVFE2GSF.js → sleep-MOJQBZMY.js} +1 -1
  33. package/dist/bin/{chunks/sqlite3-KNN6V2W6.js → shell/chunks/sqlite3-CXQTZRPZ.js} +1 -1
  34. package/dist/bin/shell/chunks/{timeout-YGFHQJKX.js → timeout-RQOWSWYG.js} +1 -1
  35. package/dist/bin/shell/shell.js +1 -1
  36. package/dist/bundle/browser.js +596 -579
  37. package/dist/bundle/chunks/{chunk-N3A4JVFJ.js → chunk-6IA4DXG2.js} +1 -1
  38. package/dist/bundle/chunks/chunk-BS6EJR2R.js +11 -0
  39. package/dist/bundle/chunks/chunk-E2F4A3CM.js +43 -0
  40. package/dist/bundle/chunks/{chunk-GNPLDVBD.js → chunk-H3A45X3W.js} +1 -1
  41. package/dist/bundle/chunks/chunk-PS2RJNZZ.js +2 -0
  42. package/dist/bundle/chunks/{chunk-DMWNBCXJ.js → chunk-TLPMB3FO.js} +1 -1
  43. package/dist/bundle/chunks/{chunk-XV2V56NQ.js → chunk-YFFU74KY.js} +1 -1
  44. package/dist/bundle/chunks/{diff-VDB6RXHO.js → diff-R7TXVVLN.js} +1 -1
  45. package/dist/bundle/chunks/{flag-coverage-UMQ3BWDP.js → flag-coverage-YQGACUSN.js} +1 -1
  46. package/dist/bundle/chunks/js-exec-MUZRDUJ3.js +98 -0
  47. package/dist/bundle/chunks/js-exec-worker.js +4995 -0
  48. package/dist/bundle/chunks/python3-W4UMQJAQ.js +13 -0
  49. package/dist/bundle/chunks/{sleep-PPRBTSVR.js → sleep-25QUPVDK.js} +1 -1
  50. package/dist/bundle/chunks/{sqlite3-KB3MXTTM.js → sqlite3-DQNCWDG5.js} +1 -1
  51. package/dist/bundle/chunks/{timeout-C6WDYPLV.js → timeout-37GM7IIL.js} +1 -1
  52. package/dist/bundle/index.cjs +1128 -2663
  53. package/dist/bundle/index.js +2 -2
  54. package/dist/commands/js-exec/js-exec-worker.d.ts +35 -0
  55. package/dist/commands/js-exec/js-exec.d.ts +14 -1
  56. package/dist/fs/vfs-template.d.ts +6 -0
  57. package/dist/interpreter/interpreter.d.ts +1 -1
  58. package/dist/interpreter/types.d.ts +1 -1
  59. package/dist/limits.d.ts +2 -2
  60. package/dist/timers.d.ts +9 -0
  61. package/dist/types.d.ts +3 -4
  62. package/package.json +8 -8
  63. package/dist/bin/chunks/chunk-2NJJXU4K.js +0 -27
  64. package/dist/bin/chunks/chunk-PPVF2N6C.js +0 -3
  65. package/dist/bin/chunks/js-exec-T3SAB2B6.js +0 -1651
  66. package/dist/bin/chunks/python3-3ERN3L6S.js +0 -23
  67. package/dist/bin/shell/chunks/chunk-2NJJXU4K.js +0 -27
  68. package/dist/bin/shell/chunks/chunk-PPVF2N6C.js +0 -3
  69. package/dist/bin/shell/chunks/js-exec-T3SAB2B6.js +0 -1651
  70. package/dist/bin/shell/chunks/python3-3ERN3L6S.js +0 -23
  71. package/dist/bundle/chunks/chunk-B6OSJB22.js +0 -26
  72. package/dist/bundle/chunks/chunk-WXPNKIIH.js +0 -2
  73. package/dist/bundle/chunks/js-exec-ZQMIYQTH.js +0 -1650
  74. package/dist/bundle/chunks/python3-QB7OE256.js +0 -22
  75. package/dist/commands/js-exec/run-runtime.d.ts +0 -10
@@ -1,5 +1,5 @@
1
1
  import{createRequire} from"node:module";const require=createRequire(import.meta.url);
2
- import{a as Ht,b as Zt,c as dt}from"./chunks/chunk-WNH3HOQA.js";import{a as Qr}from"./chunks/chunk-BRJERIF4.js";import{c as Ii,e as Xa}from"./chunks/chunk-KIGPB52X.js";import{a as Hr,b as Zr,c as pr,d as mr}from"./chunks/chunk-WXPNKIIH.js";import{a as an}from"./chunks/chunk-SGX4WOAM.js";import{a as Di}from"./chunks/chunk-L2UW7DWF.js";import{a as on,b as Xe,c as Er}from"./chunks/chunk-DLL7UR66.js";import{a as wr,b as Ka}from"./chunks/chunk-BKUWXPEM.js";import{a as ge}from"./chunks/chunk-4KZT23KR.js";import{a as Yr,b as Jr}from"./chunks/chunk-AYSZ5MAE.js";import{a as qn,b as Re}from"./chunks/chunk-ZBUZKIPX.js";import"./chunks/chunk-57LGFT4S.js";import{c as nn,d as Hn}from"./chunks/chunk-FTET43KM.js";import"./chunks/chunk-STHBFACM.js";import{a as gr,b as St,c as rn,d as es,e as z,f as qt,g as U,h as Zn,i as sn,j as Nn,k as Gt,l as Qn}from"./chunks/chunk-4CC3OZPU.js";import{a as Jt,b as tt,c as nt,d as We,e as Qe,f as Ke,g as G,h as ue,i as rt,j as en,k as Kr,l as C,m as st,n as Oe,o as tn,p as Xr,q as ut}from"./chunks/chunk-TVCZIH6M.js";import{a as W,b as yr,c as Cn,d as Od,e as Yt,f as Ri,g as Gn,h as Dd,i as Ut,j as Oi,k as Id,l as Td}from"./chunks/chunk-GN6CQ3J4.js";import{a as x,b as _d,c as ft,d as Ld}from"./chunks/chunk-T5ZEIOJ3.js";import{a as Ot}from"./chunks/chunk-FOCWZZDE.js";import{a as jt}from"./chunks/chunk-W5DWRFSU.js";import{a as Ni}from"./chunks/chunk-NCUTH6QL.js";import*as Me from"node:path";var Rn=[{name:"echo",load:async()=>(await import("./chunks/echo-PLLZYM2L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-VZBWBIJB.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-B2NSYQ3N.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-WH5S4PPL.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-Z6MMWH3D.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-3WTXMVKI.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-W4DF6Z4T.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-IGPLE632.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-UR762VVT.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-WE7DBLEK.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-CEM7GDB5.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-TEY5MD2W.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-76BPYV5F.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-JSRKXLLQ.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-6UIPFWVJ.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-UBGSN4JF.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-7WVM7GV4.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-LXFZND2P.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-JKB7DR66.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-6G32B25J.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-VS5QVYHU.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-CB5GO7XH.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-PAEPA27E.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-DTWKU2MC.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-FMDNVWQN.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-ZNHNSRBW.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-UI2LA3GA.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-EPOS3MFH.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-IELOWYJG.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-QJBPHRFJ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-J3VOSOMK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-YD5BWFH4.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-VLFTYX2Z.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-HUKVGJTW.js")).split},{name:"column",load:async()=>(await import("./chunks/column-QJI65SH2.js")).column},{name:"join",load:async()=>(await import("./chunks/join-C2B6NGXH.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-OOWSWHRQ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-RLKBCGJR.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SJZQ5W65.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-Z2ZMOOW2.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7OOL2MH6.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-EQKH3UNA.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-VUUMB47B.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-VUUMB47B.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3N762S3K.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-VQEXRD3C.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KPIUNI6K.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-UKAA3QWU.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-MHVQ5XHI.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-VDB6RXHO.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-7OEDRA27.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-PPRBTSVR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-C6WDYPLV.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-NERE2JJ2.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-B6KDLMYQ.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-A5XITHQD.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-JEDX55KS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BLPZJ6MP.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-VJZ4PHQ4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-6AYYTULJ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-PE6BPRPA.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-QDDMBDU7.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-UWVKETYW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-YXC4HBTR.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-CESD3CQR.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KR6E7UIR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-Z4AIL3P4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Rn.push({name:"tar",load:async()=>(await import("./chunks/tar-LE7LAAIX.js")).tarCommand}),Rn.push({name:"yq",load:async()=>(await import("./chunks/yq-ZRNZKDLE.js")).yqCommand}),Rn.push({name:"xan",load:async()=>(await import("./chunks/xan-UIL24CGT.js")).xanCommand}),Rn.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-KB3MXTTM.js")).sqlite3Command}));var ts=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ts.push({name:"python3",load:async()=>(await import("./chunks/python3-QB7OE256.js")).python3Command}),ts.push({name:"python",load:async()=>(await import("./chunks/python3-QB7OE256.js")).pythonCommand}));var ns=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ns.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-ZQMIYQTH.js")).jsExecCommand}),ns.push({name:"node",load:async()=>(await import("./chunks/js-exec-ZQMIYQTH.js")).nodeStubCommand}));var Ja=[{name:"curl",load:async()=>(await import("./chunks/curl-K4WT7UPN.js")).curlCommand}],Ya=new Map;function rs(e){return{name:e.name,async execute(t,n){let r=Ya.get(e.name);if(r||(r=await Re.runTrustedAsync(()=>e.load()),Ya.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await import("./chunks/flag-coverage-UMQ3BWDP.js");s(n.coverage,e.name,t)}return r.execute(t,n)}}}function Fd(){return Rn.map(e=>e.name)}function Md(){return Ja.map(e=>e.name)}function el(e){return(e?Rn.filter(n=>e.includes(n.name)):Rn).map(rs)}function tl(){return Ja.map(rs)}function Bd(){return ts.map(e=>e.name)}function nl(){return ts.map(rs)}function Wd(){return ns.map(e=>e.name)}function rl(){return ns.map(rs)}var sl=new WeakMap,il=new WeakSet;function ss(e){let t=sl.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),sl.set(e,t),il.add(t)),t}function ol(e){return il.has(e)}var al={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxJsBridgeRequests:1e6,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},Vd={...al,maxSourceBytes:8*1024*1024,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxJsBridgeRequests:1e5,maxExtensionCleanupTimeMs:25,maxGlobOperations:1e5,maxStringLength:10*1024*1024,maxArrayElements:1e5,maxHeredocSize:10*1024*1024,maxBraceExpansionResults:1e4,maxOutputSize:10*1024*1024,maxFileDescriptors:1024,maxQueryTokens:25e3,maxQueryDepth:256,maxQueryElements:1e5,maxAwkParserTokens:25e3,maxAwkParserDepth:128,maxAwkParserOperations:1e5,maxCsvRows:1e5,maxCsvCells:1e6,maxWorkUnits:1e5,maxTraversalEntries:1e5,maxTraversalDepth:256,maxTraversalWork:1e5,maxLiveBytes:64*1024*1024,maxInputBytes:32*1024*1024,maxFileSystemBytes:128*1024*1024,maxDatabaseBytes:64*1024*1024,maxDatabaseResultBytes:16*1024*1024,maxArchiveBytes:128*1024*1024,maxArchiveCompressedBytes:64*1024*1024,maxArchiveEntryBytes:64*1024*1024,maxArchiveEntries:1e5,maxWorkerMessageBytes:16*1024*1024,maxExecutionTimeMs:3e4};function is(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?Vd:al;if(!e)return{...n};let r={maxSourceBytes:e.maxSourceBytes??n.maxSourceBytes,maxExecDepth:e.maxExecDepth??n.maxExecDepth,maxCallDepth:e.maxCallDepth??n.maxCallDepth,maxCommandCount:e.maxCommandCount??n.maxCommandCount,maxLoopIterations:e.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??n.maxAwkIterations,maxSedIterations:e.maxSedIterations??n.maxSedIterations,maxJqIterations:e.maxJqIterations??n.maxJqIterations,maxQueryTokens:e.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:e.maxQueryDepth??n.maxQueryDepth,maxQueryElements:e.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:e.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:e.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:e.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:e.maxCsvRows??n.maxCsvRows,maxCsvCells:e.maxCsvCells??n.maxCsvCells,maxWorkUnits:e.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:e.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:e.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:e.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:e.maxLiveBytes??n.maxLiveBytes,maxInputBytes:e.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:e.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:e.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:e.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:e.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:e.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:e.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:e.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:e.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:e.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:e.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??n.maxJsTimeoutMs,maxJsBridgeRequests:e.maxJsBridgeRequests??n.maxJsBridgeRequests,maxGlobOperations:e.maxGlobOperations??n.maxGlobOperations,maxStringLength:e.maxStringLength??n.maxStringLength,maxArrayElements:e.maxArrayElements??n.maxArrayElements,maxHeredocSize:e.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??n.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??n.maxSourceDepth};for(let s of Object.keys(r)){let i=r[s];if(i!==Number.POSITIVE_INFINITY&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`${s} must be a non-negative safe integer or positive Infinity`)}return r}function zd(e){let{executionLimits:t,executionLimitProfile:n,fs:r,stdin:s=Ri,...i}=e;return{fs:r,fsIdentity:i.fsIdentity??ss(r),cwd:"/",env:new Map,stdin:s,limits:is(t,n),...i}}function ll(e){return"load"in e&&typeof e.load=="function"}function Ud(e,t,n={}){return{name:e,trusted:n.trusted!==!1,execute:t}}function cl(e){let t=null,n=null;return{name:e.name,trusted:e.trusted!==!1,async execute(r,s){if(!t){let o=n;o||(o=e.load().then(a=>(t=a,a)),n=o);try{t=await o}catch(a){throw n===o&&(n=null),a}}let i=t;if(!i)throw new Error(`Failed to load command: ${e.name}`);return i.execute(r,s)}}}var ul=Object.freeze(Object.create(null)),os=class{limits;signal;abortOnUnresolvedCommands;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();unresolvedCommands=new Set;get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(t,n=void 0,r=!1){this.limits=t,this.signal=n,this.abortOnUnresolvedCommands=r}recordUnresolvedCommand(t){this.unresolvedCommands.add(t)}get unresolvedCommandNames(){return[...this.unresolvedCommands]}fail(t){throw this.poisoned??=t,this.poisoned}poisonAfterAbort(t){this.poisoned??=t}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(t=1,n="execution"){return this.consume("work",t,n)}consumeLimited(t,n,r,s=t){this.assertUsable();let i=this.countersByKind.get(t)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new C(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new C(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(t,i+n),this.workUnits+=n,i+n}consumeInput(t,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(t)||t<0||t>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new C(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=t,this.inputBytes}consume(t,n=1,r=t){this.assertUsable();let s=this.countersByKind.get(t)??0,i=t==="commands"?this.commandCount:this.workUnits,o=t==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>o-i)&&this.fail(new C(t==="commands"?`too many commands executed (>${o}), increase executionLimits.maxCommandCount`:`${r}: ${t} work limit exceeded (${o})`,t==="commands"?"commands":"iterations"));let a=i+n;return t==="commands"?this.commandCount=a:this.workUnits=a,this.countersByKind.set(t,s+n),a}reserveBytes(t,n,r){this.assertUsable();let s=typeof t=="string"?t:"live",i=typeof t=="string"?n:t,o=typeof t=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new C(`${o}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let a=!1;return{release:()=>{if(a)return;a=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(t,n,r="execution",s=0,i="text"){this.assertUsable();let o=i==="bytes"?n.length:W(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new C(`${r}: invalid ${t} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new C(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=a,o}accountResult(t,n="execution",r=Number.POSITIVE_INFINITY){let s=t.internalOutputAccounting,i=Math.min(s?.stdout??0,r),o=Math.min(s?.stderr??0,Math.max(0,r-i)),a=this.appendOutput("stdout",t.stdout,n,i,t.stdoutKind==="bytes"||t.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",t.stderr,n,o);return Object.isExtensible(t)?(t.internalOutputAccounting={stdout:a,stderr:l},t):a===0&&l===0?t:{...t,internalOutputAccounting:{stdout:a,stderr:l}}}relinquishOutput(t,n,r){this.assertUsable(),r!==ul&&this.fail(new C(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new C(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=t}enterDepth(t,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??t,o=this.depthByKind.get(t)??0;o>=s&&this.fail(new C(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(t,o+1);let a=!1;return{release:()=>{if(a)return;a=!0;let l=(this.depthByKind.get(t)??1)-1;l<=0?this.depthByKind.delete(t):this.depthByKind.set(t,l)}}}throwIfAborted(t="execution"){this.signal?.aborted&&this.fail(new st("",`bash: ${t} aborted
2
+ import{a as Ht,b as Zt,c as dt}from"./chunks/chunk-WNH3HOQA.js";import{a as Qr}from"./chunks/chunk-BRJERIF4.js";import{c as Ii,e as Xa}from"./chunks/chunk-KIGPB52X.js";import{a as Hr,b as Zr,d as pr,e as mr}from"./chunks/chunk-PS2RJNZZ.js";import{a as an}from"./chunks/chunk-SGX4WOAM.js";import{a as Di}from"./chunks/chunk-L2UW7DWF.js";import{a as on,b as Xe,c as Er}from"./chunks/chunk-DLL7UR66.js";import{a as wr,b as Ka}from"./chunks/chunk-BKUWXPEM.js";import{a as ge}from"./chunks/chunk-4KZT23KR.js";import{a as Yr,b as Jr}from"./chunks/chunk-AYSZ5MAE.js";import{a as qn,b as Re}from"./chunks/chunk-ZBUZKIPX.js";import"./chunks/chunk-57LGFT4S.js";import{c as nn,d as Hn}from"./chunks/chunk-FTET43KM.js";import"./chunks/chunk-STHBFACM.js";import{a as gr,b as St,c as rn,d as es,e as z,f as qt,g as U,h as Zn,i as sn,j as Nn,k as Gt,l as Qn}from"./chunks/chunk-4CC3OZPU.js";import{a as Jt,b as tt,c as nt,d as We,e as Qe,f as Ke,g as G,h as ue,i as rt,j as en,k as Kr,l as C,m as st,n as Oe,o as tn,p as Xr,q as ut}from"./chunks/chunk-TVCZIH6M.js";import{a as W,b as yr,c as Cn,d as Od,e as Yt,f as Ri,g as Gn,h as Dd,i as Ut,j as Oi,k as Id,l as Td}from"./chunks/chunk-GN6CQ3J4.js";import{a as x,b as _d,c as ft,d as Ld}from"./chunks/chunk-T5ZEIOJ3.js";import{a as Ot}from"./chunks/chunk-FOCWZZDE.js";import{a as jt}from"./chunks/chunk-W5DWRFSU.js";import{a as Ni}from"./chunks/chunk-NCUTH6QL.js";import*as Me from"node:path";var Rn=[{name:"echo",load:async()=>(await import("./chunks/echo-PLLZYM2L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-VZBWBIJB.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-B2NSYQ3N.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-WH5S4PPL.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-Z6MMWH3D.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-3WTXMVKI.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-W4DF6Z4T.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-IGPLE632.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-UR762VVT.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-WE7DBLEK.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-CEM7GDB5.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-TEY5MD2W.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-76BPYV5F.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-JSRKXLLQ.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-6UIPFWVJ.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-UBGSN4JF.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-7WVM7GV4.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-LXFZND2P.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-JKB7DR66.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-6G32B25J.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-VS5QVYHU.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-CB5GO7XH.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-PAEPA27E.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-DTWKU2MC.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-FMDNVWQN.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-ZNHNSRBW.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-UI2LA3GA.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-EPOS3MFH.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-IELOWYJG.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-QJBPHRFJ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-J3VOSOMK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-YD5BWFH4.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-VLFTYX2Z.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-HUKVGJTW.js")).split},{name:"column",load:async()=>(await import("./chunks/column-QJI65SH2.js")).column},{name:"join",load:async()=>(await import("./chunks/join-C2B6NGXH.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-OOWSWHRQ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-RLKBCGJR.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SJZQ5W65.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-Z2ZMOOW2.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7OOL2MH6.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-EQKH3UNA.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-VUUMB47B.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-VUUMB47B.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3N762S3K.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-VQEXRD3C.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KPIUNI6K.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-UKAA3QWU.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-MHVQ5XHI.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-R7TXVVLN.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-7OEDRA27.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-25QUPVDK.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-37GM7IIL.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-NERE2JJ2.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-B6KDLMYQ.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-A5XITHQD.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-JEDX55KS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BLPZJ6MP.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-VJZ4PHQ4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-6AYYTULJ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-PE6BPRPA.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-QDDMBDU7.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-UWVKETYW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-YXC4HBTR.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-CESD3CQR.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KR6E7UIR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-Z4AIL3P4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Rn.push({name:"tar",load:async()=>(await import("./chunks/tar-LE7LAAIX.js")).tarCommand}),Rn.push({name:"yq",load:async()=>(await import("./chunks/yq-ZRNZKDLE.js")).yqCommand}),Rn.push({name:"xan",load:async()=>(await import("./chunks/xan-UIL24CGT.js")).xanCommand}),Rn.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-DQNCWDG5.js")).sqlite3Command}));var ts=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ts.push({name:"python3",load:async()=>(await import("./chunks/python3-W4UMQJAQ.js")).python3Command}),ts.push({name:"python",load:async()=>(await import("./chunks/python3-W4UMQJAQ.js")).pythonCommand}));var ns=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ns.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-MUZRDUJ3.js")).jsExecCommand}),ns.push({name:"node",load:async()=>(await import("./chunks/js-exec-MUZRDUJ3.js")).nodeStubCommand}));var Ja=[{name:"curl",load:async()=>(await import("./chunks/curl-K4WT7UPN.js")).curlCommand}],Ya=new Map;function rs(e){return{name:e.name,async execute(t,n){let r=Ya.get(e.name);if(r||(r=await Re.runTrustedAsync(()=>e.load()),Ya.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await import("./chunks/flag-coverage-YQGACUSN.js");s(n.coverage,e.name,t)}return r.execute(t,n)}}}function Fd(){return Rn.map(e=>e.name)}function Md(){return Ja.map(e=>e.name)}function el(e){return(e?Rn.filter(n=>e.includes(n.name)):Rn).map(rs)}function tl(){return Ja.map(rs)}function Bd(){return ts.map(e=>e.name)}function nl(){return ts.map(rs)}function Wd(){return ns.map(e=>e.name)}function rl(){return ns.map(rs)}var sl=new WeakMap,il=new WeakSet;function ss(e){let t=sl.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),sl.set(e,t),il.add(t)),t}function ol(e){return il.has(e)}var al={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxJsMemoryBytes:67108864,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},Vd={...al,maxSourceBytes:8*1024*1024,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxExtensionCleanupTimeMs:25,maxGlobOperations:1e5,maxStringLength:10*1024*1024,maxArrayElements:1e5,maxHeredocSize:10*1024*1024,maxBraceExpansionResults:1e4,maxOutputSize:10*1024*1024,maxFileDescriptors:1024,maxQueryTokens:25e3,maxQueryDepth:256,maxQueryElements:1e5,maxAwkParserTokens:25e3,maxAwkParserDepth:128,maxAwkParserOperations:1e5,maxCsvRows:1e5,maxCsvCells:1e6,maxWorkUnits:1e5,maxTraversalEntries:1e5,maxTraversalDepth:256,maxTraversalWork:1e5,maxLiveBytes:64*1024*1024,maxInputBytes:32*1024*1024,maxFileSystemBytes:128*1024*1024,maxDatabaseBytes:64*1024*1024,maxDatabaseResultBytes:16*1024*1024,maxArchiveBytes:128*1024*1024,maxArchiveCompressedBytes:64*1024*1024,maxArchiveEntryBytes:64*1024*1024,maxArchiveEntries:1e5,maxWorkerMessageBytes:16*1024*1024,maxExecutionTimeMs:3e4};function is(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?Vd:al;if(!e)return{...n};let r={maxSourceBytes:e.maxSourceBytes??n.maxSourceBytes,maxExecDepth:e.maxExecDepth??n.maxExecDepth,maxCallDepth:e.maxCallDepth??n.maxCallDepth,maxCommandCount:e.maxCommandCount??n.maxCommandCount,maxLoopIterations:e.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??n.maxAwkIterations,maxSedIterations:e.maxSedIterations??n.maxSedIterations,maxJqIterations:e.maxJqIterations??n.maxJqIterations,maxQueryTokens:e.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:e.maxQueryDepth??n.maxQueryDepth,maxQueryElements:e.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:e.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:e.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:e.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:e.maxCsvRows??n.maxCsvRows,maxCsvCells:e.maxCsvCells??n.maxCsvCells,maxWorkUnits:e.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:e.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:e.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:e.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:e.maxLiveBytes??n.maxLiveBytes,maxInputBytes:e.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:e.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:e.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:e.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:e.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:e.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:e.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:e.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:e.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:e.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:e.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??n.maxJsTimeoutMs,maxJsMemoryBytes:e.maxJsMemoryBytes??n.maxJsMemoryBytes,maxGlobOperations:e.maxGlobOperations??n.maxGlobOperations,maxStringLength:e.maxStringLength??n.maxStringLength,maxArrayElements:e.maxArrayElements??n.maxArrayElements,maxHeredocSize:e.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??n.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??n.maxSourceDepth};for(let s of Object.keys(r)){let i=r[s];if(i!==Number.POSITIVE_INFINITY&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`${s} must be a non-negative safe integer or positive Infinity`)}return r}function zd(e){let{executionLimits:t,executionLimitProfile:n,fs:r,stdin:s=Ri,...i}=e;return{fs:r,fsIdentity:i.fsIdentity??ss(r),cwd:"/",env:new Map,stdin:s,limits:is(t,n),...i}}function ll(e){return"load"in e&&typeof e.load=="function"}function Ud(e,t,n={}){return{name:e,trusted:n.trusted!==!1,execute:t}}function cl(e){let t=null,n=null;return{name:e.name,trusted:e.trusted!==!1,async execute(r,s){if(!t){let o=n;o||(o=e.load().then(a=>(t=a,a)),n=o);try{t=await o}catch(a){throw n===o&&(n=null),a}}let i=t;if(!i)throw new Error(`Failed to load command: ${e.name}`);return i.execute(r,s)}}}var ul=Object.freeze(Object.create(null)),os=class{limits;signal;abortOnUnresolvedCommands;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();unresolvedCommands=new Set;get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(t,n=void 0,r=!1){this.limits=t,this.signal=n,this.abortOnUnresolvedCommands=r}recordUnresolvedCommand(t){this.unresolvedCommands.add(t)}get unresolvedCommandNames(){return[...this.unresolvedCommands]}fail(t){throw this.poisoned??=t,this.poisoned}poisonAfterAbort(t){this.poisoned??=t}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(t=1,n="execution"){return this.consume("work",t,n)}consumeLimited(t,n,r,s=t){this.assertUsable();let i=this.countersByKind.get(t)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new C(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new C(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(t,i+n),this.workUnits+=n,i+n}consumeInput(t,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(t)||t<0||t>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new C(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=t,this.inputBytes}consume(t,n=1,r=t){this.assertUsable();let s=this.countersByKind.get(t)??0,i=t==="commands"?this.commandCount:this.workUnits,o=t==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>o-i)&&this.fail(new C(t==="commands"?`too many commands executed (>${o}), increase executionLimits.maxCommandCount`:`${r}: ${t} work limit exceeded (${o})`,t==="commands"?"commands":"iterations"));let a=i+n;return t==="commands"?this.commandCount=a:this.workUnits=a,this.countersByKind.set(t,s+n),a}reserveBytes(t,n,r){this.assertUsable();let s=typeof t=="string"?t:"live",i=typeof t=="string"?n:t,o=typeof t=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new C(`${o}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let a=!1;return{release:()=>{if(a)return;a=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(t,n,r="execution",s=0,i="text"){this.assertUsable();let o=i==="bytes"?n.length:W(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new C(`${r}: invalid ${t} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new C(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=a,o}accountResult(t,n="execution",r=Number.POSITIVE_INFINITY){let s=t.internalOutputAccounting,i=Math.min(s?.stdout??0,r),o=Math.min(s?.stderr??0,Math.max(0,r-i)),a=this.appendOutput("stdout",t.stdout,n,i,t.stdoutKind==="bytes"||t.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",t.stderr,n,o);return Object.isExtensible(t)?(t.internalOutputAccounting={stdout:a,stderr:l},t):a===0&&l===0?t:{...t,internalOutputAccounting:{stdout:a,stderr:l}}}relinquishOutput(t,n,r){this.assertUsable(),r!==ul&&this.fail(new C(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new C(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=t}enterDepth(t,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??t,o=this.depthByKind.get(t)??0;o>=s&&this.fail(new C(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(t,o+1);let a=!1;return{release:()=>{if(a)return;a=!0;let l=(this.depthByKind.get(t)??1)-1;l<=0?this.depthByKind.delete(t):this.depthByKind.set(t,l)}}}throwIfAborted(t="execution"){this.signal?.aborted&&this.fail(new st("",`bash: ${t} aborted
3
3
  `)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new st("",`bash: ${t} exceeded execution deadline (${this.limits.maxExecutionTimeMs}ms)
4
4
  `))}remainingTimeMs(){return Math.max(0,this.limits.maxExecutionTimeMs-(Date.now()-this.startedAt))}registerCleanup(t){this.assertUsable(),this.cleanupCallbacks.push(t);let n=!0;return()=>{if(!n)return;n=!1;let r=this.cleanupCallbacks.indexOf(t);r>=0&&this.cleanupCallbacks.splice(r,1)}}async close(){if(this.closed)return;this.closed=!0;let t=[],n=Date.now()+this.limits.maxExtensionCleanupTimeMs;for(let r=this.cleanupCallbacks.length-1;r>=0;r--)try{let s=n-Date.now();if(s<=0){t.push(new Error("execution cleanup grace period exceeded"));break}let i,o=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[r]).then(()=>({ok:!0}),a=>({ok:!1,error:a})),new Promise(a=>{i=pr(()=>a({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(mr(i),!o.ok&&(t.push(o.error),Date.now()>=n))break}catch(s){t.push(s)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,t.length>0)throw new AggregateError(t,"execution cleanup failed")}assertExecDepth(t){this.assertUsable(),t>this.limits.maxExecDepth&&this.fail(new C(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function fl(e){let t=Object.create(null);return Object.defineProperties(t,{remainingLiveBytes:{enumerable:!0,get:()=>e.remainingLiveBytes},consumeWork:{enumerable:!0,value:e.consumeWork.bind(e)},consumeLimited:{enumerable:!0,value:e.consumeLimited.bind(e)},consumeInput:{enumerable:!0,value:e.consumeInput.bind(e)},reserveBytes:{enumerable:!0,value:e.reserveBytes.bind(e)},enterDepth:{enumerable:!0,value:e.enterDepth.bind(e)},throwIfAborted:{enumerable:!0,value:e.throwIfAborted.bind(e)},remainingTimeMs:{enumerable:!0,value:e.remainingTimeMs.bind(e)},registerCleanup:{enumerable:!0,value:e.registerCleanup.bind(e)}}),Object.freeze(t)}function dl(e,t,n="pipeline"){e.relinquishOutput(t,n,ul)}var On=new TextEncoder;function jd(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var ze=class{data=new Map;entryIdentities=new WeakMap;nextEntryIdentity=1;maxTotalBytes;retainedBytes=0;contentReferences=new WeakMap;materializedContent(t){return t?.type==="file"&&"content"in t?t.content:null}storedByteLength(t){return t===null?0:t instanceof Uint8Array?t.byteLength:W(t)}wouldReleaseBytes(t){let n=this.materializedContent(t);return n===null?0:n instanceof Uint8Array?this.contentReferences.get(n)===1?n.byteLength:0:this.storedByteLength(n)}assertCanAllocate(t,n){let r=this.wouldReleaseBytes(this.data.get(t));if(!Number.isSafeInteger(n)||n<0||n>this.maxTotalBytes-this.retainedBytes+r)throw new x("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(t,n){let r=this.data.get(t),s=this.materializedContent(r),i=this.materializedContent(n);if(s===i){this.data.set(t,n);return}let o=this.wouldReleaseBytes(r),a=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(a>this.maxTotalBytes-this.retainedBytes+o)throw new x("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(s instanceof Uint8Array){let l=this.contentReferences.get(s)??0;l<=1?this.contentReferences.delete(s):this.contentReferences.set(s,l-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=a-o,this.data.set(t,n)}deleteEntry(t){let n=this.data.get(t);if(!n)return!1;let r=this.materializedContent(n),s=this.wouldReleaseBytes(n);if(r instanceof Uint8Array){let i=this.contentReferences.get(r)??0;i<=1?this.contentReferences.delete(r):this.contentReferences.set(r,i-1)}return this.retainedBytes-=s,this.data.delete(t)}contentByteLength(t,n){if(t instanceof Uint8Array)return t.byteLength;if(n==="hex")return Math.floor(t.length/2);if(n==="base64"){let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-r)}return n==="binary"||n==="latin1"?t.length:W(t)}identityFor(t){let n=this.entryIdentities.get(t);return n||(n=`memfs:${this.nextEntryIdentity++}`,this.entryIdentities.set(t,n)),n}constructor(t,n={}){if(this.maxTotalBytes=n.maxTotalBytes??1024*1024*1024,!Number.isSafeInteger(this.maxTotalBytes)||this.maxTotalBytes<0)throw new Error("InMemoryFs: invalid maxTotalBytes");if(this.data.set("/",{type:"directory",mode:St,mtime:new Date}),t)for(let[r,s]of Object.entries(t))typeof s=="function"?this.writeFileLazy(r,s):jd(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(t){let n=Zn(t);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:St,mtime:new Date})))}writeFileSync(t,n,r,s){U(t,"write");let i=z(t);this.ensureParentDirs(i);let o=dt(r);this.assertCanAllocate(i,this.contentByteLength(n,o));let a=Ht(n,o);this.setEntry(i,{type:"file",content:a,mode:s?.mode??rn,mtime:s?.mtime??new Date})}writeFileLazy(t,n,r){U(t,"write");let s=z(t);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??rn,mtime:r?.mtime??new Date})}async materializeLazy(t,n){let r=await Re.runTrustedAsync(async()=>n.lazy()),s=typeof r=="string"?On.encode(r):r,i={type:"file",content:s,mode:n.mode,mtime:n.mtime};return this.assertCanAllocate(t,s.byteLength),this.setEntry(t,i),i}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t){U(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, open '${t}'`);if(r.type!=="file")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:On.encode(s.content)}return r.content instanceof Uint8Array?r.content:On.encode(r.content)}async writeFile(t,n,r){this.writeFileSync(t,n,r)}async appendFile(t,n,r){U(t,"append");let s=z(t),i=this.data.get(s);if(i&&i.type==="directory")throw new x("EISDIR",`illegal operation on a directory, write '${t}'`);let o=dt(r),a=this.contentByteLength(n,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:On.encode("content"in l?l.content:"");this.assertCanAllocate(s,c.byteLength+a);let u=Ht(n,o),f=new Uint8Array(c.length+u.length);f.set(c),f.set(u,c.length),this.setEntry(s,{type:"file",content:f,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,n,r)}async exists(t){if(t.includes("\0"))return!1;try{let n=this.resolvePathWithSymlinks(t);return this.data.has(n)}catch{return!1}}async stat(t){U(t,"stat");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=On.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}async lstat(t){U(t,"lstat");let n=this.resolveIntermediateSymlinks(t),r=this.data.get(n);if(!r)throw new x("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(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=On.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}resolveIntermediateSymlinks(t){let n=z(t);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];s=`${s}/${a}`;let l=this.data.get(s),c=0,u=gr;for(;l&&l.type==="symlink"&&c<u;){if(i.has(s))throw new x("ELOOP",`too many levels of symbolic links, lstat '${t}'`);i.add(s),s=Qn(s,l.target),l=this.data.get(s),c++}if(c>=u)throw new x("ELOOP",`too many levels of symbolic links, lstat '${t}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let n=z(t);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let o of r){s=`${s}/${o}`;let a=this.data.get(s),l=0,c=gr;for(;a&&a.type==="symlink"&&l<c;){if(i.has(s))throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`);i.add(s),s=Qn(s,a.target),a=this.data.get(s),l++}if(l>=c)throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`)}return s}async mkdir(t,n){this.mkdirSync(t,n)}mkdirSync(t,n){U(t,"mkdir");let r=z(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new x("EEXIST",`file already exists, mkdir '${t}'`);if(!n?.recursive)throw new x("EEXIST",`directory already exists, mkdir '${t}'`);return}let s=Zn(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:St,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){U(t,"scandir");let n=z(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new x("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(n),n=Qn(n,r.target),r=this.data.get(n)}if(!r)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(t,n){U(t,"rm");let r=z(t),s=this.data.get(r);if(!s){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);for(let o of i){let a=Gt(r,o);await this.rm(a,n)}}}this.deleteEntry(r)}async cp(t,n,r){U(t,"cp"),U(n,"cp");let s=z(t),i=z(n),o=this.data.get(s);if(!o)throw new x("ENOENT",`no such file or directory, cp '${t}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?o.content.byteLength:On.encode(o.content).byteLength;this.assertCanAllocate(i,a);let l=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.setEntry(i,{...o,content:l})}else this.setEntry(i,{...o});else if(o.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new x("EISDIR",`is a directory, cp '${t}'`);if(qt(s,i))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=Gt(s,l),u=Gt(i,l);await this.cp(c,u,r)}}}async mv(t,n){U(t,"mv"),U(n,"mv");let r=z(t),s=z(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(i.type==="directory"&&qt(r,s))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let o=await this.readdir(r);for(let a of o)await this.mv(Gt(r,a),Gt(s,a));this.deleteEntry(r);return}this.ensureParentDirs(s),this.setEntry(s,i),this.deleteEntry(r)}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,n){return sn(t,n)}async chmod(t,n){U(t,"chmod");let r=z(t),s=this.data.get(r);if(!s)throw new x("ENOENT",`no such file or directory, chmod '${t}'`);s.mode=n}async symlink(t,n){U(n,"symlink");let r=z(n);if(this.data.has(r))throw new x("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:es,mtime:new Date})}async link(t,n){U(t,"link"),U(n,"link");let r=z(t),s=z(n),i=this.data.get(r);if(!i)throw new x("ENOENT",`no such file or directory, link '${t}'`);if(i.type!=="file")throw new x("EPERM",`operation not permitted, link '${t}'`);if(this.data.has(s))throw new x("EEXIST",`file already exists, link '${n}'`);let o=i;"lazy"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(s);let a={type:"file",content:o.content,mode:o.mode,mtime:o.mtime};this.entryIdentities.set(a,this.identityFor(o)),this.setEntry(s,a)}async readlink(t){U(t,"readlink");let n=z(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new x("EINVAL",`invalid argument, readlink '${t}'`);return r.target}async realpath(t){U(t,"realpath");let n=this.resolvePathWithSymlinks(t);if(!this.data.has(n))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return n}async utimes(t,n,r){U(t,"utimes");let s=z(t),i=this.resolvePathWithSymlinks(s),o=this.data.get(i);if(!o)throw new x("ENOENT",`no such file or directory, utimes '${t}'`);o.mtime=r}};var hl="5.1.0(1)-release",pl="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Ti(e){let{pid:t,ppid:n,uid:r,gid:s}=e;return`Name: bash
5
5
  State: R (running)
@@ -807,7 +807,7 @@ ${b.join(`
807
807
  `,exitCode:2,env:Xe(this.state.env,u.env)});if(y instanceof RangeError)return l({stdout:"",stderr:`bash: ${Ot(y.message)}
808
808
  `,exitCode:1,env:Xe(this.state.env,u.env)});throw y}finally{g?.deactivate()}}catch(f){if(f instanceof st)return l({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:Xe(this.state.env,u.env)});if(f instanceof C)return l({stdout:f.stdout,stderr:Ot(f.stderr),exitCode:C.EXIT_CODE,internalOutputAccounting:f.internalOutputAccounting,env:Xe(this.state.env,u.env)});throw f}finally{c.cleanup()}}async readFile(t){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),n)}getCwd(){return this.state.cwd}getEnv(){return on(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){fr(t,this.limits.maxSourceBytes);let n=Ua(t),r=qe(n,{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let i of this.transformPlugins){let o=i.transform({ast:r,metadata:s});r=o.ast,o.metadata&&(s=Er(s,o.metadata))}return{script:Nr(r),ast:r,metadata:s}}async analyzeCommands(t){fr(t,this.limits.maxSourceBytes);let n=qe(Ua(t),{maxHeredocSize:this.limits.maxHeredocSize}),{commands:r,definedFunctions:s,definedAliases:i}=ls(n),o=[];for(let a of r)s.has(a)||i.has(a)||await this.resolvesCommandForAnalysis(a)||o.push(a);return{commands:r,unresolved:o}}async resolvesCommandForAnalysis(t){if((Ar.has(t)||Dt.has(t))&&!yl.has(t)||this.state.functions.has(t))return!0;let n=await us({fs:this.fs,state:{...this.state,hashTable:new Map},commands:this.commands},t);return n!==null&&!("error"in n)}};function qy(e,t){let n=t;for(let r=0;r<e.length;r++){let s=e[r];if(n==="single")s==="'"&&(n="none");else if(n==="double")s==="\\"?r++:s==='"'&&(n="none");else if(s==="'")n="single";else if(s==='"')n="double";else if(s==="\\")r++;else if(s==="#"&&(r===0||/\s/.test(e[r-1])))break}return n}function Ua(e){let t=e.split(`
809
809
  `),n=[],r=[],s="none";for(let i=0;i<t.length;i++){let o=t[i];if(r.length>0){let u=r[r.length-1];if((u.stripTabs?o.replace(/^\t+/,""):o)===u.delimiter){n.push(o.trimStart()),r.pop();continue}n.push(o);continue}let a=s,l=a==="none"?o.trimStart():o;if(n.push(l),s=qy(o,a),a!=="none")continue;let c=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let u of l.matchAll(c)){let f=u[1]==="-",d=u[3];r.push({delimiter:d,stripTabs:f})}}return n.join(`
810
- `)}var Gy=new TextDecoder("utf-8",{fatal:!0});function bd(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>255)return e;s>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);try{return Gy.decode(n)}catch{return e}}function Hy(e,t,n,r,s,i){if(e===void 0)return;let o=t==="bytes"?e.length:W(e);if(o>n||o>r)throw new C(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),t==="bytes"?e:Yt(e)}import*as ke from"node:fs";import*as gi from"node:path";function dr(e){return ke.realpathSync(e)}function ja(e){ke.rmSync(e,{recursive:!0,force:!0})}function Ad(e,t){let n;try{n=ke.lstatSync(e)}catch{return!1}return t?!n.isDirectory():n.isDirectory()}function Sd(e,t){Ad(e,t)&&ke.rmSync(e,{recursive:!0,force:!0})}function qa(e,t){if(t.nodeType==="directory"){Sd(e,!0),ke.mkdirSync(e,{recursive:!0}),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime);return}if(ke.mkdirSync(gi.dirname(e),{recursive:!0}),t.nodeType==="symlink"){ke.rmSync(e,{force:!0,recursive:!0}),ke.symlinkSync(new TextDecoder().decode(t.content),e);return}if(t.metadataOnly&&Ad(e,!1))throw new x("EINVAL",`metadata-only entry over a different on-disk type: '${e}'`);t.metadataOnly||(Sd(e,!1),ke.writeFileSync(e,t.content)),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime)}function wi(e){for(let r of[...e.deletions,...e.writes.map(s=>s.path)])if(gi.resolve(r)!==r)throw new x("EINVAL",`change-set path is not normalized: '${r}'`);let t=[...e.deletions].sort((r,s)=>s.length-r.length||(r<s?-1:r>s?1:0));for(let r of t)ja(r);let n=[...e.writes].sort((r,s)=>r.path.length-s.path.length||(r.path<s.path?-1:r.path>s.path?1:0));for(let{path:r,...s}of n)qa(r,s)}import*as Ee from"node:fs";import*as Fe from"node:path";import*as Ze from"node:fs";import*as Ne from"node:path";function Le(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?Ne.win32:Ne.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function jn(e,t){try{let n=Ze.realpathSync(e);return Le(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=Ne.dirname(e);if(r===e)return null;let s=jn(r,t);if(s===null)return null;try{if(Ze.lstatSync(e).isSymbolicLink()){let o=Ze.readlinkSync(e),a=Ne.isAbsolute(o)?o:Ne.resolve(Ne.dirname(e),o),l=jn(a,t);return l===null?null:l}}catch{}return Ne.join(s,Ne.basename(e))}return null}}function Ei(e,t,n){let r=jn(e,n);if(r===null)return null;let s=Ne.resolve(e),i=s.slice(t.length),o=r.slice(n.length);if(i!==o)return null;try{if(Ze.lstatSync(s).isSymbolicLink())return null}catch{}return r}function bi(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 vd(e,t){if(!Ne.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=Ze.realpathSync(e)}catch{n=Ne.resolve(e)}return Le(n,t)?{withinRoot:!0,relativePath:Nn(n.slice(t.length))||"/"}:{withinRoot:!1,safeName:Ne.basename(e)}}function Si(e,t,n,r){let s=e;if(s.path===void 0){for(let o of r)if(s.message?.includes(o))throw e}let i=s.code||"EIO";throw new x(i,`${n} '${t}'`)}async function Nt(e){return kd(await Ze.promises.lstat(e))}function Ga(e){return kd(Ze.lstatSync(e))}function kd(e){return process.platform==="win32"&&e.isDirectory()&&(e.mode=e.mode&-512|493),e}function Ai(e){let t=e.content.byteLength;for(let n of e.appendChunks??[])t+=n.byteLength;return t}function $d(e){return Ai(e)}function ki(e,t){if(!e.appendChunks||e.appendChunks.length===0)return e.content;let n=e.appendChunks.reduce((i,o)=>i+o.byteLength,e.content.byteLength);if(!Number.isSafeInteger(n))throw new x("EFBIG",`file too large, read '${t}'`);let r=new Uint8Array(n);r.set(e.content);let s=e.content.byteLength;for(let i of e.appendChunks)r.set(i,s),s+=i.byteLength;return e.content=r,e.appendChunks=void 0,r}function xd(e){return!e||e.type!=="file"?0:Ai(e)}function qr(){return{type:"directory",children:new Map,changedAt:Date.now(),mode:St,mtime:new Date}}function Gr(e){return e.split("/").filter(Boolean)}var vi=class e{maxMemoryBytes;rootNode=qr();bytes=0;mutationSeq_=0;constructor(t){this.maxMemoryBytes=t}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(t){let n=Gr(t),r=[this.rootNode],s=this.rootNode;for(let i=0;i<n.length;i++){let o=s.children.get(n[i]);if(o===void 0)return{kind:"missing",stack:r,missingAt:i};if(i===n.length-1)return{kind:"found",stack:r,node:o};if(o.type==="whiteout")return{kind:"blocked",stack:r,blockedAt:i};if(o.type!=="directory")return{kind:"notdir",stack:r,notdirAt:i};r.push(o),s=o}return{kind:"found",stack:[],node:this.rootNode}}ensureDirs(t,n){let r=this.rootNode,s="";for(let i of Gr(t)){s=`${s}/${i}`;let o=r.children.get(i);if(o===void 0)o=qr(),r.children.set(i,o);else if(o.type==="whiteout")o=this.resurrectDir(r,i,s,o.changedAt??0,n);else if(o.type!=="directory")throw new x("ENOTDIR",`not a directory, mkdir '${t}'`);r=o}return r}resurrectDir(t,n,r,s,i){let o=qr();t.children.set(n,o);let a=i?.(r);if(a)for(let l of a)o.children.has(l)||o.children.set(l,{type:"whiteout",changedAt:s});return o}attach(t,n){n.changedAt=Date.now();let r=Gr(t);if(r.length===0)throw new x("EINVAL",`cannot attach at root, attach '${t}'`);let s=this.parentDirOf(r,t),i=s.children.get(r[r.length-1]);if(i?.type==="directory"&&n.type!=="directory")throw new x("EISDIR",`cannot replace directory with ${n.type}, attach '${t}'`);if(i!==void 0&&n.type==="directory")throw new x("EEXIST",`cannot replace ${i.type} with directory, attach '${t}'`);let o=xd(i),a=xd(n);this.assertCapacity(a,o),s.children.set(r[r.length-1],n),this.bytes+=a-o}detach(t){let n=Gr(t);if(n.length===0)return;let r=this.descend(t);return r.kind!=="found"?void 0:(r.stack[r.stack.length-1].children.delete(n[n.length-1]),this.bytes-=e.subtreeBytes(r.node),r.node)}putWhiteout(t){let n=Gr(t);if(n.length===0)throw new x("EINVAL",`cannot whiteout the root, rm '${t}'`);let r=this.rootNode;for(let o=0;o<n.length-1;o++)r=this.ensureChildDir(r,n[o],t);let s=n[n.length-1],i=r.children.get(s);i?.type!=="whiteout"&&(this.bytes-=e.subtreeBytes(i),r.children.set(s,{type:"whiteout",changedAt:Date.now()}))}appendChunk(t,n){this.assertCapacity(n.byteLength),t.appendChunks||(t.appendChunks=[]),t.appendChunks.push(n),this.bytes+=n.byteLength,this.touch(t)}touch(t){t.seq=++this.mutationSeq_,t.changedAt=Date.now()}detachIfUnchanged(t,n,r){let s=this.descend(t);return s.kind!=="found"||s.node!==n||n.seq!==r||n.type==="directory"&&n.children.size>0?!1:(this.detach(t),!0)}*preOrder(){let t=[{path:"/",node:this.rootNode}];for(;t.length>0;){let n=t.pop();if(yield n,n.node.type==="directory"){let r=[...n.node.children.entries()];for(let s=r.length-1;s>=0;s--){let[i,o]=r[s];t.push({path:Pd(n.path,i),node:o})}}}}*postOrder(){let t=[],n=[{path:"/",node:this.rootNode}];for(;n.length>0;){let r=n.pop();if(t.push(r),r.node.type==="directory")for(let[s,i]of r.node.children)n.push({path:Pd(r.path,s),node:i})}for(let r=t.length-1;r>=0;r--)yield t[r]}clear(){this.rootNode=qr(),this.bytes=0}static subtreeBytes(t){if(t===void 0)return 0;if(t.type==="file")return Ai(t);if(t.type!=="directory")return 0;let n=0,r=[t];for(;r.length>0;){let s=r.pop();for(let i of s.children.values())i.type==="file"?n+=Ai(i):i.type==="directory"&&r.push(i)}return n}parentDirOf(t,n){let r=this.rootNode;for(let s=0;s<t.length-1;s++){let i=r.children.get(t[s]);if(i?.type!=="directory")throw new x("ENOTDIR",`not a directory, attach '${n}'`);r=i}return r}ensureChildDir(t,n,r){let s=t.children.get(n);if(s===void 0||s.type==="whiteout")s=qr(),t.children.set(n,s);else if(s.type!=="directory")throw new x("ENOTDIR",`not a directory, rm '${r}'`);return s}assertCapacity(t,n=0){if(!Number.isSafeInteger(t)||t<0||t>this.maxMemoryBytes-this.bytes+n)throw new x("ENOSPC",`overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function Pd(e,t){return e==="/"?`/${t}`:`${e}/${t}`}var Zy=["ELOOP","EFBIG","EPERM"],Qy="/home/user/project",Rt=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;get rootDir(){return this.root}restamp(t,n,r="full"){let s=z(t),i=c=>{let u=this.tree.descend(c);u.kind==="found"&&(u.node.changedAt=n)},o=c=>{let u=this.tree.descend(c);if(u.kind==="found"){let f=u.node;(f.changedAt??0)>n&&(f.changedAt=n,f.mtime=new Date(n))}};r==="full"&&i(s);let a=s;for(;;){let c=a.lastIndexOf("/");if(c<=0)break;a=a.slice(0,c),o(a)}if(r==="ancestors")return;let l=[s];for(;l.length>0;){let c=l.pop(),u=this.tree.descend(c);if(!(u.kind!=="found"||u.node.type!=="directory"))for(let f of u.node.children.keys()){let d=`${c==="/"?"":c}/${f}`;o(d),l.push(d)}}}identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Fe.resolve(t.root);let n=t.mountPoint??Qy;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxMemoryBytes=t.maxMemoryBytes??1024*1024*1024,!Number.isSafeInteger(this.maxMemoryBytes)||this.maxMemoryBytes<0)throw new Error("OverlayFs: invalid maxMemoryBytes");this.allowSymlinks=t.allowSymlinks??!1,bi(this.root,"OverlayFs"),this.canonicalRoot=Ee.realpathSync(this.root),this.tree=new vi(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new x("EROFS",`read-only file system, ${t}`)}createMountPointDirs(){this.tree.ensureDirs(this.mountPoint)}getMountPoint(){return this.mountPoint}diff(){let t=[],n=[],r=[];for(let{path:i,node:o}of this.tree.preOrder()){let a=this.getRelativeToMount(i);if(!(a===null||a==="/")){if(o.type==="whiteout"){this.existsOnRealFs(i)&&(n.push(a),r.push(o.changedAt??0));continue}if(o.type==="file")if(o.metacopy){if(!this.existsOnRealFs(i))continue;t.push({path:a,nodeType:"file",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0,metadataOnly:!0})}else t.push({path:a,nodeType:"file",content:ki(o,i),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0});else o.type==="directory"?t.push({path:a,nodeType:"directory",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0}):t.push({path:a,nodeType:"symlink",content:new TextEncoder().encode(o.target),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0})}}t.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0);let s=n.map((i,o)=>({path:i,changedAt:r[o]}));return s.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),{writes:t,deletions:s.map(i=>i.path),...s.length>0&&{deletionChangedAt:s.map(i=>i.changedAt)}}}async sync(){for(let{path:t,node:n}of this.tree.postOrder()){let r=this.getRelativeToMount(t);if(r===null||r==="/")continue;if(n.type==="whiteout"){this.existsOnRealFs(t)||this.tree.detach(t);continue}if(n.type==="directory"&&n.children.size>0)continue;let s=n.seq;await this.nodeMatchesDisk(t,n)&&this.tree.detachIfUnchanged(t,n,s)}}reset(){this.tree.clear(),this.createMountPointDirs()}drop(t){let n=t.map(r=>{let s=z(r);if(s==="/")throw new x("EINVAL",`invalid argument, drop '${r}'`);return this.mountPoint==="/"?s:`${this.mountPoint}${s}`});n.sort((r,s)=>s.length-r.length);for(let r of n){let s=this.tree.descend(r);if(s.kind!=="found")continue;let i=s.node;i.type==="directory"&&i.children.size>0||this.tree.detach(r)}}async lstatLower(t){let n=this.resolveRealPathParent_(this.toRealPath(t));if(!n)return null;try{return{canonical:n,stat:await Nt(n)}}catch{return null}}async nodeMatchesDisk(t,n){if(n.type==="directory")return(await this.lstatLower(t))?.stat.isDirectory()??!1;if(n.type==="symlink"){if(!this.allowSymlinks)return!1;let s=await this.lstatLower(t);if(!s?.stat.isSymbolicLink())return!1;try{let i=await Ee.promises.readlink(s.canonical);return this.realTargetToVirtual(i)===n.target}catch{return!1}}if(n.metacopy){let s=await this.lstatLower(t);if(!s?.stat.isFile())return!1;let{stat:i}=s;return!(i.mtime.getTime()!==n.mtime.getTime()||process.platform!=="win32"&&(i.mode&4095)!==(n.mode&4095))}let r=this.resolveRealPath_(this.toRealPath(t));if(!r)return!1;try{let s=await Nt(r);if(!s.isFile())return!1;let i=ki(n,t);if(s.size!==i.byteLength)return!1;let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(r,o),l;try{l=new Uint8Array(await a.readFile())}finally{await a.close()}for(let c=0;c<l.byteLength;c++)if(l[c]!==i[c])return!1;return!0}catch{return!1}}mkdirSync(t,n){this.tree.ensureDirs(z(t),r=>this.lowerChildren(r))}writeFileSync(t,n){let r=z(t);this.ensureParentDirs(r);let s=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.tree.attach(r,{type:"file",content:s,mode:rn,mtime:new Date})}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let n=z(t),r=this.getRelativeToMount(n);if(r===null)return null;let s=Fe.join(this.root,r),i=Fe.resolve(s);return Le(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?jn(t,this.canonicalRoot):Ei(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Fe.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Fe.join(r,Fe.basename(t))}sanitizeError(t,n,r){Si(t,n,r,Zy)}ensureParentDirs(t){let n=Zn(t);n!=="/"&&this.tree.ensureDirs(n,r=>this.lowerChildren(r))}lowerChildren(t){let n=this.resolveRealPath_(this.toRealPath(t));if(!n)return null;try{return Ee.readdirSync(n)}catch{return null}}async existsInOverlay(t){let n=z(t),r=this.tree.descend(n);if(r.kind==="found")return r.node.type!=="whiteout";if(r.kind==="blocked"||r.kind==="notdir")return!1;let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)return!1;try{return await Nt(s),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t,n=new Set){U(t,"open");let r=z(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, open '${t}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.type==="symlink"){let a=this.resolveSymlink(r,i.target);return this.readFileBuffer(a,n)}if(i.type!=="file")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(!i.metacopy)return ki(i,t);let o=await this.readLowerFileBytes(r,t,n);if(process.platform==="win32")try{this.tree.attach(r,{type:"file",content:o,mode:i.mode,mtime:i.mtime})}catch(a){if(!ft(a,"ENOSPC"))throw a}return o}return this.readLowerFileBytes(r,t,n)}async readLowerFileBytes(t,n,r){let s=this.resolveRealPath_(this.toRealPath(t));if(!s)throw new x("ENOENT",`no such file or directory, open '${n}'`);try{let i=await Nt(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, open '${n}'`);let l=await Ee.promises.readlink(s),c=this.realTargetToVirtual(l),u=this.resolveSymlink(t,c);return this.readFileBuffer(u,r)}if(i.isDirectory())throw new x("EISDIR",`illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(s,o);try{let l=await a.readFile();return new Uint8Array(l)}finally{await a.close()}}catch(i){let o=i.code;if(o==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${n}'`);if(o==="ELOOP")throw new x("ENOENT",`no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(t,n,r){U(t,"write"),this.assertWritable(`write '${t}'`);let s=z(t);this.ensureParentDirs(s);let i=dt(r),o=Ht(n,i);this.tree.attach(s,{type:"file",content:o,mode:await this.inheritedMode(s),mtime:new Date})}async inheritedMode(t){let n=this.entryAt(t);if(n?.type==="file")return n.mode;if(n?.type==="directory")return rn;if(process.platform==="win32")return rn;try{let r=await this.stat(t);if(r.isFile)return r.mode}catch{}return rn}async appendFile(t,n,r){U(t,"append"),this.assertWritable(`append '${t}'`);let s=z(t),i=dt(r),o=Ht(n,i),a=this.tree.descend(s);if(a.kind==="found"&&a.node.type==="file"){await this.appendToExisting_(s,a.node,o,t);return}if(a.kind==="blocked")throw new x("ENOENT",`no such file or directory, append '${t}'`);if(a.kind==="notdir")throw new x("ENOTDIR",`not a directory, append '${t}'`);let l;try{l=await this.readFileBuffer(s)}catch(f){if(!ft(f,"ENOENT"))throw f;l=new Uint8Array(0)}let c=await this.inheritedMode(s),u=this.tree.descend(s);if(u.kind==="found"&&u.node.type==="file"){await this.appendToExisting_(s,u.node,o,t);return}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[o],mode:c,mtime:new Date})}async appendToExisting_(t,n,r,s){if(n.metacopy){let i=await this.readLowerFileBytes(t,s,new Set),o=this.tree.descend(t);if(o.kind==="found"&&o.node.type==="file"&&!o.node.metacopy){this.tree.appendChunk(o.node,r),o.node.mtime=new Date;return}this.tree.attach(t,{type:"file",content:i,appendChunks:[r],mode:n.mode,mtime:new Date});return}this.tree.appendChunk(n,r),n.mtime=new Date}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,n=new Set){U(t,"stat");let r=z(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, stat '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, stat '${t}'`);if(s.kind==="found"){let o=s.node;if(o.type==="whiteout")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(o.type==="symlink"){let a=this.resolveSymlink(r,o.target);return this.stat(a,n)}return this.memoryEntryStat(o)}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new x("ENOENT",`no such file or directory, stat '${t}'`);try{let o=await Nt(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, stat '${t}'`);let a=await Ee.promises.readlink(i),l=this.realTargetToVirtual(a),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime,dev:o.dev,ino:o.ino}}catch(o){if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){U(t,"lstat");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, lstat '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, lstat '${t}'`);try{let i=await Nt(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}memoryEntryStat(t){if(t.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:t.mode,size:t.target.length,mtime:t.mtime};let n=0;return t.type==="file"&&(n=t.metacopy?t.lowerSize??0:$d(t)),{isFile:t.type==="file",isDirectory:t.type==="directory",isSymbolicLink:!1,mode:t.mode,size:n,mtime:t.mtime,identity:this.identityFor(t)}}resolveSymlink(t,n){return Qn(t,n)}realTargetToVirtual(t){let n=vd(t,this.canonicalRoot);if(n.withinRoot){if(!Fe.isAbsolute(t))return t;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(t,n){U(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=z(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new x("EEXIST",`file already exists, mkdir '${t}'`);return}let i=Zn(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.tree.ensureDirs(r,o=>this.lowerChildren(o))}async readdirCore(t,n){let r=new Map,s=new Set,i=this.tree.descend(n);if(i.kind==="blocked")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.kind==="notdir")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);let o;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(l.type!=="directory")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);o=l;for(let[c,u]of l.children){if(u.type==="whiteout"){s.add(c);continue}r.set(c,{name:c,isFile:u.type==="file",isDirectory:u.type==="directory",isSymbolicLink:u.type==="symlink"})}}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await Nt(a)).isSymbolicLink()){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);return r}let l=await Ee.promises.readdir(a,{withFileTypes:!0});for(let c of l)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,t,"scandir")}return r}async resolveForReaddir(t,n=!1){let r=z(t),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let c=l.node;if(c.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new x("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,c.target)}if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let a=this.resolveRealPath_(this.toRealPath(r));if(!a)return{normalized:r,outsideOverlay:!0};try{if((await Nt(a)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let c=await Ee.promises.readlink(a),u=this.realTargetToVirtual(c),f=this.resolveSymlink(r,u);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,n){U(t,"rm"),this.assertWritable(`rm '${t}'`);let r=z(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}let i=!1;try{(await this.stat(r)).isDirectory&&(i=(await this.readdir(r)).length>0)}catch{}if(i&&!n?.recursive)throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.existsOnRealFs(r)?this.tree.putWhiteout(r):this.tree.detach(r)}existsOnRealFs(t){let n=this.toRealPath(t),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return Ga(r),!0}catch{return!1}}async cp(t,n,r){U(t,"cp"),U(n,"cp"),this.assertWritable(`cp '${n}'`);let s=z(t),i=z(n);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, cp '${t}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new x("EISDIR",`is a directory, cp '${t}'`);if(qt(s,i))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,n){this.assertWritable(`mv '${n}'`),await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return sn(t,n)}getAllPaths(){let t=new Set;for(let{path:n,node:r}of this.tree.preOrder())r.type!=="whiteout"&&t.add(n);return this.scanRealFs(this.mountPoint,t),Array.from(t)}scanRealFs(t,n){if(this.lowerHidden(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let s=Ee.readdirSync(r);for(let i of s){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.lowerHidden(o))continue;n.add(o);let a=Fe.join(r,i);Ga(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}lowerHidden(t){let n=this.tree.descend(t);switch(n.kind){case"blocked":case"notdir":return!0;case"found":return n.node.type!=="directory";default:return!1}}entryAt(t){let n=this.tree.descend(t);if(n.kind==="found"&&n.node.type!=="whiteout")return n.node}async chmod(t,n){U(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=z(t);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, chmod '${t}'`);let i=this.entryAt(r);if(i){i.mode=n,this.tree.touch(i);return}let o=await this.stat(r);this.attachMetacopyShadow(r,o,n,o.isFile?o.mtime:new Date)}attachMetacopyShadow(t,n,r,s){this.ensureParentDirs(t),n.isFile?this.tree.attach(t,{type:"file",content:new Uint8Array(0),metacopy:!0,lowerSize:n.size,mode:r,mtime:s}):n.isDirectory&&this.tree.attach(t,{type:"directory",children:new Map,mode:r,mtime:s})}async symlink(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=z(n);if(await this.existsInOverlay(r))throw new x("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:t,mode:es,mtime:new Date})}async link(t,n){U(t,"link"),U(n,"link"),this.assertWritable(`link '${n}'`);let r=z(t),s=z(n);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new x("EPERM",`operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new x("EEXIST",`file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,mode:o.mode,mtime:new Date,identity:o.identity??`overlay:${this.nextMemoryIdentity++}`})}async readlink(t){U(t,"readlink");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, readlink '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.type!=="symlink")throw new x("EINVAL",`invalid argument, readlink '${t}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, readlink '${t}'`);try{let i=await Ee.promises.readlink(s);if(!Fe.isAbsolute(i)){let o=Fe.resolve(Fe.dirname(s),i),a;try{a=Ee.realpathSync(o)}catch{a=o}if(!Le(a,this.canonicalRoot))return Fe.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){U(t,"realpath");let n=z(t),r=new Set,s=l=>{let c=this.tree.descend(l);if(c.kind==="blocked"||c.kind==="found"&&c.node.type==="whiteout")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return c.kind==="found"?c.node:void 0},i=async l=>{let c=l==="/"?[]:l.slice(1).split("/"),u="";for(let f of c){if(u=`${u}/${f}`,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);let d=s(u),h=0,p=gr;for(;d&&d.type==="symlink"&&h<p;){if(r.add(u),u=this.resolveSymlink(u,d.target),h++,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);d=s(u)}if(h>=p)throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);if(!d){let m=this.toRealPath(u),E=this.resolveRealPath_(m);if(E)try{if((await Nt(E)).isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, realpath '${t}'`);let g=await Ee.promises.readlink(E),y=this.realTargetToVirtual(g);return r.add(u),u=this.resolveSymlink(u,y),i(u)}}catch(S){if(S.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(S,t,"realpath")}else if(!this.allowSymlinks){let S=this.resolveRealPathParent_(m);if(S)try{if((await Nt(S)).isSymbolicLink())throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}catch(g){if(ft(g,"ENOENT")||ft(g,"ELOOP"))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(g,t,"realpath")}}}}return u||"/"},o=await i(n);if(!await this.existsInOverlay(o))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return o}async utimes(t,n,r){U(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=z(t);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, utimes '${t}'`);let o=this.entryAt(s);if(o){o.mtime=r,this.tree.touch(o);return}let a=await this.stat(s);this.attachMetacopyShadow(s,a,a.mode,r)}};var xi=class{bash;overlays;constructor(t={}){let{home:n,project:r,cwd:s,env:i,...o}=t,a=new Map,l=[],c=n?dr(n):null,u=r?dr(r):null,f=c&&u&&(()=>{let p=Me.relative(c,u);return p!==".."&&!p.startsWith(`..${Me.sep}`)&&!Me.isAbsolute(p)})();if(c){let p=new Rt({root:c,mountPoint:"/"});a.set("/home/user",{root:c,fs:p}),l.push({mountPoint:"/home/user",filesystem:p})}let d="/home/user";if(u)if(f&&c){let p=Me.relative(c,u);d=p?`/home/user/${p.split(Me.sep).join("/")}`:"/home/user"}else{let p=new Rt({root:u,mountPoint:"/"});a.set("/project",{root:u,fs:p}),l.push({mountPoint:"/project",filesystem:p}),d="/project"}let h=new Pt({base:new ze,mounts:l});this.overlays=a,this.bash=new Un({...o,env:{HOME:"/home/user",...i},cwd:s??d,fs:h})}analyzeCommands(t){return this.bash.analyzeCommands(t)}exec(t){return this.bash.exec(t)}diff(){let t=[],n=[];for(let{root:r,fs:s}of this.overlays.values()){let i=s.diff();for(let{path:o,...a}of i.writes)t.push({...a,path:Me.join(r,o)});for(let o=0;o<i.deletions.length;o++)n.push({path:Me.join(r,i.deletions[o]),changedAt:i.deletionChangedAt?.[o]})}return t.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),n.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),{writes:t,deletions:n.map(r=>r.path),...n.length>0&&{deletionChangedAt:n.map(r=>r.changedAt??0)}}}async applyChanges(t=this.diff()){let n=new Map,r=s=>{let i=this.findOverlay(s);if(!i)return;let o=`/${Me.relative(i.root,s).split(Me.sep).join("/")}`;if(o==="/")return;let a=n.get(i.fs);a?a.push(o):n.set(i.fs,[o])};try{for(let s of t.deletions)ja(s),r(s);for(let s of t.writes)qa(s.path,s),r(s.path)}finally{for(let[s,i]of n)s.drop(i)}}findOverlayEntry(t){let n=null;for(let[r,s]of this.overlays)(t===s.root||t.startsWith(s.root+Me.sep))&&(!n||s.root.length>n.root.length)&&(n={mountPoint:r,root:s.root,fs:s.fs});return n}findOverlay(t){return this.findOverlayEntry(t)}resolveRealPath(t){let n=this.findOverlayEntry(t);if(!n)return null;let r=`/${Me.relative(n.root,t).split(Me.sep).join("/")}`;return{mountPoint:n.mountPoint,overlay:n.fs,path:r}}toRealPath(t){let n=t.startsWith("/")?t:`/${t}`,r=null;for(let[s,i]of this.overlays)(n===s||n.startsWith(`${s}/`))&&(!r||s.length>r.mountPoint.length)&&(r={mountPoint:s,root:i.root});return r?Me.join(r.root,n.slice(r.mountPoint.length)):null}async sync(){for(let{fs:t}of this.overlays.values())await t.sync()}reset(){for(let{fs:t}of this.overlays.values())t.reset()}};function Ky(e={}){return new xi(e)}import{randomBytes as Xy}from"node:crypto";import*as L from"node:fs";import*as Z from"node:path";var Yy=["EACCES","escaping sandbox","EFBIG","ENOTSUP"],Pi=class e{static activeMutationRoots=new Set;static pendingMutations=[];root;canonicalRoot;maxFileReadSize;maxCopyOnWriteSize;maxCopySize;allowSymlinks;constructor(t){this.root=Z.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxCopyOnWriteSize=t.maxCopyOnWriteSize??104857600,this.maxCopySize=t.maxCopySize??0,this.allowSymlinks=t.allowSymlinks??!1,bi(this.root,"ReadWriteFs"),this.canonicalRoot=L.realpathSync(this.root)}resolveAndValidate(t,n){let r=this.allowSymlinks?jn(t,this.canonicalRoot):Ei(t,this.root,this.canonicalRoot);if(r===null)throw new x("EACCES",`permission denied, '${n}' resolves outside sandbox`);return r}validateParent(t,n){let r=Z.dirname(t),s=this.resolveAndValidate(r,n);return Z.join(s,Z.basename(t))}toRealPath(t){let n=z(t),r=Z.join(this.root,n);return Z.resolve(r)}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t){U(t,"open");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=this.allowSymlinks?L.constants.O_RDONLY:L.constants.O_RDONLY|L.constants.O_NOFOLLOW,i=await L.promises.open(r,s);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.code==="EISDIR")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(i.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(s,t,"open")}}async writeFile(t,n,r){await this.withFilesystemMutation(()=>this.writeFileUnlocked(t,n,r))}async writeFileUnlocked(t,n,r){U(t,"write");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t),o=dt(r),a=Ht(n,o),l=Z.dirname(i);try{await L.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:L.constants.O_NOFOLLOW,u=null;try{let f=await L.promises.lstat(i);if(!f.isFile()&&!f.isDirectory())throw new x("EACCES",`cannot write special file '${t}'`);let d=await L.promises.open(i,L.constants.O_WRONLY|L.constants.O_NONBLOCK|c);try{if(u=await d.stat(),!u.isFile())throw new x("EACCES",`cannot write special file '${t}'`);if(u.nlink<=1){await d.truncate(0),await d.writeFile(a);return}}finally{await d.close()}}catch(f){if(f.code!=="ENOENT")throw f}await this.replaceFile(i,a,u)}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"write")}}async appendFile(t,n,r){await this.withFilesystemMutation(()=>this.appendFileUnlocked(t,n,r))}async appendFileUnlocked(t,n,r){U(t,"append");let s=this.toRealPath(t),i=dt(r),o=Ht(n,i),a=this.resolveAndValidate(s,t),l=Z.dirname(a);try{await L.promises.mkdir(l,{recursive:!0}),a=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:L.constants.O_NOFOLLOW,u=null;try{let d=await L.promises.lstat(a);if(!d.isFile()&&!d.isDirectory())throw new x("EACCES",`cannot append special file '${t}'`);let h=await L.promises.open(a,L.constants.O_WRONLY|L.constants.O_APPEND|L.constants.O_NONBLOCK|c);try{if(u=await h.stat(),!u.isFile())throw new x("EACCES",`cannot append special file '${t}'`);if(u.nlink<=1){await h.writeFile(o);return}}finally{await h.close()}}catch(d){if(d.code!=="ENOENT")throw d}if(!u){await this.replaceFile(a,o,null);return}this.assertCopyOnWriteSize(u.size,"append",t);let f=await this.openCopySource(a);try{let d=await f.stat();if(!d.isFile()||d.dev!==u.dev||d.ino!==u.ino)throw new x("EACCES",`file identity changed, append '${t}'`);await this.replaceFile(a,o,d,{handle:f,size:u.size})}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"append")}}async withFilesystemMutation(t){return new Promise((n,r)=>{e.pendingMutations.push({root:this.canonicalRoot,start:()=>{e.activeMutationRoots.add(this.canonicalRoot),t().then(n,r).finally(()=>{e.activeMutationRoots.delete(this.canonicalRoot),e.drainMutationQueue()})}}),e.drainMutationQueue()})}static drainMutationQueue(){for(let t=0;t<e.pendingMutations.length;){let n=e.pendingMutations[t];if([...e.activeMutationRoots].some(s=>Le(n.root,s)||Le(s,n.root))){t++;continue}e.pendingMutations.splice(t,1),n.start()}}assertCopyOnWriteSize(t,n,r){if(this.maxCopyOnWriteSize>0&&t>this.maxCopyOnWriteSize)throw new x("EFBIG",`file too large for copy-on-write ${n} '${r}' (${t} bytes, max ${this.maxCopyOnWriteSize})`)}assertCopySize(t,n){if(this.maxCopySize>0&&t.size>this.maxCopySize)throw new x("EFBIG",`file too large to copy '${n}' (${t.size} bytes, max ${this.maxCopySize})`)}randomTransactionToken(){return Xy(16).toString("hex")}async openCopySource(t){let n=this.allowSymlinks?0:L.constants.O_NOFOLLOW,r=L.constants.O_RDONLY|L.constants.O_NONBLOCK|n,s=L.constants.O_NOATIME;if(process.platform!=="linux"||s===void 0)return L.promises.open(t,r);try{return await L.promises.open(t,r|s)}catch(i){if(i.code!=="EPERM")throw i;return L.promises.open(t,r)}}async replaceFile(t,n,r,s,i,o=!1){let a=Z.dirname(t),l="",c=null,u=r===null?438:384;for(let p=0;p<16;p++){l=Z.join(a,`.just-bash-write-${this.randomTransactionToken()}`);try{c=await L.promises.open(l,L.constants.O_WRONLY|L.constants.O_CREAT|L.constants.O_EXCL,u);break}catch(m){if(m.code!=="EEXIST")throw m}}if(!c)throw new x("EEXIST",`replacement write '${t}'`);let f=c,d=await f.stat(),h=!1;try{try{let m=0,E=async S=>{let g=0;for(;g<S.byteLength;){let{bytesWritten:y}=await f.write(S,g,S.byteLength-g,m+g);if(y===0)throw new x("EIO","replacement write made no progress");g+=y}m+=g};if(s){let S=Buffer.allocUnsafe(65536),g=0,y=s.size;for(;y>0;){let b=Math.min(S.length,y),{bytesRead:A}=await s.handle.read(S,0,b,g);if(A===0)break;await E(S.subarray(0,A)),g+=A,y-=A}}if(await E(n),r!==null&&await f.chmod(r.mode&(o?4095:511)),i)await f.utimes(i.atime,i.mtime);else if(r!==null){let S=await f.stat();await f.utimes(r.atime,S.mtime)}}finally{await f.close(),c=null}let p=await L.promises.lstat(l);if(!p.isFile()||p.dev!==d.dev||p.ino!==d.ino)throw new x("EACCES","replacement staging entry changed");await L.promises.rename(l,t),h=!0}finally{c&&await c.close().catch(()=>{}),h||await L.promises.rm(l,{force:!0}).catch(()=>{})}}async exists(t){if(t.includes("\0"))return!1;let n=this.toRealPath(t);try{let r=this.resolveAndValidate(n,t);return await L.promises.access(r),!0}catch{return!1}}async stat(t){U(t,"stat");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=await L.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(s,t,"stat")}}async lstat(t){U(t,"lstat");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await L.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(s,t,"lstat")}}async mkdir(t,n){await this.withFilesystemMutation(()=>this.mkdirUnlocked(t,n))}async mkdirUnlocked(t,n){U(t,"mkdir");let r=this.toRealPath(t),s=r===this.root?this.resolveAndValidate(r,t):this.validateParent(r,t);try{await L.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new x("EEXIST",`file already exists, mkdir '${t}'`);if(o.code==="ENOENT")throw new x("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){U(t,"scandir");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{if(!this.allowSymlinks&&(await L.promises.lstat(r)).isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return(await L.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.code==="ENOTDIR")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);this.sanitizeError(s,t,"scandir")}}async rm(t,n){await this.withFilesystemMutation(()=>this.rmUnlocked(t,n))}async rmUnlocked(t,n){U(t,"rm");let r=this.toRealPath(t),s=this.validateParent(r,t);try{let i=await L.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);await L.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}if(o.code==="ENOTEMPTY")throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,n,r){await this.withFilesystemMutation(()=>this.cpUnlocked(t,n,r))}async cpUnlocked(t,n,r){U(t,"cp"),U(n,"cp");let s=this.toRealPath(t),i=this.toRealPath(n),o=this.validateParent(s,t),a=this.resolveAndValidate(i,n),l;try{l=await L.promises.lstat(o)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}if(l.isDirectory()&&Le(a,o))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);if(!l.isDirectory())try{let c=this.validateParent(i,n),u=await L.promises.lstat(c);if(l.dev===u.dev&&l.ino===u.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}if(l.isFile())try{let c=await L.promises.stat(a);if(l.dev===c.dev&&l.ino===c.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}try{await this.preflightCopyTree(o,t)}catch(c){this.sanitizeError(c,t,"cp")}if(l.isFile()||l.isSymbolicLink())try{await L.promises.mkdir(Z.dirname(a),{recursive:!0}),this.resolveAndValidate(i,n)}catch(c){this.sanitizeError(c,n,"cp")}try{await this.copyTreeEntry(o,i,t,n,r?.recursive??!1)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);if(u.code==="EISDIR")throw new x("EISDIR",`is a directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}}async copyTreeEntry(t,n,r,s,i){let o=await L.promises.lstat(t);if(o.isFile()){this.assertCopySize(o,r);let a=this.resolveAndValidate(n,s),l=await this.assertCopyDestinationWritable(a,s),c=await this.openCopySource(t);try{let u=await c.stat();if(!u.isFile()||u.dev!==o.dev||u.ino!==o.ino)throw new x("EACCES",`file identity changed, cp '${r}'`);await this.replaceFile(a,new Uint8Array(0),l??o,{handle:c,size:o.size})}finally{await c.close()}return}if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${r}' contains a symlink`);let a=await L.promises.readlink(t),l=Z.isAbsolute(a)?await this.toVirtualAbsoluteSymlinkTarget(a,r):a;await this.replaceSymlink(n,s,l);return}if(o.isDirectory()){if(!i)throw new x("EISDIR",`is a directory, cp '${r}'`);let a=this.resolveAndValidate(n,s);await L.promises.mkdir(a,{recursive:!0}),a=this.resolveAndValidate(n,s);for(let l of await L.promises.readdir(t))await this.copyTreeEntry(Z.join(t,l),Z.join(n,l),Z.join(r,l),Z.join(s,l),!0);await L.promises.chmod(a,o.mode&4095);return}throw new x("EINVAL",`unsupported file type, cp '${r}'`)}async assertCopyDestinationWritable(t,n){let r;try{r=await L.promises.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}if(!r.isFile()){if(r.isDirectory())return r;throw new x("EACCES",`cannot copy over special file '${n}'`)}let s=this.allowSymlinks?0:L.constants.O_NOFOLLOW,i=await L.promises.open(t,L.constants.O_WRONLY|L.constants.O_NONBLOCK|s);try{let o=await i.stat();if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)throw new x("EACCES",`destination changed, cp '${n}'`)}finally{await i.close()}return r}async replaceSymlink(t,n,r){let s=this.validateParent(t,n),i=Z.dirname(z(n)),o="",a="",l="",c=null;for(let f=0;f<16;f++){let d=`.just-bash-copy-link-${this.randomTransactionToken()}`;o=i==="/"?`/${d}`:`${i}/${d}`,a=this.toRealPath(o);try{await this.symlinkUnlocked(r,o),l=this.validateParent(a,o),c=await L.promises.lstat(l);break}catch(h){if(!ft(h,"EEXIST"))throw h}}if(!c)throw new x("EEXIST",`replacement symlink '${n}'`);let u=!1;try{let f=await L.promises.lstat(l);if(!f.isSymbolicLink()||f.dev!==c.dev||f.ino!==c.ino)throw new x("EACCES","replacement symlink entry changed");await L.promises.rename(l,s),u=!0}finally{!u&&l&&await L.promises.rm(l,{force:!0}).catch(()=>{})}}async toVirtualAbsoluteSymlinkTarget(t,n){let r=Z.resolve(t),s=await L.promises.realpath(r),i=await L.promises.realpath(Z.dirname(r)),o=Z.join(i,Z.basename(r));if(!Le(s,this.canonicalRoot)||!Le(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return Nn(o.slice(this.canonicalRoot.length))||"/"}async preflightCopyTree(t,n,r=new Set){let s=await L.promises.lstat(t),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new x("ELOOP",`cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${n}' contains a symlink`);let o=await L.promises.realpath(t);if(!Le(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let o=await L.promises.readdir(t);for(let a of o)await this.preflightCopyTree(Z.join(t,a),Z.join(n,a),r)}finally{r.delete(i)}}}async mv(t,n){await this.withFilesystemMutation(()=>this.mvUnlocked(t,n))}async mvUnlocked(t,n){U(t,"mv"),U(n,"mv");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.validateParent(r,t),o=this.validateParent(s,n),a;try{a=await L.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);this.sanitizeError(c,t,"mv")}if(a.isDirectory()&&this.isSameOrDescendantIdentity(i,o))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);try{if(a.isSymbolicLink()){let c=await L.promises.readlink(i),u=Z.resolve(Z.dirname(o),c),f=await L.promises.realpath(u).catch(()=>u);if(!Le(f,this.canonicalRoot))throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(ft(u,"EACCES"))throw c}let l=Z.dirname(o);try{await L.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await L.promises.rename(i,o)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(t,n);return}this.sanitizeError(c,t,"mv")}try{if(L.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await L.promises.rename(o,i),new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(ft(c,"EACCES"))throw c;await L.promises.rename(o,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(t,n){let r=t,s=n;try{r=L.realpathSync(t)}catch{}try{s=L.realpathSync(n)}catch{try{let i=L.realpathSync(Z.dirname(n));s=Z.join(i,Z.basename(n))}catch{}}return Le(s,r)}async uniqueTransactionPath(t,n){let r=Z.posix.dirname(t);for(let s=0;s<16;s++){let i=Z.posix.join(r,`.just-bash-mv-${n}-${this.randomTransactionToken()}`);if(!await this.exists(i))return i}throw new x("EEXIST",`mv '${t}'`)}async moveAcrossDevices(t,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(t,"source"),o=this.validateParent(this.toRealPath(r),r),a=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(t),t),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,h=!1,p=async()=>{h&&await L.promises.rename(c,l).catch(()=>{}),d&&await L.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await L.promises.rename(a,u).catch(()=>{}),await L.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cpUnlocked(t,r,{recursive:!0}),(await L.promises.lstat(o)).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`);try{await L.promises.rename(u,a),f=!0}catch(E){if(E.code!=="ENOENT")throw E}await L.promises.rename(o,u),d=!0,await L.promises.rename(l,c),h=!0,await L.promises.rm(c,{recursive:!0,force:!1}),h=!1,f&&await L.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await p(),this.sanitizeError(m,t,"mv")}}resolvePath(t,n){return sn(t,n)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,n,r){Si(t,n,r,Yy)}findEscapingSymlinks(t){let n=[],r=L.readdirSync(t);for(let s of r){let i=Z.join(t,s),o=L.lstatSync(i);if(o.isSymbolicLink()){let a=L.readlinkSync(i),l=Z.resolve(t,a),c;try{c=L.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}Le(c,this.canonicalRoot)||n.push(i)}else o.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(t,n){let r=this.toRealPath(t),s;try{s=this.resolveAndValidate(r,t)}catch{return}try{let i=L.readdirSync(s);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`;n.push(a);let l=Z.join(s,o);L.lstatSync(l).isDirectory()&&this.scanDir(a,n)}}catch{}}async chmod(t,n){await this.withFilesystemMutation(()=>this.chmodUnlocked(t,n))}async chmodUnlocked(t,n){U(t,"chmod");let r=this.toRealPath(t),s=this.resolveAndValidate(r,t);try{let i=await L.promises.lstat(s);if(!i.isFile()){if(!i.isDirectory()&&i.nlink>1)throw new x("EACCES",`cannot chmod multiply-linked special file '${t}'`);await L.promises.chmod(s,n);return}if(i.nlink<=1){await L.promises.chmod(s,n);return}this.assertCopyOnWriteSize(i.size,"chmod",t);let o=await this.openCopySource(s);try{let a=await o.stat();if(!a.isFile())throw new x("EACCES",`file type changed, chmod '${t}'`);await this.replaceFile(s,new Uint8Array(0),{mode:n,atime:a.atime,mtime:a.mtime},{handle:o,size:a.size},{atime:a.atime,mtime:a.mtime},!0)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, chmod '${t}'`);if(o.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,"chmod")}}async symlink(t,n){await this.withFilesystemMutation(()=>this.symlinkUnlocked(t,n))}async symlinkUnlocked(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=z(n),o=z(Z.dirname(i)),a=t.startsWith("/")?z(t):z(o==="/"?`/${t}`:`${o}/${t}`),l=Z.join(this.canonicalRoot,a),c=Z.dirname(s),u=t.startsWith("/")?l:Z.relative(c,l)||".";try{await L.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new x("EEXIST",`file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(t,n){await this.withFilesystemMutation(()=>this.linkUnlocked(t,n))}async linkUnlocked(t,n){U(t,"link"),U(n,"link");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.resolveAndValidate(r,t),o=s===this.root?this.resolveAndValidate(s,n):this.validateParent(s,n);try{await L.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new x("ENOENT",`no such file or directory, link '${t}'`);if(l.code==="EEXIST")throw new x("EEXIST",`file already exists, link '${n}'`);if(l.code==="EPERM")throw new x("EPERM",`operation not permitted, link '${t}'`);this.sanitizeError(a,t,"link")}}async readlink(t){U(t,"readlink");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await L.promises.readlink(r),i=z(t),o=Z.dirname(i),a=Z.isAbsolute(s)?s:Z.resolve(Z.dirname(r),s),l=await L.promises.realpath(a).catch(()=>a);if(Le(l,this.canonicalRoot)){let c=Nn(l.slice(this.canonicalRoot.length))||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:Nn(Z.relative(o,c))}return Z.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(s,t,"readlink")}}async realpath(t){U(t,"realpath");let n=this.toRealPath(t);try{this.resolveAndValidate(n,t)}catch{throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}let r;try{r=await L.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);if(i.code==="ELOOP")throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(s,t,"realpath")}if(Le(r,this.canonicalRoot))return Nn(r.slice(this.canonicalRoot.length))||"/";throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}async utimes(t,n,r){await this.withFilesystemMutation(()=>this.utimesUnlocked(t,n,r))}async utimesUnlocked(t,n,r){U(t,"utimes");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t);try{let o=await L.promises.lstat(i);if(!o.isFile()){if(!o.isDirectory()&&o.nlink>1)throw new x("EACCES",`cannot change times on multiply-linked special file '${t}'`);await L.promises.utimes(i,n,r);return}if(o.nlink<=1){await L.promises.utimes(i,n,r);return}this.assertCopyOnWriteSize(o.size,"utimes",t);let a=await this.openCopySource(i);try{let l=await a.stat();if(!l.isFile())throw new x("EACCES",`file type changed, utimes '${t}'`);await this.replaceFile(i,new Uint8Array(0),l,{handle:a,size:l.size},{atime:n,mtime:r},!0)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new x("ENOENT",`no such file or directory, utimes '${t}'`);if(a.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(o,t,"utimes")}}};import $n from"node:path";function Jy(e){if(e.mounts.length===0)throw new x("EINVAL","createVfsTemplate needs at least one mount");let t=e.mounts.map(({at:c,root:u})=>{let f=dr(u);return{at:(c.startsWith("/")?c:`/${c}`).replace(/\/+$/,"")||"/",root:f}}),n=new Set;for(let{at:c}of t){if(n.has(c))throw new x("EINVAL",`duplicate mount point '${c}' in createVfsTemplate`);if(n.add(c),c==="/")throw new x("EINVAL","mount point '/' would swallow the shared scratch space");for(let u of n)if(u!==c&&c.startsWith(`${u}/`))throw new x("EINVAL",`mount point '${c}' is nested inside '${u}'`)}let r=[];for(let{root:c}of t){for(let u of r){let f=$n.sep;if(c!==u&&(c.startsWith(u+f)||u.startsWith(c+f)))throw new x("EINVAL",`nested template roots share one real subtree: '${c}' and '${u}'`)}r.push(c)}let s=new ze,i=()=>{let c=new Pt({base:s});for(let{at:u,root:f}of t)c.mount(u,new Rt({root:f,mountPoint:"/",...e.maxMemoryBytes!==void 0&&{maxMemoryBytes:e.maxMemoryBytes}}));return c};return{fork:()=>i(),merge:async c=>{let u=[],f=0;for(let h of c){let p=h instanceof Pt?h.diff({space:"vfs"}):h;for(let m of p.writes){let E=m.changedAt??0;u.push({kind:"write",changedAt:E,order:f++,write:m})}for(let m=0;m<p.deletions.length;m++){let E=p.deletionChangedAt?.[m]??0;u.push({kind:"delete",changedAt:E,order:f++,path:p.deletions[m]})}}u.sort((h,p)=>h.changedAt!==p.changedAt?h.changedAt-p.changedAt:h.order-p.order);let d=i();for(let h of u){if(h.kind==="write"&&h.write.metadataOnly&&h.write.mode===void 0&&h.write.mtime===void 0)continue;let p=!1;try{if(h.kind==="delete")await d.rm(h.path,{recursive:!0});else{let m=h.write;m.metadataOnly?(m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="directory"?(await d.mkdir(m.path,{recursive:!0}),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="symlink"?await d.symlink(new TextDecoder().decode(m.content),m.path):(await d.writeFile(m.path,m.content),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime))}p=!0}catch{}p?d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt):d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt,"ancestors")}return d},apply:c=>{let u={writes:c.writes.map(f=>({...f,path:$n.normalize(f.path)})),deletions:c.deletions.map(f=>$n.normalize(f)),...c.deletionChangedAt&&{deletionChangedAt:c.deletionChangedAt}};for(let f of u.writes)if(f.nodeType==="symlink")throw new x("EINVAL",`change-set contains a symlink write: '${f.path}'`);for(let f of[...u.deletions,...u.writes.map(d=>d.path)]){if(!t.some(({root:m})=>f===m||f.startsWith(m+$n.sep)))throw new x("EINVAL",`change-set entry outside every template root: '${f}'`);if(u.deletions.includes(f)&&t.some(({root:E})=>f===E))throw new x("EINVAL",`change-set deletes a registered root: '${f}'`);let h=eg(f);if(!t.some(({root:m})=>h===m||h.startsWith(m+$n.sep)))throw new x("EINVAL",`change-set entry escapes its root through a symlink: '${f}'`)}wi(u)}}}function eg(e){let t=e,n=[];for(;;)try{let r=dr(t);return n.length===0?r:$n.join(r,...n.reverse())}catch{let r=$n.dirname(t);if(r===t)return e;n.push($n.basename(t)),t=r}}var hr=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,n,r,s,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=Hr(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(Zr(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 n=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=n.exitCode,n}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 $i=class e{bashEnv;timeoutMs;constructor(t,n){this.bashEnv=t,this.timeoutMs=n}static async create(t){let n=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Rt({root:t.overlayRoot})}let r=new Un({env:t?.env,cwd:t?.cwd,fs:n,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,n,r){let s,i,o,a,l=!1,c,u;if(typeof t=="object"){let m=t,E=[m.cmd,...m.args??[]];s=Di(E),i=m.cwd,o=m.env,a=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=Di([t,...n]),a=m?.signal}else{s=t;let m=n;i=m?.cwd,o=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new hr(this.bashEnv,s,f,o,d,a,this.timeoutMs);if(l)return h;let p=await h.wait();if(c){let m=await h.stdout();m&&c.write(m)}if(u){let m=await h.stderr();m&&u.write(m)}return p}async writeFiles(t){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(t)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let o=this.bashEnv.fs.resolvePath(n,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(t,n){let r=await this.bashEnv.readFile(t);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Ci=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 n=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(n),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(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)s.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:n,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(s)})}return t.sort((n,r)=>r.count-n.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 Cd(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
810
+ `)}var Gy=new TextDecoder("utf-8",{fatal:!0});function bd(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>255)return e;s>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);try{return Gy.decode(n)}catch{return e}}function Hy(e,t,n,r,s,i){if(e===void 0)return;let o=t==="bytes"?e.length:W(e);if(o>n||o>r)throw new C(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),t==="bytes"?e:Yt(e)}import*as ke from"node:fs";import*as gi from"node:path";function dr(e){return ke.realpathSync(e)}function ja(e){ke.rmSync(e,{recursive:!0,force:!0})}function Ad(e,t){let n;try{n=ke.lstatSync(e)}catch{return!1}return t?!n.isDirectory():n.isDirectory()}function Sd(e,t){Ad(e,t)&&ke.rmSync(e,{recursive:!0,force:!0})}function qa(e,t){if(t.nodeType==="directory"){Sd(e,!0),ke.mkdirSync(e,{recursive:!0}),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime);return}if(ke.mkdirSync(gi.dirname(e),{recursive:!0}),t.nodeType==="symlink"){ke.rmSync(e,{force:!0,recursive:!0}),ke.symlinkSync(new TextDecoder().decode(t.content),e);return}if(t.metadataOnly&&Ad(e,!1))throw new x("EINVAL",`metadata-only entry over a different on-disk type: '${e}'`);t.metadataOnly||(Sd(e,!1),ke.writeFileSync(e,t.content)),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime)}function wi(e){for(let r of[...e.deletions,...e.writes.map(s=>s.path)])if(gi.resolve(r)!==r)throw new x("EINVAL",`change-set path is not normalized: '${r}'`);let t=[...e.deletions].sort((r,s)=>s.length-r.length||(r<s?-1:r>s?1:0));for(let r of t)ja(r);let n=[...e.writes].sort((r,s)=>r.path.length-s.path.length||(r.path<s.path?-1:r.path>s.path?1:0));for(let{path:r,...s}of n)qa(r,s)}import*as Ee from"node:fs";import*as Fe from"node:path";import*as Ze from"node:fs";import*as Ne from"node:path";function Le(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?Ne.win32:Ne.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function jn(e,t){try{let n=Ze.realpathSync(e);return Le(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=Ne.dirname(e);if(r===e)return null;let s=jn(r,t);if(s===null)return null;try{if(Ze.lstatSync(e).isSymbolicLink()){let o=Ze.readlinkSync(e),a=Ne.isAbsolute(o)?o:Ne.resolve(Ne.dirname(e),o),l=jn(a,t);return l===null?null:l}}catch{}return Ne.join(s,Ne.basename(e))}return null}}function Ei(e,t,n){let r=jn(e,n);if(r===null)return null;let s=Ne.resolve(e),i=s.slice(t.length),o=r.slice(n.length);if(i!==o)return null;try{if(Ze.lstatSync(s).isSymbolicLink())return null}catch{}return r}function bi(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 vd(e,t){if(!Ne.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=Ze.realpathSync(e)}catch{n=Ne.resolve(e)}return Le(n,t)?{withinRoot:!0,relativePath:Nn(n.slice(t.length))||"/"}:{withinRoot:!1,safeName:Ne.basename(e)}}function Si(e,t,n,r){let s=e;if(s.path===void 0){for(let o of r)if(s.message?.includes(o))throw e}let i=s.code||"EIO";throw new x(i,`${n} '${t}'`)}async function Nt(e){return kd(await Ze.promises.lstat(e))}function Ga(e){return kd(Ze.lstatSync(e))}function kd(e){return process.platform==="win32"&&e.isDirectory()&&(e.mode=e.mode&-512|493),e}function Ai(e){let t=e.content.byteLength;for(let n of e.appendChunks??[])t+=n.byteLength;return t}function $d(e){return Ai(e)}function ki(e,t){if(!e.appendChunks||e.appendChunks.length===0)return e.content;let n=e.appendChunks.reduce((i,o)=>i+o.byteLength,e.content.byteLength);if(!Number.isSafeInteger(n))throw new x("EFBIG",`file too large, read '${t}'`);let r=new Uint8Array(n);r.set(e.content);let s=e.content.byteLength;for(let i of e.appendChunks)r.set(i,s),s+=i.byteLength;return e.content=r,e.appendChunks=void 0,r}function xd(e){return!e||e.type!=="file"?0:Ai(e)}function qr(){return{type:"directory",children:new Map,changedAt:Date.now(),mode:St,mtime:new Date}}function Gr(e){return e.split("/").filter(Boolean)}var vi=class e{maxMemoryBytes;rootNode=qr();bytes=0;mutationSeq_=0;constructor(t){this.maxMemoryBytes=t}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(t){let n=Gr(t),r=[this.rootNode],s=this.rootNode;for(let i=0;i<n.length;i++){let o=s.children.get(n[i]);if(o===void 0)return{kind:"missing",stack:r,missingAt:i};if(i===n.length-1)return{kind:"found",stack:r,node:o};if(o.type==="whiteout")return{kind:"blocked",stack:r,blockedAt:i};if(o.type!=="directory")return{kind:"notdir",stack:r,notdirAt:i};r.push(o),s=o}return{kind:"found",stack:[],node:this.rootNode}}ensureDirs(t,n){let r=this.rootNode,s="";for(let i of Gr(t)){s=`${s}/${i}`;let o=r.children.get(i);if(o===void 0)o=qr(),r.children.set(i,o);else if(o.type==="whiteout")o=this.resurrectDir(r,i,s,o.changedAt??0,n);else if(o.type!=="directory")throw new x("ENOTDIR",`not a directory, mkdir '${t}'`);r=o}return r}resurrectDir(t,n,r,s,i){let o=qr();t.children.set(n,o);let a=i?.(r);if(a)for(let l of a)o.children.has(l)||o.children.set(l,{type:"whiteout",changedAt:s});return o}attach(t,n){n.changedAt=Date.now();let r=Gr(t);if(r.length===0)throw new x("EINVAL",`cannot attach at root, attach '${t}'`);let s=this.parentDirOf(r,t),i=s.children.get(r[r.length-1]);if(i?.type==="directory"&&n.type!=="directory")throw new x("EISDIR",`cannot replace directory with ${n.type}, attach '${t}'`);if(i!==void 0&&n.type==="directory")throw new x("EEXIST",`cannot replace ${i.type} with directory, attach '${t}'`);let o=xd(i),a=xd(n);this.assertCapacity(a,o),s.children.set(r[r.length-1],n),this.bytes+=a-o}detach(t){let n=Gr(t);if(n.length===0)return;let r=this.descend(t);return r.kind!=="found"?void 0:(r.stack[r.stack.length-1].children.delete(n[n.length-1]),this.bytes-=e.subtreeBytes(r.node),r.node)}putWhiteout(t){let n=Gr(t);if(n.length===0)throw new x("EINVAL",`cannot whiteout the root, rm '${t}'`);let r=this.rootNode;for(let o=0;o<n.length-1;o++)r=this.ensureChildDir(r,n[o],t);let s=n[n.length-1],i=r.children.get(s);i?.type!=="whiteout"&&(this.bytes-=e.subtreeBytes(i),r.children.set(s,{type:"whiteout",changedAt:Date.now()}))}appendChunk(t,n){this.assertCapacity(n.byteLength),t.appendChunks||(t.appendChunks=[]),t.appendChunks.push(n),this.bytes+=n.byteLength,this.touch(t)}touch(t){t.seq=++this.mutationSeq_,t.changedAt=Date.now()}detachIfUnchanged(t,n,r){let s=this.descend(t);return s.kind!=="found"||s.node!==n||n.seq!==r||n.type==="directory"&&n.children.size>0?!1:(this.detach(t),!0)}*preOrder(){let t=[{path:"/",node:this.rootNode}];for(;t.length>0;){let n=t.pop();if(yield n,n.node.type==="directory"){let r=[...n.node.children.entries()];for(let s=r.length-1;s>=0;s--){let[i,o]=r[s];t.push({path:Pd(n.path,i),node:o})}}}}*postOrder(){let t=[],n=[{path:"/",node:this.rootNode}];for(;n.length>0;){let r=n.pop();if(t.push(r),r.node.type==="directory")for(let[s,i]of r.node.children)n.push({path:Pd(r.path,s),node:i})}for(let r=t.length-1;r>=0;r--)yield t[r]}clear(){this.rootNode=qr(),this.bytes=0}static subtreeBytes(t){if(t===void 0)return 0;if(t.type==="file")return Ai(t);if(t.type!=="directory")return 0;let n=0,r=[t];for(;r.length>0;){let s=r.pop();for(let i of s.children.values())i.type==="file"?n+=Ai(i):i.type==="directory"&&r.push(i)}return n}parentDirOf(t,n){let r=this.rootNode;for(let s=0;s<t.length-1;s++){let i=r.children.get(t[s]);if(i?.type!=="directory")throw new x("ENOTDIR",`not a directory, attach '${n}'`);r=i}return r}ensureChildDir(t,n,r){let s=t.children.get(n);if(s===void 0||s.type==="whiteout")s=qr(),t.children.set(n,s);else if(s.type!=="directory")throw new x("ENOTDIR",`not a directory, rm '${r}'`);return s}assertCapacity(t,n=0){if(!Number.isSafeInteger(t)||t<0||t>this.maxMemoryBytes-this.bytes+n)throw new x("ENOSPC",`overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function Pd(e,t){return e==="/"?`/${t}`:`${e}/${t}`}var Zy=["ELOOP","EFBIG","EPERM"],Qy="/home/user/project",Rt=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;get rootDir(){return this.root}restamp(t,n,r="full"){let s=z(t),i=c=>{let u=this.tree.descend(c);u.kind==="found"&&(u.node.changedAt=n)},o=c=>{let u=this.tree.descend(c);if(u.kind==="found"){let f=u.node;(f.changedAt??0)>n&&(f.changedAt=n,f.mtime=new Date(n))}};r==="full"&&i(s);let a=s;for(;;){let c=a.lastIndexOf("/");if(c<=0)break;a=a.slice(0,c),o(a)}if(r==="ancestors")return;let l=[s];for(;l.length>0;){let c=l.pop(),u=this.tree.descend(c);if(!(u.kind!=="found"||u.node.type!=="directory"))for(let f of u.node.children.keys()){let d=`${c==="/"?"":c}/${f}`;o(d),l.push(d)}}}identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Fe.resolve(t.root);let n=t.mountPoint??Qy;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxMemoryBytes=t.maxMemoryBytes??1024*1024*1024,!Number.isSafeInteger(this.maxMemoryBytes)||this.maxMemoryBytes<0)throw new Error("OverlayFs: invalid maxMemoryBytes");this.allowSymlinks=t.allowSymlinks??!1,bi(this.root,"OverlayFs"),this.canonicalRoot=Ee.realpathSync(this.root),this.tree=new vi(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new x("EROFS",`read-only file system, ${t}`)}createMountPointDirs(){this.tree.ensureDirs(this.mountPoint)}getMountPoint(){return this.mountPoint}diff(){let t=[],n=[],r=[];for(let{path:i,node:o}of this.tree.preOrder()){let a=this.getRelativeToMount(i);if(!(a===null||a==="/")){if(o.type==="whiteout"){this.existsOnRealFs(i)&&(n.push(a),r.push(o.changedAt??0));continue}if(o.type==="file")if(o.metacopy){if(!this.existsOnRealFs(i))continue;t.push({path:a,nodeType:"file",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0,metadataOnly:!0})}else t.push({path:a,nodeType:"file",content:ki(o,i),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0});else o.type==="directory"?t.push({path:a,nodeType:"directory",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0}):t.push({path:a,nodeType:"symlink",content:new TextEncoder().encode(o.target),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0})}}t.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0);let s=n.map((i,o)=>({path:i,changedAt:r[o]}));return s.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),{writes:t,deletions:s.map(i=>i.path),...s.length>0&&{deletionChangedAt:s.map(i=>i.changedAt)}}}async sync(){for(let{path:t,node:n}of this.tree.postOrder()){let r=this.getRelativeToMount(t);if(r===null||r==="/")continue;if(n.type==="whiteout"){this.existsOnRealFs(t)||this.tree.detach(t);continue}if(n.type==="directory"&&n.children.size>0)continue;let s=n.seq;await this.nodeMatchesDisk(t,n)&&this.tree.detachIfUnchanged(t,n,s)}}reset(){this.tree.clear(),this.createMountPointDirs()}drop(t){let n=t.map(r=>{let s=z(r);if(s==="/")throw new x("EINVAL",`invalid argument, drop '${r}'`);return this.mountPoint==="/"?s:`${this.mountPoint}${s}`});n.sort((r,s)=>s.length-r.length);for(let r of n){let s=this.tree.descend(r);if(s.kind!=="found")continue;let i=s.node;i.type==="directory"&&i.children.size>0||this.tree.detach(r)}}async lstatLower(t){let n=this.resolveRealPathParent_(this.toRealPath(t));if(!n)return null;try{return{canonical:n,stat:await Nt(n)}}catch{return null}}async nodeMatchesDisk(t,n){if(n.type==="directory")return(await this.lstatLower(t))?.stat.isDirectory()??!1;if(n.type==="symlink"){if(!this.allowSymlinks)return!1;let s=await this.lstatLower(t);if(!s?.stat.isSymbolicLink())return!1;try{let i=await Ee.promises.readlink(s.canonical);return this.realTargetToVirtual(i)===n.target}catch{return!1}}if(n.metacopy){let s=await this.lstatLower(t);if(!s?.stat.isFile())return!1;let{stat:i}=s;return!(i.mtime.getTime()!==n.mtime.getTime()||process.platform!=="win32"&&(i.mode&4095)!==(n.mode&4095))}let r=this.resolveRealPath_(this.toRealPath(t));if(!r)return!1;try{let s=await Nt(r);if(!s.isFile())return!1;let i=ki(n,t);if(s.size!==i.byteLength)return!1;let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(r,o),l;try{l=new Uint8Array(await a.readFile())}finally{await a.close()}for(let c=0;c<l.byteLength;c++)if(l[c]!==i[c])return!1;return!0}catch{return!1}}mkdirSync(t,n){this.tree.ensureDirs(z(t),r=>this.lowerChildren(r))}writeFileSync(t,n){let r=z(t);this.ensureParentDirs(r);let s=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.tree.attach(r,{type:"file",content:s,mode:rn,mtime:new Date})}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let n=z(t),r=this.getRelativeToMount(n);if(r===null)return null;let s=Fe.join(this.root,r),i=Fe.resolve(s);return Le(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?jn(t,this.canonicalRoot):Ei(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Fe.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Fe.join(r,Fe.basename(t))}sanitizeError(t,n,r){Si(t,n,r,Zy)}ensureParentDirs(t){let n=Zn(t);n!=="/"&&this.tree.ensureDirs(n,r=>this.lowerChildren(r))}lowerChildren(t){let n=this.resolveRealPath_(this.toRealPath(t));if(!n)return null;try{return Ee.readdirSync(n)}catch{return null}}async existsInOverlay(t){let n=z(t),r=this.tree.descend(n);if(r.kind==="found")return r.node.type!=="whiteout";if(r.kind==="blocked"||r.kind==="notdir")return!1;let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)return!1;try{return await Nt(s),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t,n=new Set){U(t,"open");let r=z(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, open '${t}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.type==="symlink"){let a=this.resolveSymlink(r,i.target);return this.readFileBuffer(a,n)}if(i.type!=="file")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(!i.metacopy)return ki(i,t);let o=await this.readLowerFileBytes(r,t,n);if(process.platform==="win32")try{this.tree.attach(r,{type:"file",content:o,mode:i.mode,mtime:i.mtime})}catch(a){if(!ft(a,"ENOSPC"))throw a}return o}return this.readLowerFileBytes(r,t,n)}async readLowerFileBytes(t,n,r){let s=this.resolveRealPath_(this.toRealPath(t));if(!s)throw new x("ENOENT",`no such file or directory, open '${n}'`);try{let i=await Nt(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, open '${n}'`);let l=await Ee.promises.readlink(s),c=this.realTargetToVirtual(l),u=this.resolveSymlink(t,c);return this.readFileBuffer(u,r)}if(i.isDirectory())throw new x("EISDIR",`illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(s,o);try{let l=await a.readFile();return new Uint8Array(l)}finally{await a.close()}}catch(i){let o=i.code;if(o==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${n}'`);if(o==="ELOOP")throw new x("ENOENT",`no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(t,n,r){U(t,"write"),this.assertWritable(`write '${t}'`);let s=z(t);this.ensureParentDirs(s);let i=dt(r),o=Ht(n,i);this.tree.attach(s,{type:"file",content:o,mode:await this.inheritedMode(s),mtime:new Date})}async inheritedMode(t){let n=this.entryAt(t);if(n?.type==="file")return n.mode;if(n?.type==="directory")return rn;if(process.platform==="win32")return rn;try{let r=await this.stat(t);if(r.isFile)return r.mode}catch{}return rn}async appendFile(t,n,r){U(t,"append"),this.assertWritable(`append '${t}'`);let s=z(t),i=dt(r),o=Ht(n,i),a=this.tree.descend(s);if(a.kind==="found"&&a.node.type==="file"){await this.appendToExisting_(s,a.node,o,t);return}if(a.kind==="blocked")throw new x("ENOENT",`no such file or directory, append '${t}'`);if(a.kind==="notdir")throw new x("ENOTDIR",`not a directory, append '${t}'`);let l;try{l=await this.readFileBuffer(s)}catch(f){if(!ft(f,"ENOENT"))throw f;l=new Uint8Array(0)}let c=await this.inheritedMode(s),u=this.tree.descend(s);if(u.kind==="found"&&u.node.type==="file"){await this.appendToExisting_(s,u.node,o,t);return}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[o],mode:c,mtime:new Date})}async appendToExisting_(t,n,r,s){if(n.metacopy){let i=await this.readLowerFileBytes(t,s,new Set),o=this.tree.descend(t);if(o.kind==="found"&&o.node.type==="file"&&!o.node.metacopy){this.tree.appendChunk(o.node,r),o.node.mtime=new Date;return}this.tree.attach(t,{type:"file",content:i,appendChunks:[r],mode:n.mode,mtime:new Date});return}this.tree.appendChunk(n,r),n.mtime=new Date}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,n=new Set){U(t,"stat");let r=z(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, stat '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, stat '${t}'`);if(s.kind==="found"){let o=s.node;if(o.type==="whiteout")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(o.type==="symlink"){let a=this.resolveSymlink(r,o.target);return this.stat(a,n)}return this.memoryEntryStat(o)}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new x("ENOENT",`no such file or directory, stat '${t}'`);try{let o=await Nt(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, stat '${t}'`);let a=await Ee.promises.readlink(i),l=this.realTargetToVirtual(a),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime,dev:o.dev,ino:o.ino}}catch(o){if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){U(t,"lstat");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, lstat '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, lstat '${t}'`);try{let i=await Nt(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}memoryEntryStat(t){if(t.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:t.mode,size:t.target.length,mtime:t.mtime};let n=0;return t.type==="file"&&(n=t.metacopy?t.lowerSize??0:$d(t)),{isFile:t.type==="file",isDirectory:t.type==="directory",isSymbolicLink:!1,mode:t.mode,size:n,mtime:t.mtime,identity:this.identityFor(t)}}resolveSymlink(t,n){return Qn(t,n)}realTargetToVirtual(t){let n=vd(t,this.canonicalRoot);if(n.withinRoot){if(!Fe.isAbsolute(t))return t;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(t,n){U(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=z(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new x("EEXIST",`file already exists, mkdir '${t}'`);return}let i=Zn(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.tree.ensureDirs(r,o=>this.lowerChildren(o))}async readdirCore(t,n){let r=new Map,s=new Set,i=this.tree.descend(n);if(i.kind==="blocked")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.kind==="notdir")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);let o;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(l.type!=="directory")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);o=l;for(let[c,u]of l.children){if(u.type==="whiteout"){s.add(c);continue}r.set(c,{name:c,isFile:u.type==="file",isDirectory:u.type==="directory",isSymbolicLink:u.type==="symlink"})}}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await Nt(a)).isSymbolicLink()){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);return r}let l=await Ee.promises.readdir(a,{withFileTypes:!0});for(let c of l)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,t,"scandir")}return r}async resolveForReaddir(t,n=!1){let r=z(t),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let c=l.node;if(c.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new x("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,c.target)}if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let a=this.resolveRealPath_(this.toRealPath(r));if(!a)return{normalized:r,outsideOverlay:!0};try{if((await Nt(a)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let c=await Ee.promises.readlink(a),u=this.realTargetToVirtual(c),f=this.resolveSymlink(r,u);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,n){U(t,"rm"),this.assertWritable(`rm '${t}'`);let r=z(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}let i=!1;try{(await this.stat(r)).isDirectory&&(i=(await this.readdir(r)).length>0)}catch{}if(i&&!n?.recursive)throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.existsOnRealFs(r)?this.tree.putWhiteout(r):this.tree.detach(r)}existsOnRealFs(t){let n=this.toRealPath(t),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return Ga(r),!0}catch{return!1}}async cp(t,n,r){U(t,"cp"),U(n,"cp"),this.assertWritable(`cp '${n}'`);let s=z(t),i=z(n);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, cp '${t}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new x("EISDIR",`is a directory, cp '${t}'`);if(qt(s,i))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,n){this.assertWritable(`mv '${n}'`),await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return sn(t,n)}getAllPaths(){let t=new Set;for(let{path:n,node:r}of this.tree.preOrder())r.type!=="whiteout"&&t.add(n);return this.scanRealFs(this.mountPoint,t),Array.from(t)}scanRealFs(t,n){if(this.lowerHidden(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let s=Ee.readdirSync(r);for(let i of s){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.lowerHidden(o))continue;n.add(o);let a=Fe.join(r,i);Ga(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}lowerHidden(t){let n=this.tree.descend(t);switch(n.kind){case"blocked":case"notdir":return!0;case"found":return n.node.type!=="directory";default:return!1}}entryAt(t){let n=this.tree.descend(t);if(n.kind==="found"&&n.node.type!=="whiteout")return n.node}async chmod(t,n){U(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=z(t);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, chmod '${t}'`);let i=this.entryAt(r);if(i){i.mode=n,this.tree.touch(i);return}let o=await this.stat(r);this.attachMetacopyShadow(r,o,n,o.isFile?o.mtime:new Date)}attachMetacopyShadow(t,n,r,s){this.ensureParentDirs(t),n.isFile?this.tree.attach(t,{type:"file",content:new Uint8Array(0),metacopy:!0,lowerSize:n.size,mode:r,mtime:s}):n.isDirectory&&this.tree.attach(t,{type:"directory",children:new Map,mode:r,mtime:s})}async symlink(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=z(n);if(await this.existsInOverlay(r))throw new x("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:t,mode:es,mtime:new Date})}async link(t,n){U(t,"link"),U(n,"link"),this.assertWritable(`link '${n}'`);let r=z(t),s=z(n);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new x("EPERM",`operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new x("EEXIST",`file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,mode:o.mode,mtime:new Date,identity:o.identity??`overlay:${this.nextMemoryIdentity++}`})}async readlink(t){U(t,"readlink");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, readlink '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.type!=="symlink")throw new x("EINVAL",`invalid argument, readlink '${t}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, readlink '${t}'`);try{let i=await Ee.promises.readlink(s);if(!Fe.isAbsolute(i)){let o=Fe.resolve(Fe.dirname(s),i),a;try{a=Ee.realpathSync(o)}catch{a=o}if(!Le(a,this.canonicalRoot))return Fe.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){U(t,"realpath");let n=z(t),r=new Set,s=l=>{let c=this.tree.descend(l);if(c.kind==="blocked"||c.kind==="found"&&c.node.type==="whiteout")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return c.kind==="found"?c.node:void 0},i=async l=>{let c=l==="/"?[]:l.slice(1).split("/"),u="";for(let f of c){if(u=`${u}/${f}`,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);let d=s(u),h=0,p=gr;for(;d&&d.type==="symlink"&&h<p;){if(r.add(u),u=this.resolveSymlink(u,d.target),h++,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);d=s(u)}if(h>=p)throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);if(!d){let m=this.toRealPath(u),E=this.resolveRealPath_(m);if(E)try{if((await Nt(E)).isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, realpath '${t}'`);let g=await Ee.promises.readlink(E),y=this.realTargetToVirtual(g);return r.add(u),u=this.resolveSymlink(u,y),i(u)}}catch(S){if(S.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(S,t,"realpath")}else if(!this.allowSymlinks){let S=this.resolveRealPathParent_(m);if(S)try{if((await Nt(S)).isSymbolicLink())throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}catch(g){if(ft(g,"ENOENT")||ft(g,"ELOOP"))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(g,t,"realpath")}}}}return u||"/"},o=await i(n);if(!await this.existsInOverlay(o))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return o}async utimes(t,n,r){U(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=z(t);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, utimes '${t}'`);let o=this.entryAt(s);if(o){o.mtime=r,this.tree.touch(o);return}let a=await this.stat(s);this.attachMetacopyShadow(s,a,a.mode,r)}};var xi=class{bash;overlays;constructor(t={}){let{home:n,project:r,cwd:s,env:i,...o}=t,a=new Map,l=[],c=n?dr(n):null,u=r?dr(r):null,f=c&&u&&(()=>{let p=Me.relative(c,u);return p!==".."&&!p.startsWith(`..${Me.sep}`)&&!Me.isAbsolute(p)})();if(c){let p=new Rt({root:c,mountPoint:"/"});a.set("/home/user",{root:c,fs:p}),l.push({mountPoint:"/home/user",filesystem:p})}let d="/home/user";if(u)if(f&&c){let p=Me.relative(c,u);d=p?`/home/user/${p.split(Me.sep).join("/")}`:"/home/user"}else{let p=new Rt({root:u,mountPoint:"/"});a.set("/project",{root:u,fs:p}),l.push({mountPoint:"/project",filesystem:p}),d="/project"}let h=new Pt({base:new ze,mounts:l});this.overlays=a,this.bash=new Un({...o,env:{HOME:"/home/user",...i},cwd:s??d,fs:h})}analyzeCommands(t){return this.bash.analyzeCommands(t)}exec(t){return this.bash.exec(t)}diff(){let t=[],n=[];for(let{root:r,fs:s}of this.overlays.values()){let i=s.diff();for(let{path:o,...a}of i.writes)t.push({...a,path:Me.join(r,o)});for(let o=0;o<i.deletions.length;o++)n.push({path:Me.join(r,i.deletions[o]),changedAt:i.deletionChangedAt?.[o]})}return t.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),n.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),{writes:t,deletions:n.map(r=>r.path),...n.length>0&&{deletionChangedAt:n.map(r=>r.changedAt??0)}}}async applyChanges(t=this.diff()){let n=new Map,r=s=>{let i=this.findOverlay(s);if(!i)return;let o=`/${Me.relative(i.root,s).split(Me.sep).join("/")}`;if(o==="/")return;let a=n.get(i.fs);a?a.push(o):n.set(i.fs,[o])};try{for(let s of t.deletions)ja(s),r(s);for(let s of t.writes)qa(s.path,s),r(s.path)}finally{for(let[s,i]of n)s.drop(i)}}findOverlayEntry(t){let n=null;for(let[r,s]of this.overlays)(t===s.root||t.startsWith(s.root+Me.sep))&&(!n||s.root.length>n.root.length)&&(n={mountPoint:r,root:s.root,fs:s.fs});return n}findOverlay(t){return this.findOverlayEntry(t)}resolveRealPath(t){let n=this.findOverlayEntry(t);if(!n)return null;let r=`/${Me.relative(n.root,t).split(Me.sep).join("/")}`;return{mountPoint:n.mountPoint,overlay:n.fs,path:r}}toRealPath(t){let n=t.startsWith("/")?t:`/${t}`,r=null;for(let[s,i]of this.overlays)(n===s||n.startsWith(`${s}/`))&&(!r||s.length>r.mountPoint.length)&&(r={mountPoint:s,root:i.root});return r?Me.join(r.root,n.slice(r.mountPoint.length)):null}async sync(){for(let{fs:t}of this.overlays.values())await t.sync()}reset(){for(let{fs:t}of this.overlays.values())t.reset()}};function Ky(e={}){return new xi(e)}import{randomBytes as Xy}from"node:crypto";import*as L from"node:fs";import*as Z from"node:path";var Yy=["EACCES","escaping sandbox","EFBIG","ENOTSUP"],Pi=class e{static activeMutationRoots=new Set;static pendingMutations=[];root;canonicalRoot;maxFileReadSize;maxCopyOnWriteSize;maxCopySize;allowSymlinks;constructor(t){this.root=Z.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxCopyOnWriteSize=t.maxCopyOnWriteSize??104857600,this.maxCopySize=t.maxCopySize??0,this.allowSymlinks=t.allowSymlinks??!1,bi(this.root,"ReadWriteFs"),this.canonicalRoot=L.realpathSync(this.root)}resolveAndValidate(t,n){let r=this.allowSymlinks?jn(t,this.canonicalRoot):Ei(t,this.root,this.canonicalRoot);if(r===null)throw new x("EACCES",`permission denied, '${n}' resolves outside sandbox`);return r}validateParent(t,n){let r=Z.dirname(t),s=this.resolveAndValidate(r,n);return Z.join(s,Z.basename(t))}toRealPath(t){let n=z(t),r=Z.join(this.root,n);return Z.resolve(r)}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t){U(t,"open");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=this.allowSymlinks?L.constants.O_RDONLY:L.constants.O_RDONLY|L.constants.O_NOFOLLOW,i=await L.promises.open(r,s);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.code==="EISDIR")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(i.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(s,t,"open")}}async writeFile(t,n,r){await this.withFilesystemMutation(()=>this.writeFileUnlocked(t,n,r))}async writeFileUnlocked(t,n,r){U(t,"write");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t),o=dt(r),a=Ht(n,o),l=Z.dirname(i);try{await L.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:L.constants.O_NOFOLLOW,u=null;try{let f=await L.promises.lstat(i);if(!f.isFile()&&!f.isDirectory())throw new x("EACCES",`cannot write special file '${t}'`);let d=await L.promises.open(i,L.constants.O_WRONLY|L.constants.O_NONBLOCK|c);try{if(u=await d.stat(),!u.isFile())throw new x("EACCES",`cannot write special file '${t}'`);if(u.nlink<=1){await d.truncate(0),await d.writeFile(a);return}}finally{await d.close()}}catch(f){if(f.code!=="ENOENT")throw f}await this.replaceFile(i,a,u)}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"write")}}async appendFile(t,n,r){await this.withFilesystemMutation(()=>this.appendFileUnlocked(t,n,r))}async appendFileUnlocked(t,n,r){U(t,"append");let s=this.toRealPath(t),i=dt(r),o=Ht(n,i),a=this.resolveAndValidate(s,t),l=Z.dirname(a);try{await L.promises.mkdir(l,{recursive:!0}),a=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:L.constants.O_NOFOLLOW,u=null;try{let d=await L.promises.lstat(a);if(!d.isFile()&&!d.isDirectory())throw new x("EACCES",`cannot append special file '${t}'`);let h=await L.promises.open(a,L.constants.O_WRONLY|L.constants.O_APPEND|L.constants.O_NONBLOCK|c);try{if(u=await h.stat(),!u.isFile())throw new x("EACCES",`cannot append special file '${t}'`);if(u.nlink<=1){await h.writeFile(o);return}}finally{await h.close()}}catch(d){if(d.code!=="ENOENT")throw d}if(!u){await this.replaceFile(a,o,null);return}this.assertCopyOnWriteSize(u.size,"append",t);let f=await this.openCopySource(a);try{let d=await f.stat();if(!d.isFile()||d.dev!==u.dev||d.ino!==u.ino)throw new x("EACCES",`file identity changed, append '${t}'`);await this.replaceFile(a,o,d,{handle:f,size:u.size})}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"append")}}async withFilesystemMutation(t){return new Promise((n,r)=>{e.pendingMutations.push({root:this.canonicalRoot,start:()=>{e.activeMutationRoots.add(this.canonicalRoot),t().then(n,r).finally(()=>{e.activeMutationRoots.delete(this.canonicalRoot),e.drainMutationQueue()})}}),e.drainMutationQueue()})}static drainMutationQueue(){for(let t=0;t<e.pendingMutations.length;){let n=e.pendingMutations[t];if([...e.activeMutationRoots].some(s=>Le(n.root,s)||Le(s,n.root))){t++;continue}e.pendingMutations.splice(t,1),n.start()}}assertCopyOnWriteSize(t,n,r){if(this.maxCopyOnWriteSize>0&&t>this.maxCopyOnWriteSize)throw new x("EFBIG",`file too large for copy-on-write ${n} '${r}' (${t} bytes, max ${this.maxCopyOnWriteSize})`)}assertCopySize(t,n){if(this.maxCopySize>0&&t.size>this.maxCopySize)throw new x("EFBIG",`file too large to copy '${n}' (${t.size} bytes, max ${this.maxCopySize})`)}randomTransactionToken(){return Xy(16).toString("hex")}async openCopySource(t){let n=this.allowSymlinks?0:L.constants.O_NOFOLLOW,r=L.constants.O_RDONLY|L.constants.O_NONBLOCK|n,s=L.constants.O_NOATIME;if(process.platform!=="linux"||s===void 0)return L.promises.open(t,r);try{return await L.promises.open(t,r|s)}catch(i){if(i.code!=="EPERM")throw i;return L.promises.open(t,r)}}async replaceFile(t,n,r,s,i,o=!1){let a=Z.dirname(t),l="",c=null,u=r===null?438:384;for(let p=0;p<16;p++){l=Z.join(a,`.just-bash-write-${this.randomTransactionToken()}`);try{c=await L.promises.open(l,L.constants.O_WRONLY|L.constants.O_CREAT|L.constants.O_EXCL,u);break}catch(m){if(m.code!=="EEXIST")throw m}}if(!c)throw new x("EEXIST",`replacement write '${t}'`);let f=c,d=await f.stat(),h=!1;try{try{let m=0,E=async S=>{let g=0;for(;g<S.byteLength;){let{bytesWritten:y}=await f.write(S,g,S.byteLength-g,m+g);if(y===0)throw new x("EIO","replacement write made no progress");g+=y}m+=g};if(s){let S=Buffer.allocUnsafe(65536),g=0,y=s.size;for(;y>0;){let b=Math.min(S.length,y),{bytesRead:A}=await s.handle.read(S,0,b,g);if(A===0)break;await E(S.subarray(0,A)),g+=A,y-=A}}if(await E(n),r!==null&&await f.chmod(r.mode&(o?4095:511)),i)await f.utimes(i.atime,i.mtime);else if(r!==null){let S=await f.stat();await f.utimes(r.atime,S.mtime)}}finally{await f.close(),c=null}let p=await L.promises.lstat(l);if(!p.isFile()||p.dev!==d.dev||p.ino!==d.ino)throw new x("EACCES","replacement staging entry changed");await L.promises.rename(l,t),h=!0}finally{c&&await c.close().catch(()=>{}),h||await L.promises.rm(l,{force:!0}).catch(()=>{})}}async exists(t){if(t.includes("\0"))return!1;let n=this.toRealPath(t);try{let r=this.resolveAndValidate(n,t);return await L.promises.access(r),!0}catch{return!1}}async stat(t){U(t,"stat");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=await L.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(s,t,"stat")}}async lstat(t){U(t,"lstat");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await L.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(s,t,"lstat")}}async mkdir(t,n){await this.withFilesystemMutation(()=>this.mkdirUnlocked(t,n))}async mkdirUnlocked(t,n){U(t,"mkdir");let r=this.toRealPath(t),s=r===this.root?this.resolveAndValidate(r,t):this.validateParent(r,t);try{await L.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new x("EEXIST",`file already exists, mkdir '${t}'`);if(o.code==="ENOENT")throw new x("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){U(t,"scandir");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{if(!this.allowSymlinks&&(await L.promises.lstat(r)).isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return(await L.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.code==="ENOTDIR")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);this.sanitizeError(s,t,"scandir")}}async rm(t,n){await this.withFilesystemMutation(()=>this.rmUnlocked(t,n))}async rmUnlocked(t,n){U(t,"rm");let r=this.toRealPath(t),s=this.validateParent(r,t);try{let i=await L.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);await L.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}if(o.code==="ENOTEMPTY")throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,n,r){await this.withFilesystemMutation(()=>this.cpUnlocked(t,n,r))}async cpUnlocked(t,n,r){U(t,"cp"),U(n,"cp");let s=this.toRealPath(t),i=this.toRealPath(n),o=this.validateParent(s,t),a=this.resolveAndValidate(i,n),l;try{l=await L.promises.lstat(o)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}if(l.isDirectory()&&Le(a,o))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);if(!l.isDirectory())try{let c=this.validateParent(i,n),u=await L.promises.lstat(c);if(l.dev===u.dev&&l.ino===u.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}if(l.isFile())try{let c=await L.promises.stat(a);if(l.dev===c.dev&&l.ino===c.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}try{await this.preflightCopyTree(o,t)}catch(c){this.sanitizeError(c,t,"cp")}if(l.isFile()||l.isSymbolicLink())try{await L.promises.mkdir(Z.dirname(a),{recursive:!0}),this.resolveAndValidate(i,n)}catch(c){this.sanitizeError(c,n,"cp")}try{await this.copyTreeEntry(o,i,t,n,r?.recursive??!1)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);if(u.code==="EISDIR")throw new x("EISDIR",`is a directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}}async copyTreeEntry(t,n,r,s,i){let o=await L.promises.lstat(t);if(o.isFile()){this.assertCopySize(o,r);let a=this.resolveAndValidate(n,s),l=await this.assertCopyDestinationWritable(a,s),c=await this.openCopySource(t);try{let u=await c.stat();if(!u.isFile()||u.dev!==o.dev||u.ino!==o.ino)throw new x("EACCES",`file identity changed, cp '${r}'`);await this.replaceFile(a,new Uint8Array(0),l??o,{handle:c,size:o.size})}finally{await c.close()}return}if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${r}' contains a symlink`);let a=await L.promises.readlink(t),l=Z.isAbsolute(a)?await this.toVirtualAbsoluteSymlinkTarget(a,r):a;await this.replaceSymlink(n,s,l);return}if(o.isDirectory()){if(!i)throw new x("EISDIR",`is a directory, cp '${r}'`);let a=this.resolveAndValidate(n,s);await L.promises.mkdir(a,{recursive:!0}),a=this.resolveAndValidate(n,s);for(let l of await L.promises.readdir(t))await this.copyTreeEntry(Z.join(t,l),Z.join(n,l),Z.join(r,l),Z.join(s,l),!0);await L.promises.chmod(a,o.mode&4095);return}throw new x("EINVAL",`unsupported file type, cp '${r}'`)}async assertCopyDestinationWritable(t,n){let r;try{r=await L.promises.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}if(!r.isFile()){if(r.isDirectory())return r;throw new x("EACCES",`cannot copy over special file '${n}'`)}let s=this.allowSymlinks?0:L.constants.O_NOFOLLOW,i=await L.promises.open(t,L.constants.O_WRONLY|L.constants.O_NONBLOCK|s);try{let o=await i.stat();if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)throw new x("EACCES",`destination changed, cp '${n}'`)}finally{await i.close()}return r}async replaceSymlink(t,n,r){let s=this.validateParent(t,n),i=Z.dirname(z(n)),o="",a="",l="",c=null;for(let f=0;f<16;f++){let d=`.just-bash-copy-link-${this.randomTransactionToken()}`;o=i==="/"?`/${d}`:`${i}/${d}`,a=this.toRealPath(o);try{await this.symlinkUnlocked(r,o),l=this.validateParent(a,o),c=await L.promises.lstat(l);break}catch(h){if(!ft(h,"EEXIST"))throw h}}if(!c)throw new x("EEXIST",`replacement symlink '${n}'`);let u=!1;try{let f=await L.promises.lstat(l);if(!f.isSymbolicLink()||f.dev!==c.dev||f.ino!==c.ino)throw new x("EACCES","replacement symlink entry changed");await L.promises.rename(l,s),u=!0}finally{!u&&l&&await L.promises.rm(l,{force:!0}).catch(()=>{})}}async toVirtualAbsoluteSymlinkTarget(t,n){let r=Z.resolve(t),s=await L.promises.realpath(r),i=await L.promises.realpath(Z.dirname(r)),o=Z.join(i,Z.basename(r));if(!Le(s,this.canonicalRoot)||!Le(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return Nn(o.slice(this.canonicalRoot.length))||"/"}async preflightCopyTree(t,n,r=new Set){let s=await L.promises.lstat(t),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new x("ELOOP",`cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${n}' contains a symlink`);let o=await L.promises.realpath(t);if(!Le(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let o=await L.promises.readdir(t);for(let a of o)await this.preflightCopyTree(Z.join(t,a),Z.join(n,a),r)}finally{r.delete(i)}}}async mv(t,n){await this.withFilesystemMutation(()=>this.mvUnlocked(t,n))}async mvUnlocked(t,n){U(t,"mv"),U(n,"mv");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.validateParent(r,t),o=this.validateParent(s,n),a;try{a=await L.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);this.sanitizeError(c,t,"mv")}if(a.isDirectory()&&this.isSameOrDescendantIdentity(i,o))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);try{if(a.isSymbolicLink()){let c=await L.promises.readlink(i),u=Z.resolve(Z.dirname(o),c),f=await L.promises.realpath(u).catch(()=>u);if(!Le(f,this.canonicalRoot))throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(ft(u,"EACCES"))throw c}let l=Z.dirname(o);try{await L.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await L.promises.rename(i,o)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(t,n);return}this.sanitizeError(c,t,"mv")}try{if(L.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await L.promises.rename(o,i),new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(ft(c,"EACCES"))throw c;await L.promises.rename(o,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(t,n){let r=t,s=n;try{r=L.realpathSync(t)}catch{}try{s=L.realpathSync(n)}catch{try{let i=L.realpathSync(Z.dirname(n));s=Z.join(i,Z.basename(n))}catch{}}return Le(s,r)}async uniqueTransactionPath(t,n){let r=Z.posix.dirname(t);for(let s=0;s<16;s++){let i=Z.posix.join(r,`.just-bash-mv-${n}-${this.randomTransactionToken()}`);if(!await this.exists(i))return i}throw new x("EEXIST",`mv '${t}'`)}async moveAcrossDevices(t,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(t,"source"),o=this.validateParent(this.toRealPath(r),r),a=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(t),t),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,h=!1,p=async()=>{h&&await L.promises.rename(c,l).catch(()=>{}),d&&await L.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await L.promises.rename(a,u).catch(()=>{}),await L.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cpUnlocked(t,r,{recursive:!0}),(await L.promises.lstat(o)).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`);try{await L.promises.rename(u,a),f=!0}catch(E){if(E.code!=="ENOENT")throw E}await L.promises.rename(o,u),d=!0,await L.promises.rename(l,c),h=!0,await L.promises.rm(c,{recursive:!0,force:!1}),h=!1,f&&await L.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await p(),this.sanitizeError(m,t,"mv")}}resolvePath(t,n){return sn(t,n)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,n,r){Si(t,n,r,Yy)}findEscapingSymlinks(t){let n=[],r=L.readdirSync(t);for(let s of r){let i=Z.join(t,s),o=L.lstatSync(i);if(o.isSymbolicLink()){let a=L.readlinkSync(i),l=Z.resolve(t,a),c;try{c=L.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}Le(c,this.canonicalRoot)||n.push(i)}else o.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(t,n){let r=this.toRealPath(t),s;try{s=this.resolveAndValidate(r,t)}catch{return}try{let i=L.readdirSync(s);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`;n.push(a);let l=Z.join(s,o);L.lstatSync(l).isDirectory()&&this.scanDir(a,n)}}catch{}}async chmod(t,n){await this.withFilesystemMutation(()=>this.chmodUnlocked(t,n))}async chmodUnlocked(t,n){U(t,"chmod");let r=this.toRealPath(t),s=this.resolveAndValidate(r,t);try{let i=await L.promises.lstat(s);if(!i.isFile()){if(!i.isDirectory()&&i.nlink>1)throw new x("EACCES",`cannot chmod multiply-linked special file '${t}'`);await L.promises.chmod(s,n);return}if(i.nlink<=1){await L.promises.chmod(s,n);return}this.assertCopyOnWriteSize(i.size,"chmod",t);let o=await this.openCopySource(s);try{let a=await o.stat();if(!a.isFile())throw new x("EACCES",`file type changed, chmod '${t}'`);await this.replaceFile(s,new Uint8Array(0),{mode:n,atime:a.atime,mtime:a.mtime},{handle:o,size:a.size},{atime:a.atime,mtime:a.mtime},!0)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, chmod '${t}'`);if(o.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,"chmod")}}async symlink(t,n){await this.withFilesystemMutation(()=>this.symlinkUnlocked(t,n))}async symlinkUnlocked(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=z(n),o=z(Z.dirname(i)),a=t.startsWith("/")?z(t):z(o==="/"?`/${t}`:`${o}/${t}`),l=Z.join(this.canonicalRoot,a),c=Z.dirname(s),u=t.startsWith("/")?l:Z.relative(c,l)||".";try{await L.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new x("EEXIST",`file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(t,n){await this.withFilesystemMutation(()=>this.linkUnlocked(t,n))}async linkUnlocked(t,n){U(t,"link"),U(n,"link");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.resolveAndValidate(r,t),o=s===this.root?this.resolveAndValidate(s,n):this.validateParent(s,n);try{await L.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new x("ENOENT",`no such file or directory, link '${t}'`);if(l.code==="EEXIST")throw new x("EEXIST",`file already exists, link '${n}'`);if(l.code==="EPERM")throw new x("EPERM",`operation not permitted, link '${t}'`);this.sanitizeError(a,t,"link")}}async readlink(t){U(t,"readlink");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await L.promises.readlink(r),i=z(t),o=Z.dirname(i),a=Z.isAbsolute(s)?s:Z.resolve(Z.dirname(r),s),l=await L.promises.realpath(a).catch(()=>a);if(Le(l,this.canonicalRoot)){let c=Nn(l.slice(this.canonicalRoot.length))||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:Nn(Z.relative(o,c))}return Z.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(s,t,"readlink")}}async realpath(t){U(t,"realpath");let n=this.toRealPath(t);try{this.resolveAndValidate(n,t)}catch{throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}let r;try{r=await L.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);if(i.code==="ELOOP")throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(s,t,"realpath")}if(Le(r,this.canonicalRoot))return Nn(r.slice(this.canonicalRoot.length))||"/";throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}async utimes(t,n,r){await this.withFilesystemMutation(()=>this.utimesUnlocked(t,n,r))}async utimesUnlocked(t,n,r){U(t,"utimes");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t);try{let o=await L.promises.lstat(i);if(!o.isFile()){if(!o.isDirectory()&&o.nlink>1)throw new x("EACCES",`cannot change times on multiply-linked special file '${t}'`);await L.promises.utimes(i,n,r);return}if(o.nlink<=1){await L.promises.utimes(i,n,r);return}this.assertCopyOnWriteSize(o.size,"utimes",t);let a=await this.openCopySource(i);try{let l=await a.stat();if(!l.isFile())throw new x("EACCES",`file type changed, utimes '${t}'`);await this.replaceFile(i,new Uint8Array(0),l,{handle:a,size:l.size},{atime:n,mtime:r},!0)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new x("ENOENT",`no such file or directory, utimes '${t}'`);if(a.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(o,t,"utimes")}}};import $n from"node:path";function Jy(e){if(e.mounts.length===0)throw new x("EINVAL","createVfsTemplate needs at least one mount");let t=e.mounts.map(({at:c,root:u})=>{let f=dr(u);return{at:(c.startsWith("/")?c:`/${c}`).replace(/\/+$/,"")||"/",root:f}}),n=new Set;for(let{at:c}of t){if(n.has(c))throw new x("EINVAL",`duplicate mount point '${c}' in createVfsTemplate`);if(n.add(c),c==="/")throw new x("EINVAL","mount point '/' would swallow the shared scratch space");for(let u of n)if(u!==c&&c.startsWith(`${u}/`))throw new x("EINVAL",`mount point '${c}' is nested inside '${u}'`)}let r=[];for(let{root:c}of t){for(let u of r){let f=$n.sep;if(c!==u&&(c.startsWith(u+f)||u.startsWith(c+f)))throw new x("EINVAL",`nested template roots share one real subtree: '${c}' and '${u}'`)}r.push(c)}let s=new ze,i=()=>{let c=new Pt({base:s});for(let{at:u,root:f}of t)c.mount(u,new Rt({root:f,mountPoint:"/",...e.readOnly!==void 0&&{readOnly:e.readOnly},...e.maxMemoryBytes!==void 0&&{maxMemoryBytes:e.maxMemoryBytes}}));return c};return{fork:()=>i(),merge:async c=>{let u=[],f=0;for(let h of c){let p=h instanceof Pt?h.diff({space:"vfs"}):h;for(let m of p.writes){let E=m.changedAt??0;u.push({kind:"write",changedAt:E,order:f++,write:m})}for(let m=0;m<p.deletions.length;m++){let E=p.deletionChangedAt?.[m]??0;u.push({kind:"delete",changedAt:E,order:f++,path:p.deletions[m]})}}u.sort((h,p)=>h.changedAt!==p.changedAt?h.changedAt-p.changedAt:h.order-p.order);let d=i();for(let h of u){if(h.kind==="write"&&h.write.metadataOnly&&h.write.mode===void 0&&h.write.mtime===void 0)continue;let p=!1;try{if(h.kind==="delete")await d.rm(h.path,{recursive:!0});else{let m=h.write;m.metadataOnly?(m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="directory"?(await d.mkdir(m.path,{recursive:!0}),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="symlink"?await d.symlink(new TextDecoder().decode(m.content),m.path):(await d.writeFile(m.path,m.content),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime))}p=!0}catch{}p?d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt):d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt,"ancestors")}return d},apply:c=>{let u={writes:c.writes.map(f=>({...f,path:$n.normalize(f.path)})),deletions:c.deletions.map(f=>$n.normalize(f)),...c.deletionChangedAt&&{deletionChangedAt:c.deletionChangedAt}};for(let f of u.writes)if(f.nodeType==="symlink")throw new x("EINVAL",`change-set contains a symlink write: '${f.path}'`);for(let f of[...u.deletions,...u.writes.map(d=>d.path)]){if(!t.some(({root:m})=>f===m||f.startsWith(m+$n.sep)))throw new x("EINVAL",`change-set entry outside every template root: '${f}'`);if(u.deletions.includes(f)&&t.some(({root:E})=>f===E))throw new x("EINVAL",`change-set deletes a registered root: '${f}'`);let h=eg(f);if(!t.some(({root:m})=>h===m||h.startsWith(m+$n.sep)))throw new x("EINVAL",`change-set entry escapes its root through a symlink: '${f}'`)}wi(u)}}}function eg(e){let t=e,n=[];for(;;)try{let r=dr(t);return n.length===0?r:$n.join(r,...n.reverse())}catch{let r=$n.dirname(t);if(r===t)return e;n.push($n.basename(t)),t=r}}var hr=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,n,r,s,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=Hr(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(Zr(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 n=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=n.exitCode,n}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 $i=class e{bashEnv;timeoutMs;constructor(t,n){this.bashEnv=t,this.timeoutMs=n}static async create(t){let n=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Rt({root:t.overlayRoot})}let r=new Un({env:t?.env,cwd:t?.cwd,fs:n,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,n,r){let s,i,o,a,l=!1,c,u;if(typeof t=="object"){let m=t,E=[m.cmd,...m.args??[]];s=Di(E),i=m.cwd,o=m.env,a=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=Di([t,...n]),a=m?.signal}else{s=t;let m=n;i=m?.cwd,o=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new hr(this.bashEnv,s,f,o,d,a,this.timeoutMs);if(l)return h;let p=await h.wait();if(c){let m=await h.stdout();m&&c.write(m)}if(u){let m=await h.stderr();m&&u.write(m)}return p}async writeFiles(t){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(t)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let o=this.bashEnv.fs.resolvePath(n,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(t,n){let r=await this.bashEnv.readFile(t);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Ci=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 n=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(n),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(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)s.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:n,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(s)})}return t.sort((n,r)=>r.count-n.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 Cd(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
811
811
  Type: ${e.type}`,`
812
812
  Path: ${e.path}`,`
813
813
  Message: ${e.message}`,e.executionId?`
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Worker thread for JavaScript execution via QuickJS.
3
+ * Keeps QuickJS loaded and handles multiple execution requests.
4
+ *
5
+ * Defense-in-depth activates AFTER QuickJS loads (WASM init needs unrestricted JS).
6
+ * User JavaScript code runs inside the QuickJS sandbox with no access to Node.js globals.
7
+ *
8
+ * Build: Bundled to js-exec-worker.js via esbuild (see package.json "build:worker").
9
+ * Run: npx esbuild src/commands/js-exec/js-exec-worker.ts --bundle --platform=node --format=esm --outfile=src/commands/js-exec/js-exec-worker.js --external:quickjs-emscripten
10
+ */
11
+ import { type WorkerDefenseStats } from "../../security/index.js";
12
+ export interface JsExecWorkerInput {
13
+ protocolToken: string;
14
+ sharedBuffer: SharedArrayBuffer;
15
+ jsCode: string;
16
+ cwd: string;
17
+ env: Record<string, string>;
18
+ args: string[];
19
+ scriptPath?: string;
20
+ bootstrapCode?: string;
21
+ isModule?: boolean;
22
+ stripTypes?: boolean;
23
+ timeoutMs?: number;
24
+ /** QuickJS heap limit in bytes. Defaults to 64MB. */
25
+ memoryBytes?: number;
26
+ /** When true, the QuickJS guest gets a `tools` proxy that calls the host's invokeTool hook. */
27
+ hasInvokeTool?: boolean;
28
+ }
29
+ export interface JsExecWorkerOutput {
30
+ protocolToken?: string;
31
+ type?: "initialization-failure";
32
+ success: boolean;
33
+ error?: string;
34
+ defenseStats?: WorkerDefenseStats;
35
+ }
@@ -1,4 +1,17 @@
1
- /** js-exec - Execute JavaScript code via the run package. */
1
+ /**
2
+ * js-exec - Execute JavaScript code via QuickJS (WASM)
3
+ *
4
+ * Runs JavaScript code in an isolated worker thread with access to the
5
+ * virtual filesystem, HTTP, and sub-shell execution via SharedArrayBuffer bridge.
6
+ *
7
+ * This command is Node.js only (uses worker_threads).
8
+ */
2
9
  import type { RuntimeCommand } from "../../types.js";
10
+ /** @internal Set the idle-teardown delay — for focused lifecycle tests only. */
11
+ export declare function _setJsExecWorkerIdleTimeoutMsForTests(ms: number): void;
12
+ /** @internal Whether the shared worker is currently alive — for tests only. */
13
+ export declare function _hasSharedJsExecWorkerForTests(): boolean;
14
+ /** @internal Reset singleton worker state — for focused protocol tests only. */
15
+ export declare function _resetJsExecWorkerForTests(): void;
3
16
  export declare const jsExecCommand: RuntimeCommand;
4
17
  export declare const nodeStubCommand: RuntimeCommand;
@@ -20,6 +20,12 @@ export interface VfsTemplateOptions {
20
20
  * default.
21
21
  */
22
22
  maxMemoryBytes?: number;
23
+ /**
24
+ * When true, overlay mounts are read-only: writes through the
25
+ * overlay fail with EROFS. Forks can read the host filesystem
26
+ * but cannot modify it. Default: false.
27
+ */
28
+ readOnly?: boolean;
23
29
  }
24
30
  /**
25
31
  * Template for cheap parallel forks (see
@@ -38,7 +38,7 @@ export interface InterpreterOptions {
38
38
  /** Bootstrap JavaScript code for js-exec */
39
39
  jsBootstrapCode?: string;
40
40
  /** Tool invoker hook for js-exec's `tools` proxy */
41
- invokeTool?: (path: string, argsJson: string, abortSignal: AbortSignal) => Promise<string>;
41
+ invokeTool?: (path: string, argsJson: string) => Promise<string>;
42
42
  }
43
43
  export declare class Interpreter {
44
44
  private ctx;
@@ -405,5 +405,5 @@ export interface InterpreterContext {
405
405
  * Tool invoker hook. When present, js-exec sets up a `tools` proxy that
406
406
  * routes calls through this callback.
407
407
  */
408
- invokeTool?: (path: string, argsJson: string, abortSignal: AbortSignal) => Promise<string>;
408
+ invokeTool?: (path: string, argsJson: string) => Promise<string>;
409
409
  }
package/dist/limits.d.ts CHANGED
@@ -82,8 +82,8 @@ export interface ExecutionLimits {
82
82
  maxPythonTimeoutMs?: number;
83
83
  /** Maximum JavaScript execution time in milliseconds (normal default: 30000) */
84
84
  maxJsTimeoutMs?: number;
85
- /** Maximum JavaScript host-bridge operations (normal default: 1000000) */
86
- maxJsBridgeRequests?: number;
85
+ /** Maximum QuickJS heap size in bytes (normal default: 64 MiB) */
86
+ maxJsMemoryBytes?: number;
87
87
  /** Maximum glob filesystem operations (normal default: 1000000) */
88
88
  maxGlobOperations?: number;
89
89
  /** Maximum string length in bytes (normal default: 64 MiB) */