@jerryan/just-bash 3.6.0 → 3.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +349 -316
- package/LICENSE +201 -201
- package/README.md +827 -827
- package/dist/agent-sandbox.d.ts +5 -0
- package/dist/bin/chunks/chmod-G2BCCQGF.js +3 -0
- package/dist/bin/chunks/{chunk-B2GCIQI2.js → chunk-2UKTHDUM.js} +1 -1
- package/dist/bin/{shell/chunks/chunk-7WBCA2BB.js → chunks/chunk-3DWQCLNP.js} +1 -1
- package/dist/bin/chunks/chunk-66UHJFN6.js +11 -0
- package/dist/bin/{shell/chunks/chunk-67XYNGRV.js → chunks/chunk-6O4Z6BQT.js} +1 -1
- package/dist/bin/chunks/{chunk-QFTZKD5O.js → chunk-6TUILMPB.js} +1 -1
- package/dist/bin/chunks/{chunk-M7SIPZZZ.js → chunk-7KMOGI3N.js} +1 -1
- package/dist/bin/{shell/chunks/chunk-6ESRNSO7.js → chunks/chunk-ADI36B7X.js} +1 -1
- package/dist/bin/chunks/chunk-CN4JKMTR.js +8 -0
- package/dist/bin/{shell/chunks/chunk-DZAFUADN.js → chunks/chunk-E26NQEH2.js} +1 -1
- package/dist/bin/chunks/chunk-E54Z6VIE.js +12 -0
- package/dist/bin/chunks/chunk-F2PYTUMR.js +9 -0
- package/dist/bin/chunks/chunk-FO7XJH3J.js +13 -0
- package/dist/bin/chunks/chunk-HWK7KFGB.js +3 -0
- package/dist/bin/{shell/chunks/chunk-LE2XKKGQ.js → chunks/chunk-HYLF56CC.js} +1 -1
- package/dist/bin/chunks/chunk-KNTDFP7X.js +12 -0
- package/dist/bin/{shell/chunks/chunk-MF3GVFLC.js → chunks/chunk-L345YZ6R.js} +1 -1
- package/dist/bin/chunks/chunk-NBTZL3VS.js +3 -0
- package/dist/bin/chunks/chunk-OHFB3M3X.js +3 -0
- package/dist/bin/{shell/chunks/chunk-HQ63MFHG.js → chunks/chunk-PEUGMGJJ.js} +1 -1
- package/dist/bin/chunks/chunk-QKJAAJ7J.js +3 -0
- package/dist/bin/{shell/chunks/chunk-JELR4642.js → chunks/chunk-R76AK3KD.js} +12 -12
- package/dist/bin/chunks/{chunk-NLU5LALY.js → chunk-RRECHBUS.js} +1 -1
- package/dist/bin/chunks/{chunk-ZMGLTHSU.js → chunk-THFQI5LV.js} +1 -1
- package/dist/bin/chunks/{chunk-CL7IYCGG.js → chunk-U7YR5CDD.js} +1 -1
- package/dist/bin/chunks/cp-TMDR6USI.js +3 -0
- package/dist/bin/chunks/du-UKFUX7KM.js +3 -0
- package/dist/bin/chunks/find-W2RZWTOF.js +3 -0
- package/dist/bin/chunks/{flag-coverage-C7PB2MO7.js → flag-coverage-QJ5ZQKCF.js} +1 -1
- package/dist/bin/{shell/chunks/grep-CVU5V66H.js → chunks/grep-IHDO3L72.js} +1 -1
- package/dist/bin/chunks/gzip-WUK63QLL.js +3 -0
- package/dist/bin/{shell/chunks/js-exec-DJQLXWCS.js → chunks/js-exec-BE37X4L2.js} +7 -7
- package/dist/bin/chunks/js-exec-worker.js +296 -116
- package/dist/bin/chunks/ln-XVC53673.js +3 -0
- package/dist/bin/chunks/ls-EROTXGTC.js +3 -0
- package/dist/bin/chunks/mkdir-YJ3SOVRP.js +3 -0
- package/dist/bin/chunks/mv-HDNKXPO6.js +3 -0
- package/dist/bin/{shell/chunks/python3-JCJHSX4Z.js → chunks/python3-TJ6DCPIA.js} +1 -1
- package/dist/bin/chunks/readlink-ZUIECKQC.js +3 -0
- package/dist/bin/chunks/rg-ODJAYIKX.js +3 -0
- package/dist/bin/chunks/rm-B4LVIG7A.js +3 -0
- package/dist/bin/chunks/rmdir-W5NBOJ7E.js +3 -0
- package/dist/bin/{shell/chunks/sleep-DVFE2GSF.js → chunks/sleep-MOJQBZMY.js} +1 -1
- package/dist/bin/chunks/split-TVJYLTIJ.js +3 -0
- package/dist/bin/chunks/sqlite3-5BGAK7VX.js +3 -0
- package/dist/bin/chunks/{timeout-YGFHQJKX.js → timeout-RQOWSWYG.js} +1 -1
- package/dist/bin/chunks/worker.js +233 -108
- package/dist/bin/just-bash.js +381 -376
- package/dist/bin/shell/chunks/chmod-G2BCCQGF.js +3 -0
- package/dist/bin/shell/chunks/{chunk-B2GCIQI2.js → chunk-2UKTHDUM.js} +1 -1
- package/dist/bin/{chunks/chunk-7WBCA2BB.js → shell/chunks/chunk-3DWQCLNP.js} +1 -1
- package/dist/bin/shell/chunks/chunk-66UHJFN6.js +11 -0
- package/dist/bin/{chunks/chunk-67XYNGRV.js → shell/chunks/chunk-6O4Z6BQT.js} +1 -1
- package/dist/bin/shell/chunks/{chunk-QFTZKD5O.js → chunk-6TUILMPB.js} +1 -1
- package/dist/bin/shell/chunks/{chunk-M7SIPZZZ.js → chunk-7KMOGI3N.js} +1 -1
- package/dist/bin/{chunks/chunk-6ESRNSO7.js → shell/chunks/chunk-ADI36B7X.js} +1 -1
- package/dist/bin/shell/chunks/chunk-CN4JKMTR.js +8 -0
- package/dist/bin/{chunks/chunk-DZAFUADN.js → shell/chunks/chunk-E26NQEH2.js} +1 -1
- package/dist/bin/shell/chunks/chunk-E54Z6VIE.js +12 -0
- package/dist/bin/shell/chunks/chunk-F2PYTUMR.js +9 -0
- package/dist/bin/shell/chunks/chunk-FO7XJH3J.js +13 -0
- package/dist/bin/shell/chunks/chunk-HWK7KFGB.js +3 -0
- package/dist/bin/{chunks/chunk-LE2XKKGQ.js → shell/chunks/chunk-HYLF56CC.js} +1 -1
- package/dist/bin/shell/chunks/chunk-KNTDFP7X.js +12 -0
- package/dist/bin/{chunks/chunk-MF3GVFLC.js → shell/chunks/chunk-L345YZ6R.js} +1 -1
- package/dist/bin/shell/chunks/chunk-NBTZL3VS.js +3 -0
- package/dist/bin/shell/chunks/chunk-OHFB3M3X.js +3 -0
- package/dist/bin/{chunks/chunk-HQ63MFHG.js → shell/chunks/chunk-PEUGMGJJ.js} +1 -1
- package/dist/bin/shell/chunks/chunk-QKJAAJ7J.js +3 -0
- package/dist/bin/{chunks/chunk-JELR4642.js → shell/chunks/chunk-R76AK3KD.js} +12 -12
- package/dist/bin/shell/chunks/{chunk-NLU5LALY.js → chunk-RRECHBUS.js} +1 -1
- package/dist/bin/shell/chunks/{chunk-ZMGLTHSU.js → chunk-THFQI5LV.js} +1 -1
- package/dist/bin/shell/chunks/{chunk-CL7IYCGG.js → chunk-U7YR5CDD.js} +1 -1
- package/dist/bin/shell/chunks/cp-TMDR6USI.js +3 -0
- package/dist/bin/shell/chunks/du-UKFUX7KM.js +3 -0
- package/dist/bin/shell/chunks/find-W2RZWTOF.js +3 -0
- package/dist/bin/shell/chunks/{flag-coverage-C7PB2MO7.js → flag-coverage-QJ5ZQKCF.js} +1 -1
- package/dist/bin/{chunks/grep-CVU5V66H.js → shell/chunks/grep-IHDO3L72.js} +1 -1
- package/dist/bin/shell/chunks/gzip-WUK63QLL.js +3 -0
- package/dist/bin/{chunks/js-exec-DJQLXWCS.js → shell/chunks/js-exec-BE37X4L2.js} +7 -7
- package/dist/bin/shell/chunks/ln-XVC53673.js +3 -0
- package/dist/bin/shell/chunks/ls-EROTXGTC.js +3 -0
- package/dist/bin/shell/chunks/mkdir-YJ3SOVRP.js +3 -0
- package/dist/bin/shell/chunks/mv-HDNKXPO6.js +3 -0
- package/dist/bin/{chunks/python3-JCJHSX4Z.js → shell/chunks/python3-TJ6DCPIA.js} +1 -1
- package/dist/bin/shell/chunks/readlink-ZUIECKQC.js +3 -0
- package/dist/bin/shell/chunks/rg-ODJAYIKX.js +3 -0
- package/dist/bin/shell/chunks/rm-B4LVIG7A.js +3 -0
- package/dist/bin/shell/chunks/rmdir-W5NBOJ7E.js +3 -0
- package/dist/bin/{chunks/sleep-DVFE2GSF.js → shell/chunks/sleep-MOJQBZMY.js} +1 -1
- package/dist/bin/shell/chunks/split-TVJYLTIJ.js +3 -0
- package/dist/bin/shell/chunks/sqlite3-5BGAK7VX.js +3 -0
- package/dist/bin/shell/chunks/{timeout-YGFHQJKX.js → timeout-RQOWSWYG.js} +1 -1
- package/dist/bin/shell/shell.js +385 -380
- package/dist/bundle/browser.js +643 -638
- package/dist/bundle/chunks/chmod-XZNKTJHL.js +2 -0
- package/dist/bundle/chunks/{chunk-XVSR5HHH.js → chunk-2T7PBFL4.js} +1 -1
- package/dist/bundle/chunks/chunk-3BMWRGU2.js +10 -0
- package/dist/bundle/chunks/chunk-3CIDHL5V.js +11 -0
- package/dist/bundle/chunks/chunk-4CC3OZPU.js +2 -0
- package/dist/bundle/chunks/{chunk-FIMF2TLE.js → chunk-5DMO6LFU.js} +12 -12
- package/dist/bundle/chunks/{chunk-N3A4JVFJ.js → chunk-6IA4DXG2.js} +1 -1
- package/dist/bundle/chunks/chunk-A257L6QO.js +7 -0
- package/dist/bundle/chunks/{chunk-6DDRR56B.js → chunk-ACVD6PQF.js} +1 -1
- package/dist/bundle/chunks/chunk-BS6EJR2R.js +11 -0
- package/dist/bundle/chunks/chunk-D5FHVW27.js +2 -0
- package/dist/bundle/chunks/{chunk-24NLAR7R.js → chunk-E3ABCXE4.js} +1 -1
- package/dist/bundle/chunks/{chunk-FSJ6TTCC.js → chunk-HMM3NGUJ.js} +1 -1
- package/dist/bundle/chunks/chunk-IYJLVOVE.js +12 -0
- package/dist/bundle/chunks/chunk-LRFR25IP.js +8 -0
- package/dist/bundle/chunks/{chunk-NBNI7G66.js → chunk-OPYVVD5P.js} +1 -1
- package/dist/bundle/chunks/{chunk-F6XU52K3.js → chunk-OR544SGH.js} +1 -1
- package/dist/bundle/chunks/{chunk-RPKJJFGZ.js → chunk-PMBXJ3OQ.js} +1 -1
- package/dist/bundle/chunks/chunk-PS2RJNZZ.js +2 -0
- package/dist/bundle/chunks/{chunk-UC76ZOWM.js → chunk-SBOTR4JQ.js} +1 -1
- package/dist/bundle/chunks/chunk-T5ZEIOJ3.js +2 -0
- package/dist/bundle/chunks/{chunk-DMWNBCXJ.js → chunk-TLPMB3FO.js} +1 -1
- package/dist/bundle/chunks/{chunk-XV2V56NQ.js → chunk-YFFU74KY.js} +1 -1
- package/dist/bundle/chunks/{chunk-DAKEIWT3.js → chunk-YNYC232D.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZXFELXJH.js → chunk-YUOBBH7P.js} +1 -1
- package/dist/bundle/chunks/cp-NWITRTH3.js +2 -0
- package/dist/bundle/chunks/du-IFLWEM6M.js +2 -0
- package/dist/bundle/chunks/find-EW6OHRPJ.js +2 -0
- package/dist/bundle/chunks/{flag-coverage-XTIQGK65.js → flag-coverage-PIF5QRO7.js} +1 -1
- package/dist/bundle/chunks/{grep-4AYF3A5J.js → grep-QDFNKAUW.js} +1 -1
- package/dist/bundle/chunks/gzip-HBDKZBIP.js +2 -0
- package/dist/bundle/chunks/{js-exec-XKF2B7C3.js → js-exec-IREGAOMH.js} +7 -7
- package/dist/bundle/chunks/js-exec-worker.js +296 -116
- package/dist/bundle/chunks/ln-CEM7GDB5.js +2 -0
- package/dist/bundle/chunks/ls-WJ7EIFVM.js +2 -0
- package/dist/bundle/chunks/mkdir-Z6MMWH3D.js +2 -0
- package/dist/bundle/chunks/mv-E2NFLGRQ.js +2 -0
- package/dist/bundle/chunks/{python3-F5S5TYGS.js → python3-W4UMQJAQ.js} +1 -1
- package/dist/bundle/chunks/readlink-XCFO7YD2.js +2 -0
- package/dist/bundle/chunks/rg-J7XDRV3B.js +2 -0
- package/dist/bundle/chunks/rm-IGPLE632.js +2 -0
- package/dist/bundle/chunks/rmdir-UMUDM2L2.js +2 -0
- package/dist/bundle/chunks/{sleep-PPRBTSVR.js → sleep-25QUPVDK.js} +1 -1
- package/dist/bundle/chunks/split-D4HPO4G5.js +2 -0
- package/dist/bundle/chunks/sqlite3-3HL2ECCQ.js +2 -0
- package/dist/bundle/chunks/{timeout-C6WDYPLV.js → timeout-37GM7IIL.js} +1 -1
- package/dist/bundle/chunks/worker.js +233 -108
- package/dist/bundle/index.cjs +975 -970
- package/dist/bundle/index.js +357 -352
- package/dist/commands/js-exec/js-exec.d.ts +4 -0
- package/dist/commands/worker-bridge/bridge-handler.d.ts +9 -3
- package/dist/commands/worker-bridge/protocol.d.ts +72 -21
- package/dist/commands/worker-bridge/sync-backend.d.ts +3 -0
- package/dist/fs/fs-error.d.ts +43 -0
- package/dist/fs/interface.d.ts +13 -0
- package/dist/fs/mountable-fs/mountable-fs.d.ts +20 -0
- package/dist/fs/overlay-fs/apply.d.ts +15 -1
- package/dist/fs/overlay-fs/index.d.ts +1 -0
- package/dist/fs/overlay-fs/overlay-fs.d.ts +31 -0
- package/dist/fs/overlay-fs/overlay-tree.d.ts +39 -0
- package/dist/fs/path-utils.d.ts +5 -0
- package/dist/fs/vfs-template.d.ts +74 -0
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/interpreter/builtin-dispatch.d.ts +10 -0
- package/dist/interpreter/builtin-manifest.d.ts +273 -0
- package/dist/interpreter/builtins/help.d.ts +6 -0
- package/dist/interpreter/builtins/shopt.d.ts +3 -0
- package/dist/interpreter/helpers/shell-constants.d.ts +0 -20
- package/dist/timers.d.ts +9 -0
- package/package.json +135 -136
- package/vendor/cpython-emscripten/python.cjs +2 -2
- package/dist/bin/chunks/chmod-WYYTXGVB.js +0 -3
- package/dist/bin/chunks/chunk-43E7AR6A.js +0 -3
- package/dist/bin/chunks/chunk-6LDOIBU7.js +0 -9
- package/dist/bin/chunks/chunk-AI7JUA46.js +0 -13
- package/dist/bin/chunks/chunk-GQKQEK5N.js +0 -11
- package/dist/bin/chunks/chunk-JQM3DKCH.js +0 -12
- package/dist/bin/chunks/chunk-OLEQNRKX.js +0 -8
- package/dist/bin/chunks/chunk-PPVF2N6C.js +0 -3
- package/dist/bin/chunks/chunk-WEHA3JFD.js +0 -3
- package/dist/bin/chunks/chunk-YQEKKZTU.js +0 -12
- package/dist/bin/chunks/cp-OMVKM35F.js +0 -3
- package/dist/bin/chunks/du-LUFPVLNW.js +0 -3
- package/dist/bin/chunks/find-AWH2KOY7.js +0 -3
- package/dist/bin/chunks/gzip-FDPA6EKG.js +0 -3
- package/dist/bin/chunks/ln-B35EKC2Q.js +0 -3
- package/dist/bin/chunks/ls-Q6ZZ6SQ2.js +0 -3
- package/dist/bin/chunks/mkdir-74BP5NTG.js +0 -3
- package/dist/bin/chunks/mv-76LAHXFR.js +0 -3
- package/dist/bin/chunks/readlink-EHXJNW62.js +0 -3
- package/dist/bin/chunks/rg-PXNKNIMY.js +0 -3
- package/dist/bin/chunks/rm-TF2NJQIA.js +0 -3
- package/dist/bin/chunks/rmdir-7ZIVFZJX.js +0 -3
- package/dist/bin/chunks/split-ZNNNHKSP.js +0 -3
- package/dist/bin/chunks/sqlite3-KP42NNIY.js +0 -3
- package/dist/bin/shell/chunks/chmod-WYYTXGVB.js +0 -3
- package/dist/bin/shell/chunks/chunk-43E7AR6A.js +0 -3
- package/dist/bin/shell/chunks/chunk-6LDOIBU7.js +0 -9
- package/dist/bin/shell/chunks/chunk-AI7JUA46.js +0 -13
- package/dist/bin/shell/chunks/chunk-GQKQEK5N.js +0 -11
- package/dist/bin/shell/chunks/chunk-JQM3DKCH.js +0 -12
- package/dist/bin/shell/chunks/chunk-OLEQNRKX.js +0 -8
- package/dist/bin/shell/chunks/chunk-PPVF2N6C.js +0 -3
- package/dist/bin/shell/chunks/chunk-WEHA3JFD.js +0 -3
- package/dist/bin/shell/chunks/chunk-YQEKKZTU.js +0 -12
- package/dist/bin/shell/chunks/cp-OMVKM35F.js +0 -3
- package/dist/bin/shell/chunks/du-LUFPVLNW.js +0 -3
- package/dist/bin/shell/chunks/find-AWH2KOY7.js +0 -3
- package/dist/bin/shell/chunks/gzip-FDPA6EKG.js +0 -3
- package/dist/bin/shell/chunks/ln-B35EKC2Q.js +0 -3
- package/dist/bin/shell/chunks/ls-Q6ZZ6SQ2.js +0 -3
- package/dist/bin/shell/chunks/mkdir-74BP5NTG.js +0 -3
- package/dist/bin/shell/chunks/mv-76LAHXFR.js +0 -3
- package/dist/bin/shell/chunks/readlink-EHXJNW62.js +0 -3
- package/dist/bin/shell/chunks/rg-PXNKNIMY.js +0 -3
- package/dist/bin/shell/chunks/rm-TF2NJQIA.js +0 -3
- package/dist/bin/shell/chunks/rmdir-7ZIVFZJX.js +0 -3
- package/dist/bin/shell/chunks/split-ZNNNHKSP.js +0 -3
- package/dist/bin/shell/chunks/sqlite3-KP42NNIY.js +0 -3
- package/dist/bundle/chunks/chmod-WM2JFFQC.js +0 -2
- package/dist/bundle/chunks/chunk-7IJWBG4I.js +0 -2
- package/dist/bundle/chunks/chunk-MLIO3BK2.js +0 -7
- package/dist/bundle/chunks/chunk-PIRTX3D3.js +0 -8
- package/dist/bundle/chunks/chunk-TBVD66LC.js +0 -10
- package/dist/bundle/chunks/chunk-W2Z6LYL6.js +0 -11
- package/dist/bundle/chunks/chunk-WN54B5NQ.js +0 -12
- package/dist/bundle/chunks/chunk-WXPNKIIH.js +0 -2
- package/dist/bundle/chunks/chunk-YJKHREBZ.js +0 -11
- package/dist/bundle/chunks/chunk-YUSFCOM7.js +0 -2
- package/dist/bundle/chunks/cp-2KZIPZJS.js +0 -2
- package/dist/bundle/chunks/du-7AZCLKR6.js +0 -2
- package/dist/bundle/chunks/find-END3EAHV.js +0 -2
- package/dist/bundle/chunks/gzip-RQOBR22H.js +0 -2
- package/dist/bundle/chunks/ln-OPY2ZVGQ.js +0 -2
- package/dist/bundle/chunks/ls-ZPXGZX63.js +0 -2
- package/dist/bundle/chunks/mkdir-WDDKK2P3.js +0 -2
- package/dist/bundle/chunks/mv-ZF6UBVRB.js +0 -2
- package/dist/bundle/chunks/readlink-U5OM5A3M.js +0 -2
- package/dist/bundle/chunks/rg-NAMXBYKS.js +0 -2
- package/dist/bundle/chunks/rm-OAZOF7XI.js +0 -2
- package/dist/bundle/chunks/rmdir-YJKPQVCK.js +0 -2
- package/dist/bundle/chunks/split-JICLAMP6.js +0 -2
- package/dist/bundle/chunks/sqlite3-4EZ4GXVD.js +0 -2
package/dist/bin/shell/shell.js
CHANGED
|
@@ -1,274 +1,290 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire} from"node:module";const require=createRequire(import.meta.url);
|
|
3
|
-
import{a as Dn,b as In,c as jt}from"./chunks/chunk-O2BCKSMK.js";import{a as Nr}from"./chunks/chunk-3PCPQIUD.js";import{c as Qs,e as wa}from"./chunks/chunk-TW2IJRUF.js";import{a as ma,b as ya,c as Qn,d as Kn}from"./chunks/chunk-PPVF2N6C.js";import{a as qt}from"./chunks/chunk-K27FY3ES.js";import{a as Ut,b as Ue,c as Zs}from"./chunks/chunk-MROECM42.js";import{a as Xn,b as ga}from"./chunks/chunk-42AMF6EE.js";import{a as he}from"./chunks/chunk-GA5TPRMF.js";import{a as Ir,b as Or}from"./chunks/chunk-GR4ZHKXI.js";import{a as Cr,b as Ge}from"./chunks/chunk-HWI42GQO.js";import"./chunks/chunk-YERKK5B3.js";import{c as zt,d as Pn}from"./chunks/chunk-I57EACSL.js";import"./chunks/chunk-7JZKVC3F.js";import{a as z,b as _t,c as K,d as Cn,e as Nn,f as Lt,g as Rn}from"./chunks/chunk-43E7AR6A.js";import{a as Bt,b as Ze,c as Qe,d as _e,e as Ve,f as ze,g as U,h as ae,i as Ke,j as Wt,k as Rr,l as P,m as Xe,n as Pe,o as Vt,p as Dr,q as rt}from"./chunks/chunk-FUT3X2GJ.js";import{a as M,c as pn,e as xn,f as Mt,g as Gs}from"./chunks/chunk-CPKBPQ2C.js";import{a as St}from"./chunks/chunk-PBOVSFTJ.js";import{a as st}from"./chunks/chunk-I4IRHQDW.js";import"./chunks/chunk-DN2YCFOR.js";import*as Gf from"node:fs";import*as Zf from"node:path";import*as Qf from"node:readline";var On=[{name:"echo",load:async()=>(await import("./chunks/echo-NYDCCFWB.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-BQ7FQTN5.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-YXCSED2H.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-Q6ZZ6SQ2.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-74BP5NTG.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-7ZIVFZJX.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-TVQAUQOG.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-TF2NJQIA.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-OMVKM35F.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-76LAHXFR.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-B35EKC2Q.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-WYYTXGVB.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-YKLNXWZI.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-EHXJNW62.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-QKVY3SIO.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-UOTUV25D.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-3KLVOCI2.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-LROLDXHH.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-CVU5V66H.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-CVU5V66H.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-CVU5V66H.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-PXNKNIMY.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-4LVDFHIJ.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-KO7ZE3P7.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-HBOCBBJQ.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-JMHDIJXT.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-URDMZCXL.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-42X6363P.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-DWWA3JTW.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-PVFO6FRY.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-CZTQCNOZ.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-4IZRRT7U.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-YEY7X54W.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-IQRKKT7D.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-JPOQORZF.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-CNUK76JL.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-ZNNNHKSP.js")).split},{name:"column",load:async()=>(await import("./chunks/column-AJFK3TWF.js")).column},{name:"join",load:async()=>(await import("./chunks/join-34DX7YK5.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-L4HKV5PD.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-AWH2KOY7.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-C4CRGDXP.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-TPUFCYF6.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-ZGP6NPGS.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-LUFPVLNW.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-2TSVF4W7.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-2TSVF4W7.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-3R4G6HQY.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-3R4G6HQY.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3HAU45KT.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-4AMMXFXL.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-KFTJGQLQ.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-KFTJGQLQ.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-OE52K3TM.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-CFCBBWVH.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-CFCBBWVH.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-V7OTAVU5.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-TQ5KOCNW.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-YXZZCUSQ.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-6MQGVWDY.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-DVFE2GSF.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-YGFHQJKX.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-LF7BTSK5.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-X2EAOGV5.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-NNMDHOCN.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-Z6KAYGDK.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-CATBXX76.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-YGSNBVY3.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-4T64QNLS.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-XUMA42ZC.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-HVIDHJ6M.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-4TPGVSBZ.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-DG4BMYM5.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-2I76DUQL.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-B5HDVKW6.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-2GXD4D5K.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-FDPA6EKG.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-FDPA6EKG.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-FDPA6EKG.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(On.push({name:"tar",load:async()=>(await import("./chunks/tar-7HGZIMZD.js")).tarCommand}),On.push({name:"yq",load:async()=>(await import("./chunks/yq-MYZOS2WN.js")).yqCommand}),On.push({name:"xan",load:async()=>(await import("./chunks/xan-WW53ETXT.js")).xanCommand}),On.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-KP42NNIY.js")).sqlite3Command}));var Ks=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Ks.push({name:"python3",load:async()=>(await import("./chunks/python3-JCJHSX4Z.js")).python3Command}),Ks.push({name:"python",load:async()=>(await import("./chunks/python3-JCJHSX4Z.js")).pythonCommand}));var Xs=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Xs.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-DJQLXWCS.js")).jsExecCommand}),Xs.push({name:"node",load:async()=>(await import("./chunks/js-exec-DJQLXWCS.js")).nodeStubCommand}));var Xf=[{name:"curl",load:async()=>(await import("./chunks/curl-NHNZ46BU.js")).curlCommand}],Ea=new Map;function _r(e){return{name:e.name,async execute(t,n){let r=Ea.get(e.name);if(r||(r=await Ge.runTrustedAsync(()=>e.load()),Ea.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await import("./chunks/flag-coverage-C7PB2MO7.js");s(n.coverage,e.name,t)}return r.execute(t,n)}}}function ba(e){return(e?On.filter(n=>e.includes(n.name)):On).map(_r)}function Sa(){return Xf.map(_r)}function Aa(){return Ks.map(_r)}function va(){return Xs.map(_r)}var ka=new WeakMap,$a=new WeakSet;function Ys(e){let t=ka.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),ka.set(e,t),$a.add(t)),t}function xa(e){return $a.has(e)}var Pa={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,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},Yf={...Pa,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 Js(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?Yf:Pa;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,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 Ca(e){return"load"in e&&typeof e.load=="function"}function Na(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 Ra=Object.freeze(Object.create(null)),Lr=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 P(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new P(`${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 P(`${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 P(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 P(`${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:M(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new P(`${r}: invalid ${t} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new P(`${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!==Ra&&this.fail(new P(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new P(`${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 P(`${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 Xe("",`bash: ${t} aborted
|
|
4
|
-
`)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new
|
|
5
|
-
`))}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=Qn(()=>a({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(Kn(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 P(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function Da(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 Ia(e,t,n="pipeline"){e.relinquishOutput(t,n,Ra)}var hn=new TextEncoder;function Jf(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var vt=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:M(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 Error(`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 Error(`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:M(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:493,mtime:new Date}),t)for(let[r,s]of Object.entries(t))typeof s=="function"?this.writeFileLazy(r,s):Jf(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(t){let n=Cn(t);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,n,r,s){K(t,"write");let i=z(t);this.ensureParentDirs(i);let o=jt(r);this.assertCanAllocate(i,this.contentByteLength(n,o));let a=Dn(n,o);this.setEntry(i,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}writeFileLazy(t,n,r){K(t,"write");let s=z(t);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??420,mtime:r?.mtime??new Date})}async materializeLazy(t,n){let r=await n.lazy(),s=typeof r=="string"?hn.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=jt(n);return In(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return In(n,"binary")}async readFileBuffer(t){K(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:hn.encode(s.content)}return r.content instanceof Uint8Array?r.content:hn.encode(r.content)}async writeFile(t,n,r){this.writeFileSync(t,n,r)}async appendFile(t,n,r){K(t,"append");let s=z(t),i=this.data.get(s);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let o=jt(r),a=this.contentByteLength(n,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let u="content"in l&&l.content instanceof Uint8Array?l.content:hn.encode("content"in l?l.content:"");this.assertCanAllocate(s,u.byteLength+a);let c=Dn(n,o),f=new Uint8Array(u.length+c.length);f.set(u),f.set(c,u.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){K(t,"stat");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`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=hn.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){K(t,"lstat");let n=this.resolveIntermediateSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=hn.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),u=0,c=40;for(;l&&l.type==="symlink"&&u<c;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(s),s=Rn(s,l.target),l=this.data.get(s),u++}if(u>=c)throw new Error(`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,u=40;for(;a&&a.type==="symlink"&&l<u;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(s),s=Rn(s,a.target),a=this.data.get(s),l++}if(l>=u)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return s}async mkdir(t,n){this.mkdirSync(t,n)}mkdirSync(t,n){K(t,"mkdir");let r=z(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let s=Cn(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){K(t,"scandir");let n=z(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);s.add(n),n=Rn(n,r.target),r=this.data.get(n)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(i)){let u=a.slice(i.length),c=u.split("/")[0];c&&!u.includes("/",c.length)&&!o.has(c)&&o.set(c,{name:c,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){K(t,"rm");let r=z(t),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`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 Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of i){let a=Lt(r,o);await this.rm(a,n)}}}this.deleteEntry(r)}async cp(t,n,r){K(t,"cp"),K(n,"cp");let s=z(t),i=z(n),o=this.data.get(s);if(!o)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?o.content.byteLength:hn.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 Error(`EISDIR: is a directory, cp '${t}'`);if(_t(s,i))throw new Error(`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 u=Lt(s,l),c=Lt(i,l);await this.cp(u,c,r)}}}async mv(t,n){K(t,"mv"),K(n,"mv");let r=z(t),s=z(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(i.type==="directory"&&_t(r,s))throw new Error(`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(Lt(r,a),Lt(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 Nn(t,n)}async chmod(t,n){K(t,"chmod");let r=z(t),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);s.mode=n}async symlink(t,n){K(n,"symlink");let r=z(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,n){K(t,"link"),K(n,"link");let r=z(t),s=z(n),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(s))throw new Error(`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){K(t,"readlink");let n=z(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){K(t,"realpath");let n=this.resolvePathWithSymlinks(t);if(!this.data.has(n))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return n}async utimes(t,n,r){K(t,"utimes");let s=z(t),i=this.resolvePathWithSymlinks(s),o=this.data.get(i);if(!o)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);o.mtime=r}};var _a="5.1.0(1)-release",La="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
|
|
3
|
+
import{a as On,b as _n,c as Zt}from"./chunks/chunk-O2BCKSMK.js";import{a as Or}from"./chunks/chunk-3PCPQIUD.js";import{c as ri,e as ko}from"./chunks/chunk-TW2IJRUF.js";import{a as bo,b as So,d as Yn,e as Jn}from"./chunks/chunk-QKJAAJ7J.js";import{a as Gt}from"./chunks/chunk-K27FY3ES.js";import{a as Ht,b as qe,c as ni}from"./chunks/chunk-MROECM42.js";import{a as tr,b as vo}from"./chunks/chunk-42AMF6EE.js";import{a as me}from"./chunks/chunk-GA5TPRMF.js";import{a as Tr,b as Fr}from"./chunks/chunk-GR4ZHKXI.js";import{a as Ir,b as Ze}from"./chunks/chunk-HWI42GQO.js";import"./chunks/chunk-YERKK5B3.js";import{c as qt,d as Nn}from"./chunks/chunk-I57EACSL.js";import"./chunks/chunk-7JZKVC3F.js";import{a as er,b as ht,c as jt,d as Mr,e as U,f as Tt,g as X,h as Rn,i as Dn,j as Ao,k as Ft,l as In}from"./chunks/chunk-HWK7KFGB.js";import{a as Vt,b as Qe,c as Ke,d as Le,e as ze,f as Ue,g as q,h as le,i as Xe,j as zt,k as _r,l as P,m as Ye,n as Ce,o as Ut,p as Lr,q as st}from"./chunks/chunk-FUT3X2GJ.js";import{a as B,c as mn,e as Cn,f as Wt,g as ti}from"./chunks/chunk-CPKBPQ2C.js";import{a as N,c as yn}from"./chunks/chunk-OHFB3M3X.js";import{a as vt}from"./chunks/chunk-PBOVSFTJ.js";import{a as it}from"./chunks/chunk-I4IRHQDW.js";import"./chunks/chunk-DN2YCFOR.js";import*as sd from"node:fs";import*as id from"node:path";import*as ad from"node:readline";var Ln=[{name:"echo",load:async()=>(await import("./chunks/echo-NYDCCFWB.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-BQ7FQTN5.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-YXCSED2H.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-EROTXGTC.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-YJ3SOVRP.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-W5NBOJ7E.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-TVQAUQOG.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-B4LVIG7A.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-TMDR6USI.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-HDNKXPO6.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-XVC53673.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-G2BCCQGF.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-YKLNXWZI.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-ZUIECKQC.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-QKVY3SIO.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-UOTUV25D.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-3KLVOCI2.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-LROLDXHH.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-IHDO3L72.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-IHDO3L72.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-IHDO3L72.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-ODJAYIKX.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-4LVDFHIJ.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-KO7ZE3P7.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-HBOCBBJQ.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-JMHDIJXT.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-URDMZCXL.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-42X6363P.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-DWWA3JTW.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-PVFO6FRY.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-CZTQCNOZ.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-4IZRRT7U.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-YEY7X54W.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-IQRKKT7D.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-JPOQORZF.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-CNUK76JL.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-TVJYLTIJ.js")).split},{name:"column",load:async()=>(await import("./chunks/column-AJFK3TWF.js")).column},{name:"join",load:async()=>(await import("./chunks/join-34DX7YK5.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-L4HKV5PD.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-W2RZWTOF.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-C4CRGDXP.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-TPUFCYF6.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-ZGP6NPGS.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-UKFUX7KM.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-2TSVF4W7.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-2TSVF4W7.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-3R4G6HQY.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-3R4G6HQY.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3HAU45KT.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-4AMMXFXL.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-KFTJGQLQ.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-KFTJGQLQ.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-OE52K3TM.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-CFCBBWVH.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-CFCBBWVH.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-V7OTAVU5.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-TQ5KOCNW.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-YXZZCUSQ.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-6MQGVWDY.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-MOJQBZMY.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-RQOWSWYG.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-LF7BTSK5.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-X2EAOGV5.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-NNMDHOCN.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-Z6KAYGDK.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-CATBXX76.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-YGSNBVY3.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-4T64QNLS.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-XUMA42ZC.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-HVIDHJ6M.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-4TPGVSBZ.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-DG4BMYM5.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-2I76DUQL.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-B5HDVKW6.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-2GXD4D5K.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-WUK63QLL.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-WUK63QLL.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-WUK63QLL.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Ln.push({name:"tar",load:async()=>(await import("./chunks/tar-7HGZIMZD.js")).tarCommand}),Ln.push({name:"yq",load:async()=>(await import("./chunks/yq-MYZOS2WN.js")).yqCommand}),Ln.push({name:"xan",load:async()=>(await import("./chunks/xan-WW53ETXT.js")).xanCommand}),Ln.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-5BGAK7VX.js")).sqlite3Command}));var si=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(si.push({name:"python3",load:async()=>(await import("./chunks/python3-TJ6DCPIA.js")).python3Command}),si.push({name:"python",load:async()=>(await import("./chunks/python3-TJ6DCPIA.js")).pythonCommand}));var ii=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ii.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-BE37X4L2.js")).jsExecCommand}),ii.push({name:"node",load:async()=>(await import("./chunks/js-exec-BE37X4L2.js")).nodeStubCommand}));var ld=[{name:"curl",load:async()=>(await import("./chunks/curl-NHNZ46BU.js")).curlCommand}],xo=new Map;function Br(e){return{name:e.name,async execute(t,n){let r=xo.get(e.name);if(r||(r=await Ze.runTrustedAsync(()=>e.load()),xo.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await import("./chunks/flag-coverage-QJ5ZQKCF.js");s(n.coverage,e.name,t)}return r.execute(t,n)}}}function $o(e){return(e?Ln.filter(n=>e.includes(n.name)):Ln).map(Br)}function Po(){return ld.map(Br)}function Co(){return si.map(Br)}function No(){return ii.map(Br)}var Ro=new WeakMap,Do=new WeakSet;function ai(e){let t=Ro.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),Ro.set(e,t),Do.add(t)),t}function Io(e){return Do.has(e)}var Oo={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,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},ud={...Oo,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 oi(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?ud:Oo;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,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 _o(e){return"load"in e&&typeof e.load=="function"}function Lo(e){let t=null,n=null;return{name:e.name,trusted:e.trusted!==!1,async execute(r,s){if(!t){let a=n;a||(a=e.load().then(o=>(t=o,o)),n=a);try{t=await a}catch(o){throw n===a&&(n=null),o}}let i=t;if(!i)throw new Error(`Failed to load command: ${e.name}`);return i.execute(r,s)}}}var To=Object.freeze(Object.create(null)),Wr=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 P(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new P(`${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 P(`${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,a=t==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>a-i)&&this.fail(new P(t==="commands"?`too many commands executed (>${a}), increase executionLimits.maxCommandCount`:`${r}: ${t} work limit exceeded (${a})`,t==="commands"?"commands":"iterations"));let o=i+n;return t==="commands"?this.commandCount=o:this.workUnits=o,this.countersByKind.set(t,s+n),o}reserveBytes(t,n,r){this.assertUsable();let s=typeof t=="string"?t:"live",i=typeof t=="string"?n:t,a=typeof t=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new P(`${a}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let o=!1;return{release:()=>{if(o)return;o=!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 a=i==="bytes"?n.length:B(n);(!Number.isSafeInteger(s)||s<0||s>a)&&this.fail(new P(`${r}: invalid ${t} accounting`,"output_size"));let o=a-s;return o>this.limits.maxOutputSize-this.outputBytes&&this.fail(new P(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=o,a}accountResult(t,n="execution",r=Number.POSITIVE_INFINITY){let s=t.internalOutputAccounting,i=Math.min(s?.stdout??0,r),a=Math.min(s?.stderr??0,Math.max(0,r-i)),o=this.appendOutput("stdout",t.stdout,n,i,t.stdoutKind==="bytes"||t.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",t.stderr,n,a);return Object.isExtensible(t)?(t.internalOutputAccounting={stdout:o,stderr:l},t):o===0&&l===0?t:{...t,internalOutputAccounting:{stdout:o,stderr:l}}}relinquishOutput(t,n,r){this.assertUsable(),r!==To&&this.fail(new P(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new P(`${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,a=this.depthByKind.get(t)??0;a>=s&&this.fail(new P(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(t,a+1);let o=!1;return{release:()=>{if(o)return;o=!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 Ye("",`bash: ${t} aborted
|
|
4
|
+
`)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new Ye("",`bash: ${t} exceeded execution deadline (${this.limits.maxExecutionTimeMs}ms)
|
|
5
|
+
`))}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,a=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[r]).then(()=>({ok:!0}),o=>({ok:!1,error:o})),new Promise(o=>{i=Yn(()=>o({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(Jn(i),!a.ok&&(t.push(a.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 P(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function Fo(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 Mo(e,t,n="pipeline"){e.relinquishOutput(t,n,To)}var gn=new TextEncoder;function cd(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var kt=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:B(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 N("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 a=this.wouldReleaseBytes(r),o=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(o>this.maxTotalBytes-this.retainedBytes+a)throw new N("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+=o-a,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:B(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:ht,mtime:new Date}),t)for(let[r,s]of Object.entries(t))typeof s=="function"?this.writeFileLazy(r,s):cd(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(t){let n=Rn(t);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:ht,mtime:new Date})))}writeFileSync(t,n,r,s){X(t,"write");let i=U(t);this.ensureParentDirs(i);let a=Zt(r);this.assertCanAllocate(i,this.contentByteLength(n,a));let o=On(n,a);this.setEntry(i,{type:"file",content:o,mode:s?.mode??jt,mtime:s?.mtime??new Date})}writeFileLazy(t,n,r){X(t,"write");let s=U(t);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??jt,mtime:r?.mtime??new Date})}async materializeLazy(t,n){let r=await n.lazy(),s=typeof r=="string"?gn.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=Zt(n);return _n(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return _n(n,"binary")}async readFileBuffer(t){X(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new N("ENOENT",`no such file or directory, open '${t}'`);if(r.type!=="file")throw new N("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:gn.encode(s.content)}return r.content instanceof Uint8Array?r.content:gn.encode(r.content)}async writeFile(t,n,r){this.writeFileSync(t,n,r)}async appendFile(t,n,r){X(t,"append");let s=U(t),i=this.data.get(s);if(i&&i.type==="directory")throw new N("EISDIR",`illegal operation on a directory, write '${t}'`);let a=Zt(r),o=this.contentByteLength(n,a);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let u="content"in l&&l.content instanceof Uint8Array?l.content:gn.encode("content"in l?l.content:"");this.assertCanAllocate(s,u.byteLength+o);let c=On(n,a),f=new Uint8Array(u.length+c.length);f.set(u),f.set(c,u.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){X(t,"stat");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new N("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=gn.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){X(t,"lstat");let n=this.resolveIntermediateSymlinks(t),r=this.data.get(n);if(!r)throw new N("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=gn.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=U(t);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let a=0;a<r.length-1;a++){let o=r[a];s=`${s}/${o}`;let l=this.data.get(s),u=0,c=er;for(;l&&l.type==="symlink"&&u<c;){if(i.has(s))throw new N("ELOOP",`too many levels of symbolic links, lstat '${t}'`);i.add(s),s=In(s,l.target),l=this.data.get(s),u++}if(u>=c)throw new N("ELOOP",`too many levels of symbolic links, lstat '${t}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let n=U(t);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let a of r){s=`${s}/${a}`;let o=this.data.get(s),l=0,u=er;for(;o&&o.type==="symlink"&&l<u;){if(i.has(s))throw new N("ELOOP",`too many levels of symbolic links, open '${t}'`);i.add(s),s=In(s,o.target),o=this.data.get(s),l++}if(l>=u)throw new N("ELOOP",`too many levels of symbolic links, open '${t}'`)}return s}async mkdir(t,n){this.mkdirSync(t,n)}mkdirSync(t,n){X(t,"mkdir");let r=U(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new N("EEXIST",`file already exists, mkdir '${t}'`);if(!n?.recursive)throw new N("EEXIST",`directory already exists, mkdir '${t}'`);return}let s=Rn(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new N("ENOENT",`no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:ht,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){X(t,"scandir");let n=U(t),r=this.data.get(n);if(!r)throw new N("ENOENT",`no such file or directory, scandir '${t}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new N("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(n),n=In(n,r.target),r=this.data.get(n)}if(!r)throw new N("ENOENT",`no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new N("ENOTDIR",`not a directory, scandir '${t}'`);let i=n==="/"?"/":`${n}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==n&&o.startsWith(i)){let u=o.slice(i.length),c=u.split("/")[0];c&&!u.includes("/",c.length)&&!a.has(c)&&a.set(c,{name:c,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(a.values()).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0)}async rm(t,n){X(t,"rm");let r=U(t),s=this.data.get(r);if(!s){if(n?.force)return;throw new N("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 N("ENOTEMPTY",`directory not empty, rm '${t}'`);for(let a of i){let o=Ft(r,a);await this.rm(o,n)}}}this.deleteEntry(r)}async cp(t,n,r){X(t,"cp"),X(n,"cp");let s=U(t),i=U(n),a=this.data.get(s);if(!a)throw new N("ENOENT",`no such file or directory, cp '${t}'`);if(a.type==="file")if(this.ensureParentDirs(i),"content"in a){let o=a.content instanceof Uint8Array?a.content.byteLength:gn.encode(a.content).byteLength;this.assertCanAllocate(i,o);let l=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.setEntry(i,{...a,content:l})}else this.setEntry(i,{...a});else if(a.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type==="directory"){if(!r?.recursive)throw new N("EISDIR",`is a directory, cp '${t}'`);if(Tt(s,i))throw new N("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(s);for(let l of o){let u=Ft(s,l),c=Ft(i,l);await this.cp(u,c,r)}}}async mv(t,n){X(t,"mv"),X(n,"mv");let r=U(t),s=U(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new N("ENOENT",`no such file or directory, mv '${t}'`);if(i.type==="directory"&&Tt(r,s))throw new N("EINVAL",`cannot move '${t}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let a=await this.readdir(r);for(let o of a)await this.mv(Ft(r,o),Ft(s,o));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 Dn(t,n)}async chmod(t,n){X(t,"chmod");let r=U(t),s=this.data.get(r);if(!s)throw new N("ENOENT",`no such file or directory, chmod '${t}'`);s.mode=n}async symlink(t,n){X(n,"symlink");let r=U(n);if(this.data.has(r))throw new N("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:Mr,mtime:new Date})}async link(t,n){X(t,"link"),X(n,"link");let r=U(t),s=U(n),i=this.data.get(r);if(!i)throw new N("ENOENT",`no such file or directory, link '${t}'`);if(i.type!=="file")throw new N("EPERM",`operation not permitted, link '${t}'`);if(this.data.has(s))throw new N("EEXIST",`file already exists, link '${n}'`);let a=i;"lazy"in a&&(a=await this.materializeLazy(r,a)),this.ensureParentDirs(s);let o={type:"file",content:a.content,mode:a.mode,mtime:a.mtime};this.entryIdentities.set(o,this.identityFor(a)),this.setEntry(s,o)}async readlink(t){X(t,"readlink");let n=U(t),r=this.data.get(n);if(!r)throw new N("ENOENT",`no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new N("EINVAL",`invalid argument, readlink '${t}'`);return r.target}async realpath(t){X(t,"realpath");let n=this.resolvePathWithSymlinks(t);if(!this.data.has(n))throw new N("ENOENT",`no such file or directory, realpath '${t}'`);return n}async utimes(t,n,r){X(t,"utimes");let s=U(t),i=this.resolvePathWithSymlinks(s),a=this.data.get(i);if(!a)throw new N("ENOENT",`no such file or directory, utimes '${t}'`);a.mtime=r}};var Wo="5.1.0(1)-release",Vo="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function li(e){let{pid:t,ppid:n,uid:r,gid:s}=e;return`Name: bash
|
|
6
6
|
State: R (running)
|
|
7
7
|
Pid: ${t}
|
|
8
8
|
PPid: ${n}
|
|
9
9
|
Uid: ${r} ${r} ${r} ${r}
|
|
10
10
|
Gid: ${s} ${s} ${s} ${s}
|
|
11
|
-
`}function
|
|
11
|
+
`}function fd(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function dd(e,t){e.mkdirSync("/bin",{recursive:!0}),e.mkdirSync("/usr/bin",{recursive:!0}),t&&(e.mkdirSync("/home/user",{recursive:!0}),e.mkdirSync("/tmp",{recursive:!0}))}function pd(e){e.mkdirSync("/dev",{recursive:!0}),e.mkdirSync("/dev/fd",{recursive:!0}),e.writeFileSync("/dev/null",""),e.writeFileSync("/dev/zero",new Uint8Array(0)),e.writeFileSync("/dev/stdin",""),e.writeFileSync("/dev/stdout",""),e.writeFileSync("/dev/stderr","")}function hd(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${Vo}
|
|
12
12
|
`),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
|
|
13
|
-
`),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>ti(t)):e.writeFileSync("/proc/self/status",ti(t)),e.writeFileSync("/proc/self/fd/0","/dev/stdin"),e.writeFileSync("/proc/self/fd/1","/dev/stdout"),e.writeFileSync("/proc/self/fd/2","/dev/stderr")}function Ta(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){ed(e)&&(td(e,t),nd(e),rd(e,n))}function Fa(e){let t={commands:new Set,definedFunctions:new Set,definedAliases:new Set};return ni(e,t),{commands:[...t.commands],definedFunctions:t.definedFunctions,definedAliases:t.definedAliases}}function sd(e){return e.parts.length===1&&e.parts[0].type==="Literal"?e.parts[0].value:null}function id(e,t){for(let n of e){let r=n.parts[0];if(r?.type!=="Literal")continue;let s=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.value);s&&t.definedAliases.add(s[1])}}function ni(e,t){for(let n of e.statements)kt(n,t)}function kt(e,t){for(let n of e.pipelines)od(n,t)}function od(e,t){for(let n of e.commands)Ma(n,t)}function Ma(e,t){switch(e.type){case"SimpleCommand":if(e.name){let n=sd(e.name);n&&(t.commands.add(n),n==="alias"&&id(e.args,t)),Te(e.name.parts,t)}for(let n of e.args)Te(n.parts,t);for(let n of e.assignments)if(n.value&&Te(n.value.parts,t),n.array)for(let r of n.array)Te(r.parts,t);for(let n of e.redirections)n.target.type==="Word"?Te(n.target.parts,t):n.target.type==="HereDoc"&&!n.target.quoted&&Te(n.target.content.parts,t);break;case"If":for(let n of e.clauses){for(let r of n.condition)kt(r,t);for(let r of n.body)kt(r,t)}if(e.elseBody)for(let n of e.elseBody)kt(n,t);break;case"For":if(e.words)for(let n of e.words)Te(n.parts,t);for(let n of e.body)kt(n,t);break;case"CStyleFor":for(let n of e.body)kt(n,t);break;case"While":case"Until":for(let n of e.condition)kt(n,t);for(let n of e.body)kt(n,t);break;case"Case":Te(e.word.parts,t);for(let n of e.items)for(let r of n.body)kt(r,t);break;case"Subshell":case"Group":for(let n of e.body)kt(n,t);break;case"ArithmeticCommand":case"ConditionalCommand":break;case"FunctionDef":t.definedFunctions.add(e.name),Ma(e.body,t);break}}function Te(e,t){for(let n of e)switch(n.type){case"CommandSubstitution":ni(n.body,t);break;case"ProcessSubstitution":ni(n.body,t);break;case"DoubleQuoted":Te(n.parts,t);break;case"ParameterExpansion":n.operation&&Ba(n.operation,t);break}}function Ba(e,t){switch(e.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":Te(e.word.parts,t);break;case"ErrorIfUnset":e.word&&Te(e.word.parts,t);break;case"PatternRemoval":Te(e.pattern.parts,t);break;case"PatternReplacement":Te(e.pattern.parts,t),e.replacement&&Te(e.replacement.parts,t);break;case"CaseModification":e.pattern&&Te(e.pattern.parts,t);break;case"Indirection":e.innerOp&&Ba(e.innerOp,t);break}}function Fr(e,t){return e===`/bin/${t}`||e===`/usr/bin/${t}`}async function Mr(e,t,n){if(t.includes("/")){let o=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(o))return{error:"not_found",path:o};try{let a=await e.fs.stat(o);if(a.isDirectory)return{error:"permission_denied",path:o};let l=o.split("/").pop()||t,u=e.commands.get(l);return u&&Fr(o,l)?{cmd:u,path:o}:(a.mode&73)!==0?{script:!0,path:o}:{error:"permission_denied",path:o}}catch{return{error:"not_found",path:o}}}if(!n&&e.state.hashTable){let o=e.state.hashTable.get(t);if(o){try{let a=await e.fs.stat(o);if(!a.isDirectory){let l=e.commands.get(t);if(l&&Fr(o,t))return{cmd:l,path:o};if((a.mode&73)!==0)return{script:!0,path:o}}}catch{}e.state.hashTable.delete(t)}}let s=(n??e.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let o of s){if(!o)continue;let l=`${o.startsWith("/")?o:e.fs.resolvePath(e.state.cwd,o)}/${t}`;if(await e.fs.exists(l))try{let u=await e.fs.stat(l);if(u.isDirectory)continue;let c=(u.mode&73)!==0,f=e.commands.get(t),d=Fr(l,t);if(f&&d)return{cmd:f,path:l};if(c){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await e.fs.exists("/usr/bin")){let o=e.commands.get(t);if(o)return{cmd:o,path:`/usr/bin/${t}`}}return null}async function Br(e,t){let n=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let o=await e.fs.stat(i);o.isDirectory||(o.mode&73)!==0&&n.push(t)}catch{}return n}let s=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let i of s){if(!i)continue;let a=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(Fr(a,t)&&e.commands.has(t)){n.push(a);continue}if(await e.fs.exists(a)){try{let l=await e.fs.stat(a);if(l.isDirectory||(l.mode&73)===0)continue}catch{continue}n.push(i.startsWith("/")?a:`${i}/${t}`)}}return n}function Fe(e){return{kind:e.kind,elements:new Map(e.elements)}}function it(e){return new Map(Array.from(e??[],([t,n])=>[t,Fe(n)]))}function ve(e,t){return e.state.arrays?.get(t)}function Yn(e,t,n="indexed"){e.state.arrays??=new Map;let r=e.state.arrays.get(t);return r||(r={kind:n,elements:new Map},e.state.arrays.set(t,r)),r}function Ht(e,t,n){let r=Yn(e,t,n);return r.kind=n,r}function Ce(e,t){return e.state.arrays?.has(t)??!1}function oe(e,t,n){return ve(e,t)?.elements.get(String(n))}function Gt(e,t,n){return ve(e,t)?.elements.has(String(n))??!1}function q(e,t,n,r,s){let i=Yn(e,t,s),o=String(n);if(!i.elements.has(o)&&i.elements.size>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(M(r)>e.limits.maxStringLength)throw new P(`array value string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");i.elements.set(o,r)}function yn(e,t,n,r=!1){let s=new Set(r?[]:ve(e,t)?.elements.keys()??[]);for(let i of n)if(s.add(String(i)),s.size>e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements")}function gn(e,t,n){return ve(e,t)?.elements.delete(String(n))??!1}function Jn(e,t){e.state.arrays?.delete(t),e.state.associativeArrays?.delete(t)}function be(e,t){return Array.from(ve(e,t)?.elements.keys()??[]).filter(r=>/^(0|[1-9]\d*)$/.test(r)).map(Number).sort((r,s)=>r-s)}function ye(e,t){Yn(e,t,e.state.associativeArrays?.has(t)?"associative":"indexed").elements.clear()}function $t(e,t){return Array.from(ve(e,t)?.elements.keys()??[]).sort()}function Wr(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function ri(e){if(e.parts.length<2)return null;let t=e.parts[0],n=e.parts[1];if(t.type!=="Glob"||!t.pattern.startsWith("["))return null;let r,s=n,i=1;if(n.type==="Literal"&&n.value.startsWith("]")){let f=n.value.slice(1);if(f.startsWith("+=")||f.startsWith("="))r=t.pattern.slice(1);else if(f===""){if(e.parts.length<3)return null;let d=e.parts[2];if(d.type!=="Literal"||!d.value.startsWith("=")&&!d.value.startsWith("+="))return null;r=t.pattern.slice(1),s=d,i=2}else return null}else if(t.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(e.parts.length<3)return null;let f=e.parts[2];if(f.type!=="Literal"||!f.value.startsWith("]=")&&!f.value.startsWith("]+="))return null;if(n.type==="SingleQuoted")r=n.value;else{r="";for(let d of n.parts)(d.type==="Literal"||d.type==="Escaped")&&(r+=d.value)}s=f,i=2}else if(t.pattern.endsWith("]")){if(n.type!=="Literal"||!n.value.startsWith("=")&&!n.value.startsWith("+="))return null;r=t.pattern.slice(1,-1)}else return null;r=Wr(r);let o;if(s.type!=="Literal")return null;s.value.startsWith("]=")||s.value.startsWith("]+=")?o=s.value.slice(1):o=s.value;let a=o.startsWith("+=");if(!a&&!o.startsWith("="))return null;let l=[],u=a?2:1,c=o.slice(u);c&&l.push({type:"Literal",value:c});for(let f=i+1;f<e.parts.length;f++){let d=e.parts[f];d.type==="BraceExpansion"?l.push({type:"Literal",value:ad(d)}):l.push(d)}return{key:r,valueParts:l,append:a}}function ad(e){return`{${e.items.map(n=>{if(n.type==="Range"){let r=n.startStr??String(n.start),s=n.endStr??String(n.end),i=`${r}..${s}`;return n.step&&(i+=`..${n.step}`),i}return _n(n.word)}).join(",")}}`}function _n(e){let t="";for(let n of e.parts)switch(n.type){case"Literal":t+=n.value;break;case"Glob":t+=n.pattern;break;case"SingleQuoted":t+=n.value;break;case"DoubleQuoted":for(let r of n.parts)(r.type==="Literal"||r.type==="Escaped")&&(t+=r.value);break;case"Escaped":t+=n.value;break;case"BraceExpansion":t+="{",t+=n.items.map(r=>r.type==="Range"?`${r.startStr}..${r.endStr}${r.step?`..${r.step}`:""}`:_n(r.word)).join(","),t+="}";break;case"TildeExpansion":t+="~",n.user&&(t+=n.user);break}return t}var er=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function Wa(e){return er.has(e)}var si=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),Zt=new Set([":","true","false","cd","export","unset","exit","local","set","break","continue","return","eval","shift","getopts","compgen","complete","compopt","pushd","popd","dirs","source",".","read","mapfile","readarray","declare","typeset","readonly","let","command","shopt","exec","test","[","echo","printf","pwd","alias","unalias","type","hash","ulimit","umask","trap","times","wait","kill","jobs","fg","bg","disown","suspend","fc","history","help","enable","builtin","caller"]),Va=new Set(["bg","caller","disown","enable","fc","fg","jobs","kill","suspend","times","trap","ulimit","umask"]);var ld=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],ud=["braceexpand","hashall","interactive-comments"];function ii(e){let t=[],n=[...ud.map(r=>({name:r,enabled:!0})),...ld.map(r=>({name:r,enabled:e[r]}))].sort((r,s)=>r.name.localeCompare(s.name));for(let r of n)r.enabled&&t.push(r.name);return t.join(":")}function Ln(e){e.state.env.set("SHELLOPTS",ii(e.state.options))}var cd=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function oi(e){let t=[];for(let n of cd)e[n]&&t.push(n);return t.join(":")}function ai(e){e.state.env.set("BASHOPTS",oi(e.state.shoptOptions))}var T={script(e){return{type:"Script",statements:e}},statement(e,t=[],n=!1,r,s){let i={type:"Statement",pipelines:e,operators:t,background:n};return r&&(i.deferredError=r),s!==void 0&&(i.sourceText=s),i},pipeline(e,t=!1,n=!1,r=!1,s){return{type:"Pipeline",commands:e,negated:t,timed:n,timePosix:r,pipeStderr:s}},simpleCommand(e,t=[],n=[],r=[]){return{type:"SimpleCommand",name:e,args:t,assignments:n,redirections:r}},word(e){return{type:"Word",parts:e}},literal(e){return{type:"Literal",value:e}},singleQuoted(e){return{type:"SingleQuoted",value:e}},doubleQuoted(e){return{type:"DoubleQuoted",parts:e}},escaped(e){return{type:"Escaped",value:e}},parameterExpansion(e,t=null){return{type:"ParameterExpansion",parameter:e,operation:t}},commandSubstitution(e,t=!1){return{type:"CommandSubstitution",body:e,legacy:t}},arithmeticExpansion(e){return{type:"ArithmeticExpansion",expression:e}},processSubstitution(e,t){return{type:"ProcessSubstitution",body:e,direction:t}},assignment(e,t,n=!1,r=null){return{type:"Assignment",name:e,value:t,append:n,array:r}},redirection(e,t,n=null,r){let s={type:"Redirection",fd:n,operator:e,target:t};return r&&(s.fdVariable=r),s},hereDoc(e,t,n=!1,r=!1,s){let i={type:"HereDoc",delimiter:e,content:t,stripTabs:n,quoted:r};return s!==void 0&&(i.terminated=s),i},ifNode(e,t=null,n=[]){return{type:"If",clauses:e,elseBody:t,redirections:n}},forNode(e,t,n,r=[]){return{type:"For",variable:e,words:t,body:n,redirections:r}},whileNode(e,t,n=[]){return{type:"While",condition:e,body:t,redirections:n}},untilNode(e,t,n=[]){return{type:"Until",condition:e,body:t,redirections:n}},caseNode(e,t,n=[]){return{type:"Case",word:e,items:t,redirections:n}},caseItem(e,t,n=";;"){return{type:"CaseItem",patterns:e,body:t,terminator:n}},subshell(e,t=[]){return{type:"Subshell",body:e,redirections:t}},group(e,t=[]){return{type:"Group",body:e,redirections:t}},functionDef(e,t,n=[],r){return{type:"FunctionDef",name:e,body:t,redirections:n,sourceFile:r}},conditionalCommand(e,t=[],n){return{type:"ConditionalCommand",expression:e,redirections:t,line:n}},arithmeticCommand(e,t=[],n){return{type:"ArithmeticCommand",expression:e,redirections:t,line:n}}};function za(e,t){let n=e.length,r=t+3,s=2,i=!1,o=!1;for(;r<n&&s>0;){let a=e[r];if(i){a==="'"&&(i=!1),r++;continue}if(o){if(a==="\\"){r+=2;continue}a==='"'&&(o=!1),r++;continue}if(a==="'"){i=!0,r++;continue}if(a==='"'){o=!0,r++;continue}if(a==="\\"){r+=2;continue}if(a==="("){s++,r++;continue}if(a===")"){if(s--,s===1){let l=r+1;return!(l<n&&e[l]===")")}if(s===0)return!1;r++;continue}if(s===1&&(a==="|"&&r+1<n&&e[r+1]==="|"||a==="&"&&r+1<n&&e[r+1]==="&"||a==="|"&&r+1<n&&e[r+1]!=="|"))return!0;r++}return!1}function Vr(e,t){let n="",r=t,s=0,i=!1,o,a=l=>l===" "||l===" "||l===`
|
|
14
|
-
`||l===";"||l==="&"||l==="|"||l==="<"||l===">"||l==="("||l===")";for(;r<e.length;){let l=e[r];if(l==="'"){let u=s>0;for(u||(i=!0),u&&(n+=l),r++;r<e.length&&e[r]!=="'";)n+=e[r],r++;r<e.length?(u&&(n+=e[r]),r++):
|
|
13
|
+
`),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>li(t)):e.writeFileSync("/proc/self/status",li(t)),e.writeFileSync("/proc/self/fd/0","/dev/stdin"),e.writeFileSync("/proc/self/fd/1","/dev/stdout"),e.writeFileSync("/proc/self/fd/2","/dev/stderr")}function zo(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){fd(e)&&(dd(e,t),pd(e),hd(e,n))}var ui={export:{kind:"handler",phase:"early"},unset:{kind:"handler",phase:"early"},exit:{kind:"handler",phase:"early"},local:{kind:"handler",phase:"early"},set:{kind:"handler",phase:"early"},break:{kind:"handler",phase:"early"},continue:{kind:"handler",phase:"early"},return:{kind:"handler",phase:"early"},shift:{kind:"handler",phase:"early"},getopts:{kind:"handler",phase:"early"},compgen:{kind:"handler",phase:"early"},complete:{kind:"handler",phase:"early"},compopt:{kind:"handler",phase:"early"},pushd:{kind:"handler",phase:"early"},popd:{kind:"handler",phase:"early"},dirs:{kind:"handler",phase:"early"},source:{kind:"handler",phase:"early"},".":{kind:"handler",phase:"early"},read:{kind:"handler",phase:"early"},mapfile:{kind:"handler",phase:"early"},readarray:{kind:"handler",phase:"early"},declare:{kind:"handler",phase:"early"},typeset:{kind:"handler",phase:"early"},readonly:{kind:"handler",phase:"early"},eval:{kind:"handler",phase:"late",posixEarly:!0},cd:{kind:"handler",phase:"late"},":":{kind:"handler",phase:"late"},true:{kind:"handler",phase:"late"},false:{kind:"handler",phase:"late"},let:{kind:"handler",phase:"late"},command:{kind:"handler",phase:"late"},builtin:{kind:"handler",phase:"late"},shopt:{kind:"handler",phase:"late"},exec:{kind:"handler",phase:"late"},wait:{kind:"handler",phase:"late"},type:{kind:"handler",phase:"late"},hash:{kind:"handler",phase:"late"},help:{kind:"handler",phase:"late"},"[":{kind:"handler",phase:"late"},test:{kind:"handler",phase:"late"},echo:{kind:"registry"},printf:{kind:"registry"},pwd:{kind:"registry"},alias:{kind:"registry"},unalias:{kind:"registry"},history:{kind:"registry"},bg:{kind:"unimplemented"},caller:{kind:"unimplemented"},disown:{kind:"unimplemented"},enable:{kind:"unimplemented"},fc:{kind:"unimplemented"},fg:{kind:"unimplemented"},jobs:{kind:"unimplemented"},kill:{kind:"unimplemented"},suspend:{kind:"unimplemented"},times:{kind:"unimplemented"},trap:{kind:"unimplemented"},ulimit:{kind:"unimplemented"},umask:{kind:"unimplemented"}};for(let e of Object.values(ui))Object.freeze(e);Object.freeze(ui);var ci=ui,xt=new Set(Object.keys(ci)),Uo=new Set(Object.entries(ci).filter(([,e])=>e.kind==="unimplemented").map(([e])=>e)),Vr=ci;function qo(e){let t=Object.hasOwn(Vr,e)?Vr[e]:void 0;return t?.kind==="handler"?t.phase:void 0}function jo(e){let t=Object.hasOwn(Vr,e)?Vr[e]:void 0;return t?.kind==="handler"&&t.posixEarly===!0}function Ho(e){let t={commands:new Set,definedFunctions:new Set,definedAliases:new Set};return fi(e,t),{commands:[...t.commands],definedFunctions:t.definedFunctions,definedAliases:t.definedAliases}}function md(e){return e.parts.length===1&&e.parts[0].type==="Literal"?e.parts[0].value:null}function yd(e,t){for(let n of e){let r=n.parts[0];if(r?.type!=="Literal")continue;let s=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.value);s&&t.definedAliases.add(s[1])}}function fi(e,t){for(let n of e.statements)$t(n,t)}function $t(e,t){for(let n of e.pipelines)gd(n,t)}function gd(e,t){for(let n of e.commands)Go(n,t)}function Go(e,t){switch(e.type){case"SimpleCommand":if(e.name){let n=md(e.name);n&&(t.commands.add(n),n==="alias"&&yd(e.args,t)),Fe(e.name.parts,t)}for(let n of e.args)Fe(n.parts,t);for(let n of e.assignments)if(n.value&&Fe(n.value.parts,t),n.array)for(let r of n.array)Fe(r.parts,t);for(let n of e.redirections)n.target.type==="Word"?Fe(n.target.parts,t):n.target.type==="HereDoc"&&!n.target.quoted&&Fe(n.target.content.parts,t);break;case"If":for(let n of e.clauses){for(let r of n.condition)$t(r,t);for(let r of n.body)$t(r,t)}if(e.elseBody)for(let n of e.elseBody)$t(n,t);break;case"For":if(e.words)for(let n of e.words)Fe(n.parts,t);for(let n of e.body)$t(n,t);break;case"CStyleFor":for(let n of e.body)$t(n,t);break;case"While":case"Until":for(let n of e.condition)$t(n,t);for(let n of e.body)$t(n,t);break;case"Case":Fe(e.word.parts,t);for(let n of e.items)for(let r of n.body)$t(r,t);break;case"Subshell":case"Group":for(let n of e.body)$t(n,t);break;case"ArithmeticCommand":case"ConditionalCommand":break;case"FunctionDef":t.definedFunctions.add(e.name),Go(e.body,t);break}}function Fe(e,t){for(let n of e)switch(n.type){case"CommandSubstitution":fi(n.body,t);break;case"ProcessSubstitution":fi(n.body,t);break;case"DoubleQuoted":Fe(n.parts,t);break;case"ParameterExpansion":n.operation&&Zo(n.operation,t);break}}function Zo(e,t){switch(e.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":Fe(e.word.parts,t);break;case"ErrorIfUnset":e.word&&Fe(e.word.parts,t);break;case"PatternRemoval":Fe(e.pattern.parts,t);break;case"PatternReplacement":Fe(e.pattern.parts,t),e.replacement&&Fe(e.replacement.parts,t);break;case"CaseModification":e.pattern&&Fe(e.pattern.parts,t);break;case"Indirection":e.innerOp&&Zo(e.innerOp,t);break}}function zr(e,t){return e===`/bin/${t}`||e===`/usr/bin/${t}`}async function Ur(e,t,n){if(t.includes("/")){let a=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(a))return{error:"not_found",path:a};try{let o=await e.fs.stat(a);if(o.isDirectory)return{error:"permission_denied",path:a};let l=a.split("/").pop()||t,u=e.commands.get(l);return u&&zr(a,l)?{cmd:u,path:a}:(o.mode&73)!==0?{script:!0,path:a}:{error:"permission_denied",path:a}}catch{return{error:"not_found",path:a}}}if(!n&&e.state.hashTable){let a=e.state.hashTable.get(t);if(a){try{let o=await e.fs.stat(a);if(!o.isDirectory){let l=e.commands.get(t);if(l&&zr(a,t))return{cmd:l,path:a};if((o.mode&73)!==0)return{script:!0,path:a}}}catch{}e.state.hashTable.delete(t)}}let s=(n??e.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let a of s){if(!a)continue;let l=`${a.startsWith("/")?a:e.fs.resolvePath(e.state.cwd,a)}/${t}`;if(await e.fs.exists(l))try{let u=await e.fs.stat(l);if(u.isDirectory)continue;let c=(u.mode&73)!==0,f=e.commands.get(t),d=zr(l,t);if(f&&d)return{cmd:f,path:l};if(c){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await e.fs.exists("/usr/bin")){let a=e.commands.get(t);if(a)return{cmd:a,path:`/usr/bin/${t}`}}return null}async function qr(e,t){let n=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let a=await e.fs.stat(i);a.isDirectory||(a.mode&73)!==0&&n.push(t)}catch{}return n}let s=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let i of s){if(!i)continue;let o=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(zr(o,t)&&e.commands.has(t)){n.push(o);continue}if(await e.fs.exists(o)){try{let l=await e.fs.stat(o);if(l.isDirectory||(l.mode&73)===0)continue}catch{continue}n.push(i.startsWith("/")?o:`${i}/${t}`)}}return n}function Me(e){return{kind:e.kind,elements:new Map(e.elements)}}function at(e){return new Map(Array.from(e??[],([t,n])=>[t,Me(n)]))}function ke(e,t){return e.state.arrays?.get(t)}function nr(e,t,n="indexed"){e.state.arrays??=new Map;let r=e.state.arrays.get(t);return r||(r={kind:n,elements:new Map},e.state.arrays.set(t,r)),r}function Qt(e,t,n){let r=nr(e,t,n);return r.kind=n,r}function Ne(e,t){return e.state.arrays?.has(t)??!1}function oe(e,t,n){return ke(e,t)?.elements.get(String(n))}function Kt(e,t,n){return ke(e,t)?.elements.has(String(n))??!1}function j(e,t,n,r,s){let i=nr(e,t,s),a=String(n);if(!i.elements.has(a)&&i.elements.size>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(r)>e.limits.maxStringLength)throw new P(`array value string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");i.elements.set(a,r)}function wn(e,t,n,r=!1){let s=new Set(r?[]:ke(e,t)?.elements.keys()??[]);for(let i of n)if(s.add(String(i)),s.size>e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements")}function En(e,t,n){return ke(e,t)?.elements.delete(String(n))??!1}function rr(e,t){e.state.arrays?.delete(t),e.state.associativeArrays?.delete(t)}function Se(e,t){return Array.from(ke(e,t)?.elements.keys()??[]).filter(r=>/^(0|[1-9]\d*)$/.test(r)).map(Number).sort((r,s)=>r-s)}function ge(e,t){nr(e,t,e.state.associativeArrays?.has(t)?"associative":"indexed").elements.clear()}function Pt(e,t){return Array.from(ke(e,t)?.elements.keys()??[]).sort()}function jr(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function di(e){if(e.parts.length<2)return null;let t=e.parts[0],n=e.parts[1];if(t.type!=="Glob"||!t.pattern.startsWith("["))return null;let r,s=n,i=1;if(n.type==="Literal"&&n.value.startsWith("]")){let f=n.value.slice(1);if(f.startsWith("+=")||f.startsWith("="))r=t.pattern.slice(1);else if(f===""){if(e.parts.length<3)return null;let d=e.parts[2];if(d.type!=="Literal"||!d.value.startsWith("=")&&!d.value.startsWith("+="))return null;r=t.pattern.slice(1),s=d,i=2}else return null}else if(t.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(e.parts.length<3)return null;let f=e.parts[2];if(f.type!=="Literal"||!f.value.startsWith("]=")&&!f.value.startsWith("]+="))return null;if(n.type==="SingleQuoted")r=n.value;else{r="";for(let d of n.parts)(d.type==="Literal"||d.type==="Escaped")&&(r+=d.value)}s=f,i=2}else if(t.pattern.endsWith("]")){if(n.type!=="Literal"||!n.value.startsWith("=")&&!n.value.startsWith("+="))return null;r=t.pattern.slice(1,-1)}else return null;r=jr(r);let a;if(s.type!=="Literal")return null;s.value.startsWith("]=")||s.value.startsWith("]+=")?a=s.value.slice(1):a=s.value;let o=a.startsWith("+=");if(!o&&!a.startsWith("="))return null;let l=[],u=o?2:1,c=a.slice(u);c&&l.push({type:"Literal",value:c});for(let f=i+1;f<e.parts.length;f++){let d=e.parts[f];d.type==="BraceExpansion"?l.push({type:"Literal",value:wd(d)}):l.push(d)}return{key:r,valueParts:l,append:o}}function wd(e){return`{${e.items.map(n=>{if(n.type==="Range"){let r=n.startStr??String(n.start),s=n.endStr??String(n.end),i=`${r}..${s}`;return n.step&&(i+=`..${n.step}`),i}return Tn(n.word)}).join(",")}}`}function Tn(e){let t="";for(let n of e.parts)switch(n.type){case"Literal":t+=n.value;break;case"Glob":t+=n.pattern;break;case"SingleQuoted":t+=n.value;break;case"DoubleQuoted":for(let r of n.parts)(r.type==="Literal"||r.type==="Escaped")&&(t+=r.value);break;case"Escaped":t+=n.value;break;case"BraceExpansion":t+="{",t+=n.items.map(r=>r.type==="Range"?`${r.startStr}..${r.endStr}${r.step?`..${r.step}`:""}`:Tn(r.word)).join(","),t+="}";break;case"TildeExpansion":t+="~",n.user&&(t+=n.user);break}return t}var sr=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function Qo(e){return sr.has(e)}var ir=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]);var Ed=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],bd=["braceexpand","hashall","interactive-comments"];function pi(e){let t=[],n=[...bd.map(r=>({name:r,enabled:!0})),...Ed.map(r=>({name:r,enabled:e[r]}))].sort((r,s)=>r.name.localeCompare(s.name));for(let r of n)r.enabled&&t.push(r.name);return t.join(":")}function Fn(e){e.state.env.set("SHELLOPTS",pi(e.state.options))}var Sd=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function hi(e){let t=[];for(let n of Sd)e[n]&&t.push(n);return t.join(":")}function mi(e){e.state.env.set("BASHOPTS",hi(e.state.shoptOptions))}var F={script(e){return{type:"Script",statements:e}},statement(e,t=[],n=!1,r,s){let i={type:"Statement",pipelines:e,operators:t,background:n};return r&&(i.deferredError=r),s!==void 0&&(i.sourceText=s),i},pipeline(e,t=!1,n=!1,r=!1,s){return{type:"Pipeline",commands:e,negated:t,timed:n,timePosix:r,pipeStderr:s}},simpleCommand(e,t=[],n=[],r=[]){return{type:"SimpleCommand",name:e,args:t,assignments:n,redirections:r}},word(e){return{type:"Word",parts:e}},literal(e){return{type:"Literal",value:e}},singleQuoted(e){return{type:"SingleQuoted",value:e}},doubleQuoted(e){return{type:"DoubleQuoted",parts:e}},escaped(e){return{type:"Escaped",value:e}},parameterExpansion(e,t=null){return{type:"ParameterExpansion",parameter:e,operation:t}},commandSubstitution(e,t=!1){return{type:"CommandSubstitution",body:e,legacy:t}},arithmeticExpansion(e){return{type:"ArithmeticExpansion",expression:e}},processSubstitution(e,t){return{type:"ProcessSubstitution",body:e,direction:t}},assignment(e,t,n=!1,r=null){return{type:"Assignment",name:e,value:t,append:n,array:r}},redirection(e,t,n=null,r){let s={type:"Redirection",fd:n,operator:e,target:t};return r&&(s.fdVariable=r),s},hereDoc(e,t,n=!1,r=!1,s){let i={type:"HereDoc",delimiter:e,content:t,stripTabs:n,quoted:r};return s!==void 0&&(i.terminated=s),i},ifNode(e,t=null,n=[]){return{type:"If",clauses:e,elseBody:t,redirections:n}},forNode(e,t,n,r=[]){return{type:"For",variable:e,words:t,body:n,redirections:r}},whileNode(e,t,n=[]){return{type:"While",condition:e,body:t,redirections:n}},untilNode(e,t,n=[]){return{type:"Until",condition:e,body:t,redirections:n}},caseNode(e,t,n=[]){return{type:"Case",word:e,items:t,redirections:n}},caseItem(e,t,n=";;"){return{type:"CaseItem",patterns:e,body:t,terminator:n}},subshell(e,t=[]){return{type:"Subshell",body:e,redirections:t}},group(e,t=[]){return{type:"Group",body:e,redirections:t}},functionDef(e,t,n=[],r){return{type:"FunctionDef",name:e,body:t,redirections:n,sourceFile:r}},conditionalCommand(e,t=[],n){return{type:"ConditionalCommand",expression:e,redirections:t,line:n}},arithmeticCommand(e,t=[],n){return{type:"ArithmeticCommand",expression:e,redirections:t,line:n}}};function Ko(e,t){let n=e.length,r=t+3,s=2,i=!1,a=!1;for(;r<n&&s>0;){let o=e[r];if(i){o==="'"&&(i=!1),r++;continue}if(a){if(o==="\\"){r+=2;continue}o==='"'&&(a=!1),r++;continue}if(o==="'"){i=!0,r++;continue}if(o==='"'){a=!0,r++;continue}if(o==="\\"){r+=2;continue}if(o==="("){s++,r++;continue}if(o===")"){if(s--,s===1){let l=r+1;return!(l<n&&e[l]===")")}if(s===0)return!1;r++;continue}if(s===1&&(o==="|"&&r+1<n&&e[r+1]==="|"||o==="&"&&r+1<n&&e[r+1]==="&"||o==="|"&&r+1<n&&e[r+1]!=="|"))return!0;r++}return!1}function Hr(e,t){let n="",r=t,s=0,i=!1,a,o=l=>l===" "||l===" "||l===`
|
|
14
|
+
`||l===";"||l==="&"||l==="|"||l==="<"||l===">"||l==="("||l===")";for(;r<e.length;){let l=e[r];if(l==="'"){let u=s>0;for(u||(i=!0),u&&(n+=l),r++;r<e.length&&e[r]!=="'";)n+=e[r],r++;r<e.length?(u&&(n+=e[r]),r++):a=l;continue}if(l==='"'){let u=s>0;for(u||(i=!0),u&&(n+=l),r++;r<e.length&&e[r]!=='"';){if(e[r]==="\\"&&r+1<e.length){if(u){n+=e.slice(r,r+2),r+=2;continue}let c=e[r+1];if(c==="$"||c==="`"||c==='"'||c==="\\"||c===`
|
|
15
15
|
`){r+=2,c!==`
|
|
16
|
-
`&&(n+=c);continue}}n+=e[r],r++}r<e.length?(u&&(n+=e[r]),r++):
|
|
17
|
-
`&&(n+=u),r+=2;continue}if(s===0&&(l==="$"||l==="<"||l===">")&&e[r+1]==="("){n+=`${l}(`,s=1,r+=2;continue}if(s===0&&
|
|
18
|
-
`,r);
|
|
19
|
-
`&&c.length>0){let p=
|
|
16
|
+
`&&(n+=c);continue}}n+=e[r],r++}r<e.length?(u&&(n+=e[r]),r++):a=l;continue}if(l==="\\"&&r+1<e.length){if(s>0){n+=e.slice(r,r+2),r+=2;continue}i=!0;let u=e[r+1];u!==`
|
|
17
|
+
`&&(n+=u),r+=2;continue}if(s===0&&(l==="$"||l==="<"||l===">")&&e[r+1]==="("){n+=`${l}(`,s=1,r+=2;continue}if(s===0&&o(l))break;s>0&&(l==="("?s++:l===")"&&s--),n+=l,r++}return{delim:n,endPos:r,quoted:i,unclosedQuote:a,unclosedSubstitution:s>0}}function Ad(e,t,n){let r=t+1;for(let{delim:s,stripTabs:i}of n)for(;;){if(r>=e.length)return e.length;let a=e.indexOf(`
|
|
18
|
+
`,r);a===-1&&(a=e.length);let o=e.slice(r,a);if(i&&(o=o.replace(/^\t+/,"")),o===s){r=a+1;break}if(a>=e.length)return e.length;r=a+1}return Math.min(r,e.length)}function Xo(e,t,n){let r=1,s=t,i=!1,a=!1,o=0,l=!1,u="",c=[],f=0;for(;s<e.length&&r>0;){let d=e[s];if(i)d==="'"&&(i=!1);else if(a)d==="\\"&&s+1<e.length?s++:d==='"'&&(a=!1);else{if(d==="("&&e[s+1]==="("?f++:d===")"&&e[s+1]===")"&&f>0&&f--,f===0&&d==="<"&&e[s+1]==="<"&&e[s+2]!=="<"){let p=s+2,h=!1;for(e[p]==="-"&&(h=!0,p++);e[p]===" "||e[p]===" ";)p++;let{delim:m,endPos:E,unclosedQuote:S,unclosedSubstitution:g}=Hr(e,p);if(S&&n(`unexpected EOF while looking for matching \`${S}'`),g&&n("unexpected EOF while looking for matching `)'"),m.length>0){c.push({delim:m,stripTabs:h}),u="",s=E;continue}}if(d===`
|
|
19
|
+
`&&c.length>0){let p=Ad(e,s,c);c.length=0,u="",s=p;continue}d==="'"?(i=!0,u=""):d==='"'?(a=!0,u=""):d==="\\"&&s+1<e.length?(s++,u=""):/[a-zA-Z_]/.test(d)?u+=d:(u==="case"?(o++,l=!1):u==="in"&&o>0?l=!0:u==="esac"&&o>0&&(o--,l=!1),u="",d==="("?s>0&&e[s-1]==="$"?r++:l||r++:d===")"?l?l=!1:r--:d===";"&&o>0&&s+1<e.length&&e[s+1]===";"&&(l=!0))}r>0&&s++}return r>0&&n("unexpected EOF while looking for matching `)'"),s}function Yo(e,t,n,r){let s=t+2,i=Xo(e,s,r),a=e.slice(s,i),l=n().parse(a);return{part:F.commandSubstitution(l,!1),endIndex:i+1}}function Jo(e,t,n,r){let s=e[t]==="<"?"input":"output",i=t+2,a=Xo(e,i,r),o=n().parse(e.slice(i,a));return{part:F.processSubstitution(o,s),endIndex:a+1}}function el(e,t,n,r,s){let a=t+1,o="";for(;a<e.length&&e[a]!=="`";)if(e[a]==="\\"){let c=e[a+1];c==="$"||c==="`"||c==="\\"||c===`
|
|
20
20
|
`||n&&c==='"'?(c!==`
|
|
21
|
-
`&&(
|
|
22
|
-
`||e===";"||e==="&"||e==="|"||e==="("||e===")"||e==="<"||e===">"}var
|
|
23
|
-
`)r+=2,i++,s=1;else break}this.pos=r,this.column=s,this.line=i}nextToken(){let t=this.input,n=this.pos,r=this.line,s=this.column,i=t[n],
|
|
21
|
+
`&&(o+=c),a+=2):(o+=e[a],a++)}else o+=e[a],a++;a>=e.length&&s("unexpected EOF while looking for matching ``'");let u=r().parse(o);return{part:F.commandSubstitution(u,!0),endIndex:a+1}}var vd=10485760,w;(function(e){e.EOF="EOF",e.NEWLINE="NEWLINE",e.SEMICOLON="SEMICOLON",e.AMP="AMP",e.PIPE="PIPE",e.PIPE_AMP="PIPE_AMP",e.AND_AND="AND_AND",e.OR_OR="OR_OR",e.BANG="BANG",e.LESS="LESS",e.GREAT="GREAT",e.DLESS="DLESS",e.DGREAT="DGREAT",e.LESSAND="LESSAND",e.GREATAND="GREATAND",e.LESSGREAT="LESSGREAT",e.DLESSDASH="DLESSDASH",e.CLOBBER="CLOBBER",e.TLESS="TLESS",e.AND_GREAT="AND_GREAT",e.AND_DGREAT="AND_DGREAT",e.LPAREN="LPAREN",e.RPAREN="RPAREN",e.LBRACE="LBRACE",e.RBRACE="RBRACE",e.DSEMI="DSEMI",e.SEMI_AND="SEMI_AND",e.SEMI_SEMI_AND="SEMI_SEMI_AND",e.DBRACK_START="DBRACK_START",e.DBRACK_END="DBRACK_END",e.DPAREN_START="DPAREN_START",e.DPAREN_END="DPAREN_END",e.IF="IF",e.THEN="THEN",e.ELSE="ELSE",e.ELIF="ELIF",e.FI="FI",e.FOR="FOR",e.WHILE="WHILE",e.UNTIL="UNTIL",e.DO="DO",e.DONE="DONE",e.CASE="CASE",e.ESAC="ESAC",e.IN="IN",e.FUNCTION="FUNCTION",e.SELECT="SELECT",e.TIME="TIME",e.COPROC="COPROC",e.WORD="WORD",e.NAME="NAME",e.NUMBER="NUMBER",e.ASSIGNMENT_WORD="ASSIGNMENT_WORD",e.FD_VARIABLE="FD_VARIABLE",e.COMMENT="COMMENT",e.HEREDOC_CONTENT="HEREDOC_CONTENT"})(w||(w={}));var Je=class extends Error{line;column;constructor(t,n,r){super(`line ${n}: ${t}`),this.line=n,this.column=r,this.name="LexerError"}},yi=new Map([["if",w.IF],["then",w.THEN],["else",w.ELSE],["elif",w.ELIF],["fi",w.FI],["for",w.FOR],["while",w.WHILE],["until",w.UNTIL],["do",w.DO],["done",w.DONE],["case",w.CASE],["esac",w.ESAC],["in",w.IN],["function",w.FUNCTION],["select",w.SELECT],["time",w.TIME],["coproc",w.COPROC]]),kd=new Set(yi.values());function gi(e){return kd.has(e)}function tl(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return!1;let n=e.slice(t[0].length);if(n===""||n==="+")return!0;if(n[0]==="["){let r=0,s=0;for(;s<n.length;s++)if(n[s]==="[")r++;else if(n[s]==="]"&&(r--,r===0))break;if(r!==0||s>=n.length)return!1;let i=n.slice(s+1);return i===""||i==="+"}return!1}function nl(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="[")t++;else if(r==="]")t--;else{if(t===0&&r==="=")return n;if(t===0&&r==="+"&&e[n+1]==="=")return n+1}}return-1}var xd=[[";",";","&",w.SEMI_SEMI_AND],["<","<","<",w.TLESS],["&",">",">",w.AND_DGREAT]],$d=[["[","[",w.DBRACK_START],["]","]",w.DBRACK_END],["(","(",w.DPAREN_START],[")",")",w.DPAREN_END],["&","&",w.AND_AND],["|","|",w.OR_OR],[";",";",w.DSEMI],[";","&",w.SEMI_AND],["|","&",w.PIPE_AMP],[">",">",w.DGREAT],["<","&",w.LESSAND],[">","&",w.GREATAND],["<",">",w.LESSGREAT],[">","|",w.CLOBBER],["&",">",w.AND_GREAT]],Pd=new Map([["|",w.PIPE],["&",w.AMP],[";",w.SEMICOLON],["(",w.LPAREN],[")",w.RPAREN],["<",w.LESS],[">",w.GREAT]]);function Cd(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function rl(e){return e===" "||e===" "||e===`
|
|
22
|
+
`||e===";"||e==="&"||e==="|"||e==="("||e===")"||e==="<"||e===">"}var Gr=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];pendingHeredocDelimiterMode;dparenDepth=0;maxHeredocSize;constructor(t,n){this.input=t,this.maxHeredocSize=n?.maxHeredocSize??vd}tokenize(){let n=this.input.length,r=this.tokens,s=this.pendingHeredocs;for(;this.pos<n;){if(s.length>0&&r.length>0&&r[r.length-1].type===w.NEWLINE){this.readHeredocContent();continue}if(this.skipWhitespace(),this.pos>=n)break;let i=this.nextToken();i&&r.push(i)}return s.length>0&&this.readHeredocContent(),r.push({type:w.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),r}skipWhitespace(){let t=this.input,n=t.length,r=this.pos,s=this.column,i=this.line;for(;r<n;){let a=t[r];if(a===" "||a===" ")r++,s++;else if(a==="\\"&&t[r+1]===`
|
|
23
|
+
`)r+=2,i++,s=1;else break}this.pos=r,this.column=s,this.line=i}nextToken(){let t=this.input,n=this.pos,r=this.line,s=this.column,i=t[n],a=t[n+1],o=t[n+2],l=this.pendingHeredocDelimiterMode;if(this.pendingHeredocDelimiterMode=void 0,l!==void 0&&i!==`
|
|
24
24
|
`&&!(i==="#"&&this.dparenDepth===0))return this.readHeredocDelimiterToken(n,r,s,l);if(i==="#"&&this.dparenDepth===0)return this.readComment(n,r,s);if(i===`
|
|
25
25
|
`)return this.pos=n+1,this.line++,this.column=1,{type:w.NEWLINE,value:`
|
|
26
|
-
`,start:n,end:n+1,line:r,column:s};if(i==="<"&&
|
|
27
|
-
`&&p!==";"&&p!=="&"&&p!=="|"&&p!=="("&&p!==")"&&p!=="<"&&p!==">")break}return this.pos=n+2,this.column=s+2,this.makeToken(d,c+f,n,r,s)}if(i==="("&&this.dparenDepth>0)return this.pos=n+1,this.column=s+1,this.dparenDepth++,this.makeToken(w.LPAREN,"(",n,r,s);if(i===")"&&this.dparenDepth>1)return this.pos=n+1,this.column=s+1,this.dparenDepth--,this.makeToken(w.RPAREN,")",n,r,s);let u=
|
|
28
|
-
`?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(w.LBRACE,"{",n,r,s))}return i==="}"?this.isWordCharFollowing(n+1)?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(w.RBRACE,"}",n,r,s)):i==="!"?
|
|
26
|
+
`,start:n,end:n+1,line:r,column:s};if(i==="<"&&a==="<"&&o==="-")return this.pos=n+3,this.column=s+3,this.pendingHeredocDelimiterMode=!0,this.makeToken(w.DLESSDASH,"<<-",n,r,s);for(let[c,f,d,p]of xd)if(i===c&&a===f&&o===d)return this.pos=n+3,this.column=s+3,this.makeToken(p,c+f+d,n,r,s);if(i==="<"&&a==="<")return this.pos=n+2,this.column=s+2,this.pendingHeredocDelimiterMode=!1,this.makeToken(w.DLESS,"<<",n,r,s);if(i==="("&&a==="("){let c=this.tokens[this.tokens.length-1];return this.dparenDepth===0&&c?.end===n&&(c.type===w.LESS||c.type===w.GREAT)?(this.pos=n+1,this.column=s+1,this.makeToken(w.LPAREN,"(",n,r,s)):this.dparenDepth>0?(this.pos=n+1,this.column=s+1,this.dparenDepth++,this.makeToken(w.LPAREN,"(",n,r,s)):this.looksLikeNestedSubshells(n+2)||this.dparenClosesWithSpacedParens(n+2)?(this.pos=n+1,this.column=s+1,this.makeToken(w.LPAREN,"(",n,r,s)):(this.pos=n+2,this.column=s+2,this.dparenDepth=1,this.makeToken(w.DPAREN_START,"((",n,r,s))}if(i===")"&&a===")")return this.dparenDepth===1?(this.pos=n+2,this.column=s+2,this.dparenDepth=0,this.makeToken(w.DPAREN_END,"))",n,r,s)):this.dparenDepth>1?(this.pos=n+1,this.column=s+1,this.dparenDepth--,this.makeToken(w.RPAREN,")",n,r,s)):(this.pos=n+1,this.column=s+1,this.makeToken(w.RPAREN,")",n,r,s));for(let[c,f,d]of $d)if(!(c==="("&&f==="("||c===")"&&f===")")&&!(this.dparenDepth>0&&c===";"&&(d===w.DSEMI||d===w.SEMI_AND||d===w.SEMI_SEMI_AND))&&i===c&&a===f){if(d===w.DBRACK_START||d===w.DBRACK_END){let p=t[n+2];if(p!==void 0&&p!==" "&&p!==" "&&p!==`
|
|
27
|
+
`&&p!==";"&&p!=="&"&&p!=="|"&&p!=="("&&p!==")"&&p!=="<"&&p!==">")break}return this.pos=n+2,this.column=s+2,this.makeToken(d,c+f,n,r,s)}if(i==="("&&this.dparenDepth>0)return this.pos=n+1,this.column=s+1,this.dparenDepth++,this.makeToken(w.LPAREN,"(",n,r,s);if(i===")"&&this.dparenDepth>1)return this.pos=n+1,this.column=s+1,this.dparenDepth--,this.makeToken(w.RPAREN,")",n,r,s);let u=Pd.get(i);if(u!==void 0)return this.pos=n+1,this.column=s+1,this.makeToken(u,i,n,r,s);if(i==="{"){let c=this.scanFdVariable(n);return c!==null?(this.pos=c.end,this.column=s+(c.end-n),{type:w.FD_VARIABLE,value:c.varname,start:n,end:c.end,line:r,column:s}):a==="}"?(this.pos=n+2,this.column=s+2,{type:w.WORD,value:"{}",start:n,end:n+2,line:r,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(n)!==null?this.readWordWithBraceExpansion(n,r,s):this.scanLiteralBraceWord(n)!==null?this.readWordWithBraceExpansion(n,r,s):a!==void 0&&a!==" "&&a!==" "&&a!==`
|
|
28
|
+
`?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(w.LBRACE,"{",n,r,s))}return i==="}"?this.isWordCharFollowing(n+1)?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(w.RBRACE,"}",n,r,s)):i==="!"?a==="="?(this.pos=n+2,this.column=s+2,this.makeToken(w.WORD,"!=",n,r,s)):(this.pos=n+1,this.column=s+1,this.makeToken(w.BANG,"!",n,r,s)):this.readWord(n,r,s)}looksLikeNestedSubshells(t){let n=this.input,r=n.length,s=t;for(;s<r&&(n[s]===" "||n[s]===" ");)s++;if(s>=r)return!1;let i=n[s];if(i==="(")return this.looksLikeNestedSubshells(s+1);let a=/[a-zA-Z_]/.test(i),o=i==="!"||i==="[";if(!a&&!o)return!1;let l=s;for(;l<r&&/[a-zA-Z0-9_\-.]/.test(n[l]);)l++;if(l===s)return o;let u=l;for(;u<r&&(n[u]===" "||n[u]===" ");)u++;if(u>=r)return!1;let c=n[u];if(c==="="&&n[u+1]!=="="||c===`
|
|
29
29
|
`||l===u&&/[+\-*/%<>&|^!~?:]/.test(c)&&c!=="-"||c===")"&&n[u+1]===")")return!1;if(u>l&&(c==="-"||c==='"'||c==="'"||c==="$"||/[a-zA-Z_/.]/.test(c))){let f=u;for(;f<r&&n[f]!==`
|
|
30
|
-
`;){if(n[f]===")")return!0;f++}return!1}if(c===")"){let f=u+1;for(;f<r&&(n[f]===" "||n[f]===" ");)f++;if(n[f]==="|"&&n[f+1]==="|"||n[f]==="&"&&n[f+1]==="&"||n[f]===";"||n[f]==="|"&&n[f+1]!=="|")return!0}return!1}makeToken(t,n,r,s,i){return{type:t,value:n,start:r,end:this.pos,line:s,column:i}}readComment(t,n,r){let s=this.input,i=s.length,
|
|
31
|
-
`;)
|
|
32
|
-
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"||y==="'"||y==='"'||y==="\\"||y==="$"||y==="`"||y==="{"||y==="}"||y==="~"||y==="*"||y==="?"||y==="[")break;
|
|
33
|
-
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"){let b=s.slice(a
|
|
34
|
-
`)break;c+=y,
|
|
35
|
-
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">")break}if(y==="$"&&
|
|
36
|
-
`){
|
|
30
|
+
`;){if(n[f]===")")return!0;f++}return!1}if(c===")"){let f=u+1;for(;f<r&&(n[f]===" "||n[f]===" ");)f++;if(n[f]==="|"&&n[f+1]==="|"||n[f]==="&"&&n[f+1]==="&"||n[f]===";"||n[f]==="|"&&n[f+1]!=="|")return!0}return!1}makeToken(t,n,r,s,i){return{type:t,value:n,start:r,end:this.pos,line:s,column:i}}readComment(t,n,r){let s=this.input,i=s.length,a=this.pos;for(;a<i&&s[a]!==`
|
|
31
|
+
`;)a++;let o=s.slice(t,a);return this.pos=a,this.column=r+(a-t),{type:w.COMMENT,value:o,start:t,end:a,line:n,column:r}}readWord(t,n,r){let s=this.input,i=s.length,a=this.pos,o=a;for(;a<i;){let y=s[a];if(y===" "||y===" "||y===`
|
|
32
|
+
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"||y==="'"||y==='"'||y==="\\"||y==="$"||y==="`"||y==="{"||y==="}"||y==="~"||y==="*"||y==="?"||y==="[")break;a++}if(a>o){let y=s[a];if(!(y==="("&&a>o&&"@*+?!".includes(s[a-1]))){if(a>=i||y===" "||y===" "||y===`
|
|
33
|
+
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"){let b=s.slice(o,a);this.pos=a,this.column=r+(a-o);let A=yi.get(b);if(A!==void 0)return{type:A,value:b,start:t,end:a,line:n,column:r};let k=nl(b);return k>0&&tl(b.slice(0,k))?{type:w.ASSIGNMENT_WORD,value:b,start:t,end:a,line:n,column:r}:/^[0-9]+$/.test(b)?{type:w.NUMBER,value:b,start:t,end:a,line:n,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)?{type:w.NAME,value:b,start:t,end:a,line:n,column:r,quoted:!1,singleQuoted:!1}:{type:w.WORD,value:b,start:t,end:a,line:n,column:r,quoted:!1,singleQuoted:!1}}}}a=this.pos;let l=this.column,u=this.line,c="",f=!1,d=!1,p=!1,h=!1,m=s[a]==='"'||s[a]==="'",E=!1,S=0;for(;a<i;){let y=s[a];if(!p&&!h){if(y==="("&&c.length>0&&"@*+?!".includes(c[c.length-1])){let b=this.scanExtglobPattern(a);if(b!==null){c+=b.content,a=b.end,l+=b.content.length;continue}}if(y==="["&&S===0){if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){let b=a+1<i?s[a+1]:"";if(b==="^"||b==="!"){c+=y,a++,l++;continue}S=1,c+=y,a++,l++;continue}}else if(y==="["&&S>0){c.length>0&&c[c.length-1]!=="\\"&&S++,c+=y,a++,l++;continue}else if(y==="]"&&S>0){c.length>0&&c[c.length-1]!=="\\"&&S--,c+=y,a++,l++;continue}if(S>0){if(y===`
|
|
34
|
+
`)break;c+=y,a++,l++;continue}if(y===" "||y===" "||y===`
|
|
35
|
+
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">")break}if(y==="$"&&a+1<i&&s[a+1]==="'"&&!p&&!h){for(c+="$'",a+=2,l+=2;a<i&&s[a]!=="'";)s[a]==="\\"&&a+1<i?(c+=s[a]+s[a+1],a+=2,l+=2):(c+=s[a],a++,l++);a<i&&(c+="'",a++,l++);continue}if(y==="$"&&a+1<i&&s[a+1]==='"'&&!p&&!h){a++,l++,h=!0,f=!0,c===""&&(m=!0),a++,l++;continue}if(y==="'"&&!h){if(p)if(p=!1,!m||E)c+=y;else{let b=a+1<i?s[a+1]:"";b&&!rl(b)&&b!=="'"&&(b==='"'?(E=!0,c+=y,d=!1,f=!1):(E=!0,c+=y))}else p=!0,m&&!E?(d=!0,f=!0):c+=y;a++,l++;continue}if(y==='"'&&!p){if(h)if(h=!1,!m||E)c+=y;else{let b=a+1<i?s[a+1]:"";b&&!rl(b)&&b!=='"'&&(b==="'"?(E=!0,c+=y,d=!1,f=!1):(E=!0,c+=y))}else h=!0,m&&!E?f=!0:c+=y;a++,l++;continue}if(y==="\\"&&!p&&a+1<i){let b=s[a+1];if(b===`
|
|
36
|
+
`){a+=2,u++,l=1;continue}if(h){if(b==='"'||b==="\\"||b==="$"||b==="`"||b===`
|
|
37
37
|
`){if(b===`
|
|
38
|
-
`){
|
|
39
|
-
|
|
40
|
-
`,
|
|
41
|
-
`?(u++,l=0):l++,
|
|
42
|
-
`;)
|
|
43
|
-
`&&(u++,l=0,
|
|
44
|
-
`&&(u++,l=0),
|
|
45
|
-
`){
|
|
46
|
-
`&&(u++,l=0),
|
|
47
|
-
`&&(u++,l=0),
|
|
48
|
-
`?(u++,l=1):l++}if(this.pos=
|
|
49
|
-
`;)
|
|
50
|
-
`,this.pos++,this.line++,this.column=1}if((t.stripTabs?u.replace(/^\t+/,""):u)===t.delimiter){
|
|
51
|
-
`&&(this.pos++,this.line++,this.column=1);break}if(i+=l,i+=
|
|
38
|
+
`){a+=2,l=1,u++;continue}c+=y+b,a+=2,l+=2;continue}}else{c+=y+b,a+=2,l+=2;continue}}if(y==="$"&&a+1<i&&s[a+1]==="("&&!p){c+=y,a++,l++,c+=s[a],a++,l++;let b=1,A=!1,k=!1,v=0,$=!1,D="",x=[],C=s[a]==="("&&!this.dollarDparenIsSubshell(a),I=C?1:0;for(;b>0&&a<i;){let W=s[a];if(c+=W,A)W==="'"&&(A=!1);else if(k)W==="\\"&&a+1<i?(c+=s[a+1],a++,l++):W==='"'&&(k=!1);else{if(W==="("&&s[a+1]==="("?I++:W===")"&&s[a+1]===")"&&I>0&&I--,I===0&&W==="<"&&s[a+1]==="<"&&s[a+2]!=="<"){let Z=a+2,R=!1;for(s[Z]==="-"&&(R=!0,Z++);s[Z]===" "||s[Z]===" ";)Z++;let{delim:V,endPos:z,unclosedQuote:O,unclosedSubstitution:_}=Hr(s,Z);if(O)throw new Je(`unexpected EOF while looking for matching \`${O}'`,u,l);if(_)throw new Je("unexpected EOF while looking for matching `)'",u,l);if(V.length>0){c+=s.slice(a+1,z),l+=z-a,x.push({delim:V,stripTabs:R}),a=z;continue}}if(W===`
|
|
39
|
+
`&&x.length>0){u++,l=0;let Z=a+1;for(let{delim:R,stripTabs:V}of x)for(;!(Z>=i);){let z=s.indexOf(`
|
|
40
|
+
`,Z);z===-1&&(z=i);let O=s.slice(Z,z),_=V?O.replace(/^\t+/,""):O;c+=s.slice(Z,Math.min(z+1,i)),z<i&&u++;let M=z>=i;if(Z=z+1,_===R||M)break}x.length=0,l=0,a=Math.min(Z,i);continue}if(W==="'")A=!0,D="";else if(W==='"')k=!0,D="";else if(W==="\\"&&a+1<i)c+=s[a+1],a++,l++,D="";else if(W==="$"&&a+1<i&&s[a+1]==="{"){a++,l++,c+=s[a],a++,l++;let Z=1,R=!1,V=!1;for(;Z>0&&a<i;){let z=s[a];if(z==="\\"&&a+1<i&&!R){c+=z,a++,l++,c+=s[a],a++,l++;continue}c+=z,R?z==="'"&&(R=!1):V?z==='"'&&(V=!1):z==="'"?R=!0:z==='"'?V=!0:z==="{"?Z++:z==="}"&&Z--,z===`
|
|
41
|
+
`?(u++,l=0):l++,a++}D="";continue}else if(W==="#"&&!C&&(D===""||/\s/.test(s[a-1]||""))){for(;a+1<i&&s[a+1]!==`
|
|
42
|
+
`;)a++,l++,c+=s[a];D=""}else/[a-zA-Z_]/.test(W)?D+=W:(D==="case"?(v++,$=!1):D==="in"&&v>0?$=!0:D==="esac"&&v>0&&(v--,$=!1),D="",W==="("?a>0&&s[a-1]==="$"?b++:$||b++:W===")"?$?$=!1:b--:W===";"&&v>0&&(a+1<i&&s[a+1]===";"||a+1<i&&s[a+1]==="&")&&($=!0))}W===`
|
|
43
|
+
`&&(u++,l=0,D=""),a++,l++}continue}if(y==="$"&&a+1<i&&s[a+1]==="["&&!p){c+=y,a++,l++,c+=s[a],a++,l++;let b=1;for(;b>0&&a<i;){let A=s[a];c+=A,A==="["?b++:A==="]"?b--:A===`
|
|
44
|
+
`&&(u++,l=0),a++,l++}continue}if(y==="$"&&a+1<i&&s[a+1]==="{"&&!p){c+=y,a++,l++,c+=s[a],a++,l++;let b=1,A=!1,k=!1,v=u,$=l,D=u,x=l;for(;b>0&&a<i;){let C=s[a];if(C==="\\"&&a+1<i&&s[a+1]===`
|
|
45
|
+
`){a+=2,u++,l=1;continue}if(C==="\\"&&a+1<i&&!A){c+=C,a++,l++,c+=s[a],a++,l++;continue}c+=C,A?C==="'"&&(A=!1):k?C==='"'&&(k=!1):C==="'"?(A=!0,v=u,$=l):C==='"'?(k=!0,D=u,x=l):C==="{"?b++:C==="}"&&b--,C===`
|
|
46
|
+
`&&(u++,l=0),a++,l++}if(A)throw new Je("unexpected EOF while looking for matching `''",v,$);if(k)throw new Je("unexpected EOF while looking for matching `\"'",D,x);continue}if(y==="$"&&a+1<i&&!p){let b=s[a+1];if(b==="#"||b==="?"||b==="$"||b==="!"||b==="@"||b==="*"||b==="-"||b>="0"&&b<="9"){c+=y+b,a+=2,l+=2;continue}}if(y==="`"&&!p){for(c+=y,a++,l++;a<i&&s[a]!=="`";){let b=s[a];c+=b,b==="\\"&&a+1<i&&(c+=s[a+1],a++,l++),b===`
|
|
47
|
+
`&&(u++,l=0),a++,l++}a<i&&(c+=s[a],a++,l++);continue}c+=y,a++,y===`
|
|
48
|
+
`?(u++,l=1):l++}if(this.pos=a,this.column=l,this.line=u,E&&m&&(c=s[t]+c,f=!1,d=!1),p||h){let y=p?"'":'"';throw new Je(`unexpected EOF while looking for matching \`${y}'`,n,r)}if(!m&&c.length>=2){if(c[0]==="'"&&c[c.length-1]==="'"){let y=c.slice(1,-1);!y.includes("'")&&!y.includes('"')&&(c=y,f=!0,d=!0)}else if(c[0]==='"'&&c[c.length-1]==='"'){let y=c.slice(1,-1),b=!1;for(let A=0;A<y.length;A++){if(y[A]==='"'){b=!0;break}y[A]==="\\"&&A+1<y.length&&A++}b||(c=y,f=!0,d=!1)}}if(c==="")return{type:w.WORD,value:"",start:t,end:a,line:n,column:r,quoted:f,singleQuoted:d};let g=yi.get(c);if(!f&&g!==void 0)return{type:g,value:c,start:t,end:a,line:n,column:r};if(!m){let y=nl(c);if(y>0&&tl(c.slice(0,y)))return{type:w.ASSIGNMENT_WORD,value:c,start:t,end:a,line:n,column:r,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(c)?{type:w.NUMBER,value:c,start:t,end:a,line:n,column:r}:Cd(c)?{type:w.NAME,value:c,start:t,end:a,line:n,column:r,quoted:f,singleQuoted:d}:{type:w.WORD,value:c,start:t,end:a,line:n,column:r,quoted:f,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let t=this.pendingHeredocs.shift();if(!t)break;let n=this.pos,r=this.line,s=this.column,i="",a=!1;for(;this.pos<this.input.length;){let o="",l="",u="";for(;;){for(o="";this.pos<this.input.length&&this.input[this.pos]!==`
|
|
49
|
+
`;)o+=this.input[this.pos],this.pos++,this.column++;let f=0;for(let d=o.length-1;o[d]==="\\";d-=1)f+=1;if(u+=o,t.quoted||f%2===0||this.pos+1>=this.input.length)break;u=u.slice(0,-1),l+=`${o}
|
|
50
|
+
`,this.pos++,this.line++,this.column=1}if((t.stripTabs?u.replace(/^\t+/,""):u)===t.delimiter){a=!0,this.pos<this.input.length&&this.input[this.pos]===`
|
|
51
|
+
`&&(this.pos++,this.line++,this.column=1);break}if(i+=l,i+=o,this.pos<this.input.length&&this.input[this.pos]===`
|
|
52
52
|
`?(i+=`
|
|
53
|
-
`,this.pos++,this.line++,this.column=1):
|
|
54
|
-
`),i.length>this.maxHeredocSize)throw new
|
|
55
|
-
`?(f+=1,d=1):d+=1;return this.pos=
|
|
56
|
-
`||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(t,n,r){let s=this.input,i=s.length,
|
|
57
|
-
`||u===";"||u==="&"||u==="|"||u==="("||u===")"||u==="<"||u===">")break;if(u==="{"){if(this.scanBraceExpansion(
|
|
58
|
-
`||l===";"||l==="&"||l==="|")return null;s++}}return i===0&&(o
|
|
59
|
-
`||
|
|
60
|
-
`)return null;s++}}return i===0?{content:n.slice(t,s),end:s}:null}scanFdVariable(t){let n=this.input,r=n.length,s=t+1,i=s;for(;s<r;){let c=n[s];if(s===i){if(!(c>="a"&&c<="z"||c>="A"&&c<="Z"||c==="_"))return null}else if(!(c>="a"&&c<="z"||c>="A"&&c<="Z"||c>="0"&&c<="9"||c==="_"))break;s++}if(s===i)return null;let
|
|
61
|
-
`&&(l=!0),s++;continue}if(
|
|
62
|
-
`&&(l=!0),s++;continue}if(u==="'"){
|
|
53
|
+
`,this.pos++,this.line++,this.column=1):o.length>0&&(i+=`
|
|
54
|
+
`),i.length>this.maxHeredocSize)throw new Je(`Heredoc size limit exceeded (${this.maxHeredocSize} bytes)`,r,s)}this.tokens.push({type:w.HEREDOC_CONTENT,value:i,start:n,end:this.pos,line:r,column:s,heredocTerminated:a})}}readHeredocDelimiterToken(t,n,r,s){let i=this.input,{delim:a,endPos:o,quoted:l,unclosedQuote:u,unclosedSubstitution:c}=Hr(i,t);if(u)throw new Je(`unexpected EOF while looking for matching \`${u}'`,n,r);if(c)throw new Je("unexpected EOF while looking for matching `)'",n,r);if(o===t)throw new Je("Expected here-document delimiter",n,r);let f=n,d=r;for(let p=t;p<o;p++)i[p]===`
|
|
55
|
+
`?(f+=1,d=1):d+=1;return this.pos=o,this.line=f,this.column=d,this.pendingHeredocs.push({delimiter:a,stripTabs:s,quoted:l}),{type:w.WORD,value:i.slice(t,o),start:t,end:o,line:n,column:r,quoted:l,heredocDelimiter:a}}isWordCharFollowing(t){if(t>=this.input.length)return!1;let n=this.input[t];return!(n===" "||n===" "||n===`
|
|
56
|
+
`||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(t,n,r){let s=this.input,i=s.length,a=t,o=r;for(;a<i;){let u=s[a];if(u===" "||u===" "||u===`
|
|
57
|
+
`||u===";"||u==="&"||u==="|"||u==="("||u===")"||u==="<"||u===">")break;if(u==="{"){if(this.scanBraceExpansion(a)!==null){let f=1;for(a++,o++;a<i&&f>0;)s[a]==="{"?f++:s[a]==="}"&&f--,a++,o++;continue}a++,o++;continue}if(u==="}"){a++,o++;continue}if(u==="$"&&a+1<i&&s[a+1]==="("){a++,o++,a++,o++;let c=1;for(;c>0&&a<i;)s[a]==="("?c++:s[a]===")"&&c--,a++,o++;continue}if(u==="$"&&a+1<i&&s[a+1]==="{"){a++,o++,a++,o++;let c=1;for(;c>0&&a<i;)s[a]==="{"?c++:s[a]==="}"&&c--,a++,o++;continue}if(u==="`"){for(a++,o++;a<i&&s[a]!=="`";)s[a]==="\\"&&a+1<i?(a+=2,o+=2):(a++,o++);a<i&&(a++,o++);continue}a++,o++}let l=s.slice(t,a);return this.pos=a,this.column=o,{type:w.WORD,value:l,start:t,end:a,line:n,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(t){let n=this.input,r=n.length,s=t+1,i=1,a=!1,o=!1;for(;s<r&&i>0;){let l=n[s];if(l==="{")i++,s++;else if(l==="}")i--,s++;else if(l===","&&i===1)a=!0,s++;else if(l==="."&&s+1<r&&n[s+1]===".")o=!0,s+=2;else{if(l===" "||l===" "||l===`
|
|
58
|
+
`||l===";"||l==="&"||l==="|")return null;s++}}return i===0&&(a||o)?n.slice(t,s):null}scanLiteralBraceWord(t){let n=this.input,r=n.length,s=t+1,i=1;for(;s<r&&i>0;){let a=n[s];if(a==="{")i++,s++;else if(a==="}"){if(i--,i===0)return n.slice(t,s+1);s++}else{if(a===" "||a===" "||a===`
|
|
59
|
+
`||a===";"||a==="&"||a==="|")return null;s++}}return null}scanExtglobPattern(t){let n=this.input,r=n.length,s=t+1,i=1;for(;s<r&&i>0;){let a=n[s];if(a==="\\"&&s+1<r){s+=2;continue}if("@*+?!".includes(a)&&s+1<r&&n[s+1]==="("){s++,i++,s++;continue}if(a==="(")i++,s++;else if(a===")")i--,s++;else{if(a===`
|
|
60
|
+
`)return null;s++}}return i===0?{content:n.slice(t,s),end:s}:null}scanFdVariable(t){let n=this.input,r=n.length,s=t+1,i=s;for(;s<r;){let c=n[s];if(s===i){if(!(c>="a"&&c<="z"||c>="A"&&c<="Z"||c==="_"))return null}else if(!(c>="a"&&c<="z"||c>="A"&&c<="Z"||c>="0"&&c<="9"||c==="_"))break;s++}if(s===i)return null;let a=n.slice(i,s);if(s>=r||n[s]!=="}"||(s++,s>=r))return null;let o=n[s],l=s+1<r?n[s+1]:"";return o===">"||o==="<"||o==="&"&&(l===">"||l==="<")?{varname:a,end:s}:null}dollarDparenIsSubshell(t){let n=this.input,r=n.length,s=t+1,i=2,a=!1,o=!1,l=!1;for(;s<r&&i>0;){let u=n[s];if(a){u==="'"&&(a=!1),u===`
|
|
61
|
+
`&&(l=!0),s++;continue}if(o){if(u==="\\"){s+=2;continue}u==='"'&&(o=!1),u===`
|
|
62
|
+
`&&(l=!0),s++;continue}if(u==="'"){a=!0,s++;continue}if(u==='"'){o=!0,s++;continue}if(u==="\\"){s+=2;continue}if(u===`
|
|
63
63
|
`&&(l=!0),u==="("){i++,s++;continue}if(u===")"){if(i--,i===1){let c=s+1;if(c<r&&n[c]===")")return!1;let f=c,d=!1;for(;f<r&&(n[f]===" "||n[f]===" "||n[f]===`
|
|
64
|
-
`);)d=!0,f++;if(d&&f<r&&n[f]===")"||l)return!0}if(i===0)return!1;s++;continue}s++}return!1}dparenClosesWithSpacedParens(t){let n=this.input,r=n.length,s=t,i=2,
|
|
65
|
-
`);)f=!0,c++;if(f&&c<r&&n[c]===")")return!0}if(i===0)return!1;s++;continue}if(i===1&&(l==="|"&&s+1<r&&n[s+1]==="|"||l==="&"&&s+1<r&&n[s+1]==="&"||l==="|"&&s+1<r&&n[s+1]!=="|"))return!0;s++}return!1}};var
|
|
66
|
-
`){t+=2;continue}if(/\s/.test(e[t])){t++;continue}break}return t}var
|
|
67
|
-
`;break;case"t":r+=" ";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"'":r+="'";break;default:r+=i}n+=2}else r+=e[n],n++;e[n]==="'"&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function nl(e,t){if(e.slice(t,t+2)!=='$"')return null;let n=t+2,r="";for(;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(r+=e[n+1],n+=2):(r+=e[n],n++);e[n]==='"'&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function Ed(e){let t="",n=0;for(;n<e.length;)if(e[n]==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);n<e.length&&n++}else t+=e[n],n++;return t}function re(e,t){let n=Ed(t),{expr:r,pos:s}=Tn(e,n,0),i=pe(n,s);if(i<n.length){let o=t.slice(i).trim();if(o)return{type:"ArithmeticExpression",originalText:t,expression:{type:"ArithSyntaxError",errorToken:o,message:`${o}: syntax error: invalid arithmetic operator (error token is "${o}")`}}}return{type:"ArithmeticExpression",expression:r,originalText:t}}function qe(e,t){return{expr:{type:"ArithSyntaxError",errorToken:e,message:`syntax error: operand expected (error token is "${e}")`},pos:t}}function je(e,t){return pe(e,t)>=e.length}function Tn(e,t,n){return bd(e,t,n)}function wn(e,t,n){return e.withDepth(()=>Tn(e,t,n))}function bd(e,t,n){let{expr:r,pos:s}=rr(e,t,n);for(s=pe(t,s);t[s]===",";){if(s++,je(t,s))return qe(",",s);let{expr:o,pos:a}=rr(e,t,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=pe(t,a)}return{expr:r,pos:s}}function rr(e,t,n){let{expr:r,pos:s}=Sd(e,t,n);if(s=pe(t,s),t[s]==="?"){s++;let{expr:i,pos:o}=wn(e,t,s);if(s=pe(t,o),t[s]===":"){s++;let{expr:a,pos:l}=wn(e,t,s);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:a},pos:l}}}return{expr:r,pos:s}}function Sd(e,t,n){let{expr:r,pos:s}=rl(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="||";){if(s+=2,je(t,s))return qe("||",s);let{expr:o,pos:a}=rl(e,t,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=a}return{expr:r,pos:s}}function rl(e,t,n){let{expr:r,pos:s}=sl(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="&&";){if(s+=2,je(t,s))return qe("&&",s);let{expr:o,pos:a}=sl(e,t,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=a}return{expr:r,pos:s}}function sl(e,t,n){let{expr:r,pos:s}=il(e,t,n);for(;s=pe(t,s),t[s]==="|"&&t[s+1]!=="|";){if(s++,je(t,s))return qe("|",s);let{expr:o,pos:a}=il(e,t,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=a}return{expr:r,pos:s}}function il(e,t,n){let{expr:r,pos:s}=ol(e,t,n);for(;s=pe(t,s),t[s]==="^";){if(s++,je(t,s))return qe("^",s);let{expr:o,pos:a}=ol(e,t,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=a}return{expr:r,pos:s}}function ol(e,t,n){let{expr:r,pos:s}=al(e,t,n);for(;s=pe(t,s),t[s]==="&"&&t[s+1]!=="&";){if(s++,je(t,s))return qe("&",s);let{expr:o,pos:a}=al(e,t,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=a}return{expr:r,pos:s}}function al(e,t,n){let{expr:r,pos:s}=ll(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="=="||t.slice(s,s+2)==="!=";){let i=t.slice(s,s+2);if(s+=2,je(t,s))return qe(i,s);let{expr:o,pos:a}=ll(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function ll(e,t,n){let{expr:r,pos:s}=fi(e,t,n);for(;;)if(s=pe(t,s),t.slice(s,s+2)==="<="||t.slice(s,s+2)===">="){let i=t.slice(s,s+2);if(s+=2,je(t,s))return qe(i,s);let{expr:o,pos:a}=fi(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else if(t[s]==="<"||t[s]===">"){let i=t[s];if(s++,je(t,s))return qe(i,s);let{expr:o,pos:a}=fi(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function fi(e,t,n){let{expr:r,pos:s}=ul(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="<<"||t.slice(s,s+2)===">>";){let i=t.slice(s,s+2);if(s+=2,je(t,s))return qe(i,s);let{expr:o,pos:a}=ul(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function ul(e,t,n){let{expr:r,pos:s}=cl(e,t,n);for(;s=pe(t,s),(t[s]==="+"||t[s]==="-")&&t[s+1]!==t[s];){let i=t[s];if(s++,je(t,s))return qe(i,s);let{expr:o,pos:a}=cl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function cl(e,t,n){let{expr:r,pos:s}=jr(e,t,n);for(;;)if(s=pe(t,s),t[s]==="*"&&t[s+1]!=="*"){if(s++,je(t,s))return qe("*",s);let{expr:o,pos:a}=jr(e,t,s);r={type:"ArithBinary",operator:"*",left:r,right:o},s=a}else if(t[s]==="/"||t[s]==="%"){let i=t[s];if(s++,je(t,s))return qe(i,s);let{expr:o,pos:a}=jr(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function jr(e,t,n){let{expr:r,pos:s}=di(e,t,n),i=pe(t,s);if(t.slice(i,i+2)==="**"){if(i+=2,je(t,i))return qe("**",i);let{expr:a,pos:l}=e.withDepth(()=>jr(e,t,i));return{expr:{type:"ArithBinary",operator:"**",left:r,right:a},pos:l}}return{expr:r,pos:s}}function di(e,t,n){let r=pe(t,n);if(t.slice(r,r+2)==="++"||t.slice(r,r+2)==="--"){let s=t.slice(r,r+2);r+=2;let{expr:i,pos:o}=e.withDepth(()=>di(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}if(t[r]==="+"||t[r]==="-"||t[r]==="!"||t[r]==="~"){let s=t[r];r++;let{expr:i,pos:o}=e.withDepth(()=>di(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}return vd(e,t,r)}function Ad(e,t){let n=e[t];return n==="$"||n==="`"}function vd(e,t,n){let{expr:r,pos:s}=fl(e,t,n,!1),i=[r];for(;Ad(t,s);){let{expr:a,pos:l}=fl(e,t,s,!0);i.push(a),s=l}i.length>1&&(r={type:"ArithConcat",parts:i});let o;if(t[s]==="["&&r.type==="ArithConcat"){s++;let{expr:a,pos:l}=wn(e,t,s);o=a,s=l,t[s]==="]"&&s++}if(o&&r.type==="ArithConcat"&&(r={type:"ArithDynamicElement",nameExpr:r,subscript:o},o=void 0),s=pe(t,s),r.type==="ArithConcat"||r.type==="ArithVariable"||r.type==="ArithDynamicElement"){for(let a of qr)if(t.slice(s,s+a.length)===a&&t.slice(s,s+a.length+1)!=="=="){s+=a.length;let{expr:l,pos:u}=e.withDepth(()=>rr(e,t,s));return r.type==="ArithDynamicElement"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r.nameExpr,subscript:r.subscript,value:l},pos:u}:r.type==="ArithConcat"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r,value:l},pos:u}:{expr:{type:"ArithAssignment",operator:a,variable:r.name,value:l},pos:u}}}if(t.slice(s,s+2)==="++"||t.slice(s,s+2)==="--"){let a=t.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:a,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function fl(e,t,n,r=!1){let s=pe(t,n),i=el(wn,e,t,s);if(i)return i;let o=tl(t,s);if(o)return o;let a=nl(t,s);if(a)return a;if(t.slice(s,s+2)==="$("&&t[s+2]!=="("){s+=2;let u=1,c=s;for(;s<t.length&&u>0;)t[s]==="("?u++:t[s]===")"&&u--,u>0&&s++;let f=t.slice(c,s);return s++,{expr:{type:"ArithCommandSubst",command:f},pos:s}}if(t[s]==="`"){s++;let u=s;for(;s<t.length&&t[s]!=="`";)s++;let c=t.slice(u,s);return t[s]==="`"&&s++,{expr:{type:"ArithCommandSubst",command:c},pos:s}}if(t[s]==="("){s++;let{expr:u,pos:c}=wn(e,t,s);return s=pe(t,c),t[s]===")"&&s++,{expr:{type:"ArithGroup",expression:u},pos:s}}if(t[s]==="'"){s++;let u="";for(;s<t.length&&t[s]!=="'";)u+=t[s],s++;t[s]==="'"&&s++;let c=Number.parseInt(u,10);return{expr:{type:"ArithSingleQuote",content:u,value:Number.isNaN(c)?0:c},pos:s}}if(t[s]==='"'){s++;let u="";for(;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?(u+=t[s+1],s+=2):(u+=t[s],s++);t[s]==='"'&&s++;let c=u.trim();if(!c)return{expr:{type:"ArithNumber",value:0},pos:s};let{expr:f}=wn(e,c,0);return{expr:f,pos:s}}if(/[0-9]/.test(t[s])){let u="",c=!1,f=!1;for(;s<t.length;){let p=t[s];if(c)if(/[0-9a-zA-Z@_]/.test(p))u+=p,s++;else break;else if(p==="#")c=!0,u+=p,s++;else if(u==="0"&&(p==="x"||p==="X")&&s+1<t.length&&/[0-9a-fA-F]/.test(t[s+1]))f=!0,u+=p,s++;else if(f&&/[0-9a-fA-F]/.test(p))u+=p,s++;else if(!f&&/[0-9]/.test(p))u+=p,s++;else break}if(s<t.length&&/[a-zA-Z_]/.test(t[s])){let p=u;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)p+=t[s],s++;return{expr:{type:"ArithSyntaxError",errorToken:p,message:`${p}: value too great for base (error token is "${p}")`},pos:s}}if(t[s]==="."&&/[0-9]/.test(t[s+1]))throw new ae(`${u}.${t[s+1]}...: syntax error: invalid arithmetic operator`);if(t[s]==="["){let p=t.slice(s).trim();return{expr:{type:"ArithNumberSubscript",number:u,errorToken:p},pos:t.length}}return{expr:{type:"ArithNumber",value:nr(u)},pos:s}}if(t[s]==="$"&&t[s+1]==="{"){let u=s+2,c=1,f=u;for(;f<t.length&&c>0;)t[f]==="{"?c++:t[f]==="}"&&c--,c>0&&f++;let d=t.slice(u,f),p=f+1;if(t[p]==="#"){let h=p+1;for(;h<t.length&&/[0-9a-zA-Z@_]/.test(t[h]);)h++;let m=t.slice(p+1,h);return{expr:{type:"ArithDynamicBase",baseExpr:d,value:m},pos:h}}if(/[0-9]/.test(t[p])||t[p]==="x"||t[p]==="X"){let h=p;if(t[p]==="x"||t[p]==="X")for(h++;h<t.length&&/[0-9a-fA-F]/.test(t[h]);)h++;else for(;h<t.length&&/[0-9]/.test(t[h]);)h++;let m=t.slice(p,h);return{expr:{type:"ArithDynamicNumber",prefix:d,suffix:m},pos:h}}return s=p,{expr:{type:"ArithBracedExpansion",content:d},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[0-9]/.test(t[s+1])){s++;let u="";for(;s<t.length&&/[0-9]/.test(t[s]);)u+=t[s],s++;return{expr:{type:"ArithVariable",name:u,hasDollarPrefix:!0},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[*@#?\-!$]/.test(t[s+1])){let u=t[s+1];return s+=2,{expr:{type:"ArithSpecialVar",name:u},pos:s}}let l=!1;if(t[s]==="$"&&s+1<t.length&&/[a-zA-Z_]/.test(t[s+1])&&(l=!0,s++),s<t.length&&/[a-zA-Z_]/.test(t[s])){let u="";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)u+=t[s],s++;if(t[s]==="["&&!r){s++;let c;if(t[s]==="'"||t[s]==='"'){let d=t[s];for(s++,c="";s<t.length&&t[s]!==d;)c+=t[s],s++;t[s]===d&&s++,s=pe(t,s),t[s]==="]"&&s++}let f;if(c===void 0){let{expr:d,pos:p}=wn(e,t,s);f=d,s=p,t[s]==="]"&&s++}if(s=pe(t,s),t[s]==="["&&f)return{expr:{type:"ArithDoubleSubscript",array:u,index:f},pos:s};if(!r){for(let d of qr)if(t.slice(s,s+d.length)===d&&t.slice(s,s+d.length+1)!=="=="){s+=d.length;let{expr:p,pos:h}=e.withDepth(()=>rr(e,t,s));return{expr:{type:"ArithAssignment",operator:d,variable:u,subscript:f,stringKey:c,value:p},pos:h}}}return{expr:{type:"ArithArrayElement",array:u,index:f,stringKey:c},pos:s}}if(s=pe(t,s),!r){for(let c of qr)if(t.slice(s,s+c.length)===c&&t.slice(s,s+c.length+1)!=="=="){s+=c.length;let{expr:f,pos:d}=e.withDepth(()=>rr(e,t,s));return{expr:{type:"ArithAssignment",operator:c,variable:u,value:f},pos:d}}}return{expr:{type:"ArithVariable",name:u,hasDollarPrefix:l},pos:s}}if(t[s]==="#"){let u=s+1;for(;u<t.length&&t[u]!==`
|
|
68
|
-
`;)u++;let c=t.slice(s,u).trim()||"#";return{expr:{type:"ArithSyntaxError",errorToken:c,message:`${c}: syntax error: invalid arithmetic operator (error token is "${c}")`},pos:t.length}}return{expr:{type:"ArithNumber",value:0},pos:s}}var
|
|
69
|
-
`,s+=2;break;case"t":r+=" ",s+=2;break;case"r":r+="\r",s+=2;break;case"\\":r+="\\",s+=2;break;case"'":r+="'",s+=2;break;case'"':r+='"',s+=2;break;case"a":r+="\x07",s+=2;break;case"b":r+="\b",s+=2;break;case"e":case"E":r+="\x1B",s+=2;break;case"f":r+="\f",s+=2;break;case"v":r+="\v",s+=2;break;case"x":{let a=[],l=s;for(;l+1<t.length&&t[l]==="\\"&&t[l+1]==="x";){let u=t.slice(l+2,l+4),c=parseInt(u,16);if(!Number.isNaN(c)&&u.length>0)a.push(c),l+=2+u.length;else break}a.length>0?(r+=kd(a),s=l):(r+="\\x",s+=2);break}case"u":{let a=t.slice(s+2,s+6),l=parseInt(a,16);Number.isNaN(l)?(r+="\\u",s+=2):(r+=String.fromCharCode(l),s+=6);break}case"c":{if(s+2<t.length){let l=t[s+2].charCodeAt(0)&31;r+=String.fromCharCode(l),s+=3}else r+="\\c",s+=2;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",l=s+1;for(;l<t.length&&l<s+4&&/[0-7]/.test(t[l]);)a+=t[l],l++;let u=parseInt(a,8);r+=String.fromCharCode(u),s=l;break}default:r+=i,s++}else r+=i,s++}return s<t.length&&t[s]==="'"&&s++,{part:T.literal(r),endIndex:s}}function hi(e,t){let n=t.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:re(e,n)}function pl(e){let t=[],n="",r=0;for(let s=0;s<e.length;s++){let i=e[s];i==="{"?(r++,n+=i):i==="}"?(r--,n+=i):i===","&&r===0?(t.push(n),n=""):n+=i}return t.push(n),t}function wl(e,t,n,r){let s=pi(e,t,n,"{","}");if(s===-1)return null;let i=t.slice(n+1,s),o=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(o)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(o[1],10),end:Number.parseInt(o[2],10),step:o[3]?Number.parseInt(o[3],10):void 0,startStr:o[1],endStr:o[2]}]},endIndex:s+1};let a=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:s+1}:i.includes(",")&&r?{part:{type:"BraceExpansion",items:pl(i).map(c=>e.withDepth(()=>({type:"Word",word:T.word(r(e,c,!1,!1,!1))})))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:pl(i).map(c=>({type:"Word",word:T.word([T.literal(c)])}))},endIndex:s+1}:null}function mi(e,t){let n="";for(let r of t.parts)switch(r.type){case"Literal":n+=r.value;break;case"SingleQuoted":n+=`'${r.value}'`;break;case"Escaped":n+=r.value;break;case"DoubleQuoted":n+='"';for(let s of r.parts)s.type==="Literal"||s.type==="Escaped"?n+=s.value:s.type==="ParameterExpansion"&&(n+=`\${${s.parameter}}`);n+='"';break;case"ParameterExpansion":n+=`\${${r.parameter}}`;break;case"Glob":n+=r.pattern;break;case"TildeExpansion":n+="~",r.user&&(n+=r.user);break;case"BraceExpansion":{n+="{";let s=[];for(let i of r.items)if(i.type==="Range"){let o=i.startStr??String(i.start),a=i.endStr??String(i.end);i.step!==void 0?s.push(`${o}..${a}..${i.step}`):s.push(`${o}..${a}`)}else s.push(mi(e,i.word));s.length===1&&r.items[0].type==="Range"?n+=s[0]:n+=s.join(","),n+="}";break}default:n+=r.type}return n}function El(e,t){return{[w.LESS]:"<",[w.GREAT]:">",[w.DGREAT]:">>",[w.LESSAND]:"<&",[w.GREATAND]:">&",[w.LESSGREAT]:"<>",[w.CLOBBER]:">|",[w.TLESS]:"<<<",[w.AND_GREAT]:"&>",[w.AND_DGREAT]:"&>>",[w.DLESS]:"<",[w.DLESSDASH]:"<"}[t]||">"}function sr(e){let t=e.current(),n=t.type;if(n===w.NUMBER){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:Ya.has(r.type)}if(n===w.FD_VARIABLE){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:Ja.has(r.type)}return!e.isProcessSubstitutionStart()&&Xa.has(n)}function Gr(e){let t=null,n;e.check(w.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(w.FD_VARIABLE)&&(n=e.advance().value);let r=e.advance(),s=El(e,r.type);if(r.type===w.DLESS||r.type===w.DLESSDASH)return xd(e,t,n,r.type===w.DLESSDASH);e.isWord()||e.error("Expected redirection target");let i=e.parseWord();return T.redirection(s,i,t,n)}function xd(e,t,n,r){e.isWord()||e.error("Expected here-document delimiter");let s=e.advance(),i=s.heredocDelimiter??s.value,o=s.quoted||!1,a=T.redirection(r?"<<-":"<<",T.hereDoc(i,T.word([]),r,o),t,n);return e.addPendingHeredoc(a,i,r,o),a}function gi(e){let t=e.getSourceLine(),n=[],r=null,s=[],i=[];for(;e.check(w.ASSIGNMENT_WORD)||sr(e);)e.checkIterationLimit(),e.check(w.ASSIGNMENT_WORD)?n.push(Pd(e)):i.push(Gr(e));if(e.isWord())r=e.parseWord();else if(n.length>0&&(e.check(w.DBRACK_START)||e.check(w.DPAREN_START))){let a=e.advance();r=T.word([T.literal(a.value)])}for(;(!e.isStatementEnd()||e.check(w.RBRACE))&&!e.check(w.PIPE,w.PIPE_AMP);)if(e.checkIterationLimit(),sr(e))i.push(Gr(e));else if(e.check(w.ASSIGNMENT_WORD)){let a=e.advance(),l=a.value,u=l.endsWith("="),c=l.endsWith("=(");if((u||c)&&(c||e.check(w.LPAREN))){let f=c?l.slice(0,-2):l.slice(0,-1);c||e.expect(w.LPAREN);let d=yi(e);e.expect(w.RPAREN);let p=d.map(m=>mi(e,m)),h=`${f}=(${p.join(" ")})`;s.push(e.parseWordFromString(h,!1,!1,!0))}else{let f=e.parseWordFromString(l,a.quoted,a.singleQuoted,!0);s.push(e.parseAdjacentWordParts(f.parts,a.end,Ne.Assignment))}}else if(e.isWord())s.push(e.parseWord());else if(e.check(w.RBRACE)){let a=e.advance();s.push(e.parseWordFromString(a.value,!1,!1))}else if(e.check(w.LBRACE)){let a=e.advance();s.push(e.parseWordFromString(a.value,!1,!1))}else if(e.check(w.DBRACK_END)){let a=e.advance();s.push(e.parseWordFromString(a.value,!1,!1))}else if(e.check(w.LPAREN))e.error("syntax error near unexpected token `('");else break;let o=T.simpleCommand(r,s,n,i);return o.line=t,o}function Pd(e){let t=e.expect(w.ASSIGNMENT_WORD),n=t.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||e.error(`Invalid assignment: ${n}`);let s=r[0],i,o=s.length;if(n[o]==="["){let f=0,d=o+1;for(;o<n.length;o++)if(n[o]==="[")f++;else if(n[o]==="]"&&(f--,f===0))break;f!==0&&e.error(`Invalid assignment: ${n}`),i=Hr(n.slice(d,o)),o++}let a=n[o]==="+";a&&o++,n[o]!=="="&&e.error(`Invalid assignment: ${n}`),o++;let l=n.slice(o);if(l==="("){let f=yi(e);e.expect(w.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return T.assignment(d,null,a,f)}if(l===""&&e.check(w.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let d=yi(e);e.expect(w.RPAREN);let p=i!==void 0?`${s}[${i}]`:s;return T.assignment(p,null,a,d)}}let u=l?e.parseWordFromString(l,t.quoted,t.singleQuoted,!0):null;t.end===e.current().start&&e.isProcessSubstitutionStart()&&(u=e.parseAdjacentWordParts(u?.parts??[],t.end,Ne.Assignment));let c=i!==void 0?`${s}[${i}]`:s;return T.assignment(c,u,a,null)}var Cd=new Set([w.AMP,w.PIPE,w.PIPE_AMP,w.SEMICOLON,w.AND_AND,w.OR_OR,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND]);function yi(e){let t=[];for(e.skipNewlines();!e.check(w.RPAREN,w.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):Cd.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function wi(e,t){e.expect(w.IF);let n=[],r=e.parseCompoundList();e.expect(w.THEN);let s=e.parseCompoundList();if(s.length===0){let a=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${a}'`)}for(n.push({condition:r,body:s});e.check(w.ELIF);){e.advance();let a=e.parseCompoundList();e.expect(w.THEN);let l=e.parseCompoundList();if(l.length===0){let u=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${u}'`)}n.push({condition:a,body:l})}let i=null;e.check(w.ELSE)&&(e.advance(),i=e.parseCompoundList(),i.length===0&&e.error("syntax error near unexpected token `fi'")),e.expect(w.FI);let o=t?.skipRedirections?[]:e.parseOptionalRedirections();return T.ifNode(n,i,o)}function Ei(e,t){let n=e.expect(w.FOR);if(e.check(w.DPAREN_START))return Rd(e,t,e.getSourceLine(n));e.isWord()||e.error("Expected variable name in for loop");let s=e.advance().value,i=null;if(e.skipNewlines(),e.check(w.IN))for(e.advance(),i=[];!e.check(w.SEMICOLON,w.NEWLINE,w.DO,w.EOF)&&e.isWord();)i.push(e.parseWord());e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines(),e.expect(w.DO);let o=e.parseCompoundList();e.expect(w.DONE);let a=t?.skipRedirections?[]:e.parseOptionalRedirections();return T.forNode(s,i,o,a)}function Rd(e,t,n){e.expect(w.DPAREN_START);let r=null,s=null,i=null,o=["","",""],a=0,l=0;for(;!e.check(w.DPAREN_END,w.EOF);){let f=e.advance();if(f.type===w.SEMICOLON&&l===0){if(a++,a>2)break}else f.value==="("&&l++,f.value===")"&&l--,o[a]+=f.value}e.expect(w.DPAREN_END),o[0].trim()&&(r=re(e,o[0].trim())),o[1].trim()&&(s=re(e,o[1].trim())),o[2].trim()&&(i=re(e,o[2].trim())),e.skipNewlines(),e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines();let u;e.check(w.LBRACE)?(e.advance(),u=e.parseCompoundList(),e.expect(w.RBRACE)):(e.expect(w.DO),u=e.parseCompoundList(),e.expect(w.DONE));let c=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:r,condition:s,update:i,body:u,redirections:c,line:n}}function bi(e,t){e.expect(w.WHILE);let n=e.parseCompoundList();e.expect(w.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(w.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return T.whileNode(n,r,s)}function Si(e,t){e.expect(w.UNTIL);let n=e.parseCompoundList();e.expect(w.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(w.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return T.untilNode(n,r,s)}function Ai(e,t){e.expect(w.CASE),e.isWord()||e.error("Expected word after 'case'");let n=e.parseWord();e.skipNewlines(),e.expect(w.IN),e.skipNewlines();let r=[];for(;!e.check(w.ESAC,w.EOF);){e.checkIterationLimit();let i=e.getPos(),o=Dd(e);if(o&&r.push(o),e.skipNewlines(),e.getPos()===i&&!o)break}e.expect(w.ESAC);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return T.caseNode(n,r,s)}function Dd(e){e.check(w.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(w.PIPE));)e.advance();if(t.length===0)return null;e.expect(w.RPAREN),e.skipNewlines();let n=[];for(;!e.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND,w.ESAC,w.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===w.RPAREN&&e.error("syntax error near unexpected token `)'"),e.check(w.LPAREN)&&e.peek(1).type===w.WORD&&e.error(`syntax error near unexpected token \`${e.peek(1).value}'`);let s=e.getPos(),i=e.parseStatement();if(i&&n.push(i),e.skipSeparators(!1),e.getPos()===s&&!i)break}let r=";;";return e.check(w.DSEMI)?(e.advance(),r=";;"):e.check(w.SEMI_AND)?(e.advance(),r=";&"):e.check(w.SEMI_SEMI_AND)&&(e.advance(),r=";;&"),T.caseItem(t,n,r)}function vi(e,t){e.expect(w.LPAREN);let n=e.parseCompoundList();e.expect(w.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return T.subshell(n,r)}function ki(e,t){e.expect(w.LBRACE);let n=e.parseCompoundList();e.expect(w.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return T.group(n,r)}var Od=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],_d=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function Sl(e){return e.isWord()||e.check(w.LBRACE)||e.check(w.RBRACE)||e.check(w.ASSIGNMENT_WORD)}function Al(e){if(e.check(w.BANG)&&e.peek(1).type===w.LPAREN){e.advance(),e.advance();let t=1,n="!(";for(;t>0&&!e.check(w.EOF);)if(e.check(w.LPAREN))t++,n+="(",e.advance();else if(e.check(w.RPAREN))t--,t>0&&(n+=")"),e.advance();else if(e.isWord())n+=e.advance().value;else if(e.check(w.PIPE))n+="|",e.advance();else break;return n+=")",e.parseWordFromString(n,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function xi(e){return e.skipNewlines(),Ld(e)}function Ld(e){let t=vl(e);for(e.skipNewlines();e.check(w.OR_OR);){e.advance(),e.skipNewlines();let n=vl(e);t={type:"CondOr",left:t,right:n},e.skipNewlines()}return t}function vl(e){let t=$i(e);for(e.skipNewlines();e.check(w.AND_AND);){e.advance(),e.skipNewlines();let n=$i(e);t={type:"CondAnd",left:t,right:n},e.skipNewlines()}return t}function $i(e){return e.skipNewlines(),e.check(w.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:e.withDepth(()=>$i(e))}):Td(e)}function Td(e){if(e.check(w.LPAREN)){e.advance();let t=e.withDepth(()=>xi(e));return e.expect(w.RPAREN),{type:"CondGroup",expression:t}}if(Sl(e)){let t=e.current(),n=t.value;if(Od.includes(n)&&!t.quoted){if(e.advance(),e.check(w.DBRACK_END)&&e.error(`Expected operand after ${n}`),Sl(e)){let i=e.parseWordNoBraceExpansion();return{type:"CondUnary",operator:n,operand:i}}let s=e.current();e.error(`unexpected argument \`${s.value}' to conditional unary operator`)}let r=e.parseWordNoBraceExpansion();if(e.isWord()&&_d.includes(e.current().value)){let s=e.advance().value,i;return s==="=~"?i=Fd(e):s==="=="||s==="!="?i=Al(e):i=e.parseWordNoBraceExpansion(),{type:"CondBinary",operator:s,left:r,right:i}}if(e.check(w.LESS)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:"<",left:r,right:s}}if(e.check(w.GREAT)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:">",left:r,right:s}}if(e.isWord()&&e.current().value==="="){e.advance();let s=Al(e);return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}e.error("Expected conditional expression")}function Fd(e){let t=[],n=0,r=-1,s=e.getInput(),i=()=>e.check(w.DBRACK_END)||e.check(w.AND_AND)||e.check(w.OR_OR)||e.check(w.NEWLINE)||e.check(w.EOF);for(;!i();){let o=e.current(),a=r>=0&&o.start>r;if(n===0&&a)break;if(n>0&&a){let l=s.slice(r,o.start);t.push({type:"Literal",value:l})}if(e.isWord()||e.check(w.ASSIGNMENT_WORD)){let l=e.parseWordForRegex();t.push(...l.parts),r=e.peek(-1).end}else if(e.check(w.LPAREN)){let l=e.advance();t.push({type:"Literal",value:"("}),n++,r=l.end}else if(e.check(w.DPAREN_START)){let l=e.advance();t.push({type:"Literal",value:"(("}),n+=2,r=l.end}else if(e.check(w.DPAREN_END))if(n>=2){let l=e.advance();t.push({type:"Literal",value:"))"}),n-=2,r=l.end}else{if(n===1)break;break}else if(e.check(w.RPAREN))if(n>0){let l=e.advance();t.push({type:"Literal",value:")"}),n--,r=l.end}else break;else if(e.check(w.PIPE)){let l=e.advance();t.push({type:"Literal",value:"|"}),r=l.end}else if(e.check(w.SEMICOLON))if(n>0){let l=e.advance();t.push({type:"Literal",value:";"}),r=l.end}else break;else if(n>0&&e.check(w.LESS)){let l=e.advance();t.push({type:"Literal",value:"<"}),r=l.end}else if(n>0&&e.check(w.GREAT)){let l=e.advance();t.push({type:"Literal",value:">"}),r=l.end}else if(n>0&&e.check(w.DGREAT)){let l=e.advance();t.push({type:"Literal",value:">>"}),r=l.end}else if(n>0&&e.check(w.DLESS)){let l=e.advance();t.push({type:"Literal",value:"<<"}),r=l.end}else if(n>0&&e.check(w.LESSAND)){let l=e.advance();t.push({type:"Literal",value:"<&"}),r=l.end}else if(n>0&&e.check(w.GREATAND)){let l=e.advance();t.push({type:"Literal",value:">&"}),r=l.end}else if(n>0&&e.check(w.LESSGREAT)){let l=e.advance();t.push({type:"Literal",value:"<>"}),r=l.end}else if(n>0&&e.check(w.CLOBBER)){let l=e.advance();t.push({type:"Literal",value:">|"}),r=l.end}else if(n>0&&e.check(w.TLESS)){let l=e.advance();t.push({type:"Literal",value:"<<<"}),r=l.end}else if(n>0&&e.check(w.AMP)){let l=e.advance();t.push({type:"Literal",value:"&"}),r=l.end}else if(n>0&&e.check(w.LBRACE)){let l=e.advance();t.push({type:"Literal",value:"{"}),r=l.end}else if(n>0&&e.check(w.RBRACE)){let l=e.advance();t.push({type:"Literal",value:"}"}),r=l.end}else break}return t.length===0&&e.error("Expected regex pattern after =~"),{type:"Word",parts:t}}function Bd(e){let t="";for(let n=0;n<e.length;n++){let r=e[n],s=e[n+1];if(r!=="\\"||s===void 0){t+=r;continue}"\\[]^-".includes(s)&&(t+="\\"),t+=s,n++}return t}function ir(e){return e.length>0?e:[T.literal("")]}function Wd(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if("@*+?!".includes(s)&&r+1<e.length&&e[r+1]==="("){r++,n++,r++;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Vd(e,t,n){let r=n+1,s=t[r];if("@*#?$!-0123456789".includes(s))return{part:T.parameterExpansion(s),endIndex:r+1};let i="";for(;r<t.length&&/[a-zA-Z0-9_]/.test(t[r]);)i+=t[r],r++;return{part:T.parameterExpansion(i),endIndex:r}}function zd(e,t,n,r=!1){let s=n+2,i=!1;t[s]==="!"&&(i=!0,s++);let o=!1;t[s]==="#"&&!/[}:#%/^,]/.test(t[s+1]||"}")&&(o=!0,s++);let a="",l=t[s];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(t[s+1]||""))a=l,s++;else for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)a+=t[s],s++;if(t[s]==="["){let c=pi(e,t,s,"[","]");if(a+=`[${Hr(t.slice(s+1,c))}]`,s=c+1,t[s]==="["){let f=1,d=s;for(;d<t.length&&f>0;)t[d]==="{"?f++:t[d]==="}"&&f--,f>0&&d++;let p=t.slice(n+2,d);return{part:T.parameterExpansion("",{type:"BadSubstitution",text:p}),endIndex:d+1}}}if(a===""&&!i&&!o&&t[s]!=="}"){let c=1,f=s;for(;f<t.length&&c>0;)t[f]==="{"?c++:t[f]==="}"&&c--,c>0&&f++;if(c>0)throw new ke("unexpected EOF while looking for matching '}'",0,0);let d=t.slice(n+2,f);return{part:T.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:f+1}}let u=null;if(i){let c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(c)if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=Pi(e,t,s,a,r);f.operation?(u={type:"Indirection",innerOp:f.operation},s=f.endIndex):(u={type:"ArrayKeys",array:c[1],star:c[2]==="*"},a="")}else u={type:"ArrayKeys",array:c[1],star:c[2]==="*"},a="";else if(t[s]==="*"||t[s]==="@"&&!/[QPaAEKkuUL]/.test(t[s+1]||"")){let f=t[s];s++,u={type:"VarNamePrefix",prefix:a,star:f==="*"},a=""}else if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=Pi(e,t,s,a,r);f.operation?(u={type:"Indirection",innerOp:f.operation},s=f.endIndex):u={type:"Indirection"}}else u={type:"Indirection"}}else if(o)if(t[s]===":")for(u={type:"LengthSliceError"};s<t.length&&t[s]!=="}";)s++;else t[s]!=="}"&&/[-+=?]/.test(t[s])?e.error(`\${#${a}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):t[s]==="/"?e.error(`\${#${a}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):u={type:"Length"};if(!u&&s<t.length&&t[s]!=="}"){let c=Pi(e,t,s,a,r);u=c.operation,s=c.endIndex}if(s<t.length&&t[s]!=="}"){let c=t[s];if(!/[:\-+=?#%/^,@[]/.test(c)){let f=s;for(;f<t.length&&t[f]!=="}";)f++;let d=t.slice(n,f+1);e.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<t.length&&t[s]!=="}";)s++;if(s>=t.length)throw new ke("unexpected EOF while looking for matching '}'",0,0);return{part:T.parameterExpansion(a,u),endIndex:s+1}}function Pi(e,t,n,r,s=!1){let i=n,o=t[i],a=t[i+1]||"";if(o===":"){let l=a;if("-=?+".includes(l)){i+=2;let S=En(e,t,i),g=t.slice(i,S),y=e.withDepth(()=>Qt(e,g,!1,!1,!0,!1,s,!1,!1,!0)),b=T.word(ir(y));if(l==="-")return{operation:{type:"DefaultValue",word:b,checkEmpty:!0},endIndex:S};if(l==="=")return{operation:{type:"AssignDefault",word:b,checkEmpty:!0},endIndex:S};if(l==="?")return{operation:{type:"ErrorIfUnset",word:b,checkEmpty:!0},endIndex:S};if(l==="+")return{operation:{type:"UseAlternative",word:b,checkEmpty:!0},endIndex:S}}i++;let u=En(e,t,i),c=t.slice(i,u),f=-1,d=0,p=0;for(let E=0;E<c.length;E++){let S=c[E];if(S==="("||S==="[")d++;else if(S===")"||S==="]")d--;else if(S==="?"&&d===0)p++;else if(S===":"&&d===0)if(p>0)p--;else{f=E;break}}let h=f>=0?c.slice(0,f):c,m=f>=0?c.slice(f+1):null;return{operation:{type:"Substring",offset:hi(e,h),length:m!==null?hi(e,m):null},endIndex:u}}if("-=?+".includes(o)){i++;let l=En(e,t,i),u=t.slice(i,l),c=e.withDepth(()=>Qt(e,u,!1,!1,!0,!1,s,!1,!1,!0)),f=T.word(ir(c));if(o==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:l};if(o==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:l};if(o==="?")return{operation:{type:"ErrorIfUnset",word:u?f:null,checkEmpty:!1},endIndex:l};if(o==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:l}}if(o==="#"||o==="%"){let l=a===o,u=o==="#"?"prefix":"suffix";i+=l?2:1;let c=En(e,t,i),f=t.slice(i,c),d=e.withDepth(()=>Qt(e,f,!1,!1,!1));return{operation:{type:"PatternRemoval",pattern:T.word(ir(d)),side:u,greedy:l},endIndex:c}}if(o==="/"){let l=a==="/";i+=l?2:1;let u=null;t[i]==="#"?(u="start",i++):t[i]==="%"&&(u="end",i++);let c;u!==null&&(t[i]==="/"||t[i]==="}")?c=i:c=ml(e,t,i);let f=t.slice(i,c),d=e.withDepth(()=>Qt(e,f,!1,!1,!1)),p=T.word(ir(d)),h=null,m=c;if(t[c]==="/"){let E=c+1,S=En(e,t,E),g=t.slice(E,S),y=e.withDepth(()=>Qt(e,g,!1,!1,!1));h=T.word(ir(y)),m=S}return{operation:{type:"PatternReplacement",pattern:p,replacement:h,all:l,anchor:u},endIndex:m}}if(o==="^"||o===","){let l=a===o,u=o==="^"?"upper":"lower";i+=l?2:1;let c=En(e,t,i),f=t.slice(i,c),d=f?T.word([T.literal(f)]):null;return{operation:{type:"CaseModification",direction:u,all:l,pattern:d},endIndex:c}}return o==="@"&&/[QPaAEKkuUL]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:i+2}:{operation:null,endIndex:i}}function Ci(e,t,n,r=!1){let s=n+1;if(s>=t.length)return{part:T.literal("$"),endIndex:s};let i=t[s];if(i==="("&&t[s+1]==="(")return e.isDollarDparenSubshell(t,n)?e.parseCommandSubstitution(t,n):e.parseArithmeticExpansion(t,n);if(i==="["){let o=1,a=s+1;for(;a<t.length&&o>0;)t[a]==="["?o++:t[a]==="]"&&o--,o>0&&a++;if(o===0){let l=t.slice(s+1,a),u=re(e,l);return{part:T.arithmeticExpansion(u),endIndex:a+1}}}return i==="("?e.parseCommandSubstitution(t,n):i==="{"?zd(e,t,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Vd(e,t,n):{part:T.literal("$"),endIndex:s}}function kl(e,t){let n=[],r=0,s="",i=()=>{s&&(n.push(T.literal(s)),s="")};for(;r<t.length;){let o=t[r];if(o==="\\"&&r+1<t.length){let a=t[r+1];if(a==="$"||a==="`"||a==='"'||a==="\\"){s+=a,r+=2;continue}s+=o,r++;continue}if(o==="$"){i();let{part:a,endIndex:l}=Ci(e,t,r,!0);a&&n.push(a),r=l;continue}if(o==="`"){i();let{part:a,endIndex:l}=e.parseBacktickSubstitution(t,r,!0);n.push(a),r=l;continue}s+=o,r++}return i(),n}function Ud(e,t,n){let r=[],s=n,i="",o=()=>{i&&(r.push(T.literal(i)),i="")};for(;s<t.length&&t[s]!=='"';){let a=t[s];if(a==="\\"&&s+1<t.length){let l=t[s+1];if('"\\$`\n'.includes(l)){i+=l,s+=2;continue}i+=a,s++;continue}if(a==="$"){o();let{part:l,endIndex:u}=Ci(e,t,s,!0);l&&r.push(l),s=u;continue}if(a==="`"){o();let{part:l,endIndex:u}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=u;continue}i+=a,s++}return o(),{part:T.doubleQuoted(r),endIndex:s}}function Qt(e,t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,u=!1,c=!0){if(r)return[T.singleQuoted(t)];if(n){let m=kl(e,t);return[T.doubleQuoted(m)]}if(t.length>=2&&t[0]==='"'&&t[t.length-1]==='"'){let m=t.slice(1,-1),E=!1;for(let S=0;S<m.length;S++){if(m[S]==='"'){E=!0;break}m[S]==="\\"&&S+1<m.length&&S++}if(!E){let S=kl(e,m);return[T.doubleQuoted(S)]}}let f=[],d=0,p="",h=()=>{p&&(f.push(T.literal(p)),p="")};for(;d<t.length;){let m=t[d];if(m==="\\"&&d+1<t.length){let E=t[d+1];if(l){h(),f.push(T.escaped(E)),d+=2;continue}if(!i&&!o){E!==`
|
|
70
|
-
`&&(h(),f.push(
|
|
64
|
+
`);)d=!0,f++;if(d&&f<r&&n[f]===")"||l)return!0}if(i===0)return!1;s++;continue}s++}return!1}dparenClosesWithSpacedParens(t){let n=this.input,r=n.length,s=t,i=2,a=!1,o=!1;for(;s<r&&i>0;){let l=n[s];if(a){l==="'"&&(a=!1),s++;continue}if(o){if(l==="\\"){s+=2;continue}l==='"'&&(o=!1),s++;continue}if(l==="'"){a=!0,s++;continue}if(l==='"'){o=!0,s++;continue}if(l==="\\"){s+=2;continue}if(l==="("){i++,s++;continue}if(l===")"){if(i--,i===1){let u=s+1;if(u<r&&n[u]===")")return!1;let c=u,f=!1;for(;c<r&&(n[c]===" "||n[c]===" "||n[c]===`
|
|
65
|
+
`);)f=!0,c++;if(f&&c<r&&n[c]===")")return!0}if(i===0)return!1;s++;continue}if(i===1&&(l==="|"&&s+1<r&&n[s+1]==="|"||l==="&"&&s+1<r&&n[s+1]==="&"||l==="|"&&s+1<r&&n[s+1]!=="|"))return!0;s++}return!1}};var wi=1e6,ar=1e5,Nd=1e6,sl=200,Re;(function(e){e[e.Default=0]="Default",e[e.Assignment=1]="Assignment",e[e.NoBraceExpansion=2]="NoBraceExpansion",e[e.Regex=4]="Regex"})(Re||(Re={}));var il=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS,w.AND_GREAT,w.AND_DGREAT]),al=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS]),ol=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS,w.AND_GREAT,w.AND_DGREAT]),xe=class extends Error{line;column;token;constructor(t,n,r,s=void 0){super(`Parse error at ${n}:${r}: ${t}`),this.line=n,this.column=r,this.token=s,this.name="ParseException"}},Zr=class{iterations=0;tokens=0;depth=0;reset(){this.iterations=0,this.tokens=0,this.depth=0}chargeIteration(t,n){if(this.iterations++,this.iterations>Nd)throw new xe("Maximum parse iterations exceeded (possible infinite loop)",t,n)}chargeTokens(t,n=1,r=1){if(this.tokens+=t,this.tokens>ar)throw new xe(`Too many tokens: cumulative count exceeds limit of ${ar}`,n,r)}enter(t,n){if(this.depth++,this.depth>sl)throw this.depth--,new xe(`Maximum parser nesting depth exceeded (${sl})`,t,n);let r=!0;return()=>{r&&(r=!1,this.depth--)}}};function he(e,t){for(;t<e.length;){if(e[t]==="\\"&&e[t+1]===`
|
|
66
|
+
`){t+=2;continue}if(/\s/.test(e[t])){t++;continue}break}return t}var Qr=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];function or(e){if(e.includes("#")){let n=e.split("#");if(n.length!==2)return Number.NaN;let[r,s]=n;if(!/^\d+$/.test(r)||s.length===0)return Number.NaN;let i=Number.parseInt(r,10);if(i<2||i>64)return Number.NaN;let a=0;for(let o of s){let l;if(/[0-9]/.test(o))l=o.charCodeAt(0)-48;else if(/[a-z]/.test(o))l=o.charCodeAt(0)-97+10;else if(/[A-Z]/.test(o))l=o.charCodeAt(0)-65+(i<=36?10:36);else if(o==="@")l=62;else if(o==="_")l=63;else return Number.NaN;if(l>=i)return Number.NaN;if(a=a*i+l,a>Number.MAX_SAFE_INTEGER)return Number.MAX_SAFE_INTEGER}return a}if(e.startsWith("0x")||e.startsWith("0X")){let n=Number.parseInt(e.slice(2),16);return n>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:n}if(e.startsWith("0")&&e.length>1&&/^[0-9]+$/.test(e)){if(/[89]/.test(e))return Number.NaN;let n=Number.parseInt(e,8);return n>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:n}let t=Number.parseInt(e,10);return t>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:t}function ll(e,t,n,r){if(n.slice(r,r+3)!=="$((")return null;let s=r+3,i=1,a=s;for(;s<n.length-1&&i>0;)n[s]==="("&&n[s+1]==="("?(i++,s+=2):n[s]===")"&&n[s+1]===")"?(i--,i>0&&(s+=2)):s++;let o=n.slice(a,s),{expr:l}=e(t,o,0);return s+=2,{expr:{type:"ArithNested",expression:l},pos:s}}function ul(e,t){if(e.slice(t,t+2)!=="$'")return null;let n=t+2,r="";for(;n<e.length&&e[n]!=="'";)if(e[n]==="\\"&&n+1<e.length){let i=e[n+1];switch(i){case"n":r+=`
|
|
67
|
+
`;break;case"t":r+=" ";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"'":r+="'";break;default:r+=i}n+=2}else r+=e[n],n++;e[n]==="'"&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function cl(e,t){if(e.slice(t,t+2)!=='$"')return null;let n=t+2,r="";for(;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(r+=e[n+1],n+=2):(r+=e[n],n++);e[n]==='"'&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function Rd(e){let t="",n=0;for(;n<e.length;)if(e[n]==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);n<e.length&&n++}else t+=e[n],n++;return t}function se(e,t){let n=Rd(t),{expr:r,pos:s}=Mn(e,n,0),i=he(n,s);if(i<n.length){let a=t.slice(i).trim();if(a)return{type:"ArithmeticExpression",originalText:t,expression:{type:"ArithSyntaxError",errorToken:a,message:`${a}: syntax error: invalid arithmetic operator (error token is "${a}")`}}}return{type:"ArithmeticExpression",expression:r,originalText:t}}function je(e,t){return{expr:{type:"ArithSyntaxError",errorToken:e,message:`syntax error: operand expected (error token is "${e}")`},pos:t}}function He(e,t){return he(e,t)>=e.length}function Mn(e,t,n){return Dd(e,t,n)}function bn(e,t,n){return e.withDepth(()=>Mn(e,t,n))}function Dd(e,t,n){let{expr:r,pos:s}=lr(e,t,n);for(s=he(t,s);t[s]===",";){if(s++,He(t,s))return je(",",s);let{expr:a,pos:o}=lr(e,t,s);r={type:"ArithBinary",operator:",",left:r,right:a},s=he(t,o)}return{expr:r,pos:s}}function lr(e,t,n){let{expr:r,pos:s}=Id(e,t,n);if(s=he(t,s),t[s]==="?"){s++;let{expr:i,pos:a}=bn(e,t,s);if(s=he(t,a),t[s]===":"){s++;let{expr:o,pos:l}=bn(e,t,s);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:o},pos:l}}}return{expr:r,pos:s}}function Id(e,t,n){let{expr:r,pos:s}=fl(e,t,n);for(;s=he(t,s),t.slice(s,s+2)==="||";){if(s+=2,He(t,s))return je("||",s);let{expr:a,pos:o}=fl(e,t,s);r={type:"ArithBinary",operator:"||",left:r,right:a},s=o}return{expr:r,pos:s}}function fl(e,t,n){let{expr:r,pos:s}=dl(e,t,n);for(;s=he(t,s),t.slice(s,s+2)==="&&";){if(s+=2,He(t,s))return je("&&",s);let{expr:a,pos:o}=dl(e,t,s);r={type:"ArithBinary",operator:"&&",left:r,right:a},s=o}return{expr:r,pos:s}}function dl(e,t,n){let{expr:r,pos:s}=pl(e,t,n);for(;s=he(t,s),t[s]==="|"&&t[s+1]!=="|";){if(s++,He(t,s))return je("|",s);let{expr:a,pos:o}=pl(e,t,s);r={type:"ArithBinary",operator:"|",left:r,right:a},s=o}return{expr:r,pos:s}}function pl(e,t,n){let{expr:r,pos:s}=hl(e,t,n);for(;s=he(t,s),t[s]==="^";){if(s++,He(t,s))return je("^",s);let{expr:a,pos:o}=hl(e,t,s);r={type:"ArithBinary",operator:"^",left:r,right:a},s=o}return{expr:r,pos:s}}function hl(e,t,n){let{expr:r,pos:s}=ml(e,t,n);for(;s=he(t,s),t[s]==="&"&&t[s+1]!=="&";){if(s++,He(t,s))return je("&",s);let{expr:a,pos:o}=ml(e,t,s);r={type:"ArithBinary",operator:"&",left:r,right:a},s=o}return{expr:r,pos:s}}function ml(e,t,n){let{expr:r,pos:s}=yl(e,t,n);for(;s=he(t,s),t.slice(s,s+2)==="=="||t.slice(s,s+2)==="!=";){let i=t.slice(s,s+2);if(s+=2,He(t,s))return je(i,s);let{expr:a,pos:o}=yl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}return{expr:r,pos:s}}function yl(e,t,n){let{expr:r,pos:s}=Ei(e,t,n);for(;;)if(s=he(t,s),t.slice(s,s+2)==="<="||t.slice(s,s+2)===">="){let i=t.slice(s,s+2);if(s+=2,He(t,s))return je(i,s);let{expr:a,pos:o}=Ei(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}else if(t[s]==="<"||t[s]===">"){let i=t[s];if(s++,He(t,s))return je(i,s);let{expr:a,pos:o}=Ei(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}else break;return{expr:r,pos:s}}function Ei(e,t,n){let{expr:r,pos:s}=gl(e,t,n);for(;s=he(t,s),t.slice(s,s+2)==="<<"||t.slice(s,s+2)===">>";){let i=t.slice(s,s+2);if(s+=2,He(t,s))return je(i,s);let{expr:a,pos:o}=gl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}return{expr:r,pos:s}}function gl(e,t,n){let{expr:r,pos:s}=wl(e,t,n);for(;s=he(t,s),(t[s]==="+"||t[s]==="-")&&t[s+1]!==t[s];){let i=t[s];if(s++,He(t,s))return je(i,s);let{expr:a,pos:o}=wl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}return{expr:r,pos:s}}function wl(e,t,n){let{expr:r,pos:s}=Kr(e,t,n);for(;;)if(s=he(t,s),t[s]==="*"&&t[s+1]!=="*"){if(s++,He(t,s))return je("*",s);let{expr:a,pos:o}=Kr(e,t,s);r={type:"ArithBinary",operator:"*",left:r,right:a},s=o}else if(t[s]==="/"||t[s]==="%"){let i=t[s];if(s++,He(t,s))return je(i,s);let{expr:a,pos:o}=Kr(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}else break;return{expr:r,pos:s}}function Kr(e,t,n){let{expr:r,pos:s}=bi(e,t,n),i=he(t,s);if(t.slice(i,i+2)==="**"){if(i+=2,He(t,i))return je("**",i);let{expr:o,pos:l}=e.withDepth(()=>Kr(e,t,i));return{expr:{type:"ArithBinary",operator:"**",left:r,right:o},pos:l}}return{expr:r,pos:s}}function bi(e,t,n){let r=he(t,n);if(t.slice(r,r+2)==="++"||t.slice(r,r+2)==="--"){let s=t.slice(r,r+2);r+=2;let{expr:i,pos:a}=e.withDepth(()=>bi(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}if(t[r]==="+"||t[r]==="-"||t[r]==="!"||t[r]==="~"){let s=t[r];r++;let{expr:i,pos:a}=e.withDepth(()=>bi(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}return _d(e,t,r)}function Od(e,t){let n=e[t];return n==="$"||n==="`"}function _d(e,t,n){let{expr:r,pos:s}=El(e,t,n,!1),i=[r];for(;Od(t,s);){let{expr:o,pos:l}=El(e,t,s,!0);i.push(o),s=l}i.length>1&&(r={type:"ArithConcat",parts:i});let a;if(t[s]==="["&&r.type==="ArithConcat"){s++;let{expr:o,pos:l}=bn(e,t,s);a=o,s=l,t[s]==="]"&&s++}if(a&&r.type==="ArithConcat"&&(r={type:"ArithDynamicElement",nameExpr:r,subscript:a},a=void 0),s=he(t,s),r.type==="ArithConcat"||r.type==="ArithVariable"||r.type==="ArithDynamicElement"){for(let o of Qr)if(t.slice(s,s+o.length)===o&&t.slice(s,s+o.length+1)!=="=="){s+=o.length;let{expr:l,pos:u}=e.withDepth(()=>lr(e,t,s));return r.type==="ArithDynamicElement"?{expr:{type:"ArithDynamicAssignment",operator:o,target:r.nameExpr,subscript:r.subscript,value:l},pos:u}:r.type==="ArithConcat"?{expr:{type:"ArithDynamicAssignment",operator:o,target:r,value:l},pos:u}:{expr:{type:"ArithAssignment",operator:o,variable:r.name,value:l},pos:u}}}if(t.slice(s,s+2)==="++"||t.slice(s,s+2)==="--"){let o=t.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:o,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function El(e,t,n,r=!1){let s=he(t,n),i=ll(bn,e,t,s);if(i)return i;let a=ul(t,s);if(a)return a;let o=cl(t,s);if(o)return o;if(t.slice(s,s+2)==="$("&&t[s+2]!=="("){s+=2;let u=1,c=s;for(;s<t.length&&u>0;)t[s]==="("?u++:t[s]===")"&&u--,u>0&&s++;let f=t.slice(c,s);return s++,{expr:{type:"ArithCommandSubst",command:f},pos:s}}if(t[s]==="`"){s++;let u=s;for(;s<t.length&&t[s]!=="`";)s++;let c=t.slice(u,s);return t[s]==="`"&&s++,{expr:{type:"ArithCommandSubst",command:c},pos:s}}if(t[s]==="("){s++;let{expr:u,pos:c}=bn(e,t,s);return s=he(t,c),t[s]===")"&&s++,{expr:{type:"ArithGroup",expression:u},pos:s}}if(t[s]==="'"){s++;let u="";for(;s<t.length&&t[s]!=="'";)u+=t[s],s++;t[s]==="'"&&s++;let c=Number.parseInt(u,10);return{expr:{type:"ArithSingleQuote",content:u,value:Number.isNaN(c)?0:c},pos:s}}if(t[s]==='"'){s++;let u="";for(;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?(u+=t[s+1],s+=2):(u+=t[s],s++);t[s]==='"'&&s++;let c=u.trim();if(!c)return{expr:{type:"ArithNumber",value:0},pos:s};let{expr:f}=bn(e,c,0);return{expr:f,pos:s}}if(/[0-9]/.test(t[s])){let u="",c=!1,f=!1;for(;s<t.length;){let p=t[s];if(c)if(/[0-9a-zA-Z@_]/.test(p))u+=p,s++;else break;else if(p==="#")c=!0,u+=p,s++;else if(u==="0"&&(p==="x"||p==="X")&&s+1<t.length&&/[0-9a-fA-F]/.test(t[s+1]))f=!0,u+=p,s++;else if(f&&/[0-9a-fA-F]/.test(p))u+=p,s++;else if(!f&&/[0-9]/.test(p))u+=p,s++;else break}if(s<t.length&&/[a-zA-Z_]/.test(t[s])){let p=u;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)p+=t[s],s++;return{expr:{type:"ArithSyntaxError",errorToken:p,message:`${p}: value too great for base (error token is "${p}")`},pos:s}}if(t[s]==="."&&/[0-9]/.test(t[s+1]))throw new le(`${u}.${t[s+1]}...: syntax error: invalid arithmetic operator`);if(t[s]==="["){let p=t.slice(s).trim();return{expr:{type:"ArithNumberSubscript",number:u,errorToken:p},pos:t.length}}return{expr:{type:"ArithNumber",value:or(u)},pos:s}}if(t[s]==="$"&&t[s+1]==="{"){let u=s+2,c=1,f=u;for(;f<t.length&&c>0;)t[f]==="{"?c++:t[f]==="}"&&c--,c>0&&f++;let d=t.slice(u,f),p=f+1;if(t[p]==="#"){let h=p+1;for(;h<t.length&&/[0-9a-zA-Z@_]/.test(t[h]);)h++;let m=t.slice(p+1,h);return{expr:{type:"ArithDynamicBase",baseExpr:d,value:m},pos:h}}if(/[0-9]/.test(t[p])||t[p]==="x"||t[p]==="X"){let h=p;if(t[p]==="x"||t[p]==="X")for(h++;h<t.length&&/[0-9a-fA-F]/.test(t[h]);)h++;else for(;h<t.length&&/[0-9]/.test(t[h]);)h++;let m=t.slice(p,h);return{expr:{type:"ArithDynamicNumber",prefix:d,suffix:m},pos:h}}return s=p,{expr:{type:"ArithBracedExpansion",content:d},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[0-9]/.test(t[s+1])){s++;let u="";for(;s<t.length&&/[0-9]/.test(t[s]);)u+=t[s],s++;return{expr:{type:"ArithVariable",name:u,hasDollarPrefix:!0},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[*@#?\-!$]/.test(t[s+1])){let u=t[s+1];return s+=2,{expr:{type:"ArithSpecialVar",name:u},pos:s}}let l=!1;if(t[s]==="$"&&s+1<t.length&&/[a-zA-Z_]/.test(t[s+1])&&(l=!0,s++),s<t.length&&/[a-zA-Z_]/.test(t[s])){let u="";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)u+=t[s],s++;if(t[s]==="["&&!r){s++;let c;if(t[s]==="'"||t[s]==='"'){let d=t[s];for(s++,c="";s<t.length&&t[s]!==d;)c+=t[s],s++;t[s]===d&&s++,s=he(t,s),t[s]==="]"&&s++}let f;if(c===void 0){let{expr:d,pos:p}=bn(e,t,s);f=d,s=p,t[s]==="]"&&s++}if(s=he(t,s),t[s]==="["&&f)return{expr:{type:"ArithDoubleSubscript",array:u,index:f},pos:s};if(!r){for(let d of Qr)if(t.slice(s,s+d.length)===d&&t.slice(s,s+d.length+1)!=="=="){s+=d.length;let{expr:p,pos:h}=e.withDepth(()=>lr(e,t,s));return{expr:{type:"ArithAssignment",operator:d,variable:u,subscript:f,stringKey:c,value:p},pos:h}}}return{expr:{type:"ArithArrayElement",array:u,index:f,stringKey:c},pos:s}}if(s=he(t,s),!r){for(let c of Qr)if(t.slice(s,s+c.length)===c&&t.slice(s,s+c.length+1)!=="=="){s+=c.length;let{expr:f,pos:d}=e.withDepth(()=>lr(e,t,s));return{expr:{type:"ArithAssignment",operator:c,variable:u,value:f},pos:d}}}return{expr:{type:"ArithVariable",name:u,hasDollarPrefix:l},pos:s}}if(t[s]==="#"){let u=s+1;for(;u<t.length&&t[u]!==`
|
|
68
|
+
`;)u++;let c=t.slice(s,u).trim()||"#";return{expr:{type:"ArithSyntaxError",errorToken:c,message:`${c}: syntax error: invalid arithmetic operator (error token is "${c}")`},pos:t.length}}return{expr:{type:"ArithNumber",value:0},pos:s}}var Xr=e=>{let t,n="";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\"&&t==='"'&&r+1<e.length){n+=s+e[r+1],r+=1;continue}if(s==="'"||s==='"'){t===s?t=void 0:t||(t=s),n+=s;continue}if(s==="\\"&&!t&&r+1<e.length){let i=e[r+1];n+=i==="$"||i==="`"?`\\${i}`:i,r+=1;continue}n+=s}return n};function Ld(e){let t="",n=0;for(;n<e.length;){let r=e[n];if(r<128){t+=String.fromCharCode(r),n++;continue}if((r&224)===192){if(n+1<e.length&&(e[n+1]&192)===128&&r>=194){let s=(r&31)<<6|e[n+1]&63;t+=String.fromCharCode(s),n+=2;continue}t+=String.fromCharCode(r),n++;continue}if((r&240)===224){if(n+2<e.length&&(e[n+1]&192)===128&&(e[n+2]&192)===128){if(r===224&&e[n+1]<160){t+=String.fromCharCode(r),n++;continue}let s=(r&15)<<12|(e[n+1]&63)<<6|e[n+2]&63;if(s>=55296&&s<=57343){t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(s),n+=3;continue}t+=String.fromCharCode(r),n++;continue}if((r&248)===240&&r<=244){if(n+3<e.length&&(e[n+1]&192)===128&&(e[n+2]&192)===128&&(e[n+3]&192)===128){if(r===240&&e[n+1]<144){t+=String.fromCharCode(r),n++;continue}let s=(r&7)<<18|(e[n+1]&63)<<12|(e[n+2]&63)<<6|e[n+3]&63;if(s>1114111){t+=String.fromCharCode(r),n++;continue}t+=String.fromCodePoint(s),n+=4;continue}t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(r),n++}return t}function Al(e,t,n){let r=n+1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;return r}function Si(e,t,n,r,s){let i=1,a=n+1;for(;a<t.length&&i>0;)t[a]===r?i++:t[a]===s&&i--,i>0&&a++;return i===0?a:-1}function Sn(e,t,n){let r=n,s=1;for(;r<t.length&&s>0;){let i=t[r];if(i==="\\"&&r+1<t.length){r+=2;continue}if(i==="'"){let a=t.indexOf("'",r+1);if(a!==-1){r=a+1;continue}}if(i==='"'){for(r++;r<t.length&&t[r]!=='"';)t[r]==="\\"&&r+1<t.length?r+=2:r++;r<t.length&&r++;continue}i==="{"?s++:i==="}"&&s--,s>0&&r++}return r}function vl(e,t,n){let r=n,s=!1;for(;r<t.length;){let i=t[r];if(i==="/"&&s||i==="}")break;if(i==="'"){let a=t.indexOf("'",r+1);if(a!==-1){r=a+1,s=!0;continue}}if(i==='"'){for(r++;r<t.length&&t[r]!=='"';)t[r]==="\\"&&r+1<t.length?r+=2:r++;r<t.length&&r++,s=!0;continue}i==="\\"?(r+=2,s=!0):(r++,s=!0)}return r}function kl(e,t,n){let r=n,s="";for(;r<t.length;){let i=t[r];if(i==="*"||i==="?")s+=i,r++;else if(i==="["){let a=Td(t,r);a===-1?(s+=i,r++):(s+=t.slice(r,a+1),r=a+1)}else break}return{pattern:s,endIndex:r}}function Td(e,t){let n=t+1;for(n<e.length&&e[n]==="^"&&n++,n<e.length&&e[n]==="]"&&n++;n<e.length;){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if(s==='"'||s==="'")return-1;n+=2;continue}if(r==="]")return n;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let s=e.indexOf("'",n+1);if(s!==-1){n=s+1;continue}}if(r==="["&&n+1<e.length&&e[n+1]===":"){let s=e.indexOf(":]",n+2);if(s!==-1){n=s+2;continue}}if(r==="["&&n+1<e.length&&(e[n+1]==="."||e[n+1]==="=")){let i=`${e[n+1]}]`,a=e.indexOf(i,n+2);if(a!==-1){n=a+2;continue}}n++}return-1}function xl(e,t,n){let r="",s=n;for(;s<t.length&&t[s]!=="'";){let i=t[s];if(i==="\\"&&s+1<t.length)switch(t[s+1]){case"n":r+=`
|
|
69
|
+
`,s+=2;break;case"t":r+=" ",s+=2;break;case"r":r+="\r",s+=2;break;case"\\":r+="\\",s+=2;break;case"'":r+="'",s+=2;break;case'"':r+='"',s+=2;break;case"a":r+="\x07",s+=2;break;case"b":r+="\b",s+=2;break;case"e":case"E":r+="\x1B",s+=2;break;case"f":r+="\f",s+=2;break;case"v":r+="\v",s+=2;break;case"x":{let o=[],l=s;for(;l+1<t.length&&t[l]==="\\"&&t[l+1]==="x";){let u=t.slice(l+2,l+4),c=parseInt(u,16);if(!Number.isNaN(c)&&u.length>0)o.push(c),l+=2+u.length;else break}o.length>0?(r+=Ld(o),s=l):(r+="\\x",s+=2);break}case"u":{let o=t.slice(s+2,s+6),l=parseInt(o,16);Number.isNaN(l)?(r+="\\u",s+=2):(r+=String.fromCharCode(l),s+=6);break}case"c":{if(s+2<t.length){let l=t[s+2].charCodeAt(0)&31;r+=String.fromCharCode(l),s+=3}else r+="\\c",s+=2;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let o="",l=s+1;for(;l<t.length&&l<s+4&&/[0-7]/.test(t[l]);)o+=t[l],l++;let u=parseInt(o,8);r+=String.fromCharCode(u),s=l;break}default:r+=i,s++}else r+=i,s++}return s<t.length&&t[s]==="'"&&s++,{part:F.literal(r),endIndex:s}}function Ai(e,t){let n=t.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:se(e,n)}function Sl(e){let t=[],n="",r=0;for(let s=0;s<e.length;s++){let i=e[s];i==="{"?(r++,n+=i):i==="}"?(r--,n+=i):i===","&&r===0?(t.push(n),n=""):n+=i}return t.push(n),t}function $l(e,t,n,r){let s=Si(e,t,n,"{","}");if(s===-1)return null;let i=t.slice(n+1,s),a=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(a)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(a[1],10),end:Number.parseInt(a[2],10),step:a[3]?Number.parseInt(a[3],10):void 0,startStr:a[1],endStr:a[2]}]},endIndex:s+1};let o=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return o?{part:{type:"BraceExpansion",items:[{type:"Range",start:o[1],end:o[2],step:o[3]?Number.parseInt(o[3],10):void 0}]},endIndex:s+1}:i.includes(",")&&r?{part:{type:"BraceExpansion",items:Sl(i).map(c=>e.withDepth(()=>({type:"Word",word:F.word(r(e,c,!1,!1,!1))})))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:Sl(i).map(c=>({type:"Word",word:F.word([F.literal(c)])}))},endIndex:s+1}:null}function vi(e,t){let n="";for(let r of t.parts)switch(r.type){case"Literal":n+=r.value;break;case"SingleQuoted":n+=`'${r.value}'`;break;case"Escaped":n+=r.value;break;case"DoubleQuoted":n+='"';for(let s of r.parts)s.type==="Literal"||s.type==="Escaped"?n+=s.value:s.type==="ParameterExpansion"&&(n+=`\${${s.parameter}}`);n+='"';break;case"ParameterExpansion":n+=`\${${r.parameter}}`;break;case"Glob":n+=r.pattern;break;case"TildeExpansion":n+="~",r.user&&(n+=r.user);break;case"BraceExpansion":{n+="{";let s=[];for(let i of r.items)if(i.type==="Range"){let a=i.startStr??String(i.start),o=i.endStr??String(i.end);i.step!==void 0?s.push(`${a}..${o}..${i.step}`):s.push(`${a}..${o}`)}else s.push(vi(e,i.word));s.length===1&&r.items[0].type==="Range"?n+=s[0]:n+=s.join(","),n+="}";break}default:n+=r.type}return n}function Pl(e,t){return{[w.LESS]:"<",[w.GREAT]:">",[w.DGREAT]:">>",[w.LESSAND]:"<&",[w.GREATAND]:">&",[w.LESSGREAT]:"<>",[w.CLOBBER]:">|",[w.TLESS]:"<<<",[w.AND_GREAT]:"&>",[w.AND_DGREAT]:"&>>",[w.DLESS]:"<",[w.DLESSDASH]:"<"}[t]||">"}function ur(e){let t=e.current(),n=t.type;if(n===w.NUMBER){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:al.has(r.type)}if(n===w.FD_VARIABLE){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:ol.has(r.type)}return!e.isProcessSubstitutionStart()&&il.has(n)}function Yr(e){let t=null,n;e.check(w.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(w.FD_VARIABLE)&&(n=e.advance().value);let r=e.advance(),s=Pl(e,r.type);if(r.type===w.DLESS||r.type===w.DLESSDASH)return Fd(e,t,n,r.type===w.DLESSDASH);e.isWord()||e.error("Expected redirection target");let i=e.parseWord();return F.redirection(s,i,t,n)}function Fd(e,t,n,r){e.isWord()||e.error("Expected here-document delimiter");let s=e.advance(),i=s.heredocDelimiter??s.value,a=s.quoted||!1,o=F.redirection(r?"<<-":"<<",F.hereDoc(i,F.word([]),r,a),t,n);return e.addPendingHeredoc(o,i,r,a),o}function xi(e){let t=e.getSourceLine(),n=[],r=null,s=[],i=[];for(;e.check(w.ASSIGNMENT_WORD)||ur(e);)e.checkIterationLimit(),e.check(w.ASSIGNMENT_WORD)?n.push(Md(e)):i.push(Yr(e));if(e.isWord())r=e.parseWord();else if(n.length>0&&(e.check(w.DBRACK_START)||e.check(w.DPAREN_START))){let o=e.advance();r=F.word([F.literal(o.value)])}for(;(!e.isStatementEnd()||e.check(w.RBRACE))&&!e.check(w.PIPE,w.PIPE_AMP);)if(e.checkIterationLimit(),ur(e))i.push(Yr(e));else if(e.check(w.ASSIGNMENT_WORD)){let o=e.advance(),l=o.value,u=l.endsWith("="),c=l.endsWith("=(");if((u||c)&&(c||e.check(w.LPAREN))){let f=c?l.slice(0,-2):l.slice(0,-1);c||e.expect(w.LPAREN);let d=ki(e);e.expect(w.RPAREN);let p=d.map(m=>vi(e,m)),h=`${f}=(${p.join(" ")})`;s.push(e.parseWordFromString(h,!1,!1,!0))}else{let f=e.parseWordFromString(l,o.quoted,o.singleQuoted,!0);s.push(e.parseAdjacentWordParts(f.parts,o.end,Re.Assignment))}}else if(e.isWord())s.push(e.parseWord());else if(e.check(w.RBRACE)){let o=e.advance();s.push(e.parseWordFromString(o.value,!1,!1))}else if(e.check(w.LBRACE)){let o=e.advance();s.push(e.parseWordFromString(o.value,!1,!1))}else if(e.check(w.DBRACK_END)){let o=e.advance();s.push(e.parseWordFromString(o.value,!1,!1))}else if(e.check(w.LPAREN))e.error("syntax error near unexpected token `('");else break;let a=F.simpleCommand(r,s,n,i);return a.line=t,a}function Md(e){let t=e.expect(w.ASSIGNMENT_WORD),n=t.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||e.error(`Invalid assignment: ${n}`);let s=r[0],i,a=s.length;if(n[a]==="["){let f=0,d=a+1;for(;a<n.length;a++)if(n[a]==="[")f++;else if(n[a]==="]"&&(f--,f===0))break;f!==0&&e.error(`Invalid assignment: ${n}`),i=Xr(n.slice(d,a)),a++}let o=n[a]==="+";o&&a++,n[a]!=="="&&e.error(`Invalid assignment: ${n}`),a++;let l=n.slice(a);if(l==="("){let f=ki(e);e.expect(w.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return F.assignment(d,null,o,f)}if(l===""&&e.check(w.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let d=ki(e);e.expect(w.RPAREN);let p=i!==void 0?`${s}[${i}]`:s;return F.assignment(p,null,o,d)}}let u=l?e.parseWordFromString(l,t.quoted,t.singleQuoted,!0):null;t.end===e.current().start&&e.isProcessSubstitutionStart()&&(u=e.parseAdjacentWordParts(u?.parts??[],t.end,Re.Assignment));let c=i!==void 0?`${s}[${i}]`:s;return F.assignment(c,u,o,null)}var Bd=new Set([w.AMP,w.PIPE,w.PIPE_AMP,w.SEMICOLON,w.AND_AND,w.OR_OR,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND]);function ki(e){let t=[];for(e.skipNewlines();!e.check(w.RPAREN,w.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):Bd.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function $i(e,t){e.expect(w.IF);let n=[],r=e.parseCompoundList();e.expect(w.THEN);let s=e.parseCompoundList();if(s.length===0){let o=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${o}'`)}for(n.push({condition:r,body:s});e.check(w.ELIF);){e.advance();let o=e.parseCompoundList();e.expect(w.THEN);let l=e.parseCompoundList();if(l.length===0){let u=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${u}'`)}n.push({condition:o,body:l})}let i=null;e.check(w.ELSE)&&(e.advance(),i=e.parseCompoundList(),i.length===0&&e.error("syntax error near unexpected token `fi'")),e.expect(w.FI);let a=t?.skipRedirections?[]:e.parseOptionalRedirections();return F.ifNode(n,i,a)}function Pi(e,t){let n=e.expect(w.FOR);if(e.check(w.DPAREN_START))return Vd(e,t,e.getSourceLine(n));e.isWord()||e.error("Expected variable name in for loop");let s=e.advance().value,i=null;if(e.skipNewlines(),e.check(w.IN))for(e.advance(),i=[];!e.check(w.SEMICOLON,w.NEWLINE,w.DO,w.EOF)&&e.isWord();)i.push(e.parseWord());e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines(),e.expect(w.DO);let a=e.parseCompoundList();e.expect(w.DONE);let o=t?.skipRedirections?[]:e.parseOptionalRedirections();return F.forNode(s,i,a,o)}function Vd(e,t,n){e.expect(w.DPAREN_START);let r=null,s=null,i=null,a=["","",""],o=0,l=0;for(;!e.check(w.DPAREN_END,w.EOF);){let f=e.advance();if(f.type===w.SEMICOLON&&l===0){if(o++,o>2)break}else f.value==="("&&l++,f.value===")"&&l--,a[o]+=f.value}e.expect(w.DPAREN_END),a[0].trim()&&(r=se(e,a[0].trim())),a[1].trim()&&(s=se(e,a[1].trim())),a[2].trim()&&(i=se(e,a[2].trim())),e.skipNewlines(),e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines();let u;e.check(w.LBRACE)?(e.advance(),u=e.parseCompoundList(),e.expect(w.RBRACE)):(e.expect(w.DO),u=e.parseCompoundList(),e.expect(w.DONE));let c=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:r,condition:s,update:i,body:u,redirections:c,line:n}}function Ci(e,t){e.expect(w.WHILE);let n=e.parseCompoundList();e.expect(w.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(w.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return F.whileNode(n,r,s)}function Ni(e,t){e.expect(w.UNTIL);let n=e.parseCompoundList();e.expect(w.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(w.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return F.untilNode(n,r,s)}function Ri(e,t){e.expect(w.CASE),e.isWord()||e.error("Expected word after 'case'");let n=e.parseWord();e.skipNewlines(),e.expect(w.IN),e.skipNewlines();let r=[];for(;!e.check(w.ESAC,w.EOF);){e.checkIterationLimit();let i=e.getPos(),a=zd(e);if(a&&r.push(a),e.skipNewlines(),e.getPos()===i&&!a)break}e.expect(w.ESAC);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return F.caseNode(n,r,s)}function zd(e){e.check(w.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(w.PIPE));)e.advance();if(t.length===0)return null;e.expect(w.RPAREN),e.skipNewlines();let n=[];for(;!e.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND,w.ESAC,w.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===w.RPAREN&&e.error("syntax error near unexpected token `)'"),e.check(w.LPAREN)&&e.peek(1).type===w.WORD&&e.error(`syntax error near unexpected token \`${e.peek(1).value}'`);let s=e.getPos(),i=e.parseStatement();if(i&&n.push(i),e.skipSeparators(!1),e.getPos()===s&&!i)break}let r=";;";return e.check(w.DSEMI)?(e.advance(),r=";;"):e.check(w.SEMI_AND)?(e.advance(),r=";&"):e.check(w.SEMI_SEMI_AND)&&(e.advance(),r=";;&"),F.caseItem(t,n,r)}function Di(e,t){e.expect(w.LPAREN);let n=e.parseCompoundList();e.expect(w.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return F.subshell(n,r)}function Ii(e,t){e.expect(w.LBRACE);let n=e.parseCompoundList();e.expect(w.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return F.group(n,r)}var qd=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],jd=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function Nl(e){return e.isWord()||e.check(w.LBRACE)||e.check(w.RBRACE)||e.check(w.ASSIGNMENT_WORD)}function Rl(e){if(e.check(w.BANG)&&e.peek(1).type===w.LPAREN){e.advance(),e.advance();let t=1,n="!(";for(;t>0&&!e.check(w.EOF);)if(e.check(w.LPAREN))t++,n+="(",e.advance();else if(e.check(w.RPAREN))t--,t>0&&(n+=")"),e.advance();else if(e.isWord())n+=e.advance().value;else if(e.check(w.PIPE))n+="|",e.advance();else break;return n+=")",e.parseWordFromString(n,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function _i(e){return e.skipNewlines(),Hd(e)}function Hd(e){let t=Dl(e);for(e.skipNewlines();e.check(w.OR_OR);){e.advance(),e.skipNewlines();let n=Dl(e);t={type:"CondOr",left:t,right:n},e.skipNewlines()}return t}function Dl(e){let t=Oi(e);for(e.skipNewlines();e.check(w.AND_AND);){e.advance(),e.skipNewlines();let n=Oi(e);t={type:"CondAnd",left:t,right:n},e.skipNewlines()}return t}function Oi(e){return e.skipNewlines(),e.check(w.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:e.withDepth(()=>Oi(e))}):Gd(e)}function Gd(e){if(e.check(w.LPAREN)){e.advance();let t=e.withDepth(()=>_i(e));return e.expect(w.RPAREN),{type:"CondGroup",expression:t}}if(Nl(e)){let t=e.current(),n=t.value;if(qd.includes(n)&&!t.quoted){if(e.advance(),e.check(w.DBRACK_END)&&e.error(`Expected operand after ${n}`),Nl(e)){let i=e.parseWordNoBraceExpansion();return{type:"CondUnary",operator:n,operand:i}}let s=e.current();e.error(`unexpected argument \`${s.value}' to conditional unary operator`)}let r=e.parseWordNoBraceExpansion();if(e.isWord()&&jd.includes(e.current().value)){let s=e.advance().value,i;return s==="=~"?i=Zd(e):s==="=="||s==="!="?i=Rl(e):i=e.parseWordNoBraceExpansion(),{type:"CondBinary",operator:s,left:r,right:i}}if(e.check(w.LESS)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:"<",left:r,right:s}}if(e.check(w.GREAT)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:">",left:r,right:s}}if(e.isWord()&&e.current().value==="="){e.advance();let s=Rl(e);return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}e.error("Expected conditional expression")}function Zd(e){let t=[],n=0,r=-1,s=e.getInput(),i=()=>e.check(w.DBRACK_END)||e.check(w.AND_AND)||e.check(w.OR_OR)||e.check(w.NEWLINE)||e.check(w.EOF);for(;!i();){let a=e.current(),o=r>=0&&a.start>r;if(n===0&&o)break;if(n>0&&o){let l=s.slice(r,a.start);t.push({type:"Literal",value:l})}if(e.isWord()||e.check(w.ASSIGNMENT_WORD)){let l=e.parseWordForRegex();t.push(...l.parts),r=e.peek(-1).end}else if(e.check(w.LPAREN)){let l=e.advance();t.push({type:"Literal",value:"("}),n++,r=l.end}else if(e.check(w.DPAREN_START)){let l=e.advance();t.push({type:"Literal",value:"(("}),n+=2,r=l.end}else if(e.check(w.DPAREN_END))if(n>=2){let l=e.advance();t.push({type:"Literal",value:"))"}),n-=2,r=l.end}else{if(n===1)break;break}else if(e.check(w.RPAREN))if(n>0){let l=e.advance();t.push({type:"Literal",value:")"}),n--,r=l.end}else break;else if(e.check(w.PIPE)){let l=e.advance();t.push({type:"Literal",value:"|"}),r=l.end}else if(e.check(w.SEMICOLON))if(n>0){let l=e.advance();t.push({type:"Literal",value:";"}),r=l.end}else break;else if(n>0&&e.check(w.LESS)){let l=e.advance();t.push({type:"Literal",value:"<"}),r=l.end}else if(n>0&&e.check(w.GREAT)){let l=e.advance();t.push({type:"Literal",value:">"}),r=l.end}else if(n>0&&e.check(w.DGREAT)){let l=e.advance();t.push({type:"Literal",value:">>"}),r=l.end}else if(n>0&&e.check(w.DLESS)){let l=e.advance();t.push({type:"Literal",value:"<<"}),r=l.end}else if(n>0&&e.check(w.LESSAND)){let l=e.advance();t.push({type:"Literal",value:"<&"}),r=l.end}else if(n>0&&e.check(w.GREATAND)){let l=e.advance();t.push({type:"Literal",value:">&"}),r=l.end}else if(n>0&&e.check(w.LESSGREAT)){let l=e.advance();t.push({type:"Literal",value:"<>"}),r=l.end}else if(n>0&&e.check(w.CLOBBER)){let l=e.advance();t.push({type:"Literal",value:">|"}),r=l.end}else if(n>0&&e.check(w.TLESS)){let l=e.advance();t.push({type:"Literal",value:"<<<"}),r=l.end}else if(n>0&&e.check(w.AMP)){let l=e.advance();t.push({type:"Literal",value:"&"}),r=l.end}else if(n>0&&e.check(w.LBRACE)){let l=e.advance();t.push({type:"Literal",value:"{"}),r=l.end}else if(n>0&&e.check(w.RBRACE)){let l=e.advance();t.push({type:"Literal",value:"}"}),r=l.end}else break}return t.length===0&&e.error("Expected regex pattern after =~"),{type:"Word",parts:t}}function Kd(e){let t="";for(let n=0;n<e.length;n++){let r=e[n],s=e[n+1];if(r!=="\\"||s===void 0){t+=r;continue}"\\[]^-".includes(s)&&(t+="\\"),t+=s,n++}return t}function cr(e){return e.length>0?e:[F.literal("")]}function Xd(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if("@*+?!".includes(s)&&r+1<e.length&&e[r+1]==="("){r++,n++,r++;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Yd(e,t,n){let r=n+1,s=t[r];if("@*#?$!-0123456789".includes(s))return{part:F.parameterExpansion(s),endIndex:r+1};let i="";for(;r<t.length&&/[a-zA-Z0-9_]/.test(t[r]);)i+=t[r],r++;return{part:F.parameterExpansion(i),endIndex:r}}function Jd(e,t,n,r=!1){let s=n+2,i=!1;t[s]==="!"&&(i=!0,s++);let a=!1;t[s]==="#"&&!/[}:#%/^,]/.test(t[s+1]||"}")&&(a=!0,s++);let o="",l=t[s];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(t[s+1]||""))o=l,s++;else for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)o+=t[s],s++;if(t[s]==="["){let c=Si(e,t,s,"[","]");if(o+=`[${Xr(t.slice(s+1,c))}]`,s=c+1,t[s]==="["){let f=1,d=s;for(;d<t.length&&f>0;)t[d]==="{"?f++:t[d]==="}"&&f--,f>0&&d++;let p=t.slice(n+2,d);return{part:F.parameterExpansion("",{type:"BadSubstitution",text:p}),endIndex:d+1}}}if(o===""&&!i&&!a&&t[s]!=="}"){let c=1,f=s;for(;f<t.length&&c>0;)t[f]==="{"?c++:t[f]==="}"&&c--,c>0&&f++;if(c>0)throw new xe("unexpected EOF while looking for matching '}'",0,0);let d=t.slice(n+2,f);return{part:F.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:f+1}}let u=null;if(i){let c=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(c)if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=Li(e,t,s,o,r);f.operation?(u={type:"Indirection",innerOp:f.operation},s=f.endIndex):(u={type:"ArrayKeys",array:c[1],star:c[2]==="*"},o="")}else u={type:"ArrayKeys",array:c[1],star:c[2]==="*"},o="";else if(t[s]==="*"||t[s]==="@"&&!/[QPaAEKkuUL]/.test(t[s+1]||"")){let f=t[s];s++,u={type:"VarNamePrefix",prefix:o,star:f==="*"},o=""}else if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=Li(e,t,s,o,r);f.operation?(u={type:"Indirection",innerOp:f.operation},s=f.endIndex):u={type:"Indirection"}}else u={type:"Indirection"}}else if(a)if(t[s]===":")for(u={type:"LengthSliceError"};s<t.length&&t[s]!=="}";)s++;else t[s]!=="}"&&/[-+=?]/.test(t[s])?e.error(`\${#${o}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):t[s]==="/"?e.error(`\${#${o}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):u={type:"Length"};if(!u&&s<t.length&&t[s]!=="}"){let c=Li(e,t,s,o,r);u=c.operation,s=c.endIndex}if(s<t.length&&t[s]!=="}"){let c=t[s];if(!/[:\-+=?#%/^,@[]/.test(c)){let f=s;for(;f<t.length&&t[f]!=="}";)f++;let d=t.slice(n,f+1);e.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<t.length&&t[s]!=="}";)s++;if(s>=t.length)throw new xe("unexpected EOF while looking for matching '}'",0,0);return{part:F.parameterExpansion(o,u),endIndex:s+1}}function Li(e,t,n,r,s=!1){let i=n,a=t[i],o=t[i+1]||"";if(a===":"){let l=o;if("-=?+".includes(l)){i+=2;let S=Sn(e,t,i),g=t.slice(i,S),y=e.withDepth(()=>Xt(e,g,!1,!1,!0,!1,s,!1,!1,!0)),b=F.word(cr(y));if(l==="-")return{operation:{type:"DefaultValue",word:b,checkEmpty:!0},endIndex:S};if(l==="=")return{operation:{type:"AssignDefault",word:b,checkEmpty:!0},endIndex:S};if(l==="?")return{operation:{type:"ErrorIfUnset",word:b,checkEmpty:!0},endIndex:S};if(l==="+")return{operation:{type:"UseAlternative",word:b,checkEmpty:!0},endIndex:S}}i++;let u=Sn(e,t,i),c=t.slice(i,u),f=-1,d=0,p=0;for(let E=0;E<c.length;E++){let S=c[E];if(S==="("||S==="[")d++;else if(S===")"||S==="]")d--;else if(S==="?"&&d===0)p++;else if(S===":"&&d===0)if(p>0)p--;else{f=E;break}}let h=f>=0?c.slice(0,f):c,m=f>=0?c.slice(f+1):null;return{operation:{type:"Substring",offset:Ai(e,h),length:m!==null?Ai(e,m):null},endIndex:u}}if("-=?+".includes(a)){i++;let l=Sn(e,t,i),u=t.slice(i,l),c=e.withDepth(()=>Xt(e,u,!1,!1,!0,!1,s,!1,!1,!0)),f=F.word(cr(c));if(a==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:l};if(a==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:l};if(a==="?")return{operation:{type:"ErrorIfUnset",word:u?f:null,checkEmpty:!1},endIndex:l};if(a==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:l}}if(a==="#"||a==="%"){let l=o===a,u=a==="#"?"prefix":"suffix";i+=l?2:1;let c=Sn(e,t,i),f=t.slice(i,c),d=e.withDepth(()=>Xt(e,f,!1,!1,!1));return{operation:{type:"PatternRemoval",pattern:F.word(cr(d)),side:u,greedy:l},endIndex:c}}if(a==="/"){let l=o==="/";i+=l?2:1;let u=null;t[i]==="#"?(u="start",i++):t[i]==="%"&&(u="end",i++);let c;u!==null&&(t[i]==="/"||t[i]==="}")?c=i:c=vl(e,t,i);let f=t.slice(i,c),d=e.withDepth(()=>Xt(e,f,!1,!1,!1)),p=F.word(cr(d)),h=null,m=c;if(t[c]==="/"){let E=c+1,S=Sn(e,t,E),g=t.slice(E,S),y=e.withDepth(()=>Xt(e,g,!1,!1,!1));h=F.word(cr(y)),m=S}return{operation:{type:"PatternReplacement",pattern:p,replacement:h,all:l,anchor:u},endIndex:m}}if(a==="^"||a===","){let l=o===a,u=a==="^"?"upper":"lower";i+=l?2:1;let c=Sn(e,t,i),f=t.slice(i,c),d=f?F.word([F.literal(f)]):null;return{operation:{type:"CaseModification",direction:u,all:l,pattern:d},endIndex:c}}return a==="@"&&/[QPaAEKkuUL]/.test(o)?{operation:{type:"Transform",operator:o},endIndex:i+2}:{operation:null,endIndex:i}}function Ti(e,t,n,r=!1){let s=n+1;if(s>=t.length)return{part:F.literal("$"),endIndex:s};let i=t[s];if(i==="("&&t[s+1]==="(")return e.isDollarDparenSubshell(t,n)?e.parseCommandSubstitution(t,n):e.parseArithmeticExpansion(t,n);if(i==="["){let a=1,o=s+1;for(;o<t.length&&a>0;)t[o]==="["?a++:t[o]==="]"&&a--,a>0&&o++;if(a===0){let l=t.slice(s+1,o),u=se(e,l);return{part:F.arithmeticExpansion(u),endIndex:o+1}}}return i==="("?e.parseCommandSubstitution(t,n):i==="{"?Jd(e,t,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Yd(e,t,n):{part:F.literal("$"),endIndex:s}}function Il(e,t){let n=[],r=0,s="",i=()=>{s&&(n.push(F.literal(s)),s="")};for(;r<t.length;){let a=t[r];if(a==="\\"&&r+1<t.length){let o=t[r+1];if(o==="$"||o==="`"||o==='"'||o==="\\"){s+=o,r+=2;continue}s+=a,r++;continue}if(a==="$"){i();let{part:o,endIndex:l}=Ti(e,t,r,!0);o&&n.push(o),r=l;continue}if(a==="`"){i();let{part:o,endIndex:l}=e.parseBacktickSubstitution(t,r,!0);n.push(o),r=l;continue}s+=a,r++}return i(),n}function ep(e,t,n){let r=[],s=n,i="",a=()=>{i&&(r.push(F.literal(i)),i="")};for(;s<t.length&&t[s]!=='"';){let o=t[s];if(o==="\\"&&s+1<t.length){let l=t[s+1];if('"\\$`\n'.includes(l)){i+=l,s+=2;continue}i+=o,s++;continue}if(o==="$"){a();let{part:l,endIndex:u}=Ti(e,t,s,!0);l&&r.push(l),s=u;continue}if(o==="`"){a();let{part:l,endIndex:u}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=u;continue}i+=o,s++}return a(),{part:F.doubleQuoted(r),endIndex:s}}function Xt(e,t,n=!1,r=!1,s=!1,i=!1,a=!1,o=!1,l=!1,u=!1,c=!0){if(r)return[F.singleQuoted(t)];if(n){let m=Il(e,t);return[F.doubleQuoted(m)]}if(t.length>=2&&t[0]==='"'&&t[t.length-1]==='"'){let m=t.slice(1,-1),E=!1;for(let S=0;S<m.length;S++){if(m[S]==='"'){E=!0;break}m[S]==="\\"&&S+1<m.length&&S++}if(!E){let S=Il(e,m);return[F.doubleQuoted(S)]}}let f=[],d=0,p="",h=()=>{p&&(f.push(F.literal(p)),p="")};for(;d<t.length;){let m=t[d];if(m==="\\"&&d+1<t.length){let E=t[d+1];if(l){h(),f.push(F.escaped(E)),d+=2;continue}if(!i&&!a){E!==`
|
|
70
|
+
`&&(h(),f.push(F.escaped(E))),d+=2;continue}let S=i?E==="$"||E==="`"||E===`
|
|
71
71
|
`:E==="$"||E==="`"||E==='"'||E==="'"||E===`
|
|
72
|
-
`||u&&E==="}",g=
|
|
73
|
-
`&&(p+=E):g?(h(),f.push(T.escaped(E))):p+=`\\${E}`,d+=2;continue}if(m==="'"&&!o&&!i){h();let E=t.indexOf("'",d+1);if(E===-1){p+=t.slice(d);break}f.push(T.singleQuoted(t.slice(d+1,E))),d=E+1;continue}if(m==='"'&&!i){h();let{part:E,endIndex:S}=Ud(e,t,d+1);f.push(E),d=S+1;continue}if(m==="$"&&t[d+1]==="'"){h();let{part:E,endIndex:S}=gl(e,t,d+2);f.push(E),d=S;continue}if(m==="$"){h();let{part:E,endIndex:S}=Ci(e,t,d);E&&f.push(E),d=S;continue}if(m==="`"){h();let{part:E,endIndex:S}=e.parseBacktickSubstitution(t,d);f.push(E),d=S;continue}if((m==="<"||m===">")&&t[d+1]==="("&&!i&&!o){h();let{part:E,endIndex:S}=e.parseProcessSubstitutionFromString(t,d);f.push(E),d=S;continue}if(m==="~"){let E=d>0?t[d-1]:"";if(d===0&&c||E==="="||s&&E===":"){let g=hl(e,t,d),y=t[g];if(y===void 0||y==="/"||y===":"){h();let b=t.slice(d+1,g)||null;f.push({type:"TildeExpansion",user:b}),d=g;continue}}}if("@*+?!".includes(m)&&d+1<t.length&&t[d+1]==="("){let E=Wd(t,d+1);if(E!==-1){h();let S=t.slice(d,E+1);f.push({type:"Glob",pattern:S}),d=E+1;continue}}if(m==="*"||m==="?"||m==="["){h();let{pattern:E,endIndex:S}=yl(e,t,d);f.push({type:"Glob",pattern:l?Bd(E):E}),d=S;continue}if(m==="{"&&!s&&!a&&!i){let E=wl(e,t,d,Qt);if(E){h(),f.push(E.part),d=E.endIndex;continue}}p+=m,d++}return h(),f}var j=class e{tokens=[];pos=0;pendingHeredocs=[];parseBudget;ownsParseBudget;_input="";processLineState;constructor(t){this.parseBudget=t??new Ur,this.ownsParseBudget=t===void 0}getInput(){return this._input}checkIterationLimit(){let t=this.current();this.parseBudget.chargeIteration(t?.line??1,t?.column??1)}enterDepth(){let t=this.current();return this.parseBudget.enter(t?.line??1,t?.column??1)}withDepth(t){let n=this.enterDepth();try{return t()}finally{n()}}parse(t,n){this.ownsParseBudget&&this.parseBudget.reset();let r=this.ownsParseBudget?void 0:this.enterDepth();try{if(t.length>ci)throw new ke(`Input too large: ${t.length} bytes exceeds limit of ${ci}`,1,1);this._input=t,this.processLineState=void 0;let s=new zr(t,n);if(this.tokens=s.tokenize(),this.tokens.length>tr)throw new ke(`Too many tokens: ${this.tokens.length} exceeds limit of ${tr}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseBudget.chargeTokens(this.tokens.length),this.parseScript()}finally{r?.()}}parseTokens(t){this.ownsParseBudget&&this.parseBudget.reset();let n=this.ownsParseBudget?void 0:this.enterDepth();try{return this.tokens=t,this.pos=0,this.pendingHeredocs=[],this.processLineState=void 0,this.parseBudget.chargeTokens(t.length),this.parseScript()}finally{n?.()}}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(t=0){return this.tokens[this.pos+t]||this.tokens[this.tokens.length-1]}advance(){let t=this.current();return this.pos<this.tokens.length-1&&this.pos++,t}getPos(){return this.pos}getSourceLine(t=this.current()){let n=this.processLineState;return n?(n.currentPhysicalLine===void 0?n.currentPhysicalLine=t.line:t.line>n.currentPhysicalLine&&(n.currentPhysicalLine=t.line,n.currentLogicalLine+=1),n.currentLogicalLine):t.line}check(t,n,r,s,...i){let o=this.tokens[this.pos]?.type;return o===t||n!==void 0&&o===n||r!==void 0&&o===r||s!==void 0&&o===s?!0:i.length>0?i.includes(o):!1}expect(t,n){if(this.check(t))return this.advance();let r=this.current();throw new ke(n||`Expected ${t}, got ${r.type}`,r.line,r.column,r)}error(t){let n=this.current();throw new ke(t,n.line,n.column,n)}skipNewlines(){for(;this.check(w.NEWLINE,w.COMMENT);)this.check(w.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(t=!0){for(;;){if(this.check(w.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(w.SEMICOLON,w.COMMENT)){this.advance();continue}if(t&&this.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(t,n,r,s){this.pendingHeredocs.push({redirect:t,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let t of this.pendingHeredocs)if(this.check(w.HEREDOC_CONTENT)){let n=this.advance(),r;t.quoted?r=T.word([T.literal(n.value)]):r=this.parseWordFromString(n.value,!1,!1,!1,!0),t.redirect.target=T.hereDoc(t.delimiter,r,t.stripTabs,t.quoted,n.heredocTerminated??!1)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(w.EOF,w.NEWLINE,w.SEMICOLON,w.AMP,w.AND_AND,w.OR_OR,w.RPAREN,w.RBRACE,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)}isCommandStart(){let t=this.current().type;return this.isWord()||t===w.ASSIGNMENT_WORD||t===w.FD_VARIABLE||t===w.LPAREN||t===w.LBRACE||t===w.DPAREN_START||t===w.DBRACK_START||sr(this)}parseScript(){let t=[],r=0;for(this.skipNewlines();!this.check(w.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)");let s=this.checkUnexpectedToken();if(s){t.push(s),this.skipSeparators(!1);continue}let i=this.pos,o=this.parseStatement();o&&t.push(o),this.check(w.HEREDOC_CONTENT)&&this.processHeredocs(),this.skipSeparators(!1),this.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===i&&!this.check(w.EOF)&&this.error(`syntax error near unexpected token \`${this.current().value}'`)}return T.script(t)}checkUnexpectedToken(){let t=this.current().type,n=this.current().value;if(this.currentTokenJoinsProcessSubstitution())return null;if((t===w.DO||t===w.DONE||t===w.THEN||t===w.ELSE||t===w.ELIF||t===w.FI||t===w.ESAC)&&this.error(`syntax error near unexpected token \`${n}'`),t===w.RBRACE||t===w.RPAREN){let r=`syntax error near unexpected token \`${n}'`;return this.advance(),T.statement([T.pipeline([T.simpleCommand(null,[],[],[])])],[],!1,{message:r,token:n})}return(t===w.DSEMI||t===w.SEMI_AND||t===w.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),t===w.SEMICOLON&&this.error(`syntax error near unexpected token \`${n}'`),(t===w.AMP||t===w.AND_AND||t===w.OR_OR||t===w.PIPE||t===w.PIPE_AMP)&&this.error(`syntax error near unexpected token \`${n}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let t=this.current().start,n=[],r=[],s=!1,i=this.parsePipeline();for(n.push(i);this.check(w.AND_AND,w.OR_OR);){let l=this.advance();r.push(l.type===w.AND_AND?"&&":"||"),this.skipNewlines();let u=this.parsePipeline();n.push(u)}this.check(w.AMP)&&(this.advance(),s=!0);let o=this.pos>0?this.tokens[this.pos-1].end:t,a=this._input.slice(t,o);return T.statement(n,r,s,void 0,a)}parseTimePrefix(){if(!this.check(w.TIME)||this.currentTokenJoinsProcessSubstitution())return;this.advance();let t=!1;return this.check(w.WORD,w.NAME)&&this.current().value==="-p"&&(this.advance(),t=!0),t}parsePipeline(){let t=!1,n=!1,r=0;for(;this.check(w.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),r++;if(r===0){let l=this.parseTimePrefix();if(l!==void 0)for(t=!0,n=l;this.check(w.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),r++}let s=r%2===1,i=[],o=[],a=this.parseCommand();for(i.push(a);this.check(w.PIPE,w.PIPE_AMP);){let l=this.advance();this.skipNewlines(),o.push(l.type===w.PIPE_AMP);let u=this.parseCommand();i.push(u)}return T.pipeline(i,s,t,n,o.length>0?o:void 0)}parseCommand(){if(this.currentTokenJoinsProcessSubstitution())return gi(this);let t=this.current();switch(t.type){case w.IF:return wi(this);case w.FOR:return Ei(this);case w.WHILE:return bi(this);case w.UNTIL:return Si(this);case w.CASE:return Ai(this);case w.LPAREN:return vi(this);case w.LBRACE:return ki(this);case w.DPAREN_START:return this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand();case w.DBRACK_START:return this.parseConditionalCommand();case w.FUNCTION:return this.parseFunctionDef();case w.TIME:break;case w.BANG:this.error(`syntax error near unexpected token \`${t.value}'`);break;default:ui(t.type)&&this.error(`syntax error near unexpected token \`${t.value}'`)}return this.check(w.NAME,w.WORD)&&this.peek(1).type===w.LPAREN&&this.peek(2).type===w.RPAREN?this.parseFunctionDef():gi(this)}dparenClosesWithSpacedParens(){let t=1,n=1;for(;n<this.tokens.length-this.pos;){let r=this.peek(n);if(r.type===w.EOF)return!1;if(r.type===w.DPAREN_START||r.type===w.LPAREN)t++;else if(r.type===w.DPAREN_END){if(t-=2,t<=0)return!1}else if(r.type===w.RPAREN&&(t--,t===0&&this.peek(n+1).type===w.RPAREN))return!0;n++}return!1}parseNestedSubshellsFromDparen(){this.advance();let t=this.parseCompoundList();this.expect(w.RPAREN),this.expect(w.RPAREN);let n=this.parseOptionalRedirections(),r=T.subshell(t,[]);return T.subshell([T.statement([T.pipeline([r],!1,!1,!1)])],n)}isWord(){return this.isWordToken(Ne.Default)||this.isProcessSubstitutionStart()||this.currentTokenJoinsProcessSubstitution()}isWordToken(t){let n=this.current().type;return n===w.WORD||n===w.NAME||n===w.NUMBER||ui(n)||n===w.BANG||n===w.ASSIGNMENT_WORD&&(t&Ne.Regex)!==0}isProcessSubstitutionStart(t=0){let n=this.peek(t),r=this.peek(t+1);return(n.type===w.LESS||n.type===w.GREAT)&&r.type===w.LPAREN&&n.end===r.start}currentTokenJoinsProcessSubstitution(){return this.current().type===w.COMMENT||!this.isAdjacentWordToken(Ne.Default)?!1:this.current().end===this.peek(1).start&&this.isProcessSubstitutionStart(1)}isAdjacentWordToken(t){let n=this.current().type;return this.isWordToken(t)||n===w.ASSIGNMENT_WORD||n===w.COMMENT||n===w.LBRACE||n===w.RBRACE||n===w.DBRACK_START||n===w.DBRACK_END||n===w.FD_VARIABLE}parseWord(t=Ne.Default){if(this.isProcessSubstitutionStart())return this.parseAdjacentWordParts([],this.current().start,t);let n=this.advance(),r=this.parseWordToken(n,t);return this.parseAdjacentWordParts(r.parts,n.end,t)}parseAdjacentWordParts(t,n,r=Ne.Default){for(;n===this.current().start;){if(this.isProcessSubstitutionStart()){t.push(this.parseProcessSubstitution()),n=this.tokens[this.pos-1].end;continue}if(!this.isAdjacentWordToken(r))break;let s=this.advance();t.push(...this.parseWordToken(s,r,t.length===0).parts),n=s.end}return T.word(t)}parseWordNoBraceExpansion(){return this.parseWord(Ne.NoBraceExpansion)}parseWordForRegex(){return this.parseWord(Ne.NoBraceExpansion|Ne.Regex)}parseWordToken(t,n,r=!0){return t.type===w.LBRACE||t.type===w.RBRACE||t.type===w.DBRACK_START||t.type===w.DBRACK_END||t.type===w.FD_VARIABLE?T.word([T.literal(t.type===w.FD_VARIABLE?`{${t.value}}`:t.value)]):this.parseWordFromString(t.value,t.quoted,t.singleQuoted,(n&Ne.Assignment)!==0,!1,(n&Ne.NoBraceExpansion)!==0,(n&Ne.Regex)!==0,r)}parseWordFromString(t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!0){let u=Qt(this,t,n,r,s,i,!1,o,a,!1,l);return T.word(u)}parseCommandSubstitution(t,n){return qa(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitutionFromString(t,n){return ja(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitution(){let t=this.advance();this.expect(w.LPAREN);let n=this.processLineState,r=this.getSourceLine(t);this.processLineState={currentLogicalLine:r};let s;try{s=T.script(this.parseCompoundList())}finally{this.processLineState=n}return this.check(w.EOF)&&this.error("unexpected EOF while looking for matching `)'"),this.expect(w.RPAREN),T.processSubstitution(s,t.type===w.LESS?"input":"output")}parseBacktickSubstitution(t,n,r=!1){return Ha(t,n,r,()=>new e(this.parseBudget),s=>this.error(s))}isDollarDparenSubshell(t,n){return za(t,n)}parseArithmeticExpansion(t,n){let r=n+3,s=1,i=0,o=r;for(;o<t.length-1&&s>0;)t[o]==="$"&&t[o+1]==="("?t[o+2]==="("?(s++,o+=3):(i++,o+=2):t[o]==="("&&t[o+1]==="("?(s++,o+=2):t[o]===")"&&t[o+1]===")"?i>0?(i--,o++):(s--,s>0&&(o+=2)):t[o]==="("?(i++,o++):(t[o]===")"&&i>0&&i--,o++);let a=t.slice(r,o),l=this.parseArithmeticExpression(a);return{part:T.arithmeticExpansion(l),endIndex:o+2}}parseArithmeticCommand(){let t=this.expect(w.DPAREN_START),n="",r=1,s=0,i=!1,o=!1;for(;r>0&&!this.check(w.EOF);){if(i){if(i=!1,s>0){s--,n+=")";continue}if(this.check(w.RPAREN)){r--,o=!0,this.advance();continue}if(this.check(w.DPAREN_END)){r--,o=!0;continue}n+=")";continue}if(this.check(w.DPAREN_START))r++,n+="((",this.advance();else if(this.check(w.DPAREN_END))s>=2?(s-=2,n+="))",this.advance()):s===1?(s--,n+=")",i=!0,this.advance()):(r--,o=!0,r>0&&(n+="))"),this.advance());else if(this.check(w.LPAREN))s++,n+="(",this.advance();else if(this.check(w.RPAREN))s>0&&s--,n+=")",this.advance();else{let u=this.current().value,c=n.length>0?n[n.length-1]:"";n.length>0&&!n.endsWith(" ")&&!(u==="="&&/[|&^+\-*/%<>]$/.test(n))&&!(u==="<"&&c==="<")&&!(u===">"&&c===">")&&(n+=" "),n+=u,this.advance()}}o||this.expect(w.DPAREN_END);let a=this.parseArithmeticExpression(n.trim()),l=this.parseOptionalRedirections();return T.arithmeticCommand(a,l,this.getSourceLine(t))}parseConditionalCommand(){let t=this.expect(w.DBRACK_START),n=xi(this);this.expect(w.DBRACK_END);let r=this.parseOptionalRedirections();return T.conditionalCommand(n,r,this.getSourceLine(t))}parseFunctionDef(){let t;if(this.check(w.FUNCTION)){if(this.advance(),this.check(w.NAME)||this.check(w.WORD))t=this.advance().value;else{let s=this.current();throw new ke("Expected function name",s.line,s.column,s)}this.check(w.LPAREN)&&(this.advance(),this.expect(w.RPAREN))}else t=this.advance().value,t.includes("$")&&this.error(`\`${t}': not a valid identifier`),this.expect(w.LPAREN),this.expect(w.RPAREN);this.skipNewlines();let n=this.parseCompoundCommandBody({forFunctionBody:!0}),r=this.parseOptionalRedirections();return T.functionDef(t,n,r)}parseCompoundCommandBody(t){let n=t?.forFunctionBody;if(this.check(w.LBRACE))return ki(this,{skipRedirections:n});if(this.check(w.LPAREN))return vi(this,{skipRedirections:n});if(this.check(w.IF))return wi(this,{skipRedirections:n});if(this.check(w.FOR))return Ei(this,{skipRedirections:n});if(this.check(w.WHILE))return bi(this,{skipRedirections:n});if(this.check(w.UNTIL))return Si(this,{skipRedirections:n});if(this.check(w.CASE))return Ai(this,{skipRedirections:n});this.error("Expected compound command for function body")}parseCompoundList(){let t=this.enterDepth();try{let n=[];for(this.skipNewlines();(this.currentTokenJoinsProcessSubstitution()||!this.check(w.EOF,w.FI,w.ELSE,w.ELIF,w.THEN,w.DO,w.DONE,w.ESAC,w.RPAREN,w.RBRACE,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND))&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,s=this.parseStatement();if(s&&n.push(s),this.skipSeparators(),this.pos===r&&!s)break}return n}finally{t()}}parseOptionalRedirections(){let t=[];for(;sr(this);){this.checkIterationLimit();let n=this.pos;if(t.push(Gr(this)),this.pos===n)break}return t}parseArithmeticExpression(t){return re(this,t)}};function ot(e,t){return new j().parse(e,t)}function $l(e){return Sn(e)}function Sn(e){return e.statements.map(xl).join(`
|
|
74
|
-
`)}function
|
|
75
|
-
${s}${n.delimiter}`}return e.operator==="<<<"?`${t}<<< ${
|
|
76
|
-
`)}function
|
|
77
|
-
${
|
|
78
|
-
${
|
|
72
|
+
`||u&&E==="}",g=a?"*?[]\\".includes(E):"*?[]\\(){}.^+".includes(E);S?E!==`
|
|
73
|
+
`&&(p+=E):g?(h(),f.push(F.escaped(E))):p+=`\\${E}`,d+=2;continue}if(m==="'"&&!a&&!i){h();let E=t.indexOf("'",d+1);if(E===-1){p+=t.slice(d);break}f.push(F.singleQuoted(t.slice(d+1,E))),d=E+1;continue}if(m==='"'&&!i){h();let{part:E,endIndex:S}=ep(e,t,d+1);f.push(E),d=S+1;continue}if(m==="$"&&t[d+1]==="'"){h();let{part:E,endIndex:S}=xl(e,t,d+2);f.push(E),d=S;continue}if(m==="$"){h();let{part:E,endIndex:S}=Ti(e,t,d);E&&f.push(E),d=S;continue}if(m==="`"){h();let{part:E,endIndex:S}=e.parseBacktickSubstitution(t,d);f.push(E),d=S;continue}if((m==="<"||m===">")&&t[d+1]==="("&&!i&&!a){h();let{part:E,endIndex:S}=e.parseProcessSubstitutionFromString(t,d);f.push(E),d=S;continue}if(m==="~"){let E=d>0?t[d-1]:"";if(d===0&&c||E==="="||s&&E===":"){let g=Al(e,t,d),y=t[g];if(y===void 0||y==="/"||y===":"){h();let b=t.slice(d+1,g)||null;f.push({type:"TildeExpansion",user:b}),d=g;continue}}}if("@*+?!".includes(m)&&d+1<t.length&&t[d+1]==="("){let E=Xd(t,d+1);if(E!==-1){h();let S=t.slice(d,E+1);f.push({type:"Glob",pattern:S}),d=E+1;continue}}if(m==="*"||m==="?"||m==="["){h();let{pattern:E,endIndex:S}=kl(e,t,d);f.push({type:"Glob",pattern:l?Kd(E):E}),d=S;continue}if(m==="{"&&!s&&!o&&!i){let E=$l(e,t,d,Xt);if(E){h(),f.push(E.part),d=E.endIndex;continue}}p+=m,d++}return h(),f}var H=class e{tokens=[];pos=0;pendingHeredocs=[];parseBudget;ownsParseBudget;_input="";processLineState;constructor(t){this.parseBudget=t??new Zr,this.ownsParseBudget=t===void 0}getInput(){return this._input}checkIterationLimit(){let t=this.current();this.parseBudget.chargeIteration(t?.line??1,t?.column??1)}enterDepth(){let t=this.current();return this.parseBudget.enter(t?.line??1,t?.column??1)}withDepth(t){let n=this.enterDepth();try{return t()}finally{n()}}parse(t,n){this.ownsParseBudget&&this.parseBudget.reset();let r=this.ownsParseBudget?void 0:this.enterDepth();try{if(t.length>wi)throw new xe(`Input too large: ${t.length} bytes exceeds limit of ${wi}`,1,1);this._input=t,this.processLineState=void 0;let s=new Gr(t,n);if(this.tokens=s.tokenize(),this.tokens.length>ar)throw new xe(`Too many tokens: ${this.tokens.length} exceeds limit of ${ar}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseBudget.chargeTokens(this.tokens.length),this.parseScript()}finally{r?.()}}parseTokens(t){this.ownsParseBudget&&this.parseBudget.reset();let n=this.ownsParseBudget?void 0:this.enterDepth();try{return this.tokens=t,this.pos=0,this.pendingHeredocs=[],this.processLineState=void 0,this.parseBudget.chargeTokens(t.length),this.parseScript()}finally{n?.()}}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(t=0){return this.tokens[this.pos+t]||this.tokens[this.tokens.length-1]}advance(){let t=this.current();return this.pos<this.tokens.length-1&&this.pos++,t}getPos(){return this.pos}getSourceLine(t=this.current()){let n=this.processLineState;return n?(n.currentPhysicalLine===void 0?n.currentPhysicalLine=t.line:t.line>n.currentPhysicalLine&&(n.currentPhysicalLine=t.line,n.currentLogicalLine+=1),n.currentLogicalLine):t.line}check(t,n,r,s,...i){let a=this.tokens[this.pos]?.type;return a===t||n!==void 0&&a===n||r!==void 0&&a===r||s!==void 0&&a===s?!0:i.length>0?i.includes(a):!1}expect(t,n){if(this.check(t))return this.advance();let r=this.current();throw new xe(n||`Expected ${t}, got ${r.type}`,r.line,r.column,r)}error(t){let n=this.current();throw new xe(t,n.line,n.column,n)}skipNewlines(){for(;this.check(w.NEWLINE,w.COMMENT);)this.check(w.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(t=!0){for(;;){if(this.check(w.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(w.SEMICOLON,w.COMMENT)){this.advance();continue}if(t&&this.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(t,n,r,s){this.pendingHeredocs.push({redirect:t,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let t of this.pendingHeredocs)if(this.check(w.HEREDOC_CONTENT)){let n=this.advance(),r;t.quoted?r=F.word([F.literal(n.value)]):r=this.parseWordFromString(n.value,!1,!1,!1,!0),t.redirect.target=F.hereDoc(t.delimiter,r,t.stripTabs,t.quoted,n.heredocTerminated??!1)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(w.EOF,w.NEWLINE,w.SEMICOLON,w.AMP,w.AND_AND,w.OR_OR,w.RPAREN,w.RBRACE,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)}isCommandStart(){let t=this.current().type;return this.isWord()||t===w.ASSIGNMENT_WORD||t===w.FD_VARIABLE||t===w.LPAREN||t===w.LBRACE||t===w.DPAREN_START||t===w.DBRACK_START||ur(this)}parseScript(){let t=[],r=0;for(this.skipNewlines();!this.check(w.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)");let s=this.checkUnexpectedToken();if(s){t.push(s),this.skipSeparators(!1);continue}let i=this.pos,a=this.parseStatement();a&&t.push(a),this.check(w.HEREDOC_CONTENT)&&this.processHeredocs(),this.skipSeparators(!1),this.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===i&&!this.check(w.EOF)&&this.error(`syntax error near unexpected token \`${this.current().value}'`)}return F.script(t)}checkUnexpectedToken(){let t=this.current().type,n=this.current().value;if(this.currentTokenJoinsProcessSubstitution())return null;if((t===w.DO||t===w.DONE||t===w.THEN||t===w.ELSE||t===w.ELIF||t===w.FI||t===w.ESAC)&&this.error(`syntax error near unexpected token \`${n}'`),t===w.RBRACE||t===w.RPAREN){let r=`syntax error near unexpected token \`${n}'`;return this.advance(),F.statement([F.pipeline([F.simpleCommand(null,[],[],[])])],[],!1,{message:r,token:n})}return(t===w.DSEMI||t===w.SEMI_AND||t===w.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),t===w.SEMICOLON&&this.error(`syntax error near unexpected token \`${n}'`),(t===w.AMP||t===w.AND_AND||t===w.OR_OR||t===w.PIPE||t===w.PIPE_AMP)&&this.error(`syntax error near unexpected token \`${n}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let t=this.current().start,n=[],r=[],s=!1,i=this.parsePipeline();for(n.push(i);this.check(w.AND_AND,w.OR_OR);){let l=this.advance();r.push(l.type===w.AND_AND?"&&":"||"),this.skipNewlines();let u=this.parsePipeline();n.push(u)}this.check(w.AMP)&&(this.advance(),s=!0);let a=this.pos>0?this.tokens[this.pos-1].end:t,o=this._input.slice(t,a);return F.statement(n,r,s,void 0,o)}parseTimePrefix(){if(!this.check(w.TIME)||this.currentTokenJoinsProcessSubstitution())return;this.advance();let t=!1;return this.check(w.WORD,w.NAME)&&this.current().value==="-p"&&(this.advance(),t=!0),t}parsePipeline(){let t=!1,n=!1,r=0;for(;this.check(w.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),r++;if(r===0){let l=this.parseTimePrefix();if(l!==void 0)for(t=!0,n=l;this.check(w.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),r++}let s=r%2===1,i=[],a=[],o=this.parseCommand();for(i.push(o);this.check(w.PIPE,w.PIPE_AMP);){let l=this.advance();this.skipNewlines(),a.push(l.type===w.PIPE_AMP);let u=this.parseCommand();i.push(u)}return F.pipeline(i,s,t,n,a.length>0?a:void 0)}parseCommand(){if(this.currentTokenJoinsProcessSubstitution())return xi(this);let t=this.current();switch(t.type){case w.IF:return $i(this);case w.FOR:return Pi(this);case w.WHILE:return Ci(this);case w.UNTIL:return Ni(this);case w.CASE:return Ri(this);case w.LPAREN:return Di(this);case w.LBRACE:return Ii(this);case w.DPAREN_START:return this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand();case w.DBRACK_START:return this.parseConditionalCommand();case w.FUNCTION:return this.parseFunctionDef();case w.TIME:break;case w.BANG:this.error(`syntax error near unexpected token \`${t.value}'`);break;default:gi(t.type)&&this.error(`syntax error near unexpected token \`${t.value}'`)}return this.check(w.NAME,w.WORD)&&this.peek(1).type===w.LPAREN&&this.peek(2).type===w.RPAREN?this.parseFunctionDef():xi(this)}dparenClosesWithSpacedParens(){let t=1,n=1;for(;n<this.tokens.length-this.pos;){let r=this.peek(n);if(r.type===w.EOF)return!1;if(r.type===w.DPAREN_START||r.type===w.LPAREN)t++;else if(r.type===w.DPAREN_END){if(t-=2,t<=0)return!1}else if(r.type===w.RPAREN&&(t--,t===0&&this.peek(n+1).type===w.RPAREN))return!0;n++}return!1}parseNestedSubshellsFromDparen(){this.advance();let t=this.parseCompoundList();this.expect(w.RPAREN),this.expect(w.RPAREN);let n=this.parseOptionalRedirections(),r=F.subshell(t,[]);return F.subshell([F.statement([F.pipeline([r],!1,!1,!1)])],n)}isWord(){return this.isWordToken(Re.Default)||this.isProcessSubstitutionStart()||this.currentTokenJoinsProcessSubstitution()}isWordToken(t){let n=this.current().type;return n===w.WORD||n===w.NAME||n===w.NUMBER||gi(n)||n===w.BANG||n===w.ASSIGNMENT_WORD&&(t&Re.Regex)!==0}isProcessSubstitutionStart(t=0){let n=this.peek(t),r=this.peek(t+1);return(n.type===w.LESS||n.type===w.GREAT)&&r.type===w.LPAREN&&n.end===r.start}currentTokenJoinsProcessSubstitution(){return this.current().type===w.COMMENT||!this.isAdjacentWordToken(Re.Default)?!1:this.current().end===this.peek(1).start&&this.isProcessSubstitutionStart(1)}isAdjacentWordToken(t){let n=this.current().type;return this.isWordToken(t)||n===w.ASSIGNMENT_WORD||n===w.COMMENT||n===w.LBRACE||n===w.RBRACE||n===w.DBRACK_START||n===w.DBRACK_END||n===w.FD_VARIABLE}parseWord(t=Re.Default){if(this.isProcessSubstitutionStart())return this.parseAdjacentWordParts([],this.current().start,t);let n=this.advance(),r=this.parseWordToken(n,t);return this.parseAdjacentWordParts(r.parts,n.end,t)}parseAdjacentWordParts(t,n,r=Re.Default){for(;n===this.current().start;){if(this.isProcessSubstitutionStart()){t.push(this.parseProcessSubstitution()),n=this.tokens[this.pos-1].end;continue}if(!this.isAdjacentWordToken(r))break;let s=this.advance();t.push(...this.parseWordToken(s,r,t.length===0).parts),n=s.end}return F.word(t)}parseWordNoBraceExpansion(){return this.parseWord(Re.NoBraceExpansion)}parseWordForRegex(){return this.parseWord(Re.NoBraceExpansion|Re.Regex)}parseWordToken(t,n,r=!0){return t.type===w.LBRACE||t.type===w.RBRACE||t.type===w.DBRACK_START||t.type===w.DBRACK_END||t.type===w.FD_VARIABLE?F.word([F.literal(t.type===w.FD_VARIABLE?`{${t.value}}`:t.value)]):this.parseWordFromString(t.value,t.quoted,t.singleQuoted,(n&Re.Assignment)!==0,!1,(n&Re.NoBraceExpansion)!==0,(n&Re.Regex)!==0,r)}parseWordFromString(t,n=!1,r=!1,s=!1,i=!1,a=!1,o=!1,l=!0){let u=Xt(this,t,n,r,s,i,!1,a,o,!1,l);return F.word(u)}parseCommandSubstitution(t,n){return Yo(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitutionFromString(t,n){return Jo(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitution(){let t=this.advance();this.expect(w.LPAREN);let n=this.processLineState,r=this.getSourceLine(t);this.processLineState={currentLogicalLine:r};let s;try{s=F.script(this.parseCompoundList())}finally{this.processLineState=n}return this.check(w.EOF)&&this.error("unexpected EOF while looking for matching `)'"),this.expect(w.RPAREN),F.processSubstitution(s,t.type===w.LESS?"input":"output")}parseBacktickSubstitution(t,n,r=!1){return el(t,n,r,()=>new e(this.parseBudget),s=>this.error(s))}isDollarDparenSubshell(t,n){return Ko(t,n)}parseArithmeticExpansion(t,n){let r=n+3,s=1,i=0,a=r;for(;a<t.length-1&&s>0;)t[a]==="$"&&t[a+1]==="("?t[a+2]==="("?(s++,a+=3):(i++,a+=2):t[a]==="("&&t[a+1]==="("?(s++,a+=2):t[a]===")"&&t[a+1]===")"?i>0?(i--,a++):(s--,s>0&&(a+=2)):t[a]==="("?(i++,a++):(t[a]===")"&&i>0&&i--,a++);let o=t.slice(r,a),l=this.parseArithmeticExpression(o);return{part:F.arithmeticExpansion(l),endIndex:a+2}}parseArithmeticCommand(){let t=this.expect(w.DPAREN_START),n="",r=1,s=0,i=!1,a=!1;for(;r>0&&!this.check(w.EOF);){if(i){if(i=!1,s>0){s--,n+=")";continue}if(this.check(w.RPAREN)){r--,a=!0,this.advance();continue}if(this.check(w.DPAREN_END)){r--,a=!0;continue}n+=")";continue}if(this.check(w.DPAREN_START))r++,n+="((",this.advance();else if(this.check(w.DPAREN_END))s>=2?(s-=2,n+="))",this.advance()):s===1?(s--,n+=")",i=!0,this.advance()):(r--,a=!0,r>0&&(n+="))"),this.advance());else if(this.check(w.LPAREN))s++,n+="(",this.advance();else if(this.check(w.RPAREN))s>0&&s--,n+=")",this.advance();else{let u=this.current().value,c=n.length>0?n[n.length-1]:"";n.length>0&&!n.endsWith(" ")&&!(u==="="&&/[|&^+\-*/%<>]$/.test(n))&&!(u==="<"&&c==="<")&&!(u===">"&&c===">")&&(n+=" "),n+=u,this.advance()}}a||this.expect(w.DPAREN_END);let o=this.parseArithmeticExpression(n.trim()),l=this.parseOptionalRedirections();return F.arithmeticCommand(o,l,this.getSourceLine(t))}parseConditionalCommand(){let t=this.expect(w.DBRACK_START),n=_i(this);this.expect(w.DBRACK_END);let r=this.parseOptionalRedirections();return F.conditionalCommand(n,r,this.getSourceLine(t))}parseFunctionDef(){let t;if(this.check(w.FUNCTION)){if(this.advance(),this.check(w.NAME)||this.check(w.WORD))t=this.advance().value;else{let s=this.current();throw new xe("Expected function name",s.line,s.column,s)}this.check(w.LPAREN)&&(this.advance(),this.expect(w.RPAREN))}else t=this.advance().value,t.includes("$")&&this.error(`\`${t}': not a valid identifier`),this.expect(w.LPAREN),this.expect(w.RPAREN);this.skipNewlines();let n=this.parseCompoundCommandBody({forFunctionBody:!0}),r=this.parseOptionalRedirections();return F.functionDef(t,n,r)}parseCompoundCommandBody(t){let n=t?.forFunctionBody;if(this.check(w.LBRACE))return Ii(this,{skipRedirections:n});if(this.check(w.LPAREN))return Di(this,{skipRedirections:n});if(this.check(w.IF))return $i(this,{skipRedirections:n});if(this.check(w.FOR))return Pi(this,{skipRedirections:n});if(this.check(w.WHILE))return Ci(this,{skipRedirections:n});if(this.check(w.UNTIL))return Ni(this,{skipRedirections:n});if(this.check(w.CASE))return Ri(this,{skipRedirections:n});this.error("Expected compound command for function body")}parseCompoundList(){let t=this.enterDepth();try{let n=[];for(this.skipNewlines();(this.currentTokenJoinsProcessSubstitution()||!this.check(w.EOF,w.FI,w.ELSE,w.ELIF,w.THEN,w.DO,w.DONE,w.ESAC,w.RPAREN,w.RBRACE,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND))&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,s=this.parseStatement();if(s&&n.push(s),this.skipSeparators(),this.pos===r&&!s)break}return n}finally{t()}}parseOptionalRedirections(){let t=[];for(;ur(this);){this.checkIterationLimit();let n=this.pos;if(t.push(Yr(this)),this.pos===n)break}return t}parseArithmeticExpression(t){return se(this,t)}};function ot(e,t){return new H().parse(e,t)}function Ol(e){return vn(e)}function vn(e){return e.statements.map(_l).join(`
|
|
74
|
+
`)}function _l(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(np(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let n=t.join(" ");return e.background&&(n+=" &"),n}function np(e){let t=[];e.timed&&t.push(e.timePosix?"time -p":"time"),e.negated&&t.push("!");let n=[];for(let s=0;s<e.commands.length;s++)if(n.push(Ll(e.commands[s])),s<e.commands.length-1){let i=e.pipeStderr?.[s];n.push(i?"|&":"|")}return(t.length>0?`${t.join(" ")} `:"")+n.join(" ")}function Ll(e){switch(e.type){case"SimpleCommand":return rp(e);case"If":return dp(e);case"For":return pp(e);case"CStyleFor":return hp(e);case"While":return mp(e);case"Until":return yp(e);case"Case":return gp(e);case"Subshell":return Ep(e);case"Group":return bp(e);case"ArithmeticCommand":return Sp(e);case"ConditionalCommand":return Ap(e);case"FunctionDef":return vp(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function rp(e){let t=[];for(let n of e.assignments)t.push(sp(n));e.name&&t.push(Ae(e.name));for(let n of e.args)t.push(Ae(n));for(let n of e.redirections)t.push(Ml(n));return t.join(" ")}function sp(e){let t=e.append?"+=":"=";if(e.array){let n=e.array.map(Ae).join(" ");return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${Ae(e.value)}`:`${e.name}${t}`}function Ae(e){return e.parts.map(t=>Jr(t,!1)).join("")}function Yt(e){return e.parts.map(t=>Jr(t,!0)).join("")}function Jr(e,t){switch(e.type){case"Literal":return t?ap(e.value):ip(e.value);case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(n=>Jr(n,!0)).join("")}"`;case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return Tl(e);case"CommandSubstitution":return e.legacy?`\`${vn(e.body)}\``:`$(${vn(e.body)})`;case"ArithmeticExpansion":return`$((${de(e.expression.expression)}))`;case"ProcessSubstitution":return e.direction==="input"?`<(${vn(e.body)})`:`>(${vn(e.body)})`;case"BraceExpansion":return cp(e);case"TildeExpansion":return e.user!==null?`~${e.user}`:"~";case"Glob":return e.pattern;default:{let n=e;throw new Error(`Unsupported word part type: ${n.type}`)}}}function ip(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,"\\$&")}function ap(e){return e.replace(/[$`"\\]/g,"\\$&")}function op(e,t){return e.parts.map(n=>lp(n,t)).join("")}function lp(e,t){switch(e.type){case"Literal":return t?e.value:e.value.replace(/[$`]/g,"\\$&");case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return Tl(e);case"CommandSubstitution":return e.legacy?`\`${vn(e.body)}\``:`$(${vn(e.body)})`;case"ArithmeticExpansion":return`$((${de(e.expression.expression)}))`;default:return Jr(e,!1)}}function Tl(e){return e.operation?`\${${Fl(e.parameter,e.operation)}}`:up(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function up(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function Fl(e,t){switch(t.type){case"Length":return`#${e}`;case"LengthSliceError":return`#${e}:`;case"BadSubstitution":return t.text;case"DefaultValue":return`${e}${t.checkEmpty?":":""}-${Yt(t.word)}`;case"AssignDefault":return`${e}${t.checkEmpty?":":""}=${Yt(t.word)}`;case"ErrorIfUnset":return`${e}${t.checkEmpty?":":""}?${t.word?Yt(t.word):""}`;case"UseAlternative":return`${e}${t.checkEmpty?":":""}+${Yt(t.word)}`;case"Substring":{let n=de(t.offset.expression);return t.length?`${e}:${n}:${de(t.length.expression)}`:`${e}:${n}`}case"PatternRemoval":{let n=t.side==="prefix"?"#":"%",r=t.greedy?`${n}${n}`:n;return`${e}${r}${Yt(t.pattern)}`}case"PatternReplacement":{let n="/";t.all?n="//":t.anchor==="start"?n="/#":t.anchor==="end"&&(n="/%");let r=t.replacement?`/${Yt(t.replacement)}`:"";return`${e}${n}${Yt(t.pattern)}${r}`}case"CaseModification":{let n=t.direction==="upper"?"^":",",r=t.all?`${n}${n}`:n,s=t.pattern?Yt(t.pattern):"";return`${e}${r}${s}`}case"Transform":return`${e}@${t.operator}`;case"Indirection":return t.innerOp?`!${Fl(e,t.innerOp)}`:`!${e}`;case"ArrayKeys":return`!${t.array}[${t.star?"*":"@"}]`;case"VarNamePrefix":return`!${t.prefix}${t.star?"*":"@"}`;default:{let n=t;throw new Error(`Unsupported parameter operation type: ${n.type}`)}}}function cp(e){return`{${e.items.map(fp).join(",")}}`}function fp(e){if(e.type==="Word")return Ae(e.word);let t=e.startStr??String(e.start),n=e.endStr??String(e.end);return e.step!==void 0?`${t}..${n}..${e.step}`:`${t}..${n}`}function Ml(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd!==null?String(e.fd):"";if(e.operator==="<<"||e.operator==="<<-"){let n=e.target;if(n.terminated===!1)throw new Error("Cannot serialize an unterminated here-document");let r=n.quoted?`'${n.delimiter}'`:n.delimiter,s=op(n.content,n.quoted);return`${t}${e.operator}${r}
|
|
75
|
+
${s}${n.delimiter}`}return e.operator==="<<<"?`${t}<<< ${Ae(e.target)}`:e.operator==="&>"||e.operator==="&>>"?`${e.operator} ${Ae(e.target)}`:`${t}${e.operator} ${Ae(e.target)}`}function mt(e){return e.length===0?"":` ${e.map(Ml).join(" ")}`}function lt(e){return e.map(_l).join(`
|
|
76
|
+
`)}function dp(e){let t=[];for(let n=0;n<e.clauses.length;n++){let r=e.clauses[n],s=n===0?"if":"elif";t.push(`${s} ${lt(r.condition)}; then
|
|
77
|
+
${lt(r.body)}`)}return e.elseBody&&t.push(`else
|
|
78
|
+
${lt(e.elseBody)}`),`${t.join(`
|
|
79
79
|
`)}
|
|
80
|
-
fi${
|
|
81
|
-
${
|
|
82
|
-
done${
|
|
83
|
-
${
|
|
84
|
-
done${
|
|
85
|
-
${
|
|
86
|
-
done${
|
|
87
|
-
${
|
|
88
|
-
done${
|
|
89
|
-
`);return`case ${
|
|
80
|
+
fi${mt(e.redirections)}`}function pp(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map(Ae).join(" ");t=`for ${e.variable} in ${n}`}return`${t}; do
|
|
81
|
+
${lt(e.body)}
|
|
82
|
+
done${mt(e.redirections)}`}function hp(e){let t=e.init?de(e.init.expression):"",n=e.condition?de(e.condition.expression):"",r=e.update?de(e.update.expression):"";return`for ((${t}; ${n}; ${r})); do
|
|
83
|
+
${lt(e.body)}
|
|
84
|
+
done${mt(e.redirections)}`}function mp(e){return`while ${lt(e.condition)}; do
|
|
85
|
+
${lt(e.body)}
|
|
86
|
+
done${mt(e.redirections)}`}function yp(e){return`until ${lt(e.condition)}; do
|
|
87
|
+
${lt(e.body)}
|
|
88
|
+
done${mt(e.redirections)}`}function gp(e){let t=e.items.map(wp).join(`
|
|
89
|
+
`);return`case ${Ae(e.word)} in
|
|
90
90
|
${t}
|
|
91
|
-
esac${
|
|
91
|
+
esac${mt(e.redirections)}`}function wp(e){let t=e.patterns.map(Ae).join(" | "),n=lt(e.body);return n?`${t})
|
|
92
92
|
${n}
|
|
93
93
|
${e.terminator}`:`${t})
|
|
94
|
-
${e.terminator}`}function lp(e){return`(${at(e.body)})${pt(e.redirections)}`}function up(e){return`{ ${at(e.body)}; }${pt(e.redirections)}`}function cp(e){return`((${fe(e.expression.expression)}))${pt(e.redirections)}`}function fp(e){return`[[ ${bn(e.expression)} ]]${pt(e.redirections)}`}function dp(e){let t=Pl(e.body);return`${e.name}() ${t}${pt(e.redirections)}`}function fe(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${fe(e.left)} ${e.operator} ${fe(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${fe(e.operand)}`:`${fe(e.operand)}${e.operator}`;case"ArithTernary":return`${fe(e.condition)} ? ${fe(e.consequent)} : ${fe(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${fe(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${fe(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${fe(e.target)}[${fe(e.subscript)}]`:fe(e.target)} ${e.operator} ${fe(e.value)}`;case"ArithDynamicElement":return`${fe(e.nameExpr)}[${fe(e.subscript)}]`;case"ArithGroup":return`(${fe(e.expression)})`;case"ArithNested":return`$((${fe(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${fe(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(fe).join("");case"ArithDoubleSubscript":return`${e.array}[${fe(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function bn(e){switch(e.type){case"CondBinary":return`${Se(e.left)} ${e.operator} ${Se(e.right)}`;case"CondUnary":return`${e.operator} ${Se(e.operand)}`;case"CondNot":return`! ${bn(e.operand)}`;case"CondAnd":return`${bn(e.left)} && ${bn(e.right)}`;case"CondOr":return`${bn(e.left)} || ${bn(e.right)}`;case"CondGroup":return`( ${bn(e.expression)} )`;case"CondWord":return Se(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var pp="BASH_ALIAS_";function Qr(e,t,n,r){let s=M(t);if(s>n-r.value)throw new P(`alias expansion exceeds string length limit (${n} bytes)`,"string_length");return r.value+=s,e+t}function Dl(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Il(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Ol(e,t){return e.env.get(`${pp}${t}`)}function Ll(e,t,n){return Tl(e,t,n)}function Tl(e,t,n,r=!0){if(!t.name||!Dl(t.name))return t;let s=Il(t.name);if(!s)return t;let i=Ol(e,s);if(!i||n.has(s))return t;try{n.add(s);let o=new j,a={value:0},l=Qr("",i,e.limits.maxStringLength,a),u=i.endsWith(" ");if(!u)for(let p of t.args){let h=Se(p);l=Qr(l,` ${h}`,e.limits.maxStringLength,a)}let c;try{c=o.parse(l)}catch(p){if(p instanceof ke)throw p;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return _l(e,t,i);let f=c.statements[0].pipelines[0].commands[0];if(f.type!=="SimpleCommand")return _l(e,t,i);let d={...f,assignments:[...t.assignments,...f.assignments],redirections:[...f.redirections,...t.redirections],line:t.line};if(u&&t.args.length>0){d={...d,args:[...d.args,...t.args]};let p=1;for(;r&&d.args.length>0;){let h=d.args[0];if(!Dl(h))break;let m=Il(h),E=m?Ol(e,m):null;if(!E)break;if(p>=e.limits.maxCallDepth)throw new P(`alias expansion depth limit exceeded (${e.limits.maxCallDepth})`,"recursion");p++;let S={type:"SimpleCommand",name:h,args:d.args.slice(1),assignments:[],redirections:[]},g=Tl(e,S,n,!1);if(g===S||(d={...d,name:g.name,args:[...g.args]},!E.endsWith(" ")))break}}return d}catch(o){throw n.delete(s),o}}function _l(e,t,n){let r={value:0},s=Qr("",n,e.limits.maxStringLength,r);for(let u of t.args){let c=Se(u);s=Qr(s,` ${c}`,e.limits.maxStringLength,r)}let i=new j,o=i.parseWordFromString("eval",!1,!1),a=0;for(let u of s)u==="'"&&a++;if(r.value+2+a*3>e.limits.maxStringLength)throw new P(`alias expansion exceeds string length limit (${e.limits.maxStringLength} bytes)`,"string_length");let l=i.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:o,args:[l],assignments:t.assignments,redirections:t.redirections,line:t.line}}var hp=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9a-fA-F"]]);function Ni(e){return hp.get(e)??""}function Fl(e){let t=[],n="",r=0;for(;r<e.length;){let s=e[r];if(s==="["){for(n+=s,r++,r<e.length&&(e[r]==="!"||e[r]==="^")&&(n+=e[r],r++),r<e.length&&e[r]==="]"&&(n+=e[r],r++);r<e.length&&e[r]!=="]";){if(e[r]==="["&&r+1<e.length&&e[r+1]===":"){let i=e.indexOf(":]",r+2);if(i!==-1){n+=e.slice(r,i+2),r=i+2;continue}}if(e[r]==="\\"&&r+1<e.length){n+=e[r]+e[r+1],r+=2;continue}n+=e[r],r++}r<e.length&&e[r]==="]"&&(n+=e[r],r++)}else s===":"?(n!==""&&t.push(n),n="",r++):s==="\\"&&r+1<e.length?(n+=s+e[r+1],r+=2):(n+=s,r++)}return n!==""&&t.push(n),t}function Ml(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n];if(r==="*")t+="[^/]*";else if(r==="?")t+="[^/]";else if(r==="["){let s=n+1,i="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(i+="^",s++),s<e.length&&e[s]==="]"&&(i+="\\]",s++);let o=s;for(;o<e.length;){if(e[o]==="\\"&&o+1<e.length){o+=2;continue}if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let l=e.indexOf(":]",o+2);if(l!==-1){o=l+2;continue}}if(e[o]==="]")break;o++}let a=s;for(;s<e.length&&e[s]!=="]";){if(e[s]==="["&&s+1<e.length&&e[s+1]===":"){let l=e.indexOf(":]",s+2);if(l!==-1){let u=e.slice(s+2,l),c=Ni(u);i+=c,s=l+2;continue}}if(e[s]==="\\"&&s+1<e.length){i+=`\\${e[s+1]}`,s+=2;continue}if(e[s]==="-"){let l=s===a,u=s+1===o;l||u?i+="\\-":i+="-"}else i+=e[s];s++}i+="]",t+=i,n=s}else if(r==="\\"&&n+1<e.length){let s=e[n+1];/[.+^${}()|\\*?[\]]/.test(s)?t+=`\\${s}`:t+=s,n++}else/[.+^${}()|]/.test(r)?t+=`\\${r}`:t+=r}return t+="$",he(t)}function Ri(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Di(e){let t=[],n="",r=0,s=!1,i=0;for(;i<e.length;){let o=e[i];if(o==="'"&&!s){s=!0,n+="\0QUOTE_START\0",i++;continue}if(o==="'"&&s){s=!1,n+="\0QUOTE_END\0",i++;continue}if(s){n+=o,i++;continue}if(o==="\\"){n+=o,i+1<e.length?(n+=e[i+1],i+=2):i++;continue}o==="("?(r++,n+=o):o===")"?(r--,n+=o):o==="|"&&r===0?(t.push(n),n=""):n+=o,i++}return t.push(n),t}var Bl=5,Xt=class{fs;cwd;globignorePatterns=[];hasGlobignore=!1;globstar=!1;nullglob=!1;failglob=!1;dotglob=!1;extglob=!1;globskipdots=!0;ops={count:0};maxOps;consumeOperation;constructor(t,n,r,s){this.fs=t,this.cwd=n,typeof s=="boolean"?(this.globstar=s,this.maxOps=1e5):s?(this.globstar=s.globstar??!1,this.nullglob=s.nullglob??!1,this.failglob=s.failglob??!1,this.dotglob=s.dotglob??!1,this.extglob=s.extglob??!1,this.globskipdots=s.globskipdots??!0,this.maxOps=s.maxGlobOperations??1e5,this.consumeOperation=s.consumeOperation):this.maxOps=1e5;let i=r?.get("GLOBIGNORE");i!==void 0&&i!==""&&(this.hasGlobignore=!0,this.globignorePatterns=Fl(i))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new P(`Glob operation limit exceeded (${this.maxOps})`,"glob_operations");this.consumeOperation?.()}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(t){return!this.hasGlobignore&&!this.globskipdots?t:t.filter(n=>{let r=n.split("/").pop()||n;if((this.hasGlobignore||this.globskipdots)&&(r==="."||r===".."))return!1;if(this.hasGlobignore){for(let s of this.globignorePatterns)if(this.matchGlobignorePattern(n,s))return!1}return!0})}matchGlobignorePattern(t,n){return Ml(n).test(t)}isGlobPattern(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandArgs(t,n){let r=t.map((o,a)=>(n?.[a]??!1)||!this.isGlobPattern(o)?null:this.expand(o)),s=await Promise.all(r.map(o=>o||Promise.resolve(null))),i=[];for(let o=0;o<t.length;o++){let a=s[o];a===null?i.push(t[o]):a.length>0?i.push(...a):i.push(t[o])}return i}async expand(t){if(this.globstar){let r=t.split("/"),s=0;for(let i of r)if(i==="**"&&(s++,s>Bl))throw new P(`Glob pattern has too many ** segments (max ${Bl})`,"glob_operations")}let n;if(t.includes("**")&&this.globstar&&this.isGlobstarValid(t))n=await this.expandRecursive(t);else{let r=t.replace(/\*\*+/g,"*");n=await this.expandSimple(r)}return this.filterGlobignore(n)}isGlobstarValid(t){let n=t.split("/");for(let r of n)if(r.includes("**")&&r!=="**")return!1;return!0}hasGlobChars(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandSimple(t){let n=t.startsWith("/"),r=t.split("/").filter(u=>u!==""),s=-1;for(let u=0;u<r.length;u++)if(this.hasGlobChars(r[u])){s=u;break}if(s===-1)return[t];let i,o;if(s===0)n?(i="/",o="/"):(i=this.cwd,o="");else{let u=r.slice(0,s);n?(i=`/${u.join("/")}`,o=`/${u.join("/")}`):(i=this.fs.resolvePath(this.cwd,u.join("/")),o=u.join("/"))}let a=r.slice(s);return(await this.expandSegments(i,o,a)).sort()}async expandSegments(t,n,r){if(this.checkOpsLimit(),r.length===0)return[n];let[s,...i]=r,o=[];try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let a=await this.fs.readdirWithFileTypes(t),l=[],u=[...a],c=this.dotglob||this.hasGlobignore;if(s.startsWith(".")||this.dotglob){let d=a.some(h=>h.name==="."),p=a.some(h=>h.name==="..");d||u.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),p||u.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let d of u)if(!(d.name.startsWith(".")&&!s.startsWith(".")&&!c)&&this.matchPattern(d.name,s)){let p=t==="/"?`/${d.name}`:`${t}/${d.name}`,h;n===""?h=d.name:n==="/"?h=`/${d.name}`:h=`${n}/${d.name}`,i.length===0?l.push(Promise.resolve([h])):d.isDirectory&&l.push(this.expandSegments(p,h,i))}let f=await Promise.all(l);for(let d of f)o.push(...d)}else{this.checkOpsLimit();let a=await this.fs.readdir(t),l=[],u=[...a],c=this.dotglob||this.hasGlobignore;(s.startsWith(".")||this.dotglob)&&(a.includes(".")||u.push("."),a.includes("..")||u.push(".."));for(let d of u)if(!(d.startsWith(".")&&!s.startsWith(".")&&!c)&&this.matchPattern(d,s)){let p=t==="/"?`/${d}`:`${t}/${d}`,h;n===""?h=d:n==="/"?h=`/${d}`:h=`${n}/${d}`,i.length===0?l.push(Promise.resolve([h])):l.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(p)).isDirectory)return this.expandSegments(p,h,i)}catch(m){if(m instanceof P)throw m}return[]})())}let f=await Promise.all(l);for(let d of f)o.push(...d)}}catch(a){if(a instanceof P)throw a}return o}async expandRecursive(t){let n=[],r=t.indexOf("**"),s=t.slice(0,r).replace(/\/$/,"")||".",o=t.slice(r+2).replace(/^\//,"");return o.includes("**")&&this.isGlobstarValid(o)?(await this.walkDirectoryMultiGlobstar(s,o,n),[...new Set(n)].sort()):(await this.walkDirectory(s,o,n),n.sort())}async walkDirectoryMultiGlobstar(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{this.checkOpsLimit();let i=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(s):null;if(i){let o=[];for(let u of i){let c=t==="."?u.name:`${t}/${u.name}`;u.isDirectory&&o.push(c)}let a=t==="."?n:`${t}/${n}`,l=await this.expandRecursive(a);r.push(...l);for(let u=0;u<o.length;u+=100){let c=o.slice(u,u+100);await Promise.all(c.map(f=>this.walkDirectoryMultiGlobstar(f,n,r)))}}else{this.checkOpsLimit();let o=await this.fs.readdir(s),a=[];for(let c of o){let f=t==="."?c:`${t}/${c}`,d=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory&&a.push(f)}catch(p){if(p instanceof P)throw p}}let l=t==="."?n:`${t}/${n}`,u=await this.expandRecursive(l);r.push(...u);for(let c=0;c<a.length;c+=100){let f=a.slice(c,c+100);await Promise.all(f.map(d=>this.walkDirectoryMultiGlobstar(d,n,r)))}}}catch(i){if(i instanceof P)throw i}}async walkDirectory(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let i=await this.fs.readdirWithFileTypes(s),o=[],a=[];for(let l of i){let u=t==="."?l.name:`${t}/${l.name}`;l.isDirectory?a.push(u):n&&this.matchPattern(l.name,n)&&o.push(u)}r.push(...o);for(let l=0;l<a.length;l+=100){let u=a.slice(l,l+100);await Promise.all(u.map(c=>this.walkDirectory(c,n,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(s),o=[];for(let l=0;l<i.length;l+=100){let u=i.slice(l,l+100),c=await Promise.all(u.map(async f=>{let d=t==="."?f:`${t}/${f}`,p=this.fs.resolvePath(this.cwd,d);try{this.checkOpsLimit();let h=await this.fs.stat(p);return{name:f,path:d,isDirectory:h.isDirectory}}catch(h){if(h instanceof P)throw h;return null}}));o.push(...c.filter(f=>f!==null))}for(let l of o)!l.isDirectory&&n&&this.matchPattern(l.name,n)&&r.push(l.path);let a=o.filter(l=>l.isDirectory);for(let l=0;l<a.length;l+=100){let u=a.slice(l,l+100);await Promise.all(u.map(c=>this.walkDirectory(c.path,n,r)))}}}catch(i){if(i instanceof P)throw i}}matchPattern(t,n){return this.patternToRegex(n).test(t)}patternToRegex(t){let n=this.patternToRegexStr(t);return he(`^${n}$`)}patternToRegexStr(t){let n="",r=!1;for(let s=0;s<t.length;s++){if(t.slice(s,s+13)==="\0QUOTE_START\0"){r=!0,s+=12;continue}if(t.slice(s,s+11)==="\0QUOTE_END\0"){r=!1,s+=10;continue}let i=t[s];if(r){/[.+^${}()|\\*?[\]]/.test(i)?n+=`\\${i}`:n+=i;continue}if(this.extglob&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<t.length&&t[s+1]==="("){let o=Ri(t,s+1);if(o!==-1){let a=t.slice(s+2,o),l=Di(a),u=l.map(f=>this.patternToRegexStr(f)),c=u.length>0?u.join("|"):"(?:)";if(i==="@")n+=`(?:${c})`;else if(i==="*")n+=`(?:${c})*`;else if(i==="+")n+=`(?:${c})+`;else if(i==="?")n+=`(?:${c})?`;else if(i==="!")if(o<t.length-1){let d=l.map(h=>this.computePatternLength(h));if(d.every(h=>h!==null)&&d.every(h=>h===d[0])&&d[0]!==null){let h=d[0];if(h===0)n+="(?:.+)";else{let m=[];h>0&&m.push(`.{0,${h-1}}`),m.push(`.{${h+1},}`),m.push(`(?!(?:${c})).{${h}}`),n+=`(?:${m.join("|")})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;s=o;continue}}if(i==="*")n+=".*";else if(i==="?")n+=".";else if(i==="["){let o=s+1,a="[";o<t.length&&(t[o]==="^"||t[o]==="!")&&(a+="^",o++),o<t.length&&t[o]==="]"&&(a+="\\]",o++);let l=o;for(;l<t.length;){if(t[l]==="\\"&&l+1<t.length){l+=2;continue}if(t[l]==="["&&l+1<t.length&&t[l+1]===":"){let c=t.indexOf(":]",l+2);if(c!==-1){l=c+2;continue}}if(t[l]==="]")break;l++}let u=o;for(;o<t.length&&t[o]!=="]";){if(t[o]==="["&&o+1<t.length&&t[o+1]===":"){let c=t.indexOf(":]",o+2);if(c!==-1){let f=t.slice(o+2,c),d=Ni(f);a+=d,o=c+2;continue}}if(t[o]==="\\"&&o+1<t.length){a+=`\\${t[o+1]}`,o+=2;continue}if(t[o]==="-"){let c=o===u,f=o+1===l;c||f?a+="\\-":a+="-"}else a+=t[o];o++}a+="]",n+=a,s=o}else if(i==="\\"&&s+1<t.length){let o=t[s+1];/[.+^${}()|\\*?[\]]/.test(o)?n+=`\\${o}`:n+=o,s++}else/[.+^${}()|]/.test(i)?n+=`\\${i}`:n+=i}return n}computePatternLength(t){let n=0,r=0,s=!1;for(;r<t.length;){if(t.slice(r,r+13)==="\0QUOTE_START\0"){s=!0,r+=13;continue}if(t.slice(r,r+11)==="\0QUOTE_END\0"){s=!1,r+=11;continue}let i=t[r];if(s){n+=1,r++;continue}if((i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&r+1<t.length&&t[r+1]==="("){let o=Ri(t,r+1);if(o!==-1){if(i==="@"){let a=t.slice(r+2,o),u=Di(a).map(c=>this.computePatternLength(c));if(u.every(c=>c!==null)&&u.every(c=>c===u[0])){n+=u[0],r=o+1;continue}return null}return null}}if(i==="*")return null;if(i==="?"){n+=1,r++;continue}if(i==="["){let o=t.indexOf("]",r+1);if(o!==-1){n+=1,r=o+1;continue}n+=1,r++;continue}if(i==="\\"){n+=1,r+=2;continue}n+=1,r++}return n}};function Ii(e){for(let t=0;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==="$"){let n=e[t+1];if(n==="{"||n&&/[a-zA-Z_]/.test(n))return!0}}return!1}function mp(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n)return!1;for(let r of n)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Wl(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n||n.length===0)return!1;for(let r of n)if(r.type!=="DoubleQuoted"&&r.type!=="SingleQuoted")return!1;return!0}function or(e){let t=!1,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1;for(let l of e){if((l.type==="SingleQuoted"||l.type==="DoubleQuoted")&&(t=!0,l.type==="DoubleQuoted"))for(let u of l.parts)u.type==="ParameterExpansion"&&(u.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&(!u.operation||u.operation.type==="PatternRemoval"||u.operation.type==="PatternReplacement")&&(s=!0),(u.operation?.type==="VarNamePrefix"||u.operation?.type==="ArrayKeys")&&(o=!0),u.operation?.type==="Indirection"&&(a=!0));l.type==="CommandSubstitution"&&(n=!0),l.type==="ParameterExpansion"&&(i=!0,(l.parameter==="@"||l.parameter==="*")&&(r=!0),mp(l)&&(t=!0),(l.operation?.type==="VarNamePrefix"||l.operation?.type==="ArrayKeys")&&(o=!0),l.operation?.type==="Indirection"&&(a=!0)),l.type==="Glob"&&Ii(l.pattern)&&(i=!0)}return{hasQuoted:t,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:i,hasVarNamePrefixExpansion:o,hasIndirection:a}}var yp=`
|
|
95
|
-
`;function
|
|
96
|
-
`)return!1;return!0}function
|
|
97
|
-
`?n.push("\\n"):n.push(r);return t&&n.push("\\-"),n.join("")}function
|
|
98
|
-
`;function
|
|
99
|
-
`,"";let h=Math.max(...f.map(([E])=>typeof E=="number"?E:0))+1+u;return h<0?(e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${
|
|
100
|
-
`,""):oe(e,o,h)||""}let c=oe(e,o,u);if(c!==void 0)return c;if(u===0){let f=e.state.env.get(o);if(f!==void 0)return f}if(n&&e.state.options.nounset)throw new ze(`${o}[${u}]`);return""}if(/^[1-9][0-9]*$/.test(t)){let o=e.state.env.get(t);if(o===void 0&&n&&e.state.options.nounset)throw new ze(t);return o||""}if(le(e,t)){let o=Me(e,t);if(o===void 0)return"";if(o!==t)return await ie(e,o,n,r);let a=e.state.env.get(t);if((a===void 0||a==="")&&n&&e.state.options.nounset)throw new ze(t);return a||""}let i=e.state.env.get(t);if(i!==void 0)return e.state.tempEnvBindings?.some(o=>o.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),i;if(ht(e,t)){let o=oe(e,t,0);if(o!==void 0)return o;if(n&&e.state.options.nounset)throw new ze(t);return""}if(n&&e.state.options.nounset)throw new ze(t);return""}async function Pt(e,t){if(new Set(["?","$","#","_","-","0","PPID","UID","EUID","RANDOM","SECONDS","BASH_VERSION","!","BASHPID","LINENO"]).has(t))return!0;if(t==="@"||t==="*")return Number.parseInt(e.state.env.get("#")||"0",10)>0;if(t==="PWD"||t==="OLDPWD")return e.state.env.has(t);let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let s=r[1],i=r[2];if(le(e,s)){let l=Me(e,s);if(l&&l!==s){if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;s=l}}if(i==="@"||i==="*")return H(e,s).length>0?!0:e.state.env.has(s);if(e.state.associativeArrays?.has(s)){let l=Hl(e,Wr(i));return Gt(e,s,l)}let a;if(/^-?\d+$/.test(i))a=Number.parseInt(i,10);else try{let l=new j,u=re(l,i);a=await X(e,u.expression)}catch{let l=e.state.env.get(i);a=l?Number.parseInt(l,10):0,Number.isNaN(a)&&(a=0)}if(a<0){let l=H(e,s);if(l.length===0)return!1;let c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+a;return c<0?!1:Gt(e,s,c)}return Gt(e,s,a)}if(le(e,t)){let s=Me(e,t);return s===void 0||s===t?e.state.env.has(t):Pt(e,s)}return e.state.env.has(t)?!0:ht(e,t)?Gt(e,t,0):!1}async function Gl(e,t){let n="",r=0;for(;r<t.length;){if(t[r]==="$"){if(t[r+1]==="{"){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="{"?s++:t[i]==="}"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(t[r+1]==="("){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="("?s++:t[i]===")"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),o=await ie(e,i);n+=o,r=s;continue}if(/[0-9]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[0-9]/.test(t[s]);)s++;let i=t.slice(r+1,s),o=await ie(e,i);n+=o,r=s;continue}if(/[*@#?\-!$]/.test(t[r+1]||"")){let s=t[r+1],i=await ie(e,s);n+=i,r+=2;continue}}if(t[r]==='"'){for(n+='"',r++;r<t.length&&t[r]!=='"';)if(t[r]==="$"&&/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),o=await ie(e,i);n+=o,r=s}else t[r]==="\\"?(n+=t[r],r++,r<t.length&&(n+=t[r],r++)):(n+=t[r],r++);r<t.length&&(n+='"',r++);continue}n+=t[r],r++}return n}async function Fi(e,t){let n=t,r=t.startsWith('"')&&t.endsWith('"'),s=t.startsWith("'")&&t.endsWith("'");if((r||s)&&(n=t.slice(1,-1)),s)return n;let i="",o=0;for(;o<n.length;)if(n[o]==="$")if(n[o+1]==="("){let a=1,l=o+2;for(;l<n.length&&a>0;)n[l]==="("&&n[l-1]==="$"||n[l]==="("?a++:n[l]===")"&&a--,l++;let u=n.slice(o+2,l-1);if(e.execFn){let c=await e.execFn(u,{signal:e.state.signal});i+=c.stdout.replace(/\n+$/,""),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr)}o=l}else if(n[o+1]==="{"){let a=1,l=o+2;for(;l<n.length&&a>0;)n[l]==="{"?a++:n[l]==="}"&&a--,l++;let u=n.slice(o+2,l-1),c=await ie(e,u);i+=c,o=l}else if(/[a-zA-Z_]/.test(n[o+1]||"")){let a=o+1;for(;a<n.length&&/[a-zA-Z0-9_]/.test(n[a]);)a++;let l=n.slice(o+1,a),u=await ie(e,l);i+=u,o=a}else i+=n[o],o++;else if(n[o]==="`"){let a=o+1;for(;a<n.length&&n[a]!=="`";)a++;let l=n.slice(o+1,a);if(e.execFn){let u=await e.execFn(l,{signal:e.state.signal});i+=u.stdout.replace(/\n+$/,""),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.stderr)}o=a+1}else i+=n[o],o++;return i}var ar=1e4,Mi={maxResults:ar,maxStringBytes:10*1024*1024};function es(e,t,n,r){if(e.length>=n.maxResults)return!1;let s=M(t);if(s>n.maxStringBytes-r.value)throw new P(`brace expansion string limit exceeded (${n.maxStringBytes} bytes)`,"string_length");return e.push(t),r.value+=s,!0}function bp(e,t,n,r,s,i=Mi){let o=n??1;o===0&&(o=1);let a=Math.abs(o),l=[],u=0;if(r?.match(/^-?0\d/)&&(u=Math.max(u,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(u=Math.max(u,s.replace(/^-/,"").length)),u>i.maxStringBytes)throw new P(`brace expansion padding limit exceeded (${i.maxStringBytes} bytes)`,"string_length");let c={value:0},f=d=>{if(u>0){let p=d<0,h=String(Math.abs(d)).padStart(u,"0");return p?`-${h}`:h}return String(d)};if(e<=t)for(let d=e,p=0;d<=t&&p<ar&&es(l,f(d),i,c);d+=a,p++);else for(let d=e,p=0;d>=t&&p<ar&&es(l,f(d),i,c);d-=a,p++);return l}function Sp(e,t,n,r=Mi){let s=n??1;s===0&&(s=1);let i=e.charCodeAt(0),o=t.charCodeAt(0),a=Math.abs(s),l=e>="A"&&e<="Z",u=e>="a"&&e<="z",c=t>="A"&&t<="Z",f=t>="a"&&t<="z";if(l&&f||u&&c){let h=n!==void 0?`..${n}`:"";throw new Rr(`{${e}..${t}${h}}: invalid sequence`)}let d=[],p={value:0};if(i<=o)for(let h=i,m=0;h<=o&&m<ar&&es(d,String.fromCharCode(h),r,p);h+=a,m++);else for(let h=i,m=0;h>=o&&m<ar&&es(d,String.fromCharCode(h),r,p);h-=a,m++);return d}function Bi(e,t,n,r,s,i=Mi){let o=n!==void 0?`..${n}`:"";return typeof e=="number"&&typeof t=="number"?{expanded:bp(e,t,n,r,s,i),literal:`{${e}..${t}${o}}`}:typeof e=="string"&&typeof t=="string"?{expanded:Sp(e,t,n,i),literal:`{${e}..${t}${o}}`}:{expanded:null,literal:`{${e}..${t}${o}}`}}function Zl(e){if(e.statements.length!==1)return null;let t=e.statements[0];if(t.operators.length!==0||t.pipelines.length!==1)return null;let n=t.pipelines[0];if(n.negated||n.commands.length!==1)return null;let r=n.commands[0];if(r.type!=="SimpleCommand")return null;let s=r;if(s.name!==null||s.args.length!==0||s.assignments.length!==0||s.redirections.length!==1)return null;let i=s.redirections[0];return i.operator!=="<"||i.target.type!=="Word"?null:{target:i.target}}function Ct(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\(/.test(e))}function Wi(e){let t="",n=0;for(;n<e.length;)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);return t}function Je(e){return e.replace(/([*?[\]\\()|])/g,"\\$1")}function Fn(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}function ee(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(e,t,n=!1){let r="",s=0;for(;s<e.length;){let i=e[s];if(n&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<e.length&&e[s+1]==="("){let o=Ap(e,s+1);if(o!==-1){let a=e.slice(s+2,o),u=vp(a).map(f=>Y(f,t,n)),c=u.length>0?u.join("|"):"(?:)";i==="@"?r+=`(?:${c})`:i==="*"?r+=`(?:${c})*`:i==="+"?r+=`(?:${c})+`:i==="?"?r+=`(?:${c})?`:i==="!"&&(r+=`(?!(?:${c})$).*`),s=o+1;continue}}if(i==="\\")if(s+1<e.length){let o=e[s+1];/[\\^$.|+(){}[\]*?]/.test(o)?r+=`\\${o}`:r+=o,s+=2}else r+="\\\\",s++;else if(i==="*")r+=t?".*":".*?",s++;else if(i==="?")r+=".",s++;else if(i==="["){let o=kp(e,s);if(o===-1)r+="\\[",s++;else{let a=e.slice(s+1,o);r+=$p(a),s=o+1}}else/[\^$.|+(){}]/.test(i)?(r+=`\\${i}`,s++):(r+=i,s++)}return r}function Ap(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function vp(e){let t=[],n="",r=0,s=0;for(;s<e.length;){let i=e[s];if(i==="\\"){n+=i,s+1<e.length?(n+=e[s+1],s+=2):s++;continue}i==="("?(r++,n+=i):i===")"?(r--,n+=i):i==="|"&&r===0?(t.push(n),n=""):n+=i,s++}return t.push(n),t}function kp(e,t){let n=t+1;for(n<e.length&&e[n]==="^"&&n++,n<e.length&&e[n]==="]"&&n++;n<e.length;){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==="]")return n;if(e[n]==="'"){let r=e.indexOf("'",n+1);if(r!==-1){n=r+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let r=e.indexOf(":]",n+2);if(r!==-1){n=r+2;continue}}n++}return-1}function $p(e){let t="[",n=0;for((e[0]==="^"||e[0]==="!")&&(t+="^",n++);n<e.length;){if(e[n]==="'"){let s=e.indexOf("'",n+1);if(s!==-1){let i=e.slice(n+1,s);for(let o of i)o==="\\"?t+="\\\\":o==="]"?t+="\\]":o==="^"&&t==="["?t+="\\^":t+=o;n=s+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let s=e.indexOf(":]",n+2);if(s!==-1){let i=e.slice(n+2,s);t+=Pp(i),n=s+2;continue}}let r=e[n];r==="\\"?n+1<e.length?(t+=`\\${e[n+1]}`,n+=2):(t+="\\\\",n++):r==="-"&&n>0&&n<e.length-1?(t+="-",n++):r==="^"&&n===0?(t+="^",n++):(r==="]"&&n===0?t+="\\]":t+=r,n++)}return t+="]",t}var xp=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]);function Pp(e){return xp.get(e)??""}function mt(e,t,n,r,s){if(r==="prefix")return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),he(`^${n}`,"s").replace(t,"");let i=he(`${n}$`,"s");if(s)return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),i.replace(t,"");e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal");let o=he(`^(?:.*)(${n})$`,"s").exec(t);if(!o)return t;let a=o[1]??"";return t.slice(0,t.length-a.length)}function Mn(e,t){let n=new Set;for(let r of e.state.env.keys())r.startsWith(t)&&n.add(r);for(let r of e.state.arrays?.keys()??[])r.startsWith(t)&&n.add(r);return[...n].sort()}function ts(e,t,n,r,s){let i=new Pn(e.limits.maxStringLength,"pattern replacement",()=>new P(`pattern replacement: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length"));n.lastIndex=0;let o=0,a=n.exec(t);for(;a!==null&&(e.executionScope.consumeLimited("pattern_operations",1,e.limits.maxGlobOperations,"pattern replacement"),!(s&&a[0].length===0&&a.index===t.length||(i.append(t.slice(o,a.index)),i.append(r),o=a.index+a[0].length,!s)));)a[0].length===0&&(o++,n.lastIndex<=a.index&&(n.lastIndex=a.index+1)),a=n.exec(t);return i.append(t.slice(o)),n.lastIndex=0,i.build()}function Ql(e){let t=[],n=0;return{append(r){let s=M(r);if(s>e-n)throw new P(`prompt expansion exceeds string length limit (${e} bytes)`,"string_length");r&&t.push(r),n+=s},build:()=>t.join("")}}function Cp(e,t,n){let r=(o,a=2)=>String(o).padStart(a,"0");if(e===""){let o=r(t.getHours()),a=r(t.getMinutes()),l=r(t.getSeconds());return`${o}:${a}:${l}`}let s=Ql(n),i=0;for(;i<e.length;)if(e[i]==="%"){if(i+1>=e.length){s.append("%"),i++;continue}let o=e[i+1];switch(o){case"H":s.append(r(t.getHours()));break;case"M":s.append(r(t.getMinutes()));break;case"S":s.append(r(t.getSeconds()));break;case"d":s.append(r(t.getDate()));break;case"m":s.append(r(t.getMonth()+1));break;case"Y":s.append(String(t.getFullYear()));break;case"y":s.append(r(t.getFullYear()%100));break;case"I":{let a=t.getHours()%12;a===0&&(a=12),s.append(r(a));break}case"p":s.append(t.getHours()<12?"AM":"PM");break;case"P":s.append(t.getHours()<12?"am":"pm");break;case"%":s.append("%");break;case"a":{let a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];s.append(a[t.getDay()]);break}case"b":{let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];s.append(a[t.getMonth()]);break}default:s.append(`%${o}`)}i+=2}else s.append(e[i]),i++;return s.build()}function lr(e,t){let n=Ql(e.limits.maxStringLength),r=0,s=e.state.env.get("USER")||e.state.env.get("LOGNAME")||"user",i=e.state.env.get("HOSTNAME")||"localhost",o=i.split(".")[0],a=e.state.env.get("PWD")||"/",l=e.state.env.get("HOME")||"/",u=a.startsWith(l)?`~${a.slice(l.length)}`:a,c=a.split("/").pop()||a,f=new Date,d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=e.state.env.get("__COMMAND_NUMBER")||"1";for(;r<t.length;){let m=t[r];if(m==="\\"){if(r+1>=t.length){n.append("\\"),r++;continue}let E=t[r+1];if(E>="0"&&E<="7"){let S="",g=r+1;for(;g<t.length&&g<r+4&&t[g]>="0"&&t[g]<="7";)S+=t[g],g++;let y=Number.parseInt(S,8)%256;n.append(String.fromCharCode(y)),r=g;continue}switch(E){case"\\":n.append("\\"),r+=2;break;case"a":n.append("\x07"),r+=2;break;case"e":n.append("\x1B"),r+=2;break;case"n":n.append(`
|
|
101
|
-
`),r+=2;break;case"r":n.append("\r"),r+=2;break;case"$":n.append("$"),r+=2;break;case"[":case"]":r+=2;break;case"u":n.append(s),r+=2;break;case"h":n.append(
|
|
102
|
-
`:n+="\\n";break;case"\r":n+="\\r";break;case" ":n+="\\t";break;default:{let s=r.charCodeAt(0);s<32||s===127?n+=`\\${s.toString(8).padStart(3,"0")}`:n+=r}}return`${n}'`}return`'${e}'`}function
|
|
103
|
-
`;throw new
|
|
104
|
-
`)}return r.effectiveValue}async function
|
|
105
|
-
`);let c=
|
|
106
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return l}});case"K":case"k":return r?"":Yt(n);case"u":return n.charAt(0).toUpperCase()+n.slice(1);case"U":return n.toUpperCase();case"L":return n.toLowerCase();default:return n}}async function ou(e,t,n,r,s,i,o=!1){if(e.coverage?.hit("bash:expansion:indirection"),le(e,t))return vn(e,t)||"";let a=/^[a-zA-Z_][a-zA-Z0-9_]*\[([@*])\]$/.test(t);if(r){if(s.innerOp?.type==="UseAlternative")return"";throw new Ke(`\${!${t}}`)}let l=n;if(a&&(l===""||l.includes(" ")))throw new Ke(`\${!${t}}`);let u=l.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(u&&u[1].includes("~"))throw new Ke(`\${!${t}}`);if(s.innerOp){let c={type:"ParameterExpansion",parameter:l,operation:s.innerOp};return i(e,c,o)}return await ie(e,l)}function au(e,t){e.coverage?.hit("bash:expansion:array_keys");let r=H(e,t.array).map(([s])=>String(s));return t.star?r.join(Z(e.state.env)):r.join(" ")}function lu(e,t){e.coverage?.hit("bash:expansion:var_name_prefix");let n=Mn(e,t.prefix);return t.star?n.join(Z(e.state.env)):n.join(" ")}function uu(e,t,n,r){let s=Number.parseInt(e.state.env.get("#")||"0",10),i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(t==="*")return{isEmpty:s===0,effectiveValue:n};if(t==="@")return{isEmpty:s===0||s===1&&e.state.env.get("1")==="",effectiveValue:n};if(i){let[,o,a]=i,l=H(e,o);if(l.length===0)return{isEmpty:!0,effectiveValue:""};if(a==="*"){let u=Z(e.state.env),c=l.map(([,f])=>f).join(u);return{isEmpty:r?c==="":!1,effectiveValue:c}}return{isEmpty:l.length===1&&l.every(([,u])=>u===""),effectiveValue:l.map(([,u])=>u).join(" ")}}return{isEmpty:n==="",effectiveValue:n}}function cu(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="\\"&&t+1<e.length){t+=2;continue}if(n==="'"){let r=e.indexOf("'",t+1);if(r!==-1){t=r+1;continue}}if(n==="$"&&t+1<e.length&&e[t+1]==="("||n==="`")return!0;t++}return!1}function fu(e,t){let n=1,r=t,s=!1,i=!1;for(;r<e.length&&n>0;){let o=e[r];if(o==="\\"&&!s&&r+1<e.length){r+=2;continue}if(o==="'"&&!i){s=!s,r++;continue}if(o==='"'&&!s){i=!i,r++;continue}if(!s&&!i){if(o==="(")n++;else if(o===")"&&(n--,n===0))return r}r++}return-1}async function rs(e,t){let n=new j,r;try{r=n.parse(t)}catch{return""}let s=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let i=new Map(e.state.env),o=it(e.state.arrays),a=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let u=await e.executeScript(r),c=u.exitCode;return e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.suppressVerbose=l,e.state.lastExitCode=c,e.state.env.set("?",String(c)),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.stderr),e.state.bashPid=s,u.stdout.replace(/\n+$/,"")}catch(u){return e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.bashPid=s,e.state.suppressVerbose=l,Or(u),u instanceof U?(e.state.lastExitCode=u.exitCode,e.state.env.set("?",String(u.exitCode)),u.stdout?.replace(/\n+$/,"")??""):""}}function Vi(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let o=t.slice(r+1,i);n+=Je(o),r=i+1;continue}}if(s==='"'){let i=-1,o=r+1;for(;o<t.length;){if(t[o]==="\\"){o+=2;continue}if(t[o]==='"'){i=o;break}o++}if(i!==-1){let a=t.slice(r+1,i),l=Np(e,a);n+=Je(l),r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}function Np(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}n+=s,r++}return n}async function du(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let o=t.slice(r+1,i);n+=Je(o),r=i+1;continue}}if(s==='"'){let i=-1,o=r+1;for(;o<t.length;){if(t[o]==="\\"){o+=2;continue}if(t[o]==='"'){i=o;break}o++}if(i!==-1){let a=t.slice(r+1,i),l=await Rp(e,a);n+=Je(l),r=i+1;continue}}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=fu(t,r+2);if(i!==-1){let o=t.slice(r+2,i),a=await rs(e,o);n+=a,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let o=t.slice(r+1,i),a=await rs(e,o);n+=a,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}async function Rp(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=fu(t,r+2);if(i!==-1){let o=t.slice(r+2,i),a=await rs(e,o);n+=a,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let o=t.slice(r+1,i),a=await rs(e,o);n+=a,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}n+=s,r++}return n}function zi(e,t){if(!t.startsWith("~"))return t;e.coverage?.hit("bash:expansion:tilde");let n=e.state.env.get("HOME")!==void 0?e.state.env.get("HOME"):"/home/user";if(t==="~"||t.startsWith("~/"))return n+t.slice(1);let r=1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;let s=t.slice(1,r),i=t.slice(r);return i!==""&&!i.startsWith("/")?t:s==="root"?`/root${i}`:t}function en(e,t){return t.split(":").map(n=>zi(e,n)).join(":")}function De(e,t,n,r){if(e.length>n-t.length)throw new P(`${r} element limit exceeded (${n})`,"array_elements");for(let s of t)e.push(s)}async function Dp(e,t,n,r){let s="";for(let i of t.parts)if(i.type==="Glob")s+=Y(i.pattern,!0,e.state.shoptOptions.extglob);else if(i.type==="Literal")s+=Y(i.value,!0,e.state.shoptOptions.extglob);else if(i.type==="SingleQuoted"||i.type==="Escaped")s+=ee(i.value);else if(i.type==="DoubleQuoted"){let o=await n(e,i.parts);s+=ee(o)}else if(i.type==="ParameterExpansion"){let o=await r(e,i);s+=Y(o,!0,e.state.shoptOptions.extglob)}else{let o=await r(e,i);s+=ee(o)}return s}async function pu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternReplacement")return null;let i=s.parts[0],o=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!o)return null;let a=o[1],l=o[2]==="*",u=i.operation,c=H(e,a),f=c.map(([,E])=>E);if(c.length===0){let E=e.state.env.get(a);E!==void 0&&f.push(E)}if(f.length===0)return{values:[],quoted:!0};let d="";u.pattern&&(d=await Dp(e,u.pattern,n,r));let p=u.replacement?await n(e,u.replacement.parts):"",h=d;u.anchor==="start"?h=`^${d}`:u.anchor==="end"&&(h=`${d}$`);let m=[];try{let E=he(h,u.all?"g":"");for(let S of f)m.push(E.replace(S,p))}catch{m.push(...f)}if(l){let E=Z(e.state.env);return{values:[m.join(E)],quoted:!0}}return{values:m,quoted:!0}}async function hu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternRemoval")return null;let i=s.parts[0],o=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!o)return null;let a=o[1],l=o[2]==="*",u=i.operation,c=H(e,a),f=c.map(([,m])=>m);if(c.length===0){let m=e.state.env.get(a);m!==void 0&&f.push(m)}if(f.length===0)return{values:[],quoted:!0};let d="",p=e.state.shoptOptions.extglob;if(u.pattern)for(let m of u.pattern.parts)if(m.type==="Glob")d+=Y(m.pattern,u.greedy,p);else if(m.type==="Literal")d+=Y(m.value,u.greedy,p);else if(m.type==="SingleQuoted"||m.type==="Escaped")d+=ee(m.value);else if(m.type==="DoubleQuoted"){let E=await n(e,m.parts);d+=ee(E)}else if(m.type==="ParameterExpansion"){let E=await r(e,m);d+=Y(E,u.greedy,p)}else{let E=await r(e,m);d+=ee(E)}let h=[];for(let m of f)h.push(mt(e,m,d,u.side,u.greedy));if(l){let m=Z(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}async function mu(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="DefaultValue"&&n.parts[0].operation?.type!=="UseAlternative"&&n.parts[0].operation?.type!=="AssignDefault")return null;let r=n.parts[0],s=r.operation,i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/),o,a=!1;if(i){let l=i[1];a=i[2]==="*";let u=H(e,l),c=u.length>0||e.state.env.has(l),f=u.length===0||u.length===1&&u.every(([,p])=>p===""),d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=c&&!(d&&f):o=!c||d&&f,!o){if(u.length>0){let h=u.map(([,m])=>m);if(a){let m=Z(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}let p=e.state.env.get(l);return p!==void 0?{values:[p],quoted:!0}:{values:[],quoted:!0}}}else{let l=r.parameter,u=await Pt(e,l),c=await ie(e,l),f=c==="",d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=u&&!(d&&f):o=!u||d&&f,!o)return{values:[c],quoted:!0}}if(o&&s.word){let l=s.word.parts,u=null,c=!1;for(let f of l)if(f.type==="ParameterExpansion"&&!f.operation){let d=f.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(d){u=d[1],c=d[2]==="*";break}}if(u){let f=H(e,u);if(f.length>0){let p=f.map(([,h])=>h);if(c||a){let h=Z(e.state.env);return{values:[p.join(h)],quoted:!0}}return{values:p,quoted:!0}}let d=e.state.env.get(u);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}return null}async function yu(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0],o=-1,a="",l=!1,u=null;for(let m=0;m<i.parts.length;m++){let E=i.parts[m];if(E.type==="ParameterExpansion"&&(E.operation?.type==="PatternRemoval"||E.operation?.type==="PatternReplacement")){let S=E.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(S){o=m,a=S[1],l=S[2]==="*",u=E.operation;break}}}if(o===-1||o===0&&o===i.parts.length-1)return null;let c="";for(let m=0;m<o;m++)c+=await r(e,i.parts[m]);let f="";for(let m=o+1;m<i.parts.length;m++)f+=await r(e,i.parts[m]);let d=H(e,a),p=d.map(([,m])=>m);if(d.length===0){let m=e.state.env.get(a);if(m!==void 0)p=[m];else{if(l)return{values:[c+f],quoted:!0};let E=c+f;return{values:E?[E]:[],quoted:!0}}}if(u?.type==="PatternRemoval"){let m=u,E="",S=e.state.shoptOptions.extglob;if(m.pattern)for(let g of m.pattern.parts)if(g.type==="Glob")E+=Y(g.pattern,m.greedy,S);else if(g.type==="Literal")E+=Y(g.value,m.greedy,S);else if(g.type==="SingleQuoted"||g.type==="Escaped")E+=ee(g.value);else if(g.type==="DoubleQuoted"){let y=await s(e,g.parts);E+=ee(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);E+=Y(y,m.greedy,S)}else{let y=await r(e,g);E+=ee(y)}p=p.map(g=>mt(e,g,E,m.side,m.greedy))}else if(u?.type==="PatternReplacement"){let m=u,E="";if(m.pattern)for(let y of m.pattern.parts)if(y.type==="Glob")E+=Y(y.pattern,!0,e.state.shoptOptions.extglob);else if(y.type==="Literal")E+=Y(y.value,!0,e.state.shoptOptions.extglob);else if(y.type==="SingleQuoted"||y.type==="Escaped")E+=ee(y.value);else if(y.type==="DoubleQuoted"){let b=await s(e,y.parts);E+=ee(b)}else if(y.type==="ParameterExpansion"){let b=await r(e,y);E+=Y(b,!0,e.state.shoptOptions.extglob)}else{let b=await r(e,y);E+=ee(b)}let S=m.replacement?await s(e,m.replacement.parts):"",g=E;m.anchor==="start"?g=`^${E}`:m.anchor==="end"&&(g=`${E}$`);try{let y=he(g,m.all?"g":"");p=p.map(b=>y.replace(b,S))}catch{}}if(l){let m=Z(e.state.env);return{values:[c+p.join(m)+f],quoted:!0}}return p.length===1?{values:[c+p[0]+f],quoted:!0}:{values:[c+p[0],...p.slice(1,-1),p[p.length-1]+f],quoted:!0}}async function gu(e,t,n,r){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o="",a=!1;for(let p=0;p<s.parts.length;p++){let h=s.parts[p];if(h.type==="ParameterExpansion"&&!h.operation){let m=h.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(m){i=p,o=m[1],a=m[2]==="*";break}}}if(i===-1)return null;let l="";for(let p=0;p<i;p++)l+=await r(e,s.parts[p]);let u="";for(let p=i+1;p<s.parts.length;p++)u+=await r(e,s.parts[p]);let c=H(e,o),f=c.map(([,p])=>p);if(c.length===0){let p=e.state.env.get(o);if(p!==void 0)return{values:[l+p+u],quoted:!0};if(a)return{values:[l+u],quoted:!0};let h=l+u;return{values:h?[h]:[],quoted:!0}}if(a){let p=Z(e.state.env);return{values:[l+f.join(p)+u],quoted:!0}}return f.length===1?{values:[l+f[0]+u],quoted:!0}:{values:[l+f[0],...f.slice(1,-1),f[f.length-1]+u],quoted:!0}}async function wu(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!=="ParameterExpansion"||r.parts[0].operation?.type!=="Substring")return null;let s=r.parts[0],i=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!i)return null;let o=i[1],a=i[2]==="*",l=s.operation;if(e.state.associativeArrays?.has(o))throw new U(1,"",`bash: \${${o}[@]: 0: 3}: bad substitution
|
|
107
|
-
`);let u=l.offset?await n(e,l.offset.expression):0,c=l.length?await n(e,l.length.expression):void 0,f=H(e,o);if(f.length>e.limits.maxArrayElements)throw new P(`array transform element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let d=0;if(u<0){if(f.length>0){let h=f[f.length-1][0],E=(typeof h=="number"?h:0)+1+u;if(E<0)return{values:[],quoted:!0};d=f.findIndex(([S])=>typeof S=="number"&&S>=E),d<0&&(d=f.length)}}else d=f.findIndex(([h])=>typeof h=="number"&&h>=u),d<0&&(d=f.length);let p;if(c!==void 0){if(c<0)throw new ae(`${o}[@]: substring expression < 0`);p=f.slice(d,d+c).map(([,h])=>h)}else p=f.slice(d).map(([,h])=>h);if(p.length===0)return{values:[],quoted:!0};if(a){let h=Z(e.state.env);return{values:[p.join(h)],quoted:!0}}return{values:p,quoted:!0}}function Eu(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="Transform")return null;let r=n.parts[0],s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!s)return null;let i=s[1],o=s[2]==="*",a=r.operation,l=H(e,i);if(l.length===0){let d=e.state.env.get(i);if(d!==void 0){let p;switch(a.operator){case"a":p="";break;case"P":p=lr(e,d);break;case"Q":p=Yt(d);break;default:p=d}if(M(p)>e.limits.maxStringLength)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[p],quoted:!0}}return o?{values:[""],quoted:!0}:{values:[],quoted:!0}}let u=Jt(e,i),c=[],f=0;for(let[,d]of l){let p;switch(a.operator){case"a":p=u;break;case"P":p=lr(e,d);break;case"Q":p=Yt(d);break;case"u":p=d.charAt(0).toUpperCase()+d.slice(1);break;case"U":p=d.toUpperCase();break;case"L":p=d.toLowerCase();break;default:p=d}let h=M(p);if(h>e.limits.maxStringLength-f)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");c.push(p),f+=h}if(o){let d=Z(e.state.env);if(Math.max(0,c.length-1)*M(d)>e.limits.maxStringLength-f)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[c.join(d)],quoted:!0}}return{values:c,quoted:!0}}function bu(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion")return null;let r=n.parts[0];if(r.operation)return null;let s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!s)return null;let i=s[1];if(le(e,i)){let l=vn(e,i);if(l?.endsWith("[@]")||l?.endsWith("[*]"))return{values:[],quoted:!0}}let o=H(e,i);if(o.length>0)return{values:o.map(([,l])=>l),quoted:!0};let a=e.state.env.get(i);return a!==void 0?{values:[a],quoted:!0}:{values:[],quoted:!0}}function Su(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation)return null;let s=n.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)||!le(e,s))return null;let i=vn(e,s);if(!i)return null;let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!o)return null;let a=o[1],l=H(e,a);if(l.length>0)return{values:l.map(([,c])=>c),quoted:!0};let u=e.state.env.get(a);return u!==void 0?{values:[u],quoted:!0}:{values:[],quoted:!0}}async function Au(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let o=i.parts[0],a=o.operation,l=await ie(e,o.parameter),u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!u){if(!a.innerOp&&(l==="@"||l==="*")){let h=Number.parseInt(e.state.env.get("#")||"0",10),m=[];for(let E=1;E<=h;E++)m.push(e.state.env.get(String(E))||"");return l==="*"?{values:[m.join(Z(e.state.env))],quoted:!0}:{values:m,quoted:!0}}return null}let c=u[1],f=u[2]==="*",d=H(e,c);if(a.innerOp){if(a.innerOp.type==="Substring")return Ip(e,d,c,f,a.innerOp);if(a.innerOp.type==="DefaultValue"||a.innerOp.type==="UseAlternative"||a.innerOp.type==="AssignDefault"||a.innerOp.type==="ErrorIfUnset")return Op(e,d,c,f,a.innerOp,s);if(a.innerOp.type==="Transform"&&a.innerOp.operator==="a"){let m=Jt(e,c),E=d.map(()=>m);return f?{values:[E.join(Z(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let h=[];for(let[,m]of d){let E={type:"ParameterExpansion",parameter:"_indirect_elem_",operation:a.innerOp},S=e.state.env.get("_indirect_elem_");e.state.env.set("_indirect_elem_",m);try{let g=await r(e,E,!0);h.push(g)}finally{S!==void 0?e.state.env.set("_indirect_elem_",S):e.state.env.delete("_indirect_elem_")}}return f?{values:[h.join(Z(e.state.env))],quoted:!0}:{values:h,quoted:!0}}if(d.length>0){let h=d.map(([,m])=>m);return f?{values:[h.join(Z(e.state.env))],quoted:!0}:{values:h,quoted:!0}}let p=e.state.env.get(c);return p!==void 0?{values:[p],quoted:!0}:{values:[],quoted:!0}}async function Ip(e,t,n,r,s){let i=s.offset?await X(e,s.offset.expression):0,o=s.length?await X(e,s.length.expression):void 0,a=0;if(i<0){if(t.length>0){let c=t[t.length-1][0],d=(typeof c=="number"?c:0)+1+i;if(d<0)return{values:[],quoted:!0};if(a=t.findIndex(([p])=>typeof p=="number"&&p>=d),a<0)return{values:[],quoted:!0}}}else if(a=t.findIndex(([c])=>typeof c=="number"&&c>=i),a<0)return{values:[],quoted:!0};let l;if(o!==void 0){if(o<0)throw new ae(`${n}[@]: substring expression < 0`);l=t.slice(a,a+o)}else l=t.slice(a);let u=l.map(([,c])=>c);return r?{values:[u.join(Z(e.state.env))],quoted:!0}:{values:u,quoted:!0}}async function Op(e,t,n,r,s,i){let o=s.checkEmpty??!1,a=t.map(([,c])=>c),l=t.length===0,u=t.length===0;if(s.type==="UseAlternative")return!u&&!(o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(s.type==="DefaultValue")return(u||o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:r?{values:[a.join(Z(e.state.env))],quoted:!0}:{values:a,quoted:!0};if(s.type==="AssignDefault"){if((u||o&&l)&&s.word){let f=await i(e,s.word.parts,!0);return q(e,n,0,f),{values:[f],quoted:!0}}return r?{values:[a.join(Z(e.state.env))],quoted:!0}:{values:a,quoted:!0}}return r?{values:[a.join(Z(e.state.env))],quoted:!0}:{values:a,quoted:!0}}async function vu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="UseAlternative"&&t[0].operation?.type!=="DefaultValue")return null;let n=t[0],r=n.operation,s=r?.word;if(!s||s.parts.length!==1||s.parts[0].type!=="DoubleQuoted")return null;let i=s.parts[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let o=i.parts[0],l=(await ie(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!l)return null;let u=await Pt(e,n.parameter),c=await ie(e,n.parameter)==="",f=r.checkEmpty??!1,d;if(r.type==="UseAlternative"?d=u&&!(f&&c):d=!u||f&&c,d){let p=l[1],h=l[2]==="*",m=H(e,p);if(m.length>0){let S=m.map(([,g])=>g);return h?{values:[S.join(Z(e.state.env))],quoted:!0}:{values:S,quoted:!0}}let E=e.state.env.get(p);return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function ku(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="Indirection")return null;let n=t[0],s=n.operation.innerOp;if(!s||s.type!=="UseAlternative"&&s.type!=="DefaultValue")return null;let i=s.word;if(!i||i.parts.length!==1||i.parts[0].type!=="DoubleQuoted")return null;let o=i.parts[0];if(o.parts.length!==1||o.parts[0].type!=="ParameterExpansion"||o.parts[0].operation?.type!=="Indirection")return null;let a=o.parts[0],u=(await ie(e,a.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!u)return null;let c=await ie(e,n.parameter),f=await Pt(e,n.parameter),d=c==="",p=s.checkEmpty??!1,h;if(s.type==="UseAlternative"?h=f&&!(p&&d):h=!f||p&&d,h){let m=u[1],E=u[2]==="*",S=H(e,m);if(S.length>0){let y=S.map(([,b])=>b);return E?{values:[y.join(Z(e.state.env))],quoted:!0}:{values:y,quoted:!0}}let g=e.state.env.get(m);return g!==void 0?{values:[g],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}function $u(e){let t=Number.parseInt(e.state.env.get("#")||"0",10);if(t>e.limits.maxArrayElements)throw new P(`positional parameter element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let n=[],r=0;for(let s=1;s<=t;s++){let i=e.state.env.get(String(s))||"",o=M(i);if(o>e.limits.maxStringLength-r)throw new P(`positional parameter string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n.push(i),r+=o}return n}function ss(e,t,n){if(M(t)>n-M(e))throw new P(`positional expansion string limit exceeded (${n} bytes)`,"string_length");return e+t}function Ui(e,t,n,r){if(e.length>=r.limits.maxArrayElements)throw new P(`positional expansion element limit exceeded (${r.limits.maxArrayElements})`,"array_elements");let s=M(t);if(s>r.limits.maxStringLength-n.value)throw new P(`positional expansion string limit exceeded (${r.limits.maxStringLength} bytes)`,"string_length");e.push(t),n.value+=s}async function xu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let g=0;g<s.parts.length;g++){let y=s.parts[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="Substring"){i=g,o=y.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,u=l.offset?await n(e,l.offset.expression):0,c=l.length?await n(e,l.length.expression):void 0,f=Number.parseInt(e.state.env.get("#")||"0",10),d=[];for(let g=1;g<=f;g++)d.push(e.state.env.get(String(g))||"");let p=e.state.env.get("0")||"bash",h;if(u<=0){let g=[p,...d],y=g.length+u;if(y<0)h=[];else{let b=u<0?y:0;if(c!==void 0){let A=c<0?g.length+c:b+c;h=g.slice(b,Math.max(b,A))}else h=g.slice(b)}}else{let g=u-1;if(g>=d.length)h=[];else if(c!==void 0){let y=c<0?d.length+c:g+c;h=d.slice(g,Math.max(g,y))}else h=d.slice(g)}let m="";for(let g=0;g<i;g++)m+=await r(e,s.parts[g]);let E="";for(let g=i+1;g<s.parts.length;g++)E+=await r(e,s.parts[g]);if(h.length===0){let g=m+E;return{values:g?[g]:[],quoted:!0}}if(o){let g=Z(e.state.env);return{values:[m+h.join(g)+E],quoted:!0}}return h.length===1?{values:[m+h[0]+E],quoted:!0}:{values:[m+h[0],...h.slice(1,-1),h[h.length-1]+E],quoted:!0}}async function Pu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let g=0;g<s.parts.length;g++){let y=s.parts[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="PatternReplacement"){i=g,o=y.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,u=$u(e),c="";for(let g=0;g<i;g++)c=ss(c,await n(e,s.parts[g]),e.limits.maxStringLength);let f="";for(let g=i+1;g<s.parts.length;g++)f=ss(f,await n(e,s.parts[g]),e.limits.maxStringLength);if(u.length===0){let g=c+f;return{values:g?[g]:[],quoted:!0}}let d="";if(l.pattern)for(let g of l.pattern.parts)if(g.type==="Glob")d+=Y(g.pattern,!0,e.state.shoptOptions.extglob);else if(g.type==="Literal")d+=Y(g.value,!0,e.state.shoptOptions.extglob);else if(g.type==="SingleQuoted"||g.type==="Escaped")d+=ee(g.value);else if(g.type==="DoubleQuoted"){let y=await r(e,g.parts);d+=ee(y)}else if(g.type==="ParameterExpansion"){let y=await n(e,g);d+=Y(y,!0,e.state.shoptOptions.extglob)}else{let y=await n(e,g);d+=ee(y)}let p=l.replacement?await r(e,l.replacement.parts):"",h=d;l.anchor==="start"?h=`^${d}`:l.anchor==="end"&&(h=`${d}$`);let m=[],E={value:0};try{let g=he(h,l.all?"g":"");for(let y of u){let b=0;g.lastIndex=0;for(let $=g.exec(y);$&&(b++,!!l.all);$=g.exec(y))$[0].length===0&&g.lastIndex++;let A=M(y),k=M(p),v=0,x=/\$(?:\$|&|\d+|<[^>]+>|`|')/g;for(;x.exec(p)!==null;)v++;if(A+b*k+b*v*A>e.limits.maxStringLength-E.value)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");Ui(m,g.replace(y,p),E,e)}}catch(g){if(g instanceof P)throw g;for(let y of u)Ui(m,y,E,e)}if(o){let g=Z(e.state.env);if(E.value+Math.max(0,m.length-1)*M(g)+M(c)+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[c+m.join(g)+f],quoted:!0}}if(M(c)+E.value+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return m.length===1?{values:[c+m[0]+f],quoted:!0}:{values:[c+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function Cu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let S=0;S<s.parts.length;S++){let g=s.parts[S];if(g.type==="ParameterExpansion"&&(g.parameter==="@"||g.parameter==="*")&&g.operation?.type==="PatternRemoval"){i=S,o=g.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,u=$u(e),c="";for(let S=0;S<i;S++)c=ss(c,await n(e,s.parts[S]),e.limits.maxStringLength);let f="";for(let S=i+1;S<s.parts.length;S++)f=ss(f,await n(e,s.parts[S]),e.limits.maxStringLength);if(u.length===0){let S=c+f;return{values:S?[S]:[],quoted:!0}}let d="",p=e.state.shoptOptions.extglob;if(l.pattern)for(let S of l.pattern.parts)if(S.type==="Glob")d+=Y(S.pattern,l.greedy,p);else if(S.type==="Literal")d+=Y(S.value,l.greedy,p);else if(S.type==="SingleQuoted"||S.type==="Escaped")d+=ee(S.value);else if(S.type==="DoubleQuoted"){let g=await r(e,S.parts);d+=ee(g)}else if(S.type==="ParameterExpansion"){let g=await n(e,S);d+=Y(g,l.greedy,p)}else{let g=await n(e,S);d+=ee(g)}let h=[],m={value:0};for(let S of u)Ui(h,mt(e,S,d,l.side,l.greedy),m,e);if(o){let S=Z(e.state.env);if(m.value+Math.max(0,h.length-1)*M(S)+M(c)+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[c+h.join(S)+f],quoted:!0}}if(M(c)+m.value+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return h.length===1?{values:[c+h[0]+f],quoted:!0}:{values:[c+h[0],...h.slice(1,-1),h[h.length-1]+f],quoted:!0}}async function Nu(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0],s=-1,i=!1;for(let d=0;d<r.parts.length;d++){let p=r.parts[d];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")){s=d,i=p.parameter==="*";break}}if(s===-1)return null;let o=r.parts[s];if(o.type==="ParameterExpansion"&&o.operation)return null;let a=Number.parseInt(e.state.env.get("#")||"0",10),l="";for(let d=0;d<s;d++)l+=await n(e,r.parts[d]);let u="";for(let d=s+1;d<r.parts.length;d++)u+=await n(e,r.parts[d]);if(a===0){if(i)return{values:[l+u],quoted:!0};let d=l+u;return{values:d?[d]:[],quoted:!0}}let c=[];for(let d=1;d<=a;d++)c.push(e.state.env.get(String(d))||"");if(i){let d=Z(e.state.env);return{values:[l+c.join(d)+u],quoted:!0}}return c.length===1?{values:[l+c[0]+u],quoted:!0}:{values:[l+c[0],...c.slice(1,-1),c[c.length-1]+u],quoted:!0}}function Nt(e,t,n,r){if(t.length>=e.limits.maxArrayElements)throw new P(`unquoted expansion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let s=M(n);if(s>e.limits.maxStringLength-r.value)throw new P(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");t.push(n),r.value+=s}function qi(e,t,n,r){let s=M(n),i=Math.max(0,t.length-1);if(s>0&&i>Math.floor((e.limits.maxStringLength-r)/s))throw new P(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return t.join(n)}function _p(e){return new Xt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")})}async function is(e,t){if(e.state.options.noglob)return t;let n=_p(e),r=[];for(let s of t)if(Ct(s,e.state.shoptOptions.extglob)){let i=await n.expand(s);if(i.length>0)De(r,i,e.limits.maxArrayElements,"unquoted glob expansion");else{if(n.hasFailglob())throw new Wt(s);n.hasNullglob()||r.push(s)}}else r.push(s);return r}async function Ru(e,t,n,r){let s=-1,i="",o=!1;for(let b=0;b<t.length;b++){let A=t[b];if(A.type==="ParameterExpansion"&&A.operation?.type==="PatternReplacement"){let k=A.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(k){s=b,i=k[1],o=k[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,u=H(e,i),c=u.map(([,b])=>b);if(u.length===0){let b=e.state.env.get(i);b!==void 0&&(c=[b])}if(c.length===0)return{values:[],quoted:!1};let f="";if(l.pattern)for(let b of l.pattern.parts)if(b.type==="Glob")f+=Y(b.pattern,!0,e.state.shoptOptions.extglob);else if(b.type==="Literal")f+=Y(b.value,!0,e.state.shoptOptions.extglob);else if(b.type==="SingleQuoted"||b.type==="Escaped")f+=ee(b.value);else if(b.type==="DoubleQuoted"){let A=await n(e,b.parts);f+=ee(A)}else if(b.type==="ParameterExpansion"){let A=await r(e,b);f+=Y(A,!0,e.state.shoptOptions.extglob)}else{let A=await r(e,b);f+=ee(A)}let d=l.replacement?await n(e,l.replacement.parts):"",p=f;l.anchor==="start"?p=`^${f}`:l.anchor==="end"&&(p=`${f}$`);let h=[],m={value:0};try{let b=he(p,l.all?"g":"");for(let A of c)Nt(e,h,ts(e,A,b,d,l.all),m)}catch(b){if(b instanceof P)throw b;for(let A of c)Nt(e,h,A,m)}let E=Ae(e.state.env),S=Re(e.state.env);if(o){let b=Z(e.state.env),A=qi(e,h,b,m.value);return S?{values:A?[A]:[],quoted:!1}:{values:ce(A,E,e.limits.maxArrayElements),quoted:!1}}if(S)return{values:h,quoted:!1};let g=[],y={value:0};for(let b of h)if(b==="")Nt(e,g,"",y);else for(let A of ce(b,E,e.limits.maxArrayElements))Nt(e,g,A,y);return{values:g,quoted:!1}}async function Du(e,t,n,r){let s=-1,i="",o=!1;for(let y=0;y<t.length;y++){let b=t[y];if(b.type==="ParameterExpansion"&&b.operation?.type==="PatternRemoval"){let A=b.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(A){s=y,i=A[1],o=A[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,u=H(e,i),c=u.map(([,y])=>y);if(u.length===0){let y=e.state.env.get(i);y!==void 0&&(c=[y])}if(c.length===0)return{values:[],quoted:!1};let f="",d=e.state.shoptOptions.extglob;if(l.pattern)for(let y of l.pattern.parts)if(y.type==="Glob")f+=Y(y.pattern,l.greedy,d);else if(y.type==="Literal")f+=Y(y.value,l.greedy,d);else if(y.type==="SingleQuoted"||y.type==="Escaped")f+=ee(y.value);else if(y.type==="DoubleQuoted"){let b=await n(e,y.parts);f+=ee(b)}else if(y.type==="ParameterExpansion"){let b=await r(e,y);f+=Y(b,l.greedy,d)}else{let b=await r(e,y);f+=ee(b)}let p=[],h={value:0};for(let y of c)Nt(e,p,mt(e,y,f,l.side,l.greedy),h);let m=Ae(e.state.env),E=Re(e.state.env);if(o){let y=Z(e.state.env),b=qi(e,p,y,h.value);return E?{values:b?[b]:[],quoted:!1}:{values:ce(b,m,e.limits.maxArrayElements),quoted:!1}}if(E)return{values:p,quoted:!1};let S=[],g={value:0};for(let y of p)if(y==="")Nt(e,S,"",g);else for(let b of ce(y,m,e.limits.maxArrayElements))Nt(e,S,b,g);return{values:S,quoted:!1}}async function Iu(e,t,n,r){let s=-1,i=!1;for(let g=0;g<t.length;g++){let y=t[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="PatternRemoval"){s=g,i=y.parameter==="*";break}}if(s===-1)return null;let a=t[s].operation,l=Number.parseInt(e.state.env.get("#")||"0",10),u=[];for(let g=1;g<=l;g++)u.push(e.state.env.get(String(g))||"");if(u.length===0)return{values:[],quoted:!1};let c="",f=e.state.shoptOptions.extglob;if(a.pattern)for(let g of a.pattern.parts)if(g.type==="Glob")c+=Y(g.pattern,a.greedy,f);else if(g.type==="Literal")c+=Y(g.value,a.greedy,f);else if(g.type==="SingleQuoted"||g.type==="Escaped")c+=ee(g.value);else if(g.type==="DoubleQuoted"){let y=await n(e,g.parts);c+=ee(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);c+=Y(y,a.greedy,f)}else{let y=await r(e,g);c+=ee(y)}let d=[],p={value:0};for(let g of u)Nt(e,d,mt(e,g,c,a.side,a.greedy),p);let h=Ae(e.state.env),m=Re(e.state.env);if(i){let g=Z(e.state.env),y=qi(e,d,g,p.value);return m?{values:y?[y]:[],quoted:!1}:{values:ce(y,h,e.limits.maxArrayElements),quoted:!1}}if(m)return{values:d,quoted:!1};let E=[],S={value:0};for(let g of d)if(g==="")Nt(e,E,"",S);else for(let y of ce(g,h,e.limits.maxArrayElements))Nt(e,E,y,S);return{values:E,quoted:!1}}async function Ou(e,t,n,r){let s=-1,i=!1;for(let y=0;y<t.length;y++){let b=t[y];if(b.type==="ParameterExpansion"&&(b.parameter==="@"||b.parameter==="*")&&b.operation?.type==="Substring"){s=y,i=b.parameter==="*";break}}if(s===-1)return null;let a=t[s].operation,l=a.offset?await n(e,a.offset.expression):0,u=a.length?await n(e,a.length.expression):void 0,c=Number.parseInt(e.state.env.get("#")||"0",10),f=[];for(let y=1;y<=c;y++)f.push(e.state.env.get(String(y))||"");let d=e.state.env.get("0")||"bash",p;if(l<=0){let y=[d,...f],b=y.length+l;if(b<0)p=[];else{let A=l<0?b:0;if(u!==void 0){let k=u<0?y.length+u:A+u;p=y.slice(A,Math.max(A,k))}else p=y.slice(A)}}else{let y=l-1;if(y>=f.length)p=[];else if(u!==void 0){let b=u<0?f.length+u:y+u;p=f.slice(y,Math.max(y,b))}else p=f.slice(y)}let h="";for(let y=0;y<s;y++)h+=await r(e,t[y]);let m="";for(let y=s+1;y<t.length;y++)m+=await r(e,t[y]);let E=Ae(e.state.env),S=Re(e.state.env);if(p.length===0){let y=h+m;return y?S?{values:[y],quoted:!1}:{values:ce(y,E,e.limits.maxArrayElements),quoted:!1}:{values:[],quoted:!1}}let g;if(i){let y=Z(e.state.env),b=h+p.join(y)+m;S?g=b?[b]:[]:g=ce(b,E,e.limits.maxArrayElements)}else if(S)p.length===1?g=[h+p[0]+m]:g=[h+p[0],...p.slice(1,-1),p[p.length-1]+m];else{g=[];for(let y=0;y<p.length;y++){let b=p[y];if(y===0&&(b=h+b),y===p.length-1&&(b=b+m),b==="")g.push("");else{let A=ce(b,E,e.limits.maxArrayElements);De(g,A,e.limits.maxArrayElements,"unquoted expansion")}}}return{values:await is(e,g),quoted:!1}}async function _u(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].parameter!=="@"&&t[0].parameter!=="*"||t[0].operation)return null;let n=t[0].parameter==="*",r=Number.parseInt(e.state.env.get("#")||"0",10);if(r===0)return{values:[],quoted:!1};let s=[];for(let u=1;u<=r;u++)s.push(e.state.env.get(String(u))||"");let i=Ae(e.state.env),o=Re(e.state.env),a=Kr(e.state.env),l;if(n)if(o)l=s.filter(u=>u!=="");else{let u=Z(e.state.env),c=s.join(u);l=ce(c,i,e.limits.maxArrayElements)}else if(o)l=s.filter(u=>u!=="");else if(a){l=[];for(let u of s){if(u==="")continue;let c=ce(u,i,e.limits.maxArrayElements);De(l,c,e.limits.maxArrayElements,"unquoted expansion")}}else{l=[];for(let u of s)if(u==="")l.push("");else{let c=ce(u,i,e.limits.maxArrayElements);De(l,c,e.limits.maxArrayElements,"unquoted expansion")}for(;l.length>0&&l[l.length-1]==="";)l.pop()}return{values:await is(e,l),quoted:!1}}async function Lu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation)return null;let n=t[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!n)return null;let r=n[1],s=n[2]==="*",i=H(e,r),o;if(i.length===0){let f=e.state.env.get(r);if(f!==void 0)o=[f];else return{values:[],quoted:!1}}else o=i.map(([,f])=>f);let a=Ae(e.state.env),l=Re(e.state.env),u=Kr(e.state.env),c;if(s)if(l)c=o.filter(f=>f!=="");else{let f=Z(e.state.env),d=o.join(f);c=ce(d,a,e.limits.maxArrayElements)}else if(l)c=o.filter(f=>f!=="");else if(u){c=[];for(let f of o){if(f==="")continue;let d=ce(f,a,e.limits.maxArrayElements);De(c,d,e.limits.maxArrayElements,"unquoted expansion")}}else{c=[];for(let f of o)if(f==="")c.push("");else{let d=ce(f,a,e.limits.maxArrayElements);De(c,d,e.limits.maxArrayElements,"unquoted expansion")}for(;c.length>0&&c[c.length-1]==="";)c.pop()}return{values:await is(e,c),quoted:!1}}function Tu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="VarNamePrefix")return null;let n=t[0].operation,r=Mn(e,n.prefix);if(r.length===0)return{values:[],quoted:!1};let s=Ae(e.state.env),i=Re(e.state.env),o;if(n.star)if(i)o=r;else{let a=Z(e.state.env),l=r.join(a);o=ce(l,s,e.limits.maxArrayElements)}else if(i)o=r;else{o=[];for(let a of r){let l=ce(a,s,e.limits.maxArrayElements);De(o,l,e.limits.maxArrayElements,"unquoted expansion")}}return{values:o,quoted:!1}}function Fu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="ArrayKeys")return null;let n=t[0].operation,s=H(e,n.array).map(([l])=>String(l));if(s.length===0)return{values:[],quoted:!1};let i=Ae(e.state.env),o=Re(e.state.env),a;if(n.star)if(o)a=s;else{let l=Z(e.state.env),u=s.join(l);a=ce(u,i,e.limits.maxArrayElements)}else if(o)a=s;else{a=[];for(let l of s){let u=ce(l,i,e.limits.maxArrayElements);De(a,u,e.limits.maxArrayElements,"unquoted expansion")}}return{values:a,quoted:!1}}async function Mu(e,t,n){let r=-1;for(let d=0;d<t.length;d++){let p=t[d];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")&&!p.operation){r=d;break}}if(r===-1||t.length<=1)return null;let s=Number.parseInt(e.state.env.get("#")||"0",10),i=[];for(let d=1;d<=s;d++)i.push(e.state.env.get(String(d))||"");let o="";for(let d=0;d<r;d++)o+=await n(e,t[d]);let a="";for(let d=r+1;d<t.length;d++)a+=await n(e,t[d]);let l=Ae(e.state.env),u=Re(e.state.env),c=Kr(e.state.env);if(s===0){let d=o+a;return{values:d?[d]:[],quoted:!1}}let f;{let d=[];for(let p=0;p<i.length;p++){let h=i[p];p===0&&(h=o+h),p===i.length-1&&(h=h+a),d.push(h)}if(u)f=d.filter(p=>p!=="");else if(c){f=[];for(let p of d){if(p==="")continue;let h=ce(p,l,e.limits.maxArrayElements);De(f,h,e.limits.maxArrayElements,"unquoted expansion")}}else{f=[];for(let p of d)if(p==="")f.push("");else{let h=ce(p,l,e.limits.maxArrayElements);De(f,h,e.limits.maxArrayElements,"unquoted expansion")}for(;f.length>0&&f[f.length-1]==="";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await is(e,f),quoted:!1}}async function Vu(e,t,n){e.coverage?.hit("bash:expansion:word_glob");let r=t.parts,{hasQuoted:s,hasCommandSub:i,hasArrayVar:o,hasArrayAtExpansion:a,hasParamExpansion:l,hasVarNamePrefixExpansion:u,hasIndirection:c}=or(r),d=n.hasBraceExpansion(r)?await n.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return Lp(e,d,s);let p=await Tp(e,r,a,u,c,n);if(p!==null)return p;let h=await Mp(e,r,n);if(h!==null)return h;let m=await Bp(e,r,n);if(m!==null)return m;let E=await Vp(e,r,n.expandPart);if(E!==null)return Wu(e,E);if((i||o||l)&&!Re(e.state.env)){let g=Ae(e.state.env),y=n.buildIfsCharClassPattern(g),b=await n.smartWordSplit(e,r,g,y,n.expandPart);return Wu(e,b)}let S=await n.expandWordAsync(e,t);return zp(e,t,r,S,s,n.expandWordForGlobbing)}async function Lp(e,t,n){let r=[];for(let s of t)if(!(!n&&s===""))if(!n&&!e.state.options.noglob&&Ct(s,e.state.shoptOptions.extglob)){let i=await os(e,s);De(r,i,e.limits.maxArrayElements,"brace/glob expansion")}else r.push(s);return{values:r,quoted:!1}}async function Tp(e,t,n,r,s,i){if(n){let o=bu(e,t);if(o!==null)return o}{let o=Su(e,t);if(o!==null)return o}{let o=await mu(e,t);if(o!==null)return o}{let o=await yu(e,t,n,i.expandPart,i.expandWordPartsAsync);if(o!==null)return o}{let o=await gu(e,t,n,i.expandPart);if(o!==null)return o}{let o=await wu(e,t,i.evaluateArithmetic);if(o!==null)return o}{let o=Eu(e,t);if(o!==null)return o}{let o=await pu(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}{let o=await hu(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}if(r&&t.length===1&&t[0].type==="DoubleQuoted"){let o=Fp(e,t);if(o!==null)return o}{let o=await Au(e,t,s,i.expandParameterAsync,i.expandWordPartsAsync);if(o!==null)return o}{let o=await vu(e,t);if(o!==null)return o}{let o=await ku(e,t);if(o!==null)return o}return null}function Fp(e,t){let n=t[0];if(n.type!=="DoubleQuoted")return null;if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="VarNamePrefix"){let r=n.parts[0].operation,s=Mn(e,r.prefix);return r.star?{values:[s.join(Z(e.state.env))],quoted:!0}:{values:s,quoted:!0}}if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="ArrayKeys"){let r=n.parts[0].operation,i=H(e,r.array).map(([o])=>String(o));return r.star?{values:[i.join(Z(e.state.env))],quoted:!0}:{values:i,quoted:!0}}return null}async function Mp(e,t,n){{let r=await xu(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await Pu(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await Cu(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await Nu(e,t,n.expandPart);if(r!==null)return r}return null}async function Bp(e,t,n){{let r=await Ru(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Du(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Iu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Ou(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await _u(e,t);if(r!==null)return r}{let r=await Lu(e,t);if(r!==null)return r}{let r=Tu(e,t);if(r!==null)return r}{let r=Fu(e,t);if(r!==null)return r}{let r=await Mu(e,t,n.expandPart);if(r!==null)return r}return null}function Bu(e){if(e.type!=="DoubleQuoted")return null;for(let t=0;t<e.parts.length;t++){let n=e.parts[t];if(n.type!=="ParameterExpansion"||n.operation)continue;let r=n.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(r)return{type:"array",name:r[1],atIndex:t,isStar:r[2]==="*"};if(n.parameter==="@"||n.parameter==="*")return{type:"positional",atIndex:t,isStar:n.parameter==="*"}}return null}async function Wp(e,t,n,r){let s="";for(let a=0;a<n.atIndex;a++)s+=await r(e,t.parts[a]);let i="";for(let a=n.atIndex+1;a<t.parts.length;a++)i+=await r(e,t.parts[a]);let o;if(n.type==="array"){if(o=H(e,n.name).map(([,l])=>l),o.length===0){let l=e.state.env.get(n.name);l!==void 0&&(o=[l])}}else{let a=Number.parseInt(e.state.env.get("#")||"0",10);o=[];for(let l=1;l<=a;l++)o.push(e.state.env.get(String(l))||"")}if(n.isStar){let a=Z(e.state.env),l=o.join(a);return[s+l+i]}if(o.length===0){let a=s+i;return a?[a]:[]}return o.length===1?[s+o[0]+i]:[s+o[0],...o.slice(1,-1),o[o.length-1]+i]}async function Vp(e,t,n){if(t.length<2)return null;let r=!1;for(let l of t)if(Bu(l)){r=!0;break}if(!r)return null;let s=Ae(e.state.env),i=Re(e.state.env),o=[];for(let l of t){let u=Bu(l);if(u&&l.type==="DoubleQuoted"){let c=await Wp(e,l,u,n);o.push(c)}else if(l.type==="DoubleQuoted"||l.type==="SingleQuoted"){let c=await n(e,l);o.push([c])}else if(l.type==="Literal")o.push([l.value]);else if(l.type==="ParameterExpansion"){let c=await n(e,l);if(i)o.push(c?[c]:[]);else{let f=ce(c,s,e.limits.maxArrayElements);o.push(f)}}else{let c=await n(e,l);if(i)o.push(c?[c]:[]);else{let f=ce(c,s,e.limits.maxArrayElements);o.push(f)}}}let a=[];for(let l of o)if(l.length!==0)if(a.length===0)De(a,l,e.limits.maxArrayElements,"word expansion");else{let u=a.length-1;a[u]=a[u]+l[0];for(let c=1;c<l.length;c++)a.push(l[c])}return a}async function Wu(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let n=[];for(let r of t)if(Ct(r,e.state.shoptOptions.extglob)){let s=await os(e,r);De(n,s,e.limits.maxArrayElements,"glob expansion")}else n.push(r);return{values:n,quoted:!1}}async function os(e,t){let n=new Xt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")}),r=await n.expand(t);if(r.length>0)return r;if(n.hasFailglob())throw new Wt(t);return n.hasNullglob()?[]:[t]}async function zp(e,t,n,r,s,i){let o=n.some(a=>a.type==="Glob");if(!e.state.options.noglob&&o){let a=await i(e,t);if(Ct(a,e.state.shoptOptions.extglob)){let u=await os(e,a);if(u.length>0&&u[0]!==a)return{values:u,quoted:!1};if(u.length===0)return{values:[],quoted:!1}}let l=Wi(r);if(!Re(e.state.env)){let u=Ae(e.state.env);return{values:ce(l,u,e.limits.maxArrayElements),quoted:!1}}return{values:[l],quoted:!1}}if(!s&&!e.state.options.noglob&&Ct(r,e.state.shoptOptions.extglob)){let a=await i(e,t);if(Ct(a,e.state.shoptOptions.extglob)){let l=await os(e,a);if(l.length>0&&l[0]!==a)return{values:l,quoted:!1}}}if(r===""&&!s)return{values:[],quoted:!1};if(o&&!s){let a=Wi(r);if(!Re(e.state.env)){let l=Ae(e.state.env);return{values:ce(a,l,e.limits.maxArrayElements),quoted:!1}}return{values:[a],quoted:!1}}return{values:[r],quoted:s}}function Le(e,t,n){if(t.length>=e.limits.maxArrayElements)throw new P(`word splitting element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");t.push(n)}async function Uu(e,t){let n=t.operation;if(!n||n.type!=="DefaultValue"&&n.type!=="AssignDefault"&&n.type!=="UseAlternative")return null;let r=n.word;if(!r||r.parts.length===0)return null;let s=await Pt(e,t.parameter),o=await ie(e,t.parameter,!1)==="",a=n.checkEmpty??!1,l;return n.type==="UseAlternative"?l=s&&!(a&&o):l=!s||a&&o,l?r.parts:null}function Up(e){return e.type==="SingleQuoted"?!0:e.type==="DoubleQuoted"?e.parts.every(n=>n.type==="Literal"):!1}async function qp(e,t){if(t.type!=="ParameterExpansion")return null;let n=await Uu(e,t);if(!n||n.length<=1)return null;let r=n.some(i=>Up(i)),s=n.some(i=>i.type==="Literal"||i.type==="ParameterExpansion"||i.type==="CommandSubstitution"||i.type==="ArithmeticExpansion");return r&&s?n:null}function jp(e){return e.type==="DoubleQuoted"||e.type==="SingleQuoted"||e.type==="Literal"?!1:e.type==="Glob"?Ii(e.pattern):!(!(e.type==="ParameterExpansion"||e.type==="CommandSubstitution"||e.type==="ArithmeticExpansion")||e.type==="ParameterExpansion"&&Wl(e))}async function qu(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:word_split"),t.length===1&&t[0].type==="ParameterExpansion"){let d=t[0],p=await Uu(e,d);if(p&&p.length>0&&p.length>1&&p.some(m=>m.type==="DoubleQuoted"||m.type==="SingleQuoted")&&p.some(m=>m.type==="Literal"||m.type==="ParameterExpansion"||m.type==="CommandSubstitution"||m.type==="ArithmeticExpansion"))return zu(e,p,n,r,s)}let i=[],o=!1;for(let d of t){let p=jp(d),h=d.type==="DoubleQuoted"||d.type==="SingleQuoted",m=p?await qp(e,d):null,E=await s(e,d);i.push({value:E,isSplittable:p,isQuoted:h,mixedDefaultParts:m??void 0}),p&&(o=!0)}if(!o){let d=i.map(p=>p.value).join("");return d?[d]:[]}let a=[],l="",u=!1,c=!1,f=!1;for(let d of i)if(!d.isSplittable)c?d.isQuoted&&d.value===""?(l!==""&&Le(e,a,l),Le(e,a,""),u=!0,l="",c=!1,f=!0):d.value!==""?(l!==""&&Le(e,a,l),l=d.value,c=!1,f=!1):(l+=d.value,f=!1):(l+=d.value,f=d.isQuoted&&d.value==="");else if(d.mixedDefaultParts){let p=await zu(e,d.mixedDefaultParts,n,r,s);if(p.length!==0)if(p.length===1)l+=p[0],u=!0;else{l+=p[0],Le(e,a,l),u=!0;for(let h=1;h<p.length-1;h++)Le(e,a,p[h]);l=p[p.length-1]}c=!1,f=!1}else{let{words:p,hadLeadingDelimiter:h,hadTrailingDelimiter:m}=Xr(d.value,n,e.limits.maxArrayElements);if(f&&h&&l===""&&(Le(e,a,""),u=!0),p.length===0)m&&(c=!0);else if(p.length===1)l+=p[0],u=!0,c=m;else{l+=p[0],Le(e,a,l),u=!0;for(let E=1;E<p.length-1;E++)Le(e,a,p[E]);l=p[p.length-1],c=m}f=!1}return l!==""?Le(e,a,l):a.length===0&&u&&Le(e,a,""),a}function Hp(e,t){return e.length>0&&t.includes(e[0])}async function zu(e,t,n,r,s){let i=[];for(let c of t){let d=!(c.type==="DoubleQuoted"||c.type==="SingleQuoted"),p=await s(e,c);i.push({value:p,isSplittable:d})}let o=[],a="",l=!1,u=!1;for(let c of i)if(!c.isSplittable)u&&c.value!==""?(a!==""&&Le(e,o,a),a=c.value,u=!1):a+=c.value;else{Hp(c.value,n)&&a!==""&&(Le(e,o,a),a="",l=!0);let{words:d,hadTrailingDelimiter:p}=Xr(c.value,n,e.limits.maxArrayElements);if(d.length===0)p&&(u=!0);else if(d.length===1)a+=d[0],l=!0,u=p;else{a+=d[0],Le(e,o,a),l=!0;for(let h=1;h<d.length-1;h++)Le(e,o,d[h]);a=d[d.length-1],u=p}}return a!==""?Le(e,o,a):o.length===0&&l&&Le(e,o,""),o}function ju(e){switch(e.type){case"Literal":return e.value;case"SingleQuoted":return e.value;case"Escaped":return e.value;default:return null}}function Hu(e){switch(e.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return e.value==="";default:return!1}}var ur=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new vt,t?.mounts)for(let{mountPoint:n,filesystem:r}of t.mounts)this.mount(n,r)}mount(t,n){this.validateMountPath(t);let r=z(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(t){let n=z(t);if(!this.mounts.has(n))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(n)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let n=z(t);return this.mounts.has(n)}validateMountPath(t){let n=t.split("/");for(let r of n)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let n of this.mounts.keys())if(n!==t){if(t.startsWith(`${n}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${n}'`);if(n.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${n}'`)}}routePath(t){K(t,"access");let n=z(t),r=null,s=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(n===o)return{fs:i.filesystem,relativePath:"/"};n.startsWith(`${o}/`)&&o.length>s&&(r=i,s=o.length)}if(r){let i=n.slice(s);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:n}}getChildMountPoints(t){let n=z(t),r=n==="/"?"/":`${n}/`,s=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!s.includes(a)&&s.push(a)}return s}async readFile(t,n){let{fs:r,relativePath:s}=this.routePath(t);return r.readFile(s,n)}async readFileBytes(t){let{fs:n,relativePath:r}=this.routePath(t);return xn(n,r)}async readFileBuffer(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readFileBuffer(r)}async writeFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.writeFile(i,n,r)}async appendFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.appendFile(i,n,r)}async exists(t){let n=z(t);if(this.mounts.has(n)||this.getChildMountPoints(n).length>0)return!0;let{fs:s,relativePath:i}=this.routePath(t);return s.exists(i)}async stat(t){let n=z(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.stat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.stat(o)}async lstat(t){let n=z(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.lstat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.lstat(o)}async mkdir(t,n){let r=z(t);if(this.mounts.has(r)){if(n?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&n?.recursive)return;let{fs:i,relativePath:o}=this.routePath(t);return i.mkdir(o,n)}async readdir(t){let n=z(t),r=new Set,s=null,{fs:i,relativePath:o}=this.routePath(t);try{let l=await i.readdir(o);for(let u of l)r.add(u)}catch(l){let u=l.code,c=l.message||"";if(u!=="ENOENT"&&!c.includes("ENOENT"))throw l;s=l}let a=this.getChildMountPoints(n);for(let l of a)r.add(l);if(r.size===0&&s&&!this.mounts.has(n))throw s;return Array.from(r).sort()}async rm(t,n){let r=z(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:o}=this.routePath(t);return i.rm(o,n)}async cp(t,n,r){if((await this.stat(t)).isDirectory&&_t(t,n))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);let i=this.routePath(t),o=this.routePath(n);return i.fs===o.fs?i.fs.cp(i.relativePath,o.relativePath,r):this.crossMountCopy(t,n,r)}async mv(t,n){let r=z(t);if((await this.stat(t)).isDirectory&&_t(t,n))throw new Error(`EINVAL: cannot move '${t}' into itself, '${n}'`);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let i=this.routePath(t),o=this.routePath(n);if(i.fs===o.fs)return i.fs.mv(i.relativePath,o.relativePath);await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return Nn(t,n)}getAllPaths(){let t=new Set;for(let n of this.baseFs.getAllPaths())t.add(n);for(let n of this.mounts.keys()){let r=n.split("/").filter(Boolean),s="";for(let o of r)s=`${s}/${o}`,t.add(s);let i=this.mounts.get(n);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?t.add(n):t.add(`${n}${o}`)}return Array.from(t).sort()}async chmod(t,n){let r=z(t),s=this.mounts.get(r);if(s)return s.filesystem.chmod("/",n);let{fs:i,relativePath:o}=this.routePath(t);return i.chmod(o,n)}async symlink(t,n){let{fs:r,relativePath:s}=this.routePath(n);return r.symlink(t,s)}async link(t,n){let r=this.routePath(t),s=this.routePath(n);if(r.fs!==s.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${n}'`);return r.fs.link(r.relativePath,s.relativePath)}async readlink(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readlink(r)}async realpath(t){let n=z(t);if(this.mounts.get(n))return n;let{fs:s,relativePath:i}=this.routePath(t),o=await s.realpath(i);for(let[a,l]of this.mounts)if(n===a||n.startsWith(`${a}/`))return o==="/"?a:`${a}${o}`;return o}async crossMountCopy(t,n,r){let s=await this.lstat(t);if(s.isFile){let i=await this.readFileBuffer(t);await this.writeFile(n,i),await this.chmod(n,s.mode)}else if(s.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(n,{recursive:!0});let i=await this.readdir(t);for(let o of i){let a=Lt(t,o),l=Lt(n,o);await this.crossMountCopy(a,l,r)}}else if(s.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,n)}}async utimes(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.utimes(i,n,r)}};var as="/dev/fd",Zu=63,Gp=10,Gu=Zu-Gp+1,ji=class extends vt{isLiveDescriptor;constructor(t){super(),this.isLiveDescriptor=t}assertLiveDescriptor(t,n){this.isLiveDescriptor(t)||this.refuse(t,n)}refuse(t,n){throw new Error(`EROFS: read-only file system, ${n} '${as}${t}'`)}async writeFile(t,n,r){return this.assertLiveDescriptor(t,"write"),super.writeFile(t,n,r)}async appendFile(t,n,r){return this.assertLiveDescriptor(t,"append"),super.appendFile(t,n,r)}async rm(t,n){return this.assertLiveDescriptor(t,"rm"),super.rm(t,n)}async mkdir(t,n){this.refuse(t,"mkdir")}async cp(t,n){this.refuse(n,"cp")}async mv(t,n){this.refuse(n,"mv")}async symlink(t,n){this.refuse(n,"symlink")}async link(t,n){this.refuse(n,"link")}async chmod(t,n){this.refuse(t,"chmod")}async utimes(t,n,r){this.refuse(t,"utimes")}};function Zp(e){let t=new ji(n=>Qu(e).some(r=>r.path===`${as}${n}`));e.fs=new ur({base:e.fs,mounts:[{mountPoint:as,filesystem:t}]}),e.state.processSubstitutionFsMounted=!0}async function Qp(e,t,n){try{await e.fs.writeFile(t,n,"binary");return}catch(r){if(e.state.processSubstitutionFsMounted)throw r;Zp(e)}await e.fs.writeFile(t,n,"binary")}async function Kp(e,t){try{await e.fs.rm(t,{force:!0})}catch{}}function Qu(e){let t=e.state.processSubstitutions;if(t)return t;let n=[];return e.state.processSubstitutions=n,n}async function Ku(e,t,n){let r=e.substitutionDepth??0,s=e.limits.maxSubstitutionDepth;if(r>=s)throw new P(`Process substitution nesting limit exceeded (${s})`,"substitution_depth");let i=e.substitutionDepth,o=new Map(e.state.env),a=it(e.state.arrays),l=e.state.cwd,u=e.state.bashPid,c=e.state.suppressVerbose,f=e.state.groupStdin,d=e.state.lastExitCode,p=e.state.env.get("?");e.substitutionDepth=r+1,e.state.bashPid=e.state.nextVirtualPid++,e.state.suppressVerbose=!0,n!==void 0&&(e.state.groupStdin=n);let h;try{h=await e.executeScript(t)}catch(m){if(m instanceof P)throw m;if(m instanceof U)return{stdout:m.stdout,stderr:m.stderr,exitCode:m.exitCode};throw m}finally{e.substitutionDepth=i,e.state.env=o,e.state.arrays=a,e.state.cwd=l,e.state.bashPid=u,e.state.suppressVerbose=c,e.state.groupStdin=f,e.state.lastExitCode=d,p!==void 0?e.state.env.set("?",p):e.state.env.delete("?")}return h}async function Xu(e,t){let n=Qu(e);if(n.length>=Gu)throw new P(`Process substitution limit exceeded (${Gu} concurrent)`,"file_descriptors");let r="";if(t.direction==="input"){let o=await Ku(e,t.body,void 0);if(o.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+o.stderr),r=Mt(o),r.length>e.limits.maxStringLength)throw new P(`process substitution: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")}let s=Zu-n.length,i=`${as}/${s}`;n.push({fd:s,path:i,direction:t.direction,body:t.body});try{await Qp(e,i,r)}catch(o){throw n.pop(),o}return i}function Yu(e){return e.state.processSubstitutions?.length??0}var Xp={stdout:"",stderr:""};async function Hi(e,t){let n=e.state.processSubstitutions;if(!n||n.length<=t)return Xp;let r="",s="";for(;n.length>t;){let i=n[n.length-1],o="";if(i.direction==="output")try{o=await xn(e.fs,i.path)}catch{}if(await Kp(e,i.path),n.pop(),i.direction==="output"){let a=await Ku(e,i.body,o);r+=Mt(a),s+=a.stderr}}return{stdout:r,stderr:s}}function tn(e,t,n){if(e.length>t)throw new P(`${n}: string length limit exceeded (${t} bytes)`,"string_length")}async function gt(e,t,n=!1){let r=[];for(let s of t)r.push(await et(e,s,n));return r.join("")}function Yp(e){return Hu(e)}function ec(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!Yp(t))return!1;return!0}function Jp(e,t,n=!1){let r=ju(t);if(r!==null)return r;switch(t.type){case"TildeExpansion":return n?t.user===null?"~":`~${t.user}`:(e.coverage?.hit("bash:expansion:tilde"),t.user===null?e.state.env.get("HOME")??"/home/user":t.user==="root"?"/root":`~${t.user}`);case"Glob":return Vi(e,t.pattern);default:return null}}async function se(e,t){return Zi(e,t)}async function tc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped")n.push(Fn(r.value));else if(r.type==="SingleQuoted")n.push(r.value);else if(r.type==="DoubleQuoted"){let s=await gt(e,r.parts);n.push(s)}else if(r.type==="TildeExpansion"){let s=await et(e,r);n.push(Fn(s))}else n.push(await et(e,r));return n.join("")}async function nc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped"){let s=r.value;"()|*?[]".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="SingleQuoted")n.push(Je(r.value));else if(r.type==="DoubleQuoted"){let s=await gt(e,r.parts);n.push(Je(s))}else n.push(await et(e,r));return n.join("")}async function rc(e,t){let n=[];for(let r of t.parts)if(r.type==="SingleQuoted")n.push(Je(r.value));else if(r.type==="Escaped"){let s=r.value;"*?[]\\()|".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="DoubleQuoted"){let s=await gt(e,r.parts);n.push(Je(s))}else r.type==="Glob"?cu(r.pattern)?n.push(await du(e,r.pattern)):n.push(Vi(e,r.pattern)):r.type==="Literal"?n.push(r.value):n.push(await et(e,r));return n.join("")}function us(e){for(let t of e)if(t.type==="BraceExpansion"||t.type==="DoubleQuoted"&&us(t.parts))return!0;return!1}var Ju=1e5;async function sc(e,t,n={count:0}){let r=()=>{n.count++,e.executionScope.consumeLimited("brace_operations",1,Math.min(Ju,e.limits.maxBraceExpansionResults),"brace expansion")},s=(o,a)=>{if(o.length>=e.limits.maxBraceExpansionResults)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),o.push(a)},i=[[]];for(let o of t)if(o.type==="BraceExpansion"){let a=[],l=!1,u="";for(let d of o.items)if(d.type==="Range"){let p=Bi(d.start,d.end,d.step,d.startStr,d.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(p.expanded)for(let h of p.expanded)s(a,h);else{l=!0,u=p.literal;break}}else{let p=await sc(e,d.word.parts,n);for(let h of p){let m=[];for(let E of h)typeof E=="string"?m.push(E):m.push(await et(e,E));s(a,m.join(""))}}if(l){for(let d of i)r(),d.push(u);continue}if(i.length*a.length>e.limits.maxBraceExpansionResults||n.count>Ju)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");let f=[];for(let d of i)for(let p of a){if(f.length>=e.limits.maxBraceExpansionResults)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),f.push([...d,p])}i=f}else for(let a of i)r(),a.push(o);return i}async function ic(e,t){let n=t.parts;if(!us(n))return[await se(e,t)];let r=await sc(e,n),s=[];for(let i of r){let o=[];for(let a of i)typeof a=="string"?o.push(a):o.push(await et(e,a));s.push(zi(e,o.join("")))}return s}function eh(){return{expandWordAsync:Zi,expandWordForGlobbing:rc,expandWordWithBracesAsync:ic,expandWordPartsAsync:gt,expandPart:et,expandParameterAsync:ls,hasBraceExpansion:us,evaluateArithmetic:X,buildIfsCharClassPattern:Vl,smartWordSplit:qu}}async function wt(e,t){return Vu(e,t,eh())}function th(e){for(let t of e){if(t.type==="ParameterExpansion")return t.parameter;if(t.type==="Literal")return t.value}return""}function Gi(e,t){if(Number.parseInt(e.state.env.get("#")||"0",10)<2)return!1;function r(s){for(let i of s)if(i.type==="DoubleQuoted"){for(let o of i.parts)if(o.type==="ParameterExpansion"&&o.parameter==="@"&&!o.operation)return!0}return!1}return r(t.parts)}async function oc(e,t){if(Gi(e,t))return{error:`bash: $@: ambiguous redirect
|
|
108
|
-
`};let n=t.parts,{hasQuoted:r}=
|
|
109
|
-
`};let s=await
|
|
110
|
-
`}}if(r||e.state.options.noglob||n.some(f=>f.type==="ProcessSubstitution"))return{target:s};let l=await
|
|
94
|
+
${e.terminator}`}function Ep(e){return`(${lt(e.body)})${mt(e.redirections)}`}function bp(e){return`{ ${lt(e.body)}; }${mt(e.redirections)}`}function Sp(e){return`((${de(e.expression.expression)}))${mt(e.redirections)}`}function Ap(e){return`[[ ${An(e.expression)} ]]${mt(e.redirections)}`}function vp(e){let t=Ll(e.body);return`${e.name}() ${t}${mt(e.redirections)}`}function de(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${de(e.left)} ${e.operator} ${de(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${de(e.operand)}`:`${de(e.operand)}${e.operator}`;case"ArithTernary":return`${de(e.condition)} ? ${de(e.consequent)} : ${de(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${de(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${de(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${de(e.target)}[${de(e.subscript)}]`:de(e.target)} ${e.operator} ${de(e.value)}`;case"ArithDynamicElement":return`${de(e.nameExpr)}[${de(e.subscript)}]`;case"ArithGroup":return`(${de(e.expression)})`;case"ArithNested":return`$((${de(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${de(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(de).join("");case"ArithDoubleSubscript":return`${e.array}[${de(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function An(e){switch(e.type){case"CondBinary":return`${Ae(e.left)} ${e.operator} ${Ae(e.right)}`;case"CondUnary":return`${e.operator} ${Ae(e.operand)}`;case"CondNot":return`! ${An(e.operand)}`;case"CondAnd":return`${An(e.left)} && ${An(e.right)}`;case"CondOr":return`${An(e.left)} || ${An(e.right)}`;case"CondGroup":return`( ${An(e.expression)} )`;case"CondWord":return Ae(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var kp="BASH_ALIAS_";function es(e,t,n,r){let s=B(t);if(s>n-r.value)throw new P(`alias expansion exceeds string length limit (${n} bytes)`,"string_length");return r.value+=s,e+t}function Bl(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Wl(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Vl(e,t){return e.env.get(`${kp}${t}`)}function Ul(e,t,n){return ql(e,t,n)}function ql(e,t,n,r=!0){if(!t.name||!Bl(t.name))return t;let s=Wl(t.name);if(!s)return t;let i=Vl(e,s);if(!i||n.has(s))return t;try{n.add(s);let a=new H,o={value:0},l=es("",i,e.limits.maxStringLength,o),u=i.endsWith(" ");if(!u)for(let p of t.args){let h=Ae(p);l=es(l,` ${h}`,e.limits.maxStringLength,o)}let c;try{c=a.parse(l)}catch(p){if(p instanceof xe)throw p;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return zl(e,t,i);let f=c.statements[0].pipelines[0].commands[0];if(f.type!=="SimpleCommand")return zl(e,t,i);let d={...f,assignments:[...t.assignments,...f.assignments],redirections:[...f.redirections,...t.redirections],line:t.line};if(u&&t.args.length>0){d={...d,args:[...d.args,...t.args]};let p=1;for(;r&&d.args.length>0;){let h=d.args[0];if(!Bl(h))break;let m=Wl(h),E=m?Vl(e,m):null;if(!E)break;if(p>=e.limits.maxCallDepth)throw new P(`alias expansion depth limit exceeded (${e.limits.maxCallDepth})`,"recursion");p++;let S={type:"SimpleCommand",name:h,args:d.args.slice(1),assignments:[],redirections:[]},g=ql(e,S,n,!1);if(g===S||(d={...d,name:g.name,args:[...g.args]},!E.endsWith(" ")))break}}return d}catch(a){throw n.delete(s),a}}function zl(e,t,n){let r={value:0},s=es("",n,e.limits.maxStringLength,r);for(let u of t.args){let c=Ae(u);s=es(s,` ${c}`,e.limits.maxStringLength,r)}let i=new H,a=i.parseWordFromString("eval",!1,!1),o=0;for(let u of s)u==="'"&&o++;if(r.value+2+o*3>e.limits.maxStringLength)throw new P(`alias expansion exceeds string length limit (${e.limits.maxStringLength} bytes)`,"string_length");let l=i.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:a,args:[l],assignments:t.assignments,redirections:t.redirections,line:t.line}}var xp=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9a-fA-F"]]);function Fi(e){return xp.get(e)??""}function jl(e){let t=[],n="",r=0;for(;r<e.length;){let s=e[r];if(s==="["){for(n+=s,r++,r<e.length&&(e[r]==="!"||e[r]==="^")&&(n+=e[r],r++),r<e.length&&e[r]==="]"&&(n+=e[r],r++);r<e.length&&e[r]!=="]";){if(e[r]==="["&&r+1<e.length&&e[r+1]===":"){let i=e.indexOf(":]",r+2);if(i!==-1){n+=e.slice(r,i+2),r=i+2;continue}}if(e[r]==="\\"&&r+1<e.length){n+=e[r]+e[r+1],r+=2;continue}n+=e[r],r++}r<e.length&&e[r]==="]"&&(n+=e[r],r++)}else s===":"?(n!==""&&t.push(n),n="",r++):s==="\\"&&r+1<e.length?(n+=s+e[r+1],r+=2):(n+=s,r++)}return n!==""&&t.push(n),t}function Hl(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n];if(r==="*")t+="[^/]*";else if(r==="?")t+="[^/]";else if(r==="["){let s=n+1,i="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(i+="^",s++),s<e.length&&e[s]==="]"&&(i+="\\]",s++);let a=s;for(;a<e.length;){if(e[a]==="\\"&&a+1<e.length){a+=2;continue}if(e[a]==="["&&a+1<e.length&&e[a+1]===":"){let l=e.indexOf(":]",a+2);if(l!==-1){a=l+2;continue}}if(e[a]==="]")break;a++}let o=s;for(;s<e.length&&e[s]!=="]";){if(e[s]==="["&&s+1<e.length&&e[s+1]===":"){let l=e.indexOf(":]",s+2);if(l!==-1){let u=e.slice(s+2,l),c=Fi(u);i+=c,s=l+2;continue}}if(e[s]==="\\"&&s+1<e.length){i+=`\\${e[s+1]}`,s+=2;continue}if(e[s]==="-"){let l=s===o,u=s+1===a;l||u?i+="\\-":i+="-"}else i+=e[s];s++}i+="]",t+=i,n=s}else if(r==="\\"&&n+1<e.length){let s=e[n+1];/[.+^${}()|\\*?[\]]/.test(s)?t+=`\\${s}`:t+=s,n++}else/[.+^${}()|]/.test(r)?t+=`\\${r}`:t+=r}return t+="$",me(t)}function Mi(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Bi(e){let t=[],n="",r=0,s=!1,i=0;for(;i<e.length;){let a=e[i];if(a==="'"&&!s){s=!0,n+="\0QUOTE_START\0",i++;continue}if(a==="'"&&s){s=!1,n+="\0QUOTE_END\0",i++;continue}if(s){n+=a,i++;continue}if(a==="\\"){n+=a,i+1<e.length?(n+=e[i+1],i+=2):i++;continue}a==="("?(r++,n+=a):a===")"?(r--,n+=a):a==="|"&&r===0?(t.push(n),n=""):n+=a,i++}return t.push(n),t}var Gl=5,Jt=class{fs;cwd;globignorePatterns=[];hasGlobignore=!1;globstar=!1;nullglob=!1;failglob=!1;dotglob=!1;extglob=!1;globskipdots=!0;ops={count:0};maxOps;consumeOperation;constructor(t,n,r,s){this.fs=t,this.cwd=n,typeof s=="boolean"?(this.globstar=s,this.maxOps=1e5):s?(this.globstar=s.globstar??!1,this.nullglob=s.nullglob??!1,this.failglob=s.failglob??!1,this.dotglob=s.dotglob??!1,this.extglob=s.extglob??!1,this.globskipdots=s.globskipdots??!0,this.maxOps=s.maxGlobOperations??1e5,this.consumeOperation=s.consumeOperation):this.maxOps=1e5;let i=r?.get("GLOBIGNORE");i!==void 0&&i!==""&&(this.hasGlobignore=!0,this.globignorePatterns=jl(i))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new P(`Glob operation limit exceeded (${this.maxOps})`,"glob_operations");this.consumeOperation?.()}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(t){return!this.hasGlobignore&&!this.globskipdots?t:t.filter(n=>{let r=n.split("/").pop()||n;if((this.hasGlobignore||this.globskipdots)&&(r==="."||r===".."))return!1;if(this.hasGlobignore){for(let s of this.globignorePatterns)if(this.matchGlobignorePattern(n,s))return!1}return!0})}matchGlobignorePattern(t,n){return Hl(n).test(t)}isGlobPattern(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandArgs(t,n){let r=t.map((a,o)=>(n?.[o]??!1)||!this.isGlobPattern(a)?null:this.expand(a)),s=await Promise.all(r.map(a=>a||Promise.resolve(null))),i=[];for(let a=0;a<t.length;a++){let o=s[a];o===null?i.push(t[a]):o.length>0?i.push(...o):i.push(t[a])}return i}async expand(t){if(this.globstar){let r=t.split("/"),s=0;for(let i of r)if(i==="**"&&(s++,s>Gl))throw new P(`Glob pattern has too many ** segments (max ${Gl})`,"glob_operations")}let n;if(t.includes("**")&&this.globstar&&this.isGlobstarValid(t))n=await this.expandRecursive(t);else{let r=t.replace(/\*\*+/g,"*");n=await this.expandSimple(r)}return this.filterGlobignore(n)}isGlobstarValid(t){let n=t.split("/");for(let r of n)if(r.includes("**")&&r!=="**")return!1;return!0}hasGlobChars(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandSimple(t){let n=t.startsWith("/"),r=t.split("/").filter(u=>u!==""),s=-1;for(let u=0;u<r.length;u++)if(this.hasGlobChars(r[u])){s=u;break}if(s===-1)return[t];let i,a;if(s===0)n?(i="/",a="/"):(i=this.cwd,a="");else{let u=r.slice(0,s);n?(i=`/${u.join("/")}`,a=`/${u.join("/")}`):(i=this.fs.resolvePath(this.cwd,u.join("/")),a=u.join("/"))}let o=r.slice(s);return(await this.expandSegments(i,a,o)).sort()}async expandSegments(t,n,r){if(this.checkOpsLimit(),r.length===0)return[n];let[s,...i]=r,a=[];try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let o=await this.fs.readdirWithFileTypes(t),l=[],u=[...o],c=this.dotglob||this.hasGlobignore;if(s.startsWith(".")||this.dotglob){let d=o.some(h=>h.name==="."),p=o.some(h=>h.name==="..");d||u.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),p||u.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let d of u)if(!(d.name.startsWith(".")&&!s.startsWith(".")&&!c)&&this.matchPattern(d.name,s)){let p=t==="/"?`/${d.name}`:`${t}/${d.name}`,h;n===""?h=d.name:n==="/"?h=`/${d.name}`:h=`${n}/${d.name}`,i.length===0?l.push(Promise.resolve([h])):d.isDirectory&&l.push(this.expandSegments(p,h,i))}let f=await Promise.all(l);for(let d of f)a.push(...d)}else{this.checkOpsLimit();let o=await this.fs.readdir(t),l=[],u=[...o],c=this.dotglob||this.hasGlobignore;(s.startsWith(".")||this.dotglob)&&(o.includes(".")||u.push("."),o.includes("..")||u.push(".."));for(let d of u)if(!(d.startsWith(".")&&!s.startsWith(".")&&!c)&&this.matchPattern(d,s)){let p=t==="/"?`/${d}`:`${t}/${d}`,h;n===""?h=d:n==="/"?h=`/${d}`:h=`${n}/${d}`,i.length===0?l.push(Promise.resolve([h])):l.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(p)).isDirectory)return this.expandSegments(p,h,i)}catch(m){if(m instanceof P)throw m}return[]})())}let f=await Promise.all(l);for(let d of f)a.push(...d)}}catch(o){if(o instanceof P)throw o}return a}async expandRecursive(t){let n=[],r=t.indexOf("**"),s=t.slice(0,r).replace(/\/$/,"")||".",a=t.slice(r+2).replace(/^\//,"");return a.includes("**")&&this.isGlobstarValid(a)?(await this.walkDirectoryMultiGlobstar(s,a,n),[...new Set(n)].sort()):(await this.walkDirectory(s,a,n),n.sort())}async walkDirectoryMultiGlobstar(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{this.checkOpsLimit();let i=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(s):null;if(i){let a=[];for(let u of i){let c=t==="."?u.name:`${t}/${u.name}`;u.isDirectory&&a.push(c)}let o=t==="."?n:`${t}/${n}`,l=await this.expandRecursive(o);r.push(...l);for(let u=0;u<a.length;u+=100){let c=a.slice(u,u+100);await Promise.all(c.map(f=>this.walkDirectoryMultiGlobstar(f,n,r)))}}else{this.checkOpsLimit();let a=await this.fs.readdir(s),o=[];for(let c of a){let f=t==="."?c:`${t}/${c}`,d=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory&&o.push(f)}catch(p){if(p instanceof P)throw p}}let l=t==="."?n:`${t}/${n}`,u=await this.expandRecursive(l);r.push(...u);for(let c=0;c<o.length;c+=100){let f=o.slice(c,c+100);await Promise.all(f.map(d=>this.walkDirectoryMultiGlobstar(d,n,r)))}}}catch(i){if(i instanceof P)throw i}}async walkDirectory(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let i=await this.fs.readdirWithFileTypes(s),a=[],o=[];for(let l of i){let u=t==="."?l.name:`${t}/${l.name}`;l.isDirectory?o.push(u):n&&this.matchPattern(l.name,n)&&a.push(u)}r.push(...a);for(let l=0;l<o.length;l+=100){let u=o.slice(l,l+100);await Promise.all(u.map(c=>this.walkDirectory(c,n,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(s),a=[];for(let l=0;l<i.length;l+=100){let u=i.slice(l,l+100),c=await Promise.all(u.map(async f=>{let d=t==="."?f:`${t}/${f}`,p=this.fs.resolvePath(this.cwd,d);try{this.checkOpsLimit();let h=await this.fs.stat(p);return{name:f,path:d,isDirectory:h.isDirectory}}catch(h){if(h instanceof P)throw h;return null}}));a.push(...c.filter(f=>f!==null))}for(let l of a)!l.isDirectory&&n&&this.matchPattern(l.name,n)&&r.push(l.path);let o=a.filter(l=>l.isDirectory);for(let l=0;l<o.length;l+=100){let u=o.slice(l,l+100);await Promise.all(u.map(c=>this.walkDirectory(c.path,n,r)))}}}catch(i){if(i instanceof P)throw i}}matchPattern(t,n){return this.patternToRegex(n).test(t)}patternToRegex(t){let n=this.patternToRegexStr(t);return me(`^${n}$`)}patternToRegexStr(t){let n="",r=!1;for(let s=0;s<t.length;s++){if(t.slice(s,s+13)==="\0QUOTE_START\0"){r=!0,s+=12;continue}if(t.slice(s,s+11)==="\0QUOTE_END\0"){r=!1,s+=10;continue}let i=t[s];if(r){/[.+^${}()|\\*?[\]]/.test(i)?n+=`\\${i}`:n+=i;continue}if(this.extglob&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<t.length&&t[s+1]==="("){let a=Mi(t,s+1);if(a!==-1){let o=t.slice(s+2,a),l=Bi(o),u=l.map(f=>this.patternToRegexStr(f)),c=u.length>0?u.join("|"):"(?:)";if(i==="@")n+=`(?:${c})`;else if(i==="*")n+=`(?:${c})*`;else if(i==="+")n+=`(?:${c})+`;else if(i==="?")n+=`(?:${c})?`;else if(i==="!")if(a<t.length-1){let d=l.map(h=>this.computePatternLength(h));if(d.every(h=>h!==null)&&d.every(h=>h===d[0])&&d[0]!==null){let h=d[0];if(h===0)n+="(?:.+)";else{let m=[];h>0&&m.push(`.{0,${h-1}}`),m.push(`.{${h+1},}`),m.push(`(?!(?:${c})).{${h}}`),n+=`(?:${m.join("|")})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;s=a;continue}}if(i==="*")n+=".*";else if(i==="?")n+=".";else if(i==="["){let a=s+1,o="[";a<t.length&&(t[a]==="^"||t[a]==="!")&&(o+="^",a++),a<t.length&&t[a]==="]"&&(o+="\\]",a++);let l=a;for(;l<t.length;){if(t[l]==="\\"&&l+1<t.length){l+=2;continue}if(t[l]==="["&&l+1<t.length&&t[l+1]===":"){let c=t.indexOf(":]",l+2);if(c!==-1){l=c+2;continue}}if(t[l]==="]")break;l++}let u=a;for(;a<t.length&&t[a]!=="]";){if(t[a]==="["&&a+1<t.length&&t[a+1]===":"){let c=t.indexOf(":]",a+2);if(c!==-1){let f=t.slice(a+2,c),d=Fi(f);o+=d,a=c+2;continue}}if(t[a]==="\\"&&a+1<t.length){o+=`\\${t[a+1]}`,a+=2;continue}if(t[a]==="-"){let c=a===u,f=a+1===l;c||f?o+="\\-":o+="-"}else o+=t[a];a++}o+="]",n+=o,s=a}else if(i==="\\"&&s+1<t.length){let a=t[s+1];/[.+^${}()|\\*?[\]]/.test(a)?n+=`\\${a}`:n+=a,s++}else/[.+^${}()|]/.test(i)?n+=`\\${i}`:n+=i}return n}computePatternLength(t){let n=0,r=0,s=!1;for(;r<t.length;){if(t.slice(r,r+13)==="\0QUOTE_START\0"){s=!0,r+=13;continue}if(t.slice(r,r+11)==="\0QUOTE_END\0"){s=!1,r+=11;continue}let i=t[r];if(s){n+=1,r++;continue}if((i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&r+1<t.length&&t[r+1]==="("){let a=Mi(t,r+1);if(a!==-1){if(i==="@"){let o=t.slice(r+2,a),u=Bi(o).map(c=>this.computePatternLength(c));if(u.every(c=>c!==null)&&u.every(c=>c===u[0])){n+=u[0],r=a+1;continue}return null}return null}}if(i==="*")return null;if(i==="?"){n+=1,r++;continue}if(i==="["){let a=t.indexOf("]",r+1);if(a!==-1){n+=1,r=a+1;continue}n+=1,r++;continue}if(i==="\\"){n+=1,r+=2;continue}n+=1,r++}return n}};function Wi(e){for(let t=0;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==="$"){let n=e[t+1];if(n==="{"||n&&/[a-zA-Z_]/.test(n))return!0}}return!1}function $p(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n)return!1;for(let r of n)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Zl(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n||n.length===0)return!1;for(let r of n)if(r.type!=="DoubleQuoted"&&r.type!=="SingleQuoted")return!1;return!0}function fr(e){let t=!1,n=!1,r=!1,s=!1,i=!1,a=!1,o=!1;for(let l of e){if((l.type==="SingleQuoted"||l.type==="DoubleQuoted")&&(t=!0,l.type==="DoubleQuoted"))for(let u of l.parts)u.type==="ParameterExpansion"&&(u.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&(!u.operation||u.operation.type==="PatternRemoval"||u.operation.type==="PatternReplacement")&&(s=!0),(u.operation?.type==="VarNamePrefix"||u.operation?.type==="ArrayKeys")&&(a=!0),u.operation?.type==="Indirection"&&(o=!0));l.type==="CommandSubstitution"&&(n=!0),l.type==="ParameterExpansion"&&(i=!0,(l.parameter==="@"||l.parameter==="*")&&(r=!0),$p(l)&&(t=!0),(l.operation?.type==="VarNamePrefix"||l.operation?.type==="ArrayKeys")&&(a=!0),l.operation?.type==="Indirection"&&(o=!0)),l.type==="Glob"&&Wi(l.pattern)&&(i=!0)}return{hasQuoted:t,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:i,hasVarNamePrefixExpansion:a,hasIndirection:o}}var Pp=`
|
|
95
|
+
`;function kn(e,t){if(e>=t)throw new P(`array element limit exceeded (${t})`,"array_elements")}function Vi(e,t,n,r,s){kn(e.length,s),kn(t.length,s),e.push(n),t.push(r)}function ve(e){return e.get("IFS")??Pp}function De(e){return e.get("IFS")===""}function ts(e){let t=ve(e);if(t==="")return!0;for(let n of t)if(n!==" "&&n!==" "&&n!==`
|
|
96
|
+
`)return!1;return!0}function Ql(e){let t=!1,n=[];for(let r of e.split(""))r==="-"?t=!0:/[\\^$.*+?()[\]{}|]/.test(r)?n.push(`\\${r}`):r===" "?n.push("\\t"):r===`
|
|
97
|
+
`?n.push("\\n"):n.push(r);return t&&n.push("\\-"),n.join("")}function Q(e){let t=e.get("IFS");return t===void 0?" ":t[0]||""}var Cp=`
|
|
98
|
+
`;function Np(e){return Cp.includes(e)}function zi(e){let t=new Set,n=new Set;for(let r of e)Np(r)?t.add(r):n.add(r);return{whitespace:t,nonWhitespace:n}}function Ui(e,t,n,r,s){if(t==="")return e===""?{words:[],wordStarts:[]}:(kn(0,n),{words:[e],wordStarts:[0]});let{whitespace:i,nonWhitespace:a}=zi(t),o=[],l=[],u=0;for(;u<e.length&&i.has(e[u]);)u++;if(u>=e.length)return{words:[],wordStarts:[]};if(a.has(e[u]))for(Vi(o,l,"",u,n),u++;u<e.length&&i.has(e[u]);)u++;for(;u<e.length&&!(r!==void 0&&o.length>=r);){let c=u;for(;u<e.length;){let f=e[u];if(!s&&f==="\\"){u++,u<e.length&&u++;continue}if(i.has(f)||a.has(f))break;u++}if(Vi(o,l,e.substring(c,u),c,n),u>=e.length)break;for(;u<e.length&&i.has(e[u]);)u++;if(u<e.length&&a.has(e[u])){for(u++;u<e.length&&i.has(e[u]);)u++;for(;u<e.length&&a.has(e[u])&&!(r!==void 0&&o.length>=r);)for(Vi(o,l,"",u,n),u++;u<e.length&&i.has(e[u]);)u++}}return{words:o,wordStarts:l}}function ns(e,t,n){if(t==="")return e&&kn(0,n),{words:e?[e]:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};if(e==="")return{words:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};let{whitespace:r,nonWhitespace:s}=zi(t),i=[],a=0,o=!1,l=!1,u=a;for(;a<e.length&&r.has(e[a]);)a++;if(a>u&&(o=!0),a>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(s.has(e[a]))for(kn(i.length,n),i.push(""),a++;a<e.length&&r.has(e[a]);)a++;for(;a<e.length;){let c=a;for(;a<e.length;){let d=e[a];if(r.has(d)||s.has(d))break;a++}if(kn(i.length,n),i.push(e.substring(c,a)),a>=e.length){l=!1;break}let f=a;for(;a<e.length&&r.has(e[a]);)a++;if(a<e.length&&s.has(e[a])){for(a++;a<e.length&&r.has(e[a]);)a++;for(;a<e.length&&s.has(e[a]);)for(kn(i.length,n),i.push(""),a++;a<e.length&&r.has(e[a]);)a++}a>=e.length&&a>f&&(l=!0)}return{words:i,hadLeadingDelimiter:o,hadTrailingDelimiter:l}}function fe(e,t,n){return ns(e,t,n).words}function Rp(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Kl(e,t,n){if(t==="")return e;let{whitespace:r,nonWhitespace:s}=zi(t),i=e.length;for(;i>0&&r.has(e[i-1]);){if(!n&&i>=2){let o=0,l=i-2;for(;l>=0&&e[l]==="\\";)o++,l--;if(o%2===1)break}i--}let a=e.substring(0,i);if(a.length>=1&&s.has(a[a.length-1])){if(!n&&a.length>=2){let l=0,u=a.length-2;for(;u>=0&&a[u]==="\\";)l++,u--;if(l%2===1)return a}let o=a.substring(0,a.length-1);if(!Rp(o,s))return o}return a}function ue(e,t){return e.state.namerefs?.has(t)??!1}function Mt(e,t){e.state.namerefs??=new Set,e.state.namerefs.add(t)}function Xl(e,t){e.state.namerefs?.delete(t),e.state.boundNamerefs?.delete(t),e.state.invalidNamerefs?.delete(t)}function Yl(e,t){e.state.invalidNamerefs??=new Set,e.state.invalidNamerefs.add(t)}function Jl(e,t){return e.state.invalidNamerefs?.has(t)??!1}function qi(e,t){e.state.boundNamerefs??=new Set,e.state.boundNamerefs.add(t)}function rs(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let s=n[1],i=Ne(e,s),a=e.state.associativeArrays?.has(s)??!1;return i||a}return Ne(e,t)?!0:e.state.env.has(t)}function Be(e,t,n=100){if(!ue(e,t)||Jl(e,t))return t;let r=new Set,s=t;for(;n-- >0;){if(r.has(s))return;if(r.add(s),!ue(e,s))return s;let i=e.state.env.get(s);if(i===void 0||i===""||!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(i))return s;s=i}}function xn(e,t){if(ue(e,t))return e.state.env.get(t)}function ss(e,t,n,r=100){if(!ue(e,t)||Jl(e,t))return t;let s=new Set,i=t;for(;r-- >0;){if(s.has(i))return;if(s.add(i),!ue(e,i))return i;let a=e.state.env.get(i);if(a===void 0||a==="")return n!==void 0?/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&rs(e,n)?i:null:i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(a))return i;i=a}}function eu(e,t){let n=t.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g,(r,s)=>e.state.env.get(s)??"");return n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>e.state.env.get(s)??""),n}function G(e,t){return t==="FUNCNAME"?(e.state.funcNameStack??[]).map((i,a)=>[a,i]):t==="BASH_LINENO"?(e.state.callLineStack??[]).map((i,a)=>[a,String(i)]):t==="BASH_SOURCE"?(e.state.sourceStack??[]).map((i,a)=>[a,i]):e.state.associativeArrays?.has(t)?Pt(e,t).map(i=>[i,oe(e,t,i)??""]):Se(e,t).map(s=>[s,oe(e,t,s)??""])}function yt(e,t){return t==="FUNCNAME"?(e.state.funcNameStack?.length??0)>0:t==="BASH_LINENO"?(e.state.callLineStack?.length??0)>0:t==="BASH_SOURCE"?(e.state.sourceStack?.length??0)>0:e.state.associativeArrays?.has(t)?Ne(e,t):Ne(e,t)}async function ae(e,t,n=!0,r=!1){switch(t){case"?":return String(e.state.lastExitCode);case"$":return String(e.state.virtualPid);case"#":return e.state.env.get("#")||"0";case"@":return e.state.env.get("@")||"";case"_":return e.state.lastArg;case"-":{let a="";return a+="h",e.state.options.errexit&&(a+="e"),e.state.options.noglob&&(a+="f"),e.state.options.nounset&&(a+="u"),e.state.options.verbose&&(a+="v"),e.state.options.xtrace&&(a+="x"),a+="B",e.state.options.noclobber&&(a+="C"),a+="s",a}case"*":{let a=Number.parseInt(e.state.env.get("#")||"0",10);if(a===0)return"";let o=[];for(let l=1;l<=a;l++)o.push(e.state.env.get(String(l))||"");return o.join(Q(e.state.env))}case"0":return e.state.env.get("0")||"bash";case"PWD":return e.state.env.get("PWD")??"";case"OLDPWD":return e.state.env.get("OLDPWD")??"";case"PPID":return String(e.state.virtualPpid);case"UID":return String(e.state.virtualUid);case"EUID":return String(e.state.virtualUid);case"RANDOM":return String(Math.floor(Math.random()*32768));case"SECONDS":return String(Math.floor((Date.now()-e.state.startTime)/1e3));case"BASH_VERSION":return Wo;case"!":return String(e.state.lastBackgroundPid);case"BASHPID":return String(e.state.bashPid);case"LINENO":return String(e.state.currentLine);case"FUNCNAME":{let a=e.state.funcNameStack?.[0];if(a!==void 0)return a;if(n&&e.state.options.nounset)throw new Ue("FUNCNAME");return""}case"BASH_LINENO":{let a=e.state.callLineStack?.[0];if(a!==void 0)return String(a);if(n&&e.state.options.nounset)throw new Ue("BASH_LINENO");return""}case"BASH_SOURCE":{let a=e.state.sourceStack?.[0];if(a!==void 0)return a;if(n&&e.state.options.nounset)throw new Ue("BASH_SOURCE");return""}}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(t))throw new Xe(`\${${t}}`);let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=s[1],o=s[2];if(ue(e,a)){let f=Be(e,a);if(f&&f!==a){if(f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return"";a=f}}if(o==="@"||o==="*"){let f=G(e,a);if(f.length>0)return f.map(([,p])=>p).join(" ");let d=e.state.env.get(a);return d!==void 0?d:""}if(a==="FUNCNAME"){let f=Number.parseInt(o,10);return!Number.isNaN(f)&&f>=0?e.state.funcNameStack?.[f]??"":""}if(a==="BASH_LINENO"){let f=Number.parseInt(o,10);if(!Number.isNaN(f)&&f>=0){let d=e.state.callLineStack?.[f];return d!==void 0?String(d):""}return""}if(a==="BASH_SOURCE"){let f=Number.parseInt(o,10);return!Number.isNaN(f)&&f>=0?e.state.sourceStack?.[f]??"":""}if(e.state.associativeArrays?.has(a)){let f=jr(o);f=eu(e,f);let d=oe(e,a,f);if(d===void 0&&n&&e.state.options.nounset)throw new Ue(`${a}[${o}]`);return d||""}let u;if(/^-?\d+$/.test(o))u=Number.parseInt(o,10);else try{let f=new H,d=se(f,o);u=await Y(e,d.expression)}catch{let f=e.state.env.get(o);u=f?Number.parseInt(f,10):0,Number.isNaN(u)&&(u=0)}if(u<0){let f=G(e,a),d=e.state.currentLine;if(f.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${a}: bad array subscript
|
|
99
|
+
`,"";let h=Math.max(...f.map(([E])=>typeof E=="number"?E:0))+1+u;return h<0?(e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${a}: bad array subscript
|
|
100
|
+
`,""):oe(e,a,h)||""}let c=oe(e,a,u);if(c!==void 0)return c;if(u===0){let f=e.state.env.get(a);if(f!==void 0)return f}if(n&&e.state.options.nounset)throw new Ue(`${a}[${u}]`);return""}if(/^[1-9][0-9]*$/.test(t)){let a=e.state.env.get(t);if(a===void 0&&n&&e.state.options.nounset)throw new Ue(t);return a||""}if(ue(e,t)){let a=Be(e,t);if(a===void 0)return"";if(a!==t)return await ae(e,a,n,r);let o=e.state.env.get(t);if((o===void 0||o==="")&&n&&e.state.options.nounset)throw new Ue(t);return o||""}let i=e.state.env.get(t);if(i!==void 0)return e.state.tempEnvBindings?.some(a=>a.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),i;if(yt(e,t)){let a=oe(e,t,0);if(a!==void 0)return a;if(n&&e.state.options.nounset)throw new Ue(t);return""}if(n&&e.state.options.nounset)throw new Ue(t);return""}async function Nt(e,t){if(new Set(["?","$","#","_","-","0","PPID","UID","EUID","RANDOM","SECONDS","BASH_VERSION","!","BASHPID","LINENO"]).has(t))return!0;if(t==="@"||t==="*")return Number.parseInt(e.state.env.get("#")||"0",10)>0;if(t==="PWD"||t==="OLDPWD")return e.state.env.has(t);let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let s=r[1],i=r[2];if(ue(e,s)){let l=Be(e,s);if(l&&l!==s){if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;s=l}}if(i==="@"||i==="*")return G(e,s).length>0?!0:e.state.env.has(s);if(e.state.associativeArrays?.has(s)){let l=eu(e,jr(i));return Kt(e,s,l)}let o;if(/^-?\d+$/.test(i))o=Number.parseInt(i,10);else try{let l=new H,u=se(l,i);o=await Y(e,u.expression)}catch{let l=e.state.env.get(i);o=l?Number.parseInt(l,10):0,Number.isNaN(o)&&(o=0)}if(o<0){let l=G(e,s);if(l.length===0)return!1;let c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+o;return c<0?!1:Kt(e,s,c)}return Kt(e,s,o)}if(ue(e,t)){let s=Be(e,t);return s===void 0||s===t?e.state.env.has(t):Nt(e,s)}return e.state.env.has(t)?!0:yt(e,t)?Kt(e,t,0):!1}async function tu(e,t){let n="",r=0;for(;r<t.length;){if(t[r]==="$"){if(t[r+1]==="{"){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="{"?s++:t[i]==="}"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(t[r+1]==="("){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="("?s++:t[i]===")"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),a=await ae(e,i);n+=a,r=s;continue}if(/[0-9]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[0-9]/.test(t[s]);)s++;let i=t.slice(r+1,s),a=await ae(e,i);n+=a,r=s;continue}if(/[*@#?\-!$]/.test(t[r+1]||"")){let s=t[r+1],i=await ae(e,s);n+=i,r+=2;continue}}if(t[r]==='"'){for(n+='"',r++;r<t.length&&t[r]!=='"';)if(t[r]==="$"&&/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),a=await ae(e,i);n+=a,r=s}else t[r]==="\\"?(n+=t[r],r++,r<t.length&&(n+=t[r],r++)):(n+=t[r],r++);r<t.length&&(n+='"',r++);continue}n+=t[r],r++}return n}async function ji(e,t){let n=t,r=t.startsWith('"')&&t.endsWith('"'),s=t.startsWith("'")&&t.endsWith("'");if((r||s)&&(n=t.slice(1,-1)),s)return n;let i="",a=0;for(;a<n.length;)if(n[a]==="$")if(n[a+1]==="("){let o=1,l=a+2;for(;l<n.length&&o>0;)n[l]==="("&&n[l-1]==="$"||n[l]==="("?o++:n[l]===")"&&o--,l++;let u=n.slice(a+2,l-1);if(e.execFn){let c=await e.execFn(u,{signal:e.state.signal});i+=c.stdout.replace(/\n+$/,""),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr)}a=l}else if(n[a+1]==="{"){let o=1,l=a+2;for(;l<n.length&&o>0;)n[l]==="{"?o++:n[l]==="}"&&o--,l++;let u=n.slice(a+2,l-1),c=await ae(e,u);i+=c,a=l}else if(/[a-zA-Z_]/.test(n[a+1]||"")){let o=a+1;for(;o<n.length&&/[a-zA-Z0-9_]/.test(n[o]);)o++;let l=n.slice(a+1,o),u=await ae(e,l);i+=u,a=o}else i+=n[a],a++;else if(n[a]==="`"){let o=a+1;for(;o<n.length&&n[o]!=="`";)o++;let l=n.slice(a+1,o);if(e.execFn){let u=await e.execFn(l,{signal:e.state.signal});i+=u.stdout.replace(/\n+$/,""),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.stderr)}a=o+1}else i+=n[a],a++;return i}var dr=1e4,Hi={maxResults:dr,maxStringBytes:10*1024*1024};function is(e,t,n,r){if(e.length>=n.maxResults)return!1;let s=B(t);if(s>n.maxStringBytes-r.value)throw new P(`brace expansion string limit exceeded (${n.maxStringBytes} bytes)`,"string_length");return e.push(t),r.value+=s,!0}function Dp(e,t,n,r,s,i=Hi){let a=n??1;a===0&&(a=1);let o=Math.abs(a),l=[],u=0;if(r?.match(/^-?0\d/)&&(u=Math.max(u,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(u=Math.max(u,s.replace(/^-/,"").length)),u>i.maxStringBytes)throw new P(`brace expansion padding limit exceeded (${i.maxStringBytes} bytes)`,"string_length");let c={value:0},f=d=>{if(u>0){let p=d<0,h=String(Math.abs(d)).padStart(u,"0");return p?`-${h}`:h}return String(d)};if(e<=t)for(let d=e,p=0;d<=t&&p<dr&&is(l,f(d),i,c);d+=o,p++);else for(let d=e,p=0;d>=t&&p<dr&&is(l,f(d),i,c);d-=o,p++);return l}function Ip(e,t,n,r=Hi){let s=n??1;s===0&&(s=1);let i=e.charCodeAt(0),a=t.charCodeAt(0),o=Math.abs(s),l=e>="A"&&e<="Z",u=e>="a"&&e<="z",c=t>="A"&&t<="Z",f=t>="a"&&t<="z";if(l&&f||u&&c){let h=n!==void 0?`..${n}`:"";throw new _r(`{${e}..${t}${h}}: invalid sequence`)}let d=[],p={value:0};if(i<=a)for(let h=i,m=0;h<=a&&m<dr&&is(d,String.fromCharCode(h),r,p);h+=o,m++);else for(let h=i,m=0;h>=a&&m<dr&&is(d,String.fromCharCode(h),r,p);h-=o,m++);return d}function Gi(e,t,n,r,s,i=Hi){let a=n!==void 0?`..${n}`:"";return typeof e=="number"&&typeof t=="number"?{expanded:Dp(e,t,n,r,s,i),literal:`{${e}..${t}${a}}`}:typeof e=="string"&&typeof t=="string"?{expanded:Ip(e,t,n,i),literal:`{${e}..${t}${a}}`}:{expanded:null,literal:`{${e}..${t}${a}}`}}function nu(e){if(e.statements.length!==1)return null;let t=e.statements[0];if(t.operators.length!==0||t.pipelines.length!==1)return null;let n=t.pipelines[0];if(n.negated||n.commands.length!==1)return null;let r=n.commands[0];if(r.type!=="SimpleCommand")return null;let s=r;if(s.name!==null||s.args.length!==0||s.assignments.length!==0||s.redirections.length!==1)return null;let i=s.redirections[0];return i.operator!=="<"||i.target.type!=="Word"?null:{target:i.target}}function Rt(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\(/.test(e))}function Zi(e){let t="",n=0;for(;n<e.length;)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);return t}function et(e){return e.replace(/([*?[\]\\()|])/g,"\\$1")}function Bn(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}function te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(e,t,n=!1){let r="",s=0;for(;s<e.length;){let i=e[s];if(n&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<e.length&&e[s+1]==="("){let a=Op(e,s+1);if(a!==-1){let o=e.slice(s+2,a),u=_p(o).map(f=>J(f,t,n)),c=u.length>0?u.join("|"):"(?:)";i==="@"?r+=`(?:${c})`:i==="*"?r+=`(?:${c})*`:i==="+"?r+=`(?:${c})+`:i==="?"?r+=`(?:${c})?`:i==="!"&&(r+=`(?!(?:${c})$).*`),s=a+1;continue}}if(i==="\\")if(s+1<e.length){let a=e[s+1];/[\\^$.|+(){}[\]*?]/.test(a)?r+=`\\${a}`:r+=a,s+=2}else r+="\\\\",s++;else if(i==="*")r+=t?".*":".*?",s++;else if(i==="?")r+=".",s++;else if(i==="["){let a=Lp(e,s);if(a===-1)r+="\\[",s++;else{let o=e.slice(s+1,a);r+=Tp(o),s=a+1}}else/[\^$.|+(){}]/.test(i)?(r+=`\\${i}`,s++):(r+=i,s++)}return r}function Op(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function _p(e){let t=[],n="",r=0,s=0;for(;s<e.length;){let i=e[s];if(i==="\\"){n+=i,s+1<e.length?(n+=e[s+1],s+=2):s++;continue}i==="("?(r++,n+=i):i===")"?(r--,n+=i):i==="|"&&r===0?(t.push(n),n=""):n+=i,s++}return t.push(n),t}function Lp(e,t){let n=t+1;for(n<e.length&&e[n]==="^"&&n++,n<e.length&&e[n]==="]"&&n++;n<e.length;){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==="]")return n;if(e[n]==="'"){let r=e.indexOf("'",n+1);if(r!==-1){n=r+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let r=e.indexOf(":]",n+2);if(r!==-1){n=r+2;continue}}n++}return-1}function Tp(e){let t="[",n=0;for((e[0]==="^"||e[0]==="!")&&(t+="^",n++);n<e.length;){if(e[n]==="'"){let s=e.indexOf("'",n+1);if(s!==-1){let i=e.slice(n+1,s);for(let a of i)a==="\\"?t+="\\\\":a==="]"?t+="\\]":a==="^"&&t==="["?t+="\\^":t+=a;n=s+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let s=e.indexOf(":]",n+2);if(s!==-1){let i=e.slice(n+2,s);t+=Mp(i),n=s+2;continue}}let r=e[n];r==="\\"?n+1<e.length?(t+=`\\${e[n+1]}`,n+=2):(t+="\\\\",n++):r==="-"&&n>0&&n<e.length-1?(t+="-",n++):r==="^"&&n===0?(t+="^",n++):(r==="]"&&n===0?t+="\\]":t+=r,n++)}return t+="]",t}var Fp=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]);function Mp(e){return Fp.get(e)??""}function gt(e,t,n,r,s){if(r==="prefix")return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),me(`^${n}`,"s").replace(t,"");let i=me(`${n}$`,"s");if(s)return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),i.replace(t,"");e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal");let a=me(`^(?:.*)(${n})$`,"s").exec(t);if(!a)return t;let o=a[1]??"";return t.slice(0,t.length-o.length)}function Wn(e,t){let n=new Set;for(let r of e.state.env.keys())r.startsWith(t)&&n.add(r);for(let r of e.state.arrays?.keys()??[])r.startsWith(t)&&n.add(r);return[...n].sort()}function as(e,t,n,r,s){let i=new Nn(e.limits.maxStringLength,"pattern replacement",()=>new P(`pattern replacement: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length"));n.lastIndex=0;let a=0,o=n.exec(t);for(;o!==null&&(e.executionScope.consumeLimited("pattern_operations",1,e.limits.maxGlobOperations,"pattern replacement"),!(s&&o[0].length===0&&o.index===t.length||(i.append(t.slice(a,o.index)),i.append(r),a=o.index+o[0].length,!s)));)o[0].length===0&&(a++,n.lastIndex<=o.index&&(n.lastIndex=o.index+1)),o=n.exec(t);return i.append(t.slice(a)),n.lastIndex=0,i.build()}function ru(e){let t=[],n=0;return{append(r){let s=B(r);if(s>e-n)throw new P(`prompt expansion exceeds string length limit (${e} bytes)`,"string_length");r&&t.push(r),n+=s},build:()=>t.join("")}}function Bp(e,t,n){let r=(a,o=2)=>String(a).padStart(o,"0");if(e===""){let a=r(t.getHours()),o=r(t.getMinutes()),l=r(t.getSeconds());return`${a}:${o}:${l}`}let s=ru(n),i=0;for(;i<e.length;)if(e[i]==="%"){if(i+1>=e.length){s.append("%"),i++;continue}let a=e[i+1];switch(a){case"H":s.append(r(t.getHours()));break;case"M":s.append(r(t.getMinutes()));break;case"S":s.append(r(t.getSeconds()));break;case"d":s.append(r(t.getDate()));break;case"m":s.append(r(t.getMonth()+1));break;case"Y":s.append(String(t.getFullYear()));break;case"y":s.append(r(t.getFullYear()%100));break;case"I":{let o=t.getHours()%12;o===0&&(o=12),s.append(r(o));break}case"p":s.append(t.getHours()<12?"AM":"PM");break;case"P":s.append(t.getHours()<12?"am":"pm");break;case"%":s.append("%");break;case"a":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];s.append(o[t.getDay()]);break}case"b":{let o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];s.append(o[t.getMonth()]);break}default:s.append(`%${a}`)}i+=2}else s.append(e[i]),i++;return s.build()}function pr(e,t){let n=ru(e.limits.maxStringLength),r=0,s=e.state.env.get("USER")||e.state.env.get("LOGNAME")||"user",i=e.state.env.get("HOSTNAME")||"localhost",a=i.split(".")[0],o=e.state.env.get("PWD")||"/",l=e.state.env.get("HOME")||"/",u=o.startsWith(l)?`~${o.slice(l.length)}`:o,c=o.split("/").pop()||o,f=new Date,d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=e.state.env.get("__COMMAND_NUMBER")||"1";for(;r<t.length;){let m=t[r];if(m==="\\"){if(r+1>=t.length){n.append("\\"),r++;continue}let E=t[r+1];if(E>="0"&&E<="7"){let S="",g=r+1;for(;g<t.length&&g<r+4&&t[g]>="0"&&t[g]<="7";)S+=t[g],g++;let y=Number.parseInt(S,8)%256;n.append(String.fromCharCode(y)),r=g;continue}switch(E){case"\\":n.append("\\"),r+=2;break;case"a":n.append("\x07"),r+=2;break;case"e":n.append("\x1B"),r+=2;break;case"n":n.append(`
|
|
101
|
+
`),r+=2;break;case"r":n.append("\r"),r+=2;break;case"$":n.append("$"),r+=2;break;case"[":case"]":r+=2;break;case"u":n.append(s),r+=2;break;case"h":n.append(a),r+=2;break;case"H":n.append(i),r+=2;break;case"w":n.append(u),r+=2;break;case"W":n.append(c),r+=2;break;case"d":{let S=String(f.getDate()).padStart(2," ");n.append(`${d[f.getDay()]} ${p[f.getMonth()]} ${S}`),r+=2;break}case"t":{let S=String(f.getHours()).padStart(2,"0"),g=String(f.getMinutes()).padStart(2,"0"),y=String(f.getSeconds()).padStart(2,"0");n.append(`${S}:${g}:${y}`),r+=2;break}case"T":{let S=f.getHours()%12;S===0&&(S=12);let g=String(S).padStart(2,"0"),y=String(f.getMinutes()).padStart(2,"0"),b=String(f.getSeconds()).padStart(2,"0");n.append(`${g}:${y}:${b}`),r+=2;break}case"@":{let S=f.getHours()%12;S===0&&(S=12);let g=String(S).padStart(2,"0"),y=String(f.getMinutes()).padStart(2,"0"),b=f.getHours()<12?"AM":"PM";n.append(`${g}:${y} ${b}`),r+=2;break}case"A":{let S=String(f.getHours()).padStart(2,"0"),g=String(f.getMinutes()).padStart(2,"0");n.append(`${S}:${g}`),r+=2;break}case"D":if(r+2<t.length&&t[r+2]==="{"){let S=t.indexOf("}",r+3);if(S!==-1){let g=t.slice(r+3,S);n.append(Bp(g,f,e.limits.maxStringLength)),r=S+1}else n.append("\\D"),r+=2}else n.append("\\D"),r+=2;break;case"s":n.append("bash"),r+=2;break;case"v":n.append("5.0"),r+=2;break;case"V":n.append("5.0.0"),r+=2;break;case"j":n.append("0"),r+=2;break;case"l":n.append("tty"),r+=2;break;case"#":n.append(h),r+=2;break;case"!":n.append(h),r+=2;break;case"x":n.append("\\x"),r+=2;break;default:n.append(`\\${E}`),r+=2}}else n.append(m),r++}return n.build()}function en(e){if(e==="")return"''";if(/[\n\r\t\x00-\x1f\x7f']/.test(e)){let n="$'";for(let r of e)switch(r){case"'":n+="\\'";break;case"\\":n+="\\\\";break;case`
|
|
102
|
+
`:n+="\\n";break;case"\r":n+="\\r";break;case" ":n+="\\t";break;default:{let s=r.charCodeAt(0);s<32||s===127?n+=`\\${s.toString(8).padStart(3,"0")}`:n+=r}}return`${n}'`}return`'${e}'`}function Ge(e,t){e.state.readonlyVars=e.state.readonlyVars||new Set,e.state.readonlyVars.add(t)}function We(e,t){return e.state.readonlyVars?.has(t)??!1}function ce(e,t,n="bash"){if(We(e,t)){let r=`${n}: ${t}: readonly variable
|
|
103
|
+
`;throw new q(1,"",r)}return null}function wt(e,t){let n=e.state.exportedVars?.has(t)??!1;if(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t),e.state.localScopes.length>0&&e.state.localScopes[e.state.localScopes.length-1].has(t)&&!n){for(e.state.localExportedVars||(e.state.localExportedVars=[]);e.state.localExportedVars.length<e.state.localScopes.length;)e.state.localExportedVars.push(new Set);e.state.localExportedVars[e.state.localExportedVars.length-1].add(t)}}function os(e,t){e.state.exportedVars?.delete(t)}function tn(e,t){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))return"";let n="",r=ke(e,t)?.kind==="indexed",s=e.state.associativeArrays?.has(t)??!1;return r&&!s&&(n+="a"),s&&(n+="A"),e.state.integerVars?.has(t)&&(n+="i"),ue(e,t)&&(n+="n"),We(e,t)&&(n+="r"),e.state.exportedVars?.has(t)&&(n+="x"),n}async function su(e,t,n,r){return e.coverage?.hit("bash:expansion:default_value"),(n.isUnset||t.checkEmpty&&n.isEmpty)&&t.word?r(e,t.word.parts,n.inDoubleQuotes):n.effectiveValue}async function iu(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:assign_default"),(r.isUnset||n.checkEmpty&&r.isEmpty)&&n.word){let a=await s(e,n.word.parts,r.inDoubleQuotes),o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let[,l,u]=o,c;if(/^\d+$/.test(u))c=Number.parseInt(u,10);else{try{let f=new H,d=se(f,u);c=await Y(e,d.expression)}catch{let f=e.state.env.get(u);c=f?Number.parseInt(f,10):0}Number.isNaN(c)&&(c=0)}j(e,l,c,a)}else e.state.env.set(t,a);return a}return r.effectiveValue}async function au(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:error_if_unset"),r.isUnset||n.checkEmpty&&r.isEmpty){let a=n.word?await s(e,n.word.parts,r.inDoubleQuotes):`${t}: parameter null or not set`;throw new q(1,"",`bash: ${a}
|
|
104
|
+
`)}return r.effectiveValue}async function ou(e,t,n,r){return e.coverage?.hit("bash:expansion:use_alternative"),!(n.isUnset||t.checkEmpty&&n.isEmpty)&&t.word?r(e,t.word.parts,n.inDoubleQuotes):""}async function lu(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_removal");let i="",a=e.state.shoptOptions.extglob;if(n.pattern)for(let o of n.pattern.parts)if(o.type==="Glob")i+=J(o.pattern,n.greedy,a);else if(o.type==="Literal")i+=J(o.value,n.greedy,a);else if(o.type==="SingleQuoted"||o.type==="Escaped")i+=te(o.value);else if(o.type==="DoubleQuoted"){let l=await r(e,o.parts);i+=te(l)}else if(o.type==="ParameterExpansion"){let l=await s(e,o);i+=J(l,n.greedy,a)}else{let l=await s(e,o);i+=te(l)}return gt(e,t,i,n.side,n.greedy)}async function uu(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_replacement");let i="",a=e.state.shoptOptions.extglob;if(n.pattern)for(let u of n.pattern.parts)if(u.type==="Glob")i+=J(u.pattern,!0,a);else if(u.type==="Literal")i+=J(u.value,!0,a);else if(u.type==="SingleQuoted"||u.type==="Escaped")i+=te(u.value);else if(u.type==="DoubleQuoted"){let c=await r(e,u.parts);i+=te(c)}else if(u.type==="ParameterExpansion"){let c=await s(e,u);i+=J(c,!0,a)}else{let c=await s(e,u);i+=te(c)}let o=n.replacement?await r(e,n.replacement.parts):"";if(n.anchor==="start"?i=`^${i}`:n.anchor==="end"&&(i=`${i}$`),i==="")return t;let l=n.all?"gs":"s";try{let u=me(i,l);return as(e,t,u,o,n.all)}catch(u){if(u instanceof P)throw u;return t}}function cu(e,t,n){e.coverage?.hit("bash:expansion:length");let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(r){let s=r[1],i=G(e,s);return i.length>0?String(i.length):e.state.env.get(s)!==void 0?"1":"0"}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&yt(e,t)){if(t==="FUNCNAME"){let i=e.state.funcNameStack?.[0]||"";return String([...i].length)}if(t==="BASH_LINENO"){let i=e.state.callLineStack?.[0];return String(i!==void 0?[...String(i)].length:0)}let s=oe(e,t,0)||"";return String([...s].length)}return String([...n].length)}async function fu(e,t,n,r){e.coverage?.hit("bash:expansion:substring");let s=await Y(e,r.offset.expression),i=r.length?await Y(e,r.length.expression):void 0;if(t==="@"||t==="*"){let u=Number.parseInt(e.state.env.get("#")||"0",10),c=[];for(let h=1;h<=u;h++)c.push(e.state.env.get(String(h))||"");let f=e.state.env.get("0")||"bash",d,p;if(s<=0)if(d=[f,...c],s<0){if(p=d.length+s,p<0)return""}else p=0;else d=c,p=s-1;if(p<0||p>=d.length)return"";if(i!==void 0){let h=i<0?d.length+i:p+i;return d.slice(p,Math.max(p,h)).join(" ")}return d.slice(p).join(" ")}let a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(a){let u=a[1];if(e.state.associativeArrays?.has(u))throw new q(1,"",`bash: \${${u}[@]: 0: 3}: bad substitution
|
|
105
|
+
`);let c=G(e,u),f=0;if(s<0){if(c.length>0){let d=c[c.length-1][0],h=(typeof d=="number"?d:0)+1+s;if(h<0||(f=c.findIndex(([m])=>typeof m=="number"&&m>=h),f<0))return""}}else if(f=c.findIndex(([d])=>typeof d=="number"&&d>=s),f<0)return"";if(i!==void 0){if(i<0)throw new le(`${a[1]}[@]: substring expression < 0`);return c.slice(f,f+i).map(([,d])=>d).join(" ")}return c.slice(f).map(([,d])=>d).join(" ")}let o=[...n],l=s;if(l<0&&(l=Math.max(0,o.length+l)),i!==void 0){if(i<0){let u=o.length+i;return o.slice(l,Math.max(l,u)).join("")}return o.slice(l,l+i).join("")}return o.slice(l).join("")}async function du(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:case_modification"),n.pattern){let i=e.state.shoptOptions.extglob,a="";for(let f of n.pattern.parts)if(f.type==="Glob")a+=J(f.pattern,!0,i);else if(f.type==="Literal")a+=J(f.value,!0,i);else if(f.type==="SingleQuoted"||f.type==="Escaped")a+=te(f.value);else if(f.type==="DoubleQuoted"){let d=await r(e,f.parts);a+=te(d)}else if(f.type==="ParameterExpansion"){let d=await s(e,f);a+=J(d,!0,i)}let o=me(`^(?:${a})$`),l=n.direction==="upper"?f=>f.toUpperCase():f=>f.toLowerCase(),u="",c=!1;for(let f of t)!n.all&&c?u+=f:o.test(f)?(u+=l(f),c=!0):u+=f;return u}return n.direction==="upper"?n.all?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1):n.all?t.toLowerCase():t.charAt(0).toLowerCase()+t.slice(1)}function pu(e,t,n,r,s){e.coverage?.hit("bash:expansion:transform");let i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(i&&s.operator==="Q")return G(e,i[1]).map(([,u])=>en(u)).join(" ");if(i&&s.operator==="a")return tn(e,i[1]);let a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[.+\]$/);if(a&&s.operator==="a")return tn(e,a[1]);switch(s.operator){case"Q":return r?"":en(n);case"P":return pr(e,n);case"a":return tn(e,t);case"A":return r?"":`${t}=${en(n)}`;case"E":return n.replace(/\\([\\abefnrtv'"?])/g,(o,l)=>{switch(l){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
|
|
106
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return l}});case"K":case"k":return r?"":en(n);case"u":return n.charAt(0).toUpperCase()+n.slice(1);case"U":return n.toUpperCase();case"L":return n.toLowerCase();default:return n}}async function hu(e,t,n,r,s,i,a=!1){if(e.coverage?.hit("bash:expansion:indirection"),ue(e,t))return xn(e,t)||"";let o=/^[a-zA-Z_][a-zA-Z0-9_]*\[([@*])\]$/.test(t);if(r){if(s.innerOp?.type==="UseAlternative")return"";throw new Xe(`\${!${t}}`)}let l=n;if(o&&(l===""||l.includes(" ")))throw new Xe(`\${!${t}}`);let u=l.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(u&&u[1].includes("~"))throw new Xe(`\${!${t}}`);if(s.innerOp){let c={type:"ParameterExpansion",parameter:l,operation:s.innerOp};return i(e,c,a)}return await ae(e,l)}function mu(e,t){e.coverage?.hit("bash:expansion:array_keys");let r=G(e,t.array).map(([s])=>String(s));return t.star?r.join(Q(e.state.env)):r.join(" ")}function yu(e,t){e.coverage?.hit("bash:expansion:var_name_prefix");let n=Wn(e,t.prefix);return t.star?n.join(Q(e.state.env)):n.join(" ")}function gu(e,t,n,r){let s=Number.parseInt(e.state.env.get("#")||"0",10),i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(t==="*")return{isEmpty:s===0,effectiveValue:n};if(t==="@")return{isEmpty:s===0||s===1&&e.state.env.get("1")==="",effectiveValue:n};if(i){let[,a,o]=i,l=G(e,a);if(l.length===0)return{isEmpty:!0,effectiveValue:""};if(o==="*"){let u=Q(e.state.env),c=l.map(([,f])=>f).join(u);return{isEmpty:r?c==="":!1,effectiveValue:c}}return{isEmpty:l.length===1&&l.every(([,u])=>u===""),effectiveValue:l.map(([,u])=>u).join(" ")}}return{isEmpty:n==="",effectiveValue:n}}function wu(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="\\"&&t+1<e.length){t+=2;continue}if(n==="'"){let r=e.indexOf("'",t+1);if(r!==-1){t=r+1;continue}}if(n==="$"&&t+1<e.length&&e[t+1]==="("||n==="`")return!0;t++}return!1}function Eu(e,t){let n=1,r=t,s=!1,i=!1;for(;r<e.length&&n>0;){let a=e[r];if(a==="\\"&&!s&&r+1<e.length){r+=2;continue}if(a==="'"&&!i){s=!s,r++;continue}if(a==='"'&&!s){i=!i,r++;continue}if(!s&&!i){if(a==="(")n++;else if(a===")"&&(n--,n===0))return r}r++}return-1}async function ls(e,t){let n=new H,r;try{r=n.parse(t)}catch{return""}let s=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let i=new Map(e.state.env),a=at(e.state.arrays),o=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let u=await e.executeScript(r),c=u.exitCode;return e.state.env=i,e.state.arrays=a,e.state.cwd=o,e.state.suppressVerbose=l,e.state.lastExitCode=c,e.state.env.set("?",String(c)),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.stderr),e.state.bashPid=s,u.stdout.replace(/\n+$/,"")}catch(u){return e.state.env=i,e.state.arrays=a,e.state.cwd=o,e.state.bashPid=s,e.state.suppressVerbose=l,Fr(u),u instanceof q?(e.state.lastExitCode=u.exitCode,e.state.env.set("?",String(u.exitCode)),u.stdout?.replace(/\n+$/,"")??""):""}}function Qi(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let a=t.slice(r+1,i);n+=et(a),r=i+1;continue}}if(s==='"'){let i=-1,a=r+1;for(;a<t.length;){if(t[a]==="\\"){a+=2;continue}if(t[a]==='"'){i=a;break}a++}if(i!==-1){let o=t.slice(r+1,i),l=Wp(e,o);n+=et(l),r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}function Wp(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}n+=s,r++}return n}async function bu(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let a=t.slice(r+1,i);n+=et(a),r=i+1;continue}}if(s==='"'){let i=-1,a=r+1;for(;a<t.length;){if(t[a]==="\\"){a+=2;continue}if(t[a]==='"'){i=a;break}a++}if(i!==-1){let o=t.slice(r+1,i),l=await Vp(e,o);n+=et(l),r=i+1;continue}}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=Eu(t,r+2);if(i!==-1){let a=t.slice(r+2,i),o=await ls(e,a);n+=o,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let a=t.slice(r+1,i),o=await ls(e,a);n+=o,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}async function Vp(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=Eu(t,r+2);if(i!==-1){let a=t.slice(r+2,i),o=await ls(e,a);n+=o,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let a=t.slice(r+1,i),o=await ls(e,a);n+=o,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}n+=s,r++}return n}function Ki(e,t){if(!t.startsWith("~"))return t;e.coverage?.hit("bash:expansion:tilde");let n=e.state.env.get("HOME")!==void 0?e.state.env.get("HOME"):"/home/user";if(t==="~"||t.startsWith("~/"))return n+t.slice(1);let r=1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;let s=t.slice(1,r),i=t.slice(r);return i!==""&&!i.startsWith("/")?t:s==="root"?`/root${i}`:t}function nn(e,t){return t.split(":").map(n=>Ki(e,n)).join(":")}function Ie(e,t,n,r){if(e.length>n-t.length)throw new P(`${r} element limit exceeded (${n})`,"array_elements");for(let s of t)e.push(s)}async function zp(e,t,n,r){let s="";for(let i of t.parts)if(i.type==="Glob")s+=J(i.pattern,!0,e.state.shoptOptions.extglob);else if(i.type==="Literal")s+=J(i.value,!0,e.state.shoptOptions.extglob);else if(i.type==="SingleQuoted"||i.type==="Escaped")s+=te(i.value);else if(i.type==="DoubleQuoted"){let a=await n(e,i.parts);s+=te(a)}else if(i.type==="ParameterExpansion"){let a=await r(e,i);s+=J(a,!0,e.state.shoptOptions.extglob)}else{let a=await r(e,i);s+=te(a)}return s}async function Su(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternReplacement")return null;let i=s.parts[0],a=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!a)return null;let o=a[1],l=a[2]==="*",u=i.operation,c=G(e,o),f=c.map(([,E])=>E);if(c.length===0){let E=e.state.env.get(o);E!==void 0&&f.push(E)}if(f.length===0)return{values:[],quoted:!0};let d="";u.pattern&&(d=await zp(e,u.pattern,n,r));let p=u.replacement?await n(e,u.replacement.parts):"",h=d;u.anchor==="start"?h=`^${d}`:u.anchor==="end"&&(h=`${d}$`);let m=[];try{let E=me(h,u.all?"g":"");for(let S of f)m.push(E.replace(S,p))}catch{m.push(...f)}if(l){let E=Q(e.state.env);return{values:[m.join(E)],quoted:!0}}return{values:m,quoted:!0}}async function Au(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternRemoval")return null;let i=s.parts[0],a=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!a)return null;let o=a[1],l=a[2]==="*",u=i.operation,c=G(e,o),f=c.map(([,m])=>m);if(c.length===0){let m=e.state.env.get(o);m!==void 0&&f.push(m)}if(f.length===0)return{values:[],quoted:!0};let d="",p=e.state.shoptOptions.extglob;if(u.pattern)for(let m of u.pattern.parts)if(m.type==="Glob")d+=J(m.pattern,u.greedy,p);else if(m.type==="Literal")d+=J(m.value,u.greedy,p);else if(m.type==="SingleQuoted"||m.type==="Escaped")d+=te(m.value);else if(m.type==="DoubleQuoted"){let E=await n(e,m.parts);d+=te(E)}else if(m.type==="ParameterExpansion"){let E=await r(e,m);d+=J(E,u.greedy,p)}else{let E=await r(e,m);d+=te(E)}let h=[];for(let m of f)h.push(gt(e,m,d,u.side,u.greedy));if(l){let m=Q(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}async function vu(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="DefaultValue"&&n.parts[0].operation?.type!=="UseAlternative"&&n.parts[0].operation?.type!=="AssignDefault")return null;let r=n.parts[0],s=r.operation,i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/),a,o=!1;if(i){let l=i[1];o=i[2]==="*";let u=G(e,l),c=u.length>0||e.state.env.has(l),f=u.length===0||u.length===1&&u.every(([,p])=>p===""),d=s.checkEmpty??!1;if(s.type==="UseAlternative"?a=c&&!(d&&f):a=!c||d&&f,!a){if(u.length>0){let h=u.map(([,m])=>m);if(o){let m=Q(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}let p=e.state.env.get(l);return p!==void 0?{values:[p],quoted:!0}:{values:[],quoted:!0}}}else{let l=r.parameter,u=await Nt(e,l),c=await ae(e,l),f=c==="",d=s.checkEmpty??!1;if(s.type==="UseAlternative"?a=u&&!(d&&f):a=!u||d&&f,!a)return{values:[c],quoted:!0}}if(a&&s.word){let l=s.word.parts,u=null,c=!1;for(let f of l)if(f.type==="ParameterExpansion"&&!f.operation){let d=f.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(d){u=d[1],c=d[2]==="*";break}}if(u){let f=G(e,u);if(f.length>0){let p=f.map(([,h])=>h);if(c||o){let h=Q(e.state.env);return{values:[p.join(h)],quoted:!0}}return{values:p,quoted:!0}}let d=e.state.env.get(u);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}return null}async function ku(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0],a=-1,o="",l=!1,u=null;for(let m=0;m<i.parts.length;m++){let E=i.parts[m];if(E.type==="ParameterExpansion"&&(E.operation?.type==="PatternRemoval"||E.operation?.type==="PatternReplacement")){let S=E.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(S){a=m,o=S[1],l=S[2]==="*",u=E.operation;break}}}if(a===-1||a===0&&a===i.parts.length-1)return null;let c="";for(let m=0;m<a;m++)c+=await r(e,i.parts[m]);let f="";for(let m=a+1;m<i.parts.length;m++)f+=await r(e,i.parts[m]);let d=G(e,o),p=d.map(([,m])=>m);if(d.length===0){let m=e.state.env.get(o);if(m!==void 0)p=[m];else{if(l)return{values:[c+f],quoted:!0};let E=c+f;return{values:E?[E]:[],quoted:!0}}}if(u?.type==="PatternRemoval"){let m=u,E="",S=e.state.shoptOptions.extglob;if(m.pattern)for(let g of m.pattern.parts)if(g.type==="Glob")E+=J(g.pattern,m.greedy,S);else if(g.type==="Literal")E+=J(g.value,m.greedy,S);else if(g.type==="SingleQuoted"||g.type==="Escaped")E+=te(g.value);else if(g.type==="DoubleQuoted"){let y=await s(e,g.parts);E+=te(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);E+=J(y,m.greedy,S)}else{let y=await r(e,g);E+=te(y)}p=p.map(g=>gt(e,g,E,m.side,m.greedy))}else if(u?.type==="PatternReplacement"){let m=u,E="";if(m.pattern)for(let y of m.pattern.parts)if(y.type==="Glob")E+=J(y.pattern,!0,e.state.shoptOptions.extglob);else if(y.type==="Literal")E+=J(y.value,!0,e.state.shoptOptions.extglob);else if(y.type==="SingleQuoted"||y.type==="Escaped")E+=te(y.value);else if(y.type==="DoubleQuoted"){let b=await s(e,y.parts);E+=te(b)}else if(y.type==="ParameterExpansion"){let b=await r(e,y);E+=J(b,!0,e.state.shoptOptions.extglob)}else{let b=await r(e,y);E+=te(b)}let S=m.replacement?await s(e,m.replacement.parts):"",g=E;m.anchor==="start"?g=`^${E}`:m.anchor==="end"&&(g=`${E}$`);try{let y=me(g,m.all?"g":"");p=p.map(b=>y.replace(b,S))}catch{}}if(l){let m=Q(e.state.env);return{values:[c+p.join(m)+f],quoted:!0}}return p.length===1?{values:[c+p[0]+f],quoted:!0}:{values:[c+p[0],...p.slice(1,-1),p[p.length-1]+f],quoted:!0}}async function xu(e,t,n,r){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a="",o=!1;for(let p=0;p<s.parts.length;p++){let h=s.parts[p];if(h.type==="ParameterExpansion"&&!h.operation){let m=h.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(m){i=p,a=m[1],o=m[2]==="*";break}}}if(i===-1)return null;let l="";for(let p=0;p<i;p++)l+=await r(e,s.parts[p]);let u="";for(let p=i+1;p<s.parts.length;p++)u+=await r(e,s.parts[p]);let c=G(e,a),f=c.map(([,p])=>p);if(c.length===0){let p=e.state.env.get(a);if(p!==void 0)return{values:[l+p+u],quoted:!0};if(o)return{values:[l+u],quoted:!0};let h=l+u;return{values:h?[h]:[],quoted:!0}}if(o){let p=Q(e.state.env);return{values:[l+f.join(p)+u],quoted:!0}}return f.length===1?{values:[l+f[0]+u],quoted:!0}:{values:[l+f[0],...f.slice(1,-1),f[f.length-1]+u],quoted:!0}}async function $u(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!=="ParameterExpansion"||r.parts[0].operation?.type!=="Substring")return null;let s=r.parts[0],i=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!i)return null;let a=i[1],o=i[2]==="*",l=s.operation;if(e.state.associativeArrays?.has(a))throw new q(1,"",`bash: \${${a}[@]: 0: 3}: bad substitution
|
|
107
|
+
`);let u=l.offset?await n(e,l.offset.expression):0,c=l.length?await n(e,l.length.expression):void 0,f=G(e,a);if(f.length>e.limits.maxArrayElements)throw new P(`array transform element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let d=0;if(u<0){if(f.length>0){let h=f[f.length-1][0],E=(typeof h=="number"?h:0)+1+u;if(E<0)return{values:[],quoted:!0};d=f.findIndex(([S])=>typeof S=="number"&&S>=E),d<0&&(d=f.length)}}else d=f.findIndex(([h])=>typeof h=="number"&&h>=u),d<0&&(d=f.length);let p;if(c!==void 0){if(c<0)throw new le(`${a}[@]: substring expression < 0`);p=f.slice(d,d+c).map(([,h])=>h)}else p=f.slice(d).map(([,h])=>h);if(p.length===0)return{values:[],quoted:!0};if(o){let h=Q(e.state.env);return{values:[p.join(h)],quoted:!0}}return{values:p,quoted:!0}}function Pu(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="Transform")return null;let r=n.parts[0],s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!s)return null;let i=s[1],a=s[2]==="*",o=r.operation,l=G(e,i);if(l.length===0){let d=e.state.env.get(i);if(d!==void 0){let p;switch(o.operator){case"a":p="";break;case"P":p=pr(e,d);break;case"Q":p=en(d);break;default:p=d}if(B(p)>e.limits.maxStringLength)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[p],quoted:!0}}return a?{values:[""],quoted:!0}:{values:[],quoted:!0}}let u=tn(e,i),c=[],f=0;for(let[,d]of l){let p;switch(o.operator){case"a":p=u;break;case"P":p=pr(e,d);break;case"Q":p=en(d);break;case"u":p=d.charAt(0).toUpperCase()+d.slice(1);break;case"U":p=d.toUpperCase();break;case"L":p=d.toLowerCase();break;default:p=d}let h=B(p);if(h>e.limits.maxStringLength-f)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");c.push(p),f+=h}if(a){let d=Q(e.state.env);if(Math.max(0,c.length-1)*B(d)>e.limits.maxStringLength-f)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[c.join(d)],quoted:!0}}return{values:c,quoted:!0}}function Cu(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion")return null;let r=n.parts[0];if(r.operation)return null;let s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!s)return null;let i=s[1];if(ue(e,i)){let l=xn(e,i);if(l?.endsWith("[@]")||l?.endsWith("[*]"))return{values:[],quoted:!0}}let a=G(e,i);if(a.length>0)return{values:a.map(([,l])=>l),quoted:!0};let o=e.state.env.get(i);return o!==void 0?{values:[o],quoted:!0}:{values:[],quoted:!0}}function Nu(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation)return null;let s=n.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)||!ue(e,s))return null;let i=xn(e,s);if(!i)return null;let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!a)return null;let o=a[1],l=G(e,o);if(l.length>0)return{values:l.map(([,c])=>c),quoted:!0};let u=e.state.env.get(o);return u!==void 0?{values:[u],quoted:!0}:{values:[],quoted:!0}}async function Ru(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let a=i.parts[0],o=a.operation,l=await ae(e,a.parameter),u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!u){if(!o.innerOp&&(l==="@"||l==="*")){let h=Number.parseInt(e.state.env.get("#")||"0",10),m=[];for(let E=1;E<=h;E++)m.push(e.state.env.get(String(E))||"");return l==="*"?{values:[m.join(Q(e.state.env))],quoted:!0}:{values:m,quoted:!0}}return null}let c=u[1],f=u[2]==="*",d=G(e,c);if(o.innerOp){if(o.innerOp.type==="Substring")return Up(e,d,c,f,o.innerOp);if(o.innerOp.type==="DefaultValue"||o.innerOp.type==="UseAlternative"||o.innerOp.type==="AssignDefault"||o.innerOp.type==="ErrorIfUnset")return qp(e,d,c,f,o.innerOp,s);if(o.innerOp.type==="Transform"&&o.innerOp.operator==="a"){let m=tn(e,c),E=d.map(()=>m);return f?{values:[E.join(Q(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let h=[];for(let[,m]of d){let E={type:"ParameterExpansion",parameter:"_indirect_elem_",operation:o.innerOp},S=e.state.env.get("_indirect_elem_");e.state.env.set("_indirect_elem_",m);try{let g=await r(e,E,!0);h.push(g)}finally{S!==void 0?e.state.env.set("_indirect_elem_",S):e.state.env.delete("_indirect_elem_")}}return f?{values:[h.join(Q(e.state.env))],quoted:!0}:{values:h,quoted:!0}}if(d.length>0){let h=d.map(([,m])=>m);return f?{values:[h.join(Q(e.state.env))],quoted:!0}:{values:h,quoted:!0}}let p=e.state.env.get(c);return p!==void 0?{values:[p],quoted:!0}:{values:[],quoted:!0}}async function Up(e,t,n,r,s){let i=s.offset?await Y(e,s.offset.expression):0,a=s.length?await Y(e,s.length.expression):void 0,o=0;if(i<0){if(t.length>0){let c=t[t.length-1][0],d=(typeof c=="number"?c:0)+1+i;if(d<0)return{values:[],quoted:!0};if(o=t.findIndex(([p])=>typeof p=="number"&&p>=d),o<0)return{values:[],quoted:!0}}}else if(o=t.findIndex(([c])=>typeof c=="number"&&c>=i),o<0)return{values:[],quoted:!0};let l;if(a!==void 0){if(a<0)throw new le(`${n}[@]: substring expression < 0`);l=t.slice(o,o+a)}else l=t.slice(o);let u=l.map(([,c])=>c);return r?{values:[u.join(Q(e.state.env))],quoted:!0}:{values:u,quoted:!0}}async function qp(e,t,n,r,s,i){let a=s.checkEmpty??!1,o=t.map(([,c])=>c),l=t.length===0,u=t.length===0;if(s.type==="UseAlternative")return!u&&!(a&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(s.type==="DefaultValue")return(u||a&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:r?{values:[o.join(Q(e.state.env))],quoted:!0}:{values:o,quoted:!0};if(s.type==="AssignDefault"){if((u||a&&l)&&s.word){let f=await i(e,s.word.parts,!0);return j(e,n,0,f),{values:[f],quoted:!0}}return r?{values:[o.join(Q(e.state.env))],quoted:!0}:{values:o,quoted:!0}}return r?{values:[o.join(Q(e.state.env))],quoted:!0}:{values:o,quoted:!0}}async function Du(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="UseAlternative"&&t[0].operation?.type!=="DefaultValue")return null;let n=t[0],r=n.operation,s=r?.word;if(!s||s.parts.length!==1||s.parts[0].type!=="DoubleQuoted")return null;let i=s.parts[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let a=i.parts[0],l=(await ae(e,a.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!l)return null;let u=await Nt(e,n.parameter),c=await ae(e,n.parameter)==="",f=r.checkEmpty??!1,d;if(r.type==="UseAlternative"?d=u&&!(f&&c):d=!u||f&&c,d){let p=l[1],h=l[2]==="*",m=G(e,p);if(m.length>0){let S=m.map(([,g])=>g);return h?{values:[S.join(Q(e.state.env))],quoted:!0}:{values:S,quoted:!0}}let E=e.state.env.get(p);return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function Iu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="Indirection")return null;let n=t[0],s=n.operation.innerOp;if(!s||s.type!=="UseAlternative"&&s.type!=="DefaultValue")return null;let i=s.word;if(!i||i.parts.length!==1||i.parts[0].type!=="DoubleQuoted")return null;let a=i.parts[0];if(a.parts.length!==1||a.parts[0].type!=="ParameterExpansion"||a.parts[0].operation?.type!=="Indirection")return null;let o=a.parts[0],u=(await ae(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!u)return null;let c=await ae(e,n.parameter),f=await Nt(e,n.parameter),d=c==="",p=s.checkEmpty??!1,h;if(s.type==="UseAlternative"?h=f&&!(p&&d):h=!f||p&&d,h){let m=u[1],E=u[2]==="*",S=G(e,m);if(S.length>0){let y=S.map(([,b])=>b);return E?{values:[y.join(Q(e.state.env))],quoted:!0}:{values:y,quoted:!0}}let g=e.state.env.get(m);return g!==void 0?{values:[g],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}function Ou(e){let t=Number.parseInt(e.state.env.get("#")||"0",10);if(t>e.limits.maxArrayElements)throw new P(`positional parameter element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let n=[],r=0;for(let s=1;s<=t;s++){let i=e.state.env.get(String(s))||"",a=B(i);if(a>e.limits.maxStringLength-r)throw new P(`positional parameter string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n.push(i),r+=a}return n}function us(e,t,n){if(B(t)>n-B(e))throw new P(`positional expansion string limit exceeded (${n} bytes)`,"string_length");return e+t}function Xi(e,t,n,r){if(e.length>=r.limits.maxArrayElements)throw new P(`positional expansion element limit exceeded (${r.limits.maxArrayElements})`,"array_elements");let s=B(t);if(s>r.limits.maxStringLength-n.value)throw new P(`positional expansion string limit exceeded (${r.limits.maxStringLength} bytes)`,"string_length");e.push(t),n.value+=s}async function _u(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a=!1;for(let g=0;g<s.parts.length;g++){let y=s.parts[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="Substring"){i=g,a=y.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,u=l.offset?await n(e,l.offset.expression):0,c=l.length?await n(e,l.length.expression):void 0,f=Number.parseInt(e.state.env.get("#")||"0",10),d=[];for(let g=1;g<=f;g++)d.push(e.state.env.get(String(g))||"");let p=e.state.env.get("0")||"bash",h;if(u<=0){let g=[p,...d],y=g.length+u;if(y<0)h=[];else{let b=u<0?y:0;if(c!==void 0){let A=c<0?g.length+c:b+c;h=g.slice(b,Math.max(b,A))}else h=g.slice(b)}}else{let g=u-1;if(g>=d.length)h=[];else if(c!==void 0){let y=c<0?d.length+c:g+c;h=d.slice(g,Math.max(g,y))}else h=d.slice(g)}let m="";for(let g=0;g<i;g++)m+=await r(e,s.parts[g]);let E="";for(let g=i+1;g<s.parts.length;g++)E+=await r(e,s.parts[g]);if(h.length===0){let g=m+E;return{values:g?[g]:[],quoted:!0}}if(a){let g=Q(e.state.env);return{values:[m+h.join(g)+E],quoted:!0}}return h.length===1?{values:[m+h[0]+E],quoted:!0}:{values:[m+h[0],...h.slice(1,-1),h[h.length-1]+E],quoted:!0}}async function Lu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a=!1;for(let g=0;g<s.parts.length;g++){let y=s.parts[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="PatternReplacement"){i=g,a=y.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,u=Ou(e),c="";for(let g=0;g<i;g++)c=us(c,await n(e,s.parts[g]),e.limits.maxStringLength);let f="";for(let g=i+1;g<s.parts.length;g++)f=us(f,await n(e,s.parts[g]),e.limits.maxStringLength);if(u.length===0){let g=c+f;return{values:g?[g]:[],quoted:!0}}let d="";if(l.pattern)for(let g of l.pattern.parts)if(g.type==="Glob")d+=J(g.pattern,!0,e.state.shoptOptions.extglob);else if(g.type==="Literal")d+=J(g.value,!0,e.state.shoptOptions.extglob);else if(g.type==="SingleQuoted"||g.type==="Escaped")d+=te(g.value);else if(g.type==="DoubleQuoted"){let y=await r(e,g.parts);d+=te(y)}else if(g.type==="ParameterExpansion"){let y=await n(e,g);d+=J(y,!0,e.state.shoptOptions.extglob)}else{let y=await n(e,g);d+=te(y)}let p=l.replacement?await r(e,l.replacement.parts):"",h=d;l.anchor==="start"?h=`^${d}`:l.anchor==="end"&&(h=`${d}$`);let m=[],E={value:0};try{let g=me(h,l.all?"g":"");for(let y of u){let b=0;g.lastIndex=0;for(let x=g.exec(y);x&&(b++,!!l.all);x=g.exec(y))x[0].length===0&&g.lastIndex++;let A=B(y),k=B(p),v=0,$=/\$(?:\$|&|\d+|<[^>]+>|`|')/g;for(;$.exec(p)!==null;)v++;if(A+b*k+b*v*A>e.limits.maxStringLength-E.value)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");Xi(m,g.replace(y,p),E,e)}}catch(g){if(g instanceof P)throw g;for(let y of u)Xi(m,y,E,e)}if(a){let g=Q(e.state.env);if(E.value+Math.max(0,m.length-1)*B(g)+B(c)+B(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[c+m.join(g)+f],quoted:!0}}if(B(c)+E.value+B(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return m.length===1?{values:[c+m[0]+f],quoted:!0}:{values:[c+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function Tu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a=!1;for(let S=0;S<s.parts.length;S++){let g=s.parts[S];if(g.type==="ParameterExpansion"&&(g.parameter==="@"||g.parameter==="*")&&g.operation?.type==="PatternRemoval"){i=S,a=g.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,u=Ou(e),c="";for(let S=0;S<i;S++)c=us(c,await n(e,s.parts[S]),e.limits.maxStringLength);let f="";for(let S=i+1;S<s.parts.length;S++)f=us(f,await n(e,s.parts[S]),e.limits.maxStringLength);if(u.length===0){let S=c+f;return{values:S?[S]:[],quoted:!0}}let d="",p=e.state.shoptOptions.extglob;if(l.pattern)for(let S of l.pattern.parts)if(S.type==="Glob")d+=J(S.pattern,l.greedy,p);else if(S.type==="Literal")d+=J(S.value,l.greedy,p);else if(S.type==="SingleQuoted"||S.type==="Escaped")d+=te(S.value);else if(S.type==="DoubleQuoted"){let g=await r(e,S.parts);d+=te(g)}else if(S.type==="ParameterExpansion"){let g=await n(e,S);d+=J(g,l.greedy,p)}else{let g=await n(e,S);d+=te(g)}let h=[],m={value:0};for(let S of u)Xi(h,gt(e,S,d,l.side,l.greedy),m,e);if(a){let S=Q(e.state.env);if(m.value+Math.max(0,h.length-1)*B(S)+B(c)+B(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[c+h.join(S)+f],quoted:!0}}if(B(c)+m.value+B(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return h.length===1?{values:[c+h[0]+f],quoted:!0}:{values:[c+h[0],...h.slice(1,-1),h[h.length-1]+f],quoted:!0}}async function Fu(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0],s=-1,i=!1;for(let d=0;d<r.parts.length;d++){let p=r.parts[d];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")){s=d,i=p.parameter==="*";break}}if(s===-1)return null;let a=r.parts[s];if(a.type==="ParameterExpansion"&&a.operation)return null;let o=Number.parseInt(e.state.env.get("#")||"0",10),l="";for(let d=0;d<s;d++)l+=await n(e,r.parts[d]);let u="";for(let d=s+1;d<r.parts.length;d++)u+=await n(e,r.parts[d]);if(o===0){if(i)return{values:[l+u],quoted:!0};let d=l+u;return{values:d?[d]:[],quoted:!0}}let c=[];for(let d=1;d<=o;d++)c.push(e.state.env.get(String(d))||"");if(i){let d=Q(e.state.env);return{values:[l+c.join(d)+u],quoted:!0}}return c.length===1?{values:[l+c[0]+u],quoted:!0}:{values:[l+c[0],...c.slice(1,-1),c[c.length-1]+u],quoted:!0}}function Dt(e,t,n,r){if(t.length>=e.limits.maxArrayElements)throw new P(`unquoted expansion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let s=B(n);if(s>e.limits.maxStringLength-r.value)throw new P(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");t.push(n),r.value+=s}function Yi(e,t,n,r){let s=B(n),i=Math.max(0,t.length-1);if(s>0&&i>Math.floor((e.limits.maxStringLength-r)/s))throw new P(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return t.join(n)}function jp(e){return new Jt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")})}async function cs(e,t){if(e.state.options.noglob)return t;let n=jp(e),r=[];for(let s of t)if(Rt(s,e.state.shoptOptions.extglob)){let i=await n.expand(s);if(i.length>0)Ie(r,i,e.limits.maxArrayElements,"unquoted glob expansion");else{if(n.hasFailglob())throw new zt(s);n.hasNullglob()||r.push(s)}}else r.push(s);return r}async function Mu(e,t,n,r){let s=-1,i="",a=!1;for(let b=0;b<t.length;b++){let A=t[b];if(A.type==="ParameterExpansion"&&A.operation?.type==="PatternReplacement"){let k=A.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(k){s=b,i=k[1],a=k[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,u=G(e,i),c=u.map(([,b])=>b);if(u.length===0){let b=e.state.env.get(i);b!==void 0&&(c=[b])}if(c.length===0)return{values:[],quoted:!1};let f="";if(l.pattern)for(let b of l.pattern.parts)if(b.type==="Glob")f+=J(b.pattern,!0,e.state.shoptOptions.extglob);else if(b.type==="Literal")f+=J(b.value,!0,e.state.shoptOptions.extglob);else if(b.type==="SingleQuoted"||b.type==="Escaped")f+=te(b.value);else if(b.type==="DoubleQuoted"){let A=await n(e,b.parts);f+=te(A)}else if(b.type==="ParameterExpansion"){let A=await r(e,b);f+=J(A,!0,e.state.shoptOptions.extglob)}else{let A=await r(e,b);f+=te(A)}let d=l.replacement?await n(e,l.replacement.parts):"",p=f;l.anchor==="start"?p=`^${f}`:l.anchor==="end"&&(p=`${f}$`);let h=[],m={value:0};try{let b=me(p,l.all?"g":"");for(let A of c)Dt(e,h,as(e,A,b,d,l.all),m)}catch(b){if(b instanceof P)throw b;for(let A of c)Dt(e,h,A,m)}let E=ve(e.state.env),S=De(e.state.env);if(a){let b=Q(e.state.env),A=Yi(e,h,b,m.value);return S?{values:A?[A]:[],quoted:!1}:{values:fe(A,E,e.limits.maxArrayElements),quoted:!1}}if(S)return{values:h,quoted:!1};let g=[],y={value:0};for(let b of h)if(b==="")Dt(e,g,"",y);else for(let A of fe(b,E,e.limits.maxArrayElements))Dt(e,g,A,y);return{values:g,quoted:!1}}async function Bu(e,t,n,r){let s=-1,i="",a=!1;for(let y=0;y<t.length;y++){let b=t[y];if(b.type==="ParameterExpansion"&&b.operation?.type==="PatternRemoval"){let A=b.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(A){s=y,i=A[1],a=A[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,u=G(e,i),c=u.map(([,y])=>y);if(u.length===0){let y=e.state.env.get(i);y!==void 0&&(c=[y])}if(c.length===0)return{values:[],quoted:!1};let f="",d=e.state.shoptOptions.extglob;if(l.pattern)for(let y of l.pattern.parts)if(y.type==="Glob")f+=J(y.pattern,l.greedy,d);else if(y.type==="Literal")f+=J(y.value,l.greedy,d);else if(y.type==="SingleQuoted"||y.type==="Escaped")f+=te(y.value);else if(y.type==="DoubleQuoted"){let b=await n(e,y.parts);f+=te(b)}else if(y.type==="ParameterExpansion"){let b=await r(e,y);f+=J(b,l.greedy,d)}else{let b=await r(e,y);f+=te(b)}let p=[],h={value:0};for(let y of c)Dt(e,p,gt(e,y,f,l.side,l.greedy),h);let m=ve(e.state.env),E=De(e.state.env);if(a){let y=Q(e.state.env),b=Yi(e,p,y,h.value);return E?{values:b?[b]:[],quoted:!1}:{values:fe(b,m,e.limits.maxArrayElements),quoted:!1}}if(E)return{values:p,quoted:!1};let S=[],g={value:0};for(let y of p)if(y==="")Dt(e,S,"",g);else for(let b of fe(y,m,e.limits.maxArrayElements))Dt(e,S,b,g);return{values:S,quoted:!1}}async function Wu(e,t,n,r){let s=-1,i=!1;for(let g=0;g<t.length;g++){let y=t[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="PatternRemoval"){s=g,i=y.parameter==="*";break}}if(s===-1)return null;let o=t[s].operation,l=Number.parseInt(e.state.env.get("#")||"0",10),u=[];for(let g=1;g<=l;g++)u.push(e.state.env.get(String(g))||"");if(u.length===0)return{values:[],quoted:!1};let c="",f=e.state.shoptOptions.extglob;if(o.pattern)for(let g of o.pattern.parts)if(g.type==="Glob")c+=J(g.pattern,o.greedy,f);else if(g.type==="Literal")c+=J(g.value,o.greedy,f);else if(g.type==="SingleQuoted"||g.type==="Escaped")c+=te(g.value);else if(g.type==="DoubleQuoted"){let y=await n(e,g.parts);c+=te(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);c+=J(y,o.greedy,f)}else{let y=await r(e,g);c+=te(y)}let d=[],p={value:0};for(let g of u)Dt(e,d,gt(e,g,c,o.side,o.greedy),p);let h=ve(e.state.env),m=De(e.state.env);if(i){let g=Q(e.state.env),y=Yi(e,d,g,p.value);return m?{values:y?[y]:[],quoted:!1}:{values:fe(y,h,e.limits.maxArrayElements),quoted:!1}}if(m)return{values:d,quoted:!1};let E=[],S={value:0};for(let g of d)if(g==="")Dt(e,E,"",S);else for(let y of fe(g,h,e.limits.maxArrayElements))Dt(e,E,y,S);return{values:E,quoted:!1}}async function Vu(e,t,n,r){let s=-1,i=!1;for(let y=0;y<t.length;y++){let b=t[y];if(b.type==="ParameterExpansion"&&(b.parameter==="@"||b.parameter==="*")&&b.operation?.type==="Substring"){s=y,i=b.parameter==="*";break}}if(s===-1)return null;let o=t[s].operation,l=o.offset?await n(e,o.offset.expression):0,u=o.length?await n(e,o.length.expression):void 0,c=Number.parseInt(e.state.env.get("#")||"0",10),f=[];for(let y=1;y<=c;y++)f.push(e.state.env.get(String(y))||"");let d=e.state.env.get("0")||"bash",p;if(l<=0){let y=[d,...f],b=y.length+l;if(b<0)p=[];else{let A=l<0?b:0;if(u!==void 0){let k=u<0?y.length+u:A+u;p=y.slice(A,Math.max(A,k))}else p=y.slice(A)}}else{let y=l-1;if(y>=f.length)p=[];else if(u!==void 0){let b=u<0?f.length+u:y+u;p=f.slice(y,Math.max(y,b))}else p=f.slice(y)}let h="";for(let y=0;y<s;y++)h+=await r(e,t[y]);let m="";for(let y=s+1;y<t.length;y++)m+=await r(e,t[y]);let E=ve(e.state.env),S=De(e.state.env);if(p.length===0){let y=h+m;return y?S?{values:[y],quoted:!1}:{values:fe(y,E,e.limits.maxArrayElements),quoted:!1}:{values:[],quoted:!1}}let g;if(i){let y=Q(e.state.env),b=h+p.join(y)+m;S?g=b?[b]:[]:g=fe(b,E,e.limits.maxArrayElements)}else if(S)p.length===1?g=[h+p[0]+m]:g=[h+p[0],...p.slice(1,-1),p[p.length-1]+m];else{g=[];for(let y=0;y<p.length;y++){let b=p[y];if(y===0&&(b=h+b),y===p.length-1&&(b=b+m),b==="")g.push("");else{let A=fe(b,E,e.limits.maxArrayElements);Ie(g,A,e.limits.maxArrayElements,"unquoted expansion")}}}return{values:await cs(e,g),quoted:!1}}async function zu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].parameter!=="@"&&t[0].parameter!=="*"||t[0].operation)return null;let n=t[0].parameter==="*",r=Number.parseInt(e.state.env.get("#")||"0",10);if(r===0)return{values:[],quoted:!1};let s=[];for(let u=1;u<=r;u++)s.push(e.state.env.get(String(u))||"");let i=ve(e.state.env),a=De(e.state.env),o=ts(e.state.env),l;if(n)if(a)l=s.filter(u=>u!=="");else{let u=Q(e.state.env),c=s.join(u);l=fe(c,i,e.limits.maxArrayElements)}else if(a)l=s.filter(u=>u!=="");else if(o){l=[];for(let u of s){if(u==="")continue;let c=fe(u,i,e.limits.maxArrayElements);Ie(l,c,e.limits.maxArrayElements,"unquoted expansion")}}else{l=[];for(let u of s)if(u==="")l.push("");else{let c=fe(u,i,e.limits.maxArrayElements);Ie(l,c,e.limits.maxArrayElements,"unquoted expansion")}for(;l.length>0&&l[l.length-1]==="";)l.pop()}return{values:await cs(e,l),quoted:!1}}async function Uu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation)return null;let n=t[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!n)return null;let r=n[1],s=n[2]==="*",i=G(e,r),a;if(i.length===0){let f=e.state.env.get(r);if(f!==void 0)a=[f];else return{values:[],quoted:!1}}else a=i.map(([,f])=>f);let o=ve(e.state.env),l=De(e.state.env),u=ts(e.state.env),c;if(s)if(l)c=a.filter(f=>f!=="");else{let f=Q(e.state.env),d=a.join(f);c=fe(d,o,e.limits.maxArrayElements)}else if(l)c=a.filter(f=>f!=="");else if(u){c=[];for(let f of a){if(f==="")continue;let d=fe(f,o,e.limits.maxArrayElements);Ie(c,d,e.limits.maxArrayElements,"unquoted expansion")}}else{c=[];for(let f of a)if(f==="")c.push("");else{let d=fe(f,o,e.limits.maxArrayElements);Ie(c,d,e.limits.maxArrayElements,"unquoted expansion")}for(;c.length>0&&c[c.length-1]==="";)c.pop()}return{values:await cs(e,c),quoted:!1}}function qu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="VarNamePrefix")return null;let n=t[0].operation,r=Wn(e,n.prefix);if(r.length===0)return{values:[],quoted:!1};let s=ve(e.state.env),i=De(e.state.env),a;if(n.star)if(i)a=r;else{let o=Q(e.state.env),l=r.join(o);a=fe(l,s,e.limits.maxArrayElements)}else if(i)a=r;else{a=[];for(let o of r){let l=fe(o,s,e.limits.maxArrayElements);Ie(a,l,e.limits.maxArrayElements,"unquoted expansion")}}return{values:a,quoted:!1}}function ju(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="ArrayKeys")return null;let n=t[0].operation,s=G(e,n.array).map(([l])=>String(l));if(s.length===0)return{values:[],quoted:!1};let i=ve(e.state.env),a=De(e.state.env),o;if(n.star)if(a)o=s;else{let l=Q(e.state.env),u=s.join(l);o=fe(u,i,e.limits.maxArrayElements)}else if(a)o=s;else{o=[];for(let l of s){let u=fe(l,i,e.limits.maxArrayElements);Ie(o,u,e.limits.maxArrayElements,"unquoted expansion")}}return{values:o,quoted:!1}}async function Hu(e,t,n){let r=-1;for(let d=0;d<t.length;d++){let p=t[d];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")&&!p.operation){r=d;break}}if(r===-1||t.length<=1)return null;let s=Number.parseInt(e.state.env.get("#")||"0",10),i=[];for(let d=1;d<=s;d++)i.push(e.state.env.get(String(d))||"");let a="";for(let d=0;d<r;d++)a+=await n(e,t[d]);let o="";for(let d=r+1;d<t.length;d++)o+=await n(e,t[d]);let l=ve(e.state.env),u=De(e.state.env),c=ts(e.state.env);if(s===0){let d=a+o;return{values:d?[d]:[],quoted:!1}}let f;{let d=[];for(let p=0;p<i.length;p++){let h=i[p];p===0&&(h=a+h),p===i.length-1&&(h=h+o),d.push(h)}if(u)f=d.filter(p=>p!=="");else if(c){f=[];for(let p of d){if(p==="")continue;let h=fe(p,l,e.limits.maxArrayElements);Ie(f,h,e.limits.maxArrayElements,"unquoted expansion")}}else{f=[];for(let p of d)if(p==="")f.push("");else{let h=fe(p,l,e.limits.maxArrayElements);Ie(f,h,e.limits.maxArrayElements,"unquoted expansion")}for(;f.length>0&&f[f.length-1]==="";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await cs(e,f),quoted:!1}}async function Qu(e,t,n){e.coverage?.hit("bash:expansion:word_glob");let r=t.parts,{hasQuoted:s,hasCommandSub:i,hasArrayVar:a,hasArrayAtExpansion:o,hasParamExpansion:l,hasVarNamePrefixExpansion:u,hasIndirection:c}=fr(r),d=n.hasBraceExpansion(r)?await n.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return Hp(e,d,s);let p=await Gp(e,r,o,u,c,n);if(p!==null)return p;let h=await Qp(e,r,n);if(h!==null)return h;let m=await Kp(e,r,n);if(m!==null)return m;let E=await Yp(e,r,n.expandPart);if(E!==null)return Zu(e,E);if((i||a||l)&&!De(e.state.env)){let g=ve(e.state.env),y=n.buildIfsCharClassPattern(g),b=await n.smartWordSplit(e,r,g,y,n.expandPart);return Zu(e,b)}let S=await n.expandWordAsync(e,t);return Jp(e,t,r,S,s,n.expandWordForGlobbing)}async function Hp(e,t,n){let r=[];for(let s of t)if(!(!n&&s===""))if(!n&&!e.state.options.noglob&&Rt(s,e.state.shoptOptions.extglob)){let i=await fs(e,s);Ie(r,i,e.limits.maxArrayElements,"brace/glob expansion")}else r.push(s);return{values:r,quoted:!1}}async function Gp(e,t,n,r,s,i){if(n){let a=Cu(e,t);if(a!==null)return a}{let a=Nu(e,t);if(a!==null)return a}{let a=await vu(e,t);if(a!==null)return a}{let a=await ku(e,t,n,i.expandPart,i.expandWordPartsAsync);if(a!==null)return a}{let a=await xu(e,t,n,i.expandPart);if(a!==null)return a}{let a=await $u(e,t,i.evaluateArithmetic);if(a!==null)return a}{let a=Pu(e,t);if(a!==null)return a}{let a=await Su(e,t,i.expandWordPartsAsync,i.expandPart);if(a!==null)return a}{let a=await Au(e,t,i.expandWordPartsAsync,i.expandPart);if(a!==null)return a}if(r&&t.length===1&&t[0].type==="DoubleQuoted"){let a=Zp(e,t);if(a!==null)return a}{let a=await Ru(e,t,s,i.expandParameterAsync,i.expandWordPartsAsync);if(a!==null)return a}{let a=await Du(e,t);if(a!==null)return a}{let a=await Iu(e,t);if(a!==null)return a}return null}function Zp(e,t){let n=t[0];if(n.type!=="DoubleQuoted")return null;if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="VarNamePrefix"){let r=n.parts[0].operation,s=Wn(e,r.prefix);return r.star?{values:[s.join(Q(e.state.env))],quoted:!0}:{values:s,quoted:!0}}if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="ArrayKeys"){let r=n.parts[0].operation,i=G(e,r.array).map(([a])=>String(a));return r.star?{values:[i.join(Q(e.state.env))],quoted:!0}:{values:i,quoted:!0}}return null}async function Qp(e,t,n){{let r=await _u(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await Lu(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await Tu(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await Fu(e,t,n.expandPart);if(r!==null)return r}return null}async function Kp(e,t,n){{let r=await Mu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Bu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Wu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Vu(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await zu(e,t);if(r!==null)return r}{let r=await Uu(e,t);if(r!==null)return r}{let r=qu(e,t);if(r!==null)return r}{let r=ju(e,t);if(r!==null)return r}{let r=await Hu(e,t,n.expandPart);if(r!==null)return r}return null}function Gu(e){if(e.type!=="DoubleQuoted")return null;for(let t=0;t<e.parts.length;t++){let n=e.parts[t];if(n.type!=="ParameterExpansion"||n.operation)continue;let r=n.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(r)return{type:"array",name:r[1],atIndex:t,isStar:r[2]==="*"};if(n.parameter==="@"||n.parameter==="*")return{type:"positional",atIndex:t,isStar:n.parameter==="*"}}return null}async function Xp(e,t,n,r){let s="";for(let o=0;o<n.atIndex;o++)s+=await r(e,t.parts[o]);let i="";for(let o=n.atIndex+1;o<t.parts.length;o++)i+=await r(e,t.parts[o]);let a;if(n.type==="array"){if(a=G(e,n.name).map(([,l])=>l),a.length===0){let l=e.state.env.get(n.name);l!==void 0&&(a=[l])}}else{let o=Number.parseInt(e.state.env.get("#")||"0",10);a=[];for(let l=1;l<=o;l++)a.push(e.state.env.get(String(l))||"")}if(n.isStar){let o=Q(e.state.env),l=a.join(o);return[s+l+i]}if(a.length===0){let o=s+i;return o?[o]:[]}return a.length===1?[s+a[0]+i]:[s+a[0],...a.slice(1,-1),a[a.length-1]+i]}async function Yp(e,t,n){if(t.length<2)return null;let r=!1;for(let l of t)if(Gu(l)){r=!0;break}if(!r)return null;let s=ve(e.state.env),i=De(e.state.env),a=[];for(let l of t){let u=Gu(l);if(u&&l.type==="DoubleQuoted"){let c=await Xp(e,l,u,n);a.push(c)}else if(l.type==="DoubleQuoted"||l.type==="SingleQuoted"){let c=await n(e,l);a.push([c])}else if(l.type==="Literal")a.push([l.value]);else if(l.type==="ParameterExpansion"){let c=await n(e,l);if(i)a.push(c?[c]:[]);else{let f=fe(c,s,e.limits.maxArrayElements);a.push(f)}}else{let c=await n(e,l);if(i)a.push(c?[c]:[]);else{let f=fe(c,s,e.limits.maxArrayElements);a.push(f)}}}let o=[];for(let l of a)if(l.length!==0)if(o.length===0)Ie(o,l,e.limits.maxArrayElements,"word expansion");else{let u=o.length-1;o[u]=o[u]+l[0];for(let c=1;c<l.length;c++)o.push(l[c])}return o}async function Zu(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let n=[];for(let r of t)if(Rt(r,e.state.shoptOptions.extglob)){let s=await fs(e,r);Ie(n,s,e.limits.maxArrayElements,"glob expansion")}else n.push(r);return{values:n,quoted:!1}}async function fs(e,t){let n=new Jt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")}),r=await n.expand(t);if(r.length>0)return r;if(n.hasFailglob())throw new zt(t);return n.hasNullglob()?[]:[t]}async function Jp(e,t,n,r,s,i){let a=n.some(o=>o.type==="Glob");if(!e.state.options.noglob&&a){let o=await i(e,t);if(Rt(o,e.state.shoptOptions.extglob)){let u=await fs(e,o);if(u.length>0&&u[0]!==o)return{values:u,quoted:!1};if(u.length===0)return{values:[],quoted:!1}}let l=Zi(r);if(!De(e.state.env)){let u=ve(e.state.env);return{values:fe(l,u,e.limits.maxArrayElements),quoted:!1}}return{values:[l],quoted:!1}}if(!s&&!e.state.options.noglob&&Rt(r,e.state.shoptOptions.extglob)){let o=await i(e,t);if(Rt(o,e.state.shoptOptions.extglob)){let l=await fs(e,o);if(l.length>0&&l[0]!==o)return{values:l,quoted:!1}}}if(r===""&&!s)return{values:[],quoted:!1};if(a&&!s){let o=Zi(r);if(!De(e.state.env)){let l=ve(e.state.env);return{values:fe(o,l,e.limits.maxArrayElements),quoted:!1}}return{values:[o],quoted:!1}}return{values:[r],quoted:s}}function Te(e,t,n){if(t.length>=e.limits.maxArrayElements)throw new P(`word splitting element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");t.push(n)}async function Xu(e,t){let n=t.operation;if(!n||n.type!=="DefaultValue"&&n.type!=="AssignDefault"&&n.type!=="UseAlternative")return null;let r=n.word;if(!r||r.parts.length===0)return null;let s=await Nt(e,t.parameter),a=await ae(e,t.parameter,!1)==="",o=n.checkEmpty??!1,l;return n.type==="UseAlternative"?l=s&&!(o&&a):l=!s||o&&a,l?r.parts:null}function eh(e){return e.type==="SingleQuoted"?!0:e.type==="DoubleQuoted"?e.parts.every(n=>n.type==="Literal"):!1}async function th(e,t){if(t.type!=="ParameterExpansion")return null;let n=await Xu(e,t);if(!n||n.length<=1)return null;let r=n.some(i=>eh(i)),s=n.some(i=>i.type==="Literal"||i.type==="ParameterExpansion"||i.type==="CommandSubstitution"||i.type==="ArithmeticExpansion");return r&&s?n:null}function nh(e){return e.type==="DoubleQuoted"||e.type==="SingleQuoted"||e.type==="Literal"?!1:e.type==="Glob"?Wi(e.pattern):!(!(e.type==="ParameterExpansion"||e.type==="CommandSubstitution"||e.type==="ArithmeticExpansion")||e.type==="ParameterExpansion"&&Zl(e))}async function Yu(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:word_split"),t.length===1&&t[0].type==="ParameterExpansion"){let d=t[0],p=await Xu(e,d);if(p&&p.length>0&&p.length>1&&p.some(m=>m.type==="DoubleQuoted"||m.type==="SingleQuoted")&&p.some(m=>m.type==="Literal"||m.type==="ParameterExpansion"||m.type==="CommandSubstitution"||m.type==="ArithmeticExpansion"))return Ku(e,p,n,r,s)}let i=[],a=!1;for(let d of t){let p=nh(d),h=d.type==="DoubleQuoted"||d.type==="SingleQuoted",m=p?await th(e,d):null,E=await s(e,d);i.push({value:E,isSplittable:p,isQuoted:h,mixedDefaultParts:m??void 0}),p&&(a=!0)}if(!a){let d=i.map(p=>p.value).join("");return d?[d]:[]}let o=[],l="",u=!1,c=!1,f=!1;for(let d of i)if(!d.isSplittable)c?d.isQuoted&&d.value===""?(l!==""&&Te(e,o,l),Te(e,o,""),u=!0,l="",c=!1,f=!0):d.value!==""?(l!==""&&Te(e,o,l),l=d.value,c=!1,f=!1):(l+=d.value,f=!1):(l+=d.value,f=d.isQuoted&&d.value==="");else if(d.mixedDefaultParts){let p=await Ku(e,d.mixedDefaultParts,n,r,s);if(p.length!==0)if(p.length===1)l+=p[0],u=!0;else{l+=p[0],Te(e,o,l),u=!0;for(let h=1;h<p.length-1;h++)Te(e,o,p[h]);l=p[p.length-1]}c=!1,f=!1}else{let{words:p,hadLeadingDelimiter:h,hadTrailingDelimiter:m}=ns(d.value,n,e.limits.maxArrayElements);if(f&&h&&l===""&&(Te(e,o,""),u=!0),p.length===0)m&&(c=!0);else if(p.length===1)l+=p[0],u=!0,c=m;else{l+=p[0],Te(e,o,l),u=!0;for(let E=1;E<p.length-1;E++)Te(e,o,p[E]);l=p[p.length-1],c=m}f=!1}return l!==""?Te(e,o,l):o.length===0&&u&&Te(e,o,""),o}function rh(e,t){return e.length>0&&t.includes(e[0])}async function Ku(e,t,n,r,s){let i=[];for(let c of t){let d=!(c.type==="DoubleQuoted"||c.type==="SingleQuoted"),p=await s(e,c);i.push({value:p,isSplittable:d})}let a=[],o="",l=!1,u=!1;for(let c of i)if(!c.isSplittable)u&&c.value!==""?(o!==""&&Te(e,a,o),o=c.value,u=!1):o+=c.value;else{rh(c.value,n)&&o!==""&&(Te(e,a,o),o="",l=!0);let{words:d,hadTrailingDelimiter:p}=ns(c.value,n,e.limits.maxArrayElements);if(d.length===0)p&&(u=!0);else if(d.length===1)o+=d[0],l=!0,u=p;else{o+=d[0],Te(e,a,o),l=!0;for(let h=1;h<d.length-1;h++)Te(e,a,d[h]);o=d[d.length-1],u=p}}return o!==""?Te(e,a,o):a.length===0&&l&&Te(e,a,""),a}function Ju(e){switch(e.type){case"Literal":return e.value;case"SingleQuoted":return e.value;case"Escaped":return e.value;default:return null}}function ec(e){switch(e.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return e.value==="";default:return!1}}var hr=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new kt,t?.mounts)for(let{mountPoint:n,filesystem:r}of t.mounts)this.mount(n,r)}mount(t,n){this.validateMountPath(t);let r=U(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(t){let n=U(t);if(!this.mounts.has(n))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(n)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}diff(t){let n=t?.space??"vfs",r=[],s=[],i=[];for(let a of this.mounts.values()){let o=a.filesystem;if(typeof o.diff!="function")throw new N("EINVAL",`mounted filesystem at '${a.mountPoint}' does not support diff()`);let l=o.diff(),u=c=>{if(n==="vfs")return a.mountPoint==="/"?c:`${a.mountPoint}${c}`;if(typeof o.rootDir!="string")throw new N("EINVAL",`cannot produce a host-space diff: mount at '${a.mountPoint}' has no real root`);return`${o.rootDir}${c}`};for(let c of l.writes)r.push({...c,path:u(c.path)});for(let c=0;c<l.deletions.length;c++)s.push(u(l.deletions[c])),i.push(l.deletionChangedAt?.[c]??0)}return{writes:r,deletions:s,...i.length>0&&{deletionChangedAt:i}}}restamp(t,n,r="full"){let{fs:s,relativePath:i}=this.routePath(t),a=s.restamp;typeof a=="function"&&a.call(s,i,n,r)}isMountPoint(t){let n=U(t);return this.mounts.has(n)}validateMountPath(t){let n=t.split("/");for(let r of n)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let n of this.mounts.keys())if(n!==t){if(t.startsWith(`${n}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${n}'`);if(n.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${n}'`)}}routePath(t){X(t,"access");let n=U(t),r=null,s=0;for(let i of this.mounts.values()){let a=i.mountPoint;if(n===a)return{fs:i.filesystem,relativePath:"/"};n.startsWith(`${a}/`)&&a.length>s&&(r=i,s=a.length)}if(r){let i=n.slice(s);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:n}}getChildMountPoints(t){let n=U(t),r=n==="/"?"/":`${n}/`,s=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let o=i.slice(r.length).split("/")[0];o&&!s.includes(o)&&s.push(o)}return s}async readFile(t,n){let{fs:r,relativePath:s}=this.routePath(t);return r.readFile(s,n)}async readFileBytes(t){let{fs:n,relativePath:r}=this.routePath(t);return Cn(n,r)}async readFileBuffer(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readFileBuffer(r)}async writeFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.writeFile(i,n,r)}async appendFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.appendFile(i,n,r)}async exists(t){let n=U(t);if(this.mounts.has(n)||this.getChildMountPoints(n).length>0)return!0;let{fs:s,relativePath:i}=this.routePath(t);return s.exists(i)}async stat(t){let n=U(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:ht,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.stat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:ht,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.stat(a)}async lstat(t){let n=U(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:ht,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.lstat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:ht,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.lstat(a)}async mkdir(t,n){let r=U(t);if(this.mounts.has(r)){if(n?.recursive)return;throw new N("EEXIST",`directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&n?.recursive)return;let{fs:i,relativePath:a}=this.routePath(t);return i.mkdir(a,n)}async readdir(t){let n=U(t),r=new Set,s=null,{fs:i,relativePath:a}=this.routePath(t);try{let l=await i.readdir(a);for(let u of l)r.add(u)}catch(l){if(!yn(l,"ENOENT"))throw l;s=l}let o=this.getChildMountPoints(n);for(let l of o)r.add(l);if(r.size===0&&s&&!this.mounts.has(n))throw s;return Array.from(r).sort()}async rm(t,n){let r=U(t);if(this.mounts.has(r))throw new N("EBUSY",`mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new N("EBUSY",`contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:a}=this.routePath(t);return i.rm(a,n)}async cp(t,n,r){if((await this.stat(t)).isDirectory&&Tt(t,n))throw new N("EINVAL",`cannot copy '${t}' into itself, '${n}'`);let i=this.routePath(t),a=this.routePath(n);return i.fs===a.fs?i.fs.cp(i.relativePath,a.relativePath,r):this.crossMountCopy(t,n,r)}async mv(t,n){let r=U(t);if((await this.stat(t)).isDirectory&&Tt(t,n))throw new N("EINVAL",`cannot move '${t}' into itself, '${n}'`);if(this.mounts.has(r))throw new N("EBUSY",`mount point, cannot move '${t}'`);let i=this.routePath(t),a=this.routePath(n);if(i.fs===a.fs)return i.fs.mv(i.relativePath,a.relativePath);await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return Dn(t,n)}getAllPaths(){let t=new Set;for(let n of this.baseFs.getAllPaths())t.add(n);for(let n of this.mounts.keys()){let r=n.split("/").filter(Boolean),s="";for(let a of r)s=`${s}/${a}`,t.add(s);let i=this.mounts.get(n);if(i)for(let a of i.filesystem.getAllPaths())a==="/"?t.add(n):t.add(`${n}${a}`)}return Array.from(t).sort()}async chmod(t,n){let r=U(t),s=this.mounts.get(r);if(s)return s.filesystem.chmod("/",n);let{fs:i,relativePath:a}=this.routePath(t);return i.chmod(a,n)}async symlink(t,n){let{fs:r,relativePath:s}=this.routePath(n);return r.symlink(t,s)}async link(t,n){let r=this.routePath(t),s=this.routePath(n);if(r.fs!==s.fs)throw new N("EXDEV",`cross-device link not permitted, link '${t}' -> '${n}'`);return r.fs.link(r.relativePath,s.relativePath)}async readlink(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readlink(r)}async realpath(t){let n=U(t);if(this.mounts.get(n))return n;let{fs:s,relativePath:i}=this.routePath(t),a=await s.realpath(i);for(let[o,l]of this.mounts)if(n===o||n.startsWith(`${o}/`))return a==="/"?o:`${o}${a}`;return a}async crossMountCopy(t,n,r){let s=await this.lstat(t);if(s.isFile){let i=await this.readFileBuffer(t);await this.writeFile(n,i),await this.chmod(n,s.mode)}else if(s.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(n,{recursive:!0});let i=await this.readdir(t);for(let a of i){let o=Ft(t,a),l=Ft(n,a);await this.crossMountCopy(o,l,r)}}else if(s.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,n)}}async utimes(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.utimes(i,n,r)}};var ds="/dev/fd",nc=63,sh=10,tc=nc-sh+1,Ji=class extends kt{isLiveDescriptor;constructor(t){super(),this.isLiveDescriptor=t}assertLiveDescriptor(t,n){this.isLiveDescriptor(t)||this.refuse(t,n)}refuse(t,n){throw new N("EROFS",`read-only file system, ${n} '${ds}${t}'`)}async writeFile(t,n,r){return this.assertLiveDescriptor(t,"write"),super.writeFile(t,n,r)}async appendFile(t,n,r){return this.assertLiveDescriptor(t,"append"),super.appendFile(t,n,r)}async rm(t,n){return this.assertLiveDescriptor(t,"rm"),super.rm(t,n)}async mkdir(t,n){this.refuse(t,"mkdir")}async cp(t,n){this.refuse(n,"cp")}async mv(t,n){this.refuse(n,"mv")}async symlink(t,n){this.refuse(n,"symlink")}async link(t,n){this.refuse(n,"link")}async chmod(t,n){this.refuse(t,"chmod")}async utimes(t,n,r){this.refuse(t,"utimes")}};function ih(e){let t=new Ji(n=>rc(e).some(r=>r.path===`${ds}${n}`));e.fs=new hr({base:e.fs,mounts:[{mountPoint:ds,filesystem:t}]}),e.state.processSubstitutionFsMounted=!0}async function ah(e,t,n){try{await e.fs.writeFile(t,n,"binary");return}catch(r){if(e.state.processSubstitutionFsMounted)throw r;ih(e)}await e.fs.writeFile(t,n,"binary")}async function oh(e,t){try{await e.fs.rm(t,{force:!0})}catch{}}function rc(e){let t=e.state.processSubstitutions;if(t)return t;let n=[];return e.state.processSubstitutions=n,n}async function sc(e,t,n){let r=e.substitutionDepth??0,s=e.limits.maxSubstitutionDepth;if(r>=s)throw new P(`Process substitution nesting limit exceeded (${s})`,"substitution_depth");let i=e.substitutionDepth,a=new Map(e.state.env),o=at(e.state.arrays),l=e.state.cwd,u=e.state.bashPid,c=e.state.suppressVerbose,f=e.state.groupStdin,d=e.state.lastExitCode,p=e.state.env.get("?");e.substitutionDepth=r+1,e.state.bashPid=e.state.nextVirtualPid++,e.state.suppressVerbose=!0,n!==void 0&&(e.state.groupStdin=n);let h;try{h=await e.executeScript(t)}catch(m){if(m instanceof P)throw m;if(m instanceof q)return{stdout:m.stdout,stderr:m.stderr,exitCode:m.exitCode};throw m}finally{e.substitutionDepth=i,e.state.env=a,e.state.arrays=o,e.state.cwd=l,e.state.bashPid=u,e.state.suppressVerbose=c,e.state.groupStdin=f,e.state.lastExitCode=d,p!==void 0?e.state.env.set("?",p):e.state.env.delete("?")}return h}async function ic(e,t){let n=rc(e);if(n.length>=tc)throw new P(`Process substitution limit exceeded (${tc} concurrent)`,"file_descriptors");let r="";if(t.direction==="input"){let a=await sc(e,t.body,void 0);if(a.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+a.stderr),r=Wt(a),r.length>e.limits.maxStringLength)throw new P(`process substitution: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")}let s=nc-n.length,i=`${ds}/${s}`;n.push({fd:s,path:i,direction:t.direction,body:t.body});try{await ah(e,i,r)}catch(a){throw n.pop(),a}return i}function ac(e){return e.state.processSubstitutions?.length??0}var lh={stdout:"",stderr:""};async function ea(e,t){let n=e.state.processSubstitutions;if(!n||n.length<=t)return lh;let r="",s="";for(;n.length>t;){let i=n[n.length-1],a="";if(i.direction==="output")try{a=await Cn(e.fs,i.path)}catch{}if(await oh(e,i.path),n.pop(),i.direction==="output"){let o=await sc(e,i.body,a);r+=Wt(o),s+=o.stderr}}return{stdout:r,stderr:s}}function rn(e,t,n){if(e.length>t)throw new P(`${n}: string length limit exceeded (${t} bytes)`,"string_length")}async function Et(e,t,n=!1){let r=[];for(let s of t)r.push(await tt(e,s,n));return r.join("")}function uh(e){return ec(e)}function lc(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!uh(t))return!1;return!0}function ch(e,t,n=!1){let r=Ju(t);if(r!==null)return r;switch(t.type){case"TildeExpansion":return n?t.user===null?"~":`~${t.user}`:(e.coverage?.hit("bash:expansion:tilde"),t.user===null?e.state.env.get("HOME")??"/home/user":t.user==="root"?"/root":`~${t.user}`);case"Glob":return Qi(e,t.pattern);default:return null}}async function ie(e,t){return na(e,t)}async function uc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped")n.push(Bn(r.value));else if(r.type==="SingleQuoted")n.push(r.value);else if(r.type==="DoubleQuoted"){let s=await Et(e,r.parts);n.push(s)}else if(r.type==="TildeExpansion"){let s=await tt(e,r);n.push(Bn(s))}else n.push(await tt(e,r));return n.join("")}async function cc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped"){let s=r.value;"()|*?[]".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="SingleQuoted")n.push(et(r.value));else if(r.type==="DoubleQuoted"){let s=await Et(e,r.parts);n.push(et(s))}else n.push(await tt(e,r));return n.join("")}async function fc(e,t){let n=[];for(let r of t.parts)if(r.type==="SingleQuoted")n.push(et(r.value));else if(r.type==="Escaped"){let s=r.value;"*?[]\\()|".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="DoubleQuoted"){let s=await Et(e,r.parts);n.push(et(s))}else r.type==="Glob"?wu(r.pattern)?n.push(await bu(e,r.pattern)):n.push(Qi(e,r.pattern)):r.type==="Literal"?n.push(r.value):n.push(await tt(e,r));return n.join("")}function hs(e){for(let t of e)if(t.type==="BraceExpansion"||t.type==="DoubleQuoted"&&hs(t.parts))return!0;return!1}var oc=1e5;async function dc(e,t,n={count:0}){let r=()=>{n.count++,e.executionScope.consumeLimited("brace_operations",1,Math.min(oc,e.limits.maxBraceExpansionResults),"brace expansion")},s=(a,o)=>{if(a.length>=e.limits.maxBraceExpansionResults)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),a.push(o)},i=[[]];for(let a of t)if(a.type==="BraceExpansion"){let o=[],l=!1,u="";for(let d of a.items)if(d.type==="Range"){let p=Gi(d.start,d.end,d.step,d.startStr,d.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(p.expanded)for(let h of p.expanded)s(o,h);else{l=!0,u=p.literal;break}}else{let p=await dc(e,d.word.parts,n);for(let h of p){let m=[];for(let E of h)typeof E=="string"?m.push(E):m.push(await tt(e,E));s(o,m.join(""))}}if(l){for(let d of i)r(),d.push(u);continue}if(i.length*o.length>e.limits.maxBraceExpansionResults||n.count>oc)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");let f=[];for(let d of i)for(let p of o){if(f.length>=e.limits.maxBraceExpansionResults)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),f.push([...d,p])}i=f}else for(let o of i)r(),o.push(a);return i}async function pc(e,t){let n=t.parts;if(!hs(n))return[await ie(e,t)];let r=await dc(e,n),s=[];for(let i of r){let a=[];for(let o of i)typeof o=="string"?a.push(o):a.push(await tt(e,o));s.push(Ki(e,a.join("")))}return s}function fh(){return{expandWordAsync:na,expandWordForGlobbing:fc,expandWordWithBracesAsync:pc,expandWordPartsAsync:Et,expandPart:tt,expandParameterAsync:ps,hasBraceExpansion:hs,evaluateArithmetic:Y,buildIfsCharClassPattern:Ql,smartWordSplit:Yu}}async function bt(e,t){return Qu(e,t,fh())}function dh(e){for(let t of e){if(t.type==="ParameterExpansion")return t.parameter;if(t.type==="Literal")return t.value}return""}function ta(e,t){if(Number.parseInt(e.state.env.get("#")||"0",10)<2)return!1;function r(s){for(let i of s)if(i.type==="DoubleQuoted"){for(let a of i.parts)if(a.type==="ParameterExpansion"&&a.parameter==="@"&&!a.operation)return!0}return!1}return r(t.parts)}async function hc(e,t){if(ta(e,t))return{error:`bash: $@: ambiguous redirect
|
|
108
|
+
`};let n=t.parts,{hasQuoted:r}=fr(n);if(hs(n)&&(await pc(e,t)).length>1)return{error:`bash: ${n.map(p=>p.type==="Literal"?p.value:p.type==="BraceExpansion"?`{${p.items.map(m=>{if(m.type==="Range"){let E=m.step?`..${m.step}`:"";return`${m.startStr??m.start}..${m.endStr??m.end}${E}`}return m.word.parts.map(E=>E.type==="Literal"?E.value:"").join("")}).join(",")}}`:"").join("")}: ambiguous redirect
|
|
109
|
+
`};let s=await na(e,t),{hasParamExpansion:i,hasCommandSub:a}=fr(n);if((i||a)&&!r&&!De(e.state.env)){let f=ve(e.state.env);if(fe(s,f,e.limits.maxArrayElements).length>1)return{error:`bash: $${dh(n)}: ambiguous redirect
|
|
110
|
+
`}}if(r||e.state.options.noglob||n.some(f=>f.type==="ProcessSubstitution"))return{target:s};let l=await fc(e,t);if(!Rt(l,e.state.shoptOptions.extglob))return{target:s};let u=new Jt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")}),c=await u.expand(l);return c.length===0?u.hasFailglob()?{error:`bash: no match: ${s}
|
|
111
111
|
`}:{target:s}:c.length===1?{target:c[0]}:{error:`bash: ${s}: ambiguous redirect
|
|
112
|
-
`}}async function
|
|
113
|
-
`,0;let p=Math.max(...c.map(([h])=>typeof h=="number"?h:0))+1+
|
|
114
|
-
`,0;
|
|
115
|
-
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new
|
|
116
|
-
`);n=r}throw new
|
|
117
|
-
`)}catch{return
|
|
118
|
-
`)}}let c=u||"/";if(s)try{c=await e.fs.realpath(c)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=c,e.state.env.set("PWD",e.state.cwd),e.state.env.set("OLDPWD",e.state.previousDir),
|
|
119
|
-
`:"")}function
|
|
120
|
-
`,!1;if(
|
|
121
|
-
`,!1}return
|
|
122
|
-
`,2):
|
|
123
|
-
`,2):
|
|
124
|
-
`,2):
|
|
125
|
-
`)&&!s&&!i){
|
|
112
|
+
`}}async function na(e,t){let n=t.parts,r=n.length;if(r===1){let a=await tt(e,n[0]);return rn(a,e.limits.maxStringLength,"word expansion"),a}let s=[];for(let a=0;a<r;a++)s.push(await tt(e,n[a]));let i=s.join("");return rn(i,e.limits.maxStringLength,"word expansion"),i}async function tt(e,t,n=!1){if(t.type==="ParameterExpansion")return ps(e,t,n);let r=ch(e,t,n);if(r!==null)return r;switch(t.type){case"DoubleQuoted":{let s=[];for(let i of t.parts)s.push(await tt(e,i,!0));return s.join("")}case"CommandSubstitution":{let s=nu(t.body);if(s)try{let p=await ie(e,s.target),h=p.startsWith("/")?p:`${e.state.cwd}/${p}`,m=await e.fs.readFile(h);e.state.lastExitCode=0,e.state.env.set("?","0");let E=m.replace(/\n+$/,"");return rn(E,e.limits.maxStringLength,"command substitution"),E}catch(p){if(p instanceof P)throw p;return e.state.lastExitCode=1,e.state.env.set("?","1"),""}let i=e.substitutionDepth??0,a=e.limits.maxSubstitutionDepth;if(i>=a)throw new P(`Command substitution nesting limit exceeded (${a})`,"substitution_depth");let o=e.substitutionDepth;e.substitutionDepth=i+1;let l=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let u=new Map(e.state.env),c=at(e.state.arrays),f=e.state.cwd,d=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let p=await e.executeScript(t.body),h=p.exitCode;e.state.env=u,e.state.arrays=c,e.state.cwd=f,e.state.suppressVerbose=d,e.state.lastExitCode=h,e.state.env.set("?",String(h)),p.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+p.stderr),e.state.bashPid=l,e.substitutionDepth=o;let m=p.stdout.replace(/\n+$/,"");return rn(m,e.limits.maxStringLength,"command substitution"),m}catch(p){if(e.state.env=u,e.state.arrays=c,e.state.cwd=f,e.state.bashPid=l,e.substitutionDepth=o,e.state.suppressVerbose=d,p instanceof P)throw p;if(p instanceof q){e.state.lastExitCode=p.exitCode,e.state.env.set("?",String(p.exitCode)),p.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+p.stderr);let h=p.stdout.replace(/\n+$/,"");return rn(h,e.limits.maxStringLength,"command substitution"),h}throw p}}case"ProcessSubstitution":return ic(e,t);case"ArithmeticExpansion":{let s=t.expression.originalText;if(s&&/\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(s)){let a=await tu(e,s),o=new H,l=se(o,a);return String(await Y(e,l.expression,!0))}return String(await Y(e,t.expression.expression,!0))}case"BraceExpansion":{let s=[];for(let i of t.items)if(i.type==="Range"){let a=Gi(i.start,i.end,i.step,i.startStr,i.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(a.expanded)s.push(...a.expanded);else return a.literal}else s.push(await ie(e,i.word));return s.join(" ")}default:return""}}async function ps(e,t,n=!1){let{parameter:r}=t,{operation:s}=t,i=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let[,d,p]=i;if(e.state.associativeArrays?.has(d)||p.includes("$(")||p.includes("`")||p.includes("${")){let m=await ji(e,p);r=`${d}[${m}]`}}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&ue(e,r)){let d=Be(e,r);if(d&&d!==r){let p=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(p){let[,h,m]=p;if(e.state.associativeArrays?.has(h)||m.includes("$(")||m.includes("`")||m.includes("${")){let S=await ji(e,m);r=`${h}[${S}]`}}}}let a=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),o=await ae(e,r,!a);if(!s)return o;let l=!await Nt(e,r),{isEmpty:u,effectiveValue:c}=gu(e,r,o,n),f={value:o,isUnset:l,isEmpty:u,effectiveValue:c,inDoubleQuotes:n};switch(s.type){case"DefaultValue":return su(e,s,f,Et);case"AssignDefault":return iu(e,r,s,f,Et);case"ErrorIfUnset":return au(e,r,s,f,Et);case"UseAlternative":return ou(e,s,f,Et);case"PatternRemoval":{let d=await lu(e,o,s,Et,tt);return rn(d,e.limits.maxStringLength,"pattern removal"),d}case"PatternReplacement":{let d=await uu(e,o,s,Et,tt);return rn(d,e.limits.maxStringLength,"pattern replacement"),d}case"Length":return cu(e,r,o);case"LengthSliceError":throw new Xe(r);case"BadSubstitution":throw new Xe(s.text);case"Substring":return fu(e,r,o,s);case"CaseModification":{let d=await du(e,o,s,Et,ps);return rn(d,e.limits.maxStringLength,"case modification"),d}case"Transform":return pu(e,r,o,l,s);case"Indirection":return hu(e,r,o,l,s,ps,n);case"ArrayKeys":return mu(e,s);case"VarNamePrefix":return yu(e,s);default:return o}}function yc(){return{visited:new Set,depth:0}}function ph(e,t,n){switch(n){case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":if(t===0)throw new le("division by 0");return Math.trunc(e/t);case"%":if(t===0)throw new le("division by 0");return e%t;case"**":if(t<0)throw new le("exponent less than 0");return e**t;case"<<":return e<<t;case">>":return e>>t;case"<":return e<t?1:0;case"<=":return e<=t?1:0;case">":return e>t?1:0;case">=":return e>=t?1:0;case"==":return e===t?1:0;case"!=":return e!==t?1:0;case"&":return e&t;case"|":return e|t;case"^":return e^t;case",":return t;default:return 0}}function mc(e,t,n){switch(n){case"=":return t;case"+=":return e+t;case"-=":return e-t;case"*=":return e*t;case"/=":return t!==0?Math.trunc(e/t):0;case"%=":return t!==0?e%t:0;case"<<=":return e<<t;case">>=":return e>>t;case"&=":return e&t;case"|=":return e|t;case"^=":return e^t;default:return t}}function hh(e,t){switch(t){case"-":return-e;case"+":return+e;case"!":return e===0?1:0;case"~":return~e;default:return e}}async function mh(e,t){let n=e.state.env.get(t);if(n!==void 0)return n;let r=oe(e,t,0);return r!==void 0?r:await ae(e,t)}async function yh(e,t,n){if(!t)return 0;let r=Number.parseInt(t,10);if(!Number.isNaN(r)&&/^-?\d+$/.test(t.trim()))return r;let s=t.trim();if(!s)return 0;let i=new H,{expr:a,pos:o}=Mn(i,s,0);if(o<s.length){let l=s.slice(o).trim(),u=l.split(/\s+/)[0]||l;throw new le(`syntax error in expression (error token is "${u}")`,"","")}return await zn(e,a,!1,n)}async function ms(e,t,n,r){if(r.depth>100)throw new le("maximum variable indirection depth exceeded");if(r.visited.has(t))throw new le(`arithmetic variable cycle detected at ${t}`);r.visited.add(t),r.depth++;try{return await yh(e,n,r)}finally{r.depth--,r.visited.delete(t)}}async function ra(e,t,n){if(n.depth>100)throw new le("maximum variable indirection depth exceeded");if(n.visited.has(t))throw new le(`arithmetic variable cycle detected at ${t}`);n.visited.add(t),n.depth++;try{let r=await mh(e,t);if(!r)return 0;let s=Number.parseInt(r,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(r.trim()))return s;let i=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return await ra(e,i,n);let a=new H,{expr:o,pos:l}=Mn(a,i,0);if(l<i.length){let u=i.slice(l).trim(),c=u.split(/\s+/)[0]||u;throw new le(`${i}: syntax error in expression (error token is "${c}")`)}return await zn(e,o,!1,n)}finally{n.depth--,n.visited.delete(t)}}async function ys(e,t){if(t.startsWith("#")){let f=t.slice(1),d=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let h=d[1],m=G(e,h);return String(m.length)}let p=e.state.env.get(f)||"";return String(p.length)}if(t.startsWith("!")){let f=t.slice(1),d=e.state.env.get(f)||"";return e.state.env.get(d)||""}let n=[":-",":=",":?",":+","-","=","?","+"],r=-1,s="";for(let f of n){let d=t.indexOf(f);d>0&&(r===-1||d<r)&&(r=d,s=f)}if(r===-1)return await ae(e,t);let i=t.slice(0,r),a=t.slice(r+s.length),o=e.state.env.get(i),l=o===void 0,u=o==="",c=s.startsWith(":");switch(s){case":-":case"-":return l||c&&u?a:o||"";case":=":case"=":return l||c&&u?(e.state.env.set(i,a),a):o||"";case":+":case"+":return!(l||c&&u)?a:"";case":?":case"?":{if(l||c&&u)throw new Error(a||`${i}: parameter null or not set`);return o||""}default:return o||""}}async function Y(e,t,n=!1){return zn(e,t,n,yc())}async function zn(e,t,n,r){let s=(i,a=n)=>zn(e,i,a,r);switch(t.type){case"ArithNumber":if(Number.isNaN(t.value))throw new le("value too great for base");return t.value;case"ArithVariable":return await ra(e,t.name,r);case"ArithSpecialVar":{let a=(await ae(e,t.name)).trim();if(!a)return 0;let o=Number.parseInt(a,10);if(!Number.isNaN(o)&&/^-?\d+$/.test(a))return o;let l=new H,{expr:u}=Mn(l,a,0);return await s(u)}case"ArithNested":return await s(t.expression);case"ArithCommandSubst":{if(e.execFn){let i=await e.execFn(t.command,{signal:e.state.signal});i.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+i.stderr);let a=i.stdout.trim();return Number.parseInt(a,10)||0}return 0}case"ArithBracedExpansion":{let i=await ys(e,t.content);return Number.parseInt(i,10)||0}case"ArithDynamicBase":{let i=await ys(e,t.baseExpr),a=Number.parseInt(i,10);if(a<2||a>64)return 0;let o=`${a}#${t.value}`;return or(o)}case"ArithDynamicNumber":{let a=await ys(e,t.prefix)+t.suffix;return or(a)}case"ArithArrayElement":{let i=e.state.associativeArrays?.has(t.array),a=async o=>{let l=oe(e,t.array,o);return l!==void 0?await ms(e,`${t.array}[${o}]`,l,r):0};if(t.stringKey!==void 0)return await a(t.stringKey);if(i&&t.index?.type==="ArithVariable"&&!t.index.hasDollarPrefix)return await a(t.index.name);if(i&&t.index?.type==="ArithVariable"&&t.index.hasDollarPrefix){let o=await ae(e,t.index.name);return await a(o)}if(t.index){let o=await s(t.index);if(o<0){let c=G(e,t.array),f=e.state.currentLine;if(c.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${t.array}: bad array subscript
|
|
113
|
+
`,0;let p=Math.max(...c.map(([h])=>typeof h=="number"?h:0))+1+o;if(p<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${t.array}: bad array subscript
|
|
114
|
+
`,0;o=p}let l=`${t.array}[${o}]`,u=oe(e,t.array,o);if(u!==void 0)return ms(e,l,u,r);if(o===0){let c=e.state.env.get(t.array);if(c!==void 0)return ms(e,t.array,c,r)}if(e.state.options.nounset&&!(e.state.env.has(t.array)||Ne(e,t.array)))throw new Ue(`${t.array}[${o}]`);return 0}return 0}case"ArithDoubleSubscript":throw new le("double subscript","","");case"ArithNumberSubscript":throw new le(`${t.number}${t.errorToken}: syntax error: invalid arithmetic operator (error token is "${t.errorToken}")`);case"ArithSyntaxError":throw new le(t.message,"","",!0);case"ArithSingleQuote":{if(n)throw new le(`syntax error: operand expected (error token is "'${t.content}'")`);return t.value}case"ArithBinary":{if(t.operator==="||")return await s(t.left)||await s(t.right)?1:0;if(t.operator==="&&")return await s(t.left)&&await s(t.right)?1:0;let i=await s(t.left),a=await s(t.right);return ph(i,a,t.operator)}case"ArithUnary":{let i=await s(t.operand);if(t.operator==="++"||t.operator==="--"){if(t.operand.type==="ArithVariable"){let a=t.operand.name,o=Number.parseInt(await ae(e,a),10)||0,l=t.operator==="++"?o+1:o-1;return e.state.env.set(a,String(l)),t.prefix?l:o}if(t.operand.type==="ArithArrayElement"){let a=t.operand.array,o=e.state.associativeArrays?.has(a),l;if(t.operand.stringKey!==void 0)l=t.operand.stringKey;else if(o&&t.operand.index?.type==="ArithVariable"&&!t.operand.index.hasDollarPrefix)l=t.operand.index.name;else if(o&&t.operand.index?.type==="ArithVariable"&&t.operand.index.hasDollarPrefix)l=await ae(e,t.operand.index.name);else if(t.operand.index){let f=await s(t.operand.index);l=String(f)}else return i;let u=Number.parseInt(oe(e,a,l)||"0",10)||0,c=t.operator==="++"?u+1:u-1;return j(e,a,l,String(c),o?"associative":"indexed"),t.prefix?c:u}if(t.operand.type==="ArithConcat"){let a="";for(let o of t.operand.parts)a+=await Vn(e,o,n,r);if(a&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){let o=Number.parseInt(e.state.env.get(a)||"0",10)||0,l=t.operator==="++"?o+1:o-1;return e.state.env.set(a,String(l)),t.prefix?l:o}}if(t.operand.type==="ArithDynamicElement"){let a="";if(t.operand.nameExpr.type==="ArithConcat")for(let o of t.operand.nameExpr.parts)a+=await Vn(e,o,n,r);else t.operand.nameExpr.type==="ArithVariable"&&(a=t.operand.nameExpr.hasDollarPrefix?await ae(e,t.operand.nameExpr.name):t.operand.nameExpr.name);if(a&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){let o=await s(t.operand.subscript),l=Number.parseInt(oe(e,a,o)||"0",10)||0,u=t.operator==="++"?l+1:l-1;return j(e,a,o,String(u)),t.prefix?u:l}}return i}return hh(i,t.operator)}case"ArithTernary":return await s(t.condition)?await s(t.consequent):await s(t.alternate);case"ArithAssignment":{let i=t.variable,a=i,o;if(t.stringKey!==void 0)o=t.stringKey;else if(t.subscript){let d=e.state.associativeArrays?.has(i);if(d&&t.subscript.type==="ArithVariable"&&!t.subscript.hasDollarPrefix)o=t.subscript.name;else if(d&&t.subscript.type==="ArithVariable"&&t.subscript.hasDollarPrefix)o=await ae(e,t.subscript.name)||"\\";else if(d){let p=await s(t.subscript);o=String(p)}else{let p=await s(t.subscript);if(p<0){let h=G(e,i);h.length>0&&(p=Math.max(...h.map(([E])=>typeof E=="number"?E:0))+1+p)}o=String(p)}}let l=o===void 0?e.state.env.get(a):oe(e,i,o),u=Number.parseInt(l||"0",10)||0,c=await s(t.value),f=mc(u,c,t.operator);return o===void 0?e.state.env.set(a,String(f)):j(e,i,o,String(f),e.state.associativeArrays?.has(i)?"associative":"indexed"),f}case"ArithGroup":return await s(t.expression);case"ArithConcat":{let i="";for(let a of t.parts)i+=await Vn(e,a,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?await ra(e,i,r):Number.parseInt(i,10)||0}case"ArithDynamicAssignment":{let i="";if(t.target.type==="ArithConcat")for(let c of t.target.parts)i+=await Vn(e,c,n,r);else t.target.type==="ArithVariable"&&(i=t.target.hasDollarPrefix?await ae(e,t.target.name):t.target.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let a=i;if(t.subscript){let c=await s(t.subscript);a=`${i}_${c}`}let o=Number.parseInt(e.state.env.get(a)||"0",10)||0,l=await s(t.value),u=mc(o,l,t.operator);return e.state.env.set(a,String(u)),u}case"ArithDynamicElement":{let i="";if(t.nameExpr.type==="ArithConcat")for(let u of t.nameExpr.parts)i+=await Vn(e,u,n,r);else t.nameExpr.type==="ArithVariable"&&(i=t.nameExpr.hasDollarPrefix?await ae(e,t.nameExpr.name):t.nameExpr.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let a=await s(t.subscript),o=`${i}_${a}`,l=e.state.env.get(o);return l!==void 0?ms(e,o,l,r):0}default:return 0}}async function Vn(e,t,n=!1,r=yc()){switch(t.type){case"ArithNumber":return String(t.value);case"ArithSingleQuote":return String(await zn(e,t,n,r));case"ArithVariable":return t.hasDollarPrefix?await ae(e,t.name):t.name;case"ArithSpecialVar":return await ae(e,t.name);case"ArithBracedExpansion":return await ys(e,t.content);case"ArithCommandSubst":return e.execFn?(await e.execFn(t.command,{signal:e.state.signal})).stdout.trim():"0";case"ArithConcat":{let s="";for(let i of t.parts)s+=await Vn(e,i,n,r);return s}default:return String(await zn(e,t,n,r))}}async function gc(e,t){let n="",r=0;for(let A of t.parts){let k=A.type==="Literal"?A.value:"\0",v=B(k);if(v>e.limits.maxStringLength-r)throw new P(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n+=k,r+=v}let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!s||!n.endsWith(")"))return null;let i=s[1],a=[],o=[],l=!1,u="",c=0,f=0,d=!1,p=!0,h=A=>{let k=B(A);if(k>e.limits.maxStringLength-f-c)throw new P(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");u+=A,c+=k},m=(A,k=!1)=>{if(a.length>=e.limits.maxArrayElements)throw new P(`array assignment element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let v=B(A);if(v>e.limits.maxStringLength-f)throw new P(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");a.push(A),o.push(k),f+=v},E=()=>{m(u,p),u="",c=0,d=!1,p=!0};for(let A of t.parts)if(A.type==="Literal"){let k=A.value;if(!l){let v=k.indexOf("=(");v!==-1&&(l=!0,k=k.slice(v+2))}if(l){k.endsWith(")")&&(k=k.slice(0,-1));for(let v of k)/\s/.test(v)?(u||d)&&E():h(v)}}else if(l)if(A.type==="BraceExpansion")if(/^\[.+\]=/.test(u))h(Tn({type:"Word",parts:[A]}));else{(u||d)&&E();let v=await bt(e,{type:"Word",parts:[A]});for(let $ of v.values)m($)}else{(A.type==="SingleQuoted"||A.type==="DoubleQuoted"||A.type==="Escaped")&&(d=!0),p=!1;let k=await ie(e,{type:"Word",parts:[A]});h(k)}(u||d)&&E();let S=a.splice(0),g=o.splice(0);f=0;for(let A=0;A<S.length;A++){let k=S[A];if(!g[A]){m(k);continue}let v=k.match(/^(\[[^\]]+\]=)(.*)$/s);if(v){let $=nn(e,v[2]);k=v[1]+$}if(k.includes("{")&&k.includes("}")){let $=new H().parseWordFromString(k,!1,!1);if($.parts.some(D=>D.type==="BraceExpansion")){let D=await bt(e,$);for(let x of D.values)m(x);continue}}m(k)}let y=[`${i}=(`],b=B(y[0]);for(let A=0;A<a.length;A++){let k=a[A],v;/^\[.+\]=/.test(k)?v=k:k===""?v="''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(k)&&!k.startsWith("'")&&!k.startsWith('"')?v=`'${k.replace(/'/g,"'\\''")}'`:v=k;let $=`${A>0?" ":""}${v}`,D=B($);if(D+1>e.limits.maxStringLength-b)throw new P(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");y.push($),b+=D}return y.push(")"),y.join("")}async function wc(e,t){let n=-1,r=-1,s=!1;for(let m=0;m<t.parts.length;m++){let E=t.parts[m];if(E.type==="Literal"){let S=E.value.indexOf("+=");if(S!==-1){let y=E.value.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)){n=m,r=S,s=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(y)){n=m,r=S,s=!0;break}}let g=E.value.indexOf("=");if(g!==-1&&(g===0||E.value[g-1]!=="+")){let y=E.value.slice(0,g);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(y)){n=m,r=g;break}}}}if(n===-1)return null;let i=t.parts.slice(0,n),a=t.parts[n];if(a.type!=="Literal")return null;let o=s?2:1,l=a.value.slice(0,r),u=a.value.slice(r+o),c=t.parts.slice(n+1),f="";for(let m of i)f+=await ie(e,{type:"Word",parts:[m]});f+=l;let d={type:"Word",parts:u!==""?[{type:"Literal",value:u},...c]:c},p=d.parts.length>0?await ie(e,d):"";return`${f}${s?"+=":"="}${p}`}var gh=["tar","yq","xan","sqlite3","python3","python"];function Ec(e){return gh.includes(e)}var ne=Object.freeze({stdout:"",stderr:"",exitCode:0,internalStdinConsumed:0});function ee(e=""){return{stdout:e,stderr:"",exitCode:0}}function L(e,t=1){return{stdout:"",stderr:e,exitCode:t}}function T(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function we(e){return{stdout:"",stderr:"",exitCode:e?0:1,internalStdinConsumed:0}}function sn(e,t,n="",r=""){throw new P(e,t,n,r)}function bc(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new P(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors")}function sa(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Ut;return ne}if(t.length>1)throw new q(1,"",`bash: break: too many arguments
|
|
115
|
+
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new q(128,"",`bash: break: ${t[0]}: numeric argument required
|
|
116
|
+
`);n=r}throw new Qe(n)}async function ia(e,t){let n,r=!1,s=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")s=!1,i++;else if(t[i]==="-P")s=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let a=t.slice(i);if(a.length===0||a[0]==="~"?n=e.state.env.get("HOME")||"/":a[0]==="-"?(n=e.state.previousDir,r=!0):n=a[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let f=e.state.env.get("CDPATH");if(f){let d=f.split(":").filter(p=>p);for(let p of d){let h=p.startsWith("/")?`${p}/${n}`:`${e.state.cwd}/${p}/${n}`;try{if((await e.fs.stat(h)).isDirectory){n=h,r=!0;break}}catch{}}}}let l=(n.startsWith("/")?n:`${e.state.cwd}/${n}`).split("/").filter(f=>f&&f!=="."),u="";for(let f of l)if(f==="..")u=u.split("/").slice(0,-1).join("/")||"/";else{u=u?`${u}/${f}`:`/${f}`;try{if(!(await e.fs.stat(u)).isDirectory)return L(`bash: cd: ${n}: Not a directory
|
|
117
|
+
`)}catch{return L(`bash: cd: ${n}: No such file or directory
|
|
118
|
+
`)}}let c=u||"/";if(s)try{c=await e.fs.realpath(c)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=c,e.state.env.set("PWD",e.state.cwd),e.state.env.set("OLDPWD",e.state.previousDir),ee(r?`${c}
|
|
119
|
+
`:"")}function aa(e,t){return e.fs.resolvePath(e.state.cwd,t)}var wh=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function gs(e){return wh.includes(e)}async function ws(e,t,n){let r=aa(e,n);switch(t){case"-e":case"-a":return e.fs.exists(r);case"-f":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case"-d":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case"-r":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case"-w":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case"-x":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case"-s":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case"-g":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(r);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].includes(r);case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(r);default:return!1}}var Eh=["-nt","-ot","-ef"];function Es(e){return Eh.includes(e)}async function bs(e,t,n,r){let s=aa(e,n),i=aa(e,r);switch(t){case"-nt":{let[a,o]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return a!==null&&(o===null||a.mtime>o.mtime)}case"-ot":{let[a,o]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return o!==null&&(a===null||a.mtime<o.mtime)}case"-ef":try{let[a,o]=await Promise.all([e.fs.realpath(s),e.fs.realpath(i)]);if(a===o)return!0;let[l,u]=await Promise.all([e.fs.stat(s),e.fs.stat(i)]);return l.dev!==void 0&&l.ino!==void 0&&u.dev!==void 0&&u.ino!==void 0?l.dev===u.dev&&l.ino===u.ino:l.identity&&u.identity?l.identity===u.identity:!1}catch{return!1}default:return!1}}var bh=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function Ss(e){return bh.has(e)}function As(e,t,n){switch(e){case"-eq":return t===n;case"-ne":return t!==n;case"-lt":return t<n;case"-le":return t<=n;case"-gt":return t>n;case"-ge":return t>=n}}function yr(e){return e==="="||e==="=="||e==="!="}function vs(e,t,n,r=!1,s=!1,i=!1,a=256){if(r){let l=Un(t,n,s,i,a);return e==="!="?!l:l}if(s){let l=t.toLowerCase()===n.toLowerCase();return e==="!="?!l:l}let o=t===n;return e==="!="?!o:o}var Sh=new Set(["-z","-n"]);function ks(e){return Sh.has(e)}function xs(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function $s(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let r=n[1],s=n[2];if(e.state.associativeArrays?.has(r)){let o=s;return(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1)),o=o.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,u)=>e.state.env.get(u)||""),Kt(e,r,o)}let a;try{let o=new H,l=se(o,s);a=await Y(e,l.expression)}catch{if(/^-?\d+$/.test(s))a=Number.parseInt(s,10);else{let o=e.state.env.get(s);a=o?Number.parseInt(o,10):0}}if(a<0){let o=Se(e,r),l=e.state.currentLine;if(o.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${l}: ${r}: bad array subscript
|
|
120
|
+
`,!1;if(a=Math.max(...o)+1+a,a<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${l}: ${r}: bad array subscript
|
|
121
|
+
`,!1}return Kt(e,r,a)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Pt(e,t).length>0:Se(e,t).length>0}async function an(e,t){switch(t.type){case"CondBinary":{let n=await ie(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),s;if(t.operator==="=~")if(r){let i=await ie(e,t.right);s=Bn(i)}else s=await uc(e,t.right);else yr(t.operator)&&!r?s=await cc(e,t.right):s=await ie(e,t.right);if(yr(t.operator)){let i=e.state.shoptOptions.nocasematch;return vs(t.operator,n,s,!r,i,!0,e.limits.maxCallDepth)}if(Ss(t.operator))return As(t.operator,await Ac(e,n),await Ac(e,s));if(Es(t.operator))return bs(e,t.operator,n,s);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,a=$h(s),l=me(a,i?"i":"").match(n);if(ge(e,"BASH_REMATCH"),l)for(let u=0;u<l.length;u++)j(e,"BASH_REMATCH",u,l[u]||"");return l!==null}catch{throw new Error("syntax error in regular expression")}case"<":return n<s;case">":return n>s;default:return!1}}case"CondUnary":{let n=await ie(e,t.operand);return gs(t.operator)?ws(e,t.operator,n):ks(t.operator)?xs(t.operator,n):t.operator==="-v"?await $s(e,n):t.operator==="-o"?la(e,n):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await ie(e,t.operand.expression.word)})`!=="":!await an(e,t.operand);case"CondAnd":return await an(e,t.left)?await an(e,t.right):!1;case"CondOr":return await an(e,t.left)?!0:await an(e,t.right);case"CondGroup":return await an(e,t.expression);case"CondWord":return await ie(e,t.word)!=="";default:return!1}}async function qn(e,t){if(t.length===0)return T("","",1);if(t.length===1)return we(!!t[0]);if(t.length===2){let r=t[0],s=t[1];return r==="("?L(`test: '(' without matching ')'
|
|
122
|
+
`,2):gs(r)?we(await ws(e,r,s)):ks(r)?we(xs(r,s)):r==="!"?we(!s):r==="-v"?we(await $s(e,s)):r==="-o"?we(la(e,s)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?L(`test: ${r}: unary operator expected
|
|
123
|
+
`,2):T("","",1)}if(t.length===3){let r=t[0],s=t[1],i=t[2];if(yr(s))return we(vs(s,r,i));if(Ss(s)){let a=Ps(r),o=Ps(i);return!a.valid||!o.valid?T("","",2):we(As(s,a.value,o.value))}if(Es(s))return we(await bs(e,s,r,i));switch(s){case"-a":return we(r!==""&&i!=="");case"-o":return we(r!==""||i!=="");case">":return we(r>i);case"<":return we(r<i)}if(r==="!"){let a=await qn(e,[s,i]);return T("",a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(r==="("&&i===")")return we(s!=="")}if(t.length===4){if(t[0]==="!"){let r=await qn(e,t.slice(1));return T("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return qn(e,[t[1],t[2]])}let n=await kc(e,t,0);return n.pos<t.length?L(`test: too many arguments
|
|
124
|
+
`,2):we(n.value)}async function kc(e,t,n){return Ah(e,t,n)}async function Ah(e,t,n){let{value:r,pos:s}=await Sc(e,t,n);for(;t[s]==="-o";){let i=await Sc(e,t,s+1);r=r||i.value,s=i.pos}return{value:r,pos:s}}async function Sc(e,t,n){let{value:r,pos:s}=await oa(e,t,n);for(;t[s]==="-a";){let i=await oa(e,t,s+1);r=r&&i.value,s=i.pos}return{value:r,pos:s}}async function oa(e,t,n){let r=e.executionScope.enterDepth("test_expression",e.limits.maxCallDepth,"test expression");try{if(t[n]==="!"){let{value:s,pos:i}=await oa(e,t,n+1);return{value:!s,pos:i}}return vh(e,t,n)}finally{r.release()}}async function vh(e,t,n){let r=t[n];if(r==="("){let{value:i,pos:a}=await kc(e,t,n+1);return{value:i,pos:t[a]===")"?a+1:a}}let s=t[n+1];if(yr(s)){let i=r,a=t[n+2]??"";return{value:vs(s,i,a),pos:n+3}}if(Ss(s)){let i=Ps(r),a=Ps(t[n+2]??"0");return!i.valid||!a.valid?{value:!1,pos:n+3}:{value:As(s,i.value,a.value),pos:n+3}}if(Es(s)){let i=r,a=t[n+2]??"";return{value:await bs(e,s,i,a),pos:n+3}}if(gs(r)){let i=t[n+1]??"";return{value:await ws(e,r,i),pos:n+2}}if(ks(r)){let i=t[n+1]??"";return{value:xs(r,i),pos:n+2}}if(r==="-v"){let i=t[n+1]??"";return{value:await $s(e,i),pos:n+2}}if(r==="-o"){let i=t[n+1]??"";return{value:la(e,i),pos:n+2}}return{value:r!==void 0&&r!=="",pos:n+1}}function Un(e,t,n=!1,r=!1,s=256){r&&kh(t,s);let i=`^${xc(t,r)}$`;return me(i,n?"is":"s").test(e)}function kh(e,t){let n=0,r=[];for(let s=0;s<e.length;s++){if(e[s]==="\\"){s++;continue}if(e[s]==="("){let i=s>0&&"@*+?!".includes(e[s-1]);if(r.push(i),i&&n++,n>t)throw new P(`extglob maximum depth (${t}) exceeded`,"recursion")}else e[s]===")"&&r.length>0&&r.pop()&&n--}}function xc(e,t){let n="";for(let r=0;r<e.length;r++){let s=e[r];if(t&&(s==="@"||s==="*"||s==="+"||s==="?"||s==="!")&&r+1<e.length&&e[r+1]==="("){let i=$c(e,r+1);if(i!==-1){let a=e.slice(r+2,i),o=Pc(a),l=o.map(c=>xc(c,t)),u=l.length>0?l.join("|"):"(?:)";if(s==="@")n+=`(?:${u})`;else if(s==="*")n+=`(?:${u})*`;else if(s==="+")n+=`(?:${u})+`;else if(s==="?")n+=`(?:${u})?`;else if(s==="!")if(i<e.length-1){let f=o.map(p=>Cc(p,t));if(f.every(p=>p!==null)&&f.every(p=>p===f[0])&&f[0]!==null){let p=f[0];if(p===0)n+="(?:.+)";else{let h=[];p>0&&h.push(`.{0,${p-1}}`),h.push(`.{${p+1},}`),h.push(`(?!(?:${u})).{${p}}`),n+=`(?:${h.join("|")})`}}else n+=`(?:(?!(?:${u})).)*?`}else n+=`(?!(?:${u})$).*`;r=i;continue}}if(s==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?n+=`\\${i}`:n+=i,r++}else n+="\\\\";else if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let i=e.indexOf("]",r+1);i!==-1?(n+=e.slice(r,i+1),r=i):n+="\\["}else/[\\^$.|+(){}]/.test(s)?n+=`\\${s}`:n+=s}return n}function $c(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Pc(e){let t=[],n="",r=0,s=0;for(;s<e.length;){let i=e[s];if(i==="\\"){n+=i,s+1<e.length?(n+=e[s+1],s+=2):s++;continue}i==="("?(r++,n+=i):i===")"?(r--,n+=i):i==="|"&&r===0?(t.push(n),n=""):n+=i,s++}return t.push(n),t}function Cc(e,t){let n=0,r=0;for(;r<e.length;){let s=e[r];if(t&&(s==="@"||s==="*"||s==="+"||s==="?"||s==="!")&&r+1<e.length&&e[r+1]==="("){let i=$c(e,r+1);if(i!==-1){if(s==="@"){let a=e.slice(r+2,i),l=Pc(a).map(u=>Cc(u,t));if(l.every(u=>u!==null)&&l.every(u=>u===l[0])){n+=l[0],r=i+1;continue}return null}return null}}if(s==="*")return null;if(s==="?"){n+=1,r++;continue}if(s==="["){let i=e.indexOf("]",r+1);if(i!==-1){n+=1,r=i+1;continue}n+=1,r++;continue}if(s==="\\"){n+=1,r+=2;continue}n+=1,r++}return n}function la(e,t){let r=new Map([["errexit",()=>e.state.options.errexit===!0],["nounset",()=>e.state.options.nounset===!0],["pipefail",()=>e.state.options.pipefail===!0],["xtrace",()=>e.state.options.xtrace===!0],["e",()=>e.state.options.errexit===!0],["u",()=>e.state.options.nounset===!0],["x",()=>e.state.options.xtrace===!0]]).get(t);return r?r():!1}async function Ac(e,t){if(t=t.trim(),t==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return vc(t);try{let n=new H,r=se(n,t);return await Y(e,r.expression)}catch{return vc(t)}}function xh(e,t){let n=0;for(let r of e){let s;if(r>="0"&&r<="9")s=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")s=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")s=r.charCodeAt(0)-65+36;else if(r==="@")s=62;else if(r==="_")s=63;else return Number.NaN;if(s>=t)return Number.NaN;n=n*t+s}return n}function vc(e){if(e=e.trim(),e==="")return 0;let t=!1;e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1));let n,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let s=Number.parseInt(r[1],10);s>=2&&s<=64?n=xh(r[2],s):n=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?n=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?n=Number.parseInt(e,8):n=Number.parseInt(e,10);return Number.isNaN(n)&&(n=0),t?-n:n}function Ps(e){if(e=e.trim(),e==="")return{value:0,valid:!0};let t=!1;if(e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let n=Number.parseInt(e,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:t?-n:n,valid:!0}}function $h(e){let t="",n=0;for(;n<e.length;)if(e[n]==="\\"&&n+1<e.length)t+=e[n]+e[n+1],n+=2;else if(e[n]==="["){let r=Ph(e,n);t+=r.converted,n=r.endIndex}else t+=e[n],n++;return t}function Ph(e,t){let n=t+1,r="[";n<e.length&&(e[n]==="^"||e[n]==="!")&&(r+="^",n++);let s=!1;n<e.length&&e[n]==="]"&&(s=!0,n++);let i=!1;n<e.length&&e[n]==="["&&n+1<e.length&&e[n+1]!==":"&&(i=!0,n++);let a="",o=!1;for(;n<e.length;){let l=e[n];if(l==="]"){o=!0,n++;break}if(l==="["&&n+1<e.length&&e[n+1]===":"){let u=e.indexOf(":]",n+2);if(u!==-1){let c=e.slice(n+2,u);a+=Ch(c),n=u+2;continue}}if(l==="["&&n+1<e.length){let u=e[n+1];if(u==="."||u==="="){let c=`${u}]`,f=e.indexOf(c,n+2);if(f!==-1){let d=e.slice(n+2,f);a+=d,n=f+2;continue}}}if(l==="\\"&&n+1<e.length){a+=l+e[n+1],n+=2;continue}a+=l,n++}return o?(s&&(r+="\\]"),i&&(r+="\\["),r+=a,r+="]",{converted:r,endIndex:n}):{converted:"\\[",endIndex:t+1}}function Ch(e){return new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]).get(e)??""}function ua(e,t,n){if(n&&e.length>=n.maxElements)throw new P(`array element limit exceeded (${n.maxElements})`,"array_elements");e.push(t)}function Bt(e,t){if(t&&B(e)>t.maxStringBytes)throw new P(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,"string_length");let n=[],r="",s=!1,i=!1,a=!1,o=!1;for(let l of e){if(a){r+=l,a=!1,o=!0;continue}if(l==="\\"){a=!0;continue}if(l==="'"&&!i){s||(o=!0),s=!s;continue}if(l==='"'&&!s){i||(o=!0),i=!i;continue}if((l===" "||l===" "||l===`
|
|
125
|
+
`)&&!s&&!i){o&&(ua(n,r,t),r="",o=!1);continue}r+=l,o=!0}return o&&ua(n,r,t),n}function Cs(e,t){if(t&&B(e)>t.maxStringBytes)throw new P(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,"string_length");let n=[],r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r++;if(r>=e.length)break;if(e[r]!=="["){r++;continue}r++;let s="";if(e[r]==="'"||e[r]==='"'){let a=e[r];for(r++;r<e.length&&e[r]!==a;)s+=e[r],r++;e[r]===a&&r++}else for(;r<e.length&&e[r]!=="]"&&e[r]!=="=";)s+=e[r],r++;for(;r<e.length&&e[r]!=="]";)r++;if(e[r]==="]"&&r++,e[r]!=="=")continue;r++;let i="";if(e[r]==="'"||e[r]==='"'){let a=e[r];for(r++;r<e.length&&e[r]!==a;)e[r]==="\\"&&r+1<e.length&&r++,i+=e[r],r++;e[r]===a&&r++}else for(;r<e.length&&!/\s/.test(e[r]);)i+=e[r],r++;ua(n,[s,i],t)}return n}function Nc(e,t){let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(n)return{name:n[1],isArray:!0,arrayElements:Bt(n[2],t)};let r=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(r)return{name:r[1],isArray:!1,arrayIndex:r[2],value:r[3]};if(e.includes("=")){let s=e.indexOf("=");return{name:e.slice(0,s),isArray:!1,value:e.slice(s+1)}}return{name:e,isArray:!1}}async function Nh(e,t){try{let n=new H,r=se(n,t);return await Y(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}async function Rc(e,t,n={}){let{name:r,isArray:s,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:u=!0}=n;if(u){let c=ce(e,r);if(c)return c}if(s&&i){e.executionScope.consumeWork(i.length,"array assignment");let c=ke(e,r),f=c?Me(c):void 0,d=e.state.env.get(r);try{ge(e,r);for(let p=0;p<i.length;p++)j(e,r,p,i[p]);e.state.env.delete(r)}catch(p){throw e.state.arrays??=new Map,f?e.state.arrays.set(r,f):e.state.arrays.delete(r),d===void 0?e.state.env.delete(r):e.state.env.set(r,d),p}}else if(o!==void 0&&a!==void 0){let c=await Nh(e,o);j(e,r,c,a)}else a!==void 0&&e.state.env.set(r,a);return l&&Ge(e,r),null}function on(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function ca(e,t){return e.state.localVarDepth?.get(t)}function Ns(e,t){e.state.localVarDepth?.delete(t)}function Dc(e,t,n){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:n,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function Rs(e,t){let n=e.state.localVarStack?.get(t);if(!(!n||n.length===0))return n.pop()}function Ic(e,t){if(e.state.localVarStack)for(let[n,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(n)}}var fa="__file__:",da="__file_append__:",ma="__rw__:",pa="__dupout__:",ha="__dupin__:",Ee=3;function Rh(e){let t=e.slice(ma.length),n=t.indexOf(":");if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let s=n+1,i=t.slice(s,s+r),a=t.slice(s+r+1),o=a.indexOf(":");if(o===-1)return null;let l=Number.parseInt(a.slice(0,o),10);return Number.isNaN(l)||l<0?null:{path:i,position:l,content:a.slice(o+1)}}function Oc(e,t){let n=Number.parseInt(e.slice(t.length),10);return Number.isNaN(n)?null:n}function Dh(e){if(e.startsWith(fa))return{kind:"output",path:e.slice(fa.length),append:!1};if(e.startsWith(da))return{kind:"output",path:e.slice(da.length),append:!0};if(e.startsWith(ma)){let t=Rh(e);if(t)return{kind:"readwrite",...t}}if(e.startsWith(pa)){let t=Oc(e,pa);if(t!==null)return{kind:"dup-out",sourceFd:t}}if(e.startsWith(ha)){let t=Oc(e,ha);if(t!==null)return{kind:"dup-in",sourceFd:t}}return{kind:"input",content:e}}function ya(e){switch(e.kind){case"input":return e.content;case"output":return`${e.append?da:fa}${e.path}`;case"readwrite":return`${ma}${e.path.length}:${e.path}:${e.position}:${e.content}`;case"dup-out":return`${pa}${e.sourceFd}`;case"dup-in":return`${ha}${e.sourceFd}`;case"closed":throw new Error("Closed descriptors have no table encoding")}}function Ih(e){return e.state.fileDescriptors??=new Map,e.state.fileDescriptors}function Oh(e,t,n){n?(e.state.inputFds??=new Set,e.state.inputFds.add(t)):e.state.inputFds?.delete(t)}function jn(e,t){return e.state.fdAliases?.get(t)}function ln(e,t){return[...jn(e,t)??[t]]}function _c(e,t){let n=jn(e,t);if(n&&(n.delete(t),e.state.fdAliases?.delete(t),n.size<2))for(let r of n)e.state.fdAliases?.delete(r)}function ga(e,t,n){if(t===n)return;e.state.fdAliases??=new Map;let r=jn(e,n)??new Set([n]);r.add(t);for(let s of r)e.state.fdAliases.set(s,r)}function Ds(e,t){return e.state.fileDescriptors?.get(t)}function nt(e,t){let n=Ds(e,t);if(n!==void 0)return e.state.inputFds?.has(t)?{kind:"input",content:n}:Dh(n)}function $n(e,t){return e.state.fileDescriptors?.has(t)===!0}function wa(e,t,n,r){let s=Ih(e);s.has(t)||bc(e),s.set(t,n),Oh(e,t,r)}function Is(e,t,n,r=!1){_c(e,t),wa(e,t,n,r)}function ut(e,t,n){Is(e,t,ya(n),n.kind==="input")}function It(e,t){e.state.fileDescriptors?.delete(t),e.state.inputFds?.delete(t),_c(e,t)}function Os(e,t,n){let r=Ds(e,n);return r===void 0?!1:(Is(e,t,r,e.state.inputFds?.has(n)===!0),ga(e,t,n),!0)}function Ea(e,t,n){let r=Ds(e,n);if(r===void 0)return!1;if(t===n)return!0;let s=e.state.inputFds?.has(n)===!0,i=[...jn(e,n)??[]].filter(o=>o!==n);It(e,n),Is(e,t,r,s);let a=i.find(o=>$n(e,o));return a!==void 0&&ga(e,t,a),!0}function _s(e,t){let n=nt(e,t);if(n===void 0)return{error:"not-open"};switch(n.kind){case"input":return{content:n.content};case"readwrite":return{content:n.content.slice(n.position)};case"output":case"dup-out":return{error:"write-only"};case"dup-in":return{error:"not-open"};case"closed":return{error:"not-open"}}}function un(e,t,n){let r=nt(e,t);if(r===void 0)return;let s;if(r.kind==="input")s={kind:"input",content:r.content.slice(n)};else if(r.kind==="readwrite")s={...r,position:r.position+n};else return;let i=ya(s),a=s.kind==="input";for(let o of jn(e,t)??[t])wa(e,o,i,a)}async function ba(e,t,n,r,s){if(t.kind==="output")return await e.fs.appendFile(t.path,r,s),!0;let a=n.map(c=>nt(e,c)).find(c=>c?.kind==="readwrite")??t;if(a.kind!=="readwrite")return!1;let o=a.content.slice(0,a.position)+r+a.content.slice(a.position+r.length),l={...a,position:a.position+r.length,content:o};await e.fs.writeFile(a.path,o,s);let u=ya(l);for(let c of n)$n(e,c)&&wa(e,c,u,!1);return!0}function cn(e,t,n){if(t.has(n))return;let r=jn(e,n);t.set(n,{raw:Ds(e,n),isInput:e.state.inputFds?.has(n)===!0,aliases:r?[...r].filter(s=>s!==n):[]})}function Ls(e,t){let n=e.state.fileDescriptors;if(n)for(let[r,{raw:s,isInput:i,aliases:a}]of t){if(s===void 0){It(e,r);continue}Is(e,r,s,i);let o=a.find(l=>n.has(l));o!==void 0&&ga(e,r,o)}}function Sa(e){switch(e.operator){case"<":case"<>":case"<<":case"<<-":case"<<<":case"<&":return e.fd??0;case">":case">>":case">|":case">&":return e.fd??1;default:return null}}function Lc(e){if(e.fdVariable)return!1;let t=Sa(e);return t!==null&&t>=Ee}async function _h(e,t,n,r){try{if(!await e.fs.exists(t))return null;if((await e.fs.stat(t)).isDirectory)return`bash: ${n}: Is a directory
|
|
126
126
|
`;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&n!=="/dev/null")return`bash: ${n}: cannot overwrite existing file
|
|
127
127
|
`}catch{return`bash: ${n}: cannot open redirect target
|
|
128
|
-
`}return null}function
|
|
129
|
-
`,1)};if(t==="/dev/stdout")return{entry:{kind:"dup-out",sourceFd:1}};if(t==="/dev/stderr")return{entry:{kind:"dup-out",sourceFd:2}};try{n?await e.fs.appendFile(i,"","binary"):await e.fs.writeFile(i,"","binary")}catch(
|
|
130
|
-
`,1)}}return{entry:{kind:"output",path:i,append:n}}}async function
|
|
131
|
-
`,1)};try{return await e.fs.writeFile(r,"","binary"),{entry:{kind:"readwrite",path:r,position:0,content:""}}}catch{return{error:
|
|
132
|
-
`,1)}}}}var
|
|
128
|
+
`}return null}function Tc(e){let n=Math.min(e.length,8192);for(let r=0;r<n;r++)if(e.charCodeAt(r)>127)return"utf8";return"binary"}var gr="scoped",Mc="bare",Bc="persistent",Lh=e=>new P(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors"),Th=(e,t)=>$n(e,t)||(e.state.fileDescriptors?.size??0)<e.limits.maxFileDescriptors,Fc=e=>{let t=Math.max(e.state.nextFd??10,10);for(;$n(e,t);)t+=1;return t},Ts=e=>{let t=e.endsWith("-"),n=t?e.slice(0,-1):e;return/^\d+$/.test(n)?{sourceFd:Number.parseInt(n,10),move:t}:null},Fh=(e,t,n)=>{let r=nt(e,t);return t<Ee?r?{kind:"entry",entry:r,descriptors:ln(e,t)}:{kind:"standard",fd:t}:r?n?r.kind==="input"||r.kind==="readwrite"||r.kind==="dup-in"?{kind:"entry",entry:r,descriptors:ln(e,t)}:null:r.kind==="output"||r.kind==="readwrite"||r.kind==="dup-out"?{kind:"entry",entry:r,descriptors:ln(e,t)}:null:null};async function Hn(e,t,n,r,s=!0){let i=e.fs.resolvePath(e.state.cwd,t),a=await _h(e,i,t,{checkNoclobber:!n,isClobber:r});if(a)return{error:T("",a,1)};if(t==="/dev/full")return{error:T("",`bash: /dev/full: No space left on device
|
|
129
|
+
`,1)};if(t==="/dev/stdout")return{entry:{kind:"dup-out",sourceFd:1}};if(t==="/dev/stderr")return{entry:{kind:"dup-out",sourceFd:2}};try{n?await e.fs.appendFile(i,"","binary"):await e.fs.writeFile(i,"","binary")}catch(o){if(!s)throw o;return{error:T("",`bash: ${t}: cannot open redirect target
|
|
130
|
+
`,1)}}return{entry:{kind:"output",path:i,append:n}}}async function Aa(e,t,n){let r=e.fs.resolvePath(e.state.cwd,t);try{let s=await e.fs.readFile(r);return n?{entry:{kind:"readwrite",path:r,position:0,content:s}}:{entry:{kind:"input",content:s}}}catch{if(!n)return{error:T("",`bash: ${t}: No such file or directory
|
|
131
|
+
`,1)};try{return await e.fs.writeFile(r,"","binary"),{entry:{kind:"readwrite",path:r,position:0,content:""}}}catch{return{error:T("",`bash: ${t}: No such file or directory
|
|
132
|
+
`,1)}}}}var Mh=async(e,t)=>{let n=await ie(e,t.content);return t.stripTabs?n.split(`
|
|
133
133
|
`).map(r=>r.replace(/^\t+/,"")).join(`
|
|
134
|
-
`):n};async function
|
|
135
|
-
`,1),g);A=await
|
|
136
|
-
`,1),g);if(y.fdVariable){try{
|
|
137
|
-
`,1),g);if(!(
|
|
138
|
-
`,1),g);C=
|
|
139
|
-
`,1),g);let
|
|
140
|
-
`};else if(y.operator==="<"||y.operator==="<>"){let
|
|
141
|
-
`,1),g)}else
|
|
142
|
-
`,1),g);if(!(
|
|
143
|
-
`,1),g);let
|
|
144
|
-
`,1),g);if(C.kind==="standard")
|
|
145
|
-
`,1),g)
|
|
146
|
-
`});else if(y.operator==="<"||y.operator==="<>"){let
|
|
147
|
-
`,1),g);let
|
|
148
|
-
`,1),g);if(i.set(g
|
|
149
|
-
`,1),g);
|
|
150
|
-
`,1),g);u=
|
|
151
|
-
`),c=-1,m(b,{kind:"input",content:u});else if(y.operator==="<"){let v=e.fs.resolvePath(e.state.cwd,A);try{u=await
|
|
152
|
-
`,1),g)}}else if(y.operator==="<>"){let v=await
|
|
153
|
-
`,c=1,v===1&&(l="");break}if(k==="/dev/null"&&v===2){m={kind:"discard"};break}let
|
|
154
|
-
`,c=1),m.kind==="invalid-output"&&(A="");let k=async(v
|
|
155
|
-
`;throw new
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
`,
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
`)
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
`,2);
|
|
173
|
-
`,2);
|
|
174
|
-
`,2);
|
|
175
|
-
`,2);
|
|
176
|
-
`,2);
|
|
177
|
-
`,2)
|
|
178
|
-
`,2)}else if(
|
|
179
|
-
`,2)}else if(
|
|
180
|
-
`,2)}else if(
|
|
181
|
-
`,2);
|
|
182
|
-
|
|
134
|
+
`):n};async function Bh(e,t,n,r){let s=new Map,i=new Map,a=(g,y)=>e.state.closedStandardFds?.has(g)?{kind:"closed"}:nt(e,g)??y,o=new Map([[0,a(0,{kind:"dup-in",sourceFd:0})],[1,a(1,{kind:"dup-out",sourceFd:1})],[2,a(2,{kind:"dup-out",sourceFd:2})]]),l=r.numericSnapshot,u,c=-1,f=o.get(0);f?.kind==="input"?(u=f.content,c=0):f?.kind==="readwrite"&&(u=f.content.slice(f.position),c=0);let d=()=>({targets:s,dupSources:i,standardRoutes:o,stdin:u,stdinSourceFd:c,error:null}),p=async(g,y,b)=>{let A={...d(),error:await fn(e,g,t.slice(0,y),s,i,o)};return b?{...A,errorCause:b}:A},h=async(g,y)=>{if(Th(e,g))return null;let b=Lh(e);return p(T("",b.stderr,P.EXIT_CODE),y,b)},m=(g,y)=>{g!==null&&g<Ee&&o.set(g,y),r.policy==="persistent"&&g!==null&&g<Ee&&(e.state.closedStandardFds?.delete(g),ut(e,g,y))},E=(g,y)=>{o.set(g,y),cn(e,r.standardSnapshot,g),r.standardClosedSnapshot.has(g)||r.standardClosedSnapshot.set(g,e.state.closedStandardFds?.has(g)===!0),e.state.closedStandardFds?.delete(g),ut(e,g,y)},S=(g,y)=>{if(g<Ee){let b=o.get(g);return b?.kind==="closed"?null:b?{kind:"entry",entry:b,descriptors:ln(e,g)}:{kind:"standard",fd:g}}return Fh(e,g,y)};for(let g=0;g<t.length;g++){let y=t[g],b=Sa(y);if(y.target.type==="HereDoc"){let v=await Mh(e,y.target);if(y.fdVariable){try{ce(e,y.fdVariable)}catch(x){if(!(x instanceof q))throw x;return p(T(x.stdout,x.stderr,x.exitCode),g,x)}let $=Fc(e),D=await h($,g);if(D)return D;cn(e,r.fdVariableSnapshot,$),r.fdVariableEnv.has(y.fdVariable)||r.fdVariableEnv.set(y.fdVariable,e.state.env.get(y.fdVariable)),ut(e,$,{kind:"input",content:v}),e.state.env.set(y.fdVariable,String($)),e.state.nextFd=$+1}else if(b!==null&&b>=Ee){let $=await h(b,g);if($)return $;cn(e,l,b),ut(e,b,{kind:"input",content:v})}else if(b===0||b===null)u=mn(v),c=-1,m(b,{kind:"input",content:u});else{let $={kind:"input",content:v};r.policy==="persistent"?m(b,$):E(b,$)}continue}let A,k=y.operator===">&"||y.operator==="<&";if(k){if(ta(e,y.target))return p(T("",`bash: $@: ambiguous redirect
|
|
135
|
+
`,1),g);A=await ie(e,y.target)}else if(y.operator==="<<<")A=await ie(e,y.target);else{let v=await hc(e,y.target);if("error"in v)return p(T("",v.error,1),g);A=v.target}if(s.set(g,A),A.includes("\0"))return p(T("",`bash: ${A.replace(/\0/g,"")}: No such file or directory
|
|
136
|
+
`,1),g);if(y.fdVariable){try{ce(e,y.fdVariable)}catch(I){if(!(I instanceof q))throw I;return p(T(I.stdout,I.stderr,I.exitCode),g,I)}if(k&&A==="-"){let I=Number.parseInt(e.state.env.get(y.fdVariable)??"",10);Number.isNaN(I)||(cn(e,r.fdVariableSnapshot,I),It(e,I));continue}let v=Fc(e),$=k?Ts(A):null;if($&&!S($.sourceFd,y.operator==="<&"))return p(T("",`bash: ${$.sourceFd}: Bad file descriptor
|
|
137
|
+
`,1),g);if(!($?.move===!0&&$.sourceFd>=Ee)){let I=await h(v,g);if(I)return I}cn(e,r.fdVariableSnapshot,v),r.fdVariableEnv.has(y.fdVariable)||r.fdVariableEnv.set(y.fdVariable,e.state.env.get(y.fdVariable));let x,C;if(k){let I=$;if(I){let W=S(I.sourceFd,y.operator==="<&");if(!W)return p(T("",`bash: ${I.sourceFd}: Bad file descriptor
|
|
138
|
+
`,1),g);C=I,W.kind==="standard"?x={kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:W.fd}:I.sourceFd<Ee&&(x=W.entry)}else{if(y.operator==="<&")return p(T("",`bash: ${A}: ambiguous redirect
|
|
139
|
+
`,1),g);let W=await Hn(e,A,!1,!1);if(W.error)return p(W.error,g);x=W.entry}}else if(y.operator===">"||y.operator===">|"||y.operator===">>"||y.operator==="&>"||y.operator==="&>>"){let I=y.operator===">>"||y.operator==="&>>",W=await Hn(e,A,I,y.operator===">|");if(W.error)return p(W.error,g);x=W.entry}else if(y.operator==="<<<")x={kind:"input",content:`${A}
|
|
140
|
+
`};else if(y.operator==="<"||y.operator==="<>"){let I=await Aa(e,A,y.operator==="<>");if(I.error)return p(I.error,g);x=I.entry}if(C&&C.sourceFd>=Ee){if(!(C.move?Ea(e,v,C.sourceFd):Os(e,v,C.sourceFd)))return p(T("",`bash: ${C.sourceFd}: Bad file descriptor
|
|
141
|
+
`,1),g)}else x&&ut(e,v,x);C?.move&&C.sourceFd!==v&&C.sourceFd<Ee&&It(e,C.sourceFd),e.state.env.set(y.fdVariable,String(v)),e.state.nextFd=v+1;continue}if(Lc(y)){let v=b;if(k&&A==="-"){cn(e,l,v),It(e,v);continue}let $=k?Ts(A):null;if($&&!S($.sourceFd,y.operator==="<&"))return p(T("",`bash: ${$.sourceFd}: Bad file descriptor
|
|
142
|
+
`,1),g);if(!($?.move===!0&&$.sourceFd>=Ee)){let x=await h(v,g);if(x)return x}if(cn(e,l,v),k){let x=$;if(!x){if(y.operator==="<&")return p(T("",`bash: ${A}: ambiguous redirect
|
|
143
|
+
`,1),g);let I=await Hn(e,A,!1,!1);if(I.error)return p(I.error,g);ut(e,v,I.entry);continue}let C=S(x.sourceFd,y.operator==="<&");if(!C)return p(T("",`bash: ${x.sourceFd}: Bad file descriptor
|
|
144
|
+
`,1),g);if(C.kind==="standard")ut(e,v,{kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:C.fd});else if(x.sourceFd<Ee)ut(e,v,C.entry);else if(!(x.move?Ea(e,v,x.sourceFd):Os(e,v,x.sourceFd)))return p(T("",`bash: ${x.sourceFd}: Bad file descriptor
|
|
145
|
+
`,1),g);x.move&&x.sourceFd!==v&&x.sourceFd<Ee&&It(e,x.sourceFd);continue}if(y.operator===">"||y.operator===">|"||y.operator===">>"){let x=await Hn(e,A,y.operator===">>",y.operator===">|");if(x.error)return p(x.error,g);ut(e,v,x.entry)}else if(y.operator==="<<<")ut(e,v,{kind:"input",content:`${A}
|
|
146
|
+
`});else if(y.operator==="<"||y.operator==="<>"){let x=await Aa(e,A,y.operator==="<>");if(x.error)return p(x.error,g);ut(e,v,x.entry)}continue}if(k){if(A==="-"){b===0&&(u="",c=-1),b!==null&&b<Ee&&(o.set(b,{kind:"closed"}),r.policy==="persistent"&&(It(e,b),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(b)));continue}let v=Ts(A);if(!v){if(y.operator==="<&")return p(T("",`bash: ${A}: ambiguous redirect
|
|
147
|
+
`,1),g);let D=await Hn(e,A,!1,!1,!1);if(D.error)return p(D.error,g);let x=D.entry;i.set(g,{kind:"entry",entry:x,descriptors:[]}),y.fd==null?(m(1,x),m(2,x)):m(b,x);continue}let $=S(v.sourceFd,y.operator==="<&");if(!$)return p(T("",`bash: ${v.sourceFd}: Bad file descriptor
|
|
148
|
+
`,1),g);if(i.set(g,$),$.kind==="entry"&&r.policy==="persistent"&&b!==null&&b<Ee&&v.sourceFd>=Ee){if(!Os(e,b,v.sourceFd))return p(T("",`bash: ${v.sourceFd}: Bad file descriptor
|
|
149
|
+
`,1),g);o.set(b,nt(e,b)),e.state.closedStandardFds?.delete(b)}else $.kind==="standard"?m(b,{kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:$.fd}):m(b,$.entry);if(y.operator==="<&"&&b===0)if($.kind==="standard")u=$.fd===0?n:"",c=-1;else if($.entry.kind==="input"||$.entry.kind==="readwrite"){let D=v.sourceFd<Ee&&!$n(e,v.sourceFd)?{content:$.entry.kind==="input"?$.entry.content:$.entry.content.slice($.entry.position)}:_s(e,v.sourceFd);if("error"in D)return p(T("",`bash: ${v.sourceFd}: Bad file descriptor
|
|
150
|
+
`,1),g);u=D.content,c=$n(e,v.sourceFd)?v.sourceFd:-1}else u=n,c=-1;v.move&&(v.sourceFd>=Ee?It(e,v.sourceFd):(o.set(v.sourceFd,{kind:"closed"}),r.policy==="persistent"&&(It(e,v.sourceFd),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(v.sourceFd))));continue}if(y.operator===">"||y.operator===">|"||y.operator===">>"||y.operator==="&>"||y.operator==="&>>"){let v=await Hn(e,A,y.operator===">>"||y.operator==="&>>",y.operator===">|",!1);if(v.error)return p(v.error,g);let $=v.entry;y.operator==="&>"||y.operator==="&>>"?(m(1,$),m(2,$)):m(b,$);continue}if(y.operator==="<<<")u=mn(`${A}
|
|
151
|
+
`),c=-1,m(b,{kind:"input",content:u});else if(y.operator==="<"){let v=e.fs.resolvePath(e.state.cwd,A);try{u=await Cn(e.fs,v),c=-1,m(b,{kind:"input",content:u})}catch{return p(T("",`bash: ${A}: No such file or directory
|
|
152
|
+
`,1),g)}}else if(y.operator==="<>"){let v=await Aa(e,A,!0);if(v.error)return p(v.error,g);let $=v.entry;m(b,$),b===0&&$.kind==="readwrite"&&(u=$.content,c=-1)}}return d()}function Gn(e,t,n){let r={numericSnapshot:new Map,fdVariableSnapshot:new Map,standardSnapshot:new Map,standardClosedSnapshot:new Map,fdVariableEnv:new Map,nextFd:e.state.nextFd,policy:n},s=!1;return{prepare:(i="")=>Bh(e,t,i,r),finish:()=>{if(!s){if(s=!0,n!=="persistent"&&Ls(e,r.numericSnapshot),n!=="persistent"){Ls(e,r.standardSnapshot);for(let[i,a]of r.standardClosedSnapshot)a?(e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(i)):e.state.closedStandardFds?.delete(i)}if(n==="bare"){Ls(e,r.fdVariableSnapshot);for(let[i,a]of r.fdVariableEnv)a===void 0?e.state.env.delete(i):e.state.env.set(i,a);e.state.nextFd=r.nextFd}}}}}function Zn(e){if(!e.error)throw new Error("Expected a redirection error");if(e.errorCause)throw e.errorCause.stdout=e.error.stdout,e.errorCause.stderr=e.error.stderr,e.errorCause;return e.error}async function va(e,t,n,r){let s=t instanceof q||t instanceof Le||t instanceof ze?t.exitCode:t instanceof P?P.EXIT_CODE:0,i=await fn(e,T(t.stdout,t.stderr,s),n,r.targets,r.dupSources,r.standardRoutes);t.stdout=i.stdout,t.stderr=i.stderr,t.internalOutputAccounting=i.internalOutputAccounting??{stdout:B(i.stdout),stderr:B(i.stderr)}}async function rt(e,t,n,r){let s=Gn(e,t,gr),i;try{if(i=await s.prepare(n),i.error)return Zn(i);let a=e.state.groupStdin,o=e.state.groupStdinSourceFd;i.stdin!==void 0&&(e.state.groupStdin=i.stdin,e.state.groupStdinSourceFd=i.stdinSourceFd);try{let l=await r(i);return await fn(e,l,t,i.targets,i.dupSources,i.standardRoutes)}finally{i.stdin!==void 0&&(e.state.groupStdin=a,e.state.groupStdinSourceFd=o)}}catch(a){throw!(a instanceof Vt)||!i||await va(e,a,t,i),a}finally{s.finish()}}async function fn(e,t,n,r,s=new Map,i=new Map,a="bash",o=!1){n.length>0&&(t=e.executionScope.accountResult(t,"redirection"));let{stdout:l,stderr:u,exitCode:c}=t,d=t.stdoutKind==="bytes"||t.stdoutKind===void 0&&t.stdoutEncoding==="binary"?"binary":"utf8",p=b=>d,h={kind:"live-stdout"},m={kind:"live-stderr"},E=b=>{if(!b)return null;if(b.kind==="entry"){if(b.entry.kind==="dup-out"){if(b.entry.sourceFd===1)return{kind:"live-stdout"};if(b.entry.sourceFd===2)return{kind:"live-stderr"}}return b.entry.kind==="output"||b.entry.kind==="readwrite"?{kind:"descriptor",source:b}:null}return b.fd===1?h:b.fd===2?m:null},S=b=>{let A=i.get(b)??nt(e,b);return A?A.kind==="closed"?{kind:"invalid-output",fd:b}:A.kind==="input"||A.kind==="dup-in"?{kind:"invalid-output",fd:b}:A.kind==="dup-out"?A.sourceFd===1?{kind:"live-stdout"}:A.sourceFd===2?{kind:"live-stderr"}:null:A.kind==="output"||A.kind==="readwrite"?{kind:"descriptor",source:{kind:"entry",entry:A,descriptors:ln(e,b)}}:null:null};h=S(1)??h,m=S(2)??m;for(let b=0;b<n.length;b++){let A=n[b];if(A.target.type==="HereDoc"||A.fdVariable)continue;let k=r.get(b);if(k!==void 0)switch(A.operator){case">":case">|":case">>":{let v=A.fd??1;if(v!==1&&v!==2)break;let $=A.operator===">>";if(k==="/dev/stdout"){v===2&&(m=h);break}if(k==="/dev/stderr"){v===1&&(h=m);break}if(k==="/dev/full"){u+=`bash: echo: write error: No space left on device
|
|
153
|
+
`,c=1,v===1&&(l="");break}if(k==="/dev/null"&&v===2){m={kind:"discard"};break}let D=e.fs.resolvePath(e.state.cwd,k);v===1?h={kind:"file",path:D,append:$}:m={kind:"file",path:D,append:$};break}case">&":case"<&":{let v=A.fd??(A.operator==="<&"?0:1);if(v>=Ee||v===0)break;if(k==="-"){v===1?h={kind:"discard"}:m={kind:"discard"};break}let $=E(s.get(b));if(!$)break;A.fd==null&&Ts(k)===null?(h=$,m=$):v===1?h=$:v===2&&(m=$);break}case"&>":{h={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!1},m=h;break}case"&>>":{h={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!0},m=h;break}}}if(l!==""||u!==""){let b=l,A=u;l="",u="",h.kind==="invalid-output"&&b!==""&&(b="",A+=`${o?"":"bash: "}${a}: write error: Bad file descriptor
|
|
154
|
+
`,c=1),m.kind==="invalid-output"&&(A="");let k=async(v,$,D)=>{v.append?await e.fs.appendFile(v.path,$,D):await e.fs.writeFile(v.path,$,D)};if(h===m&&(h.kind==="file"||h.kind==="descriptor")){let v=b+A;v!==""&&(h.kind==="file"?await k(h,v,p(v)):await ba(e,h.source.entry,h.source.descriptors,v,p(v)))}else for(let[v,$,D]of[[b,h,!0],[A,m,!1]])if(v!=="")switch($.kind){case"live-stdout":l+=v;break;case"live-stderr":u+=v;break;case"file":await k($,v,D?p(v):Tc(v));break;case"descriptor":await ba(e,$.source.entry,$.source.descriptors,v,D?p(v):Tc(v));break;case"invalid-output":break;case"discard":break}}let g=T(l,u,c);if(t.stdoutKind&&(g.stdoutKind=t.stdoutKind),t.stdoutEncoding==="binary"&&(g.stdoutEncoding="binary"),t.internalPipeStatusOverride&&(g.internalPipeStatusOverride=t.internalPipeStatusOverride),n.length>0||e.state.fileDescriptors?.has(1)===!0||e.state.fileDescriptors?.has(2)===!0){let b=(t.internalOutputAccounting?.stdout??0)+(t.internalOutputAccounting?.stderr??0),A=B(g.stdout),k=B(g.stderr),v=Math.min(A,b);g.internalOutputAccounting={stdout:v,stderr:Math.min(k,b-v)},e.executionScope.accountResult(g,"redirection")}else t.internalOutputAccounting&&(g.internalOutputAccounting=t.internalOutputAccounting);return g}function Wc(e,t){if(e.state.options.posix&&sr.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
|
|
155
|
+
`;throw new q(2,"",r)}let n={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,n),ne}async function Fs(e,t,n,r="",s,i=!1){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,sn(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(s??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??"main"),e.state.localScopes.push(new Map),e.state.localArrayScopes??=[],e.state.localArrayScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let a=new Map,o=Number.parseInt(e.state.env.get("#")??"0",10),l=Math.max(n.length,o);for(let p=0;p<l;p++){let h=String(p+1);a.set(h,e.state.env.get(h)),p<n.length?e.state.env.set(h,n[p]):e.state.env.delete(h)}a.set("@",e.state.env.get("@")),a.set("#",e.state.env.get("#")),e.state.env.set("@",n.join(" ")),e.state.env.set("#",String(n.length));let u=!1,c=()=>{if(u)return;u=!0;let p=e.state.localScopes.length-1,h=e.state.localScopes.pop(),m=e.state.localArrayScopes?.pop();if(h)for(let[E,S]of h)S===void 0?e.state.env.delete(E):e.state.env.set(E,S);if(m){e.state.arrays??=new Map;for(let[E,S]of m)S===void 0?(e.state.arrays.delete(E),e.state.associativeArrays?.delete(E)):(e.state.arrays.set(E,Me(S)),e.state.associativeArrays??=new Set,S.kind==="associative"?e.state.associativeArrays.add(E):e.state.associativeArrays.delete(E))}if(Ic(e,p),e.state.fullyUnsetLocals)for(let[E,S]of e.state.fullyUnsetLocals.entries())S===p&&e.state.fullyUnsetLocals.delete(E);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let E=e.state.localExportedVars.pop();if(E)for(let S of E)e.state.exportedVars?.delete(S)}for(let[E,S]of a)S===void 0?e.state.env.delete(E):e.state.env.set(E,S);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},f=null,d=Gn(e,t.redirections,gr);try{if(f=await d.prepare(r),f.error)return Zn(f);let p=f.stdin??r,h=i||f.stdin!==void 0||r!=="",m=await e.executeCommand(t.body,p,h);return fn(e,m,t.redirections,f.targets,f.dupSources,f.standardRoutes)}catch(p){if(p instanceof Vt&&f&&(await va(e,p,t.redirections,f),p instanceof Le))return T(p.stdout,p.stderr,p.exitCode);throw p}finally{d.finish(),c()}}function Ot(e,t,n,r){let s=n+B(t)+1;if(s>r)throw new P(`shopt: output size limit exceeded (${r} bytes)`,"output_size");return e.push(t),s}var Bs=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],Vc=["autocd","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","execfail","extdebug","extquote","force_fignore","globasciiranges","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath"],zc=[...Bs,...Vc];function Ms(e){return Bs.includes(e)}function Wh(e){return Vc.includes(e)}function Uc(e,t){let n=e.limits.maxArrayElements;if(t.length>n)throw new P(`shopt: argument limit exceeded (${n})`,"array_elements");let r=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),s=!1,i=!1,a=!1,o=!1,l=!1,u=[],c=0;for(;c<t.length;){let E=t[c];if(E==="--"){c++;break}if(E.startsWith("-")&&E.length>1){for(let S=1;S<E.length;S++){let g=E[S];switch(g){case"s":s=!0;break;case"u":i=!0;break;case"p":a=!0;break;case"q":o=!0;break;case"o":l=!0;break;default:return{exitCode:2,stdout:"",stderr:`shopt: -${g}: invalid option
|
|
156
|
+
`}}}c++}else break}for(;c<t.length;)u.push(t[c]),c++;if(l)return Vh(e,u,s,i,a,o);if(s&&i)return{exitCode:1,stdout:"",stderr:`shopt: cannot set and unset shell options simultaneously
|
|
157
|
+
`};if(u.length===0){if(s||i){let S=[];for(let g of Bs){let y=e.state.shoptOptions[g];s&&y?S.push(a?`shopt -s ${g}`:`${g} on`):i&&!y&&S.push(a?`shopt -u ${g}`:`${g} off`)}return{exitCode:0,stdout:S.length>0?`${S.join(`
|
|
158
|
+
`)}
|
|
159
|
+
`:"",stderr:""}}let E=[];for(let S of Bs){let g=e.state.shoptOptions[S];E.push(a?`shopt ${g?"-s":"-u"} ${S}`:`${S} ${g?"on":"off"}`)}return{exitCode:0,stdout:`${E.join(`
|
|
160
|
+
`)}
|
|
161
|
+
`,stderr:""}}let f=!1,d=[],p=0,h=[],m=0;for(let E of u){if(!Ms(E)&&!Wh(E)){p=Ot(d,`shopt: ${E}: invalid shell option name`,p,r),f=!0;continue}if(s)Ms(E)&&(e.state.shoptOptions[E]=!0,mi(e));else if(i)Ms(E)&&(e.state.shoptOptions[E]=!1,mi(e));else if(Ms(E)){let S=e.state.shoptOptions[E];o?S||(f=!0):a?(m=Ot(h,`shopt ${S?"-s":"-u"} ${E}`,m,r),S||(f=!0)):(m=Ot(h,`${E} ${S?"on":"off"}`,m,r),S||(f=!0))}else o?f=!0:a?(m=Ot(h,`shopt -u ${E}`,m,r),f=!0):(m=Ot(h,`${E} off`,m,r),f=!0)}return{exitCode:f?1:0,stdout:h.length>0?`${h.join(`
|
|
162
|
+
`)}
|
|
163
|
+
`:"",stderr:d.length>0?`${d.join(`
|
|
164
|
+
`)}
|
|
165
|
+
`:""}}function Vh(e,t,n,r,s,i){let a=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),o=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),l=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],u=[...o.keys(),...l].sort();if(t.length===0){let m=[];for(let E of u){let S=l.includes(E),g=o.get(E),y=S||!g?!1:e.state.options[g];n&&!y||r&&y||m.push(s?`set ${y?"-o":"+o"} ${E}`:`${E} ${y?"on":"off"}`)}return{exitCode:0,stdout:m.length>0?`${m.join(`
|
|
166
|
+
`)}
|
|
167
|
+
`:"",stderr:""}}let c=!1,f=[],d=0,p=[],h=0;for(let m of t){let E=o.has(m),S=l.includes(m);if(!E&&!S){d=Ot(f,`shopt: ${m}: invalid option name`,d,a),c=!0;continue}if(S){n||r||(i?c=!0:s?(h=Ot(p,`set +o ${m}`,h,a),c=!0):(h=Ot(p,`${m} off`,h,a),c=!0));continue}let g=o.get(m);if(g)if(n)g==="vi"?e.state.options.emacs=!1:g==="emacs"&&(e.state.options.vi=!1),e.state.options[g]=!0,Fn(e);else if(r)e.state.options[g]=!1,Fn(e);else{let y=e.state.options[g];i?y||(c=!0):s?(h=Ot(p,`set ${y?"-o":"+o"} ${m}`,h,a),y||(c=!0)):(h=Ot(p,`${m} ${y?"on":"off"}`,h,a),y||(c=!0))}}return{exitCode:c?1:0,stdout:p.length>0?`${p.join(`
|
|
168
|
+
`)}
|
|
169
|
+
`:"",stderr:f.length>0?`${f.join(`
|
|
170
|
+
`)}
|
|
171
|
+
`:""}}var jc=e=>e.type==="Escaped"?F.literal(`\\${e.value}`):e.type==="DoubleQuoted"?{...e,parts:e.parts.map(jc)}:e,Hc=ir,$a=xt,zh=zc,Uh=$a;async function Pa(e,t){let n=[],r=null,s="",i="",a=null,o=!1,l=!1,u=!1,c=null,f=null,d=null,p=[],h=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let k=0;k<t.length;k++){let v=t[k];if(v==="-v")n.push("variable");else if(v==="-e")n.push("export");else if(v==="-f")n.push("file");else if(v==="-d")n.push("directory");else if(v==="-k")n.push("keyword");else if(v==="-A"){if(k++,k>=t.length)return L(`compgen: -A: option requires an argument
|
|
172
|
+
`,2);let $=t[k];if(!h.includes($))return L(`compgen: ${$}: invalid action name
|
|
173
|
+
`,2);n.push($)}else if(v==="-W"){if(k++,k>=t.length)return L(`compgen: -W: option requires an argument
|
|
174
|
+
`,2);r=t[k]}else if(v==="-P"){if(k++,k>=t.length)return L(`compgen: -P: option requires an argument
|
|
175
|
+
`,2);s=t[k]}else if(v==="-S"){if(k++,k>=t.length)return L(`compgen: -S: option requires an argument
|
|
176
|
+
`,2);i=t[k]}else if(v==="-o"){if(k++,k>=t.length)return L(`compgen: -o: option requires an argument
|
|
177
|
+
`,2);let $=t[k];if($==="plusdirs")o=!0;else if($==="dirnames")l=!0;else if($==="default")u=!0;else if(!($==="filenames"||$==="nospace"||$==="bashdefault"||$==="noquote"))return L(`compgen: ${$}: invalid option name
|
|
178
|
+
`,2)}else if(v==="-F"){if(k++,k>=t.length)return L(`compgen: -F: option requires an argument
|
|
179
|
+
`,2);f=t[k]}else if(v==="-C"){if(k++,k>=t.length)return L(`compgen: -C: option requires an argument
|
|
180
|
+
`,2);d=t[k]}else if(v==="-X"){if(k++,k>=t.length)return L(`compgen: -X: option requires an argument
|
|
181
|
+
`,2);c=t[k]}else if(v==="-G"){if(k++,k>=t.length)return L(`compgen: -G: option requires an argument
|
|
182
|
+
`,2)}else if(v==="--"){p.push(...t.slice(k+1));break}else v.startsWith("-")||p.push(v)}a=p[0]??null;let m=[],E=new Set,S=()=>e.limits.maxArrayElements-m.length,g=k=>{for(let v of k){if(m.length>=e.limits.maxArrayElements)throw new P(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(v)>e.limits.maxStringLength)throw new P(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");e.executionScope.consumeWork(1,"compgen completion"),m.push(v),E.add(v)}};if(l){let k=await ka(e,a,S());g(k)}if(u){let k=await qc(e,a,S());g(k)}for(let k of n)if(k==="variable"){let v=qh(e,a,S());g(v)}else if(k==="export"){let v=jh(e,a,S());g(v)}else if(k==="function"){let v=Hh(e,a,S());g(v)}else if(k==="builtin"){let v=Gh(e,a,S());g(v)}else if(k==="keyword"){let v=Zh(e,a,S());g(v)}else if(k==="alias"){let v=Qh(e,a,S());g(v)}else if(k==="shopt"){let v=Kh(e,a,S());g(v)}else if(k==="helptopic"){let v=Xh(e,a,S());g(v)}else if(k==="directory"){let v=await ka(e,a,S());g(v)}else if(k==="file"){let v=await qc(e,a,S());g(v)}else if(k==="user"){let v=Yh(e,a,S());g(v)}else if(k==="command"){let v=await Jh(e,a,S());g(v)}if(r!==null)try{let k=await em(e,r),v=tm(e,k,S(),a);for(let $ of v)g([$])}catch(k){if(k instanceof P)throw k;return T("","",1)}if(o){let k=await ka(e,a,S(),E);for(let v of k)E.has(v)||g([v])}let y="";if(f!==null){let k=e.state.functions.get(f);if(k){let v=new Map,$=ke(e,"COMP_WORDS"),D=$?Me($):void 0;ge(e,"COMP_WORDS"),nr(e,"COMP_WORDS"),v.set("COMP_CWORD",e.state.env.get("COMP_CWORD")),e.state.env.set("COMP_CWORD","-1"),v.set("COMP_LINE",e.state.env.get("COMP_LINE")),e.state.env.set("COMP_LINE",""),v.set("COMP_POINT",e.state.env.get("COMP_POINT")),e.state.env.set("COMP_POINT","0");let x=ke(e,"COMPREPLY"),C=x?Me(x):void 0,I=e.state.env.get("COMPREPLY");ge(e,"COMPREPLY"),e.state.env.delete("COMPREPLY");let W=["compgen",p[0]??"",""];try{let Z=await Fs(e,k,W,"");if(Z.exitCode!==0)return xa(e,v),Qn(e,"COMP_WORDS",D),Qn(e,"COMPREPLY",C),I!==void 0&&e.state.env.set("COMPREPLY",I),T("",Z.stderr,1);y=Z.stdout;let R=nm(e,S());g(R)}catch(Z){if(Z instanceof P)throw Z;return xa(e,v),Qn(e,"COMP_WORDS",D),Qn(e,"COMPREPLY",C),I!==void 0&&e.state.env.set("COMPREPLY",I),T("","",1)}xa(e,v),Qn(e,"COMP_WORDS",D),Qn(e,"COMPREPLY",C),I!==void 0&&e.state.env.set("COMPREPLY",I)}}if(d!==null)try{let k=ot(d),v=await e.executeScript(k);if(v.exitCode!==0)return T("",v.stderr,v.exitCode);if(v.stdout)for(let $ of rm(v.stdout))$.length>0&&g([$])}catch(k){if(k.name==="ParseException")return L(`compgen: -C: ${k.message}
|
|
183
|
+
`,2);throw k}let b=m;if(c!==null){let k=c.startsWith("!"),v=k?c.slice(1):c;b=m.filter($=>{let D=Un($,v,!1,!0,e.limits.maxCallDepth);return k?D:!D})}if(b.length===0&&a!==null)return T(y,"",1);let A=new Nn(e.limits.maxOutputSize,"compgen");A.append(y);for(let k of b)A.append(s).append(k).append(i).append(`
|
|
184
|
+
`);return ee(A.build())}function qh(e,t,n){let r=ct(e,t,n);for(let s of e.state.env.keys())/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)&&r.add(s);for(let s of e.state.arrays?.keys()??[])r.add(s);return r.build()}function jh(e,t,n){let r=ct(e,t,n),s=e.state.exportedVars??new Set;for(let i of s)e.state.env.has(i)&&r.add(i);return r.build()}function Hh(e,t,n){let r=ct(e,t,n);for(let s of e.state.functions.keys())r.add(s);return r.build()}function Gh(e,t,n){let r=ct(e,t,n);for(let s of $a)r.add(s);return r.build()}function Zh(e,t,n){let r=ct(e,t,n);for(let s of Hc)r.add(s);return r.build()}function Qh(e,t,n){let r=ct(e,t,n);for(let s of e.state.env.keys())if(s.startsWith("BASH_ALIAS_")){let i=s.slice(11);r.add(i)}return r.build()}function Kh(e,t,n){let r=ct(e,t,n);for(let s of zh)r.add(s);return r.build()}function Xh(e,t,n){let r=ct(e,t,n);for(let s of Uh)r.add(s);return r.build()}async function ka(e,t,n=e.limits.maxArrayElements,r){let s=ct(e,null,n,r);try{let i=e.state.cwd,a=t??"";if(t){let l=t.lastIndexOf("/");if(l!==-1){let u=t.slice(0,l)||"/";a=t.slice(l+1),u.startsWith("/")?i=u:i=`${e.state.cwd}/${u}`}}let o=await e.fs.readdir(i);for(let l of o){e.executionScope.consumeWork(1,"compgen directory scan");let u=`${i}/${l}`;try{if((await e.fs.stat(u)).isDirectory&&(!a||l.startsWith(a)))if(t?.includes("/")){let f=t.lastIndexOf("/"),d=t.slice(0,f+1);s.add(d+l)}else s.add(l)}catch(c){if(c instanceof P)throw c}}}catch(i){if(i instanceof P)throw i}return s.build()}async function qc(e,t,n=e.limits.maxArrayElements){let r=ct(e,null,n);try{let s=e.state.cwd,i=t??"";if(t){let o=t.lastIndexOf("/");if(o!==-1){let l=t.slice(0,o)||"/";i=t.slice(o+1),l.startsWith("/")?s=l:s=`${e.state.cwd}/${l}`}}let a=await e.fs.readdir(s);for(let o of a)if(e.executionScope.consumeWork(1,"compgen file scan"),!i||o.startsWith(i))if(t?.includes("/")){let l=t.lastIndexOf("/"),u=t.slice(0,l+1);r.add(u+o)}else r.add(o)}catch(s){if(s instanceof P)throw s}return r.build()}function Yh(e,t,n){let r=ct(e,t,n);return r.add("root"),r.add("nobody"),r.build()}async function Jh(e,t,n){let r=ct(e,t,n);for(let i of $a)r.add(i);for(let i of e.state.functions.keys())r.add(i);for(let i of e.state.env.keys())i.startsWith("BASH_ALIAS_")&&r.add(i.slice(11));for(let i of Hc)r.add(i);let s=e.state.env.get("PATH")??"/usr/bin:/bin";for(let i of s.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let o of a)r.add(o)}catch(a){if(a instanceof P)throw a}return r.build()}function ct(e,t,n,r){let s=new Set;return{add(i){if(e.executionScope.consumeWork(1,"compgen candidate collection"),!(t!==null&&!i.startsWith(t))&&!r?.has(i)&&!s.has(i)){if(s.size>=n)throw new P(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(i)>e.limits.maxStringLength)throw new P(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");s.add(i)}},build(){return Array.from(s).sort()}}}async function em(e,t){let r=new H().parseWordFromString(t,!1,!1);return await ie(e,F.word(r.parts.map(jc)))}function tm(e,t,n,r){let s=e.state.env.get("IFS")??`
|
|
185
|
+
`;if(s.length===0){if(r!==null&&!t.startsWith(r))return[];if(n===0)throw new P(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");return[t]}let i=new Set(s.split("")),a=[],o=c=>{if(!(r!==null&&!c.startsWith(r))){if(a.length>=n)throw new P(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");a.push(c)}},l="",u=0;for(;u<t.length;){let c=t[u];if(c==="\\"&&u+1<t.length){let f=t[u+1];l+=f,u+=2}else i.has(c)?(l.length>0&&(o(l),l=""),u++):(l+=c,u++)}return l.length>0&&o(l),a}function xa(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function Qn(e,t,n){e.state.arrays??=new Map,n?e.state.arrays.set(t,Me(n)):e.state.arrays.delete(t)}function nm(e,t){let n=[],r=s=>{if(n.length>=t)throw new P(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");n.push(s)};if(Ne(e,"COMPREPLY")){let s=G(e,"COMPREPLY");for(let[,i]of s)r(i)}else{let s=e.state.env.get("COMPREPLY");s!==void 0&&r(s)}return n}function*rm(e){let t=0;for(;t<=e.length;){let n=e.indexOf(`
|
|
186
|
+
`,t),r=n===-1?e.length:n;if(r>t&&(yield e.slice(t,r)),n===-1)return;t=n+1}}function wr(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function Ca(e){let t="$'";for(let n=0;n<e.length;n++){let r=e[n],s=e.charCodeAt(n);s===7?t+="\\a":s===8?t+="\\b":s===9?t+="\\t":s===10?t+="\\n":s===11?t+="\\v":s===12?t+="\\f":s===13?t+="\\r":s===27?t+="\\e":s===39?t+="\\'":s===92?t+="\\\\":s<32||s===127?t+=`\\${s.toString(8).padStart(3,"0")}`:t+=r}return t+="'",t}function Gc(e){if(wr(e))return Zc(e);if(e==="")return 2;if(/^[a-zA-Z0-9_/.:\-@%+,=]+$/.test(e))return B(e);let t=B(e)+2;for(let n of e)n==="'"&&(t+=3);return t}function be(e){return wr(e)?Ca(e):e===""?"''":/^[a-zA-Z0-9_/.:\-@%+,=]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Ws(e){if(wr(e))return Zc(e);let t=B(e)+2;for(let n of e)(n==="\\"||n==='"'||n==="$"||n==="`")&&t++;return t}function dn(e){return wr(e)?Ca(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}function Zc(e){let t=3;for(let n of e){let r=n.codePointAt(0)??0;r===7||r===8||r===9||r===10||r===11||r===12||r===13||r===27||r===39||r===92?t+=2:r<32||r===127?t+=4:t+=B(n)}return t}function Er(e){return wr(e)?Ca(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}var sm=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function Ra(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,s=!1,i,a,o,l=[],u=[],c=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")n=!0;else if(d==="-r")r=!0;else if(d==="-D")s=!0;else if(d==="-W"){if(f++,f>=t.length)return L(`complete: -W: option requires an argument
|
|
187
|
+
`,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return L(`complete: -F: option requires an argument
|
|
188
|
+
`,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return L(`complete: -o: option requires an argument
|
|
189
|
+
`,2);let p=t[f];if(!sm.includes(p))return L(`complete: ${p}: invalid option name
|
|
190
|
+
`,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return L(`complete: -A: option requires an argument
|
|
191
|
+
`,2);u.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return L(`complete: -C: option requires an argument
|
|
192
|
+
`,2);o=t[f]}else if(d==="-G"){if(f++,f>=t.length)return L(`complete: -G: option requires an argument
|
|
193
|
+
`,2)}else if(d==="-P"){if(f++,f>=t.length)return L(`complete: -P: option requires an argument
|
|
194
|
+
`,2)}else if(d==="-S"){if(f++,f>=t.length)return L(`complete: -S: option requires an argument
|
|
195
|
+
`,2)}else if(d==="-X"){if(f++,f>=t.length)return L(`complete: -X: option requires an argument
|
|
196
|
+
`,2)}else if(d==="--"){c.push(...t.slice(f+1));break}else d.startsWith("-")||c.push(d)}if(r){if(c.length===0)return e.state.completionSpecs.clear(),e.state.defaultCompletionSpec=void 0,e.state.emptyCompletionSpec=void 0,ee("");for(let f of c)e.state.completionSpecs.delete(f);return ee("")}if(n)return c.length===0?Na(e):Na(e,c);if(t.length===0||c.length===0&&!i&&!a&&!o&&l.length===0&&u.length===0&&!s)return Na(e);if(a&&c.length===0&&!s)return L(`complete: -F: option requires a command name
|
|
197
|
+
`,2);if(s){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),a!==void 0&&(f.function=a),o!==void 0&&(f.command=o),l.length>0&&(f.options=l),u.length>0&&(f.actions=u),e.state.defaultCompletionSpec=f,ee("")}for(let f of c){let d=Object.create(null);i!==void 0&&(d.wordlist=i),a!==void 0&&(d.function=a),o!==void 0&&(d.command=o),l.length>0&&(d.options=l),u.length>0&&(d.actions=u),e.state.completionSpecs.set(f,d)}return ee("")}function Na(e,t){let n=e.state.completionSpecs??new Map;if(n.size===0&&!e.state.defaultCompletionSpec){if(t&&t.length>0){let i="";for(let a of t)i+=`complete: ${a}: no completion specification
|
|
198
|
+
`;return T("",i,1)}return ee("")}let r=[],s=t||Array.from(n.keys());for(let i of s){let a=n.get(i);if(!a){if(t)return T(r.join(`
|
|
183
199
|
`)+(r.length>0?`
|
|
184
200
|
`:""),`complete: ${i}: no completion specification
|
|
185
|
-
`,1);continue}let
|
|
201
|
+
`,1);continue}let o="complete";if(a.options)for(let l of a.options)o+=` -o ${be(l)}`;if(a.actions)for(let l of a.actions)o+=` -A ${be(l)}`;a.wordlist!==void 0&&(a.wordlist.includes(" ")||a.wordlist.includes("'")?o+=` -W ${be(a.wordlist)}`:o+=` -W ${be(a.wordlist)}`),a.function!==void 0&&(o+=` -F ${be(a.function)}`),a.command!==void 0&&(o+=` -C ${be(a.command)}`),a.isDefault&&(o+=" -D"),o+=`${i.startsWith("-")?" -- ":" "}${be(i)}`,r.push(o)}if(!t&&e.state.defaultCompletionSpec){let i=e.state.defaultCompletionSpec,a="complete";for(let o of i.options??[])a+=` -o ${be(o)}`;for(let o of i.actions??[])a+=` -A ${be(o)}`;i.wordlist!==void 0&&(a+=` -W ${be(i.wordlist)}`),i.function!==void 0&&(a+=` -F ${be(i.function)}`),i.command!==void 0&&(a+=` -C ${be(i.command)}`),a+=" -D",r.push(a)}return r.length===0?ee(""):ee(`${r.join(`
|
|
186
202
|
`)}
|
|
187
|
-
`)}var
|
|
188
|
-
`,2);let u=t[
|
|
189
|
-
`,2);s.push(u)}else if(l==="+o"){if(
|
|
190
|
-
`,2);let u=t[
|
|
191
|
-
`,2);i.push(u)}else if(l==="--"){
|
|
192
|
-
`,1)}function
|
|
193
|
-
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new
|
|
194
|
-
`);n=r}throw new
|
|
195
|
-
`;else{let f=c.map(d=>{let p=oe(e,i,d)??"",h=
|
|
196
|
-
`}continue}let l=
|
|
197
|
-
`;continue}if(
|
|
198
|
-
`;continue}let u=e.state.env.get(i);if(u!==void 0)n+=`declare ${
|
|
199
|
-
`;else{let c=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);c||f?n+=`declare ${
|
|
203
|
+
`)}var Qc=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function Da(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,s=[],i=[],a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-D")n=!0;else if(l==="-E")r=!0;else if(l==="-o"){if(o++,o>=t.length)return L(`compopt: -o: option requires an argument
|
|
204
|
+
`,2);let u=t[o];if(!Qc.includes(u))return L(`compopt: ${u}: invalid option name
|
|
205
|
+
`,2);s.push(u)}else if(l==="+o"){if(o++,o>=t.length)return L(`compopt: +o: option requires an argument
|
|
206
|
+
`,2);let u=t[o];if(!Qc.includes(u))return L(`compopt: ${u}: invalid option name
|
|
207
|
+
`,2);i.push(u)}else if(l==="--"){a.push(...t.slice(o+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&a.push(l)}if(n){let o=e.state.defaultCompletionSpec??{isDefault:!0},l=new Set(o.options??[]);for(let u of s)l.add(u);for(let u of i)l.delete(u);return o.options=l.size>0?Array.from(l):void 0,e.state.defaultCompletionSpec=o,ee("")}if(r){let o=e.state.emptyCompletionSpec??Object.create(null),l=new Set(o.options??[]);for(let u of s)l.add(u);for(let u of i)l.delete(u);return o.options=l.size>0?Array.from(l):void 0,e.state.emptyCompletionSpec=o,ee("")}if(a.length>0){for(let o of a){let l=e.state.completionSpecs.get(o)??{},u=new Set(l.options??[]);for(let c of s)u.add(c);for(let c of i)u.delete(c);l.options=u.size>0?Array.from(u):void 0,e.state.completionSpecs.set(o,l)}return ee("")}return L(`compopt: not currently executing completion function
|
|
208
|
+
`,1)}function Ia(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Ut;return ne}if(t.length>1)throw new q(1,"",`bash: continue: too many arguments
|
|
209
|
+
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new q(1,"",`bash: continue: ${t[0]}: numeric argument required
|
|
210
|
+
`);n=r}throw new Ke(n)}function Kc(e,t){let n="";return e.state.integerVars?.has(t)&&(n+="i"),e.state.lowercaseVars?.has(t)&&(n+="l"),ue(e,t)&&(n+="n"),e.state.readonlyVars?.has(t)&&(n+="r"),e.state.uppercaseVars?.has(t)&&(n+="u"),e.state.exportedVars?.has(t)&&(n+="x"),n===""?"--":`-${n}`}function Oa(e){return be(e)}function _a(e){return`'${e.replace(/'/g,"'\\''")}'`}function Xc(e,t){let n="",r="",s=!1;for(let i of t){let a=Kc(e,i);if(e.state.associativeArrays?.has(i)){let c=Pt(e,i);if(c.length===0)n+=`declare -A ${i}=()
|
|
211
|
+
`;else{let f=c.map(d=>{let p=oe(e,i,d)??"",h=Oa(p);return`[${_a(d)}]=${h}`});n+=`declare -A ${i}=(${f.join(" ")})
|
|
212
|
+
`}continue}let l=Se(e,i);if(l.length>0){let c=l.map(f=>{let d=oe(e,i,f)??"";return`[${f}]=${dn(d)}`});n+=`declare -a ${i}=(${c.join(" ")})
|
|
213
|
+
`;continue}if(Ne(e,i)){n+=`declare -a ${i}=()
|
|
214
|
+
`;continue}let u=e.state.env.get(i);if(u!==void 0)n+=`declare ${a} ${i}=${Er(u)}
|
|
215
|
+
`;else{let c=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);c||f?n+=`declare ${a} ${i}
|
|
200
216
|
`:(r+=`bash: declare: ${i}: not found
|
|
201
|
-
`,s=!0)}}return
|
|
202
|
-
`;else{let g=S.map(y=>{let b=oe(e,f,y)??"",A=
|
|
203
|
-
`}continue}if(h.length>0){let S=h.map(g=>{let y=oe(e,f,g)??"";return`[${g}]=${
|
|
204
|
-
`;continue}if(
|
|
205
|
-
`;continue}let E=e.state.env.get(f);E!==void 0&&(l+=`declare ${d} ${f}=${
|
|
206
|
-
`)}return
|
|
207
|
-
`;else{let i=s.map(
|
|
208
|
-
`}}return
|
|
209
|
-
`;else{let
|
|
210
|
-
`}}return
|
|
211
|
-
`)}return
|
|
212
|
-
`,2)}}}else if(C==="-i")d=!0;else if(C==="-l")p=!0;else if(C==="-u")h=!0;else if(C==="-f")m=!0;else if(C==="-F")E=!0;else if(C==="-g")S=!0;else if(C.startsWith("-"))for(let
|
|
213
|
-
`,2);else g.push(C)}let b=e.state.localScopes.length>0&&!S,A
|
|
214
|
-
`;return
|
|
215
|
-
|
|
217
|
+
`,s=!0)}}return T(n,r,s?1:0)}function Yc(e,t){let{filterExport:n,filterReadonly:r,filterNameref:s,filterIndexedArray:i,filterAssocArray:a}=t,o=n||r||s||i||a,l="",u=new Set;for(let f of e.state.env.keys())f.startsWith("BASH_")||u.add(f);for(let f of e.state.arrays?.keys()??[])u.add(f);if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())u.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)u.add(f);let c=Array.from(u).sort();for(let f of c){let d=Kc(e,f),p=e.state.associativeArrays?.has(f),h=Se(e,f),m=!p&&Ne(e,f);if(o&&(a&&!p||i&&!m||n&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||s&&!ue(e,f)))continue;if(p){let S=Pt(e,f);if(S.length===0)l+=`declare -A ${f}=()
|
|
218
|
+
`;else{let g=S.map(y=>{let b=oe(e,f,y)??"",A=Oa(b);return`[${_a(y)}]=${A}`});l+=`declare -A ${f}=(${g.join(" ")})
|
|
219
|
+
`}continue}if(h.length>0){let S=h.map(g=>{let y=oe(e,f,g)??"";return`[${g}]=${dn(y)}`});l+=`declare -a ${f}=(${S.join(" ")})
|
|
220
|
+
`;continue}if(Ne(e,f)){l+=`declare -a ${f}=()
|
|
221
|
+
`;continue}let E=e.state.env.get(f);E!==void 0&&(l+=`declare ${d} ${f}=${Er(E)}
|
|
222
|
+
`)}return ee(l)}function Jc(e){let t="",n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let s=Pt(e,r);if(s.length===0)t+=`declare -A ${r}=()
|
|
223
|
+
`;else{let i=s.map(a=>{let o=oe(e,r,a)??"",l=Oa(o);return`[${_a(a)}]=${l}`});t+=`declare -A ${r}=(${i.join(" ")})
|
|
224
|
+
`}}return ee(t)}function ef(e){let t="",n=new Set(Array.from(e.state.arrays??[]).filter(([,s])=>s.kind==="indexed").map(([s])=>s)),r=Array.from(n).sort();for(let s of r){let i=Se(e,s);if(i.length===0)t+=`declare -a ${s}=()
|
|
225
|
+
`;else{let a=i.map(o=>{let l=oe(e,s,o)??"";return`[${o}]=${dn(l)}`});t+=`declare -a ${s}=(${a.join(" ")})
|
|
226
|
+
`}}return ee(t)}function tf(e){let t="",n=new Set;for(let s of e.state.env.keys())s.startsWith("BASH_")||n.add(s);let r=Array.from(n).sort();for(let s of r){if(e.state.associativeArrays?.has(s)||Se(e,s).length>0||Ne(e,s))continue;let o=e.state.env.get(s);o!==void 0&&(t+=`${s}=${be(o)}
|
|
227
|
+
`)}return ee(t)}function La(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function br(e,t){return e.state.integerVars?.has(t)??!1}function Ta(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function im(e,t){return e.state.lowercaseVars?.has(t)??!1}function Fa(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function am(e,t){return e.state.uppercaseVars?.has(t)??!1}function Kn(e,t,n){return im(e,t)?n.toLowerCase():am(e,t)?n.toUpperCase():n}async function nf(e,t){try{let n=new H,r=se(n,t),s=await Y(e,r.expression);return String(s)}catch{return"0"}}function om(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let n=t[0],r=n.length;if(e[r]!=="[")return null;let s=0,i=r+1;for(;r<e.length;r++)if(e[r]==="[")s++;else if(e[r]==="]"&&(s--,s===0))break;if(s!==0)return null;let a=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let o=e.slice(r);return{name:n,indexExpr:a,value:o}}async function Vs(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,a=!1,o=!1,l=!1,u=!1,c=!1,f=!1,d=!1,p=!1,h=!1,m=!1,E=!1,S=!1,g=[];for(let x=0;x<t.length;x++){let C=t[x];if(C==="-a")r=!0;else if(C==="-A")s=!0;else if(C==="-r")i=!0;else if(C==="-x")a=!0;else if(C==="-p")o=!0;else if(C==="-n")l=!0;else if(C==="+n")u=!0;else if(C==="+a")c=!0;else if(C==="+x")f=!0;else if(C==="--"){g.push(...t.slice(x+1));break}else if(C.startsWith("+")){for(let I of C.slice(1))if(I==="n")u=!0;else if(I==="a")c=!0;else if(I==="x")f=!0;else if(I!=="r"){if(I!=="i"){if(!(I==="f"||I==="F"))return T("",`bash: typeset: +${I}: invalid option
|
|
228
|
+
`,2)}}}else if(C==="-i")d=!0;else if(C==="-l")p=!0;else if(C==="-u")h=!0;else if(C==="-f")m=!0;else if(C==="-F")E=!0;else if(C==="-g")S=!0;else if(C.startsWith("-"))for(let I of C.slice(1))if(I==="a")r=!0;else if(I==="A")s=!0;else if(I==="r")i=!0;else if(I==="x")a=!0;else if(I==="p")o=!0;else if(I==="n")l=!0;else if(I==="i")d=!0;else if(I==="l")p=!0;else if(I==="u")h=!0;else if(I==="f")m=!0;else if(I==="F")E=!0;else if(I==="g")S=!0;else return T("",`bash: typeset: -${I}: invalid option
|
|
229
|
+
`,2);else g.push(C)}let b=e.state.localScopes.length>0&&!S,A=x=>{if(!b)return;let C=e.state.localScopes[e.state.localScopes.length-1];C.has(x)||C.set(x,e.state.env.get(x))},k=x=>{if(!b)return;let C=e.state.localScopes[e.state.localScopes.length-1];for(C.has(x)||C.set(x,e.state.env.get(x)),e.state.localArrayScopes??=[];e.state.localArrayScopes.length<e.state.localScopes.length;)e.state.localArrayScopes.push(new Map);let I=e.state.localArrayScopes.at(-1);if(I&&!I.has(x)){let W=ke(e,x);I.set(x,W?Me(W):void 0)}},v=x=>{b&&on(e,x)};if(E){if(g.length===0){let I=Array.from(e.state.functions.keys()).sort(),W="";for(let Z of I)W+=`declare -f ${Z}
|
|
230
|
+
`;return ee(W)}let x=!0,C="";for(let I of g)e.state.functions.has(I)?C+=`${I}
|
|
231
|
+
`:x=!1;return T(C,"",x?0:1)}if(m){if(g.length===0){let C="",I=Array.from(e.state.functions.keys()).sort();for(let W of I)C+=`${W} ()
|
|
216
232
|
{
|
|
217
233
|
# function body
|
|
218
234
|
}
|
|
219
|
-
`;return
|
|
220
|
-
`,
|
|
221
|
-
`,
|
|
222
|
-
`,
|
|
223
|
-
`,
|
|
224
|
-
`,
|
|
225
|
-
`,
|
|
226
|
-
`}}return
|
|
227
|
-
`,2);r=t[
|
|
228
|
-
`,2);if(r!==void 0)return
|
|
229
|
-
`,2);r=l}}if(r===void 0){if(n.length<2)return
|
|
230
|
-
`,1);let
|
|
231
|
-
`,1)}catch{return
|
|
232
|
-
`,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=s,e.state.env.set("PWD",s),e.state.env.set("OLDPWD",e.state.previousDir);let i=e.state.env.get("HOME")||"",
|
|
233
|
-
`;return
|
|
234
|
-
`,2):
|
|
235
|
-
`,2);if(n.length===0)return
|
|
236
|
-
`,1);let r=n.shift();if(!r)return
|
|
237
|
-
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set("PWD",r),e.state.env.set("OLDPWD",e.state.previousDir);let s=e.state.env.get("HOME")||"",i=`${[r,...n].map(
|
|
238
|
-
`;return
|
|
239
|
-
`,2);else return
|
|
240
|
-
`,1);if(r)return e.state.directoryStack=[],
|
|
235
|
+
`;return ee(C)}let x=!0;for(let C of g)e.state.functions.has(C)||(x=!1);return T("","",x?0:1)}if(o&&g.length>0)return Xc(e,g);if(o&&g.length===0)return Yc(e,{filterExport:a,filterReadonly:i,filterNameref:l,filterIndexedArray:r,filterAssocArray:s});if(g.length===0&&s&&!o)return Jc(e);if(g.length===0&&r&&!o)return ef(e);if(g.length===0&&!o)return tf(e);let $="",D=0;for(let x of g){let C=x.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(C&&!c){let R=C[1],V=C[2],z=ce(e,R);if(z)return z;if(s&&Se(e,R).length>0){$+=`bash: declare: ${R}: cannot convert indexed to associative array
|
|
236
|
+
`,D=1;continue}if((r||!s&&!r)&&e.state.associativeArrays?.has(R)){$+=`bash: declare: ${R}: cannot convert associative to indexed array
|
|
237
|
+
`,D=1;continue}let O=s&&V.includes("[")?Cs(V,n):void 0,_=O===void 0?Bt(V,{...n,maxElements:s?n.maxElements*2:n.maxElements}):void 0;if(e.executionScope.consumeWork(O?.length??_?.length??0,"declare array assignment"),k(R),s?(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(R),Qt(e,R,"associative")):Qt(e,R,"indexed"),ge(e,R),e.state.env.delete(R),s&&V.includes("["))for(let[M,re]of O??[])j(e,R,M,nn(e,re),"associative");else if(s){let M=_??[];for(let re=0;re<M.length;re+=2){let K=M[re],_e=re+1<M.length?M[re+1]:"";j(e,R,K,_e,"associative")}}else{let M=_??[];if(M.some(K=>/^\[[^\]]+\]=/.test(K))){let K=0;for(let _e of M){let ft=_e.match(/^\[([^\]]+)\]=(.*)$/);if(ft){let _t=ft[1],dt=ft[2],pt;if(/^-?\d+$/.test(_t))pt=Number.parseInt(_t,10);else try{let Lt=new H,od=se(Lt,_t);pt=await Y(e,od.expression)}catch{pt=0}j(e,R,pt,nn(e,dt)),K=pt+1}else j(e,R,K,_e),K++}}else for(let K=0;K<M.length;K++)j(e,R,K,M[K])}v(R),i&&Ge(e,R),a&&wt(e,R);continue}if(u){let R=x.includes("=")?x.slice(0,x.indexOf("=")):x;if(Xl(e,R),!x.includes("="))continue}if(f){let R=x.includes("=")?x.slice(0,x.indexOf("=")):x;if(os(e,R),!x.includes("="))continue}let I=om(x);if(I){let{name:R,indexExpr:V,value:z}=I,O=ce(e,R);if(O)return O;k(R);let _;try{let M=new H,re=se(M,V);_=await Y(e,re.expression)}catch{let M=parseInt(V,10);_=Number.isNaN(M)?0:M}j(e,R,_,z),v(R),i&&Ge(e,R),a&&wt(e,R);continue}let W=x.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(W&&!c){let R=W[1],V=W[2],z=ce(e,R);if(z)return z;k(R);let O=Bt(V,n);if(e.state.associativeArrays?.has(R)){let _=Cs(V,n);e.executionScope.consumeWork(_.length,"declare array append"),wn(e,R,_.map(([M])=>M));for(let[M,re]of _)j(e,R,M,re,"associative")}else{e.executionScope.consumeWork(O.length,"declare array append");let _=Se(e,R),M=0,re=e.state.env.get(R);_.length===0&&re!==void 0?(j(e,R,0,re),e.state.env.delete(R),M=1):_.length>0&&(M=Math.max(..._)+1),wn(e,R,Array.from({length:O.length},(K,_e)=>M+_e));for(let K=0;K<O.length;K++)j(e,R,M+K,O[K])}v(R),i&&Ge(e,R),a&&wt(e,R);continue}let Z=x.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(Z){let R=Z[1],V=Z[2],z=ce(e,R);if(z)return z;A(R),d&&La(e,R),p&&Ta(e,R),h&&Fa(e,R);let _=Se(e,R).length>0||e.state.associativeArrays?.has(R);if(br(e,R)){let M=e.state.env.get(R)??"0",re=parseInt(M,10)||0,K=parseInt(await nf(e,V),10)||0;V=String(re+K),e.state.env.set(R,V)}else if(_){V=Kn(e,R,V);let M=oe(e,R,0)??"";j(e,R,0,qt([M,V],"",e.limits.maxStringLength,"declare append"))}else{V=Kn(e,R,V);let M=e.state.env.get(R)??"";e.state.env.set(R,qt([M,V],"",e.limits.maxStringLength,"declare append"))}v(R),i&&Ge(e,R),a&&wt(e,R),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(R));continue}if(x.includes("=")){let R=x.indexOf("="),V=x.slice(0,R),z=x.slice(R+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(V)){$+=`bash: typeset: \`${V}': not a valid identifier
|
|
238
|
+
`,D=1;continue}let O=ce(e,V);if(O)return O;if(A(V),l){if(z!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(z)){$+=`bash: declare: \`${z}': invalid variable name for name reference
|
|
239
|
+
`,D=1;continue}e.state.env.set(V,z),Mt(e,V),z!==""&&rs(e,z)&&qi(e,V),v(V),i&&Ge(e,V),a&&wt(e,V);continue}if(d&&La(e,V),p&&Ta(e,V),h&&Fa(e,V),br(e,V)&&(z=await nf(e,z)),z=Kn(e,V,z),ue(e,V)){let _=Be(e,V);_&&_!==V?e.state.env.set(_,z):e.state.env.set(V,z)}else e.state.env.set(V,z);v(V),i&&Ge(e,V),a&&wt(e,V),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(V))}else{let R=x;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(R)){$+=`bash: typeset: \`${R}': not a valid identifier
|
|
240
|
+
`,D=1;continue}if(r||s?k(R):A(R),l){Mt(e,R);let z=e.state.env.get(R);z!==void 0&&z!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(z)?Yl(e,R):z&&rs(e,z)&&qi(e,R),v(R),i&&Ge(e,R),a&&wt(e,R);continue}if(d&&La(e,R),p&&Ta(e,R),h&&Fa(e,R),s){if(Se(e,R).length>0){$+=`bash: declare: ${R}: cannot convert indexed to associative array
|
|
241
|
+
`,D=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(R),Qt(e,R,"associative")}let V=Ne(e,R);!e.state.env.has(R)&&!V&&(r||s?Qt(e,R,s?"associative":"indexed"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(R))),v(R),i&&Ge(e,R),a&&wt(e,R)}}return T("",$,D)}async function Ma(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-a")r=!0;else if(l==="-A")s=!0;else if(l==="-p")i=!0;else if(l==="--"){a.push(...t.slice(o+1));break}else l.startsWith("-")||a.push(l)}if(a.length===0){let o="",l=Array.from(e.state.readonlyVars||[]).sort();for(let u of l){let c=e.state.env.get(u);if(c!==void 0){let f=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"');o+=`declare -r ${u}="${f}"
|
|
242
|
+
`}}return ee(o)}for(let o of a){let l=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(l){let d=l[1],p=l[2],h=ce(e,d);if(h)return h;let m=Bt(p,n);if(e.state.associativeArrays?.has(d)){let E=Cs(p,n);e.executionScope.consumeWork(E.length,"readonly array append"),wn(e,d,E.map(([S])=>S));for(let[S,g]of E)j(e,d,S,g,"associative")}else{e.executionScope.consumeWork(m.length,"readonly array append");let E=Se(e,d),S=0,g=e.state.env.get(d);E.length===0&&g!==void 0?(j(e,d,0,g),e.state.env.delete(d),S=1):E.length>0&&(S=Math.max(...E)+1),wn(e,d,Array.from({length:m.length},(y,b)=>S+b));for(let y=0;y<m.length;y++)j(e,d,S+y,m[y])}Ge(e,d);continue}let u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u){let d=u[1],p=u[2],h=ce(e,d);if(h)return h;let m=e.state.env.get(d)??"";e.state.env.set(d,qt([m,p],"",e.limits.maxStringLength,"readonly append")),Ge(e,d);continue}let c=Nc(o,n);if(c.value===void 0&&!c.isArray){Ge(e,c.name);continue}let f=await Rc(e,c,{makeReadonly:!0});if(f)return f}return ne}function Ba(e){return e.state.directoryStack??=[],e.state.directoryStack}function Sr(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function lm(e){let t=e.split("/").filter(r=>r&&r!=="."),n=[];for(let r of t)r===".."?n.pop():n.push(r);return`/${n.join("/")}`}async function Wa(e,t){let n=Ba(e),r;for(let o=0;o<t.length;o++){let l=t[o];if(l==="--"){if(o+1<t.length){if(r!==void 0)return L(`bash: pushd: too many arguments
|
|
243
|
+
`,2);r=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return L(`bash: pushd: ${l}: invalid option
|
|
244
|
+
`,2);if(r!==void 0)return L(`bash: pushd: too many arguments
|
|
245
|
+
`,2);r=l}}if(r===void 0){if(n.length<2)return L(`bash: pushd: no other directory
|
|
246
|
+
`,1);let o=n[0];n[0]=n[1],n[1]=o,r=n[0]}let s;if(r.startsWith("/"))s=r;else if(r===".."){let o=e.state.cwd.split("/").filter(l=>l);o.pop(),s=`/${o.join("/")}`}else r==="."?s=e.state.cwd:r.startsWith("~")?s=(e.state.env.get("HOME")||"/")+r.slice(1):s=`${e.state.cwd}/${r}`;s=lm(s);try{if(!(await e.fs.stat(s)).isDirectory)return L(`bash: pushd: ${r}: Not a directory
|
|
247
|
+
`,1)}catch{return L(`bash: pushd: ${r}: No such file or directory
|
|
248
|
+
`,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=s,e.state.env.set("PWD",s),e.state.env.set("OLDPWD",e.state.previousDir);let i=e.state.env.get("HOME")||"",a=`${[s,...n].map(o=>Sr(o,i)).join(" ")}
|
|
249
|
+
`;return ee(a)}function Va(e,t){let n=Ba(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?L(`bash: popd: ${a}: invalid option
|
|
250
|
+
`,2):L(`bash: popd: too many arguments
|
|
251
|
+
`,2);if(n.length===0)return L(`bash: popd: directory stack empty
|
|
252
|
+
`,1);let r=n.shift();if(!r)return L(`bash: popd: directory stack empty
|
|
253
|
+
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set("PWD",r),e.state.env.set("OLDPWD",e.state.previousDir);let s=e.state.env.get("HOME")||"",i=`${[r,...n].map(a=>Sr(a,s)).join(" ")}
|
|
254
|
+
`;return ee(i)}function za(e,t){let n=Ba(e),r=!1,s=!1,i=!1,a=!1;for(let c of t)if(c!=="--")if(c.startsWith("-"))for(let f of c.slice(1))if(f==="c")r=!0;else if(f==="l")s=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,a=!0;else return L(`bash: dirs: -${f}: invalid option
|
|
255
|
+
`,2);else return L(`bash: dirs: too many arguments
|
|
256
|
+
`,1);if(r)return e.state.directoryStack=[],ne;let o=[e.state.cwd,...n],l=e.state.env.get("HOME")||"",u;return a?(u=o.map((c,f)=>{let d=s?c:Sr(c,l);return` ${f} ${d}`}).join(`
|
|
241
257
|
`),u+=`
|
|
242
|
-
`):i?u=
|
|
258
|
+
`):i?u=o.map(c=>s?c:Sr(c,l)).join(`
|
|
243
259
|
`)+`
|
|
244
|
-
`:u=
|
|
245
|
-
`,
|
|
260
|
+
`:u=o.map(c=>s?c:Sr(c,l)).join(" ")+`
|
|
261
|
+
`,ee(u)}async function Ua(e,t,n,r=!1){let s=t;if(s.length>0){let l=s[0];if(l==="--")s=s.slice(1);else if(l.startsWith("-")&&l!=="-"&&l.length>1)return L(`bash: eval: ${l}: invalid option
|
|
246
262
|
eval: usage: eval [arg ...]
|
|
247
|
-
`,2)}if(s.length===0)return
|
|
248
|
-
`);throw l}finally{(a
|
|
249
|
-
`,n=2;else{let i=BigInt(s);n=Number((i%256n+256n)%256n)}}throw new
|
|
250
|
-
`)}return
|
|
251
|
-
`,1);l!==void 0&&(
|
|
252
|
-
`,i=1;continue}if(l!==void 0)if(
|
|
253
|
-
`);let n=t[0],r=t[1],s=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=n.startsWith(":"),
|
|
254
|
-
`,s||e.state.env.set(r,"?"),f+1<c.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(l))):(e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0")),{exitCode:s?2:0,stdout:"",stderr:m}}if(p+1<
|
|
255
|
-
`,s||e.state.env.set(r,"?")),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:0,stdout:"",stderr:m}}e.state.env.set("OPTARG",
|
|
256
|
-
`,1);
|
|
257
|
-
`,1):
|
|
258
|
-
`,1);u++}else l.push(h),u++}if(n)return e.state.hashTable.clear(),
|
|
263
|
+
`,2)}if(s.length===0)return ne;let i=s.join(" ");if(i.trim()==="")return ne;let a=e.state.groupStdin,o=r||n!==void 0&&n!=="";o&&(e.state.groupStdin=n??"");try{let l=ot(i);return await e.executeScript(l)}catch(l){if(l instanceof Qe||l instanceof Ke||l instanceof Le||l instanceof q||l instanceof Ce)throw l;if(l.name==="ParseException")return L(`bash: eval: ${l.message}
|
|
264
|
+
`);throw l}finally{(o||a!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=a)}}function qa(e,t){let n,r="";if(t.length===0)n=e.state.lastExitCode;else{let s=t[0];if(s===""||!/^-?\d+$/.test(s))r=`bash: exit: ${s}: numeric argument required
|
|
265
|
+
`,n=2;else{let i=BigInt(s);n=Number((i%256n+256n)%256n)}}throw new q(n,"",r)}function ja(e,t){let n=!1,r=[];for(let a of t)a==="-n"?n=!0:a==="-p"||a==="--"||r.push(a);if(r.length===0&&!n){let a="",o=e.state.exportedVars??new Set,l=Array.from(o).sort();for(let u of l){let c=e.state.env.get(u);c!==void 0&&(a+=`declare -x ${u}=${Er(c)}
|
|
266
|
+
`)}return ee(a)}if(n){for(let a of r){let o,l;if(a.includes("=")){let u=a.indexOf("=");o=a.slice(0,u),l=a.slice(u+1)}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return T("",`bash: export: \`${a}': not a valid identifier
|
|
267
|
+
`,1);l!==void 0&&(ce(e,o),e.state.env.set(o,l)),os(e,o)}return ne}let s="",i=0;for(let a of r){let o,l,u=!1,c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c)o=c[1],l=c[2],u=!0;else if(a.includes("=")){let f=a.indexOf("=");o=a.slice(0,f),l=a.slice(f+1)}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){s+=`bash: export: \`${a}': not a valid identifier
|
|
268
|
+
`,i=1;continue}if(l!==void 0)if(ce(e,o),u){let f=e.state.env.get(o)??"";e.state.env.set(o,f+l)}else e.state.env.set(o,l);else e.state.env.has(o)||e.state.env.set(o,"");wt(e,o)}return T("",s,i)}function zs(e,t){if(t.length<2)return L(`bash: getopts: usage: getopts optstring name [arg ...]
|
|
269
|
+
`);let n=t[0],r=t[1],s=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=n.startsWith(":"),a=i?n.slice(1):n,o;if(t.length>2)o=t.slice(2);else{let m=Number.parseInt(e.state.env.get("#")||"0",10);o=[];for(let E=1;E<=m;E++)o.push(e.state.env.get(String(E))||"")}let l=Number.parseInt(e.state.env.get("OPTIND")||"1",10);l<1&&(l=1);let u=Number.parseInt(e.state.env.get("__GETOPTS_CHARINDEX")||"0",10);if(e.state.env.set("OPTARG",""),l>o.length)return s||e.state.env.set(r,"?"),e.state.env.set("OPTIND",String(o.length+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:1,stdout:"",stderr:""};let c=o[l-1];if(!c||c==="-"||!c.startsWith("-"))return s||e.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};if(c==="--")return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),s||e.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};let f=u===0?1:u,d=c[f];if(!d)return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),zs(e,t);let p=a.indexOf(d);if(p===-1){let m="";return i?e.state.env.set("OPTARG",d):m=`bash: illegal option -- ${d}
|
|
270
|
+
`,s||e.state.env.set(r,"?"),f+1<c.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(l))):(e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0")),{exitCode:s?2:0,stdout:"",stderr:m}}if(p+1<a.length&&a[p+1]===":")if(f+1<c.length)e.state.env.set("OPTARG",c.slice(f+1)),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0");else{if(l>=o.length){let m="";return i?(e.state.env.set("OPTARG",d),s||e.state.env.set(r,":")):(m=`bash: option requires an argument -- ${d}
|
|
271
|
+
`,s||e.state.env.set(r,"?")),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:0,stdout:"",stderr:m}}e.state.env.set("OPTARG",o[l]),e.state.env.set("OPTIND",String(l+2)),e.state.env.set("__GETOPTS_CHARINDEX","0")}else f+1<c.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(l))):(e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"));return s||e.state.env.set(r,d),{exitCode:s?2:0,stdout:"",stderr:""}}async function Ha(e,t){e.state.hashTable||(e.state.hashTable=new Map);let n=!1,r=!1,s=!1,i=!1,a=!1,o="",l=[],u=0;for(;u<t.length;){let h=t[u];if(h==="--"){u++,l.push(...t.slice(u));break}if(h==="-r")n=!0,u++;else if(h==="-d")r=!0,u++;else if(h==="-l")s=!0,u++;else if(h==="-t")a=!0,u++;else if(h==="-p"){if(i=!0,u++,u>=t.length)return L(`bash: hash: -p: option requires an argument
|
|
272
|
+
`,1);o=t[u],u++}else if(h.startsWith("-")&&h.length>1){for(let m of h.slice(1))if(m==="r")n=!0;else if(m==="d")r=!0;else if(m==="l")s=!0;else if(m==="t")a=!0;else return m==="p"?L(`bash: hash: -p: option requires an argument
|
|
273
|
+
`,1):L(`bash: hash: -${m}: invalid option
|
|
274
|
+
`,1);u++}else l.push(h),u++}if(n)return e.state.hashTable.clear(),ne;if(r){if(l.length===0)return L(`bash: hash: -d: option requires an argument
|
|
259
275
|
`,1);let h=!1,m="";for(let E of l)e.state.hashTable.has(E)?e.state.hashTable.delete(E):(m+=`bash: hash: ${E}: not found
|
|
260
|
-
`,h=!0);return h?
|
|
276
|
+
`,h=!0);return h?L(m,1):ne}if(a){if(l.length===0)return L(`bash: hash: -t: option requires an argument
|
|
261
277
|
`,1);let h="",m=!1,E="";for(let S of l){let g=e.state.hashTable.get(S);g?l.length>1?h+=`${S} ${g}
|
|
262
278
|
`:h+=`${g}
|
|
263
279
|
`:(E+=`bash: hash: ${S}: not found
|
|
264
|
-
`,m=!0)}return m?{exitCode:1,stdout:h,stderr:E}:
|
|
265
|
-
`,1);let h=l[0];return e.state.hashTable.set(h,
|
|
266
|
-
`);let h="";if(s)for(let[m,E]of e.state.hashTable){let S=m.startsWith("-")?" --":"";h+=`builtin hash -p ${
|
|
280
|
+
`,m=!0)}return m?{exitCode:1,stdout:h,stderr:E}:ee(h)}if(i){if(l.length===0)return L(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
|
|
281
|
+
`,1);let h=l[0];return e.state.hashTable.set(h,o),ne}if(l.length===0){if(e.state.hashTable.size===0)return ee(`hash: hash table empty
|
|
282
|
+
`);let h="";if(s)for(let[m,E]of e.state.hashTable){let S=m.startsWith("-")?" --":"";h+=`builtin hash -p ${be(E)}${S} ${be(m)}
|
|
267
283
|
`}else{h=`hits command
|
|
268
284
|
`;for(let[,m]of e.state.hashTable)h+=` 1 ${m}
|
|
269
|
-
`}return
|
|
285
|
+
`}return ee(h)}let c=!1,f="",p=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let h of l){if(h.includes("/")){f+=`bash: hash: ${h}: cannot use / in name
|
|
270
286
|
`,c=!0;continue}let m=!1;for(let E of p){if(!E)continue;let S=`${E}/${h}`;if(await e.fs.exists(S)){e.state.hashTable.set(h,S),m=!0;break}}m||(f+=`bash: hash: ${h}: not found
|
|
271
|
-
`,c=!0)}return c?
|
|
287
|
+
`,c=!0)}return c?L(f,1):ne}var rf=new Map([[":",[": [arguments]",`Null command.
|
|
272
288
|
No effect; the command does nothing.
|
|
273
289
|
Exit Status:
|
|
274
290
|
Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
|
|
@@ -332,7 +348,12 @@ eval: usage: eval [arg ...]
|
|
|
332
348
|
-V print a more verbose description of each COMMAND
|
|
333
349
|
|
|
334
350
|
Exit Status:
|
|
335
|
-
Returns exit status of COMMAND, or failure if COMMAND is not found.`]],["
|
|
351
|
+
Returns exit status of COMMAND, or failure if COMMAND is not found.`]],["compopt",["compopt [-o option] [-DE] [name ...]",`Modify completion options for each NAME.
|
|
352
|
+
Intended to be used from within a shell function generating possible
|
|
353
|
+
completions. just-bash accepts and validates the options; completion
|
|
354
|
+
behavior is not interactive.
|
|
355
|
+
Exit Status:
|
|
356
|
+
Returns success unless an invalid option is supplied.`]],["compgen",["compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]",`Display possible completions depending on the options.
|
|
336
357
|
Intended to be used from within a shell function generating possible
|
|
337
358
|
completions. If the optional WORD argument is supplied, matches against
|
|
338
359
|
WORD are generated.
|
|
@@ -613,37 +634,37 @@ eval: usage: eval [arg ...]
|
|
|
613
634
|
job specification, and reports its termination status.
|
|
614
635
|
Exit Status:
|
|
615
636
|
Returns the status of the last ID; fails if ID is invalid or an invalid
|
|
616
|
-
option is given.`]]]),
|
|
617
|
-
`,2)}s++}else r.push(l),s++}if(r.length===0)return
|
|
618
|
-
`,
|
|
637
|
+
option is given.`]]]),sf=[...rf.keys()].sort();function Ga(e,t){let n=!1,r=[],s=0;for(;s<t.length;){let l=t[s];if(l==="--"){for(s++;s<t.length;)r.push(t[s]),s++;break}if(l.startsWith("-")&&l.length>1){for(let u=1;u<l.length;u++){let c=l[u];if(c==="s")n=!0;else return L(`bash: help: -${c}: invalid option
|
|
638
|
+
`,2)}s++}else r.push(l),s++}if(r.length===0)return cm();let i="",a=!1,o="";for(let l of r){let u=um(l);if(u.length===0){o+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
|
|
639
|
+
`,a=!0;continue}for(let c of u){let f=rf.get(c);if(!f)continue;let[d,p]=f;n?i+=`${c}: ${d}
|
|
619
640
|
`:i+=`${c}: ${d}
|
|
620
641
|
${p}
|
|
621
|
-
`}}return{exitCode:
|
|
642
|
+
`}}return{exitCode:a?1:0,stdout:i,stderr:o}}function um(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),n=me(`^${t}$`);return sf.filter(r=>n.test(r))}function cm(){let e=[];e.push("just-bash shell builtins"),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push("");let t=36,n=sf.slice(),r=Math.ceil(n.length/2);for(let s=0;s<r;s++){let i=n[s]||"",a=n[s+r]||"",o=i.padEnd(t);e.push(a?`${o}${a}`:i)}return ee(`${e.join(`
|
|
622
643
|
`)}
|
|
623
|
-
`)}function
|
|
624
|
-
`);let n=
|
|
625
|
-
`)}return
|
|
626
|
-
`);let r=e.state.localScopes[e.state.localScopes.length-1];for(e.state.localArrayScopes??=[];e.state.localArrayScopes.length<e.state.localScopes.length;)e.state.localArrayScopes.push(new Map);let s=e.state.localArrayScopes.at(-1),i=d=>{if(r.has(d)||r.set(d,e.state.env.get(d)),s&&!s.has(d)){let p=
|
|
627
|
-
`)}return
|
|
628
|
-
`,
|
|
629
|
-
`,
|
|
630
|
-
`,
|
|
631
|
-
`,s=0,i=0,
|
|
632
|
-
`,u+=2):g==="-n"&&u+1<t.length?(s=Number.parseInt(t[u+1],10)||0,u+=2):g==="-O"&&u+1<t.length?(i=Number.parseInt(t[u+1],10)||0,u+=2):g==="-s"&&u+1<t.length?(
|
|
633
|
-
`,1);if(!Number.isSafeInteger(i)||i<0)return
|
|
634
|
-
`,1);
|
|
635
|
-
`,1);E(A),p++}}break}let y=c.slice(d,g),b=y.indexOf("\0");if(b!==-1&&(y=y.substring(0,b)),!
|
|
636
|
-
`,1);E(y),p++}let S=new Set(i===0?[]:e.state.arrays?.get(l)?.elements.keys()??[]);for(let g=0;g<f.length;g++)if(S.add(String(i+g)),S.size>m)return
|
|
637
|
-
`,1);i===0&&
|
|
638
|
-
`,
|
|
639
|
-
`,1);
|
|
644
|
+
`)}function fm(e){let t=[],n="",r=0;for(let s of e){for(let i of s)i==="("?r++:i===")"&&r--;n?n+=` ${s}`:n=s,r===0&&(t.push(n),n="")}return n&&t.push(n),t}async function Za(e,t){if(t.length===0)return L(`bash: let: expression expected
|
|
645
|
+
`);let n=fm(t),r=0;for(let s of n)try{let a=ot(`(( ${s} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(r=await Y(e,o.expression.expression))}}catch(i){return L(`bash: let: ${s}: ${i.message}
|
|
646
|
+
`)}return T("","",r===0?1:0)}async function Qa(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength};if(e.state.localScopes.length===0)return L(`bash: local: can only be used in a function
|
|
647
|
+
`);let r=e.state.localScopes[e.state.localScopes.length-1];for(e.state.localArrayScopes??=[];e.state.localArrayScopes.length<e.state.localScopes.length;)e.state.localArrayScopes.push(new Map);let s=e.state.localArrayScopes.at(-1),i=d=>{if(r.has(d)||r.set(d,e.state.env.get(d)),s&&!s.has(d)){let p=ke(e,d);s.set(d,p?Me(p):void 0)}},a="",o=0,l=!1,u=!1,c=!1,f=[];for(let d of t)if(d==="-n")l=!0;else if(d==="-a")u=!0;else if(d==="-p")c=!0;else if(d.startsWith("-")&&!d.includes("="))for(let p of d.slice(1))p==="n"?l=!0:p==="a"?u=!0:p==="p"&&(c=!0);else f.push(d);if(f.length===0){let d="",p=Array.from(r.keys()).sort();for(let h of p){let m=e.state.env.get(h);m!==void 0&&(d+=`${h}=${m}
|
|
648
|
+
`)}return T(d,"",0)}for(let d of f){let p,h,m=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(m){p=m[1];let b=m[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(p)){a+=`bash: local: \`${d}': not a valid identifier
|
|
649
|
+
`,o=1;continue}ce(e,p,"bash");let A=Bt(b,n);e.executionScope.consumeWork(A.length,"local array assignment"),i(p),ge(e,p),Qt(e,p,"indexed");for(let k=0;k<A.length;k++)j(e,p,k,A[k]);on(e,p),l&&Mt(e,p);continue}let E=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(E){p=E[1];let b=E[2];ce(e,p,"bash"),i(p);let A=Bt(b,n);e.executionScope.consumeWork(A.length,"local array append");let k=Se(e,p),v=0,$=e.state.env.get(p);k.length===0&&$!==void 0?(j(e,p,0,$),e.state.env.delete(p),v=1):k.length>0&&(v=Math.max(...k)+1),wn(e,p,Array.from({length:A.length},(D,x)=>v+x));for(let D=0;D<A.length;D++)j(e,p,v+D,A[D]);on(e,p),l&&Mt(e,p);continue}let S=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(S){p=S[1];let b=S[2];ce(e,p,"bash"),r.has(p)||r.set(p,e.state.env.get(p));let A=e.state.env.get(p)??"";e.state.env.set(p,qt([A,b],"",e.limits.maxStringLength,"local append")),on(e,p),l&&Mt(e,p);continue}let g=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(g){p=g[1];let b=g[2],A=g[3];ce(e,p,"bash"),i(p);let k;try{let v=new H,$=se(v,b);k=await Y(e,$.expression)}catch{let v=parseInt(b,10);k=Number.isNaN(v)?0:v}j(e,p,k,A),on(e,p),l&&Mt(e,p);continue}if(d.includes("=")){let b=d.indexOf("=");p=d.slice(0,b),h=d.slice(b+1)}else p=d;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(p)){a+=`bash: local: \`${d}': not a valid identifier
|
|
650
|
+
`,o=1;continue}let y=r.has(p);if(h!==void 0){let b=e.state.env.get(p);if(e.state.tempEnvBindings){let A=e.state.accessedTempEnvVars?.has(p),k=e.state.mutatedTempEnvVars?.has(p);if(!A&&!k)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let $=e.state.tempEnvBindings[v];if($.has(p)){b=$.get(p);break}}}Dc(e,p,b)}if(!y){let b=e.state.env.get(p);if(e.state.tempEnvBindings)for(let A=e.state.tempEnvBindings.length-1;A>=0;A--){let k=e.state.tempEnvBindings[A];if(k.has(p)){b=k.get(p);break}}r.set(p,b),u&&i(p)}if(u&&h===void 0)ge(e,p),Qt(e,p,"indexed");else if(h!==void 0){if(ce(e,p,"bash"),l&&h!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(h)){a+=`bash: local: \`${h}': invalid variable name for name reference
|
|
651
|
+
`,o=1;continue}e.state.env.set(p,h),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(p))}else{let b=e.state.tempEnvBindings?.some(A=>A.has(p));!y&&!b&&e.state.env.delete(p)}on(e,p),l&&Mt(e,p)}return T("",a,o)}function Us(e,t,n){let r=`
|
|
652
|
+
`,s=0,i=0,a=0,o=!1,l="MAPFILE",u=0;for(;u<t.length;){let g=t[u];g==="-d"&&u+1<t.length?(r=t[u+1]===""?"\0":t[u+1]||`
|
|
653
|
+
`,u+=2):g==="-n"&&u+1<t.length?(s=Number.parseInt(t[u+1],10)||0,u+=2):g==="-O"&&u+1<t.length?(i=Number.parseInt(t[u+1],10)||0,u+=2):g==="-s"&&u+1<t.length?(a=Number.parseInt(t[u+1],10)||0,u+=2):g==="-t"?(o=!0,u++):g==="-u"||g==="-C"||g==="-c"?u+=2:(g.startsWith("-")||(l=g),u++)}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l))return T("",`mapfile: ${l}: not a valid identifier
|
|
654
|
+
`,1);if(!Number.isSafeInteger(i)||i<0)return T("",`mapfile: invalid array origin
|
|
655
|
+
`,1);ce(e,l,"mapfile");let c=n;!c&&e.state.groupStdin!==void 0&&(c=e.state.groupStdin);let f=[],d=0,p=0,h=0,m=e.limits.maxArrayElements,E=g=>{if(B(g)>e.limits.maxStringLength)throw new P(`mapfile: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");f.push(g)};for(;d<c.length;){e.executionScope.consumeWork(1,"mapfile input");let g=c.indexOf(r,d);if(g===-1){if(d<c.length){if(h<a)h++;else if(s===0||p<s){let A=c.slice(d),k=A.indexOf("\0");if(k!==-1&&(A=A.substring(0,k)),f.length>=m)return T("",`mapfile: array element limit exceeded (${m})
|
|
656
|
+
`,1);E(A),p++}}break}let y=c.slice(d,g),b=y.indexOf("\0");if(b!==-1&&(y=y.substring(0,b)),!o&&r!=="\0"&&(y+=r),d=g+r.length,h<a){h++;continue}if(s>0&&p>=s)break;if(f.length>=m)return T("",`mapfile: array element limit exceeded (${m})
|
|
657
|
+
`,1);E(y),p++}let S=new Set(i===0?[]:e.state.arrays?.get(l)?.elements.keys()??[]);for(let g=0;g<f.length;g++)if(S.add(String(i+g)),S.size>m)return T("",`mapfile: array element limit exceeded (${m})
|
|
658
|
+
`,1);i===0&&ge(e,l);for(let g=0;g<f.length;g++)j(e,l,i+g,f[g]);return e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=""),{...T("","",0),internalStdinConsumed:c.length}}function Ka(e,t,n,r=-1){let s=!1,i=`
|
|
659
|
+
`,a="",o=-1,l=-1,u=null,c=-1,f=-1,d=[],p=0,h=!1,m=(O,_)=>{let M=1;for(;M<O.length;){let re=O[M];if(re==="r")s=!0,M++;else if(re==="s")M++;else{if(re==="d")return M+1<O.length?(i=O.substring(M+1),{nextArgIndex:_+1}):_+1<t.length?(i=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(re==="n"){if(M+1<O.length){let K=O.substring(M+1);return o=Number.parseInt(K,10),(Number.isNaN(o)||o<0)&&(h=!0,o=0),{nextArgIndex:_+1}}else if(_+1<t.length)return o=Number.parseInt(t[_+1],10),(Number.isNaN(o)||o<0)&&(h=!0,o=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(re==="N"){if(M+1<O.length){let K=O.substring(M+1);return l=Number.parseInt(K,10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:_+1}}else if(_+1<t.length)return l=Number.parseInt(t[_+1],10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else{if(re==="a")return M+1<O.length?(u=O.substring(M+1),{nextArgIndex:_+1}):_+1<t.length?(u=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(re==="p")return M+1<O.length?(a=O.substring(M+1),{nextArgIndex:_+1}):_+1<t.length?(a=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(re==="u"){if(M+1<O.length){let K=O.substring(M+1);return c=Number.parseInt(K,10),Number.isNaN(c)||c<0?{nextArgIndex:-2}:{nextArgIndex:_+1}}else if(_+1<t.length)return c=Number.parseInt(t[_+1],10),Number.isNaN(c)||c<0?{nextArgIndex:-2}:{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(re==="t"){if(M+1<O.length){let K=O.substring(M+1);return f=Number.parseFloat(K),Number.isNaN(f)&&(f=0),{nextArgIndex:_+1}}else if(_+1<t.length)return f=Number.parseFloat(t[_+1]),Number.isNaN(f)&&(f=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(re==="e"||re==="i"||re==="P"){if(re==="i"&&_+1<t.length)return{nextArgIndex:_+2};M++}else M++}}}return{nextArgIndex:_+1}};for(;p<t.length;){let O=t[p];if(O.startsWith("-")&&O.length>1&&O!=="--"){let _=m(O,p);if(_.nextArgIndex===-1)return{stdout:"",stderr:"",exitCode:2};if(_.nextArgIndex===-2)return{stdout:"",stderr:"",exitCode:1};p=_.nextArgIndex}else if(O==="--")for(p++;p<t.length;)d.push(t[p]),p++;else d.push(O),p++}if(h)return T("","",1);d.length===0&&u===null&&d.push("REPLY");let E=new Set;u&&E.add(u);for(let O of d)E.add(O);l>=0&&d.length===0&&E.add("REPLY");for(let O of E){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(O))return T("",`bash: read: \`${O}': not a valid identifier
|
|
660
|
+
`,1);ce(e,O,"bash")}if(f===0){if(u)ge(e,u);else{for(let O of d)e.state.env.set(O,"");d.length===0&&e.state.env.set("REPLY","")}return T("","",0)}if(f<0&&f!==-1)return T("","",1);let S=n,g=nt(e,c),y=c>0&&!(g?.kind==="dup-in"&&g.sourceFd===0);if(y){let O=_s(e,c);if("error"in O){let M=O.error==="write-only"||c===1||c===2?`bash: read: read error: ${c}: Bad file descriptor
|
|
640
661
|
`:`bash: read: ${c}: invalid file descriptor: Bad file descriptor
|
|
641
|
-
`;return
|
|
642
|
-
`){
|
|
643
|
-
`){
|
|
662
|
+
`;return T("",M,1)}S=O.content}else!S&&e.state.groupStdin!==void 0&&(S=e.state.groupStdin);let b=i===""?"\0":i,A="",k=0,v=O=>{let _=B(O);if(_>e.limits.maxStringLength-k)throw new P(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");A+=O,k+=_},$=O=>{if(B(O)>e.limits.maxStringLength)throw new P(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")},D=0,x=!0,C=O=>{y?un(e,c,O):r>=0?un(e,r,O):e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=S.substring(O),e.state.groupStdinSourceFd!==void 0&&un(e,e.state.groupStdinSourceFd,O))};if(l>=0){let O=Math.min(l,S.length);A=S.substring(0,O),$(A),D=O,x=O>=l,C(D);let _=d[0]||"REPLY";e.state.env.set(_,A);for(let M=1;M<d.length;M++)e.state.env.set(d[M],"");return T("","",x?0:1)}else if(o>=0){let O=0,_=0,M=!1;for(;_<S.length&&O<o;){let re=S[_];if(re===b){D=_+1,M=!0;break}if(!s&&re==="\\"&&_+1<S.length){let K=S[_+1];if(K===b&&b===`
|
|
663
|
+
`){_+=2,D=_;continue}if(K===b){_+=2,O++,v(K),D=_;continue}v(K),_+=2,O++,D=_}else v(re),_++,O++,D=_}x=O>=o||M,C(D)}else{D=0;let O=0;for(;O<S.length;){let _=S[O];if(_===b){D=O+b.length,x=!0;break}if(!s&&_==="\\"&&O+1<S.length){let M=S[O+1];if(M===`
|
|
664
|
+
`){O+=2;continue}if(M===b){v(M),O+=2;continue}v(_),v(M),O+=2;continue}v(_),O++}if(O>=S.length&&(x=!1,D=O,A.length===0&&S.length===0)){for(let _ of d)e.state.env.set(_,"");return u&&ge(e,u),T("","",1)}C(D)}b===`
|
|
644
665
|
`&&A.endsWith(`
|
|
645
|
-
`)&&(A=A.slice(0,-1));let
|
|
646
|
-
`,2);n=(s%256+256)%256}throw new
|
|
666
|
+
`)&&(A=A.slice(0,-1));let I=O=>s?O:O.replace(/\\(.)/g,"$1");if(d.length===1&&d[0]==="REPLY")return e.state.env.set("REPLY",I(A)),T("","",x?0:1);let W=ve(e.state.env),Z=e.limits.maxArrayElements;if(u){let{words:O}=Ui(A,W,Z,void 0,s);ge(e,u);for(let _=0;_<O.length;_++)j(e,u,_,I(O[_]));return T("","",x?0:1)}let R=d.length,{words:V,wordStarts:z}=Ui(A,W,Z,R,s);for(let O=0;O<d.length;O++){let _=d[O];if(O<d.length-1)e.state.env.set(_,I(V[O]??""));else if(O<z.length){let M=A.substring(z[O]);M=Kl(M,W,s),M=I(M),e.state.env.set(_,M)}else e.state.env.set(_,"")}return T("","",x?0:1)}function Xa(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return L("bash: return: can only `return' from a function or sourced script\n");let n=e.state.lastExitCode;if(t.length>0){let r=t[0],s=Number.parseInt(r,10);if(r===""||Number.isNaN(s)||!/^-?\d+$/.test(r))return L(`bash: return: ${r}: numeric argument required
|
|
667
|
+
`,2);n=(s%256+256)%256}throw new Le(n)}var Ar=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
647
668
|
Options:
|
|
648
669
|
-e Exit immediately if a command exits with non-zero status
|
|
649
670
|
+e Disable -e
|
|
@@ -659,163 +680,147 @@ Options:
|
|
|
659
680
|
+o pipefail Disable pipefail
|
|
660
681
|
-o xtrace Same as -x
|
|
661
682
|
+o xtrace Disable xtrace
|
|
662
|
-
`,
|
|
683
|
+
`,af=new Map([["e","errexit"],["u","nounset"],["x","xtrace"],["v","verbose"],["f","noglob"],["C","noclobber"],["a","allexport"],["n","noexec"],["h",null],["b",null],["m",null],["B",null],["H",null],["P",null],["T",null],["E",null],["p",null]]),qs=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["noclobber","noclobber"],["noglob","noglob"],["allexport","allexport"],["noexec","noexec"],["posix","posix"],["vi","vi"],["emacs","emacs"],["notify",null],["monitor",null],["braceexpand",null],["histexpand",null],["physical",null],["functrace",null],["errtrace",null],["privileged",null],["hashall",null],["ignoreeof",null],["interactive-comments",null],["keyword",null],["onecmd",null]]),uf=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],cf=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function Ya(e,t,n){t!==null&&(n&&(t==="vi"?e.state.options.emacs=!1:t==="emacs"&&(e.state.options.vi=!1)),e.state.options[t]=n,Fn(e))}function dm(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function pm(e,t,n){let r=Se(e,n);if(r.length===0){t.append(n).append("=()");return}t.append(n).append("=(");for(let s=0;s<r.length;s++){let i=r[s],a=oe(e,n,i)??"";s>0&&t.append(" "),t.append(`[${i}]=`),t.reserve(Ws(a)),t.append(dn(a))}t.append(")")}function hm(e,t){if(/^[a-zA-Z0-9_]+$/.test(t)){e.append(t);return}e.reserve(Ws(t)),e.append(dn(t))}function mm(e,t,n){let r=Pt(e,n);if(r.length===0){t.append(n).append("=()");return}t.append(n).append("=(");for(let s=0;s<r.length;s++){let i=r[s],a=oe(e,n,i)??"";s>0&&t.append(" "),t.append("["),hm(t,i),t.append("]="),t.reserve(Ws(a)),t.append(dn(a))}t.append(" )")}function ym(e){let t=new Set,n=e.state.associativeArrays??new Set;for(let[r,s]of e.state.arrays??[])s.kind==="indexed"&&!n.has(r)&&t.add(r);return t}function gm(e){return e.state.associativeArrays??new Set}function of(e){let t=uf.map(r=>`${r.padEnd(16)}${e.state.options[r]?"on":"off"}`),n=cf.map(r=>`${r.padEnd(16)}off`);return`${[...t,...n].sort().join(`
|
|
663
684
|
`)}
|
|
664
|
-
`}function
|
|
685
|
+
`}function lf(e){let t=uf.map(r=>`set ${e.state.options[r]?"-o":"+o"} ${r}`),n=cf.map(r=>`set +o ${r}`);return`${[...t,...n].sort().join(`
|
|
665
686
|
`)}
|
|
666
|
-
`}function
|
|
667
|
-
`);return
|
|
668
|
-
${
|
|
669
|
-
${
|
|
670
|
-
${
|
|
671
|
-
${
|
|
672
|
-
`;if(e.state.options.posix)throw new
|
|
673
|
-
`;if(e.state.options.posix)throw new
|
|
674
|
-
`,2);let r=n[0],s=null,i=null;if(r.includes("/")){let u=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(u),s=u}catch{}}else{let c=(e.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of c){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFile(d),s=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(f),s=f}catch{}}}if(i===null)return
|
|
675
|
-
`);let
|
|
676
|
-
`);throw u}}function
|
|
677
|
-
`,s=1;continue}if(p==="@"||p==="*"){
|
|
678
|
-
`,s=1;continue}let g=await
|
|
679
|
-
`,s=1;continue}if(g===null)continue;if(g<0){let y=
|
|
687
|
+
`}function eo(e,t){if(t.includes("--help"))return ee(Ar);if(t.length===0){let i=ym(e),a=gm(e),o=[];for(let[c,f]of e.state.env)/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)&&(i.has(c)||a.has(c)||o.push([c,f]));let l=[...o.map(([c,f])=>({kind:"scalar",name:c,value:f})),...Array.from(i,c=>({kind:"indexed",name:c})),...Array.from(a,c=>({kind:"associative",name:c}))];l.sort((c,f)=>c.name<f.name?-1:c.name>f.name?1:0);let u=new Nn(e.limits.maxOutputSize,"set");for(let c of l)e.executionScope.consumeWork(1,"set variable listing"),c.kind==="scalar"?(u.append(c.name).append("="),u.reserve(Gc(c.value)),u.append(be(c.value))):c.kind==="indexed"?pm(e,u,c.name):mm(e,u,c.name),u.append(`
|
|
688
|
+
`);return ee(u.build())}let n=[],r=()=>n.length>0?ee(n.join("")):ne,s=0;for(;s<t.length;){let i=t[s];if((i==="-o"||i==="+o")&&dm(t,s)){let a=t[s+1];if(!qs.has(a)){let o=`bash: set: ${a}: invalid option name
|
|
689
|
+
${Ar}`;if(e.state.options.posix)throw new st(1,"",o);return L(o)}Ya(e,qs.get(a)??null,i==="-o"),s+=2;continue}if(i==="-o"){n.push(of(e)),s++;continue}if(i==="+o"){n.push(lf(e)),s++;continue}if(i.length>1&&(i[0]==="-"||i[0]==="+")&&i[1]!=="-"){let a=i[0]==="-",o=0;for(let l=1;l<i.length;l++){let u=i[l];if(u==="o"){let c=s+1+o;if(c<t.length&&!t[c].startsWith("-")&&!t[c].startsWith("+")){let d=t[c];if(!qs.has(d)){let p=`bash: set: ${d}: invalid option name
|
|
690
|
+
${Ar}`;if(e.state.options.posix)throw new st(1,"",p);return L(p)}Ya(e,qs.get(d)??null,a),o++;continue}n.push(a?of(e):lf(e));continue}if(!af.has(u)){let c=`bash: set: ${i[0]}${u}: invalid option
|
|
691
|
+
${Ar}`;if(e.state.options.posix)throw new st(1,"",c);return L(c)}Ya(e,af.get(u)??null,a)}s+=1+o;continue}if(i==="--")return Ja(e,t.slice(s+1)),r();if(i==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,Fn(e),s+1<t.length)return Ja(e,t.slice(s+1)),r();s++;continue}if(i==="+"){s++;continue}if(i.startsWith("-")||i.startsWith("+")){let a=`bash: set: ${i}: invalid option
|
|
692
|
+
${Ar}`;if(e.state.options.posix)throw new st(1,"",a);return L(a)}return Ja(e,t.slice(s)),r()}return r()}function Ja(e,t){let n=1;for(;e.state.env.has(String(n));)e.state.env.delete(String(n)),n++;for(let r=0;r<t.length;r++)e.state.env.set(String(r+1),t[r]);e.state.env.set("#",String(t.length)),e.state.env.set("@",t.join(" ")),e.state.env.set("*",t.join(" "))}function to(e,t){let n=1;if(t.length>0){let a=Number.parseInt(t[0],10);if(Number.isNaN(a)||a<0){let o=`bash: shift: ${t[0]}: numeric argument required
|
|
693
|
+
`;if(e.state.options.posix)throw new st(1,"",o);return L(o)}n=a}let r=Number.parseInt(e.state.env.get("#")||"0",10);if(n>r){let a=`bash: shift: shift count out of range
|
|
694
|
+
`;if(e.state.options.posix)throw new st(1,"",a);return L(a)}if(n===0)return ne;let s=[];for(let a=1;a<=r;a++)s.push(e.state.env.get(String(a))||"");let i=s.slice(n);for(let a=1;a<=r;a++)e.state.env.delete(String(a));for(let a=0;a<i.length;a++)e.state.env.set(String(a+1),i[a]);return e.state.env.set("#",String(i.length)),e.state.env.set("@",i.join(" ")),ne}async function js(e,t){let n=t;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return T("",`bash: source: filename argument required
|
|
695
|
+
`,2);let r=n[0],s=null,i=null;if(r.includes("/")){let u=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(u),s=u}catch{}}else{let c=(e.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of c){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFile(d),s=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(f),s=f}catch{}}}if(i===null)return L(`bash: ${r}: No such file or directory
|
|
696
|
+
`);let a=new Map;if(n.length>1){for(let c=1;c<=9;c++)a.set(String(c),e.state.env.get(String(c)));a.set("#",e.state.env.get("#")),a.set("@",e.state.env.get("@"));let u=n.slice(1);e.state.env.set("#",String(u.length)),e.state.env.set("@",u.join(" "));for(let c=0;c<u.length&&c<9;c++)e.state.env.set(String(c+1),u[c]);for(let c=u.length+1;c<=9;c++)e.state.env.delete(String(c))}let o=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=o,n.length>1)for(let[u,c]of a)c===void 0?e.state.env.delete(u):e.state.env.set(u,c)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new P(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,"recursion");e.state.currentSource=r;try{let u=ot(i),c=await e.executeScript(u);return l(),c}catch(u){if(l(),u instanceof q)throw u;if(u instanceof Le)return T(u.stdout,u.stderr,u.exitCode);if(u.name==="ParseException")return L(`bash: ${r}: ${u.message}
|
|
697
|
+
`);throw u}}function ff(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function wm(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function df(e,t){if(wm(t))return null;try{let n=new H,r=se(n,t);return await Y(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}function pf(e,t){if(e.state.localVarStack?.has(t)){let r=Rs(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let s=e.state.localVarStack?.get(t);if(!s||s.length===0)Ns(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),no(e,t);else{let i=s[s.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,i.scopeIndex+1)}return!0}return e.state.env.delete(t),Ns(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let s=e.state.localScopes[r];if(s.has(t)){let i=s.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),s.delete(t);let a=!1;for(let o=r-1;o>=0;o--)if(e.state.localScopes[o].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,o+1),a=!0;break}return a||Ns(e,t),!0}}return!1}function no(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(t)){let s=r.get(t);return s===void 0?e.state.env.delete(t):e.state.env.set(t,s),r.delete(t),!0}}return!1}async function hf(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let n=t.slice(1,-1),s=new H().parseWordFromString(n,!0,!1);return ie(e,s)}if(t.includes("$")){let r=new H().parseWordFromString(t,!1,!1);return ie(e,r)}return t}async function ro(e,t){let n="both",r="",s=0;for(let i of t){if(i==="-v"){n="variable";continue}if(i==="-f"){n="function";continue}if(n==="function"){e.state.functions.delete(i);continue}if(n==="variable"){let u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let d=u[1],p=u[2];if(We(e,d)){r+=`bash: unset: ${d}: cannot unset: readonly variable
|
|
698
|
+
`,s=1;continue}if(p==="@"||p==="*"){rr(e,d),e.state.env.delete(d);continue}let h=e.state.associativeArrays?.has(d);if(h){let y=await hf(e,p);En(e,d,y);continue}let m=yt(e,d),E=e.state.declaredVars?.has(d);if((e.state.env.has(d)||E)&&!m&&!h){r+=`bash: unset: ${d}: not an array variable
|
|
699
|
+
`,s=1;continue}let g=await df(e,p);if(g===null&&m){r+=`bash: unset: ${p}: not a valid identifier
|
|
700
|
+
`,s=1;continue}if(g===null)continue;if(g<0){let y=G(e,d),b=y.length,A=e.state.currentLine;if(b===0){r+=`bash: line ${A}: unset: [${g}]: bad array subscript
|
|
680
701
|
`,s=1;continue}let k=b+g;if(k<0){r+=`bash: line ${A}: unset: [${g}]: bad array subscript
|
|
681
|
-
`,s=1;continue}let v=y[k][0];
|
|
682
|
-
`,s=1;continue}let c=i;if(
|
|
683
|
-
`,s=1;continue}
|
|
684
|
-
`,s=1;continue}if(c==="@"||c==="*"){
|
|
685
|
-
`,s=1;continue}let h=await
|
|
686
|
-
`,s=1;continue}if(h===null)continue;if(h<0){let m=
|
|
702
|
+
`,s=1;continue}let v=y[k][0];En(e,d,v);continue}En(e,d,g);continue}if(!ff(i)){r+=`bash: unset: \`${i}': not a valid identifier
|
|
703
|
+
`,s=1;continue}let c=i;if(ue(e,i)){let d=Be(e,i);d&&d!==i&&(c=d)}if(We(e,c)){r+=`bash: unset: ${c}: cannot unset: readonly variable
|
|
704
|
+
`,s=1;continue}rr(e,c);let f=ca(e,c);if(f!==void 0&&f!==e.state.callDepth)pf(e,c);else if(e.state.fullyUnsetLocals?.has(c))e.state.env.delete(c);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(c),p=e.state.mutatedTempEnvVars?.has(c);if((d||p)&&e.state.localVarStack?.has(c)){let h=Rs(e,c);h?h.value===void 0?e.state.env.delete(c):e.state.env.set(c,h.value):e.state.env.delete(c)}else e.state.env.delete(c)}else no(e,c)||e.state.env.delete(c);e.state.exportedVars?.delete(c);continue}let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let u=a[1],c=a[2];if(We(e,u)){r+=`bash: unset: ${u}: cannot unset: readonly variable
|
|
705
|
+
`,s=1;continue}if(c==="@"||c==="*"){rr(e,u),e.state.env.delete(u);continue}let f=e.state.associativeArrays?.has(u);if(f){let m=await hf(e,c);En(e,u,m);continue}let d=yt(e,u);if(e.state.env.has(u)&&!d&&!f){r+=`bash: unset: ${u}: not an array variable
|
|
706
|
+
`,s=1;continue}let h=await df(e,c);if(h===null&&d){r+=`bash: unset: ${c}: not a valid identifier
|
|
707
|
+
`,s=1;continue}if(h===null)continue;if(h<0){let m=G(e,u),E=m.length,S=e.state.currentLine;if(E===0){r+=`bash: line ${S}: unset: [${h}]: bad array subscript
|
|
687
708
|
`,s=1;continue}let g=E+h;if(g<0){r+=`bash: line ${S}: unset: [${h}]: bad array subscript
|
|
688
|
-
`,s=1;continue}let y=m[g][0];
|
|
689
|
-
`,s=1;continue}let
|
|
690
|
-
`,s=1;continue}
|
|
691
|
-
|
|
692
|
-
`
|
|
693
|
-
`)}
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
`,
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
`)}
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
`,
|
|
708
|
-
`),s=e.includes(" "),i=e.includes("\\"),o=e.includes("'");if(n||r||s||i){let l="";for(let u of e){let c=u.charCodeAt(0);u===`
|
|
709
|
-
`?l+="\\n":u===" "?l+="\\t":u==="\\"?l+="\\\\":u==="'"?l+="'":u==='"'?l+='"':c<32||c===127?c<256?l+=`\\x${c.toString(16).padStart(2,"0")}`:l+=`\\u${c.toString(16).padStart(4,"0")}`:l+=u}return`$'${l}'`}return o?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function af(e,t,n){if(!e.state.options.xtrace)return"";let r=await of(e),s=[t,...n],i=fm(s);return`${r}${i}
|
|
710
|
-
`}async function lf(e,t,n){return e.state.options.xtrace?`${await of(e)}${t}=${n}
|
|
711
|
-
`:""}function Ms(e,t,n){return zt([t,n],"",e.limits.maxStringLength,"array assignment")}async function uf(e,t){let n=new Map,r="";for(let s of t.assignments){let i=s.name;if(s.array){let c=await pm(e,t,i,s.array,s.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};if(r+=c.xtraceOutput,c.continueToNext)continue}let o=s.value?await se(e,s.value):"";if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:L("",`bash: ${i}: bad array subscript
|
|
712
|
-
`,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let c=await wm(e,t,l[1],l[2],o,s.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};if(c.continueToNext)continue}let u=await Em(e,t,i,o,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};r+=u.xtraceOutput,u.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function pm(e,t,n,r,s,i){let o="";if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: ${n}: cannot assign list to array member
|
|
713
|
-
`,1)};if(le(e,n)){let h=vn(e,n);if(h===void 0||h==="")throw new U(1,"","");let m=Me(e,n);if(m&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(m))return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: ${n}: cannot assign list to array member
|
|
714
|
-
`,1)}}if(Be(e,n)){if(t.name)return o+=`bash: ${n}: readonly variable
|
|
715
|
-
`,{continueToNext:!0,xtraceOutput:o};let h=ue(e,n);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let a=e.state.associativeArrays?.has(n),l=ve(e,n),u=l?Fe(l):void 0,c=e.state.env.get(n),f=()=>{e.state.arrays??=new Map,u?e.state.arrays.set(n,u):e.state.arrays.delete(n),c===void 0?e.state.env.delete(n):e.state.env.set(n,c)},d=hm(r),p=()=>{ye(e,n),e.state.env.delete(n)};try{a&&d?await mm(e,t,n,r,s,p,h=>{o+=h}):d?await ym(e,n,r,s,p):await gm(e,n,r,s,p)}catch(h){throw f(),h}if(t.name){i.set(n,e.state.env.get(n));let m=`(${r.map(E=>_n(E)).join(" ")})`;e.state.env.set(n,m)}return{continueToNext:!0,xtraceOutput:o}}function hm(e){return e.some(t=>{if(t.parts.length>=2){let n=t.parts[0],r=t.parts[1];if(n.type!=="Glob"||!n.pattern.startsWith("["))return!1;if(n.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let s=t.parts[2];return s.type!=="Literal"?!1:s.value.startsWith("]=")||s.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):n.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function mm(e,t,n,r,s,i,o){let a=[];for(let l of r){if(a.length>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let u=ri(l);if(u){let{key:c,valueParts:f,append:d}=u,p;f.length>0?(p=await se(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(p=en(e,p))):p="",a.push({type:"keyed",key:c,value:p,append:d})}else{let c=await se(e,l);a.push({type:"invalid",expandedValue:c})}}e.executionScope.consumeWork(a.length,"associative array assignment"),s||i();for(let l of a)if(l.type==="keyed")if(l.append){let u=oe(e,n,l.key)??"";q(e,n,l.key,Ms(e,u,l.value),"associative")}else q(e,n,l.key,l.value,"associative");else{let u=t.line??e.state.currentLine??1;o(`bash: line ${u}: ${n}: ${l.expandedValue}: must use subscript when assigning associative array
|
|
716
|
-
`)}}async function ym(e,t,n,r,s){let i=[],o=0;for(let l of n){let u=ri(l);if(u){if(o>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let{key:c,valueParts:f,append:d}=u,p;f.length>0?(p=await se(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(p=en(e,p))):p="",i.push({type:"keyed",indexExpr:c,value:p,append:d}),o++}else{let c=await wt(e,l);if(c.values.length>e.limits.maxArrayElements-o)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push({type:"non-keyed",values:c.values}),o+=c.values.length}}e.executionScope.consumeWork(o,"indexed array assignment"),r||s();let a=0;for(let l of i)if(l.type==="keyed"){let u;try{let c=new j,f=re(c,l.indexExpr);u=await X(e,f.expression,!1)}catch{if(/^-?\d+$/.test(l.indexExpr))u=Number.parseInt(l.indexExpr,10);else{let c=e.state.env.get(l.indexExpr);u=c?Number.parseInt(c,10):0,Number.isNaN(u)&&(u=0)}}if(l.append){let c=oe(e,t,u)??"";q(e,t,u,Ms(e,c,l.value))}else q(e,t,u,l.value);a=u+1}else for(let u of l.values)q(e,t,a++,u)}async function gm(e,t,n,r,s){let i=[];for(let a of n){let l=await wt(e,a);for(let u of l.values){if(i.length>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push(u)}}let o=0;if(e.executionScope.consumeWork(i.length,"indexed array assignment"),r){let a=H(e,t);if(a.length>0)o=Math.max(...a.map(([u])=>typeof u=="number"?u:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(q(e,t,0,l),e.state.env.delete(t),o=1)}}else s();for(let a=0;a<i.length;a++)q(e,t,o+a,i[a])}async function wm(e,t,n,r,s,i,o){let a=n;if(le(e,n)){let f=Me(e,n);if(f&&f!==n){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: \`${f}': not a valid identifier
|
|
717
|
-
`,1)};a=f}}if(Be(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=ue(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(a),u;if(l)u=await cf(e,r);else{let f=await ta(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};u=String(f.index)}let c=i?Ms(e,oe(e,a,u)||"",s):s;return t.name||q(e,a,u,c,l?"associative":"indexed"),{continueToNext:!0,xtraceOutput:""}}async function cf(e,t){let n;if(t.startsWith("'")&&t.endsWith("'"))n=t.slice(1,-1);else if(t.startsWith('"')&&t.endsWith('"')){let r=t.slice(1,-1),i=new j().parseWordFromString(r,!0,!1);n=await se(e,i)}else if(t.includes("$")){let s=new j().parseWordFromString(t,!1,!1);n=await se(e,s)}else n=t;return n}async function ta(e,t,n){let r=n;n.startsWith('"')&&n.endsWith('"')&&n.length>=2&&(r=n.slice(1,-1));let s;if(/^-?\d+$/.test(r))s=Number.parseInt(r,10);else{try{let i=new j,o=re(i,r);s=await X(e,o.expression,!1)}catch(i){if(i instanceof U||i instanceof Pe)throw i;if(i instanceof ae){let l=`bash: line ${e.state.currentLine}: ${n}: ${i.message}
|
|
718
|
-
`;if(i.fatal)throw new U(1,"",l);return{index:0,error:L("",l,1)}}let o=e.state.currentLine;return{index:0,error:L("",`bash: line ${o}: ${t}[${n}]: bad array subscript
|
|
719
|
-
`,1)}}Number.isNaN(s)&&(s=0)}if(s<0){let i=H(e,t);if(i.length===0){let a=e.state.currentLine;return{index:0,error:L("",`bash: line ${a}: ${t}[${n}]: bad array subscript
|
|
720
|
-
`,1)}}if(s=Math.max(...i.map(([a])=>typeof a=="number"?a:0))+1+s,s<0){let a=e.state.currentLine;return{index:0,error:L("",`bash: line ${a}: ${t}[${n}]: bad array subscript
|
|
721
|
-
`,1)}}}return{index:s}}async function Em(e,t,n,r,s,i){let o="",a=n,l=null;if(le(e,n)){let f=Jr(e,n,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: ${n}: circular name reference
|
|
722
|
-
`,1)};if(f===null)return{continueToNext:!0,xtraceOutput:""};a=f;let d=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);d&&(l={arrayName:d[1],subscriptExpr:d[2]},a=d[1])}if(Be(e,a)){if(t.name)return o+=`bash: ${a}: readonly variable
|
|
723
|
-
`,{continueToNext:!0,xtraceOutput:o};let f=ue(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let u;if(yr(e,a))try{let f=new j;if(s){let p=`(${e.state.env.get(a)||"0"}) + (${r})`,h=re(f,p);u=String(await X(e,h.expression))}else{let d=re(f,r);u=String(await X(e,d.expression))}}catch{u="0"}else{let f=ht(e,a)?oe(e,a,0):e.state.env.get(a);u=s?Ms(e,f||"",r):r}u=Gn(e,a,u),o+=await lf(e,a,u);let c;return l?c=await bm(e,l):ht(e,a)&&(c="0"),t.name?c===void 0&&(i.set(a,e.state.env.get(a)),e.state.env.set(a,u)):(c===void 0?e.state.env.set(a,u):q(e,a,c,u),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(a)),e.state.tempEnvBindings?.some(f=>f.has(a))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(a))),{continueToNext:!1,xtraceOutput:o}}async function bm(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return cf(e,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new j,a=re(o,r);i=await X(e,a.expression,!1)}catch{let o=e.state.env.get(r);i=o?Number.parseInt(o,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let o=H(e,n);o.length>0&&(i=Math.max(...o.map(l=>l[0]))+1+i)}return String(i)}async function pf(e,t,n,r){let s=!1,i=!1,o=!1,a=!1,l=!1,u=[];for(let m of t)if(m.startsWith("-")&&m.length>1)for(let E of m.slice(1))E==="t"?s=!0:E==="p"?i=!0:E==="P"?o=!0:E==="a"?a=!0:E==="f"&&(l=!0);else u.push(m);let c="",f="",d=0,p=!1,h=!1;for(let m of u){let E=!1;if(o){if(a){let k=await r(m);if(k.length>0){for(let v of k)c+=`${v}
|
|
709
|
+
`,s=1;continue}let y=m[g][0];En(e,u,y);continue}En(e,u,h);continue}if(!ff(i)){r+=`bash: unset: \`${i}': not a valid identifier
|
|
710
|
+
`,s=1;continue}let o=i;if(ue(e,i)){let u=Be(e,i);u&&u!==i&&(o=u)}if(We(e,o)){r+=`bash: unset: ${o}: cannot unset: readonly variable
|
|
711
|
+
`,s=1;continue}rr(e,o);let l=ca(e,o);if(l!==void 0&&l!==e.state.callDepth)pf(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(l!==void 0){let u=e.state.accessedTempEnvVars?.has(o),c=e.state.mutatedTempEnvVars?.has(o);if((u||c)&&e.state.localVarStack?.has(o)){let f=Rs(e,o);f?f.value===void 0?e.state.env.delete(o):e.state.env.set(o,f.value):e.state.env.delete(o)}else e.state.env.delete(o)}else no(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(i)}return T("",r,s)}function Em(e){return e!==null&&typeof e=="object"&&"then"in e&&typeof e.then=="function"}function pe(e,t,n,r){return((...s)=>{tr(t,n,`${r} call`);let i=e(...s);return Em(i)?i.then(a=>(tr(t,n,`${r} post-await`),a),a=>{throw tr(t,n,`${r} post-await`),a}):(tr(t,n,`${r} return`),i)})}function bm(e,t,n){let r={readFile:pe(e.readFile.bind(e),t,n,"fs.readFile"),...typeof e.readFileBytes=="function"?{readFileBytes:pe(e.readFileBytes.bind(e),t,n,"fs.readFileBytes")}:Object.create(null),readFileBuffer:pe(e.readFileBuffer.bind(e),t,n,"fs.readFileBuffer"),writeFile:pe(e.writeFile.bind(e),t,n,"fs.writeFile"),appendFile:pe(e.appendFile.bind(e),t,n,"fs.appendFile"),exists:pe(e.exists.bind(e),t,n,"fs.exists"),stat:pe(e.stat.bind(e),t,n,"fs.stat"),mkdir:pe(e.mkdir.bind(e),t,n,"fs.mkdir"),readdir:pe(e.readdir.bind(e),t,n,"fs.readdir"),rm:pe(e.rm.bind(e),t,n,"fs.rm"),cp:pe(e.cp.bind(e),t,n,"fs.cp"),mv:pe(e.mv.bind(e),t,n,"fs.mv"),resolvePath:pe(e.resolvePath.bind(e),t,n,"fs.resolvePath"),getAllPaths:pe(e.getAllPaths.bind(e),t,n,"fs.getAllPaths"),chmod:pe(e.chmod.bind(e),t,n,"fs.chmod"),symlink:pe(e.symlink.bind(e),t,n,"fs.symlink"),link:pe(e.link.bind(e),t,n,"fs.link"),readlink:pe(e.readlink.bind(e),t,n,"fs.readlink"),lstat:pe(e.lstat.bind(e),t,n,"fs.lstat"),realpath:pe(e.realpath.bind(e),t,n,"fs.realpath"),utimes:pe(e.utimes.bind(e),t,n,"fs.utimes")};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=pe(e.readdirWithFileTypes.bind(e),t,n,"fs.readdirWithFileTypes")),r}function so(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r=Object.getOwnPropertyDescriptors(e);r.fs={value:bm(e.fs,e.requireDefenseContext,n),enumerable:!0,configurable:!0,writable:!0};let s=Object.defineProperties(Object.create(Object.getPrototypeOf(e)),r);return e.exec&&(s.exec=pe(e.exec,e.requireDefenseContext,n,"exec")),e.origCommand&&(s.origCommand=pe(e.origCommand,e.requireDefenseContext,n,"origCommand")),e.fetch&&(s.fetch=pe(e.fetch,e.requireDefenseContext,n,"fetch")),e.sleep&&(s.sleep=pe(e.sleep,e.requireDefenseContext,n,"sleep")),e.getRegisteredCommands&&(s.getRegisteredCommands=pe(e.getRegisteredCommands,e.requireDefenseContext,n,"getRegisteredCommands")),s}var mf="+ ";async function yf(e){let t=e.state.env.get("PS4");if(t===void 0)return mf;if(t==="")return"";let n=e.state.options.xtrace;e.state.options.xtrace=!1;try{let s=new H().parseWordFromString(t,!1,!1);return await ie(e,s)}catch(r){if(r instanceof le&&!r.fatal)return t;if(r instanceof Vt||r instanceof Error&&r.name==="AbortError")throw r;return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${t}: bad substitution
|
|
712
|
+
`,t||mf}finally{e.state.options.xtrace=n}}function Sm(e){return e.map(t=>Am(t)).join(" ")}function Am(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let n=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
|
|
713
|
+
`),s=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(n||r||s||i){let l="";for(let u of e){let c=u.charCodeAt(0);u===`
|
|
714
|
+
`?l+="\\n":u===" "?l+="\\t":u==="\\"?l+="\\\\":u==="'"?l+="'":u==='"'?l+='"':c<32||c===127?c<256?l+=`\\x${c.toString(16).padStart(2,"0")}`:l+=`\\u${c.toString(16).padStart(4,"0")}`:l+=u}return`$'${l}'`}return a?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function gf(e,t,n){if(!e.state.options.xtrace)return"";let r=await yf(e),s=[t,...n],i=Sm(s);return`${r}${i}
|
|
715
|
+
`}async function wf(e,t,n){return e.state.options.xtrace?`${await yf(e)}${t}=${n}
|
|
716
|
+
`:""}function Hs(e,t,n){return qt([t,n],"",e.limits.maxStringLength,"array assignment")}async function Ef(e,t){let n=new Map,r="";for(let s of t.assignments){let i=s.name;if(s.array){let c=await vm(e,t,i,s.array,s.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};if(r+=c.xtraceOutput,c.continueToNext)continue}let a=s.value?await ie(e,s.value):"";if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:T("",`bash: ${i}: bad array subscript
|
|
717
|
+
`,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let c=await Cm(e,t,l[1],l[2],a,s.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};if(c.continueToNext)continue}let u=await Nm(e,t,i,a,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};r+=u.xtraceOutput,u.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function vm(e,t,n,r,s,i){let a="";if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:"",error:T("",`bash: ${n}: cannot assign list to array member
|
|
718
|
+
`,1)};if(ue(e,n)){let h=xn(e,n);if(h===void 0||h==="")throw new q(1,"","");let m=Be(e,n);if(m&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(m))return{continueToNext:!1,xtraceOutput:"",error:T("",`bash: ${n}: cannot assign list to array member
|
|
719
|
+
`,1)}}if(We(e,n)){if(t.name)return a+=`bash: ${n}: readonly variable
|
|
720
|
+
`,{continueToNext:!0,xtraceOutput:a};let h=ce(e,n);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let o=e.state.associativeArrays?.has(n),l=ke(e,n),u=l?Me(l):void 0,c=e.state.env.get(n),f=()=>{e.state.arrays??=new Map,u?e.state.arrays.set(n,u):e.state.arrays.delete(n),c===void 0?e.state.env.delete(n):e.state.env.set(n,c)},d=km(r),p=()=>{ge(e,n),e.state.env.delete(n)};try{o&&d?await xm(e,t,n,r,s,p,h=>{a+=h}):d?await $m(e,n,r,s,p):await Pm(e,n,r,s,p)}catch(h){throw f(),h}if(t.name){i.set(n,e.state.env.get(n));let m=`(${r.map(E=>Tn(E)).join(" ")})`;e.state.env.set(n,m)}return{continueToNext:!0,xtraceOutput:a}}function km(e){return e.some(t=>{if(t.parts.length>=2){let n=t.parts[0],r=t.parts[1];if(n.type!=="Glob"||!n.pattern.startsWith("["))return!1;if(n.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let s=t.parts[2];return s.type!=="Literal"?!1:s.value.startsWith("]=")||s.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):n.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function xm(e,t,n,r,s,i,a){let o=[];for(let l of r){if(o.length>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let u=di(l);if(u){let{key:c,valueParts:f,append:d}=u,p;f.length>0?(p=await ie(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(p=nn(e,p))):p="",o.push({type:"keyed",key:c,value:p,append:d})}else{let c=await ie(e,l);o.push({type:"invalid",expandedValue:c})}}e.executionScope.consumeWork(o.length,"associative array assignment"),s||i();for(let l of o)if(l.type==="keyed")if(l.append){let u=oe(e,n,l.key)??"";j(e,n,l.key,Hs(e,u,l.value),"associative")}else j(e,n,l.key,l.value,"associative");else{let u=t.line??e.state.currentLine??1;a(`bash: line ${u}: ${n}: ${l.expandedValue}: must use subscript when assigning associative array
|
|
721
|
+
`)}}async function $m(e,t,n,r,s){let i=[],a=0;for(let l of n){let u=di(l);if(u){if(a>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let{key:c,valueParts:f,append:d}=u,p;f.length>0?(p=await ie(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(p=nn(e,p))):p="",i.push({type:"keyed",indexExpr:c,value:p,append:d}),a++}else{let c=await bt(e,l);if(c.values.length>e.limits.maxArrayElements-a)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push({type:"non-keyed",values:c.values}),a+=c.values.length}}e.executionScope.consumeWork(a,"indexed array assignment"),r||s();let o=0;for(let l of i)if(l.type==="keyed"){let u;try{let c=new H,f=se(c,l.indexExpr);u=await Y(e,f.expression,!1)}catch{if(/^-?\d+$/.test(l.indexExpr))u=Number.parseInt(l.indexExpr,10);else{let c=e.state.env.get(l.indexExpr);u=c?Number.parseInt(c,10):0,Number.isNaN(u)&&(u=0)}}if(l.append){let c=oe(e,t,u)??"";j(e,t,u,Hs(e,c,l.value))}else j(e,t,u,l.value);o=u+1}else for(let u of l.values)j(e,t,o++,u)}async function Pm(e,t,n,r,s){let i=[];for(let o of n){let l=await bt(e,o);for(let u of l.values){if(i.length>=e.limits.maxArrayElements)throw new P(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push(u)}}let a=0;if(e.executionScope.consumeWork(i.length,"indexed array assignment"),r){let o=G(e,t);if(o.length>0)a=Math.max(...o.map(([u])=>typeof u=="number"?u:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(j(e,t,0,l),e.state.env.delete(t),a=1)}}else s();for(let o=0;o<i.length;o++)j(e,t,a+o,i[o])}async function Cm(e,t,n,r,s,i,a){let o=n;if(ue(e,n)){let f=Be(e,n);if(f&&f!==n){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:T("",`bash: \`${f}': not a valid identifier
|
|
722
|
+
`,1)};o=f}}if(We(e,o)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=ce(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(o),u;if(l)u=await bf(e,r);else{let f=await io(e,o,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};u=String(f.index)}let c=i?Hs(e,oe(e,o,u)||"",s):s;return t.name||j(e,o,u,c,l?"associative":"indexed"),{continueToNext:!0,xtraceOutput:""}}async function bf(e,t){let n;if(t.startsWith("'")&&t.endsWith("'"))n=t.slice(1,-1);else if(t.startsWith('"')&&t.endsWith('"')){let r=t.slice(1,-1),i=new H().parseWordFromString(r,!0,!1);n=await ie(e,i)}else if(t.includes("$")){let s=new H().parseWordFromString(t,!1,!1);n=await ie(e,s)}else n=t;return n}async function io(e,t,n){let r=n;n.startsWith('"')&&n.endsWith('"')&&n.length>=2&&(r=n.slice(1,-1));let s;if(/^-?\d+$/.test(r))s=Number.parseInt(r,10);else{try{let i=new H,a=se(i,r);s=await Y(e,a.expression,!1)}catch(i){if(i instanceof q||i instanceof Ce)throw i;if(i instanceof le){let l=`bash: line ${e.state.currentLine}: ${n}: ${i.message}
|
|
723
|
+
`;if(i.fatal)throw new q(1,"",l);return{index:0,error:T("",l,1)}}let a=e.state.currentLine;return{index:0,error:T("",`bash: line ${a}: ${t}[${n}]: bad array subscript
|
|
724
|
+
`,1)}}Number.isNaN(s)&&(s=0)}if(s<0){let i=G(e,t);if(i.length===0){let o=e.state.currentLine;return{index:0,error:T("",`bash: line ${o}: ${t}[${n}]: bad array subscript
|
|
725
|
+
`,1)}}if(s=Math.max(...i.map(([o])=>typeof o=="number"?o:0))+1+s,s<0){let o=e.state.currentLine;return{index:0,error:T("",`bash: line ${o}: ${t}[${n}]: bad array subscript
|
|
726
|
+
`,1)}}}return{index:s}}async function Nm(e,t,n,r,s,i){let a="",o=n,l=null;if(ue(e,n)){let f=ss(e,n,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:"",error:T("",`bash: ${n}: circular name reference
|
|
727
|
+
`,1)};if(f===null)return{continueToNext:!0,xtraceOutput:""};o=f;let d=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);d&&(l={arrayName:d[1],subscriptExpr:d[2]},o=d[1])}if(We(e,o)){if(t.name)return a+=`bash: ${o}: readonly variable
|
|
728
|
+
`,{continueToNext:!0,xtraceOutput:a};let f=ce(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let u;if(br(e,o))try{let f=new H;if(s){let p=`(${e.state.env.get(o)||"0"}) + (${r})`,h=se(f,p);u=String(await Y(e,h.expression))}else{let d=se(f,r);u=String(await Y(e,d.expression))}}catch{u="0"}else{let f=yt(e,o)?oe(e,o,0):e.state.env.get(o);u=s?Hs(e,f||"",r):r}u=Kn(e,o,u),a+=await wf(e,o,u);let c;return l?c=await Rm(e,l):yt(e,o)&&(c="0"),t.name?c===void 0&&(i.set(o,e.state.env.get(o)),e.state.env.set(o,u)):(c===void 0?e.state.env.set(o,u):j(e,o,c,u),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(o)),e.state.tempEnvBindings?.some(f=>f.has(o))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(o))),{continueToNext:!1,xtraceOutput:a}}async function Rm(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return bf(e,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let a=new H,o=se(a,r);i=await Y(e,o.expression,!1)}catch{let a=e.state.env.get(r);i=a?Number.parseInt(a,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let a=G(e,n);a.length>0&&(i=Math.max(...a.map(l=>l[0]))+1+i)}return String(i)}async function vf(e,t,n,r){let s=!1,i=!1,a=!1,o=!1,l=!1,u=[];for(let m of t)if(m.startsWith("-")&&m.length>1)for(let E of m.slice(1))E==="t"?s=!0:E==="p"?i=!0:E==="P"?a=!0:E==="a"?o=!0:E==="f"&&(l=!0);else u.push(m);let c="",f="",d=0,p=!1,h=!1;for(let m of u){let E=!1;if(a){if(o){let k=await r(m);if(k.length>0){for(let v of k)c+=`${v}
|
|
724
729
|
`;p=!0,E=!0}}else{let k=await n(m);k&&(c+=`${k}
|
|
725
|
-
`,p=!0,E=!0)}E||(h=!0);continue}let S=!l&&e.state.functions.has(m);if(
|
|
726
|
-
`;else{let k=e.state.functions.get(m),v=k?
|
|
727
|
-
`;c+=v}E=!0}let g=e.state.env.get(`BASH_ALIAS_${m}`);if(g!==void 0&&(
|
|
730
|
+
`,p=!0,E=!0)}E||(h=!0);continue}let S=!l&&e.state.functions.has(m);if(o&&S){if(!i)if(s)c+=`function
|
|
731
|
+
`;else{let k=e.state.functions.get(m),v=k?Sf(m,k):`${m} is a function
|
|
732
|
+
`;c+=v}E=!0}let g=e.state.env.get(`BASH_ALIAS_${m}`);if(g!==void 0&&(o||!E)&&(i||(s?c+=`alias
|
|
728
733
|
`:c+=`${m} is aliased to \`${g}'
|
|
729
|
-
`),E=!0,!
|
|
734
|
+
`),E=!0,!o)||ir.has(m)&&(o||!E)&&(i||(s?c+=`keyword
|
|
730
735
|
`:c+=`${m} is a shell keyword
|
|
731
|
-
`),E=!0,!
|
|
732
|
-
`;else{let k=e.state.functions.get(m),v=k?
|
|
733
|
-
`;c+=v}E=!0;continue}if(!(
|
|
736
|
+
`),E=!0,!o))continue;if(!o&&S&&!E){if(!i)if(s)c+=`function
|
|
737
|
+
`;else{let k=e.state.functions.get(m),v=k?Sf(m,k):`${m} is a function
|
|
738
|
+
`;c+=v}E=!0;continue}if(!(xt.has(m)&&(o||!E)&&(i||(s?c+=`builtin
|
|
734
739
|
`:c+=`${m} is a shell builtin
|
|
735
|
-
`),E=!0,!
|
|
740
|
+
`),E=!0,!o))){if(o){let k=await r(m);for(let v of k)i?c+=`${v}
|
|
736
741
|
`:s?c+=`file
|
|
737
742
|
`:c+=`${m} is ${v}
|
|
738
743
|
`,p=!0,E=!0}else if(!E){let k=await n(m);k&&(i?c+=`${k}
|
|
739
744
|
`:s?c+=`file
|
|
740
745
|
`:c+=`${m} is ${k}
|
|
741
746
|
`,p=!0,E=!0)}if(!E&&(h=!0,!s&&!i)){let k=!0;if(m.includes("/")){let v=e.fs.resolvePath(e.state.cwd,m);await e.fs.exists(v)&&(k=!1)}k&&(f+=`bash: type: ${m}: not found
|
|
742
|
-
`)}}}return i?d=h&&!p?1:0:d=h?1:0,
|
|
747
|
+
`)}}}return i?d=h&&!p?1:0:d=h?1:0,T(c,f,d)}function Sf(e,t){let n;return t.body.type==="Group"?n=t.body.body.map(s=>vr(s)).join("; "):n=vr(t.body),`${e} is a function
|
|
743
748
|
${e} ()
|
|
744
749
|
{
|
|
745
750
|
${n}
|
|
746
751
|
}
|
|
747
|
-
`}function
|
|
748
|
-
`:s+=`alias ${
|
|
749
|
-
`;else if(
|
|
750
|
-
`:s+=`${
|
|
751
|
-
`;else if(
|
|
752
|
-
`:s+=`${
|
|
753
|
-
`;else if(e.state.functions.has(
|
|
754
|
-
`:s+=`${
|
|
755
|
-
`;else if(
|
|
756
|
-
`:s+=`${
|
|
757
|
-
`,c=!0)}catch{}c||(r&&(i+=`${
|
|
758
|
-
`),
|
|
752
|
+
`}function vr(e){if(Array.isArray(e))return e.map(t=>vr(t)).join("; ");if(e.type==="Statement"){let t=[];for(let n=0;n<e.pipelines.length;n++){let r=e.pipelines[n];t.push(Dm(r)),e.operators[n]&&t.push(e.operators[n])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,n=[];t.name&&n.push(Af(t.name));for(let r of t.args)n.push(Af(r));return n.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>vr(r)).join("; ")}; }`:"..."}function Af(e){return e.parts.map(kf).join("")}function kf(e){switch(e.type){case"Literal":return e.value;case"Escaped":return`\\${e.value}`;case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(kf).join("")}"`;default:return Ae(F.word([e]))}}function Dm(e){let t=e.commands.map(n=>vr(n));return(e.negated?"! ":"")+t.join(" | ")}async function xf(e,t,n,r){let s="",i="",a=0;for(let o of t){if(!o){a=1;continue}let l=e.state.env.get(`BASH_ALIAS_${o}`);if(l!==void 0)r?s+=`${o} is an alias for "${l}"
|
|
753
|
+
`:s+=`alias ${o}='${l}'
|
|
754
|
+
`;else if(ir.has(o))r?s+=`${o} is a shell keyword
|
|
755
|
+
`:s+=`${o}
|
|
756
|
+
`;else if(xt.has(o))r?s+=`${o} is a shell builtin
|
|
757
|
+
`:s+=`${o}
|
|
758
|
+
`;else if(e.state.functions.has(o))r?s+=`${o} is a function
|
|
759
|
+
`:s+=`${o}
|
|
760
|
+
`;else if(o.includes("/")){let u=e.fs.resolvePath(e.state.cwd,o),c=!1;if(await e.fs.exists(u))try{let f=await e.fs.stat(u);f.isDirectory||(f.mode&73)!==0&&(r?s+=`${o} is ${o}
|
|
761
|
+
`:s+=`${o}
|
|
762
|
+
`,c=!0)}catch{}c||(r&&(i+=`${o}: not found
|
|
763
|
+
`),a=1)}else if(e.commands.has(o)){let c=(e.state.env.get("PATH")??"/usr/bin:/bin").split(":"),f=null;for(let d of c){if(!d)continue;let p=`${d}/${o}`;try{let h=await e.fs.stat(p);if(!h.isDirectory&&(h.mode&73)!==0){f=p;break}}catch{}}f||(f=`/usr/bin/${o}`),r?s+=`${o} is ${f}
|
|
759
764
|
`:s+=`${f}
|
|
760
|
-
`}else r&&(i+=`${
|
|
761
|
-
`),
|
|
762
|
-
`)},
|
|
763
|
-
`))}}}async function
|
|
764
|
-
`):new
|
|
765
|
-
`);throw m||s.poisonAfterAbort(E),E}finally{n(),
|
|
766
|
-
`,2);let
|
|
767
|
-
`,2);let
|
|
768
|
-
`,2);
|
|
769
|
-
`);let[,...
|
|
770
|
-
`;if(A)throw new
|
|
771
|
-
`);return
|
|
772
|
-
`,127)}if("error"in u)return u.error==="permission_denied"?
|
|
773
|
-
`,126):
|
|
774
|
-
`,127);if("script"in u)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,u.path)),await
|
|
775
|
-
`)}}async function
|
|
776
|
-
`,exitCode:1}}function
|
|
777
|
-
`),n.build(1)}return n.build(r)}async function
|
|
778
|
-
`);let i=[];if(t.words===null)i=(e.state.env.get("@")||"").split(" ").filter(Boolean);else if(t.words.length===0)i=[];else try{for(let
|
|
765
|
+
`}else r&&(i+=`${o}: not found
|
|
766
|
+
`),a=1}return T(s,i,a)}async function $f(e,t){if(t.includes("/")){let s=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(s)){try{let i=await e.fs.stat(s);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=(e.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let s of r){if(!s)continue;let a=`${s.startsWith("/")?s:e.fs.resolvePath(e.state.cwd,s)}/${t}`;if(await e.fs.exists(a)){try{let o=await e.fs.stat(a);if(o.isDirectory||(o.mode&73)===0)continue}catch{continue}return`${s}/${t}`}}if(e.commands.has(t)){for(let s of r)if(s==="/usr/bin"||s==="/bin")return`${s}/${t}`;return`/usr/bin/${t}`}return null}function Pf(e,t){let n=!0,r=e.signal?new AbortController:void 0,s=new WeakMap,i=()=>{if(!n)throw new Ye("",`bash: ${t} used its context after cancellation
|
|
767
|
+
`)},a=f=>{if(f===null||typeof f!="object"&&typeof f!="function")return f;let d=s.get(f);if(d!==void 0)return d;if(typeof f=="object"&&Io(f))return f;if(f instanceof Uint8Array){let E=new Uint8Array(f);return s.set(f,E),E}if(f instanceof ArrayBuffer){let E=f.slice(0);return s.set(f,E),E}if(f instanceof Promise){let E=f.then(S=>(i(),a(S)));return s.set(f,E),E}if(typeof f=="function"){let E=function(...S){return i(),a(Reflect.apply(f,this,S))};return s.set(f,E),E}let p=Object.getPrototypeOf(f);if(Array.isArray(f)||p===Object.prototype||p===null){let E=Array.isArray(f)?[]:Object.create(p);s.set(f,E);let S=Object.getOwnPropertyDescriptors(f);for(let g of Object.values(S)){if("value"in g){let y=g.value;g.value=typeof y=="function"?(...b)=>(i(),a(Reflect.apply(y,f,b))):a(y)}if(g.get){let y=g.get;g.get=()=>(i(),a(Reflect.apply(y,f,[])))}if(g.set){let y=g.set;g.set=b=>{i(),Reflect.apply(y,f,[b])}}}return Object.defineProperties(E,S),E}let h=new Map,m=new ko(f,{get(E,S){if(i(),S==="constructor"||S==="prototype"||S==="__proto__")throw new Error(`${t}: unsafe context property access`);let g=Reflect.get(E,S,E);if(typeof g!="function")return a(g);if(h.has(S))return h.get(S);let y=(...b)=>(i(),a(Reflect.apply(g,E,b)));return h.set(S,y),y},set(E,S,g){if(i(),S==="constructor"||S==="prototype"||S==="__proto__")throw new Error(`${t}: unsafe context property access`);return Reflect.set(E,S,g,E)}});return s.set(f,m),m},o=f=>a(f),l=f=>f&&((...d)=>(i(),a(f(...d)))),u=f=>({value:f,enumerable:!0,configurable:!0,writable:!0}),c=Object.getOwnPropertyDescriptors(e);return Object.assign(c,{fs:u(o(e.fs)),env:u(o(e.env)),limits:u(Object.freeze({...e.limits})),exportedEnv:u(e.exportedEnv?Object.freeze({...e.exportedEnv}):void 0),executionScope:u(e.executionScope?o(e.executionScope):void 0),fileDescriptors:u(e.fileDescriptors?o(e.fileDescriptors):void 0),coverage:u(e.coverage?o(e.coverage):void 0),assignShellVariable:u(l(e.assignShellVariable)),exec:u(l(e.exec)),origCommand:u(l(e.origCommand)),execWithInheritedStdin:u(l(e.execWithInheritedStdin)),fetch:u(l(e.fetch)),getRegisteredCommands:u(l(e.getRegisteredCommands)),sleep:u(l(e.sleep)),trace:u(l(e.trace)),invokeTool:u(l(e.invokeTool)),signal:u(r?.signal)}),{context:Object.defineProperties(Object.create(Object.getPrototypeOf(e)),c),revoke(){n=!1,r?.signal.aborted||r?.abort(new Ye("",`bash: ${t} context revoked
|
|
768
|
+
`))}}}async function Im(e,t,n,r,s,i){let a=s.remainingTimeMs()??t.limits.maxExecutionTimeMs,o=t.limits.maxExtensionCleanupTimeMs,l,u,c,d=Promise.resolve().then(e).then(h=>({kind:"result",result:h}),h=>({kind:"error",error:h})),p=new Promise(h=>{let m=()=>{n(),h({kind:"abort"})};u=m,i?.addEventListener("abort",m,{once:!0}),i?.aborted&&m(),l=Yn(()=>{n(),h({kind:"deadline"})},a)});try{let h=await Promise.race([d,p]);if(h.kind==="result")return h.result;if(h.kind==="error")throw h.error;n();let m=await Promise.race([d.then(()=>!0),new Promise(S=>{c=Yn(()=>S(!1),o)})]),E=h.kind==="deadline"?new Ye("",`bash: ${r} exceeded its execution deadline
|
|
769
|
+
`):new Ye("",`bash: execution aborted
|
|
770
|
+
`);throw m||s.poisonAfterAbort(E),E}finally{n(),Jn(l),Jn(c),u&&i?.removeEventListener("abort",u)}}var Cf={export:(e,t)=>ja(e.ctx,t),unset:(e,t)=>ro(e.ctx,t),exit:(e,t)=>qa(e.ctx,t),local:(e,t)=>Qa(e.ctx,t),set:(e,t)=>eo(e.ctx,t),break:(e,t)=>sa(e.ctx,t),continue:(e,t)=>Ia(e.ctx,t),return:(e,t)=>Xa(e.ctx,t),shift:(e,t)=>to(e.ctx,t),getopts:(e,t)=>zs(e.ctx,t),compgen:(e,t)=>Pa(e.ctx,t),complete:(e,t)=>Ra(e.ctx,t),compopt:(e,t)=>Da(e.ctx,t),pushd:(e,t)=>Wa(e.ctx,t),popd:(e,t)=>Va(e.ctx,t),dirs:(e,t)=>za(e.ctx,t),source:(e,t)=>js(e.ctx,t),".":(e,t)=>js(e.ctx,t),read:(e,t,n)=>Ka(e.ctx,t,n.stdin,n.stdinSourceFd),mapfile:(e,t,n)=>Us(e.ctx,t,n.stdin),readarray:(e,t,n)=>Us(e.ctx,t,n.stdin),declare:(e,t)=>Vs(e.ctx,t),typeset:(e,t)=>Vs(e.ctx,t),readonly:(e,t)=>Ma(e.ctx,t),eval:(e,t,n)=>Ua(e.ctx,t,n.stdin,n.stdinRedirected),cd:(e,t)=>ia(e.ctx,t),":":()=>ne,true:()=>ne,false:()=>we(!1),let:(e,t)=>Za(e.ctx,t),command:(e,t,n)=>Om(e,t,n.stdin,n.stdinRedirected),builtin:(e,t,n)=>_m(e,t,n.stdin,n.stdinRedirected),shopt:(e,t)=>Uc(e.ctx,t),exec:async(e,t,n)=>{if(t.length===0)return ne;let[r,...s]=t;return{...await e.runCommand(r,s,[],n.stdin,!1,!1,-1,n.stdinRedirected),internalProducerOmitsShellPrefix:!0}},wait:()=>ne,type:(e,t)=>vf(e.ctx,t,n=>$f(e.ctx,n),n=>qr(e.ctx,n)),hash:(e,t)=>Ha(e.ctx,t),help:(e,t)=>Ga(e.ctx,t),"[":(e,t)=>t[t.length-1]!=="]"?L("[: missing `]'\n",2):qn(e.ctx,t.slice(0,-1)),test:(e,t)=>qn(e.ctx,t)};async function Nf(e,t,n,r,s,i,a,o,l=!1){let{ctx:u}=e;u.coverage&&xt.has(t)&&u.coverage.hit(`bash:builtin:${t}`);let c={stdin:s,stdinRedirected:l,stdinSourceFd:o},f=qo(t),d=(f==="early"||f==="late")&&Object.hasOwn(Cf,t)?Cf[t]:void 0;if(d&&(f==="early"||u.state.options.posix&&jo(t)))return d(e,n,c);if(!i){let p=u.state.functions.get(t);if(p)return Fs(u,p,n,s,void 0,l)}if(t==="__just_bash_tee_restore"){if(n.length===0||n.length>u.limits.maxArrayElements)return L(`bash: invalid internal pipeline status restore
|
|
771
|
+
`,2);let p=[];for(let E of n){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(E))return L(`bash: invalid internal pipeline status restore
|
|
772
|
+
`,2);let S=Number(E);if(!Number.isSafeInteger(S)||S>255)return L(`bash: invalid internal pipeline status restore
|
|
773
|
+
`,2);p.push(S)}let h=p[p.length-1]??0,m=[...p].reverse().find(E=>E!==0);return{stdout:"",stderr:"",exitCode:u.state.options.pipefail&&m!==void 0?m:h,internalPipeStatusOverride:p}}return d&&f==="late"?d(e,n,c):null}async function Om(e,t,n,r=!1){let{ctx:s,runCommand:i}=e;if(t.length===0)return ne;let a=!1,o=!1,l=!1,u=t;for(;u.length>0&&u[0].startsWith("-");){let d=u[0];if(d==="--"){u=u.slice(1);break}for(let p of d.slice(1))p==="p"?a=!0:p==="V"?o=!0:p==="v"&&(l=!0);u=u.slice(1)}if(u.length===0)return ne;if(l||o)return await xf(s,u,l,o);let[c,...f]=u;return i(c,f,[],n,!0,a,-1,r)}async function _m(e,t,n,r=!1){let{runCommand:s}=e;if(t.length===0)return ne;let i=t;if(i[0]==="--"&&(i=i.slice(1),i.length===0))return ne;let a=i[0];if(a!=="__just_bash_tee_restore"&&!xt.has(a))return L(`bash: builtin: ${a}: not a shell builtin
|
|
774
|
+
`);let[,...o]=i;return s(a,o,[],n,!0,!1,-1,r)}async function Rf(e,t,n,r,s){let{ctx:i,buildExportedEnv:a,executeUserScript:o}=e,u=await Ur(i,t,s?"/usr/bin:/bin":void 0);if(!u){i.executionScope.recordUnresolvedCommand(t);let A=i.executionScope.abortOnUnresolvedCommands;if(Ec(t)){let k=`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
|
|
775
|
+
`;if(A)throw new Ce(t,"",k);return L(k,127)}if(A)throw new Ce(t,"",`bash: ${t}: command not found
|
|
776
|
+
`);return L(`bash: ${t}: command not found
|
|
777
|
+
`,127)}if("error"in u)return u.error==="permission_denied"?L(`bash: ${t}: Permission denied
|
|
778
|
+
`,126):L(`bash: ${t}: No such file or directory
|
|
779
|
+
`,127);if("script"in u)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,u.path)),await o(u.path,n,r);let{cmd:c,path:f}=u;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||"",p=!1,h=a();i.state.fileDescriptors??=new Map;let m={fs:i.fs,fsIdentity:ai(i.fs),cwd:i.state.cwd,env:i.state.env,assignShellVariable:async(A,k,v)=>{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(A))throw new Error(`${A}: not a valid identifier`);let $=v===void 0?A:`${A}[${v}]`,D=ss(i,A,k);if(D===void 0)throw new Error(`${A}: circular name reference`);if(D===null)return;let x=D.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(?:\[(.*)\])?$/);if(!x)throw new Error(`${$}: not a valid identifier`);let C=x[1],I=x[2]??v;if(We(i,A)||We(i,C))throw new Error(`${C}: readonly variable`);if(I===void 0)i.state.env.set(C,k);else{let W=i.state.associativeArrays?.has(C)?"associative":"indexed";if(W==="associative"){j(i,C,I,k,W);return}let Z=await io(i,C,I);if(Z.error)throw new q(Z.error.exitCode,Z.error.stdout,Z.error.stderr);j(i,C,Z.index,k,W)}},exportedEnv:h,get stdin(){return p=!0,d},limits:i.limits,executionScope:c.internalIsExtension?Fo(i.executionScope):i.executionScope,exec:(A,k)=>i.execFn(A,k,!1),execWithInheritedStdin:(A,k)=>i.execFn(A,{...k,stdin:d,stdinKind:"bytes"},!0),fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,invokeTool:i.invokeTool},E=c.internalOriginalCommand,S=()=>{};if(E){let A=Object.getOwnPropertyDescriptors(m);A.executionScope={value:i.executionScope,enumerable:!0,configurable:!0,writable:!0};let k=Object.defineProperties(Object.create(Object.getPrototypeOf(m)),A),v=Pf(k,E.name),$=so(v.context,E.name);S=v.revoke,m.origCommand=D=>{let x=()=>E.execute(D,$);return E.trusted?Ze.runTrustedAsync(x):Ze.runUntrustedAsync(x)}}let g=Pf(m,t),y=so(g.context,t),b=()=>{g.revoke(),S()};try{let A=()=>vo(i.requireDefenseContext,"command",`${t} execution`,()=>c.execute(n,y)),k=()=>Im(A,y,b,t,i.executionScope,i.state.signal),v=c.trusted?await Ze.runTrustedAsync(k):await k();return{...v,internalStdinConsumed:v.internalStdinConsumed??(p?r.length:0)}}catch(A){return Fr(A),L(`${t}: ${vt(it(A))}
|
|
780
|
+
`)}}async function ao(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=new Gt(e.executionScope,"condition"),s=0;try{for(let i of t){let a=await e.executeStatement(i);r.appendResult(a),s=a.exitCode}}catch(i){throw r.prependTo(i),i}finally{e.state.inCondition=n}return r.build(s)}function kr(e,t,n,r){if(e instanceof Qe)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:"rethrow",stdout:t,stderr:n,error:e}):{action:"break",stdout:t,stderr:n};if(e instanceof Ke)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:"rethrow",stdout:t,stderr:n,error:e}):{action:"continue",stdout:t,stderr:n};if(Tr(e)||e instanceof Le||e instanceof ze||e instanceof q)return e instanceof Vt&&e.prependOutput(t,n),{action:"rethrow",stdout:t,stderr:n,error:e};let s=it(e);return{action:"error",stdout:t,stderr:`${n}${s}
|
|
781
|
+
`,exitCode:1}}function Df(e,t){return e!==void 0?{owns:!0,stdin:e}:t!==""?{owns:!0,stdin:t}:{owns:!1}}var pn=class{ctx;stdoutChunks=[];stderrChunks=[];totalBytes=0;constructor(t){this.ctx=t}append(t,n){let r=B(t)+B(n);r>this.ctx.limits.maxOutputSize-this.totalBytes&&sn(`total output size exceeded (>${this.ctx.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size"),t&&this.stdoutChunks.push(t),n&&this.stderrChunks.push(n),this.totalBytes+=r}appendUnaccounted(t,n){this.ctx.executionScope.appendOutput("stdout",t,"control-flow"),this.ctx.executionScope.appendOutput("stderr",n,"control-flow"),this.append(t,n)}replace(t,n){this.stdoutChunks=[],this.stderrChunks=[],this.totalBytes=0,this.append(t,n)}get stdout(){return this.stdoutChunks.join("")}get stderr(){return this.stderrChunks.join("")}build(t){let n=this.stdout,r=this.stderr;return{stdout:n,stderr:r,exitCode:t,internalOutputAccounting:{stdout:B(n),stderr:B(r)}}}};async function oo(e,t,n){let r=0;try{for(let s of t){let i=await e.executeStatement(s);n.append(i.stdout,i.stderr),r=i.exitCode}}catch(s){if(Lr(s)||s instanceof ze||s instanceof q||s instanceof Ce||s instanceof P||s instanceof Ut)throw s.prependOutput(n.stdout,n.stderr),s;return n.appendUnaccounted("",`${it(s)}
|
|
782
|
+
`),n.build(1)}return n.build(r)}async function If(e,t){return rt(e,t.redirections,"",()=>Lm(e,t))}async function Lm(e,t){let n=new pn(e);for(let r of t.clauses){let s=await ao(e,r.condition);if(n.append(s.stdout,s.stderr),s.exitCode===0)return oo(e,r.body,n)}return t.elseBody?oo(e,t.elseBody,n):n.build(0)}async function Of(e,t){return rt(e,t.redirections,"",()=>Tm(e,t))}async function Tm(e,t){let n=new pn(e),r=0,s=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return L(`bash: \`${t.variable}': not a valid identifier
|
|
783
|
+
`);let i=[];if(t.words===null)i=(e.state.env.get("@")||"").split(" ").filter(Boolean);else if(t.words.length===0)i=[];else try{for(let a of t.words){let o=await bt(e,a);Ie(i,o.values,e.limits.maxArrayElements,"for-loop expansion")}}catch(a){if(a instanceof zt)return{stdout:"",stderr:a.stderr,exitCode:1};throw a}e.state.loopDepth++;try{for(let a of i){s++,s>e.limits.maxLoopIterations&&sn(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n.stdout,n.stderr),e.state.env.set(t.variable,a);try{for(let o of t.body){let l=await e.executeStatement(o);n.append(l.stdout,l.stderr),r=l.exitCode}}catch(o){let l=kr(o,n.stdout,n.stderr,e.state.loopDepth);if(n.replace(l.stdout,l.stderr),l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return n.build(l.exitCode??1);throw l.error}}}finally{e.state.loopDepth--}return n.build(r)}async function _f(e,t){return rt(e,t.redirections,"",()=>Fm(e,t))}async function Fm(e,t){let n=t.line;n!==void 0&&(e.state.currentLine=n);let r=new pn(e),s=0,i=0;t.init&&await Y(e,t.init.expression),e.state.loopDepth++;try{for(;i++,i>e.limits.maxLoopIterations&&sn(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r.stdout,r.stderr),!(t.condition&&(n!==void 0&&(e.state.currentLine=n),await Y(e,t.condition.expression)===0));){try{for(let a of t.body){let o=await e.executeStatement(a);r.append(o.stdout,o.stderr),s=o.exitCode}}catch(a){let o=kr(a,r.stdout,r.stderr,e.state.loopDepth);if(r.replace(o.stdout,o.stderr),o.action==="break")break;if(o.action==="continue"){t.update&&await Y(e,t.update.expression);continue}if(o.action==="error")return r.build(o.exitCode??1);throw o.error}t.update&&await Y(e,t.update.expression)}}finally{e.state.loopDepth--}return r.build(s)}async function Lf(e,t,n=""){return rt(e,t.redirections,n,r=>Mm(e,t,n,r))}async function Mm(e,t,n,r){let s=new pn(e),i=0,a=0,o=Df(r.stdin,n),l=e.state.groupStdin;o.owns&&(e.state.groupStdin=o.stdin),e.state.loopDepth++;try{for(;;){a++,a>e.limits.maxLoopIterations&&sn(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let u=0,c=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let p of t.condition){let h=await e.executeStatement(p);s.append(h.stdout,h.stderr),u=h.exitCode}}catch(p){if(p instanceof Qe){if(s.append(p.stdout,p.stderr),p.levels>1&&e.state.loopDepth>1)throw p.levels--,p.stdout=s.stdout,p.stderr=s.stderr,e.state.inCondition=d,p;c=!0}else if(p instanceof Ke){if(s.append(p.stdout,p.stderr),p.levels>1&&e.state.loopDepth>1)throw p.levels--,p.stdout=s.stdout,p.stderr=s.stderr,e.state.inCondition=d,p;f=!0}else throw e.state.inCondition=d,p}finally{e.state.inCondition=d}if(c)break;if(!f){if(u!==0)break;try{for(let p of t.body){let h=await e.executeStatement(p);s.append(h.stdout,h.stderr),i=h.exitCode}}catch(p){let h=kr(p,s.stdout,s.stderr,e.state.loopDepth);if(s.replace(h.stdout,h.stderr),h.action==="break")break;if(h.action==="continue")continue;if(h.action==="error")return s.build(h.exitCode??1);throw h.error}}}}finally{e.state.loopDepth--,o.owns&&(e.state.groupStdin=l)}return s.build(i)}async function Tf(e,t,n=""){return rt(e,t.redirections,n,r=>Bm(e,t,n,r))}async function Bm(e,t,n,r){let s=new pn(e),i=0,a=0,o=Df(r.stdin,n),l=e.state.groupStdin;o.owns&&(e.state.groupStdin=o.stdin),e.state.loopDepth++;try{for(;;){a++,a>e.limits.maxLoopIterations&&sn(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let u=await ao(e,t.condition);if(s.append(u.stdout,u.stderr),u.exitCode===0)break;try{for(let c of t.body){let f=await e.executeStatement(c);s.append(f.stdout,f.stderr),i=f.exitCode}}catch(c){let f=kr(c,s.stdout,s.stderr,e.state.loopDepth);if(s.replace(f.stdout,f.stderr),f.action==="break")break;if(f.action==="continue")continue;if(f.action==="error")return s.build(f.exitCode??1);throw f.error}}}finally{e.state.loopDepth--,o.owns&&(e.state.groupStdin=l)}return s.build(i)}async function Ff(e,t){return rt(e,t.redirections,"",()=>Wm(e,t))}async function Wm(e,t){let n=new pn(e),r=0,s=await ie(e,t.word),i=!1;for(let a=0;a<t.items.length;a++){let o=t.items[a],l=i;if(!i)for(let u of o.patterns){let c=await ie(e,u);lc(u)&&(c=et(c));let f=e.state.shoptOptions.nocasematch,d=e.state.shoptOptions.extglob;if(Un(s,c,f,d,e.limits.maxCallDepth)){l=!0;break}}if(l){let u=await oo(e,o.body,n);if(n.replace(u.stdout,u.stderr),r=u.exitCode,o.terminator===";;")break;o.terminator===";&"?i=!0:i=!1}else i=!1}return n.build(r)}function lo(e,t){if(e.parts.length!==1)return!1;let n=e.parts[0];return n.type!=="Literal"?!1:t.includes(n.value)}async function Mf(e,t,n){let r=t.timed?ri():0,s="",i=ne,a=0,o=[],l="",u=0,c=t.commands.length>1,f=e.state.lastArg,d=e.state.groupStdin,p=e.state.groupStdinSourceFd;for(let g=0;g<t.commands.length;g++){let y=t.commands[g],b=g===t.commands.length-1,A=g===0;c&&(e.state.lastArg="",e.state.groupStdin=A?d:void 0,e.state.groupStdinSourceFd=A?p:void 0);let k=c&&(!b||!e.state.shoptOptions.lastpipe),v=k?new Map(e.state.env):null,$=k?at(e.state.arrays):null,D,x=e.executionScope.outputBytesUsed;try{e.state.commandCount=e.executionScope.chargeCommand(),D=await n(y,s)}catch(C){if(C instanceof Xe)D={stdout:C.stdout,stderr:C.stderr,exitCode:1};else if(C instanceof q&&t.commands.length>1)D={stdout:C.stdout,stderr:C.stderr,exitCode:C.exitCode};else if(C instanceof ze&&t.commands.length>1)D={stdout:C.stdout,stderr:C.stderr,exitCode:C.exitCode};else throw v&&(e.state.env=v,e.state.arrays=$??new Map),C}finally{c&&(A&&(d=e.state.groupStdin,p=e.state.groupStdinSourceFd),e.state.groupStdin=d,e.state.groupStdinSourceFd=p)}if(v&&(e.state.env=v,e.state.arrays=$??new Map),D=e.executionScope.accountResult(D,"pipeline",e.executionScope.outputBytesUsed-x),!b){let C=t.pipeStderr?.[g]??!1,I=D.internalOutputAccounting?.stdout??0,W=C?D.internalOutputAccounting?.stderr??0:0;Mo(e.executionScope,I+W,"pipeline"),D={...D,internalOutputAccounting:{stdout:0,stderr:C?0:D.internalOutputAccounting?.stderr??0}}}o.push(D.exitCode),D.exitCode!==0&&(a=D.exitCode),b?i=D:(t.pipeStderr?.[g]??!1?s=mn(D.stderr)+Wt(D):(s=Wt(D),l+=D.stderr,u+=D.internalOutputAccounting?.stderr??0),i={stdout:"",stderr:"",exitCode:D.exitCode})}l&&(i={...i,stderr:l+i.stderr,internalOutputAccounting:{stdout:i.internalOutputAccounting?.stdout??0,stderr:u+(i.internalOutputAccounting?.stderr??0)}});let h=t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand",m=i.internalPipeStatusOverride??o;if(h){ge(e,"PIPESTATUS");for(let g=0;g<m.length;g++)j(e,"PIPESTATUS",g,String(m[g]))}if(e.state.options.pipefail&&a!==0&&(i={...i,exitCode:a}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let y=(ri()-r)/1e3,b=Math.floor(y/60),A=y%60,k;t.timePosix?k=`real ${y.toFixed(2)}
|
|
779
784
|
user 0.00
|
|
780
785
|
sys 0.00
|
|
781
786
|
`:k=`
|
|
782
787
|
real ${`${b}m${A.toFixed(3)}s`}
|
|
783
788
|
user 0m0.000s
|
|
784
789
|
sys 0m0.000s
|
|
785
|
-
`,i={...i,stderr:i.stderr+k}}c&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=f),i=e.executionScope.accountResult(i,"pipeline");let{internalPipeStatusOverride:E,...S}=i;return S}function
|
|
786
|
-
`),i.build(1)}return i.build(
|
|
787
|
-
`),
|
|
790
|
+
`,i={...i,stderr:i.stderr+k}}c&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=f),i=e.executionScope.accountResult(i,"pipeline");let{internalPipeStatusOverride:E,...S}=i;return S}function uo(e){return e?{...e,options:e.options?[...e.options]:void 0,actions:e.actions?[...e.actions]:void 0}:void 0}function Vm(e){return e?new Map(Array.from(e,([t,n])=>[t,uo(n)])):void 0}function zm(e){if(!e)return;let t=new Map,n=new Map;for(let[r,s]of e){let i=t.get(s);i||(i=new Set(s),t.set(s,i)),n.set(r,i)}return n}function Um(e){return e?.map(t=>new Map(Array.from(t,([n,r])=>[n,r?{kind:r.kind,elements:new Map(r.elements)}:void 0])))}function qm(e){return e?new Map(Array.from(e,([t,n])=>[t,n.map(r=>({...r}))])):void 0}function co(e){let t={env:e.env,arrays:e.arrays,cwd:e.cwd,previousDir:e.previousDir,lastExitCode:e.lastExitCode,lastArg:e.lastArg,currentLine:e.currentLine,options:e.options,shoptOptions:e.shoptOptions,fileDescriptors:e.fileDescriptors,inputFds:e.inputFds,fdAliases:e.fdAliases,closedStandardFds:e.closedStandardFds,nextFd:e.nextFd,readonlyVars:e.readonlyVars,associativeArrays:e.associativeArrays,namerefs:e.namerefs,boundNamerefs:e.boundNamerefs,invalidNamerefs:e.invalidNamerefs,integerVars:e.integerVars,lowercaseVars:e.lowercaseVars,uppercaseVars:e.uppercaseVars,exportedVars:e.exportedVars,tempExportedVars:e.tempExportedVars,localExportedVars:e.localExportedVars,declaredVars:e.declaredVars,localScopes:e.localScopes,localArrayScopes:e.localArrayScopes,localVarDepth:e.localVarDepth,localVarStack:e.localVarStack,fullyUnsetLocals:e.fullyUnsetLocals,tempEnvBindings:e.tempEnvBindings,mutatedTempEnvVars:e.mutatedTempEnvVars,accessedTempEnvVars:e.accessedTempEnvVars,functions:e.functions,callDepth:e.callDepth,sourceDepth:e.sourceDepth,callLineStack:e.callLineStack,funcNameStack:e.funcNameStack,sourceStack:e.sourceStack,currentSource:e.currentSource,inCondition:e.inCondition,loopDepth:e.loopDepth,parentHasLoopContext:e.parentHasLoopContext,errexitSafe:e.errexitSafe,directoryStack:e.directoryStack,hashTable:e.hashTable,completionSpecs:e.completionSpecs,defaultCompletionSpec:e.defaultCompletionSpec,emptyCompletionSpec:e.emptyCompletionSpec,groupStdin:e.groupStdin,groupStdinSourceFd:e.groupStdinSourceFd,bashPid:e.bashPid,expansionExitCode:e.expansionExitCode,expansionStderr:e.expansionStderr};e.env=new Map(e.env),e.arrays=at(e.arrays),e.options={...e.options},e.shoptOptions={...e.shoptOptions},e.fileDescriptors=e.fileDescriptors?new Map(e.fileDescriptors):void 0,e.inputFds=e.inputFds?new Set(e.inputFds):void 0,e.fdAliases=zm(e.fdAliases),e.closedStandardFds=e.closedStandardFds?new Set(e.closedStandardFds):void 0,e.readonlyVars=new Set(e.readonlyVars),e.associativeArrays=new Set(e.associativeArrays),e.namerefs=new Set(e.namerefs),e.boundNamerefs=new Set(e.boundNamerefs),e.invalidNamerefs=new Set(e.invalidNamerefs),e.integerVars=new Set(e.integerVars),e.lowercaseVars=new Set(e.lowercaseVars),e.uppercaseVars=new Set(e.uppercaseVars),e.exportedVars=new Set(e.exportedVars),e.tempExportedVars=new Set(e.tempExportedVars),e.localExportedVars=e.localExportedVars?.map(r=>new Set(r)),e.declaredVars=new Set(e.declaredVars),e.localScopes=e.localScopes.map(r=>new Map(r)),e.localArrayScopes=Um(e.localArrayScopes),e.localVarDepth=e.localVarDepth?new Map(e.localVarDepth):void 0,e.localVarStack=qm(e.localVarStack),e.fullyUnsetLocals=e.fullyUnsetLocals?new Map(e.fullyUnsetLocals):void 0,e.tempEnvBindings=e.tempEnvBindings?.map(r=>new Map(r)),e.mutatedTempEnvVars=e.mutatedTempEnvVars?new Set(e.mutatedTempEnvVars):void 0,e.accessedTempEnvVars=e.accessedTempEnvVars?new Set(e.accessedTempEnvVars):void 0,e.functions=new Map(e.functions),e.callLineStack=e.callLineStack?[...e.callLineStack]:void 0,e.funcNameStack=e.funcNameStack?[...e.funcNameStack]:void 0,e.sourceStack=e.sourceStack?[...e.sourceStack]:void 0,e.directoryStack=e.directoryStack?[...e.directoryStack]:void 0,e.hashTable=e.hashTable?new Map(e.hashTable):void 0,e.completionSpecs=Vm(e.completionSpecs),e.defaultCompletionSpec=uo(e.defaultCompletionSpec),e.emptyCompletionSpec=uo(e.emptyCompletionSpec);let n=!1;return()=>{n||(n=!0,Object.assign(e,t))}}async function Bf(e,t,n,r,s=!1){let i=e.state.loopDepth,a=new Map;for(let l of e.state.fileDescriptors?.keys()??[]){let u=nt(e,l);u&&a.set(l,u)}let o=co(e.state);e.state.parentHasLoopContext=i>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;try{return await rt(e,t.redirections,n,l=>jm(e,t,l.stdin??n,r,s||l.stdin!==void 0))}finally{let l=new Map;for(let[u,c]of a){let f=nt(e,u),d=c.kind==="input"&&f?.kind==="input"?c.content.length-f.content.length:c.kind==="readwrite"&&f?.kind==="readwrite"&&c.path===f.path?f.position-c.position:0;if(d<=0)continue;let p=Math.min(...ln(e,u));l.set(p,Math.max(l.get(p)??0,d))}o();for(let[u,c]of l)un(e,u,c)}}async function jm(e,t,n,r,s){(s||n)&&(e.state.groupStdin=n);let i=new Gt(e.executionScope,"subshell"),a=0;try{for(let o of t.body){let l=await r(o);i.appendResult(l),a=l.exitCode}}catch(o){if(o instanceof P)throw i.prependTo(o),o;if(o instanceof Ut||o instanceof Qe||o instanceof Ke)return i.append("stdout",o.stdout,o.internalOutputAccounting.stdout),i.append("stderr",o.stderr,o.internalOutputAccounting.stderr),i.build(0);if(o instanceof q||o instanceof Le||o instanceof ze)return i.append("stdout",o.stdout,o.internalOutputAccounting.stdout),i.append("stderr",o.stderr,o.internalOutputAccounting.stderr),i.build(o.exitCode);if(o instanceof Ce)throw o.prependOutput(i.stdout,i.stderr),o;return i.append("stderr",`${it(o)}
|
|
791
|
+
`),i.build(1)}return i.build(a)}async function Wf(e,t,n,r,s=!1){return rt(e,t.redirections,n,i=>Hm(e,t,n,r,s,i))}async function Hm(e,t,n,r,s,i){let a=new Gt(e.executionScope,"group"),o=0,l=i.stdin??n,u=s||n!==""||i.stdin!==void 0,c=e.state.groupStdin;u&&(e.state.groupStdin=l);let f=()=>{(u||c!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=c)};try{for(let d of t.body){let p=await r(d);a.appendResult(p),o=p.exitCode}}catch(d){if(f(),d instanceof P)throw a.prependTo(d),d;if(Lr(d)||d instanceof ze||d instanceof q||d instanceof Ce)throw d.prependOutput(a.stdout,a.stderr),d;return a.append("stderr",`${it(d)}
|
|
792
|
+
`),a.build(1)}return f(),a.build(o)}async function Vf(e,t,n,r,s){let i;try{i=await e.fs.readFile(t)}catch{return L(`bash: ${t}: No such file or directory
|
|
788
793
|
`,127)}if(i.startsWith("#!")){let l=i.indexOf(`
|
|
789
|
-
`);l!==-1&&(i=i.slice(l+1))}let
|
|
790
|
-
`);throw l}}function
|
|
791
|
-
`);let r=0,s=-1,i=!1;try{for(let l=0;l<t.pipelines.length;l++){let u=t.pipelines[l],c=l>0?t.operators[l-1]:null;if(c==="&&"&&r!==0||c==="||"&&r===0)continue;let f=await this.executePipeline(u);n.appendResult(f,
|
|
792
|
-
`,127));if(c==="exec"&&(f.length===0||f[0]==="--")){for(let[
|
|
793
|
-
`)}})}async executeConditionalCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),
|
|
794
|
-
`,r)}})}};function
|
|
794
|
+
`);l!==-1&&(i=i.slice(l+1))}let a=e.state.loopDepth,o=co(e.state);e.state.parentHasLoopContext=a>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set("0",t),e.state.env.set("#",String(n.length)),e.state.env.set("@",n.join(" ")),e.state.env.set("*",n.join(" "));for(let l=0;l<n.length&&l<9;l++)e.state.env.set(String(l+1),n[l]);for(let l=n.length+1;l<=9;l++)e.state.env.delete(String(l));try{let u=new H().parse(i),c=await s(u);return o(),c}catch(l){if(o(),l instanceof q)return T(l.stdout,l.stderr,l.exitCode);if(l instanceof Ce||l instanceof P)throw l;if(l.name==="ParseException")return L(`bash: ${t}: ${l.message}
|
|
795
|
+
`);throw l}}function Gm(e){throw new TypeError(`Unsupported command node: ${JSON.stringify(e)}`)}var xr=class{ctx;constructor(t,n){this.ctx={state:n,fs:t.fs,commands:t.commands,limits:t.limits,executionScope:t.executionScope,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,invokeTool:t.invokeTool}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||Ze.isInSandboxedContext())return;let n=`interpreter ${t} attempted outside defense context`;throw new Ir(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:Ze.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,n=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(n)for(let i of n)r.add(i);if(r.size===0)return Object.create(null);let s=Object.create(null);for(let i of r){let a=this.ctx.state.env.get(i);a!==void 0&&(s[i]=a)}return s}async executeScript(t){this.assertDefenseContext("execution");let n=0,r=new Gt(this.ctx.executionScope,"script");for(let s of t.statements)try{let i=await this.executeStatement(s);r.appendResult(i,ti(i)),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(i){if(i instanceof q||i instanceof Ce)throw i.prependOutput(r.stdout,r.stderr),i;if(i instanceof st)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Ht(this.ctx.state.env)};if(Tr(i))throw r.prependTo(i),i;if(i instanceof ze)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Ht(this.ctx.state.env)};if(i instanceof Ue)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Ht(this.ctx.state.env)};if(i instanceof Xe)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Ht(this.ctx.state.env)};if(i instanceof le){r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(i instanceof _r){r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(i instanceof Qe||i instanceof Ke){if(this.ctx.state.loopDepth>0)throw i.prependOutput(r.stdout,r.stderr),i;r.append("stdout",i.stdout),r.append("stderr",i.stderr);continue}throw i instanceof Le&&i.prependOutput(r.stdout,r.stderr),i}return{...r.build(n),env:Ht(this.ctx.state.env)}}async executeUserScript(t,n,r=""){return Vf(this.ctx,t,n,r,s=>this.executeScript(s))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new Ye;if(t.deferredError)throw new xe(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return ne;this.ctx.state.errexitSafe=!1;let n=new Gt(this.ctx.executionScope,"statement");this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&n.append("stderr",`${t.sourceText}
|
|
796
|
+
`);let r=0,s=-1,i=!1;try{for(let l=0;l<t.pipelines.length;l++){let u=t.pipelines[l],c=l>0?t.operators[l-1]:null;if(c==="&&"&&r!==0||c==="||"&&r===0)continue;let f=await this.executePipeline(u);n.appendResult(f,ti(f)),r=f.exitCode,s=l,i=u.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set("?",String(r))}}catch(l){throw n.prependTo(l),l}let a=s<t.pipelines.length-1,o=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||i||o,this.ctx.state.options.errexit&&r!==0&&s===t.pipelines.length-1&&!i&&!this.ctx.state.inCondition&&!o){let l=new ze(r);throw l.prependOutput(n.stdout,n.stderr),l}return n.build(r)}async executePipeline(t){return Mf(this.ctx,t,(n,r)=>this.executeCommand(n,r))}async executeCommand(t,n,r=!1){let s=ac(this.ctx),i;try{i=await this.executeCommandInner(t,n,r)}catch(o){throw await ea(this.ctx,s).catch(()=>{}),o}let a=await ea(this.ctx,s);return!a.stdout&&!a.stderr?i:{...i,stdout:a.stdout?Wt(i)+a.stdout:i.stdout,stdoutKind:a.stdout?"bytes":i.stdoutKind,stderr:i.stderr+a.stderr}}async executeCommandInner(t,n,r){switch(this.assertDefenseContext("command"),this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,n);case"If":return If(this.ctx,t);case"For":return Of(this.ctx,t);case"CStyleFor":return _f(this.ctx,t);case"While":return Lf(this.ctx,t,n);case"Until":return Tf(this.ctx,t,n);case"Case":return Ff(this.ctx,t);case"Subshell":return this.executeSubshell(t,n,r);case"Group":return this.executeGroup(t,n,r);case"FunctionDef":return Wc(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return Gm(t)}}async executeSimpleCommand(t,n){let r;try{return await this.executeSimpleCommandInner(t,n,s=>{r=s})}catch(s){if(r?.finish(),s instanceof zt)return L(s.stderr);throw s}}async executeSimpleCommandInner(t,n,r){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let x=t,C=0;for(;;){let I=this.expandAlias(x);if(I===x)break;if(C>=this.ctx.limits.maxCallDepth)throw new P(`alias expansion depth limit exceeded (${this.ctx.limits.maxCallDepth})`,"recursion");C++,x=I}this.aliasExpansionStack.clear(),x!==t&&(t=x)}this.ctx.state.expansionStderr="";let s=await Ef(this.ctx,t);if(s.error)return s.error;let i=s.tempAssignments,a=s.xtraceOutput,o=()=>{for(let[x,C]of i)C===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,C)};if(!t.name){if(t.redirections.length>0){let C=Gn(this.ctx,t.redirections,Mc);r(C);let I=await C.prepare(n);if(I.error){if(o(),!I.errorCause)return C.finish(),I.error;try{return Zn(I)}finally{C.finish()}}let W=T("",a,0),Z=await fn(this.ctx,W,t.redirections,I.targets,I.dupSources,I.standardRoutes);return C.finish(),Z}this.ctx.state.lastArg="";let x=(this.ctx.state.expansionStderr||"")+a;return this.ctx.state.expansionStderr="",T("",x,this.ctx.state.lastExitCode)}let l=t.name&&lo(t.name,["local","declare","typeset","export","readonly"]),u=Array.from(i.keys());if(u.length>0&&!l){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let x of u)this.ctx.state.tempExportedVars.add(x)}let c=await ie(this.ctx,t.name),f=[],d=[],p=(x,C)=>{if(f.length>=this.ctx.limits.maxArrayElements)throw new P(`expanded argument element limit exceeded (${this.ctx.limits.maxArrayElements})`,"array_elements");f.push(x),d.push(C)};if(lo(t.name,["local","declare","typeset","export","readonly"])&&(c==="local"||c==="declare"||c==="typeset"||c==="export"||c==="readonly"))for(let x of t.args){let C=await gc(this.ctx,x);if(C)p(C,!0);else{let I=await wc(this.ctx,x);if(I!==null)p(I,!0);else{let W=await bt(this.ctx,x);for(let Z of W.values)p(Z,W.quoted)}}}else for(let x of t.args){let C=await bt(this.ctx,x);for(let I of C.values)p(I,C.quoted)}let m=t.name.parts.every(x=>x.type==="CommandSubstitution"||x.type==="ParameterExpansion"||x.type==="ArithmeticExpansion");!c&&m&&f.length>0&&(c=f.shift(),d.shift());let E=Gn(this.ctx,t.redirections,c==="exec"?Bc:gr);r(E);let S=await E.prepare(n);if(S.error)return o(),S.errorCause?Zn(S):(E.finish(),S.error);let g=S.stdinSourceFd,y=S.stdin!==void 0;if(S.stdin!==void 0&&(n=S.stdin),!c)return m?(E.finish(),T("","",this.ctx.state.lastExitCode)):(E.finish(),L(`bash: : command not found
|
|
797
|
+
`,127));if(c==="exec"&&(f.length===0||f[0]==="--")){for(let[x,C]of i)C===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,C);if(this.ctx.state.tempExportedVars)for(let x of i.keys())this.ctx.state.tempExportedVars.delete(x);return E.finish(),ne}if(this.ctx.state.extraArgs){let x=this.ctx.state.extraArgs;this.ctx.state.extraArgs=void 0;for(let C of x)p(C,!0)}let b=await gf(this.ctx,c,f);i.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(i)));let A,k=null;try{A=await this.runCommand(c,f,d,n,!1,!1,g,y)}catch(x){if(x instanceof Qe||x instanceof Ke)k=x,A=ne;else throw x}g>=0&&c!=="read"&&un(this.ctx,g,A.internalStdinConsumed??0);let v=a+b;if(v&&(A={...A,stderr:v+A.stderr}),A=await fn(this.ctx,A,t.redirections,S.targets,S.dupSources,S.standardRoutes,A.internalProducerCommand??c,A.internalProducerOmitsShellPrefix),E.finish(),k)throw k;if(f.length>0){let x=f[f.length-1];if((c==="declare"||c==="local"||c==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(x)){let C=x.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);C&&(x=C[1])}this.ctx.state.lastArg=x}else this.ctx.state.lastArg=c;let $=Qo(c)&&c!=="unset"&&c!=="eval";if(!this.ctx.state.options.posix||!$)for(let[x,C]of i)this.ctx.state.fullyUnsetLocals?.has(x)||(C===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,C));if(this.ctx.state.tempExportedVars)for(let x of i.keys())this.ctx.state.tempExportedVars.delete(x);return i.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(A={...A,stderr:this.ctx.state.expansionStderr+A.stderr},this.ctx.state.expansionStderr=""),A}async runCommand(t,n,r,s,i=!1,a=!1,o=-1,l=!1){let u={ctx:this.ctx,runCommand:(d,p,h,m,E,S,g,y)=>this.runCommand(d,p,h,m,E,S,g,y),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(d,p,h)=>this.executeUserScript(d,p,h)},c=await Nf(u,t,n,r,s,i,a,o,l);return c!==null?c.internalProducerCommand===void 0?{...c,internalProducerCommand:t}:c:{...await Rf(u,t,n,s,a),internalProducerCommand:t}}aliasExpansionStack=new Set;expandAlias(t){return Ul({env:this.ctx.state.env,limits:this.ctx.limits},t,this.aliasExpansionStack)}async findCommandInPath(t){return qr(this.ctx,t)}async executeSubshell(t,n="",r=!1){return Bf(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeGroup(t,n="",r=!1){return Wf(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeArithmeticCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),rt(this.ctx,t.redirections,"",async()=>{try{let n=await Y(this.ctx,t.expression.expression),r=we(n!==0);return this.ctx.state.expansionStderr&&(r={...r,stderr:this.ctx.state.expansionStderr+r.stderr},this.ctx.state.expansionStderr=""),r}catch(n){return L(`bash: arithmetic expression: ${n.message}
|
|
798
|
+
`)}})}async executeConditionalCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),rt(this.ctx,t.redirections,"",async()=>{try{let n=await an(this.ctx,t.expression),r=we(n);return this.ctx.state.expansionStderr&&(r={...r,stderr:this.ctx.state.expansionStderr+r.stderr},this.ctx.state.expansionStderr=""),r}catch(n){let r=n instanceof le?1:2;return L(`bash: conditional expression: ${n.message}
|
|
799
|
+
`,r)}})}};function fo(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Zm(e){let t=fo(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}var Qm=3;function zf(e){let t=e;for(let n=0;n<Qm;n++){if(t.includes("\\")||t.includes(";")||/%(?![0-9a-f]{2})/i.test(t))return!0;let r=t.toLowerCase();if(r.includes("%2f")||r.includes("%2e")||r.includes("%5c")||r.includes("%3b"))return!0;let s;try{s=decodeURIComponent(t)}catch{return!0}if(s===t)return!1;t=s}return t.includes("%")}function Km(e,t){return t==="/"||t===""?!0:t.endsWith("/")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function po(e,t){let n=fo(e);if(!n)return!1;let r=Zm(t);return!r||n.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&zf(n.pathname)?!1:Km(n.pathname,r.pathPrefix)}function Uf(e){return typeof e=="string"?e:e.url}function qf(e,t){return!t||t.length===0?!1:t.some(n=>po(e,Uf(n)))}function ho(e){let t=Xm(e);if(t==="localhost"||t.endsWith(".localhost"))return!0;let n=jf(t);if(n)return Gs(n);let r=Jm(t);return r?ey(r):!1}function Xm(e){let t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Ym(e){if(!e)return null;let t=10,n=e;if(n.startsWith("0x")||n.startsWith("0X")?(t=16,n=n.slice(2)):n.length>1&&n.startsWith("0")&&(t=8),!n||t===16&&!/^[0-9a-fA-F]+$/.test(n)||t===10&&!/^\d+$/.test(n)||t===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,t);return!Number.isFinite(r)||r<0?null:r}function jf(e){let t=e.split(".");if(t.length===0||t.length>4)return null;let n=t.map(l=>Ym(l));if(n.some(l=>l===null))return null;let r=n;if(t.length===1){let l=r[0];return l>4294967295?null:[l>>>24&255,l>>>16&255,l>>>8&255,l&255]}if(t.length===2){let[l,u]=r;return l>255||u>16777215?null:[l,u>>>16&255,u>>>8&255,u&255]}if(t.length===3){let[l,u,c]=r;return l>255||u>255||c>65535?null:[l,u,c>>>8&255,c&255]}let[s,i,a,o]=r;return s>255||i>255||a>255||o>255?null:[s,i,a,o]}function Jm(e){let t=e,n=null;if(t.includes(".")){let m=t.lastIndexOf(":");if(m<0)return null;let E=t.slice(m+1),S=jf(E);if(!S)return null;n=S,t=t.slice(0,m)}let r=t.includes("::")?t.split("::").length-1:0;if(r>1)return null;let[s,i]=t.split("::"),a=s?s.split(":").filter(Boolean):[],o=i?i.split(":").filter(Boolean):[],l=m=>/^[0-9a-f]{1,4}$/i.test(m)?Number.parseInt(m,16):null,u=a.map(l),c=o.map(l);if(u.some(m=>m===null)||c.some(m=>m===null))return null;let f=n?2:0,d=u.length+c.length+f,p=0;if(r===1){if(p=8-d,p<0)return null}else if(d!==8)return null;let h=[...u,...new Array(p).fill(0),...c];return n&&(h.push(n[0]<<8|n[1]),h.push(n[2]<<8|n[3])),h.length===8?h:null}function Gs(e){let[t,n]=e;return t===127||t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===169&&n===254||t===0||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===192&&n===0&&e[2]===0||t===192&&n===0&&e[2]===2||t===198&&n===51&&e[2]===100||t===203&&n===0&&e[2]===113||t>=240}function ey(e){if(e.every(s=>s===0)||e.slice(0,7).every(s=>s===0)&&e[7]===1||(e[0]&65472)===65152||(e[0]&65024)===64512)return!0;if(e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535){let s=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Gs(s)}if(e[0]===8193&&e[1]===3512)return!0;if(e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0){let s=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Gs(s)}if(e[0]===100&&e[1]===65435&&e[2]===1)return!0;if(e[0]===8194){let s=[e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255];return Gs(s)}return!1}function Hf(e){let t=[];for(let n of e){if(typeof n!="string"&&(n===null||typeof n!="object"||!("url"in n)||typeof n.url!="string")){t.push('Invalid allow-list entry: must be a string URL or an object with a "url" string property');continue}let r=Uf(n);if(!fo(r)){t.push(`Invalid URL in allow-list: "${r}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let i=new URL(r);if(i.protocol!=="http:"&&i.protocol!=="https:"){t.push(`Only http and https URLs are allowed in allow-list: "${r}"`);continue}if(!i.hostname){t.push(`Allow-list entry must include a hostname: "${r}"`);continue}if(i.pathname!=="/"&&i.pathname!==""&&zf(i.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${r}"`);continue}(i.search||i.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${r}"`)}return t}var St=class extends Error{constructor(t,n){let r=n??"URL not in allow-list";super(`Network access denied: ${r}: ${t}`),this.name="NetworkAccessDeniedError"}},Xn=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},hn=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Zs=class extends Error{constructor(t,n){super(`HTTP method '${t}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}},Pn=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var ty=20,ny=3e4,ry=10485760,sy=["GET","HEAD"],$r;typeof __BROWSER__<"u"&&__BROWSER__?$r=null:($r=import("./chunks/dist-5MWO25Y4.js"),$r.catch(()=>{}));var iy=new Set(["GET","HEAD","OPTIONS"]),ay=new Set([301,302,303,307,308]);function Pr(e){return e.reason instanceof Error?e.reason:new DOMException("The operation was aborted","AbortError")}function oy(e){if(e?.aborted)throw Pr(e)}function yo(e){let t=e.allowedUrlPrefixes??[];if(e._dnsResolve)throw new Error("NetworkConfig._dnsResolve is no longer supported: DNS resolution is performed by guarded-fetch and cannot be overridden");if(e._createConnectionOwner)throw new Error("NetworkConfig._createConnectionOwner is no longer supported: connect-time IP pinning is performed by guarded-fetch and cannot be overridden");let n=e._fetch;if(!e.dangerouslyAllowFullInternetAccess){let b=Hf(t);if(b.length>0)throw new Error(`Invalid network allow-list:
|
|
795
800
|
${b.join(`
|
|
796
|
-
`)}`)}let r=[];for(let b of t)typeof b=="object"&&b.transform&&b.transform.length>0&&r.push(b);function s(b){if(r.length===0)return null;let A=null;for(let k of r)if(
|
|
797
|
-
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=
|
|
801
|
+
`)}`)}let r=[];for(let b of t)typeof b=="object"&&b.transform&&b.transform.length>0&&r.push(b);function s(b){if(r.length===0)return null;let A=null;for(let k of r)if(po(b,k.url)&&k.transform){A||(A=new Headers);for(let v of k.transform)for(let[$,D]of Object.entries(v.headers))A.set($,D)}return A}if(e.maxRedirects!==void 0&&(!Number.isSafeInteger(e.maxRedirects)||e.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let i=e.maxRedirects??ty,a=e.timeoutMs??ny,o=e.maxResponseSize??ry,l=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??sy,u=e.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),c=[];for(let b of t){let A=typeof b=="string"?b:b.url;try{c.push(new URL(A).hostname)}catch{}}function f(b){try{return new URL(b).hostname||"localhost.invalid"}catch{return"localhost.invalid"}}function d(b){return e.dangerouslyAllowFullInternetAccess?u?{allowedHosts:void 0,skipSsrfCheckForAllowedHosts:void 0}:{allowedHosts:[f(b)],skipSsrfCheckForAllowedHosts:!0}:{allowedHosts:c,skipSsrfCheckForAllowedHosts:!u}}function p(b){try{return ho(new URL(b).hostname)}catch{return!1}}async function h(b,A){let k={method:A.method,headers:A.headers,signal:A.signal,redirect:"manual"};return A.body!==void 0&&(k.body=A.body),await(n??globalThis.fetch)(b,k)}function m(b){if(!e.dangerouslyAllowFullInternetAccess&&!qf(b,t))throw new St(b)}function E(b){if(!u)return;let A;try{A=new URL(b)}catch{throw new St(b,"invalid URL")}if(ho(A.hostname))throw new St(b,"private/loopback IP address blocked")}function S(b){if(e.dangerouslyAllowFullInternetAccess)return;let A=b.toUpperCase();if(!l.includes(A))throw new Zs(A,l)}function g(b,A,k,v){if(!k.isGuardedFetchError(b))return b;let $=b,{onRedirectHop:D,subReason:x}=v;switch($.code){case"host_not_allowed":case"protocol_not_allowed":return D?new hn(A):new St(A);case"hostname_unsafe":return D?new hn(A):new St(A,x==="dns_resolution_failed"?"DNS resolution failed for private IP check":"hostname resolves to private/loopback IP address");case"redirect_to_unsafe_host":return new hn(A);case"too_many_redirects":return new Xn(i);case"response_too_large":return new Pn(o);default:return b}}async function y(b,A={}){let k=A.method?.toUpperCase()??"GET",v=A.followRedirects??!0;if(A.maxRedirects!==void 0&&(!Number.isSafeInteger(A.maxRedirects)||A.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let $=A.maxRedirects??i,D=Math.min(i,$),x=A.timeoutMs!==void 0?Math.min(A.timeoutMs,a):a,C=new AbortController,I=bo(()=>C.abort(new DOMException("The operation was aborted","AbortError")),x),W=Or(A.signal,C.signal);try{m(b),E(b),S(k);let Z=$r?await $r:null,R=b,V=0,z=[],O=k,_=A.body,M=A.headers,re=!1;for(;;){oy(W.signal);let K=await Ze.runTrustedAsync(async()=>{let _e=M;if(re&&_e){let Lt=_e instanceof Headers?new Headers(_e):new Headers(_e);Lt.delete("authorization"),Lt.delete("cookie"),_e=Lt}let ft=s(R),_t=uy(_e,ft),dt={method:O,headers:_t,signal:W.signal,followRedirects:!1,timeoutMs:x,sanitizeHeaders:!1};if(_&&!iy.has(O)&&(dt.body=_),Object.assign(dt,d(R)),!Z||p(R)){if(u)throw new St(R,"DNS pinning unavailable for private IP enforcement");return await h(R,dt)}u?n&&(dt.fetch=n):(dt.fetch=n??globalThis.fetch,dt.dispatcher=null);let pt;dt.onUrlBlocked=Lt=>{pt=Lt.subReason};try{return await Z.guardedFetch(R,dt)}catch(Lt){throw g(Lt,R,Z,{onRedirectHop:V>0,subReason:pt})}});if(ay.has(K.status)&&v){let _e=K.headers.get("location");if(!_e)return await Gf(K,R,o,W.signal,z);z.push({status:K.status,statusText:K.statusText,headers:Zf(K.headers)});let ft=new URL(_e,R).href;await mo(ly(K),W.signal);try{m(ft),E(ft)}catch(pt){throw W.signal?.aborted?Pr(W.signal):pt instanceof St?new hn(ft):pt}let _t=K.status;if(((_t===301||_t===302)&&O==="POST"||_t===303&&O!=="GET"&&O!=="HEAD")&&(O="GET",_=void 0,S(O)),new URL(ft).origin!==new URL(R).origin&&(re=!0),V++,V>D)throw new Xn(D);R=ft;continue}return await Gf(K,R,o,W.signal,z)}}finally{So(I),W.cleanup()}}return y}async function mo(e,t){if(!t)return e;if(t.aborted)throw e.catch(()=>{}),Pr(t);let n,r=new Promise((s,i)=>{n=()=>i(Pr(t)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,r])}finally{n&&t.removeEventListener("abort",n)}}async function ly(e){e.body&&!e.body.locked&&await e.body.cancel()}function uy(e,t){if(!e&&!t)return;if(!t)return e;let n=e instanceof Headers?new Headers(e):new Headers(e);for(let[r,s]of t)n.set(r,s);return n}function Zf(e){let t=Object.create(null);return e.forEach((n,r)=>{t[r.toLowerCase()]=n}),t}async function Gf(e,t,n,r,s){let i=Zf(e.headers);if(n>0){let l=e.headers.get("content-length");if(l){let u=parseInt(l,10);if(!Number.isNaN(u)&&u>n)throw new Pn(n)}}let a;if(n>0&&e.body){let l=e.body.getReader(),u=[],c=0;try{for(;;){let{done:d,value:p}=await mo(l.read(),r);if(d)break;if(p){if(c+=p.byteLength,c>n)throw await l.cancel(),new Pn(n);u.push(p)}}}catch(d){throw r?.aborted&&await l.cancel(Pr(r)).catch(()=>{}),d}a=new Uint8Array(c);let f=0;for(let d of u)a.set(d,f),f+=d.byteLength}else{let l=await mo(e.arrayBuffer(),r);if(n>0&&l.byteLength>n)throw new Pn(n);a=new Uint8Array(l)}let o={status:e.status,statusText:e.statusText,headers:i,body:a,url:t};return s&&s.length>0&&(o.redirectChain=s),o}function Qs(e,t){if(e.length>t||B(e)>t)throw new P(`script input size limit exceeded (${t} bytes)`,"string_length")}var Ks=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;abortOnUnresolvedCommands=!1;invokeToolFn;transformPlugins=[];state;constructor(t={}){if(this.limits=oi({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}},t.executionLimitProfile),t.fs&&t.files)throw new Error("Bash: options.files is ignored when options.fs is provided; write the files into your filesystem directly or drop options.fs");let n=t.fs??new kt(t.files,{maxTotalBytes:this.limits.maxFileSystemBytes});this.fs=n,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
802
|
+
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=yo(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth??!0,this.abortOnUnresolvedCommands=t.abortOnUnresolvedCommands??!1,this.coverageWriter=t.coverage,this.state={env:s,arrays:new Map,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:t.processInfo?.pid??1,virtualPpid:t.processInfo?.ppid??0,virtualUid:t.processInfo?.uid??1e3,virtualGid:t.processInfo?.gid??1e3,bashPid:t.processInfo?.pid??1,nextVirtualPid:(t.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",pi(this.state.options)),this.state.env.set("BASHOPTS",hi(this.state.shoptOptions)),zo(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&n instanceof kt)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let a of $o(t.commands))this.registerBundledCommand(a);if(t.fetch||t.network)for(let a of Po())this.registerBundledCommand(a);if(t.python)for(let a of Co())this.registerBundledCommand(a);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);if(t.javascript||i.invokeTool){for(let a of No())this.registerBundledCommand(a);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(t.customCommands)for(let a of t.customCommands)if(_o(a)){let o=Lo(a);this.registerCommandInternal(o,!0)}else this.registerCommandInternal(a,!0)}registerCommand(t){this.registerCommandInternal(t,!0)}registerBundledCommand(t){this.registerCommandInternal(t,!1)}registerCommandInternal(t,n,r=n?t.trusted??!0:t.trusted){let s=this.commands.get(t.name),i=n?s?.internalOriginalCommand??(s&&!s.internalIsExtension?s:void 0):void 0,a={name:t.name,trusted:r,internalIsExtension:n,internalOriginalCommand:i,execute:(l,u)=>t.execute(l,u)};this.commands.set(t.name,a);let o=this.fs;if(typeof o.writeFileSync=="function"){let l=`#!/bin/bash
|
|
798
803
|
# Built-in command: ${t.name}
|
|
799
|
-
`;try{
|
|
800
|
-
`,exitCode:126}}return i.unresolvedCommands=r.unresolvedCommandNames,t.trim()?this.logResult(i):i}async execInScope(t,n,r,s,i,
|
|
801
|
-
`,exitCode:1,env:
|
|
802
|
-
`,exitCode:2,env:
|
|
803
|
-
`,exitCode:2,env:
|
|
804
|
-
`,exitCode:1,env:
|
|
805
|
-
`),n=[],r=[],s="none";for(let i=0;i<t.length;i++){let
|
|
806
|
-
`)}var ty=new TextDecoder("utf-8",{fatal:!0});function Mf(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 ty.decode(n)}catch{return e}}function ny(e,t,n,r,s,i){if(e===void 0)return;let o=t==="bytes"?e.length:M(e);if(o>n||o>r)throw new P(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),t==="bytes"?e:pn(e)}import*as me from"node:fs";import*as Ie from"node:path";import*as We from"node:fs";import*as $e from"node:path";function $r(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?$e.win32:$e.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function kr(e,t){try{let n=We.realpathSync(e);return $r(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=$e.dirname(e);if(r===e)return null;let s=kr(r,t);if(s===null)return null;try{if(We.lstatSync(e).isSymbolicLink()){let o=We.readlinkSync(e),a=$e.isAbsolute(o)?o:$e.resolve($e.dirname(e),o),l=kr(a,t);return l===null?null:l}}catch{}return $e.join(s,$e.basename(e))}return null}}function Bf(e,t,n){let r=kr(e,n);if(r===null)return null;let s=$e.resolve(e),i=s.slice(t.length),o=r.slice(n.length);if(i!==o)return null;try{if(We.lstatSync(s).isSymbolicLink())return null}catch{}return r}function Wf(e,t){if(!We.existsSync(e))throw new Error(`${t} root does not exist`);if(!We.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function Vf(e,t){if(!$e.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=We.realpathSync(e)}catch{n=$e.resolve(e)}return $r(n,t)?{withinRoot:!0,relativePath:n.slice(t.length).replace(/\\/g,"/")||"/"}:{withinRoot:!1,safeName:$e.basename(e)}}function zf(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 Error(`${i}: ${n} '${t}'`)}async function bt(e){return Uf(await We.promises.lstat(e))}function pa(e){return Uf(We.lstatSync(e))}function Uf(e){return process.platform==="win32"&&e.isDirectory()&&(e.mode=e.mode&-512|493),e}function Us(e){let t=e.content.byteLength;for(let n of e.appendChunks??[])t+=n.byteLength;return t}function Hf(e){return Us(e)}function js(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 Error(`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 qf(e){return!e||e.type!=="file"?0:Us(e)}function xr(){return{type:"directory",children:new Map,mode:493,mtime:new Date}}function Pr(e){return e.split("/").filter(Boolean)}var qs=class e{maxMemoryBytes;rootNode=xr();bytes=0;constructor(t){this.maxMemoryBytes=t}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(t){let n=Pr(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 Pr(t)){s=`${s}/${i}`;let o=r.children.get(i);if(o===void 0)o=xr(),r.children.set(i,o);else if(o.type==="whiteout")o=this.resurrectDir(r,i,s,n);else if(o.type!=="directory")throw new Error(`ENOTDIR: not a directory, mkdir '${t}'`);r=o}return r}resurrectDir(t,n,r,s){let i=xr();t.children.set(n,i);let o=s?.(r);if(o)for(let a of o)i.children.has(a)||i.children.set(a,{type:"whiteout"});return i}attach(t,n){let r=Pr(t);if(r.length===0)throw new Error(`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 Error(`EISDIR: cannot replace directory with ${n.type}, attach '${t}'`);if(i!==void 0&&n.type==="directory")throw new Error(`EEXIST: cannot replace ${i.type} with directory, attach '${t}'`);let o=qf(i),a=qf(n);this.assertCapacity(a,o),s.children.set(r[r.length-1],n),this.bytes+=a-o}detach(t){let n=Pr(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=Pr(t);if(n.length===0)throw new Error(`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"}))}appendChunk(t,n){this.assertCapacity(n.byteLength),t.appendChunks||(t.appendChunks=[]),t.appendChunks.push(n),this.bytes+=n.byteLength}*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:jf(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:jf(r.path,s),node:i})}for(let r=t.length-1;r>=0;r--)yield t[r]}clear(){this.rootNode=xr(),this.bytes=0}static subtreeBytes(t){if(t===void 0)return 0;if(t.type==="file")return Us(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+=Us(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 Error(`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=xr(),t.children.set(n,s);else if(s.type!=="directory")throw new Error(`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 Error(`ENOSPC: overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function jf(e,t){return e==="/"?`/${t}`:`${e}/${t}`}var ry=["ELOOP","EFBIG","EPERM"],sy="/home/user/project",Hs=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Ie.resolve(t.root);let n=t.mountPoint??sy;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,Wf(this.root,"OverlayFs"),this.canonicalRoot=me.realpathSync(this.root),this.tree=new qs(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){this.tree.ensureDirs(this.mountPoint)}getMountPoint(){return this.mountPoint}diff(){let t=[],n=[];for(let{path:r,node:s}of this.tree.preOrder()){let i=this.getRelativeToMount(r);if(!(i===null||i==="/")){if(s.type==="whiteout"){this.existsOnRealFs(r)&&n.push(i);continue}if(s.type==="file")if(s.metacopy){if(!this.existsOnRealFs(r))continue;t.push({path:i,nodeType:"file",content:new Uint8Array(0),mode:s.mode,mtime:s.mtime,metadataOnly:!0})}else t.push({path:i,nodeType:"file",content:js(s,r),mode:s.mode,mtime:s.mtime});else s.type==="directory"?t.push({path:i,nodeType:"directory",content:new Uint8Array(0),mode:s.mode,mtime:s.mtime}):t.push({path:i,nodeType:"symlink",content:new TextEncoder().encode(s.target),mode:s.mode,mtime:s.mtime})}}return t.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),n.sort(),{writes:t,deletions:n}}async sync(){for(let{path:t,node:n}of this.tree.postOrder()){let r=this.getRelativeToMount(t);if(!(r===null||r==="/")){if(n.type==="whiteout"){this.existsOnRealFs(t)||this.tree.detach(t);continue}n.type==="directory"&&n.children.size>0||await this.nodeMatchesDisk(t,n)&&this.tree.detach(t)}}}reset(){this.tree.clear(),this.createMountPointDirs()}drop(t){let n=t.map(r=>{let s=z(r);if(s==="/")throw new Error(`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 bt(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 me.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 bt(r);if(!s.isFile())return!1;let i=js(n,t);if(s.size!==i.byteLength)return!1;let o=this.allowSymlinks?me.constants.O_RDONLY:me.constants.O_RDONLY|me.constants.O_NOFOLLOW,a=await me.promises.open(r,o),l;try{l=new Uint8Array(await a.readFile())}finally{await a.close()}for(let u=0;u<l.byteLength;u++)if(l[u]!==i[u])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:420,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=Ie.join(this.root,r),i=Ie.resolve(s);return $r(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?kr(t,this.canonicalRoot):Bf(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Ie.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Ie.join(r,Ie.basename(t))}sanitizeError(t,n,r){zf(t,n,r,ry)}ensureParentDirs(t){let n=Cn(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 me.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 bt(s),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=jt(n);return In(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return In(n,"binary")}async readFileBuffer(t,n=new Set){K(t,"open");let r=z(t);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(s.kind==="notdir")throw new Error(`ENOTDIR: not a directory, open '${t}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new Error(`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 Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(!i.metacopy)return js(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(!(a instanceof Error)||!a.message.startsWith("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 Error(`ENOENT: no such file or directory, open '${n}'`);try{let i=await bt(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${n}'`);let l=await me.promises.readlink(s),u=this.realTargetToVirtual(l),c=this.resolveSymlink(t,u);return this.readFileBuffer(c,r)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?me.constants.O_RDONLY:me.constants.O_RDONLY|me.constants.O_NOFOLLOW,a=await me.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 Error(`ENOENT: no such file or directory, open '${n}'`);if(o==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(t,n,r){K(t,"write"),this.assertWritable(`write '${t}'`);let s=z(t);this.ensureParentDirs(s);let i=jt(r),o=Dn(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 420;if(process.platform==="win32")return 420;try{let r=await this.stat(t);if(r.isFile)return r.mode}catch{}return 420}async appendFile(t,n,r){K(t,"append"),this.assertWritable(`append '${t}'`);let s=z(t),i=jt(r),o=Dn(n,i),a=this.tree.descend(s);if(a.kind==="found"&&a.node.type==="file"){let u=a.node;if(u.metacopy){let c=await this.readLowerFileBytes(s,t,new Set);this.tree.attach(s,{type:"file",content:c,appendChunks:[o],mode:u.mode,mtime:new Date});return}this.tree.appendChunk(u,o),u.mtime=new Date;return}if(a.kind==="blocked")throw new Error(`ENOENT: no such file or directory, append '${t}'`);if(a.kind==="notdir")throw new Error(`ENOTDIR: not a directory, append '${t}'`);let l;try{l=await this.readFileBuffer(s)}catch(u){if(!(u instanceof Error)||!u.message.startsWith("ENOENT"))throw u;l=new Uint8Array(0)}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[o],mode:await this.inheritedMode(s),mtime:new Date})}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,n=new Set){K(t,"stat");let r=z(t);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);if(s.kind==="notdir")throw new Error(`ENOTDIR: not a directory, stat '${t}'`);if(s.kind==="found"){let o=s.node;if(o.type==="whiteout")throw new Error(`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 Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await bt(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let a=await me.promises.readlink(i),l=this.realTargetToVirtual(a),u=this.resolveSymlink(r,l);return this.stat(u,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 Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){K(t,"lstat");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.kind==="notdir")throw new Error(`ENOTDIR: not a directory, lstat '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await bt(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 Error(`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:Hf(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 Rn(t,n)}realTargetToVirtual(t){let n=Vf(t,this.canonicalRoot);if(n.withinRoot){if(!Ie.isAbsolute(t))return t;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(t,n){K(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=z(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=Cn(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`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 Error(`ENOENT: no such file or directory, scandir '${t}'`);if(i.kind==="notdir")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let o;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(l.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);o=l;for(let[u,c]of l.children){if(c.type==="whiteout"){s.add(u);continue}r.set(u,{name:u,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await bt(a)).isSymbolicLink()){if(!o){let c=new Error(`ENOENT: no such file or directory, scandir '${t}'`);throw c.code="ENOENT",c}return r}let l=await me.promises.readdir(a,{withFileTypes:!0});for(let u of l)!s.has(u.name)&&!r.has(u.name)&&r.set(u.name,{name:u.name,isFile:u.isFile(),isDirectory:u.isDirectory(),isSymbolicLink:u.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!o)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,t,"scandir")}return r}async resolveForReaddir(t,n=!1){let r=z(t),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let u=l.node;if(u.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,u.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 bt(a)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await me.promises.readlink(a),c=this.realTargetToVirtual(u),f=this.resolveSymlink(r,c);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){K(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){K(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){K(t,"rm"),this.assertWritable(`rm '${t}'`);let r=z(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new Error(`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 Error(`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 pa(r),!0}catch{return!1}}async cp(t,n,r){K(t,"cp"),K(n,"cp"),this.assertWritable(`cp '${n}'`);let s=z(t),i=z(n);if(!await this.existsInOverlay(s))throw new Error(`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 Error(`EISDIR: is a directory, cp '${t}'`);if(_t(s,i))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let u of l){let c=s==="/"?`/${u}`:`${s}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(c,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 Nn(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=me.readdirSync(r);for(let i of s){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.lowerHidden(o))continue;n.add(o);let a=Ie.join(r,i);pa(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){K(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=z(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.entryAt(r);if(i){i.mode=n;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 Error(`EPERM: operation not permitted, symlink '${n}'`);K(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=z(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,n){K(t,"link"),K(n,"link"),this.assertWritable(`link '${n}'`);let r=z(t),s=z(n);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new Error(`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){K(t,"readlink");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.kind==="notdir")throw new Error(`ENOTDIR: not a directory, readlink '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await me.promises.readlink(s);if(!Ie.isAbsolute(i)){let o=Ie.resolve(Ie.dirname(s),i),a;try{a=me.realpathSync(o)}catch{a=o}if(!$r(a,this.canonicalRoot))return Ie.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){K(t,"realpath");let n=z(t),r=new Set,s=l=>{let u=this.tree.descend(l);if(u.kind==="blocked"||u.kind==="found"&&u.node.type==="whiteout")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return u.kind==="found"?u.node:void 0},i=async l=>{let u=l==="/"?[]:l.slice(1).split("/"),c="";for(let f of u){if(c=`${c}/${f}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);let d=s(c),p=0,h=40;for(;d&&d.type==="symlink"&&p<h;){if(r.add(c),c=this.resolveSymlink(c,d.target),p++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);d=s(c)}if(p>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!d){let m=this.toRealPath(c),E=this.resolveRealPath_(m);if(E)try{if((await bt(E)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let g=await me.promises.readlink(E),y=this.realTargetToVirtual(g);return r.add(c),c=this.resolveSymlink(c,y),i(c)}}catch(S){if(S.code==="ENOENT")throw new Error(`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 bt(S)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(g){if(g.message?.includes("ENOENT")||g.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(g,t,"realpath")}}}}return c||"/"},o=await i(n);if(!await this.existsInOverlay(o))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return o}async utimes(t,n,r){K(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=z(t);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let o=this.entryAt(s);if(o){o.mtime=r;return}let a=await this.stat(s);this.attachMetacopyShadow(s,a,a.mode,r)}};var xe={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"},ha=class{env;rl;running=!0;history=[];initialization;isInteractive;constructor(t={}){let n=process.cwd(),r=new Hs({root:n,mountPoint:"/"});this.env=new zs({fs:r,cwd:t.cwd||"/",env:{HOME:"/",USER:"user",SHELL:"/bin/bash",TERM:"xterm-256color",...t.env},network:t.network===!0?{dangerouslyAllowFullInternetAccess:!0}:void 0}),this.initialization=this.seedFiles(r,t.files),this.isInteractive=process.stdin.isTTY===!0,this.rl=Qf.createInterface({input:process.stdin,output:process.stdout,terminal:this.isInteractive}),this.rl.on("SIGINT",()=>{process.stdout.write(`^C
|
|
804
|
+
`;try{o.writeFileSync(`/bin/${t.name}`,l)}catch{}try{o.writeFileSync(`/usr/bin/${t.name}`,l)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=Qf(t.stdout),t.stderr=Qf(t.stderr),t}async exec(t,n){let r=new Wr(this.limits,n?.signal,this.abortOnUnresolvedCommands),s;try{s=await this.execInScope(t,n,r,0,n?.signal,!1,!1)}catch(a){try{await r.close()}catch{}throw a}let i=s;try{await r.close()}catch{i={...s,stderr:`${s.stderr}bash: execution cleanup failed
|
|
805
|
+
`,exitCode:126}}return i.unresolvedCommands=r.unresolvedCommandNames,t.trim()?this.logResult(i):i}async execInScope(t,n,r,s,i,a=!1,o=!0){let l=f=>o?this.logResult(f):f,u=Or(i,n?.signal),c=n?{...n,signal:u.signal}:{signal:u.signal};try{if(r.assertExecDepth(s),Qs(t,this.limits.maxSourceBytes),!t.trim())return{stdout:"",stderr:"",exitCode:0,env:qe(this.state.env,c.env)};this.logger?.info("exec",{command:t});let f=c.cwd??this.state.cwd,d,p=f;if(c.cwd)if(c.env&&"PWD"in c.env)d=c.env.PWD;else if(c.env&&!("PWD"in c.env))try{d=await this.fs.realpath(f),p=d}catch{d=f}else d=f;let h=c.replaceEnv?new Map:new Map(this.state.env);if(c.env)for(let[y,b]of Object.entries(c.env))h.set(y,b);d!==void 0&&h.set("PWD",d);let m={...this.state,env:h,arrays:c.replaceEnv?new Map:at(this.state.arrays),cwd:p,previousDir:c.env?.OLDPWD??this.state.previousDir,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:dy(c.stdin,c.stdinKind,this.limits.maxInputBytes,this.limits.maxStringLength,r,a),signal:c.signal,extraArgs:c.args},E=t;c.rawScript||(E=go(t));let S=this.defenseInDepthConfig?Ze.getInstance(this.defenseInDepthConfig):null,g=S?.activate();try{let y=async()=>{let b=ot(E,{maxHeredocSize:this.limits.maxHeredocSize}),A;if(this.transformPlugins.length>0){let x=Object.create(null);for(let C of this.transformPlugins){let I=C.transform({ast:b,metadata:x});b=I.ast,I.metadata&&(x=ni(x,I.metadata))}A=x}let k={fs:this.fs,commands:this.commands,limits:this.limits,executionScope:r,exec:(x,C,I=!1)=>this.execInScope(x,C,r,s+1,c.signal,I),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:S?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},D=await new xr(k,m).executeScript(b);return A&&(D.metadata=A),l(D)};return g?await g.run(y):await y()}catch(y){if(y instanceof q)return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,internalOutputAccounting:y.internalOutputAccounting,env:qe(this.state.env,c.env)});if(y instanceof Ce){if(s>0)throw y;return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,internalOutputAccounting:y.internalOutputAccounting,env:qe(this.state.env,c.env)})}if(y instanceof st)return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,env:qe(this.state.env,c.env)});if(y instanceof le)return l({stdout:y.stdout,stderr:y.stderr,exitCode:1,env:qe(this.state.env,c.env)});if(y instanceof Ye)return l({stdout:y.stdout,stderr:y.stderr,exitCode:124,env:qe(this.state.env,c.env)});if(y instanceof P)return l({stdout:y.stdout,stderr:vt(y.stderr),exitCode:P.EXIT_CODE,internalOutputAccounting:y.internalOutputAccounting,env:qe(this.state.env,c.env)});if(y instanceof Ir)return l({stdout:"",stderr:`bash: security violation: ${vt(y.message)}
|
|
806
|
+
`,exitCode:1,env:qe(this.state.env,c.env)});if(y.name==="ParseException")return l({stdout:"",stderr:`bash: syntax error: ${vt(y.message)}
|
|
807
|
+
`,exitCode:2,env:qe(this.state.env,c.env)});if(y instanceof Je)return l({stdout:"",stderr:`bash: ${vt(y.message)}
|
|
808
|
+
`,exitCode:2,env:qe(this.state.env,c.env)});if(y instanceof RangeError)return l({stdout:"",stderr:`bash: ${vt(y.message)}
|
|
809
|
+
`,exitCode:1,env:qe(this.state.env,c.env)});throw y}finally{g?.deactivate()}}catch(f){if(f instanceof Ye)return l({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:qe(this.state.env,c.env)});if(f instanceof P)return l({stdout:f.stdout,stderr:vt(f.stderr),exitCode:P.EXIT_CODE,internalOutputAccounting:f.internalOutputAccounting,env:qe(this.state.env,c.env)});throw f}finally{u.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 Ht(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){Qs(t,this.limits.maxSourceBytes);let n=go(t),r=ot(n,{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let i of this.transformPlugins){let a=i.transform({ast:r,metadata:s});r=a.ast,a.metadata&&(s=ni(s,a.metadata))}return{script:Ol(r),ast:r,metadata:s}}async analyzeCommands(t){Qs(t,this.limits.maxSourceBytes);let n=ot(go(t),{maxHeredocSize:this.limits.maxHeredocSize}),{commands:r,definedFunctions:s,definedAliases:i}=Ho(n),a=[];for(let o of r)s.has(o)||i.has(o)||await this.resolvesCommandForAnalysis(o)||a.push(o);return{commands:r,unresolved:a}}async resolvesCommandForAnalysis(t){if((sr.has(t)||xt.has(t))&&!Uo.has(t)||this.state.functions.has(t))return!0;let n=await Ur({fs:this.fs,state:{...this.state,hashTable:new Map},commands:this.commands},t);return n!==null&&!("error"in n)}};function cy(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 go(e){let t=e.split(`
|
|
810
|
+
`),n=[],r=[],s="none";for(let i=0;i<t.length;i++){let a=t[i];if(r.length>0){let c=r[r.length-1];if((c.stripTabs?a.replace(/^\t+/,""):a)===c.delimiter){n.push(a.trimStart()),r.pop();continue}n.push(a);continue}let o=s,l=o==="none"?a.trimStart():a;if(n.push(l),s=cy(a,o),o!=="none")continue;let u=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let c of l.matchAll(u)){let f=c[1]==="-",d=c[3];r.push({delimiter:d,stripTabs:f})}}return n.join(`
|
|
811
|
+
`)}var fy=new TextDecoder("utf-8",{fatal:!0});function Qf(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 fy.decode(n)}catch{return e}}function dy(e,t,n,r,s,i){if(e===void 0)return;let a=t==="bytes"?e.length:B(e);if(a>n||a>r)throw new P(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(a,"stdin"),t==="bytes"?e:mn(e)}import*as ye from"node:fs";import*as Oe from"node:path";import*as Ve from"node:fs";import*as $e from"node:path";function Nr(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?$e.win32:$e.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function Cr(e,t){try{let n=Ve.realpathSync(e);return Nr(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=$e.dirname(e);if(r===e)return null;let s=Cr(r,t);if(s===null)return null;try{if(Ve.lstatSync(e).isSymbolicLink()){let a=Ve.readlinkSync(e),o=$e.isAbsolute(a)?a:$e.resolve($e.dirname(e),a),l=Cr(o,t);return l===null?null:l}}catch{}return $e.join(s,$e.basename(e))}return null}}function Kf(e,t,n){let r=Cr(e,n);if(r===null)return null;let s=$e.resolve(e),i=s.slice(t.length),a=r.slice(n.length);if(i!==a)return null;try{if(Ve.lstatSync(s).isSymbolicLink())return null}catch{}return r}function Xf(e,t){if(!Ve.existsSync(e))throw new Error(`${t} root does not exist`);if(!Ve.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function Yf(e,t){if(!$e.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=Ve.realpathSync(e)}catch{n=$e.resolve(e)}return Nr(n,t)?{withinRoot:!0,relativePath:Ao(n.slice(t.length))||"/"}:{withinRoot:!1,safeName:$e.basename(e)}}function Jf(e,t,n,r){let s=e;if(s.path===void 0){for(let a of r)if(s.message?.includes(a))throw e}let i=s.code||"EIO";throw new N(i,`${n} '${t}'`)}async function At(e){return ed(await Ve.promises.lstat(e))}function wo(e){return ed(Ve.lstatSync(e))}function ed(e){return process.platform==="win32"&&e.isDirectory()&&(e.mode=e.mode&-512|493),e}function Xs(e){let t=e.content.byteLength;for(let n of e.appendChunks??[])t+=n.byteLength;return t}function rd(e){return Xs(e)}function Js(e,t){if(!e.appendChunks||e.appendChunks.length===0)return e.content;let n=e.appendChunks.reduce((i,a)=>i+a.byteLength,e.content.byteLength);if(!Number.isSafeInteger(n))throw new N("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 td(e){return!e||e.type!=="file"?0:Xs(e)}function Rr(){return{type:"directory",children:new Map,changedAt:Date.now(),mode:ht,mtime:new Date}}function Dr(e){return e.split("/").filter(Boolean)}var Ys=class e{maxMemoryBytes;rootNode=Rr();bytes=0;mutationSeq_=0;constructor(t){this.maxMemoryBytes=t}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(t){let n=Dr(t),r=[this.rootNode],s=this.rootNode;for(let i=0;i<n.length;i++){let a=s.children.get(n[i]);if(a===void 0)return{kind:"missing",stack:r,missingAt:i};if(i===n.length-1)return{kind:"found",stack:r,node:a};if(a.type==="whiteout")return{kind:"blocked",stack:r,blockedAt:i};if(a.type!=="directory")return{kind:"notdir",stack:r,notdirAt:i};r.push(a),s=a}return{kind:"found",stack:[],node:this.rootNode}}ensureDirs(t,n){let r=this.rootNode,s="";for(let i of Dr(t)){s=`${s}/${i}`;let a=r.children.get(i);if(a===void 0)a=Rr(),r.children.set(i,a);else if(a.type==="whiteout")a=this.resurrectDir(r,i,s,a.changedAt??0,n);else if(a.type!=="directory")throw new N("ENOTDIR",`not a directory, mkdir '${t}'`);r=a}return r}resurrectDir(t,n,r,s,i){let a=Rr();t.children.set(n,a);let o=i?.(r);if(o)for(let l of o)a.children.has(l)||a.children.set(l,{type:"whiteout",changedAt:s});return a}attach(t,n){n.changedAt=Date.now();let r=Dr(t);if(r.length===0)throw new N("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 N("EISDIR",`cannot replace directory with ${n.type}, attach '${t}'`);if(i!==void 0&&n.type==="directory")throw new N("EEXIST",`cannot replace ${i.type} with directory, attach '${t}'`);let a=td(i),o=td(n);this.assertCapacity(o,a),s.children.set(r[r.length-1],n),this.bytes+=o-a}detach(t){let n=Dr(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=Dr(t);if(n.length===0)throw new N("EINVAL",`cannot whiteout the root, rm '${t}'`);let r=this.rootNode;for(let a=0;a<n.length-1;a++)r=this.ensureChildDir(r,n[a],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,a]=r[s];t.push({path:nd(n.path,i),node:a})}}}}*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:nd(r.path,s),node:i})}for(let r=t.length-1;r>=0;r--)yield t[r]}clear(){this.rootNode=Rr(),this.bytes=0}static subtreeBytes(t){if(t===void 0)return 0;if(t.type==="file")return Xs(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+=Xs(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 N("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=Rr(),t.children.set(n,s);else if(s.type!=="directory")throw new N("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 N("ENOSPC",`overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function nd(e,t){return e==="/"?`/${t}`:`${e}/${t}`}var py=["ELOOP","EFBIG","EPERM"],hy="/home/user/project",ei=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;get rootDir(){return this.root}restamp(t,n,r="full"){let s=U(t),i=u=>{let c=this.tree.descend(u);c.kind==="found"&&(c.node.changedAt=n)},a=u=>{let c=this.tree.descend(u);if(c.kind==="found"){let f=c.node;(f.changedAt??0)>n&&(f.changedAt=n,f.mtime=new Date(n))}};r==="full"&&i(s);let o=s;for(;;){let u=o.lastIndexOf("/");if(u<=0)break;o=o.slice(0,u),a(o)}if(r==="ancestors")return;let l=[s];for(;l.length>0;){let u=l.pop(),c=this.tree.descend(u);if(!(c.kind!=="found"||c.node.type!=="directory"))for(let f of c.node.children.keys()){let d=`${u==="/"?"":u}/${f}`;a(d),l.push(d)}}}identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Oe.resolve(t.root);let n=t.mountPoint??hy;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,Xf(this.root,"OverlayFs"),this.canonicalRoot=ye.realpathSync(this.root),this.tree=new Ys(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new N("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:a}of this.tree.preOrder()){let o=this.getRelativeToMount(i);if(!(o===null||o==="/")){if(a.type==="whiteout"){this.existsOnRealFs(i)&&(n.push(o),r.push(a.changedAt??0));continue}if(a.type==="file")if(a.metacopy){if(!this.existsOnRealFs(i))continue;t.push({path:o,nodeType:"file",content:new Uint8Array(0),mode:a.mode,mtime:a.mtime,changedAt:a.changedAt??0,metadataOnly:!0})}else t.push({path:o,nodeType:"file",content:Js(a,i),mode:a.mode,mtime:a.mtime,changedAt:a.changedAt??0});else a.type==="directory"?t.push({path:o,nodeType:"directory",content:new Uint8Array(0),mode:a.mode,mtime:a.mtime,changedAt:a.changedAt??0}):t.push({path:o,nodeType:"symlink",content:new TextEncoder().encode(a.target),mode:a.mode,mtime:a.mtime,changedAt:a.changedAt??0})}}t.sort((i,a)=>i.path<a.path?-1:i.path>a.path?1:0);let s=n.map((i,a)=>({path:i,changedAt:r[a]}));return s.sort((i,a)=>i.path<a.path?-1:i.path>a.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=U(r);if(s==="/")throw new N("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 At(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 ye.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 At(r);if(!s.isFile())return!1;let i=Js(n,t);if(s.size!==i.byteLength)return!1;let a=this.allowSymlinks?ye.constants.O_RDONLY:ye.constants.O_RDONLY|ye.constants.O_NOFOLLOW,o=await ye.promises.open(r,a),l;try{l=new Uint8Array(await o.readFile())}finally{await o.close()}for(let u=0;u<l.byteLength;u++)if(l[u]!==i[u])return!1;return!0}catch{return!1}}mkdirSync(t,n){this.tree.ensureDirs(U(t),r=>this.lowerChildren(r))}writeFileSync(t,n){let r=U(t);this.ensureParentDirs(r);let s=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.tree.attach(r,{type:"file",content:s,mode:jt,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=U(t),r=this.getRelativeToMount(n);if(r===null)return null;let s=Oe.join(this.root,r),i=Oe.resolve(s);return Nr(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?Cr(t,this.canonicalRoot):Kf(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Oe.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Oe.join(r,Oe.basename(t))}sanitizeError(t,n,r){Jf(t,n,r,py)}ensureParentDirs(t){let n=Rn(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 ye.readdirSync(n)}catch{return null}}async existsInOverlay(t){let n=U(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 At(s),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=Zt(n);return _n(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return _n(n,"binary")}async readFileBuffer(t,n=new Set){X(t,"open");let r=U(t);if(n.has(r))throw new N("ELOOP",`too many levels of symbolic links, open '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new N("ENOENT",`no such file or directory, open '${t}'`);if(s.kind==="notdir")throw new N("ENOTDIR",`not a directory, open '${t}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new N("ENOENT",`no such file or directory, open '${t}'`);if(i.type==="symlink"){let o=this.resolveSymlink(r,i.target);return this.readFileBuffer(o,n)}if(i.type!=="file")throw new N("EISDIR",`illegal operation on a directory, read '${t}'`);if(!i.metacopy)return Js(i,t);let a=await this.readLowerFileBytes(r,t,n);if(process.platform==="win32")try{this.tree.attach(r,{type:"file",content:a,mode:i.mode,mtime:i.mtime})}catch(o){if(!yn(o,"ENOSPC"))throw o}return a}return this.readLowerFileBytes(r,t,n)}async readLowerFileBytes(t,n,r){let s=this.resolveRealPath_(this.toRealPath(t));if(!s)throw new N("ENOENT",`no such file or directory, open '${n}'`);try{let i=await At(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new N("ENOENT",`no such file or directory, open '${n}'`);let l=await ye.promises.readlink(s),u=this.realTargetToVirtual(l),c=this.resolveSymlink(t,u);return this.readFileBuffer(c,r)}if(i.isDirectory())throw new N("EISDIR",`illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new N("EFBIG",`file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let a=this.allowSymlinks?ye.constants.O_RDONLY:ye.constants.O_RDONLY|ye.constants.O_NOFOLLOW,o=await ye.promises.open(s,a);try{let l=await o.readFile();return new Uint8Array(l)}finally{await o.close()}}catch(i){let a=i.code;if(a==="ENOENT")throw new N("ENOENT",`no such file or directory, open '${n}'`);if(a==="ELOOP")throw new N("ENOENT",`no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(t,n,r){X(t,"write"),this.assertWritable(`write '${t}'`);let s=U(t);this.ensureParentDirs(s);let i=Zt(r),a=On(n,i);this.tree.attach(s,{type:"file",content:a,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 jt;if(process.platform==="win32")return jt;try{let r=await this.stat(t);if(r.isFile)return r.mode}catch{}return jt}async appendFile(t,n,r){X(t,"append"),this.assertWritable(`append '${t}'`);let s=U(t),i=Zt(r),a=On(n,i),o=this.tree.descend(s);if(o.kind==="found"&&o.node.type==="file"){await this.appendToExisting_(s,o.node,a,t);return}if(o.kind==="blocked")throw new N("ENOENT",`no such file or directory, append '${t}'`);if(o.kind==="notdir")throw new N("ENOTDIR",`not a directory, append '${t}'`);let l;try{l=await this.readFileBuffer(s)}catch(f){if(!yn(f,"ENOENT"))throw f;l=new Uint8Array(0)}let u=await this.inheritedMode(s),c=this.tree.descend(s);if(c.kind==="found"&&c.node.type==="file"){await this.appendToExisting_(s,c.node,a,t);return}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[a],mode:u,mtime:new Date})}async appendToExisting_(t,n,r,s){if(n.metacopy){let i=await this.readLowerFileBytes(t,s,new Set),a=this.tree.descend(t);if(a.kind==="found"&&a.node.type==="file"&&!a.node.metacopy){this.tree.appendChunk(a.node,r),a.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){X(t,"stat");let r=U(t);if(n.has(r))throw new N("ELOOP",`too many levels of symbolic links, stat '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new N("ENOENT",`no such file or directory, stat '${t}'`);if(s.kind==="notdir")throw new N("ENOTDIR",`not a directory, stat '${t}'`);if(s.kind==="found"){let a=s.node;if(a.type==="whiteout")throw new N("ENOENT",`no such file or directory, stat '${t}'`);if(a.type==="symlink"){let o=this.resolveSymlink(r,a.target);return this.stat(o,n)}return this.memoryEntryStat(a)}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new N("ENOENT",`no such file or directory, stat '${t}'`);try{let a=await At(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new N("ENOENT",`no such file or directory, stat '${t}'`);let o=await ye.promises.readlink(i),l=this.realTargetToVirtual(o),u=this.resolveSymlink(r,l);return this.stat(u,n)}return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime,dev:a.dev,ino:a.ino}}catch(a){if(a.code==="ENOENT")throw new N("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(a,t,"stat")}}async lstat(t){X(t,"lstat");let n=U(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new N("ENOENT",`no such file or directory, lstat '${t}'`);if(r.kind==="notdir")throw new N("ENOTDIR",`not a directory, lstat '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new N("ENOENT",`no such file or directory, lstat '${t}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new N("ENOENT",`no such file or directory, lstat '${t}'`);try{let i=await At(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 N("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:rd(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 In(t,n)}realTargetToVirtual(t){let n=Yf(t,this.canonicalRoot);if(n.withinRoot){if(!Oe.isAbsolute(t))return t;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(t,n){X(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=U(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new N("EEXIST",`file already exists, mkdir '${t}'`);return}let i=Rn(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new N("ENOENT",`no such file or directory, mkdir '${t}'`);this.tree.ensureDirs(r,a=>this.lowerChildren(a))}async readdirCore(t,n){let r=new Map,s=new Set,i=this.tree.descend(n);if(i.kind==="blocked")throw new N("ENOENT",`no such file or directory, scandir '${t}'`);if(i.kind==="notdir")throw new N("ENOTDIR",`not a directory, scandir '${t}'`);let a;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new N("ENOENT",`no such file or directory, scandir '${t}'`);if(l.type!=="directory")throw new N("ENOTDIR",`not a directory, scandir '${t}'`);a=l;for(let[u,c]of l.children){if(c.type==="whiteout"){s.add(u);continue}r.set(u,{name:u,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}}let o=this.resolveRealPath_(this.toRealPath(n));if(o)try{if(!this.allowSymlinks&&(await At(o)).isSymbolicLink()){if(!a)throw new N("ENOENT",`no such file or directory, scandir '${t}'`);return r}let l=await ye.promises.readdir(o,{withFileTypes:!0});for(let u of l)!s.has(u.name)&&!r.has(u.name)&&r.set(u.name,{name:u.name,isFile:u.isFile(),isDirectory:u.isDirectory(),isSymbolicLink:u.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!a)throw new N("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=U(t),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let u=l.node;if(u.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new N("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,u.target)}if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let o=this.resolveRealPath_(this.toRealPath(r));if(!o)return{normalized:r,outsideOverlay:!0};try{if((await At(o)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await ye.promises.readlink(o),c=this.realTargetToVirtual(u),f=this.resolveSymlink(r,c);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){X(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){X(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,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,n){X(t,"rm"),this.assertWritable(`rm '${t}'`);let r=U(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new N("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 N("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 wo(r),!0}catch{return!1}}async cp(t,n,r){X(t,"cp"),X(n,"cp"),this.assertWritable(`cp '${n}'`);let s=U(t),i=U(n);if(!await this.existsInOverlay(s))throw new N("ENOENT",`no such file or directory, cp '${t}'`);let o=await this.stat(s);if(o.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(o.isDirectory){if(!r?.recursive)throw new N("EISDIR",`is a directory, cp '${t}'`);if(Tt(s,i))throw new N("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let u of l){let c=s==="/"?`/${u}`:`${s}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(c,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 Dn(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=ye.readdirSync(r);for(let i of s){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.lowerHidden(a))continue;n.add(a);let o=Oe.join(r,i);wo(o).isDirectory()&&this.scanRealFs(a,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){X(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=U(t);if(!await this.existsInOverlay(r))throw new N("ENOENT",`no such file or directory, chmod '${t}'`);let i=this.entryAt(r);if(i){i.mode=n,this.tree.touch(i);return}let a=await this.stat(r);this.attachMetacopyShadow(r,a,n,a.isFile?a.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 N("EPERM",`operation not permitted, symlink '${n}'`);X(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=U(n);if(await this.existsInOverlay(r))throw new N("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:t,mode:Mr,mtime:new Date})}async link(t,n){X(t,"link"),X(n,"link"),this.assertWritable(`link '${n}'`);let r=U(t),s=U(n);if(!await this.existsInOverlay(r))throw new N("ENOENT",`no such file or directory, link '${t}'`);let a=await this.stat(r);if(!a.isFile)throw new N("EPERM",`operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new N("EEXIST",`file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,mode:a.mode,mtime:new Date,identity:a.identity??`overlay:${this.nextMemoryIdentity++}`})}async readlink(t){X(t,"readlink");let n=U(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new N("ENOENT",`no such file or directory, readlink '${t}'`);if(r.kind==="notdir")throw new N("ENOTDIR",`not a directory, readlink '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new N("ENOENT",`no such file or directory, readlink '${t}'`);if(i.type!=="symlink")throw new N("EINVAL",`invalid argument, readlink '${t}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new N("ENOENT",`no such file or directory, readlink '${t}'`);try{let i=await ye.promises.readlink(s);if(!Oe.isAbsolute(i)){let a=Oe.resolve(Oe.dirname(s),i),o;try{o=ye.realpathSync(a)}catch{o=a}if(!Nr(o,this.canonicalRoot))return Oe.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new N("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new N("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){X(t,"realpath");let n=U(t),r=new Set,s=l=>{let u=this.tree.descend(l);if(u.kind==="blocked"||u.kind==="found"&&u.node.type==="whiteout")throw new N("ENOENT",`no such file or directory, realpath '${t}'`);return u.kind==="found"?u.node:void 0},i=async l=>{let u=l==="/"?[]:l.slice(1).split("/"),c="";for(let f of u){if(c=`${c}/${f}`,r.has(c))throw new N("ELOOP",`too many levels of symbolic links, realpath '${t}'`);let d=s(c),p=0,h=er;for(;d&&d.type==="symlink"&&p<h;){if(r.add(c),c=this.resolveSymlink(c,d.target),p++,r.has(c))throw new N("ELOOP",`too many levels of symbolic links, realpath '${t}'`);d=s(c)}if(p>=h)throw new N("ELOOP",`too many levels of symbolic links, realpath '${t}'`);if(!d){let m=this.toRealPath(c),E=this.resolveRealPath_(m);if(E)try{if((await At(E)).isSymbolicLink()){if(!this.allowSymlinks)throw new N("ENOENT",`no such file or directory, realpath '${t}'`);let g=await ye.promises.readlink(E),y=this.realTargetToVirtual(g);return r.add(c),c=this.resolveSymlink(c,y),i(c)}}catch(S){if(S.code==="ENOENT")throw new N("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 At(S)).isSymbolicLink())throw new N("ENOENT",`no such file or directory, realpath '${t}'`)}catch(g){if(yn(g,"ENOENT")||yn(g,"ELOOP"))throw new N("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(g,t,"realpath")}}}}return c||"/"},a=await i(n);if(!await this.existsInOverlay(a))throw new N("ENOENT",`no such file or directory, realpath '${t}'`);return a}async utimes(t,n,r){X(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=U(t);if(!await this.existsInOverlay(s))throw new N("ENOENT",`no such file or directory, utimes '${t}'`);let a=this.entryAt(s);if(a){a.mtime=r,this.tree.touch(a);return}let o=await this.stat(s);this.attachMetacopyShadow(s,o,o.mode,r)}};var Pe={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"},Eo=class{env;rl;running=!0;history=[];initialization;isInteractive;constructor(t={}){let n=process.cwd(),r=new ei({root:n,mountPoint:"/"});this.env=new Ks({fs:r,cwd:t.cwd||"/",env:{HOME:"/",USER:"user",SHELL:"/bin/bash",TERM:"xterm-256color",...t.env},network:t.network===!0?{dangerouslyAllowFullInternetAccess:!0}:void 0}),this.initialization=this.seedFiles(r,t.files),this.isInteractive=process.stdin.isTTY===!0,this.rl=ad.createInterface({input:process.stdin,output:process.stdout,terminal:this.isInteractive}),this.rl.on("SIGINT",()=>{process.stdout.write(`^C
|
|
807
812
|
`),this.prompt()}),process.stdin.isTTY&&this.rl.on("close",()=>{this.running=!1,console.log(`
|
|
808
|
-
Goodbye!`),process.exit(0)})}async seedFiles(t,n){if(n)for(let[r,s]of Object.entries(n)){if(typeof s!="string")throw new TypeError(`Invalid --files content for ${r}`);let i=t.resolvePath("/",r);await t.mkdir(
|
|
809
|
-
${
|
|
813
|
+
Goodbye!`),process.exit(0)})}async seedFiles(t,n){if(n)for(let[r,s]of Object.entries(n)){if(typeof s!="string")throw new TypeError(`Invalid --files content for ${r}`);let i=t.resolvePath("/",r);await t.mkdir(id.posix.dirname(i),{recursive:!0}),await t.writeFile(i,s)}}syncHistory(){let t=this.env.getEnv();t.BASH_HISTORY=JSON.stringify(this.history)}getPrompt(){let t=this.env.getCwd(),n=this.env.getEnv().HOME||"/home/user",r=t;return t===n?r="~":t.startsWith(`${n}/`)&&(r=`~${t.slice(n.length)}`),`${Pe.green}${Pe.bold}user@virtual${Pe.reset}:${Pe.blue}${Pe.bold}${r}${Pe.reset}$ `}async executeCommand(t){let n=t.trim();if(n){if(this.history.push(n),n==="exit"||n.startsWith("exit ")){let r=n.split(/\s+/),s=r[1]?parseInt(r[1],10):0;console.log("exit"),process.exit(s)}this.syncHistory();try{let r=await this.env.exec(n);r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(`${Pe.red}${r.stderr}${Pe.reset}`)}catch(r){console.error(`${Pe.red}Error: ${it(r)}${Pe.reset}`)}}}printWelcome(){console.log(`
|
|
814
|
+
${Pe.cyan}${Pe.bold}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
810
815
|
\u2551 Virtual Shell v1.0 \u2551
|
|
811
816
|
\u2551 A simulated bash environment in TypeScript \u2551
|
|
812
|
-
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${
|
|
817
|
+
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${Pe.reset}
|
|
813
818
|
|
|
814
|
-
${
|
|
819
|
+
${Pe.dim}Exploring: ${process.cwd()}${Pe.reset}
|
|
815
820
|
|
|
816
|
-
Type ${
|
|
821
|
+
Type ${Pe.green}help${Pe.reset} for available commands, ${Pe.green}exit${Pe.reset} to quit.
|
|
817
822
|
Reads from real filesystem, writes stay in memory (OverlayFs).
|
|
818
|
-
`)}prompt(){this.rl.question(this.getPrompt(),async t=>{this.running&&(await this.executeCommand(t),this.prompt())})}async run(){if(await this.initialization,this.isInteractive)this.printWelcome(),this.prompt();else{let t=[];this.rl.on("line",n=>{t.push(n)}),await new Promise(n=>{this.rl.on("close",n)});for(let n of t)await this.executeCommand(n)}}};function
|
|
823
|
+
`)}prompt(){this.rl.question(this.getPrompt(),async t=>{this.running&&(await this.executeCommand(t),this.prompt())})}async run(){if(await this.initialization,this.isInteractive)this.printWelcome(),this.prompt();else{let t=[];this.rl.on("line",n=>{t.push(n)}),await new Promise(n=>{this.rl.on("close",n)});for(let n of t)await this.executeCommand(n)}}};function my(){let e=process.argv.slice(2),t={};for(let n=0;n<e.length;n++)if(e[n]==="--cwd"&&e[n+1])t.cwd=e[++n];else if(e[n]==="--files"&&e[n+1]){let r=e[++n];try{let s=sd.readFileSync(r,"utf-8");t.files=JSON.parse(s)}catch(s){console.error(`Error reading files from ${r}:`,s),process.exit(1)}}else e[n]==="--network"?t.network=!0:e[n]==="--no-network"?t.network=!1:(e[n]==="--help"||e[n]==="-h")&&(console.log(`
|
|
819
824
|
Usage: pnpm shell [options]
|
|
820
825
|
|
|
821
826
|
Interactive shell using OverlayFs - reads from the current directory,
|
|
@@ -831,4 +836,4 @@ Options:
|
|
|
831
836
|
Example:
|
|
832
837
|
pnpm shell
|
|
833
838
|
pnpm shell --network
|
|
834
|
-
`),process.exit(0));return t}var
|
|
839
|
+
`),process.exit(0));return t}var yy=my(),gy=new Eo(yy);gy.run().catch(e=>{console.error(`Error initializing virtual shell: ${it(e)}`),process.exitCode=1});
|