@jerryan/just-bash 3.9.0 → 3.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (446) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +2 -2
  3. package/dist/AGENTS.md +2 -2
  4. package/dist/abort-signals.d.ts +10 -0
  5. package/dist/bin/chunks/awk2-LCV2AUIX.js +3 -0
  6. package/dist/bin/{shell/chunks/base64-TQ5KOCNW.js → chunks/base64-OLYCF2PC.js} +1 -1
  7. package/dist/bin/chunks/builtin-manifest-ORBIZM7I.js +3 -0
  8. package/dist/bin/chunks/{cat-BQ7FQTN5.js → cat-UJLF2DU2.js} +1 -1
  9. package/dist/bin/{shell/chunks/chmod-GX5SYTRL.js → chunks/chmod-V5F4BXZ2.js} +1 -1
  10. package/dist/bin/{shell/chunks/chunk-V4S4A7M6.js → chunks/chunk-2TEF4USR.js} +1 -1
  11. package/dist/bin/{shell/chunks/chunk-GBKR5KTT.js → chunks/chunk-3ASHUC7C.js} +13 -13
  12. package/dist/bin/chunks/{chunk-N26Y42L6.js → chunk-3M5OMKFS.js} +1 -1
  13. package/dist/bin/chunks/chunk-4NYJ4ZTO.js +17 -0
  14. package/dist/bin/chunks/{chunk-M3Z5NZXT.js → chunk-572NXISH.js} +1 -1
  15. package/dist/bin/chunks/chunk-5NWK7A4R.js +13 -0
  16. package/dist/bin/{shell/chunks/chunk-YXPSX3SI.js → chunks/chunk-623Q77WZ.js} +1 -1
  17. package/dist/bin/chunks/chunk-6NG4ULJM.js +7 -0
  18. package/dist/bin/{shell/chunks/chunk-QFOXSCOD.js → chunks/chunk-726WDFMQ.js} +1 -1
  19. package/dist/bin/chunks/{chunk-DRPHNXG7.js → chunk-7LGT4LHQ.js} +1 -1
  20. package/dist/bin/chunks/{chunk-MBREBDZQ.js → chunk-AIWBN36Z.js} +1 -1
  21. package/dist/bin/chunks/{chunk-3ROYEBJI.js → chunk-AJ3CSZ34.js} +1 -1
  22. package/dist/bin/{shell/chunks/chunk-VTAMGD42.js → chunks/chunk-APEQNYAO.js} +1 -1
  23. package/dist/bin/chunks/chunk-AQKIHX3Q.js +3 -0
  24. package/dist/bin/chunks/chunk-BFLKIASG.js +7 -0
  25. package/dist/bin/chunks/{chunk-IOKQFPM6.js → chunk-BRB5PJ3E.js} +1 -1
  26. package/dist/bin/chunks/{chunk-ZVG47PYA.js → chunk-BVBYPYA5.js} +1 -1
  27. package/dist/bin/chunks/{chunk-T6OIISUC.js → chunk-BZJ77YQD.js} +1 -1
  28. package/dist/bin/{shell/chunks/chunk-GR4ZHKXI.js → chunks/chunk-C2BLJ3AE.js} +1 -1
  29. package/dist/bin/{shell/chunks/chunk-KMYJMEON.js → chunks/chunk-C45GTJTD.js} +1 -1
  30. package/dist/bin/chunks/{chunk-GOWX7VPU.js → chunk-CTS7QXCJ.js} +1 -1
  31. package/dist/bin/chunks/{chunk-42AMF6EE.js → chunk-DTNGYQCJ.js} +1 -1
  32. package/dist/bin/chunks/{chunk-TW2IJRUF.js → chunk-ENEHPI32.js} +1 -1
  33. package/dist/bin/{shell/chunks/chunk-E54Z6VIE.js → chunks/chunk-ERYPQAZE.js} +5 -5
  34. package/dist/bin/chunks/{chunk-PQ2INDRF.js → chunk-GB3KUAFV.js} +1 -1
  35. package/dist/bin/chunks/chunk-HFVQCXYX.js +10 -0
  36. package/dist/bin/chunks/chunk-HSWCKN2X.js +14 -0
  37. package/dist/bin/chunks/{chunk-B6WWC6K3.js → chunk-I6MS5ZWE.js} +1 -1
  38. package/dist/bin/chunks/{chunk-V4U26ZWL.js → chunk-IOFXLMNJ.js} +1 -1
  39. package/dist/bin/chunks/chunk-IX6QY5JW.js +5 -0
  40. package/dist/bin/chunks/{chunk-QKJAAJ7J.js → chunk-IXTPVJ6W.js} +1 -1
  41. package/dist/bin/chunks/{chunk-OUQKFRVR.js → chunk-JBYLHCKP.js} +1 -1
  42. package/dist/bin/chunks/{chunk-NXUXZWS5.js → chunk-JLRB7DV3.js} +1 -1
  43. package/dist/bin/chunks/{chunk-6JEDM6CZ.js → chunk-KH6YLKPE.js} +1 -1
  44. package/dist/bin/chunks/chunk-KXSDVBJA.js +12 -0
  45. package/dist/bin/chunks/{chunk-DYIBFLS3.js → chunk-LOU52GPJ.js} +2 -2
  46. package/dist/bin/chunks/{chunk-L345YZ6R.js → chunk-LVT5R45K.js} +1 -1
  47. package/dist/bin/chunks/{chunk-PTUQEN6I.js → chunk-M345X45Z.js} +7 -7
  48. package/dist/bin/chunks/{chunk-6FGMEZZP.js → chunk-NDS7PYKD.js} +1 -1
  49. package/dist/bin/chunks/chunk-O3PNT72D.js +3 -0
  50. package/dist/bin/chunks/chunk-OGOISDGZ.js +3 -0
  51. package/dist/bin/chunks/chunk-OSW4MDDH.js +21 -0
  52. package/dist/bin/{shell/chunks/chunk-ABP4OLJV.js → chunks/chunk-OXEDIWNZ.js} +1 -1
  53. package/dist/bin/chunks/{chunk-FPWHWWXO.js → chunk-OXV2B2YS.js} +1 -1
  54. package/dist/bin/chunks/{chunk-QMPZXXEK.js → chunk-OY25E3ZN.js} +1 -1
  55. package/dist/bin/chunks/{chunk-O2BCKSMK.js → chunk-PEJXCXSY.js} +1 -1
  56. package/dist/bin/{shell/chunks/chunk-6KHZX4HU.js → chunks/chunk-PLLMJHMV.js} +1 -1
  57. package/dist/bin/{shell/chunks/chunk-6TUILMPB.js → chunks/chunk-QELDDRV5.js} +1 -1
  58. package/dist/bin/chunks/{chunk-3FQBUEB6.js → chunk-RC4UXNHA.js} +1 -1
  59. package/dist/bin/{shell/chunks/chunk-H7PD6FLC.js → chunks/chunk-RE7Z53A3.js} +1 -1
  60. package/dist/bin/chunks/chunk-SCQRBEQW.js +275 -0
  61. package/dist/bin/chunks/{chunk-3DWQCLNP.js → chunk-SS2OPV62.js} +1 -1
  62. package/dist/bin/{shell/chunks/chunk-CC2AQ6B7.js → chunks/chunk-U6JTVQU6.js} +1 -1
  63. package/dist/bin/chunks/chunk-UBA7DOWE.js +3 -0
  64. package/dist/bin/chunks/{chunk-VPSBWWXM.js → chunk-UFAYH3WW.js} +7 -6
  65. package/dist/bin/chunks/chunk-UPUFWGHR.js +3 -0
  66. package/dist/bin/{shell/chunks/chunk-QJWFCA7P.js → chunks/chunk-UU42WPB7.js} +1 -1
  67. package/dist/bin/chunks/{chunk-CNVNOT67.js → chunk-UW4E5XU5.js} +1 -1
  68. package/dist/bin/chunks/chunk-VMVXACZ5.js +6 -0
  69. package/dist/bin/chunks/chunk-WLQ2KWS3.js +10 -0
  70. package/dist/bin/chunks/{chunk-MVBK66TR.js → chunk-WPJ5CECR.js} +1 -1
  71. package/dist/bin/chunks/{chunk-ANX7U57Q.js → chunk-XBOBVLRL.js} +2 -2
  72. package/dist/bin/chunks/{chunk-HZGHQZSY.js → chunk-Z3MXFCN7.js} +1 -1
  73. package/dist/bin/chunks/{column-AJFK3TWF.js → column-AL4LR5PO.js} +1 -1
  74. package/dist/bin/chunks/{cp-YLP7ULVT.js → cp-XJWV46T5.js} +1 -1
  75. package/dist/bin/{shell/chunks/curl-NHNZ46BU.js → chunks/curl-HZ5SBTVY.js} +11 -11
  76. package/dist/bin/chunks/{cut-42X6363P.js → cut-LNJEMWBJ.js} +1 -1
  77. package/dist/bin/{shell/chunks/diff-DM47S5PT.js → chunks/diff-YLVT27CZ.js} +1 -1
  78. package/dist/bin/chunks/dist-4NZ74CRE.js +141 -0
  79. package/dist/bin/chunks/{du-DH76GZJ3.js → du-YNAJTGCR.js} +1 -1
  80. package/dist/bin/chunks/{expr-PQEPO5TE.js → expr-GLGO2VEZ.js} +1 -1
  81. package/dist/bin/chunks/{file-JA7QI2YT.js → file-7M5LLZJY.js} +1 -1
  82. package/dist/bin/chunks/find-3QDGII35.js +3 -0
  83. package/dist/bin/chunks/flag-coverage-AGEO3F6X.js +3 -0
  84. package/dist/bin/chunks/{grep-VXWNMIDD.js → grep-AZJ2CMYE.js} +1 -1
  85. package/dist/bin/chunks/{gzip-UQZL4R74.js → gzip-W5CL2E2W.js} +1 -1
  86. package/dist/bin/{shell/chunks/head-QKVY3SIO.js → chunks/head-ABLEKDMV.js} +1 -1
  87. package/dist/bin/{shell/chunks/help-HVIDHJ6M.js → chunks/help-EXVKU23F.js} +1 -1
  88. package/dist/bin/chunks/{html-to-markdown-XUMA42ZC.js → html-to-markdown-FDNPIEKZ.js} +1 -1
  89. package/dist/bin/{shell/chunks/jq-YS4PR46D.js → chunks/jq-5SOTL7D7.js} +1 -1
  90. package/dist/bin/chunks/{js-exec-ZAAIZQWI.js → js-exec-LISDW7YC.js} +2 -2
  91. package/dist/bin/chunks/js-exec-worker.js +1 -0
  92. package/dist/bin/chunks/{ls-5Z45FV4U.js → ls-EEX3YIOF.js} +1 -1
  93. package/dist/bin/chunks/mkdir-KDEZTR53.js +3 -0
  94. package/dist/bin/chunks/mktemp-OYQYUB5H.js +3 -0
  95. package/dist/bin/{shell/chunks/mv-EOOP2TO3.js → chunks/mv-35V6IA5V.js} +1 -1
  96. package/dist/bin/{shell/chunks/od-2GXD4D5K.js → chunks/od-TD5LZDUM.js} +1 -1
  97. package/dist/bin/{shell/chunks/paste-DWWA3JTW.js → chunks/paste-QJG6BYAP.js} +1 -1
  98. package/dist/bin/chunks/{python3-TJ6DCPIA.js → python3-P6MZ44HK.js} +5 -5
  99. package/dist/bin/{shell/chunks/readlink-EJ3IKLWW.js → chunks/readlink-BF435HNQ.js} +1 -1
  100. package/dist/bin/chunks/rg-B2DVJQVY.js +3 -0
  101. package/dist/bin/chunks/rm-HCMKNRM2.js +3 -0
  102. package/dist/bin/{shell/chunks/rmdir-PRNISPBA.js → chunks/rmdir-WGVUYGPF.js} +1 -1
  103. package/dist/bin/{shell/chunks/sed-SY63U2YX.js → chunks/sed-66XZQ75T.js} +1 -1
  104. package/dist/bin/chunks/{seq-X2EAOGV5.js → seq-KBVCQ4WT.js} +1 -1
  105. package/dist/bin/chunks/{sleep-MOJQBZMY.js → sleep-4O22Z4DI.js} +1 -1
  106. package/dist/bin/{shell/chunks/split-HIFKSV2A.js → chunks/split-OK6JHDWZ.js} +1 -1
  107. package/dist/bin/chunks/sqlite3-57ACN7ES.js +3 -0
  108. package/dist/bin/chunks/{stat-LROLDXHH.js → stat-VNNI7JDZ.js} +1 -1
  109. package/dist/bin/chunks/{tail-UOTUV25D.js → tail-PAHZX3MA.js} +1 -1
  110. package/dist/bin/chunks/{tar-7XOP7VOX.js → tar-RPVTXGFJ.js} +1 -1
  111. package/dist/bin/chunks/{time-LF7BTSK5.js → time-J2DAZUIN.js} +1 -1
  112. package/dist/bin/chunks/timeout-XMTXHNFF.js +3 -0
  113. package/dist/bin/{shell/chunks/tr-PVFO6FRY.js → chunks/tr-ETPC3LHV.js} +1 -1
  114. package/dist/bin/chunks/{which-4TPGVSBZ.js → which-G7X54RZL.js} +1 -1
  115. package/dist/bin/chunks/worker.js +5 -0
  116. package/dist/bin/chunks/{xan-RMH6JEXM.js → xan-XZHKEPJ4.js} +1 -1
  117. package/dist/bin/chunks/{xan-view-PD26QEFN.js → xan-view-CNGKCABE.js} +1 -1
  118. package/dist/bin/chunks/yes-2EQTNSIB.js +3 -0
  119. package/dist/bin/chunks/yq-T6S3IDKY.js +3 -0
  120. package/dist/bin/just-bash.js +299 -293
  121. package/dist/bin/shell/chunks/awk2-LCV2AUIX.js +3 -0
  122. package/dist/bin/{chunks/base64-TQ5KOCNW.js → shell/chunks/base64-OLYCF2PC.js} +1 -1
  123. package/dist/bin/shell/chunks/builtin-manifest-ORBIZM7I.js +3 -0
  124. package/dist/bin/shell/chunks/{cat-BQ7FQTN5.js → cat-UJLF2DU2.js} +1 -1
  125. package/dist/bin/{chunks/chmod-GX5SYTRL.js → shell/chunks/chmod-V5F4BXZ2.js} +1 -1
  126. package/dist/bin/{chunks/chunk-V4S4A7M6.js → shell/chunks/chunk-2TEF4USR.js} +1 -1
  127. package/dist/bin/{chunks/chunk-GBKR5KTT.js → shell/chunks/chunk-3ASHUC7C.js} +13 -13
  128. package/dist/bin/shell/chunks/{chunk-N26Y42L6.js → chunk-3M5OMKFS.js} +1 -1
  129. package/dist/bin/shell/chunks/chunk-4NYJ4ZTO.js +17 -0
  130. package/dist/bin/shell/chunks/{chunk-M3Z5NZXT.js → chunk-572NXISH.js} +1 -1
  131. package/dist/bin/shell/chunks/chunk-5NWK7A4R.js +13 -0
  132. package/dist/bin/{chunks/chunk-YXPSX3SI.js → shell/chunks/chunk-623Q77WZ.js} +1 -1
  133. package/dist/bin/shell/chunks/chunk-6NG4ULJM.js +7 -0
  134. package/dist/bin/{chunks/chunk-QFOXSCOD.js → shell/chunks/chunk-726WDFMQ.js} +1 -1
  135. package/dist/bin/shell/chunks/{chunk-DRPHNXG7.js → chunk-7LGT4LHQ.js} +1 -1
  136. package/dist/bin/shell/chunks/{chunk-MBREBDZQ.js → chunk-AIWBN36Z.js} +1 -1
  137. package/dist/bin/shell/chunks/{chunk-3ROYEBJI.js → chunk-AJ3CSZ34.js} +1 -1
  138. package/dist/bin/{chunks/chunk-VTAMGD42.js → shell/chunks/chunk-APEQNYAO.js} +1 -1
  139. package/dist/bin/shell/chunks/chunk-AQKIHX3Q.js +3 -0
  140. package/dist/bin/shell/chunks/chunk-BFLKIASG.js +7 -0
  141. package/dist/bin/shell/chunks/{chunk-IOKQFPM6.js → chunk-BRB5PJ3E.js} +1 -1
  142. package/dist/bin/shell/chunks/{chunk-ZVG47PYA.js → chunk-BVBYPYA5.js} +1 -1
  143. package/dist/bin/shell/chunks/{chunk-T6OIISUC.js → chunk-BZJ77YQD.js} +1 -1
  144. package/dist/bin/{chunks/chunk-GR4ZHKXI.js → shell/chunks/chunk-C2BLJ3AE.js} +1 -1
  145. package/dist/bin/{chunks/chunk-KMYJMEON.js → shell/chunks/chunk-C45GTJTD.js} +1 -1
  146. package/dist/bin/shell/chunks/{chunk-GOWX7VPU.js → chunk-CTS7QXCJ.js} +1 -1
  147. package/dist/bin/shell/chunks/{chunk-42AMF6EE.js → chunk-DTNGYQCJ.js} +1 -1
  148. package/dist/bin/shell/chunks/{chunk-TW2IJRUF.js → chunk-ENEHPI32.js} +1 -1
  149. package/dist/bin/{chunks/chunk-E54Z6VIE.js → shell/chunks/chunk-ERYPQAZE.js} +5 -5
  150. package/dist/bin/shell/chunks/{chunk-PQ2INDRF.js → chunk-GB3KUAFV.js} +1 -1
  151. package/dist/bin/shell/chunks/chunk-HFVQCXYX.js +10 -0
  152. package/dist/bin/shell/chunks/chunk-HSWCKN2X.js +14 -0
  153. package/dist/bin/shell/chunks/{chunk-B6WWC6K3.js → chunk-I6MS5ZWE.js} +1 -1
  154. package/dist/bin/shell/chunks/{chunk-V4U26ZWL.js → chunk-IOFXLMNJ.js} +1 -1
  155. package/dist/bin/shell/chunks/chunk-IX6QY5JW.js +5 -0
  156. package/dist/bin/shell/chunks/{chunk-QKJAAJ7J.js → chunk-IXTPVJ6W.js} +1 -1
  157. package/dist/bin/shell/chunks/{chunk-OUQKFRVR.js → chunk-JBYLHCKP.js} +1 -1
  158. package/dist/bin/shell/chunks/{chunk-NXUXZWS5.js → chunk-JLRB7DV3.js} +1 -1
  159. package/dist/bin/shell/chunks/{chunk-6JEDM6CZ.js → chunk-KH6YLKPE.js} +1 -1
  160. package/dist/bin/shell/chunks/chunk-KXSDVBJA.js +12 -0
  161. package/dist/bin/shell/chunks/{chunk-DYIBFLS3.js → chunk-LOU52GPJ.js} +2 -2
  162. package/dist/bin/shell/chunks/{chunk-L345YZ6R.js → chunk-LVT5R45K.js} +1 -1
  163. package/dist/bin/shell/chunks/{chunk-PTUQEN6I.js → chunk-M345X45Z.js} +7 -7
  164. package/dist/bin/shell/chunks/{chunk-6FGMEZZP.js → chunk-NDS7PYKD.js} +1 -1
  165. package/dist/bin/shell/chunks/chunk-O3PNT72D.js +3 -0
  166. package/dist/bin/shell/chunks/chunk-OGOISDGZ.js +3 -0
  167. package/dist/bin/shell/chunks/chunk-OSW4MDDH.js +21 -0
  168. package/dist/bin/{chunks/chunk-ABP4OLJV.js → shell/chunks/chunk-OXEDIWNZ.js} +1 -1
  169. package/dist/bin/shell/chunks/{chunk-FPWHWWXO.js → chunk-OXV2B2YS.js} +1 -1
  170. package/dist/bin/shell/chunks/{chunk-QMPZXXEK.js → chunk-OY25E3ZN.js} +1 -1
  171. package/dist/bin/shell/chunks/{chunk-O2BCKSMK.js → chunk-PEJXCXSY.js} +1 -1
  172. package/dist/bin/{chunks/chunk-6KHZX4HU.js → shell/chunks/chunk-PLLMJHMV.js} +1 -1
  173. package/dist/bin/{chunks/chunk-6TUILMPB.js → shell/chunks/chunk-QELDDRV5.js} +1 -1
  174. package/dist/bin/shell/chunks/{chunk-3FQBUEB6.js → chunk-RC4UXNHA.js} +1 -1
  175. package/dist/bin/{chunks/chunk-H7PD6FLC.js → shell/chunks/chunk-RE7Z53A3.js} +1 -1
  176. package/dist/bin/shell/chunks/chunk-SCQRBEQW.js +275 -0
  177. package/dist/bin/shell/chunks/{chunk-3DWQCLNP.js → chunk-SS2OPV62.js} +1 -1
  178. package/dist/bin/{chunks/chunk-CC2AQ6B7.js → shell/chunks/chunk-U6JTVQU6.js} +1 -1
  179. package/dist/bin/shell/chunks/chunk-UBA7DOWE.js +3 -0
  180. package/dist/bin/shell/chunks/{chunk-VPSBWWXM.js → chunk-UFAYH3WW.js} +7 -6
  181. package/dist/bin/shell/chunks/chunk-UPUFWGHR.js +3 -0
  182. package/dist/bin/{chunks/chunk-QJWFCA7P.js → shell/chunks/chunk-UU42WPB7.js} +1 -1
  183. package/dist/bin/shell/chunks/{chunk-CNVNOT67.js → chunk-UW4E5XU5.js} +1 -1
  184. package/dist/bin/shell/chunks/chunk-VMVXACZ5.js +6 -0
  185. package/dist/bin/shell/chunks/chunk-WLQ2KWS3.js +10 -0
  186. package/dist/bin/shell/chunks/{chunk-MVBK66TR.js → chunk-WPJ5CECR.js} +1 -1
  187. package/dist/bin/shell/chunks/{chunk-ANX7U57Q.js → chunk-XBOBVLRL.js} +2 -2
  188. package/dist/bin/shell/chunks/{chunk-HZGHQZSY.js → chunk-Z3MXFCN7.js} +1 -1
  189. package/dist/bin/shell/chunks/{column-AJFK3TWF.js → column-AL4LR5PO.js} +1 -1
  190. package/dist/bin/shell/chunks/{cp-YLP7ULVT.js → cp-XJWV46T5.js} +1 -1
  191. package/dist/bin/{chunks/curl-NHNZ46BU.js → shell/chunks/curl-HZ5SBTVY.js} +11 -11
  192. package/dist/bin/shell/chunks/{cut-42X6363P.js → cut-LNJEMWBJ.js} +1 -1
  193. package/dist/bin/{chunks/diff-DM47S5PT.js → shell/chunks/diff-YLVT27CZ.js} +1 -1
  194. package/dist/bin/shell/chunks/dist-4NZ74CRE.js +141 -0
  195. package/dist/bin/shell/chunks/{du-DH76GZJ3.js → du-YNAJTGCR.js} +1 -1
  196. package/dist/bin/shell/chunks/{expr-PQEPO5TE.js → expr-GLGO2VEZ.js} +1 -1
  197. package/dist/bin/shell/chunks/{file-JA7QI2YT.js → file-7M5LLZJY.js} +1 -1
  198. package/dist/bin/shell/chunks/find-3QDGII35.js +3 -0
  199. package/dist/bin/shell/chunks/flag-coverage-AGEO3F6X.js +3 -0
  200. package/dist/bin/shell/chunks/{grep-VXWNMIDD.js → grep-AZJ2CMYE.js} +1 -1
  201. package/dist/bin/shell/chunks/{gzip-UQZL4R74.js → gzip-W5CL2E2W.js} +1 -1
  202. package/dist/bin/{chunks/head-QKVY3SIO.js → shell/chunks/head-ABLEKDMV.js} +1 -1
  203. package/dist/bin/{chunks/help-HVIDHJ6M.js → shell/chunks/help-EXVKU23F.js} +1 -1
  204. package/dist/bin/shell/chunks/{html-to-markdown-XUMA42ZC.js → html-to-markdown-FDNPIEKZ.js} +1 -1
  205. package/dist/bin/{chunks/jq-YS4PR46D.js → shell/chunks/jq-5SOTL7D7.js} +1 -1
  206. package/dist/bin/shell/chunks/{js-exec-ZAAIZQWI.js → js-exec-LISDW7YC.js} +2 -2
  207. package/dist/bin/shell/chunks/{ls-5Z45FV4U.js → ls-EEX3YIOF.js} +1 -1
  208. package/dist/bin/shell/chunks/mkdir-KDEZTR53.js +3 -0
  209. package/dist/bin/shell/chunks/mktemp-OYQYUB5H.js +3 -0
  210. package/dist/bin/{chunks/mv-EOOP2TO3.js → shell/chunks/mv-35V6IA5V.js} +1 -1
  211. package/dist/bin/{chunks/od-2GXD4D5K.js → shell/chunks/od-TD5LZDUM.js} +1 -1
  212. package/dist/bin/{chunks/paste-DWWA3JTW.js → shell/chunks/paste-QJG6BYAP.js} +1 -1
  213. package/dist/bin/shell/chunks/{python3-TJ6DCPIA.js → python3-P6MZ44HK.js} +5 -5
  214. package/dist/bin/{chunks/readlink-EJ3IKLWW.js → shell/chunks/readlink-BF435HNQ.js} +1 -1
  215. package/dist/bin/shell/chunks/rg-B2DVJQVY.js +3 -0
  216. package/dist/bin/shell/chunks/rm-HCMKNRM2.js +3 -0
  217. package/dist/bin/{chunks/rmdir-PRNISPBA.js → shell/chunks/rmdir-WGVUYGPF.js} +1 -1
  218. package/dist/bin/{chunks/sed-SY63U2YX.js → shell/chunks/sed-66XZQ75T.js} +1 -1
  219. package/dist/bin/shell/chunks/{seq-X2EAOGV5.js → seq-KBVCQ4WT.js} +1 -1
  220. package/dist/bin/shell/chunks/{sleep-MOJQBZMY.js → sleep-4O22Z4DI.js} +1 -1
  221. package/dist/bin/{chunks/split-HIFKSV2A.js → shell/chunks/split-OK6JHDWZ.js} +1 -1
  222. package/dist/bin/shell/chunks/sqlite3-57ACN7ES.js +3 -0
  223. package/dist/bin/shell/chunks/{stat-LROLDXHH.js → stat-VNNI7JDZ.js} +1 -1
  224. package/dist/bin/shell/chunks/{tail-UOTUV25D.js → tail-PAHZX3MA.js} +1 -1
  225. package/dist/bin/shell/chunks/{tar-7XOP7VOX.js → tar-RPVTXGFJ.js} +1 -1
  226. package/dist/bin/shell/chunks/{time-LF7BTSK5.js → time-J2DAZUIN.js} +1 -1
  227. package/dist/bin/shell/chunks/timeout-XMTXHNFF.js +3 -0
  228. package/dist/bin/{chunks/tr-PVFO6FRY.js → shell/chunks/tr-ETPC3LHV.js} +1 -1
  229. package/dist/bin/shell/chunks/{which-4TPGVSBZ.js → which-G7X54RZL.js} +1 -1
  230. package/dist/bin/shell/chunks/{xan-RMH6JEXM.js → xan-XZHKEPJ4.js} +1 -1
  231. package/dist/bin/shell/chunks/{xan-view-PD26QEFN.js → xan-view-CNGKCABE.js} +1 -1
  232. package/dist/bin/shell/chunks/yes-2EQTNSIB.js +3 -0
  233. package/dist/bin/shell/chunks/yq-T6S3IDKY.js +3 -0
  234. package/dist/bin/shell/shell.js +369 -363
  235. package/dist/browser.d.ts +1 -1
  236. package/dist/bundle/browser.js +746 -726
  237. package/dist/bundle/chunks/awk2-TLK6FCHV.js +2 -0
  238. package/dist/bundle/chunks/{base64-MHVQ5XHI.js → base64-GUZMZ645.js} +1 -1
  239. package/dist/bundle/chunks/builtin-manifest-7MJJDZ2T.js +2 -0
  240. package/dist/bundle/chunks/{cat-VZBWBIJB.js → cat-LG4YGKUE.js} +1 -1
  241. package/dist/bundle/chunks/{chmod-TEY5MD2W.js → chmod-XUKPG2M4.js} +1 -1
  242. package/dist/bundle/chunks/{chunk-E2F4A3CM.js → chunk-2A4OZBCS.js} +5 -5
  243. package/dist/bundle/chunks/{chunk-WNH3HOQA.js → chunk-353VO5TF.js} +1 -1
  244. package/dist/bundle/chunks/chunk-37UJACD6.js +9 -0
  245. package/dist/bundle/chunks/{chunk-H3A45X3W.js → chunk-3LGQ6XEC.js} +1 -1
  246. package/dist/bundle/chunks/{chunk-P57S6Z6R.js → chunk-3ZY5QX3G.js} +1 -1
  247. package/dist/bundle/chunks/{chunk-45QZRGYF.js → chunk-4VU4IF3W.js} +7 -6
  248. package/dist/bundle/chunks/{chunk-SIOONII3.js → chunk-52W2IWA7.js} +1 -1
  249. package/dist/bundle/chunks/chunk-5IB57TIJ.js +274 -0
  250. package/dist/bundle/chunks/chunk-5J4S2LP5.js +2 -0
  251. package/dist/bundle/chunks/{chunk-PCPW54JH.js → chunk-5LDRJ22P.js} +1 -1
  252. package/dist/bundle/chunks/{chunk-BKUWXPEM.js → chunk-654CJKE3.js} +1 -1
  253. package/dist/bundle/chunks/{chunk-EZNS4GF7.js → chunk-67ODVGSB.js} +1 -1
  254. package/dist/bundle/chunks/{chunk-6QF3PCMO.js → chunk-6HQQON3N.js} +1 -1
  255. package/dist/bundle/chunks/chunk-6L6OYVLY.js +2 -0
  256. package/dist/bundle/chunks/{chunk-U57DSHID.js → chunk-6P2DITXT.js} +1 -1
  257. package/dist/bundle/chunks/chunk-74IR77AZ.js +11 -0
  258. package/dist/bundle/chunks/{chunk-S3ENGQML.js → chunk-7DVD6YCI.js} +1 -1
  259. package/dist/bundle/chunks/{chunk-HXWB4Z5X.js → chunk-7II7XIVI.js} +1 -1
  260. package/dist/bundle/chunks/{chunk-AYSZ5MAE.js → chunk-A3C4Z3Q3.js} +1 -1
  261. package/dist/bundle/chunks/chunk-A6SU3BZX.js +6 -0
  262. package/dist/bundle/chunks/{chunk-6HO6HX7V.js → chunk-AMXNXHXK.js} +1 -1
  263. package/dist/bundle/chunks/{chunk-QJ7OXJAZ.js → chunk-BLG7RWH4.js} +1 -1
  264. package/dist/bundle/chunks/chunk-BMBITA6Y.js +2 -0
  265. package/dist/bundle/chunks/{chunk-XQ2ZZFO6.js → chunk-BQTWRHZR.js} +2 -2
  266. package/dist/bundle/chunks/{chunk-WE7BJ7YU.js → chunk-BZ2OMW2T.js} +1 -1
  267. package/dist/bundle/chunks/{chunk-S6DNKKUL.js → chunk-CM4T4GB4.js} +1 -1
  268. package/dist/bundle/chunks/{chunk-CH7SUFFO.js → chunk-CORCIYJD.js} +1 -1
  269. package/dist/bundle/chunks/{chunk-LGIJSCWH.js → chunk-EQDVNHQS.js} +1 -1
  270. package/dist/bundle/chunks/{chunk-U4K5ZDWK.js → chunk-EZEO6MFE.js} +1 -1
  271. package/dist/bundle/chunks/{chunk-SE23TEGG.js → chunk-EZT6M2HG.js} +1 -1
  272. package/dist/bundle/chunks/{chunk-4MJ7VJG4.js → chunk-H7UVJSZR.js} +1 -1
  273. package/dist/bundle/chunks/{chunk-5EI7WSRV.js → chunk-HYQGYXGZ.js} +1 -1
  274. package/dist/bundle/chunks/{chunk-6IA4DXG2.js → chunk-IPKSYZ3R.js} +1 -1
  275. package/dist/bundle/chunks/{chunk-TLPMB3FO.js → chunk-KJBPGFZD.js} +1 -1
  276. package/dist/bundle/chunks/chunk-L7NEGEOJ.js +16 -0
  277. package/dist/bundle/chunks/{chunk-YFFU74KY.js → chunk-MJEJ7QEY.js} +1 -1
  278. package/dist/bundle/chunks/{chunk-QJFYYEFV.js → chunk-N36I27VM.js} +1 -1
  279. package/dist/bundle/chunks/chunk-N5L7E4EL.js +6 -0
  280. package/dist/bundle/chunks/{chunk-6QAM55HM.js → chunk-NFODJFHN.js} +1 -1
  281. package/dist/bundle/chunks/{chunk-IXFQXNL4.js → chunk-NFW4YKDO.js} +1 -1
  282. package/dist/bundle/chunks/{chunk-HCKTU6IR.js → chunk-NOX3PCUH.js} +1 -1
  283. package/dist/bundle/chunks/{chunk-MQKGGNPS.js → chunk-NXBUT5V2.js} +2 -2
  284. package/dist/bundle/chunks/{chunk-4KZT23KR.js → chunk-O5BHWBYH.js} +1 -1
  285. package/dist/bundle/chunks/{chunk-DVSA72LH.js → chunk-QTL2XC4B.js} +1 -1
  286. package/dist/bundle/chunks/chunk-RK2WBVP4.js +2 -0
  287. package/dist/bundle/chunks/{chunk-BLPYR4TN.js → chunk-RVBBGZ22.js} +1 -1
  288. package/dist/bundle/chunks/{chunk-PS2RJNZZ.js → chunk-SXQJYLP7.js} +1 -1
  289. package/dist/bundle/chunks/{chunk-MWL2I5BV.js → chunk-T7OAZEXT.js} +1 -1
  290. package/dist/bundle/chunks/{chunk-O452S4KX.js → chunk-URIKBXSE.js} +1 -1
  291. package/dist/bundle/chunks/{chunk-6BSOPPZH.js → chunk-UVQC75LS.js} +7 -7
  292. package/dist/bundle/chunks/chunk-VCREDMWH.js +4 -0
  293. package/dist/bundle/chunks/{chunk-DDPD7SIB.js → chunk-VQ6EUBJ3.js} +1 -1
  294. package/dist/bundle/chunks/chunk-VQEB6E2M.js +13 -0
  295. package/dist/bundle/chunks/{chunk-R2FBRMDU.js → chunk-VWUMR4IC.js} +1 -1
  296. package/dist/bundle/chunks/{chunk-XXBIOG4R.js → chunk-WDY2TNMK.js} +1 -1
  297. package/dist/bundle/chunks/chunk-XT7EK6BR.js +9 -0
  298. package/dist/bundle/chunks/{chunk-BS6EJR2R.js → chunk-XUTEQMTL.js} +5 -5
  299. package/dist/bundle/chunks/{chunk-KIGPB52X.js → chunk-XZ34OGNM.js} +1 -1
  300. package/dist/bundle/chunks/{chunk-FSKXIFYT.js → chunk-Y6UHNLT5.js} +1 -1
  301. package/dist/bundle/chunks/chunk-YUITEK6N.js +12 -0
  302. package/dist/bundle/chunks/chunk-YZCPEJRE.js +20 -0
  303. package/dist/bundle/chunks/chunk-ZIQS5QAW.js +5 -0
  304. package/dist/bundle/chunks/chunk-ZUEPJPYA.js +2 -0
  305. package/dist/bundle/chunks/{column-QJI65SH2.js → column-T4LGMRJG.js} +1 -1
  306. package/dist/bundle/chunks/{cp-UR762VVT.js → cp-ZDDVNITX.js} +1 -1
  307. package/dist/bundle/chunks/{curl-K4WT7UPN.js → curl-RCRD36LD.js} +11 -11
  308. package/dist/bundle/chunks/{cut-FMDNVWQN.js → cut-35WER2E2.js} +1 -1
  309. package/dist/bundle/chunks/{diff-R7TXVVLN.js → diff-Z3XOLW44.js} +1 -1
  310. package/dist/bundle/chunks/{du-EQKH3UNA.js → du-YBSJVBXP.js} +1 -1
  311. package/dist/bundle/chunks/{expr-A5XITHQD.js → expr-KSNRNE7V.js} +1 -1
  312. package/dist/bundle/chunks/{file-6AYYTULJ.js → file-XH37HMGV.js} +1 -1
  313. package/dist/bundle/chunks/find-3AONTPPM.js +2 -0
  314. package/dist/bundle/chunks/flag-coverage-6YGO7STE.js +2 -0
  315. package/dist/bundle/chunks/{grep-Q2O5EIXQ.js → grep-WW5KJPUG.js} +1 -1
  316. package/dist/bundle/chunks/{gzip-KC5ENBD2.js → gzip-ISZXQNJJ.js} +1 -1
  317. package/dist/bundle/chunks/{head-6UIPFWVJ.js → head-VYXZQLPZ.js} +1 -1
  318. package/dist/bundle/chunks/{help-QDDMBDU7.js → help-62M75TSG.js} +1 -1
  319. package/dist/bundle/chunks/{html-to-markdown-PE6BPRPA.js → html-to-markdown-4LXS3A44.js} +1 -1
  320. package/dist/bundle/chunks/{jq-UKAA3QWU.js → jq-3IVOWP3G.js} +1 -1
  321. package/dist/bundle/chunks/{js-exec-MUZRDUJ3.js → js-exec-T2WEE4KG.js} +2 -2
  322. package/dist/bundle/chunks/js-exec-worker.js +1 -0
  323. package/dist/bundle/chunks/{ls-WH5S4PPL.js → ls-FC3CSHKE.js} +1 -1
  324. package/dist/bundle/chunks/mkdir-DPFWDY25.js +2 -0
  325. package/dist/bundle/chunks/mktemp-SW2AHXZW.js +2 -0
  326. package/dist/bundle/chunks/{mv-WE7DBLEK.js → mv-PWCFXEF2.js} +1 -1
  327. package/dist/bundle/chunks/{od-Z4AIL3P4.js → od-VJ6PBBEI.js} +1 -1
  328. package/dist/bundle/chunks/{paste-ZNHNSRBW.js → paste-TIQETHSO.js} +1 -1
  329. package/dist/bundle/chunks/{python3-W4UMQJAQ.js → python3-6JEP7ZZK.js} +5 -5
  330. package/dist/bundle/chunks/{readlink-JSRKXLLQ.js → readlink-7XGQ3PL7.js} +1 -1
  331. package/dist/bundle/chunks/rg-2OPJ5V3D.js +2 -0
  332. package/dist/bundle/chunks/rm-AZZM5DCE.js +2 -0
  333. package/dist/bundle/chunks/{rmdir-3WTXMVKI.js → rmdir-YXYSZD4X.js} +1 -1
  334. package/dist/bundle/chunks/{sed-6G32B25J.js → sed-HYSBLGO5.js} +1 -1
  335. package/dist/bundle/chunks/{seq-B6KDLMYQ.js → seq-M2S4FRN4.js} +1 -1
  336. package/dist/bundle/chunks/{sleep-25QUPVDK.js → sleep-YC4HFEGC.js} +1 -1
  337. package/dist/bundle/chunks/{split-HUKVGJTW.js → split-UOPIWKKE.js} +1 -1
  338. package/dist/bundle/chunks/sqlite3-XCROTL6G.js +2 -0
  339. package/dist/bundle/chunks/{stat-LXFZND2P.js → stat-I3FPUTR7.js} +1 -1
  340. package/dist/bundle/chunks/{tail-UBGSN4JF.js → tail-WK3WACZK.js} +1 -1
  341. package/dist/bundle/chunks/{tar-LE7LAAIX.js → tar-VZYMNZV2.js} +1 -1
  342. package/dist/bundle/chunks/{time-NERE2JJ2.js → time-N6J6DC6C.js} +1 -1
  343. package/dist/bundle/chunks/timeout-UDR5J2MP.js +2 -0
  344. package/dist/bundle/chunks/{tr-UI2LA3GA.js → tr-VI5PIA4A.js} +1 -1
  345. package/dist/bundle/chunks/{which-UWVKETYW.js → which-BP5YY5BR.js} +1 -1
  346. package/dist/bundle/chunks/worker.js +5 -0
  347. package/dist/bundle/chunks/{xan-UIL24CGT.js → xan-DL576EIT.js} +1 -1
  348. package/dist/bundle/chunks/xan-view-GJVN6IHX.js +2 -0
  349. package/dist/bundle/chunks/yes-OVJMX6NM.js +2 -0
  350. package/dist/bundle/chunks/yq-KYPU4LQP.js +2 -0
  351. package/dist/bundle/index.cjs +1079 -1059
  352. package/dist/bundle/index.js +345 -339
  353. package/dist/commands/mktemp/mktemp.d.ts +4 -0
  354. package/dist/commands/registry.d.ts +1 -1
  355. package/dist/commands/which/which.d.ts +10 -0
  356. package/dist/commands/yes/yes.d.ts +4 -0
  357. package/dist/custom-commands.d.ts +12 -0
  358. package/dist/fs/create-exclusive.d.ts +30 -0
  359. package/dist/fs/in-memory-fs/in-memory-fs.d.ts +8 -1
  360. package/dist/fs/interface.d.ts +37 -0
  361. package/dist/fs/mountable-fs/mountable-fs.d.ts +18 -1
  362. package/dist/fs/overlay-fs/overlay-fs.d.ts +19 -1
  363. package/dist/fs/path-utils.d.ts +0 -4
  364. package/dist/fs/read-write-fs/read-write-fs.d.ts +22 -1
  365. package/dist/index.d.cts +1 -1
  366. package/dist/index.d.ts +1 -1
  367. package/dist/interpreter/expansion/array-prefix-suffix.d.ts +2 -1
  368. package/dist/interpreter/expansion/parameter-ops.d.ts +1 -0
  369. package/dist/interpreter/expansion/pattern-removal.d.ts +3 -0
  370. package/dist/interpreter/expansion/variable.d.ts +1 -1
  371. package/dist/interpreter/helpers/loop.d.ts +32 -0
  372. package/dist/limits.d.ts +0 -3
  373. package/dist/network/dns-pin.d.ts +1 -32
  374. package/dist/network/fetch.d.ts +1 -1
  375. package/dist/security/trusted-globals.d.ts +8 -0
  376. package/dist/types.d.ts +6 -0
  377. package/package.json +3 -4
  378. package/dist/bin/chunks/awk2-NTRVFXRA.js +0 -3
  379. package/dist/bin/chunks/chunk-3PCPQIUD.js +0 -3
  380. package/dist/bin/chunks/chunk-6JUPBMCR.js +0 -13
  381. package/dist/bin/chunks/chunk-BB5VTPMQ.js +0 -16
  382. package/dist/bin/chunks/chunk-CN4JKMTR.js +0 -8
  383. package/dist/bin/chunks/chunk-F2PYTUMR.js +0 -9
  384. package/dist/bin/chunks/chunk-HWI42GQO.js +0 -7
  385. package/dist/bin/chunks/chunk-HWK7KFGB.js +0 -3
  386. package/dist/bin/chunks/chunk-I57EACSL.js +0 -3
  387. package/dist/bin/chunks/chunk-ONF4KUYV.js +0 -13
  388. package/dist/bin/chunks/chunk-PRVPFKTC.js +0 -276
  389. package/dist/bin/chunks/chunk-RTN6X652.js +0 -11
  390. package/dist/bin/chunks/chunk-RVPTAYDS.js +0 -4
  391. package/dist/bin/chunks/chunk-U5JLGI56.js +0 -21
  392. package/dist/bin/chunks/dist-5MWO25Y4.js +0 -141
  393. package/dist/bin/chunks/find-MHC4QV6H.js +0 -3
  394. package/dist/bin/chunks/flag-coverage-LLAQBVIG.js +0 -3
  395. package/dist/bin/chunks/mkdir-YJ3SOVRP.js +0 -3
  396. package/dist/bin/chunks/rg-WHVR3YDT.js +0 -3
  397. package/dist/bin/chunks/rm-B4LVIG7A.js +0 -3
  398. package/dist/bin/chunks/sqlite3-CXQTZRPZ.js +0 -3
  399. package/dist/bin/chunks/timeout-RQOWSWYG.js +0 -3
  400. package/dist/bin/chunks/yq-CWBZMGUV.js +0 -3
  401. package/dist/bin/shell/chunks/awk2-NTRVFXRA.js +0 -3
  402. package/dist/bin/shell/chunks/chunk-3PCPQIUD.js +0 -3
  403. package/dist/bin/shell/chunks/chunk-6JUPBMCR.js +0 -13
  404. package/dist/bin/shell/chunks/chunk-BB5VTPMQ.js +0 -16
  405. package/dist/bin/shell/chunks/chunk-CN4JKMTR.js +0 -8
  406. package/dist/bin/shell/chunks/chunk-F2PYTUMR.js +0 -9
  407. package/dist/bin/shell/chunks/chunk-HWI42GQO.js +0 -7
  408. package/dist/bin/shell/chunks/chunk-HWK7KFGB.js +0 -3
  409. package/dist/bin/shell/chunks/chunk-I57EACSL.js +0 -3
  410. package/dist/bin/shell/chunks/chunk-ONF4KUYV.js +0 -13
  411. package/dist/bin/shell/chunks/chunk-PRVPFKTC.js +0 -276
  412. package/dist/bin/shell/chunks/chunk-RTN6X652.js +0 -11
  413. package/dist/bin/shell/chunks/chunk-RVPTAYDS.js +0 -4
  414. package/dist/bin/shell/chunks/chunk-U5JLGI56.js +0 -21
  415. package/dist/bin/shell/chunks/dist-5MWO25Y4.js +0 -141
  416. package/dist/bin/shell/chunks/find-MHC4QV6H.js +0 -3
  417. package/dist/bin/shell/chunks/flag-coverage-LLAQBVIG.js +0 -3
  418. package/dist/bin/shell/chunks/mkdir-YJ3SOVRP.js +0 -3
  419. package/dist/bin/shell/chunks/rg-WHVR3YDT.js +0 -3
  420. package/dist/bin/shell/chunks/rm-B4LVIG7A.js +0 -3
  421. package/dist/bin/shell/chunks/sqlite3-CXQTZRPZ.js +0 -3
  422. package/dist/bin/shell/chunks/timeout-RQOWSWYG.js +0 -3
  423. package/dist/bin/shell/chunks/yq-CWBZMGUV.js +0 -3
  424. package/dist/bundle/chunks/awk2-VS5QVYHU.js +0 -2
  425. package/dist/bundle/chunks/chunk-2SMD2AUA.js +0 -3
  426. package/dist/bundle/chunks/chunk-35MBA3VY.js +0 -12
  427. package/dist/bundle/chunks/chunk-3OBCZP7T.js +0 -12
  428. package/dist/bundle/chunks/chunk-4CC3OZPU.js +0 -2
  429. package/dist/bundle/chunks/chunk-A257L6QO.js +0 -7
  430. package/dist/bundle/chunks/chunk-ATGOUOX2.js +0 -15
  431. package/dist/bundle/chunks/chunk-BRJERIF4.js +0 -2
  432. package/dist/bundle/chunks/chunk-FTET43KM.js +0 -2
  433. package/dist/bundle/chunks/chunk-GRUZ4SBY.js +0 -275
  434. package/dist/bundle/chunks/chunk-LRFR25IP.js +0 -8
  435. package/dist/bundle/chunks/chunk-RWQWFXMH.js +0 -10
  436. package/dist/bundle/chunks/chunk-Y6JBSHCM.js +0 -20
  437. package/dist/bundle/chunks/chunk-ZBUZKIPX.js +0 -6
  438. package/dist/bundle/chunks/find-RLKBCGJR.js +0 -2
  439. package/dist/bundle/chunks/flag-coverage-YQGACUSN.js +0 -2
  440. package/dist/bundle/chunks/mkdir-Z6MMWH3D.js +0 -2
  441. package/dist/bundle/chunks/rg-JKB7DR66.js +0 -2
  442. package/dist/bundle/chunks/rm-IGPLE632.js +0 -2
  443. package/dist/bundle/chunks/sqlite3-DQNCWDG5.js +0 -2
  444. package/dist/bundle/chunks/timeout-37GM7IIL.js +0 -2
  445. package/dist/bundle/chunks/xan-view-FOCYCKZQ.js +0 -2
  446. package/dist/bundle/chunks/yq-ZRNZKDLE.js +0 -2
@@ -1,56 +1,59 @@
1
1
  import{createRequire} from"node:module";const require=createRequire(import.meta.url);
2
- import{a as Ht,b as Zt,c as dt}from"./chunks/chunk-WNH3HOQA.js";import{a as Qr}from"./chunks/chunk-BRJERIF4.js";import{c as Ii,e as Xa}from"./chunks/chunk-KIGPB52X.js";import{a as Hr,b as Zr,d as pr,e as mr}from"./chunks/chunk-PS2RJNZZ.js";import{a as an}from"./chunks/chunk-SGX4WOAM.js";import{a as Di}from"./chunks/chunk-L2UW7DWF.js";import{a as on,b as Xe,c as Er}from"./chunks/chunk-DLL7UR66.js";import{a as wr,b as Ka}from"./chunks/chunk-BKUWXPEM.js";import{a as ge}from"./chunks/chunk-4KZT23KR.js";import{a as Yr,b as Jr}from"./chunks/chunk-AYSZ5MAE.js";import{a as qn,b as Re}from"./chunks/chunk-ZBUZKIPX.js";import"./chunks/chunk-57LGFT4S.js";import{c as nn,d as Hn}from"./chunks/chunk-FTET43KM.js";import"./chunks/chunk-STHBFACM.js";import{a as gr,b as St,c as rn,d as es,e as z,f as qt,g as U,h as Zn,i as sn,j as Nn,k as Gt,l as Qn}from"./chunks/chunk-4CC3OZPU.js";import{a as Jt,b as tt,c as nt,d as We,e as Qe,f as Ke,g as G,h as ue,i as rt,j as en,k as Kr,l as C,m as st,n as Oe,o as tn,p as Xr,q as ut}from"./chunks/chunk-TVCZIH6M.js";import{a as W,b as yr,c as Cn,d as Od,e as Yt,f as Ri,g as Gn,h as Dd,i as Ut,j as Oi,k as Id,l as Td}from"./chunks/chunk-GN6CQ3J4.js";import{a as x,b as _d,c as ft,d as Ld}from"./chunks/chunk-T5ZEIOJ3.js";import{a as Ot}from"./chunks/chunk-FOCWZZDE.js";import{a as jt}from"./chunks/chunk-W5DWRFSU.js";import{a as Ni}from"./chunks/chunk-NCUTH6QL.js";import*as Me from"node:path";var Rn=[{name:"echo",load:async()=>(await import("./chunks/echo-PLLZYM2L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-VZBWBIJB.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-B2NSYQ3N.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-WH5S4PPL.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-Z6MMWH3D.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-3WTXMVKI.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-W4DF6Z4T.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-IGPLE632.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-UR762VVT.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-WE7DBLEK.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-CEM7GDB5.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-TEY5MD2W.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-76BPYV5F.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-JSRKXLLQ.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-6UIPFWVJ.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-UBGSN4JF.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-7WVM7GV4.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-LXFZND2P.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-Q2O5EIXQ.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-JKB7DR66.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-6G32B25J.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-VS5QVYHU.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-CB5GO7XH.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-PAEPA27E.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-DTWKU2MC.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-FMDNVWQN.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-ZNHNSRBW.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-UI2LA3GA.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-EPOS3MFH.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-IELOWYJG.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-QJBPHRFJ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-J3VOSOMK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-YD5BWFH4.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-VLFTYX2Z.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-HUKVGJTW.js")).split},{name:"column",load:async()=>(await import("./chunks/column-QJI65SH2.js")).column},{name:"join",load:async()=>(await import("./chunks/join-C2B6NGXH.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-OOWSWHRQ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-RLKBCGJR.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SJZQ5W65.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-Z2ZMOOW2.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7OOL2MH6.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-EQKH3UNA.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-VUUMB47B.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-VUUMB47B.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3N762S3K.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-VQEXRD3C.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KPIUNI6K.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-UKAA3QWU.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-MHVQ5XHI.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-R7TXVVLN.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-7OEDRA27.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-25QUPVDK.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-37GM7IIL.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-NERE2JJ2.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-B6KDLMYQ.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-A5XITHQD.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-JEDX55KS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BLPZJ6MP.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-VJZ4PHQ4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-6AYYTULJ.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-PE6BPRPA.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-QDDMBDU7.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-UWVKETYW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-YXC4HBTR.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-CESD3CQR.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KR6E7UIR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-Z4AIL3P4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-KC5ENBD2.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Rn.push({name:"tar",load:async()=>(await import("./chunks/tar-LE7LAAIX.js")).tarCommand}),Rn.push({name:"yq",load:async()=>(await import("./chunks/yq-ZRNZKDLE.js")).yqCommand}),Rn.push({name:"xan",load:async()=>(await import("./chunks/xan-UIL24CGT.js")).xanCommand}),Rn.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-DQNCWDG5.js")).sqlite3Command}));var ts=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ts.push({name:"python3",load:async()=>(await import("./chunks/python3-W4UMQJAQ.js")).python3Command}),ts.push({name:"python",load:async()=>(await import("./chunks/python3-W4UMQJAQ.js")).pythonCommand}));var ns=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ns.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-MUZRDUJ3.js")).jsExecCommand}),ns.push({name:"node",load:async()=>(await import("./chunks/js-exec-MUZRDUJ3.js")).nodeStubCommand}));var Ja=[{name:"curl",load:async()=>(await import("./chunks/curl-K4WT7UPN.js")).curlCommand}],Ya=new Map;function rs(e){return{name:e.name,async execute(t,n){let r=Ya.get(e.name);if(r||(r=await Re.runTrustedAsync(()=>e.load()),Ya.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await import("./chunks/flag-coverage-YQGACUSN.js");s(n.coverage,e.name,t)}return r.execute(t,n)}}}function Fd(){return Rn.map(e=>e.name)}function Md(){return Ja.map(e=>e.name)}function el(e){return(e?Rn.filter(n=>e.includes(n.name)):Rn).map(rs)}function tl(){return Ja.map(rs)}function Bd(){return ts.map(e=>e.name)}function nl(){return ts.map(rs)}function Wd(){return ns.map(e=>e.name)}function rl(){return ns.map(rs)}var sl=new WeakMap,il=new WeakSet;function ss(e){let t=sl.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),sl.set(e,t),il.add(t)),t}function ol(e){return il.has(e)}var al={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxJsMemoryBytes:67108864,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},Vd={...al,maxSourceBytes:8*1024*1024,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxExtensionCleanupTimeMs:25,maxGlobOperations:1e5,maxStringLength:10*1024*1024,maxArrayElements:1e5,maxHeredocSize:10*1024*1024,maxBraceExpansionResults:1e4,maxOutputSize:10*1024*1024,maxFileDescriptors:1024,maxQueryTokens:25e3,maxQueryDepth:256,maxQueryElements:1e5,maxAwkParserTokens:25e3,maxAwkParserDepth:128,maxAwkParserOperations:1e5,maxCsvRows:1e5,maxCsvCells:1e6,maxWorkUnits:1e5,maxTraversalEntries:1e5,maxTraversalDepth:256,maxTraversalWork:1e5,maxLiveBytes:64*1024*1024,maxInputBytes:32*1024*1024,maxFileSystemBytes:128*1024*1024,maxDatabaseBytes:64*1024*1024,maxDatabaseResultBytes:16*1024*1024,maxArchiveBytes:128*1024*1024,maxArchiveCompressedBytes:64*1024*1024,maxArchiveEntryBytes:64*1024*1024,maxArchiveEntries:1e5,maxWorkerMessageBytes:16*1024*1024,maxExecutionTimeMs:3e4};function is(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?Vd:al;if(!e)return{...n};let r={maxSourceBytes:e.maxSourceBytes??n.maxSourceBytes,maxExecDepth:e.maxExecDepth??n.maxExecDepth,maxCallDepth:e.maxCallDepth??n.maxCallDepth,maxCommandCount:e.maxCommandCount??n.maxCommandCount,maxLoopIterations:e.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??n.maxAwkIterations,maxSedIterations:e.maxSedIterations??n.maxSedIterations,maxJqIterations:e.maxJqIterations??n.maxJqIterations,maxQueryTokens:e.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:e.maxQueryDepth??n.maxQueryDepth,maxQueryElements:e.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:e.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:e.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:e.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:e.maxCsvRows??n.maxCsvRows,maxCsvCells:e.maxCsvCells??n.maxCsvCells,maxWorkUnits:e.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:e.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:e.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:e.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:e.maxLiveBytes??n.maxLiveBytes,maxInputBytes:e.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:e.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:e.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:e.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:e.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:e.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:e.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:e.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:e.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:e.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:e.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??n.maxJsTimeoutMs,maxJsMemoryBytes:e.maxJsMemoryBytes??n.maxJsMemoryBytes,maxGlobOperations:e.maxGlobOperations??n.maxGlobOperations,maxStringLength:e.maxStringLength??n.maxStringLength,maxArrayElements:e.maxArrayElements??n.maxArrayElements,maxHeredocSize:e.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??n.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??n.maxSourceDepth};for(let s of Object.keys(r)){let i=r[s];if(i!==Number.POSITIVE_INFINITY&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`${s} must be a non-negative safe integer or positive Infinity`)}return r}function zd(e){let{executionLimits:t,executionLimitProfile:n,fs:r,stdin:s=Ri,...i}=e;return{fs:r,fsIdentity:i.fsIdentity??ss(r),cwd:"/",env:new Map,stdin:s,limits:is(t,n),...i}}function ll(e){return"load"in e&&typeof e.load=="function"}function Ud(e,t,n={}){return{name:e,trusted:n.trusted!==!1,execute:t}}function cl(e){let t=null,n=null;return{name:e.name,trusted:e.trusted!==!1,async execute(r,s){if(!t){let o=n;o||(o=e.load().then(a=>(t=a,a)),n=o);try{t=await o}catch(a){throw n===o&&(n=null),a}}let i=t;if(!i)throw new Error(`Failed to load command: ${e.name}`);return i.execute(r,s)}}}var ul=Object.freeze(Object.create(null)),os=class{limits;signal;abortOnUnresolvedCommands;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();unresolvedCommands=new Set;get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(t,n=void 0,r=!1){this.limits=t,this.signal=n,this.abortOnUnresolvedCommands=r}recordUnresolvedCommand(t){this.unresolvedCommands.add(t)}get unresolvedCommandNames(){return[...this.unresolvedCommands]}fail(t){throw this.poisoned??=t,this.poisoned}poisonAfterAbort(t){this.poisoned??=t}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(t=1,n="execution"){return this.consume("work",t,n)}consumeLimited(t,n,r,s=t){this.assertUsable();let i=this.countersByKind.get(t)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new C(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new C(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(t,i+n),this.workUnits+=n,i+n}consumeInput(t,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(t)||t<0||t>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new C(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=t,this.inputBytes}consume(t,n=1,r=t){this.assertUsable();let s=this.countersByKind.get(t)??0,i=t==="commands"?this.commandCount:this.workUnits,o=t==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>o-i)&&this.fail(new C(t==="commands"?`too many commands executed (>${o}), increase executionLimits.maxCommandCount`:`${r}: ${t} work limit exceeded (${o})`,t==="commands"?"commands":"iterations"));let a=i+n;return t==="commands"?this.commandCount=a:this.workUnits=a,this.countersByKind.set(t,s+n),a}reserveBytes(t,n,r){this.assertUsable();let s=typeof t=="string"?t:"live",i=typeof t=="string"?n:t,o=typeof t=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new C(`${o}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let a=!1;return{release:()=>{if(a)return;a=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(t,n,r="execution",s=0,i="text"){this.assertUsable();let o=i==="bytes"?n.length:W(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new C(`${r}: invalid ${t} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new C(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=a,o}accountResult(t,n="execution",r=Number.POSITIVE_INFINITY){let s=t.internalOutputAccounting,i=Math.min(s?.stdout??0,r),o=Math.min(s?.stderr??0,Math.max(0,r-i)),a=this.appendOutput("stdout",t.stdout,n,i,t.stdoutKind==="bytes"||t.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",t.stderr,n,o);return Object.isExtensible(t)?(t.internalOutputAccounting={stdout:a,stderr:l},t):a===0&&l===0?t:{...t,internalOutputAccounting:{stdout:a,stderr:l}}}relinquishOutput(t,n,r){this.assertUsable(),r!==ul&&this.fail(new C(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new C(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=t}enterDepth(t,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??t,o=this.depthByKind.get(t)??0;o>=s&&this.fail(new C(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(t,o+1);let a=!1;return{release:()=>{if(a)return;a=!0;let l=(this.depthByKind.get(t)??1)-1;l<=0?this.depthByKind.delete(t):this.depthByKind.set(t,l)}}}throwIfAborted(t="execution"){this.signal?.aborted&&this.fail(new st("",`bash: ${t} aborted
3
- `)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new st("",`bash: ${t} exceeded execution deadline (${this.limits.maxExecutionTimeMs}ms)
4
- `))}remainingTimeMs(){return Math.max(0,this.limits.maxExecutionTimeMs-(Date.now()-this.startedAt))}registerCleanup(t){this.assertUsable(),this.cleanupCallbacks.push(t);let n=!0;return()=>{if(!n)return;n=!1;let r=this.cleanupCallbacks.indexOf(t);r>=0&&this.cleanupCallbacks.splice(r,1)}}async close(){if(this.closed)return;this.closed=!0;let t=[],n=Date.now()+this.limits.maxExtensionCleanupTimeMs;for(let r=this.cleanupCallbacks.length-1;r>=0;r--)try{let s=n-Date.now();if(s<=0){t.push(new Error("execution cleanup grace period exceeded"));break}let i,o=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[r]).then(()=>({ok:!0}),a=>({ok:!1,error:a})),new Promise(a=>{i=pr(()=>a({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(mr(i),!o.ok&&(t.push(o.error),Date.now()>=n))break}catch(s){t.push(s)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,t.length>0)throw new AggregateError(t,"execution cleanup failed")}assertExecDepth(t){this.assertUsable(),t>this.limits.maxExecDepth&&this.fail(new C(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function fl(e){let t=Object.create(null);return Object.defineProperties(t,{remainingLiveBytes:{enumerable:!0,get:()=>e.remainingLiveBytes},consumeWork:{enumerable:!0,value:e.consumeWork.bind(e)},consumeLimited:{enumerable:!0,value:e.consumeLimited.bind(e)},consumeInput:{enumerable:!0,value:e.consumeInput.bind(e)},reserveBytes:{enumerable:!0,value:e.reserveBytes.bind(e)},enterDepth:{enumerable:!0,value:e.enterDepth.bind(e)},throwIfAborted:{enumerable:!0,value:e.throwIfAborted.bind(e)},remainingTimeMs:{enumerable:!0,value:e.remainingTimeMs.bind(e)},registerCleanup:{enumerable:!0,value:e.registerCleanup.bind(e)}}),Object.freeze(t)}function dl(e,t,n="pipeline"){e.relinquishOutput(t,n,ul)}var On=new TextEncoder;function jd(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var ze=class{data=new Map;entryIdentities=new WeakMap;nextEntryIdentity=1;maxTotalBytes;retainedBytes=0;contentReferences=new WeakMap;materializedContent(t){return t?.type==="file"&&"content"in t?t.content:null}storedByteLength(t){return t===null?0:t instanceof Uint8Array?t.byteLength:W(t)}wouldReleaseBytes(t){let n=this.materializedContent(t);return n===null?0:n instanceof Uint8Array?this.contentReferences.get(n)===1?n.byteLength:0:this.storedByteLength(n)}assertCanAllocate(t,n){let r=this.wouldReleaseBytes(this.data.get(t));if(!Number.isSafeInteger(n)||n<0||n>this.maxTotalBytes-this.retainedBytes+r)throw new x("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(t,n){let r=this.data.get(t),s=this.materializedContent(r),i=this.materializedContent(n);if(s===i){this.data.set(t,n);return}let o=this.wouldReleaseBytes(r),a=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(a>this.maxTotalBytes-this.retainedBytes+o)throw new x("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(s instanceof Uint8Array){let l=this.contentReferences.get(s)??0;l<=1?this.contentReferences.delete(s):this.contentReferences.set(s,l-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=a-o,this.data.set(t,n)}deleteEntry(t){let n=this.data.get(t);if(!n)return!1;let r=this.materializedContent(n),s=this.wouldReleaseBytes(n);if(r instanceof Uint8Array){let i=this.contentReferences.get(r)??0;i<=1?this.contentReferences.delete(r):this.contentReferences.set(r,i-1)}return this.retainedBytes-=s,this.data.delete(t)}contentByteLength(t,n){if(t instanceof Uint8Array)return t.byteLength;if(n==="hex")return Math.floor(t.length/2);if(n==="base64"){let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-r)}return n==="binary"||n==="latin1"?t.length:W(t)}identityFor(t){let n=this.entryIdentities.get(t);return n||(n=`memfs:${this.nextEntryIdentity++}`,this.entryIdentities.set(t,n)),n}constructor(t,n={}){if(this.maxTotalBytes=n.maxTotalBytes??1024*1024*1024,!Number.isSafeInteger(this.maxTotalBytes)||this.maxTotalBytes<0)throw new Error("InMemoryFs: invalid maxTotalBytes");if(this.data.set("/",{type:"directory",mode:St,mtime:new Date}),t)for(let[r,s]of Object.entries(t))typeof s=="function"?this.writeFileLazy(r,s):jd(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(t){let n=Zn(t);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:St,mtime:new Date})))}writeFileSync(t,n,r,s){U(t,"write");let i=z(t);this.ensureParentDirs(i);let o=dt(r);this.assertCanAllocate(i,this.contentByteLength(n,o));let a=Ht(n,o);this.setEntry(i,{type:"file",content:a,mode:s?.mode??rn,mtime:s?.mtime??new Date})}writeFileLazy(t,n,r){U(t,"write");let s=z(t);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??rn,mtime:r?.mtime??new Date})}async materializeLazy(t,n){let r=await Re.runTrustedAsync(async()=>n.lazy()),s=typeof r=="string"?On.encode(r):r,i={type:"file",content:s,mode:n.mode,mtime:n.mtime};return this.assertCanAllocate(t,s.byteLength),this.setEntry(t,i),i}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t){U(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, open '${t}'`);if(r.type!=="file")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:On.encode(s.content)}return r.content instanceof Uint8Array?r.content:On.encode(r.content)}async writeFile(t,n,r){this.writeFileSync(t,n,r)}async appendFile(t,n,r){U(t,"append");let s=z(t),i=this.data.get(s);if(i&&i.type==="directory")throw new x("EISDIR",`illegal operation on a directory, write '${t}'`);let o=dt(r),a=this.contentByteLength(n,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:On.encode("content"in l?l.content:"");this.assertCanAllocate(s,c.byteLength+a);let u=Ht(n,o),f=new Uint8Array(c.length+u.length);f.set(c),f.set(u,c.length),this.setEntry(s,{type:"file",content:f,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,n,r)}async exists(t){if(t.includes("\0"))return!1;try{let n=this.resolvePathWithSymlinks(t);return this.data.has(n)}catch{return!1}}async stat(t){U(t,"stat");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=On.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}async lstat(t){U(t,"lstat");let n=this.resolveIntermediateSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=On.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}resolveIntermediateSymlinks(t){let n=z(t);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];s=`${s}/${a}`;let l=this.data.get(s),c=0,u=gr;for(;l&&l.type==="symlink"&&c<u;){if(i.has(s))throw new x("ELOOP",`too many levels of symbolic links, lstat '${t}'`);i.add(s),s=Qn(s,l.target),l=this.data.get(s),c++}if(c>=u)throw new x("ELOOP",`too many levels of symbolic links, lstat '${t}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let n=z(t);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let o of r){s=`${s}/${o}`;let a=this.data.get(s),l=0,c=gr;for(;a&&a.type==="symlink"&&l<c;){if(i.has(s))throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`);i.add(s),s=Qn(s,a.target),a=this.data.get(s),l++}if(l>=c)throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`)}return s}async mkdir(t,n){this.mkdirSync(t,n)}mkdirSync(t,n){U(t,"mkdir");let r=z(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new x("EEXIST",`file already exists, mkdir '${t}'`);if(!n?.recursive)throw new x("EEXIST",`directory already exists, mkdir '${t}'`);return}let s=Zn(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:St,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){U(t,"scandir");let n=z(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new x("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(n),n=Qn(n,r.target),r=this.data.get(n)}if(!r)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(t,n){U(t,"rm");let r=z(t),s=this.data.get(r);if(!s){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);for(let o of i){let a=Gt(r,o);await this.rm(a,n)}}}this.deleteEntry(r)}async cp(t,n,r){U(t,"cp"),U(n,"cp");let s=z(t),i=z(n),o=this.data.get(s);if(!o)throw new x("ENOENT",`no such file or directory, cp '${t}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?o.content.byteLength:On.encode(o.content).byteLength;this.assertCanAllocate(i,a);let l=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.setEntry(i,{...o,content:l})}else this.setEntry(i,{...o});else if(o.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new x("EISDIR",`is a directory, cp '${t}'`);if(qt(s,i))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=Gt(s,l),u=Gt(i,l);await this.cp(c,u,r)}}}async mv(t,n){U(t,"mv"),U(n,"mv");let r=z(t),s=z(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(i.type==="directory"&&qt(r,s))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let o=await this.readdir(r);for(let a of o)await this.mv(Gt(r,a),Gt(s,a));this.deleteEntry(r);return}this.ensureParentDirs(s),this.setEntry(s,i),this.deleteEntry(r)}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,n){return sn(t,n)}async chmod(t,n){U(t,"chmod");let r=z(t),s=this.data.get(r);if(!s)throw new x("ENOENT",`no such file or directory, chmod '${t}'`);s.mode=n}async symlink(t,n){U(n,"symlink");let r=z(n);if(this.data.has(r))throw new x("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:es,mtime:new Date})}async link(t,n){U(t,"link"),U(n,"link");let r=z(t),s=z(n),i=this.data.get(r);if(!i)throw new x("ENOENT",`no such file or directory, link '${t}'`);if(i.type!=="file")throw new x("EPERM",`operation not permitted, link '${t}'`);if(this.data.has(s))throw new x("EEXIST",`file already exists, link '${n}'`);let o=i;"lazy"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(s);let a={type:"file",content:o.content,mode:o.mode,mtime:o.mtime};this.entryIdentities.set(a,this.identityFor(o)),this.setEntry(s,a)}async readlink(t){U(t,"readlink");let n=z(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new x("EINVAL",`invalid argument, readlink '${t}'`);return r.target}async realpath(t){U(t,"realpath");let n=this.resolvePathWithSymlinks(t);if(!this.data.has(n))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return n}async utimes(t,n,r){U(t,"utimes");let s=z(t),i=this.resolvePathWithSymlinks(s),o=this.data.get(i);if(!o)throw new x("ENOENT",`no such file or directory, utimes '${t}'`);o.mtime=r}};var hl="5.1.0(1)-release",pl="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Ti(e){let{pid:t,ppid:n,uid:r,gid:s}=e;return`Name: bash
2
+ import{a as Zt,b as Qt,c as pt}from"./chunks/chunk-353VO5TF.js";import{b as Tt,c as rl,d as sl,e as il}from"./chunks/chunk-6L6OYVLY.js";import{a as es,b as Er}from"./chunks/chunk-5J4S2LP5.js";import{a as Kr,b as Xr,d as yr,e as gr}from"./chunks/chunk-SXQJYLP7.js";import{c as Li,e as tl,f as nl}from"./chunks/chunk-XZ34OGNM.js";import{a as ln}from"./chunks/chunk-SGX4WOAM.js";import{a as _i}from"./chunks/chunk-L2UW7DWF.js";import{a as an,b as Ye,c as Ar}from"./chunks/chunk-DLL7UR66.js";import{a as Sr,b as el}from"./chunks/chunk-654CJKE3.js";import{a as ge}from"./chunks/chunk-O5BHWBYH.js";import{a as ts,b as ns}from"./chunks/chunk-A3C4Z3Q3.js";import{a as Gn,b as Re}from"./chunks/chunk-A6SU3BZX.js";import"./chunks/chunk-57LGFT4S.js";import{d as rn,e as Qn}from"./chunks/chunk-ZUEPJPYA.js";import"./chunks/chunk-STHBFACM.js";import{a as Ja}from"./chunks/chunk-RK2WBVP4.js";import{a as br,b as vt,c as sn,d as rs,e as V,f as Gt,g as U,h as kt,i as on,j as On,k as ht,l as Kn}from"./chunks/chunk-BMBITA6Y.js";import{a as en,b as nt,c as rt,d as Ve,e as Ke,f as Xe,g as H,h as ce,i as st,j as tn,k as Yr,l as C,m as it,n as Oe,o as nn,p as Jr,q as dt}from"./chunks/chunk-TVCZIH6M.js";import{a as B,b as wr,c as Rn,d as _d,e as Jt,f as Ii,g as Zn,h as Ld,i as qt,j as Ti,k as Fd,l as Md}from"./chunks/chunk-GN6CQ3J4.js";import{a as x,b as Bd,c as De,d as Wd}from"./chunks/chunk-T5ZEIOJ3.js";import{a as Ht}from"./chunks/chunk-W5DWRFSU.js";import{a as It}from"./chunks/chunk-FOCWZZDE.js";import{a as Di}from"./chunks/chunk-NCUTH6QL.js";import*as Be from"node:path";var Dn=[{name:"echo",load:async()=>(await import("./chunks/echo-PLLZYM2L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-LG4YGKUE.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-B2NSYQ3N.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-FC3CSHKE.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-DPFWDY25.js")).mkdirCommand},{name:"mktemp",load:async()=>(await import("./chunks/mktemp-SW2AHXZW.js")).mktempCommand,handlesOwnVersion:!0},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-YXYSZD4X.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-W4DF6Z4T.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-AZZM5DCE.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-ZDDVNITX.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-PWCFXEF2.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-CEM7GDB5.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-XUKPG2M4.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-76BPYV5F.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-7XGQ3PL7.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-VYXZQLPZ.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-WK3WACZK.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-7WVM7GV4.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-I3FPUTR7.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-WW5KJPUG.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-WW5KJPUG.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-WW5KJPUG.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-2OPJ5V3D.js")).rgCommand,handlesOwnVersion:!0},{name:"sed",load:async()=>(await import("./chunks/sed-HYSBLGO5.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-TLK6FCHV.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-CB5GO7XH.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-PAEPA27E.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-DTWKU2MC.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-35WER2E2.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-TIQETHSO.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-VI5PIA4A.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-EPOS3MFH.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-IELOWYJG.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-QJBPHRFJ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-J3VOSOMK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-YD5BWFH4.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-VLFTYX2Z.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-UOPIWKKE.js")).split},{name:"column",load:async()=>(await import("./chunks/column-T4LGMRJG.js")).column},{name:"join",load:async()=>(await import("./chunks/join-C2B6NGXH.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-OOWSWHRQ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-3AONTPPM.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SJZQ5W65.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-Z2ZMOOW2.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7OOL2MH6.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-YBSJVBXP.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-VUUMB47B.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-VUUMB47B.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3N762S3K.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-VQEXRD3C.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).falseCommand},{name:"yes",load:async()=>(await import("./chunks/yes-OVJMX6NM.js")).yesCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KPIUNI6K.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-3IVOWP3G.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-GUZMZ645.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-Z3XOLW44.js")).diffCommand,handlesOwnVersion:!0},{name:"date",load:async()=>(await import("./chunks/date-7OEDRA27.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-YC4HFEGC.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-UDR5J2MP.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-N6J6DC6C.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-M2S4FRN4.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-KSNRNE7V.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-JEDX55KS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BLPZJ6MP.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-VJZ4PHQ4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-XH37HMGV.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-4LXS3A44.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-62M75TSG.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-BP5YY5BR.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-YXC4HBTR.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-CESD3CQR.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KR6E7UIR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-VJ6PBBEI.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-ISZXQNJJ.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-ISZXQNJJ.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-ISZXQNJJ.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Dn.push({name:"tar",load:async()=>(await import("./chunks/tar-VZYMNZV2.js")).tarCommand}),Dn.push({name:"yq",load:async()=>(await import("./chunks/yq-KYPU4LQP.js")).yqCommand}),Dn.push({name:"xan",load:async()=>(await import("./chunks/xan-DL576EIT.js")).xanCommand}),Dn.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-XCROTL6G.js")).sqlite3Command}));var ss=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ss.push({name:"python3",load:async()=>(await import("./chunks/python3-6JEP7ZZK.js")).python3Command,handlesOwnVersion:!0}),ss.push({name:"python",load:async()=>(await import("./chunks/python3-6JEP7ZZK.js")).pythonCommand,handlesOwnVersion:!0}));var is=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(is.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-T2WEE4KG.js")).jsExecCommand,handlesOwnVersion:!0}),is.push({name:"node",load:async()=>(await import("./chunks/js-exec-T2WEE4KG.js")).nodeStubCommand}));var al=[{name:"curl",load:async()=>(await import("./chunks/curl-RCRD36LD.js")).curlCommand}],ol=new Map;function os(e){return{name:e.name,handlesOwnVersion:e.handlesOwnVersion,async execute(t,n){let r=ol.get(e.name);if(r||(r=await Re.runTrustedAsync(()=>Er(e.load(),n.signal,`bash: ${e.name} was cancelled before it started
3
+ `)),ol.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await Er(import("./chunks/flag-coverage-6YGO7STE.js"),n.signal,`bash: ${e.name} was cancelled before it started
4
+ `);s(n.coverage,e.name,t)}return r.execute(t,n)}}}function Vd(){return Dn.map(e=>e.name)}function zd(){return al.map(e=>e.name)}function ll(e){return(e?Dn.filter(n=>e.includes(n.name)):Dn).map(os)}function cl(){return al.map(os)}function Ud(){return ss.map(e=>e.name)}function ul(){return ss.map(os)}function jd(){return is.map(e=>e.name)}function fl(){return is.map(os)}var dl=new WeakMap,hl=new WeakSet;function as(e){let t=dl.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),dl.set(e,t),hl.add(t)),t}function pl(e){return hl.has(e)}var ml={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxJsMemoryBytes:67108864,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},qd={...ml,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 Hd(e){return Number.isFinite(e)?Math.min(Math.max(0,Math.floor(e)),4294967295):4294967295}function ls(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?qd:ml;if(!e)return{...n};let r={maxSourceBytes:e.maxSourceBytes??n.maxSourceBytes,maxExecDepth:e.maxExecDepth??n.maxExecDepth,maxCallDepth:e.maxCallDepth??n.maxCallDepth,maxCommandCount:e.maxCommandCount??n.maxCommandCount,maxLoopIterations:e.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??n.maxAwkIterations,maxSedIterations:e.maxSedIterations??n.maxSedIterations,maxJqIterations:e.maxJqIterations??n.maxJqIterations,maxQueryTokens:e.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:e.maxQueryDepth??n.maxQueryDepth,maxQueryElements:e.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:e.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:e.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:e.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:e.maxCsvRows??n.maxCsvRows,maxCsvCells:e.maxCsvCells??n.maxCsvCells,maxWorkUnits:e.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:e.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:e.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:e.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:e.maxLiveBytes??n.maxLiveBytes,maxInputBytes:e.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:e.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:e.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:e.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:e.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:e.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:e.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:e.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:e.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:e.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:e.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??n.maxJsTimeoutMs,maxJsMemoryBytes:Hd(e.maxJsMemoryBytes??n.maxJsMemoryBytes),maxGlobOperations:e.maxGlobOperations??n.maxGlobOperations,maxStringLength:e.maxStringLength??n.maxStringLength,maxArrayElements:e.maxArrayElements??n.maxArrayElements,maxHeredocSize:e.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??n.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??n.maxSourceDepth};for(let s of Object.keys(r)){let i=r[s];if(i!==Number.POSITIVE_INFINITY&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`${s} must be a non-negative safe integer or positive Infinity`)}return r}function Gd(e){let{executionLimits:t,executionLimitProfile:n,fs:r,stdin:s=Ii,...i}=e;return{fs:r,fsIdentity:i.fsIdentity??as(r),cwd:"/",env:new Map,stdin:s,limits:ls(t,n),...i}}function yl(e){return"load"in e&&typeof e.load=="function"}function Zd(e,t,n={}){return{name:e,trusted:n.trusted!==!1,execute:t}}function gl(e){let t=null,n=!1,r=new Set,s=a=>{t=a;for(let l of r)l.resolve(a);r.clear()},i=a=>{n=!1;for(let l of r)l.reject(a);r.clear()},o=()=>{n=!0;let a;try{a=Promise.resolve(e.load())}catch(l){i(l);return}nl.call(a,s,i)};return{name:e.name,trusted:e.trusted!==!1,handlesOwnVersion:e.handlesOwnVersion,async execute(a,l){if(!t){let u,f=new Promise((d,h)=>{u={resolve:d,reject:h},r.add(u)});n||o();try{t=await Er(f,l.signal,`bash: ${e.name} was cancelled before it started
5
+ `)}finally{u&&r.delete(u)}}let c=t;if(!c)throw new Error(`Failed to load command: ${e.name}`);return c.execute(a,l)}}}var wl=Object.freeze(Object.create(null)),cs=class{limits;signal;abortOnUnresolvedCommands;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();unresolvedCommands=new Set;get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(t,n=void 0,r=!1){this.limits=t,this.signal=n,this.abortOnUnresolvedCommands=r}recordUnresolvedCommand(t){this.unresolvedCommands.add(t)}get unresolvedCommandNames(){return[...this.unresolvedCommands]}fail(t){throw this.poisoned??=t,this.poisoned}poisonAfterAbort(t){this.poisoned??=t}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(t=1,n="execution"){return this.consume("work",t,n)}consumeLimited(t,n,r,s=t){this.assertUsable();let i=this.countersByKind.get(t)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new C(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new C(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(t,i+n),this.workUnits+=n,i+n}consumeInput(t,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(t)||t<0||t>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new C(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=t,this.inputBytes}consume(t,n=1,r=t){this.assertUsable();let s=this.countersByKind.get(t)??0,i=t==="commands"?this.commandCount:this.workUnits,o=t==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>o-i)&&this.fail(new C(t==="commands"?`too many commands executed (>${o}), increase executionLimits.maxCommandCount`:`${r}: ${t} work limit exceeded (${o})`,t==="commands"?"commands":"iterations"));let a=i+n;return t==="commands"?this.commandCount=a:this.workUnits=a,this.countersByKind.set(t,s+n),a}reserveBytes(t,n,r){this.assertUsable();let s=typeof t=="string"?t:"live",i=typeof t=="string"?n:t,o=typeof t=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new C(`${o}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let a=!1;return{release:()=>{if(a)return;a=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(t,n,r="execution",s=0,i="text"){this.assertUsable();let o=i==="bytes"?n.length:B(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new C(`${r}: invalid ${t} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new C(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=a,o}accountResult(t,n="execution",r=Number.POSITIVE_INFINITY){let s=t.internalOutputAccounting,i=Math.min(s?.stdout??0,r),o=Math.min(s?.stderr??0,Math.max(0,r-i)),a=this.appendOutput("stdout",t.stdout,n,i,t.stdoutKind==="bytes"||t.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",t.stderr,n,o);return Object.isExtensible(t)?(t.internalOutputAccounting={stdout:a,stderr:l},t):a===0&&l===0?t:{...t,internalOutputAccounting:{stdout:a,stderr:l}}}relinquishOutput(t,n,r){this.assertUsable(),r!==wl&&this.fail(new C(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new C(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=t}enterDepth(t,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??t,o=this.depthByKind.get(t)??0;o>=s&&this.fail(new C(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(t,o+1);let a=!1;return{release:()=>{if(a)return;a=!0;let l=(this.depthByKind.get(t)??1)-1;l<=0?this.depthByKind.delete(t):this.depthByKind.set(t,l)}}}throwIfAborted(t="execution"){this.signal?.aborted&&this.fail(new it("",`bash: ${t} aborted
6
+ `)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new it("",`bash: ${t} exceeded execution deadline (${this.limits.maxExecutionTimeMs}ms)
7
+ `))}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=yr(()=>a({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(gr(i),!o.ok&&(t.push(o.error),Date.now()>=n))break}catch(s){t.push(s)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,t.length>0)throw new AggregateError(t,"execution cleanup failed")}assertExecDepth(t){this.assertUsable(),t>this.limits.maxExecDepth&&this.fail(new C(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function El(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 bl(e,t,n="pipeline"){e.relinquishOutput(t,n,wl)}var In=new TextEncoder;function Qd(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var Ue=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 x("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(t,n){let r=this.data.get(t),s=this.materializedContent(r),i=this.materializedContent(n);if(s===i){this.data.set(t,n);return}let o=this.wouldReleaseBytes(r),a=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(a>this.maxTotalBytes-this.retainedBytes+o)throw new x("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(s instanceof Uint8Array){let l=this.contentReferences.get(s)??0;l<=1?this.contentReferences.delete(s):this.contentReferences.set(s,l-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=a-o,this.data.set(t,n)}deleteEntry(t){let n=this.data.get(t);if(!n)return!1;let r=this.materializedContent(n),s=this.wouldReleaseBytes(n);if(r instanceof Uint8Array){let i=this.contentReferences.get(r)??0;i<=1?this.contentReferences.delete(r):this.contentReferences.set(r,i-1)}return this.retainedBytes-=s,this.data.delete(t)}contentByteLength(t,n){if(t instanceof Uint8Array)return t.byteLength;if(n==="hex")return Math.floor(t.length/2);if(n==="base64"){let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-r)}return n==="binary"||n==="latin1"?t.length: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:vt,mtime:new Date}),t)for(let[r,s]of Object.entries(t))typeof s=="function"?this.writeFileLazy(r,s):Qd(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(t){let n=kt(t);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:vt,mtime:new Date})))}writeFileSync(t,n,r,s){U(t,"write");let i=V(t);this.ensureParentDirs(i);let o=pt(r);this.assertCanAllocate(i,this.contentByteLength(n,o));let a=Zt(n,o);this.setEntry(i,{type:"file",content:a,mode:s?.mode??sn,mtime:s?.mtime??new Date})}writeFileLazy(t,n,r){U(t,"write");let s=V(t);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??sn,mtime:r?.mtime??new Date})}async materializeLazy(t,n){let r=await Re.runTrustedAsync(async()=>n.lazy()),s=typeof r=="string"?In.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=pt(n);return Qt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Qt(n,"binary")}async readFileBuffer(t){U(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, open '${t}'`);if(r.type!=="file")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:In.encode(s.content)}return r.content instanceof Uint8Array?r.content:In.encode(r.content)}async writeFile(t,n,r){this.writeFileSync(t,n,r)}async appendFile(t,n,r){U(t,"append");let s=V(t),i=this.data.get(s);if(i&&i.type==="directory")throw new x("EISDIR",`illegal operation on a directory, write '${t}'`);let o=pt(r),a=this.contentByteLength(n,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:In.encode("content"in l?l.content:"");this.assertCanAllocate(s,c.byteLength+a);let u=Zt(n,o),f=new Uint8Array(c.length+u.length);f.set(c),f.set(u,c.length),this.setEntry(s,{type:"file",content:f,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,n,r)}async exists(t){if(t.includes("\0"))return!1;try{let n=this.resolvePathWithSymlinks(t);return this.data.has(n)}catch{return!1}}async stat(t){U(t,"stat");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=In.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}async lstat(t){U(t,"lstat");let n=this.resolveIntermediateSymlinks(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=In.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=V(t);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];s=`${s}/${a}`;let l=this.data.get(s),c=0,u=br;for(;l&&l.type==="symlink"&&c<u;){if(i.has(s))throw new x("ELOOP",`too many levels of symbolic links, lstat '${t}'`);i.add(s),s=Kn(s,l.target),l=this.data.get(s),c++}if(c>=u)throw new x("ELOOP",`too many levels of symbolic links, lstat '${t}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let n=V(t);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let o of r){s=`${s}/${o}`;let a=this.data.get(s),l=0,c=br;for(;a&&a.type==="symlink"&&l<c;){if(i.has(s))throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`);i.add(s),s=Kn(s,a.target),a=this.data.get(s),l++}if(l>=c)throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`)}return s}async mkdir(t,n){this.mkdirSync(t,n)}async createExclusive(t,n){let r=n.directory?"mkdir":"open";U(t,n.directory?"mkdir":"write");let s=V(t),i=kt(s),o=i==="/"?"/":this.resolvePathWithSymlinks(i),a=ht(o,s.slice(s.lastIndexOf("/")+1));if(this.data.has(a))throw new x("EEXIST",`file already exists, ${r} '${t}'`);if(o!=="/"){let l=this.data.get(o);if(!l)throw new x("ENOENT",`no such file or directory, ${r} '${t}'`);if(l.type!=="directory")throw new x("ENOTDIR",`not a directory, ${r} '${t}'`)}if(n.directory){this.setEntry(a,{type:"directory",mode:n.mode,mtime:new Date});return}this.assertCanAllocate(a,0),this.setEntry(a,{type:"file",content:new Uint8Array(0),mode:n.mode,mtime:new Date})}mkdirSync(t,n){U(t,"mkdir");let r=V(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new x("EEXIST",`file already exists, mkdir '${t}'`);if(!n?.recursive)throw new x("EEXIST",`directory already exists, mkdir '${t}'`);return}let s=kt(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:vt,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){U(t,"scandir");let n=V(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new x("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(n),n=Kn(n,r.target),r=this.data.get(n)}if(!r)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(t,n){U(t,"rm");let r=V(t),s=this.data.get(r);if(!s){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);for(let o of i){let a=ht(r,o);await this.rm(a,n)}}}this.deleteEntry(r)}async cp(t,n,r){U(t,"cp"),U(n,"cp");let s=V(t),i=V(n),o=this.data.get(s);if(!o)throw new x("ENOENT",`no such file or directory, cp '${t}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?o.content.byteLength:In.encode(o.content).byteLength;this.assertCanAllocate(i,a);let l=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.setEntry(i,{...o,content:l})}else this.setEntry(i,{...o});else if(o.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new x("EISDIR",`is a directory, cp '${t}'`);if(Gt(s,i))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=ht(s,l),u=ht(i,l);await this.cp(c,u,r)}}}async mv(t,n){U(t,"mv"),U(n,"mv");let r=V(t),s=V(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(i.type==="directory"&&Gt(r,s))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let o=await this.readdir(r);for(let a of o)await this.mv(ht(r,a),ht(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 on(t,n)}async chmod(t,n){U(t,"chmod");let r=V(t),s=this.data.get(r);if(!s)throw new x("ENOENT",`no such file or directory, chmod '${t}'`);s.mode=n}async symlink(t,n){U(n,"symlink");let r=V(n);if(this.data.has(r))throw new x("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:rs,mtime:new Date})}async link(t,n){U(t,"link"),U(n,"link");let r=V(t),s=V(n),i=this.data.get(r);if(!i)throw new x("ENOENT",`no such file or directory, link '${t}'`);if(i.type!=="file")throw new x("EPERM",`operation not permitted, link '${t}'`);if(this.data.has(s))throw new x("EEXIST",`file already exists, link '${n}'`);let o=i;"lazy"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(s);let a={type:"file",content:o.content,mode:o.mode,mtime:o.mtime};this.entryIdentities.set(a,this.identityFor(o)),this.setEntry(s,a)}async readlink(t){U(t,"readlink");let n=V(t),r=this.data.get(n);if(!r)throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new x("EINVAL",`invalid argument, readlink '${t}'`);return r.target}async realpath(t){U(t,"realpath");let n=this.resolvePathWithSymlinks(t);if(!this.data.has(n))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return n}async utimes(t,n,r){U(t,"utimes");let s=V(t),i=this.resolvePathWithSymlinks(s),o=this.data.get(i);if(!o)throw new x("ENOENT",`no such file or directory, utimes '${t}'`);o.mtime=r}};var Sl="5.1.0(1)-release",Al="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Fi(e){let{pid:t,ppid:n,uid:r,gid:s}=e;return`Name: bash
5
8
  State: R (running)
6
9
  Pid: ${t}
7
10
  PPid: ${n}
8
11
  Uid: ${r} ${r} ${r} ${r}
9
12
  Gid: ${s} ${s} ${s} ${s}
10
- `}function qd(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function Gd(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 Hd(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 Zd(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${pl}
13
+ `}function Kd(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function Xd(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 Yd(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 Jd(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${Al}
11
14
  `),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
12
- `),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 ml(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){qd(e)&&(Gd(e,t),Hd(e),Zd(e,n))}var _i={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(_i))Object.freeze(e);Object.freeze(_i);var Li=_i,Dt=new Set(Object.keys(Li)),yl=new Set(Object.entries(Li).filter(([,e])=>e.kind==="unimplemented").map(([e])=>e)),as=Li;function gl(e){let t=Object.hasOwn(as,e)?as[e]:void 0;return t?.kind==="handler"?t.phase:void 0}function wl(e){let t=Object.hasOwn(as,e)?as[e]:void 0;return t?.kind==="handler"&&t.posixEarly===!0}function ls(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 Qd(e){return e.parts.length===1&&e.parts[0].type==="Literal"?e.parts[0].value:null}function Kd(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)It(n,t)}function It(e,t){for(let n of e.pipelines)Xd(n,t)}function Xd(e,t){for(let n of e.commands)El(n,t)}function El(e,t){switch(e.type){case"SimpleCommand":if(e.name){let n=Qd(e.name);n&&(t.commands.add(n),n==="alias"&&Kd(e.args,t)),Ue(e.name.parts,t)}for(let n of e.args)Ue(n.parts,t);for(let n of e.assignments)if(n.value&&Ue(n.value.parts,t),n.array)for(let r of n.array)Ue(r.parts,t);for(let n of e.redirections)n.target.type==="Word"?Ue(n.target.parts,t):n.target.type==="HereDoc"&&!n.target.quoted&&Ue(n.target.content.parts,t);break;case"If":for(let n of e.clauses){for(let r of n.condition)It(r,t);for(let r of n.body)It(r,t)}if(e.elseBody)for(let n of e.elseBody)It(n,t);break;case"For":if(e.words)for(let n of e.words)Ue(n.parts,t);for(let n of e.body)It(n,t);break;case"CStyleFor":for(let n of e.body)It(n,t);break;case"While":case"Until":for(let n of e.condition)It(n,t);for(let n of e.body)It(n,t);break;case"Case":Ue(e.word.parts,t);for(let n of e.items)for(let r of n.body)It(r,t);break;case"Subshell":case"Group":for(let n of e.body)It(n,t);break;case"ArithmeticCommand":case"ConditionalCommand":break;case"FunctionDef":t.definedFunctions.add(e.name),El(e.body,t);break}}function Ue(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":Ue(n.parts,t);break;case"ParameterExpansion":n.operation&&bl(n.operation,t);break}}function bl(e,t){switch(e.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":Ue(e.word.parts,t);break;case"ErrorIfUnset":e.word&&Ue(e.word.parts,t);break;case"PatternRemoval":Ue(e.pattern.parts,t);break;case"PatternReplacement":Ue(e.pattern.parts,t),e.replacement&&Ue(e.replacement.parts,t);break;case"CaseModification":e.pattern&&Ue(e.pattern.parts,t);break;case"Indirection":e.innerOp&&bl(e.innerOp,t);break}}function cs(e,t){return e===`/bin/${t}`||e===`/usr/bin/${t}`}async function us(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,c=e.commands.get(l);return c&&cs(o,l)?{cmd:c,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&&cs(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 c=await e.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=e.commands.get(t),d=cs(l,t);if(f&&d)return{cmd:f,path:l};if(u){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 fs(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(cs(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 je(e){return{kind:e.kind,elements:new Map(e.elements)}}function ht(e){return new Map(Array.from(e??[],([t,n])=>[t,je(n)]))}function $e(e,t){return e.state.arrays?.get(t)}function br(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 ln(e,t,n){let r=br(e,t,n);return r.kind=n,r}function De(e,t){return e.state.arrays?.has(t)??!1}function ce(e,t,n){return $e(e,t)?.elements.get(String(n))}function cn(e,t,n){return $e(e,t)?.elements.has(String(n))??!1}function H(e,t,n,r,s){let i=br(e,t,s),o=String(n);if(!i.elements.has(o)&&i.elements.size>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(W(r)>e.limits.maxStringLength)throw new C(`array value string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");i.elements.set(o,r)}function Dn(e,t,n,r=!1){let s=new Set(r?[]:$e(e,t)?.elements.keys()??[]);for(let i of n)if(s.add(String(i)),s.size>e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements")}function In(e,t,n){return $e(e,t)?.elements.delete(String(n))??!1}function Sr(e,t){e.state.arrays?.delete(t),e.state.associativeArrays?.delete(t)}function xe(e,t){return Array.from($e(e,t)?.elements.keys()??[]).filter(r=>/^(0|[1-9]\d*)$/.test(r)).map(Number).sort((r,s)=>r-s)}function be(e,t){br(e,t,e.state.associativeArrays?.has(t)?"associative":"indexed").elements.clear()}function Tt(e,t){return Array.from($e(e,t)?.elements.keys()??[]).sort()}function ds(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Mi(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=ds(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=[],c=a?2:1,u=o.slice(c);u&&l.push({type:"Literal",value:u});for(let f=i+1;f<e.parts.length;f++){let d=e.parts[f];d.type==="BraceExpansion"?l.push({type:"Literal",value:Yd(d)}):l.push(d)}return{key:r,valueParts:l,append:a}}function Yd(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 Kn(n.word)}).join(",")}}`}function Kn(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}`:""}`:Kn(r.word)).join(","),t+="}";break;case"TildeExpansion":t+="~",n.user&&(t+=n.user);break}return t}var Ar=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function Sl(e){return Ar.has(e)}var vr=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]);var Jd=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],eh=["braceexpand","hashall","interactive-comments"];function Bi(e){let t=[],n=[...eh.map(r=>({name:r,enabled:!0})),...Jd.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 Xn(e){e.state.env.set("SHELLOPTS",Bi(e.state.options))}var th=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function Wi(e){let t=[];for(let n of th)e[n]&&t.push(n);return t.join(":")}function Vi(e){e.state.env.set("BASHOPTS",Wi(e.state.shoptOptions))}var M={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 Al(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 hs(e,t){let n="",r=t,s=0,i=!1,o,a=l=>l===" "||l===" "||l===`
15
+ `),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>Fi(t)):e.writeFileSync("/proc/self/status",Fi(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 vl(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){if(Kd(e)){let r=eh(e);Xd(r,t),Yd(r),Jd(r,n)}}function eh(e){let t=r=>{try{r()}catch(s){if(s?.code!=="ENOSYS")throw s}},n={mkdirSync:(r,s)=>t(()=>e.mkdirSync(r,s)),writeFileSync:(r,s)=>t(()=>e.writeFileSync(r,s))};return e.writeFileLazy&&(n.writeFileLazy=(r,s)=>t(()=>e.writeFileLazy?.(r,s))),n}var ot=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new Ue,t?.mounts)for(let{mountPoint:n,filesystem:r}of t.mounts)this.mount(n,r)}mount(t,n){this.validateMountPath(t);let r=V(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(t){let n=V(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 o of this.mounts.values()){let a=o.filesystem;if(typeof a.diff!="function")throw new x("EINVAL",`mounted filesystem at '${o.mountPoint}' does not support diff()`);let l=a.diff(),c=u=>{if(n==="vfs")return o.mountPoint==="/"?u:`${o.mountPoint}${u}`;if(typeof a.rootDir!="string")throw new x("EINVAL",`cannot produce a host-space diff: mount at '${o.mountPoint}' has no real root`);return`${a.rootDir}${u}`};for(let u of l.writes)r.push({...u,path:c(u.path)});for(let u=0;u<l.deletions.length;u++)s.push(c(l.deletions[u])),i.push(l.deletionChangedAt?.[u]??0)}return{writes:r,deletions:s,...i.length>0&&{deletionChangedAt:i}}}restamp(t,n,r="full"){let{fs:s,relativePath:i}=this.routePath(t),o=s.restamp;typeof o=="function"&&o.call(s,i,n,r)}isMountPoint(t){let n=V(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){U(t,"access");let n=V(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=V(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 Zn(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=V(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=V(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:vt,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:vt,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.stat(o)}async lstat(t){let n=V(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:vt,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:vt,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.lstat(o)}async mkdir(t,n){let r=V(t);if(this.mounts.has(r)){if(n?.recursive)return;throw new x("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 createExclusive(t,n){let r=V(t),s=n.directory?"mkdir":"open";if(this.mounts.has(r))throw new x("EEXIST",`file already exists, ${s} '${t}'`);let{fs:i,relativePath:o}=this.routePath(t);if(!i.createExclusive)throw new Ja(t,s);let a=kt(o);return a!=="/"&&this.getChildMountPoints(kt(r)).length>0&&!await i.exists(a)&&await i.mkdir(a,{recursive:!0}),i.createExclusive(o,n)}async readdir(t){let n=V(t),r=new Set,s=null,{fs:i,relativePath:o}=this.routePath(t);try{let l=await i.readdir(o);for(let c of l)r.add(c)}catch(l){if(!De(l,"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=V(t);if(this.mounts.has(r))throw new x("EBUSY",`mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new x("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&&Gt(t,n))throw new x("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=V(t);if((await this.stat(t)).isDirectory&&Gt(t,n))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);if(this.mounts.has(r))throw new x("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 on(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=V(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 x("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=V(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=ht(t,o),l=ht(n,o);await this.crossMountCopy(a,l,r)}}else if(s.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,n)}}mkdirSync(t,n){let{fs:r,relativePath:s}=this.routePath(t),i=r;if(!i.mkdirSync)throw new x("ENOSYS",`function not implemented, mkdir '${t}'`);i.mkdirSync(s,n)}writeFileSync(t,n){let{fs:r,relativePath:s}=this.routePath(t),i=r;if(!i.writeFileSync)throw new x("ENOSYS",`function not implemented, write '${t}'`);i.writeFileSync(s,n)}async utimes(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.utimes(i,n,r)}};function us(e){let t={commands:new Set,definedFunctions:new Set,definedAliases:new Set};return Mi(e,t),{commands:[...t.commands],definedFunctions:t.definedFunctions,definedAliases:t.definedAliases}}function th(e){return e.parts.length===1&&e.parts[0].type==="Literal"?e.parts[0].value:null}function nh(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 Mi(e,t){for(let n of e.statements)_t(n,t)}function _t(e,t){for(let n of e.pipelines)rh(n,t)}function rh(e,t){for(let n of e.commands)kl(n,t)}function kl(e,t){switch(e.type){case"SimpleCommand":if(e.name){let n=th(e.name);n&&(t.commands.add(n),n==="alias"&&nh(e.args,t)),je(e.name.parts,t)}for(let n of e.args)je(n.parts,t);for(let n of e.assignments)if(n.value&&je(n.value.parts,t),n.array)for(let r of n.array)je(r.parts,t);for(let n of e.redirections)n.target.type==="Word"?je(n.target.parts,t):n.target.type==="HereDoc"&&!n.target.quoted&&je(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)je(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":je(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),kl(e.body,t);break}}function je(e,t){for(let n of e)switch(n.type){case"CommandSubstitution":Mi(n.body,t);break;case"ProcessSubstitution":Mi(n.body,t);break;case"DoubleQuoted":je(n.parts,t);break;case"ParameterExpansion":n.operation&&xl(n.operation,t);break}}function xl(e,t){switch(e.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":je(e.word.parts,t);break;case"ErrorIfUnset":e.word&&je(e.word.parts,t);break;case"PatternRemoval":je(e.pattern.parts,t);break;case"PatternReplacement":je(e.pattern.parts,t),e.replacement&&je(e.replacement.parts,t);break;case"CaseModification":e.pattern&&je(e.pattern.parts,t);break;case"Indirection":e.innerOp&&xl(e.innerOp,t);break}}function fs(e,t){return e===`/bin/${t}`||e===`/usr/bin/${t}`}async function ds(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,c=e.commands.get(l);return c&&fs(o,l)?{cmd:c,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&&fs(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 c=await e.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=e.commands.get(t),d=fs(l,t);if(f&&d)return{cmd:f,path:l};if(u){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 hs(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(fs(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 qe(e){return{kind:e.kind,elements:new Map(e.elements)}}function mt(e){return new Map(Array.from(e??[],([t,n])=>[t,qe(n)]))}function $e(e,t){return e.state.arrays?.get(t)}function vr(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 cn(e,t,n){let r=vr(e,t,n);return r.kind=n,r}function Ie(e,t){return e.state.arrays?.has(t)??!1}function le(e,t,n){return $e(e,t)?.elements.get(String(n))}function un(e,t,n){return $e(e,t)?.elements.has(String(n))??!1}function G(e,t,n,r,s){let i=vr(e,t,s),o=String(n);if(!i.elements.has(o)&&i.elements.size>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(r)>e.limits.maxStringLength)throw new C(`array value string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");i.elements.set(o,r)}function Tn(e,t,n,r=!1){let s=new Set(r?[]:$e(e,t)?.elements.keys()??[]);for(let i of n)if(s.add(String(i)),s.size>e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements")}function _n(e,t,n){return $e(e,t)?.elements.delete(String(n))??!1}function kr(e,t){e.state.arrays?.delete(t),e.state.associativeArrays?.delete(t)}function xe(e,t){return Array.from($e(e,t)?.elements.keys()??[]).filter(r=>/^(0|[1-9]\d*)$/.test(r)).map(Number).sort((r,s)=>r-s)}function be(e,t){vr(e,t,e.state.associativeArrays?.has(t)?"associative":"indexed").elements.clear()}function Lt(e,t){return Array.from($e(e,t)?.elements.keys()??[]).sort()}function ps(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Bi(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=ps(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=[],c=a?2:1,u=o.slice(c);u&&l.push({type:"Literal",value:u});for(let f=i+1;f<e.parts.length;f++){let d=e.parts[f];d.type==="BraceExpansion"?l.push({type:"Literal",value:sh(d)}):l.push(d)}return{key:r,valueParts:l,append:a}}function sh(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 Xn(n.word)}).join(",")}}`}function Xn(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}`:""}`:Xn(r.word)).join(","),t+="}";break;case"TildeExpansion":t+="~",n.user&&(t+=n.user);break}return t}var xr=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function Pl(e){return xr.has(e)}var Pr=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]);var ih=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],oh=["braceexpand","hashall","interactive-comments"];function Wi(e){let t=[],n=[...oh.map(r=>({name:r,enabled:!0})),...ih.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 Yn(e){e.state.env.set("SHELLOPTS",Wi(e.state.options))}var ah=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function Vi(e){let t=[];for(let n of ah)e[n]&&t.push(n);return t.join(":")}function zi(e){e.state.env.set("BASHOPTS",Vi(e.state.shoptOptions))}var M={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 $l(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 ms(e,t){let n="",r=t,s=0,i=!1,o,a=l=>l===" "||l===" "||l===`
13
16
  `||l===";"||l==="&"||l==="|"||l==="<"||l===">"||l==="("||l===")";for(;r<e.length;){let l=e[r];if(l==="'"){let c=s>0;for(c||(i=!0),c&&(n+=l),r++;r<e.length&&e[r]!=="'";)n+=e[r],r++;r<e.length?(c&&(n+=e[r]),r++):o=l;continue}if(l==='"'){let c=s>0;for(c||(i=!0),c&&(n+=l),r++;r<e.length&&e[r]!=='"';){if(e[r]==="\\"&&r+1<e.length){if(c){n+=e.slice(r,r+2),r+=2;continue}let u=e[r+1];if(u==="$"||u==="`"||u==='"'||u==="\\"||u===`
14
17
  `){r+=2,u!==`
15
18
  `&&(n+=u);continue}}n+=e[r],r++}r<e.length?(c&&(n+=e[r]),r++):o=l;continue}if(l==="\\"&&r+1<e.length){if(s>0){n+=e.slice(r,r+2),r+=2;continue}i=!0;let c=e[r+1];c!==`
16
- `&&(n+=c),r+=2;continue}if(s===0&&(l==="$"||l==="<"||l===">")&&e[r+1]==="("){n+=`${l}(`,s=1,r+=2;continue}if(s===0&&a(l))break;s>0&&(l==="("?s++:l===")"&&s--),n+=l,r++}return{delim:n,endPos:r,quoted:i,unclosedQuote:o,unclosedSubstitution:s>0}}function nh(e,t,n){let r=t+1;for(let{delim:s,stripTabs:i}of n)for(;;){if(r>=e.length)return e.length;let o=e.indexOf(`
17
- `,r);o===-1&&(o=e.length);let a=e.slice(r,o);if(i&&(a=a.replace(/^\t+/,"")),a===s){r=o+1;break}if(o>=e.length)return e.length;r=o+1}return Math.min(r,e.length)}function vl(e,t,n){let r=1,s=t,i=!1,o=!1,a=0,l=!1,c="",u=[],f=0;for(;s<e.length&&r>0;){let d=e[s];if(i)d==="'"&&(i=!1);else if(o)d==="\\"&&s+1<e.length?s++:d==='"'&&(o=!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 h=s+2,p=!1;for(e[h]==="-"&&(p=!0,h++);e[h]===" "||e[h]===" ";)h++;let{delim:m,endPos:E,unclosedQuote:S,unclosedSubstitution:g}=hs(e,h);if(S&&n(`unexpected EOF while looking for matching \`${S}'`),g&&n("unexpected EOF while looking for matching `)'"),m.length>0){u.push({delim:m,stripTabs:p}),c="",s=E;continue}}if(d===`
18
- `&&u.length>0){let h=nh(e,s,u);u.length=0,c="",s=h;continue}d==="'"?(i=!0,c=""):d==='"'?(o=!0,c=""):d==="\\"&&s+1<e.length?(s++,c=""):/[a-zA-Z_]/.test(d)?c+=d:(c==="case"?(a++,l=!1):c==="in"&&a>0?l=!0:c==="esac"&&a>0&&(a--,l=!1),c="",d==="("?s>0&&e[s-1]==="$"?r++:l||r++:d===")"?l?l=!1:r--:d===";"&&a>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 kl(e,t,n,r){let s=t+2,i=vl(e,s,r),o=e.slice(s,i),l=n().parse(o);return{part:M.commandSubstitution(l,!1),endIndex:i+1}}function xl(e,t,n,r){let s=e[t]==="<"?"input":"output",i=t+2,o=vl(e,i,r),a=n().parse(e.slice(i,o));return{part:M.processSubstitution(a,s),endIndex:o+1}}function Pl(e,t,n,r,s){let o=t+1,a="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let u=e[o+1];u==="$"||u==="`"||u==="\\"||u===`
19
+ `&&(n+=c),r+=2;continue}if(s===0&&(l==="$"||l==="<"||l===">")&&e[r+1]==="("){n+=`${l}(`,s=1,r+=2;continue}if(s===0&&a(l))break;s>0&&(l==="("?s++:l===")"&&s--),n+=l,r++}return{delim:n,endPos:r,quoted:i,unclosedQuote:o,unclosedSubstitution:s>0}}function lh(e,t,n){let r=t+1;for(let{delim:s,stripTabs:i}of n)for(;;){if(r>=e.length)return e.length;let o=e.indexOf(`
20
+ `,r);o===-1&&(o=e.length);let a=e.slice(r,o);if(i&&(a=a.replace(/^\t+/,"")),a===s){r=o+1;break}if(o>=e.length)return e.length;r=o+1}return Math.min(r,e.length)}function Cl(e,t,n){let r=1,s=t,i=!1,o=!1,a=0,l=!1,c="",u=[],f=0;for(;s<e.length&&r>0;){let d=e[s];if(i)d==="'"&&(i=!1);else if(o)d==="\\"&&s+1<e.length?s++:d==='"'&&(o=!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 h=s+2,p=!1;for(e[h]==="-"&&(p=!0,h++);e[h]===" "||e[h]===" ";)h++;let{delim:m,endPos:E,unclosedQuote:b,unclosedSubstitution:y}=ms(e,h);if(b&&n(`unexpected EOF while looking for matching \`${b}'`),y&&n("unexpected EOF while looking for matching `)'"),m.length>0){u.push({delim:m,stripTabs:p}),c="",s=E;continue}}if(d===`
21
+ `&&u.length>0){let h=lh(e,s,u);u.length=0,c="",s=h;continue}d==="'"?(i=!0,c=""):d==='"'?(o=!0,c=""):d==="\\"&&s+1<e.length?(s++,c=""):/[a-zA-Z_]/.test(d)?c+=d:(c==="case"?(a++,l=!1):c==="in"&&a>0?l=!0:c==="esac"&&a>0&&(a--,l=!1),c="",d==="("?s>0&&e[s-1]==="$"?r++:l||r++:d===")"?l?l=!1:r--:d===";"&&a>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 Nl(e,t,n,r){let s=t+2,i=Cl(e,s,r),o=e.slice(s,i),l=n().parse(o);return{part:M.commandSubstitution(l,!1),endIndex:i+1}}function Rl(e,t,n,r){let s=e[t]==="<"?"input":"output",i=t+2,o=Cl(e,i,r),a=n().parse(e.slice(i,o));return{part:M.processSubstitution(a,s),endIndex:o+1}}function Ol(e,t,n,r,s){let o=t+1,a="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let u=e[o+1];u==="$"||u==="`"||u==="\\"||u===`
19
22
  `||n&&u==='"'?(u!==`
20
- `&&(a+=u),o+=2):(a+=e[o],o++)}else a+=e[o],o++;o>=e.length&&s("unexpected EOF while looking for matching ``'");let c=r().parse(a);return{part:M.commandSubstitution(c,!0),endIndex:o+1}}var rh=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 it=class extends Error{line;column;constructor(t,n,r){super(`line ${n}: ${t}`),this.line=n,this.column=r,this.name="LexerError"}},zi=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]]),sh=new Set(zi.values());function Ui(e){return sh.has(e)}function $l(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 Cl(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 ih=[[";",";","&",w.SEMI_SEMI_AND],["<","<","<",w.TLESS],["&",">",">",w.AND_DGREAT]],oh=[["[","[",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]],ah=new Map([["|",w.PIPE],["&",w.AMP],[";",w.SEMICOLON],["(",w.LPAREN],[")",w.RPAREN],["<",w.LESS],[">",w.GREAT]]);function lh(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Nl(e){return e===" "||e===" "||e===`
21
- `||e===";"||e==="&"||e==="|"||e==="("||e===")"||e==="<"||e===">"}var ps=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];pendingHeredocDelimiterMode;dparenDepth=0;maxHeredocSize;constructor(t,n){this.input=t,this.maxHeredocSize=n?.maxHeredocSize??rh}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 o=t[r];if(o===" "||o===" ")r++,s++;else if(o==="\\"&&t[r+1]===`
23
+ `&&(a+=u),o+=2):(a+=e[o],o++)}else a+=e[o],o++;o>=e.length&&s("unexpected EOF while looking for matching ``'");let c=r().parse(a);return{part:M.commandSubstitution(c,!0),endIndex:o+1}}var ch=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 at=class extends Error{line;column;constructor(t,n,r){super(`line ${n}: ${t}`),this.line=n,this.column=r,this.name="LexerError"}},Ui=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]]),uh=new Set(Ui.values());function ji(e){return uh.has(e)}function Dl(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 Il(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 fh=[[";",";","&",w.SEMI_SEMI_AND],["<","<","<",w.TLESS],["&",">",">",w.AND_DGREAT]],dh=[["[","[",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]],hh=new Map([["|",w.PIPE],["&",w.AMP],[";",w.SEMICOLON],["(",w.LPAREN],[")",w.RPAREN],["<",w.LESS],[">",w.GREAT]]);function ph(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Tl(e){return e===" "||e===" "||e===`
24
+ `||e===";"||e==="&"||e==="|"||e==="("||e===")"||e==="<"||e===">"}var ys=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];pendingHeredocDelimiterMode;dparenDepth=0;maxHeredocSize;constructor(t,n){this.input=t,this.maxHeredocSize=n?.maxHeredocSize??ch}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 o=t[r];if(o===" "||o===" ")r++,s++;else if(o==="\\"&&t[r+1]===`
22
25
  `)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],o=t[n+1],a=t[n+2],l=this.pendingHeredocDelimiterMode;if(this.pendingHeredocDelimiterMode=void 0,l!==void 0&&i!==`
23
26
  `&&!(i==="#"&&this.dparenDepth===0))return this.readHeredocDelimiterToken(n,r,s,l);if(i==="#"&&this.dparenDepth===0)return this.readComment(n,r,s);if(i===`
24
27
  `)return this.pos=n+1,this.line++,this.column=1,{type:w.NEWLINE,value:`
25
- `,start:n,end:n+1,line:r,column:s};if(i==="<"&&o==="<"&&a==="-")return this.pos=n+3,this.column=s+3,this.pendingHeredocDelimiterMode=!0,this.makeToken(w.DLESSDASH,"<<-",n,r,s);for(let[u,f,d,h]of ih)if(i===u&&o===f&&a===d)return this.pos=n+3,this.column=s+3,this.makeToken(h,u+f+d,n,r,s);if(i==="<"&&o==="<")return this.pos=n+2,this.column=s+2,this.pendingHeredocDelimiterMode=!1,this.makeToken(w.DLESS,"<<",n,r,s);if(i==="("&&o==="("){let u=this.tokens[this.tokens.length-1];return this.dparenDepth===0&&u?.end===n&&(u.type===w.LESS||u.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===")"&&o===")")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[u,f,d]of oh)if(!(u==="("&&f==="("||u===")"&&f===")")&&!(this.dparenDepth>0&&u===";"&&(d===w.DSEMI||d===w.SEMI_AND||d===w.SEMI_SEMI_AND))&&i===u&&o===f){if(d===w.DBRACK_START||d===w.DBRACK_END){let h=t[n+2];if(h!==void 0&&h!==" "&&h!==" "&&h!==`
26
- `&&h!==";"&&h!=="&"&&h!=="|"&&h!=="("&&h!==")"&&h!=="<"&&h!==">")break}return this.pos=n+2,this.column=s+2,this.makeToken(d,u+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 c=ah.get(i);if(c!==void 0)return this.pos=n+1,this.column=s+1,this.makeToken(c,i,n,r,s);if(i==="{"){let u=this.scanFdVariable(n);return u!==null?(this.pos=u.end,this.column=s+(u.end-n),{type:w.FD_VARIABLE,value:u.varname,start:n,end:u.end,line:r,column:s}):o==="}"?(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):o!==void 0&&o!==" "&&o!==" "&&o!==`
28
+ `,start:n,end:n+1,line:r,column:s};if(i==="<"&&o==="<"&&a==="-")return this.pos=n+3,this.column=s+3,this.pendingHeredocDelimiterMode=!0,this.makeToken(w.DLESSDASH,"<<-",n,r,s);for(let[u,f,d,h]of fh)if(i===u&&o===f&&a===d)return this.pos=n+3,this.column=s+3,this.makeToken(h,u+f+d,n,r,s);if(i==="<"&&o==="<")return this.pos=n+2,this.column=s+2,this.pendingHeredocDelimiterMode=!1,this.makeToken(w.DLESS,"<<",n,r,s);if(i==="("&&o==="("){let u=this.tokens[this.tokens.length-1];return this.dparenDepth===0&&u?.end===n&&(u.type===w.LESS||u.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===")"&&o===")")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[u,f,d]of dh)if(!(u==="("&&f==="("||u===")"&&f===")")&&!(this.dparenDepth>0&&u===";"&&(d===w.DSEMI||d===w.SEMI_AND||d===w.SEMI_SEMI_AND))&&i===u&&o===f){if(d===w.DBRACK_START||d===w.DBRACK_END){let h=t[n+2];if(h!==void 0&&h!==" "&&h!==" "&&h!==`
29
+ `&&h!==";"&&h!=="&"&&h!=="|"&&h!=="("&&h!==")"&&h!=="<"&&h!==">")break}return this.pos=n+2,this.column=s+2,this.makeToken(d,u+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 c=hh.get(i);if(c!==void 0)return this.pos=n+1,this.column=s+1,this.makeToken(c,i,n,r,s);if(i==="{"){let u=this.scanFdVariable(n);return u!==null?(this.pos=u.end,this.column=s+(u.end-n),{type:w.FD_VARIABLE,value:u.varname,start:n,end:u.end,line:r,column:s}):o==="}"?(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):o!==void 0&&o!==" "&&o!==" "&&o!==`
27
30
  `?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==="!"?o==="="?(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 o=/[a-zA-Z_]/.test(i),a=i==="!"||i==="[";if(!o&&!a)return!1;let l=s;for(;l<r&&/[a-zA-Z0-9_\-.]/.test(n[l]);)l++;if(l===s)return a;let c=l;for(;c<r&&(n[c]===" "||n[c]===" ");)c++;if(c>=r)return!1;let u=n[c];if(u==="="&&n[c+1]!=="="||u===`
28
31
  `||l===c&&/[+\-*/%<>&|^!~?:]/.test(u)&&u!=="-"||u===")"&&n[c+1]===")")return!1;if(c>l&&(u==="-"||u==='"'||u==="'"||u==="$"||/[a-zA-Z_/.]/.test(u))){let f=c;for(;f<r&&n[f]!==`
29
32
  `;){if(n[f]===")")return!0;f++}return!1}if(u===")"){let f=c+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,o=this.pos;for(;o<i&&s[o]!==`
30
- `;)o++;let a=s.slice(t,o);return this.pos=o,this.column=r+(o-t),{type:w.COMMENT,value:a,start:t,end:o,line:n,column:r}}readWord(t,n,r){let s=this.input,i=s.length,o=this.pos,a=o;for(;o<i;){let y=s[o];if(y===" "||y===" "||y===`
31
- `||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"||y==="'"||y==='"'||y==="\\"||y==="$"||y==="`"||y==="{"||y==="}"||y==="~"||y==="*"||y==="?"||y==="[")break;o++}if(o>a){let y=s[o];if(!(y==="("&&o>a&&"@*+?!".includes(s[o-1]))){if(o>=i||y===" "||y===" "||y===`
32
- `||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"){let b=s.slice(a,o);this.pos=o,this.column=r+(o-a);let A=zi.get(b);if(A!==void 0)return{type:A,value:b,start:t,end:o,line:n,column:r};let k=Cl(b);return k>0&&$l(b.slice(0,k))?{type:w.ASSIGNMENT_WORD,value:b,start:t,end:o,line:n,column:r}:/^[0-9]+$/.test(b)?{type:w.NUMBER,value:b,start:t,end:o,line:n,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)?{type:w.NAME,value:b,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}:{type:w.WORD,value:b,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}}}}o=this.pos;let l=this.column,c=this.line,u="",f=!1,d=!1,h=!1,p=!1,m=s[o]==='"'||s[o]==="'",E=!1,S=0;for(;o<i;){let y=s[o];if(!h&&!p){if(y==="("&&u.length>0&&"@*+?!".includes(u[u.length-1])){let b=this.scanExtglobPattern(o);if(b!==null){u+=b.content,o=b.end,l+=b.content.length;continue}}if(y==="["&&S===0){if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){let b=o+1<i?s[o+1]:"";if(b==="^"||b==="!"){u+=y,o++,l++;continue}S=1,u+=y,o++,l++;continue}}else if(y==="["&&S>0){u.length>0&&u[u.length-1]!=="\\"&&S++,u+=y,o++,l++;continue}else if(y==="]"&&S>0){u.length>0&&u[u.length-1]!=="\\"&&S--,u+=y,o++,l++;continue}if(S>0){if(y===`
33
- `)break;u+=y,o++,l++;continue}if(y===" "||y===" "||y===`
34
- `||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">")break}if(y==="$"&&o+1<i&&s[o+1]==="'"&&!h&&!p){for(u+="$'",o+=2,l+=2;o<i&&s[o]!=="'";)s[o]==="\\"&&o+1<i?(u+=s[o]+s[o+1],o+=2,l+=2):(u+=s[o],o++,l++);o<i&&(u+="'",o++,l++);continue}if(y==="$"&&o+1<i&&s[o+1]==='"'&&!h&&!p){o++,l++,p=!0,f=!0,u===""&&(m=!0),o++,l++;continue}if(y==="'"&&!p){if(h)if(h=!1,!m||E)u+=y;else{let b=o+1<i?s[o+1]:"";b&&!Nl(b)&&b!=="'"&&(b==='"'?(E=!0,u+=y,d=!1,f=!1):(E=!0,u+=y))}else h=!0,m&&!E?(d=!0,f=!0):u+=y;o++,l++;continue}if(y==='"'&&!h){if(p)if(p=!1,!m||E)u+=y;else{let b=o+1<i?s[o+1]:"";b&&!Nl(b)&&b!=='"'&&(b==="'"?(E=!0,u+=y,d=!1,f=!1):(E=!0,u+=y))}else p=!0,m&&!E?f=!0:u+=y;o++,l++;continue}if(y==="\\"&&!h&&o+1<i){let b=s[o+1];if(b===`
35
- `){o+=2,c++,l=1;continue}if(p){if(b==='"'||b==="\\"||b==="$"||b==="`"||b===`
36
- `){if(b===`
37
- `){o+=2,l=1,c++;continue}u+=y+b,o+=2,l+=2;continue}}else{u+=y+b,o+=2,l+=2;continue}}if(y==="$"&&o+1<i&&s[o+1]==="("&&!h){u+=y,o++,l++,u+=s[o],o++,l++;let b=1,A=!1,k=!1,v=0,$=!1,O="",P=[],N=s[o]==="("&&!this.dollarDparenIsSubshell(o),D=N?1:0;for(;b>0&&o<i;){let V=s[o];if(u+=V,A)V==="'"&&(A=!1);else if(k)V==="\\"&&o+1<i?(u+=s[o+1],o++,l++):V==='"'&&(k=!1);else{if(V==="("&&s[o+1]==="("?D++:V===")"&&s[o+1]===")"&&D>0&&D--,D===0&&V==="<"&&s[o+1]==="<"&&s[o+2]!=="<"){let X=o+2,R=!1;for(s[X]==="-"&&(R=!0,X++);s[X]===" "||s[X]===" ";)X++;let{delim:j,endPos:q,unclosedQuote:I,unclosedSubstitution:T}=hs(s,X);if(I)throw new it(`unexpected EOF while looking for matching \`${I}'`,c,l);if(T)throw new it("unexpected EOF while looking for matching `)'",c,l);if(j.length>0){u+=s.slice(o+1,q),l+=q-o,P.push({delim:j,stripTabs:R}),o=q;continue}}if(V===`
38
- `&&P.length>0){c++,l=0;let X=o+1;for(let{delim:R,stripTabs:j}of P)for(;!(X>=i);){let q=s.indexOf(`
39
- `,X);q===-1&&(q=i);let I=s.slice(X,q),T=j?I.replace(/^\t+/,""):I;u+=s.slice(X,Math.min(q+1,i)),q<i&&c++;let B=q>=i;if(X=q+1,T===R||B)break}P.length=0,l=0,o=Math.min(X,i);continue}if(V==="'")A=!0,O="";else if(V==='"')k=!0,O="";else if(V==="\\"&&o+1<i)u+=s[o+1],o++,l++,O="";else if(V==="$"&&o+1<i&&s[o+1]==="{"){o++,l++,u+=s[o],o++,l++;let X=1,R=!1,j=!1;for(;X>0&&o<i;){let q=s[o];if(q==="\\"&&o+1<i&&!R){u+=q,o++,l++,u+=s[o],o++,l++;continue}u+=q,R?q==="'"&&(R=!1):j?q==='"'&&(j=!1):q==="'"?R=!0:q==='"'?j=!0:q==="{"?X++:q==="}"&&X--,q===`
40
- `?(c++,l=0):l++,o++}O="";continue}else if(V==="#"&&!N&&(O===""||/\s/.test(s[o-1]||""))){for(;o+1<i&&s[o+1]!==`
41
- `;)o++,l++,u+=s[o];O=""}else/[a-zA-Z_]/.test(V)?O+=V:(O==="case"?(v++,$=!1):O==="in"&&v>0?$=!0:O==="esac"&&v>0&&(v--,$=!1),O="",V==="("?o>0&&s[o-1]==="$"?b++:$||b++:V===")"?$?$=!1:b--:V===";"&&v>0&&(o+1<i&&s[o+1]===";"||o+1<i&&s[o+1]==="&")&&($=!0))}V===`
42
- `&&(c++,l=0,O=""),o++,l++}continue}if(y==="$"&&o+1<i&&s[o+1]==="["&&!h){u+=y,o++,l++,u+=s[o],o++,l++;let b=1;for(;b>0&&o<i;){let A=s[o];u+=A,A==="["?b++:A==="]"?b--:A===`
43
- `&&(c++,l=0),o++,l++}continue}if(y==="$"&&o+1<i&&s[o+1]==="{"&&!h){u+=y,o++,l++,u+=s[o],o++,l++;let b=1,A=!1,k=!1,v=c,$=l,O=c,P=l;for(;b>0&&o<i;){let N=s[o];if(N==="\\"&&o+1<i&&s[o+1]===`
44
- `){o+=2,c++,l=1;continue}if(N==="\\"&&o+1<i&&!A){u+=N,o++,l++,u+=s[o],o++,l++;continue}u+=N,A?N==="'"&&(A=!1):k?N==='"'&&(k=!1):N==="'"?(A=!0,v=c,$=l):N==='"'?(k=!0,O=c,P=l):N==="{"?b++:N==="}"&&b--,N===`
45
- `&&(c++,l=0),o++,l++}if(A)throw new it("unexpected EOF while looking for matching `''",v,$);if(k)throw new it("unexpected EOF while looking for matching `\"'",O,P);continue}if(y==="$"&&o+1<i&&!h){let b=s[o+1];if(b==="#"||b==="?"||b==="$"||b==="!"||b==="@"||b==="*"||b==="-"||b>="0"&&b<="9"){u+=y+b,o+=2,l+=2;continue}}if(y==="`"&&!h){for(u+=y,o++,l++;o<i&&s[o]!=="`";){let b=s[o];u+=b,b==="\\"&&o+1<i&&(u+=s[o+1],o++,l++),b===`
46
- `&&(c++,l=0),o++,l++}o<i&&(u+=s[o],o++,l++);continue}u+=y,o++,y===`
47
- `?(c++,l=1):l++}if(this.pos=o,this.column=l,this.line=c,E&&m&&(u=s[t]+u,f=!1,d=!1),h||p){let y=h?"'":'"';throw new it(`unexpected EOF while looking for matching \`${y}'`,n,r)}if(!m&&u.length>=2){if(u[0]==="'"&&u[u.length-1]==="'"){let y=u.slice(1,-1);!y.includes("'")&&!y.includes('"')&&(u=y,f=!0,d=!0)}else if(u[0]==='"'&&u[u.length-1]==='"'){let y=u.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||(u=y,f=!0,d=!1)}}if(u==="")return{type:w.WORD,value:"",start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d};let g=zi.get(u);if(!f&&g!==void 0)return{type:g,value:u,start:t,end:o,line:n,column:r};if(!m){let y=Cl(u);if(y>0&&$l(u.slice(0,y)))return{type:w.ASSIGNMENT_WORD,value:u,start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:w.NUMBER,value:u,start:t,end:o,line:n,column:r}:lh(u)?{type:w.NAME,value:u,start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d}:{type:w.WORD,value:u,start:t,end:o,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="",o=!1;for(;this.pos<this.input.length;){let a="",l="",c="";for(;;){for(a="";this.pos<this.input.length&&this.input[this.pos]!==`
33
+ `;)o++;let a=s.slice(t,o);return this.pos=o,this.column=r+(o-t),{type:w.COMMENT,value:a,start:t,end:o,line:n,column:r}}readWord(t,n,r){let s=this.input,i=s.length,o=this.pos,a=o;for(;o<i;){let g=s[o];if(g===" "||g===" "||g===`
34
+ `||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"||g==="'"||g==='"'||g==="\\"||g==="$"||g==="`"||g==="{"||g==="}"||g==="~"||g==="*"||g==="?"||g==="[")break;o++}if(o>a){let g=s[o];if(!(g==="("&&o>a&&"@*+?!".includes(s[o-1]))){if(o>=i||g===" "||g===" "||g===`
35
+ `||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"){let S=s.slice(a,o);this.pos=o,this.column=r+(o-a);let v=Ui.get(S);if(v!==void 0)return{type:v,value:S,start:t,end:o,line:n,column:r};let k=Il(S);return k>0&&Dl(S.slice(0,k))?{type:w.ASSIGNMENT_WORD,value:S,start:t,end:o,line:n,column:r}:/^[0-9]+$/.test(S)?{type:w.NUMBER,value:S,start:t,end:o,line:n,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(S)?{type:w.NAME,value:S,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}:{type:w.WORD,value:S,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}}}}o=this.pos;let l=this.column,c=this.line,u="",f=!1,d=!1,h=!1,p=!1,m=s[o]==='"'||s[o]==="'",E=!1,b=0;for(;o<i;){let g=s[o];if(!h&&!p){if(g==="("&&u.length>0&&"@*+?!".includes(u[u.length-1])){let S=this.scanExtglobPattern(o);if(S!==null){u+=S.content,o=S.end,l+=S.content.length;continue}}if(g==="["&&b===0){if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){let S=o+1<i?s[o+1]:"";if(S==="^"||S==="!"){u+=g,o++,l++;continue}b=1,u+=g,o++,l++;continue}}else if(g==="["&&b>0){u.length>0&&u[u.length-1]!=="\\"&&b++,u+=g,o++,l++;continue}else if(g==="]"&&b>0){u.length>0&&u[u.length-1]!=="\\"&&b--,u+=g,o++,l++;continue}if(b>0){if(g===`
36
+ `)break;u+=g,o++,l++;continue}if(g===" "||g===" "||g===`
37
+ `||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">")break}if(g==="$"&&o+1<i&&s[o+1]==="'"&&!h&&!p){for(u+="$'",o+=2,l+=2;o<i&&s[o]!=="'";)s[o]==="\\"&&o+1<i?(u+=s[o]+s[o+1],o+=2,l+=2):(u+=s[o],o++,l++);o<i&&(u+="'",o++,l++);continue}if(g==="$"&&o+1<i&&s[o+1]==='"'&&!h&&!p){o++,l++,p=!0,f=!0,u===""&&(m=!0),o++,l++;continue}if(g==="'"&&!p){if(h)if(h=!1,!m||E)u+=g;else{let S=o+1<i?s[o+1]:"";S&&!Tl(S)&&S!=="'"&&(S==='"'?(E=!0,u+=g,d=!1,f=!1):(E=!0,u+=g))}else h=!0,m&&!E?(d=!0,f=!0):u+=g;o++,l++;continue}if(g==='"'&&!h){if(p)if(p=!1,!m||E)u+=g;else{let S=o+1<i?s[o+1]:"";S&&!Tl(S)&&S!=='"'&&(S==="'"?(E=!0,u+=g,d=!1,f=!1):(E=!0,u+=g))}else p=!0,m&&!E?f=!0:u+=g;o++,l++;continue}if(g==="\\"&&!h&&o+1<i){let S=s[o+1];if(S===`
38
+ `){o+=2,c++,l=1;continue}if(p){if(S==='"'||S==="\\"||S==="$"||S==="`"||S===`
39
+ `){if(S===`
40
+ `){o+=2,l=1,c++;continue}u+=g+S,o+=2,l+=2;continue}}else{u+=g+S,o+=2,l+=2;continue}}if(g==="$"&&o+1<i&&s[o+1]==="("&&!h){u+=g,o++,l++,u+=s[o],o++,l++;let S=1,v=!1,k=!1,A=0,$=!1,R="",P=[],N=s[o]==="("&&!this.dollarDparenIsSubshell(o),I=N?1:0;for(;S>0&&o<i;){let z=s[o];if(u+=z,v)z==="'"&&(v=!1);else if(k)z==="\\"&&o+1<i?(u+=s[o+1],o++,l++):z==='"'&&(k=!1);else{if(z==="("&&s[o+1]==="("?I++:z===")"&&s[o+1]===")"&&I>0&&I--,I===0&&z==="<"&&s[o+1]==="<"&&s[o+2]!=="<"){let X=o+2,O=!1;for(s[X]==="-"&&(O=!0,X++);s[X]===" "||s[X]===" ";)X++;let{delim:j,endPos:q,unclosedQuote:T,unclosedSubstitution:_}=ms(s,X);if(T)throw new at(`unexpected EOF while looking for matching \`${T}'`,c,l);if(_)throw new at("unexpected EOF while looking for matching `)'",c,l);if(j.length>0){u+=s.slice(o+1,q),l+=q-o,P.push({delim:j,stripTabs:O}),o=q;continue}}if(z===`
41
+ `&&P.length>0){c++,l=0;let X=o+1;for(let{delim:O,stripTabs:j}of P)for(;!(X>=i);){let q=s.indexOf(`
42
+ `,X);q===-1&&(q=i);let T=s.slice(X,q),_=j?T.replace(/^\t+/,""):T;u+=s.slice(X,Math.min(q+1,i)),q<i&&c++;let W=q>=i;if(X=q+1,_===O||W)break}P.length=0,l=0,o=Math.min(X,i);continue}if(z==="'")v=!0,R="";else if(z==='"')k=!0,R="";else if(z==="\\"&&o+1<i)u+=s[o+1],o++,l++,R="";else if(z==="$"&&o+1<i&&s[o+1]==="{"){o++,l++,u+=s[o],o++,l++;let X=1,O=!1,j=!1;for(;X>0&&o<i;){let q=s[o];if(q==="\\"&&o+1<i&&!O){u+=q,o++,l++,u+=s[o],o++,l++;continue}u+=q,O?q==="'"&&(O=!1):j?q==='"'&&(j=!1):q==="'"?O=!0:q==='"'?j=!0:q==="{"?X++:q==="}"&&X--,q===`
43
+ `?(c++,l=0):l++,o++}R="";continue}else if(z==="#"&&!N&&(R===""||/\s/.test(s[o-1]||""))){for(;o+1<i&&s[o+1]!==`
44
+ `;)o++,l++,u+=s[o];R=""}else/[a-zA-Z_]/.test(z)?R+=z:(R==="case"?(A++,$=!1):R==="in"&&A>0?$=!0:R==="esac"&&A>0&&(A--,$=!1),R="",z==="("?o>0&&s[o-1]==="$"?S++:$||S++:z===")"?$?$=!1:S--:z===";"&&A>0&&(o+1<i&&s[o+1]===";"||o+1<i&&s[o+1]==="&")&&($=!0))}z===`
45
+ `&&(c++,l=0,R=""),o++,l++}continue}if(g==="$"&&o+1<i&&s[o+1]==="["&&!h){u+=g,o++,l++,u+=s[o],o++,l++;let S=1;for(;S>0&&o<i;){let v=s[o];u+=v,v==="["?S++:v==="]"?S--:v===`
46
+ `&&(c++,l=0),o++,l++}continue}if(g==="$"&&o+1<i&&s[o+1]==="{"&&!h){u+=g,o++,l++,u+=s[o],o++,l++;let S=1,v=!1,k=!1,A=c,$=l,R=c,P=l;for(;S>0&&o<i;){let N=s[o];if(N==="\\"&&o+1<i&&s[o+1]===`
47
+ `){o+=2,c++,l=1;continue}if(N==="\\"&&o+1<i&&!v){u+=N,o++,l++,u+=s[o],o++,l++;continue}u+=N,v?N==="'"&&(v=!1):k?N==='"'&&(k=!1):N==="'"?(v=!0,A=c,$=l):N==='"'?(k=!0,R=c,P=l):N==="{"?S++:N==="}"&&S--,N===`
48
+ `&&(c++,l=0),o++,l++}if(v)throw new at("unexpected EOF while looking for matching `''",A,$);if(k)throw new at("unexpected EOF while looking for matching `\"'",R,P);continue}if(g==="$"&&o+1<i&&!h){let S=s[o+1];if(S==="#"||S==="?"||S==="$"||S==="!"||S==="@"||S==="*"||S==="-"||S>="0"&&S<="9"){u+=g+S,o+=2,l+=2;continue}}if(g==="`"&&!h){for(u+=g,o++,l++;o<i&&s[o]!=="`";){let S=s[o];u+=S,S==="\\"&&o+1<i&&(u+=s[o+1],o++,l++),S===`
49
+ `&&(c++,l=0),o++,l++}o<i&&(u+=s[o],o++,l++);continue}u+=g,o++,g===`
50
+ `?(c++,l=1):l++}if(this.pos=o,this.column=l,this.line=c,E&&m&&(u=s[t]+u,f=!1,d=!1),h||p){let g=h?"'":'"';throw new at(`unexpected EOF while looking for matching \`${g}'`,n,r)}if(!m&&u.length>=2){if(u[0]==="'"&&u[u.length-1]==="'"){let g=u.slice(1,-1);!g.includes("'")&&!g.includes('"')&&(u=g,f=!0,d=!0)}else if(u[0]==='"'&&u[u.length-1]==='"'){let g=u.slice(1,-1),S=!1;for(let v=0;v<g.length;v++){if(g[v]==='"'){S=!0;break}g[v]==="\\"&&v+1<g.length&&v++}S||(u=g,f=!0,d=!1)}}if(u==="")return{type:w.WORD,value:"",start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d};let y=Ui.get(u);if(!f&&y!==void 0)return{type:y,value:u,start:t,end:o,line:n,column:r};if(!m){let g=Il(u);if(g>0&&Dl(u.slice(0,g)))return{type:w.ASSIGNMENT_WORD,value:u,start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:w.NUMBER,value:u,start:t,end:o,line:n,column:r}:ph(u)?{type:w.NAME,value:u,start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d}:{type:w.WORD,value:u,start:t,end:o,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="",o=!1;for(;this.pos<this.input.length;){let a="",l="",c="";for(;;){for(a="";this.pos<this.input.length&&this.input[this.pos]!==`
48
51
  `;)a+=this.input[this.pos],this.pos++,this.column++;let f=0;for(let d=a.length-1;a[d]==="\\";d-=1)f+=1;if(c+=a,t.quoted||f%2===0||this.pos+1>=this.input.length)break;c=c.slice(0,-1),l+=`${a}
49
52
  `,this.pos++,this.line++,this.column=1}if((t.stripTabs?c.replace(/^\t+/,""):c)===t.delimiter){o=!0,this.pos<this.input.length&&this.input[this.pos]===`
50
53
  `&&(this.pos++,this.line++,this.column=1);break}if(i+=l,i+=a,this.pos<this.input.length&&this.input[this.pos]===`
51
54
  `?(i+=`
52
55
  `,this.pos++,this.line++,this.column=1):a.length>0&&(i+=`
53
- `),i.length>this.maxHeredocSize)throw new it(`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:o})}}readHeredocDelimiterToken(t,n,r,s){let i=this.input,{delim:o,endPos:a,quoted:l,unclosedQuote:c,unclosedSubstitution:u}=hs(i,t);if(c)throw new it(`unexpected EOF while looking for matching \`${c}'`,n,r);if(u)throw new it("unexpected EOF while looking for matching `)'",n,r);if(a===t)throw new it("Expected here-document delimiter",n,r);let f=n,d=r;for(let h=t;h<a;h++)i[h]===`
56
+ `),i.length>this.maxHeredocSize)throw new at(`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:o})}}readHeredocDelimiterToken(t,n,r,s){let i=this.input,{delim:o,endPos:a,quoted:l,unclosedQuote:c,unclosedSubstitution:u}=ms(i,t);if(c)throw new at(`unexpected EOF while looking for matching \`${c}'`,n,r);if(u)throw new at("unexpected EOF while looking for matching `)'",n,r);if(a===t)throw new at("Expected here-document delimiter",n,r);let f=n,d=r;for(let h=t;h<a;h++)i[h]===`
54
57
  `?(f+=1,d=1):d+=1;return this.pos=a,this.line=f,this.column=d,this.pendingHeredocs.push({delimiter:o,stripTabs:s,quoted:l}),{type:w.WORD,value:i.slice(t,a),start:t,end:a,line:n,column:r,quoted:l,heredocDelimiter:o}}isWordCharFollowing(t){if(t>=this.input.length)return!1;let n=this.input[t];return!(n===" "||n===" "||n===`
55
58
  `||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(t,n,r){let s=this.input,i=s.length,o=t,a=r;for(;o<i;){let c=s[o];if(c===" "||c===" "||c===`
56
59
  `||c===";"||c==="&"||c==="|"||c==="("||c===")"||c==="<"||c===">")break;if(c==="{"){if(this.scanBraceExpansion(o)!==null){let f=1;for(o++,a++;o<i&&f>0;)s[o]==="{"?f++:s[o]==="}"&&f--,o++,a++;continue}o++,a++;continue}if(c==="}"){o++,a++;continue}if(c==="$"&&o+1<i&&s[o+1]==="("){o++,a++,o++,a++;let u=1;for(;u>0&&o<i;)s[o]==="("?u++:s[o]===")"&&u--,o++,a++;continue}if(c==="$"&&o+1<i&&s[o+1]==="{"){o++,a++,o++,a++;let u=1;for(;u>0&&o<i;)s[o]==="{"?u++:s[o]==="}"&&u--,o++,a++;continue}if(c==="`"){for(o++,a++;o<i&&s[o]!=="`";)s[o]==="\\"&&o+1<i?(o+=2,a+=2):(o++,a++);o<i&&(o++,a++);continue}o++,a++}let l=s.slice(t,o);return this.pos=o,this.column=a,{type:w.WORD,value:l,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(t){let n=this.input,r=n.length,s=t+1,i=1,o=!1,a=!1;for(;s<r&&i>0;){let l=n[s];if(l==="{")i++,s++;else if(l==="}")i--,s++;else if(l===","&&i===1)o=!0,s++;else if(l==="."&&s+1<r&&n[s+1]===".")a=!0,s+=2;else{if(l===" "||l===" "||l===`
@@ -61,229 +64,231 @@ Gid: ${s} ${s} ${s} ${s}
61
64
  `&&(l=!0),s++;continue}if(c==="'"){o=!0,s++;continue}if(c==='"'){a=!0,s++;continue}if(c==="\\"){s+=2;continue}if(c===`
62
65
  `&&(l=!0),c==="("){i++,s++;continue}if(c===")"){if(i--,i===1){let u=s+1;if(u<r&&n[u]===")")return!1;let f=u,d=!1;for(;f<r&&(n[f]===" "||n[f]===" "||n[f]===`
63
66
  `);)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,o=!1,a=!1;for(;s<r&&i>0;){let l=n[s];if(o){l==="'"&&(o=!1),s++;continue}if(a){if(l==="\\"){s+=2;continue}l==='"'&&(a=!1),s++;continue}if(l==="'"){o=!0,s++;continue}if(l==='"'){a=!0,s++;continue}if(l==="\\"){s+=2;continue}if(l==="("){i++,s++;continue}if(l===")"){if(i--,i===1){let c=s+1;if(c<r&&n[c]===")")return!1;let u=c,f=!1;for(;u<r&&(n[u]===" "||n[u]===" "||n[u]===`
64
- `);)f=!0,u++;if(f&&u<r&&n[u]===")")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 ji=1e6,kr=1e5,ch=1e6,Rl=200,Ie;(function(e){e[e.Default=0]="Default",e[e.Assignment=1]="Assignment",e[e.NoBraceExpansion=2]="NoBraceExpansion",e[e.Regex=4]="Regex"})(Ie||(Ie={}));var 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]),Dl=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS]),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]),Ce=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"}},ms=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>ch)throw new Ce("Maximum parse iterations exceeded (possible infinite loop)",t,n)}chargeTokens(t,n=1,r=1){if(this.tokens+=t,this.tokens>kr)throw new Ce(`Too many tokens: cumulative count exceeds limit of ${kr}`,n,r)}enter(t,n){if(this.depth++,this.depth>Rl)throw this.depth--,new Ce(`Maximum parser nesting depth exceeded (${Rl})`,t,n);let r=!0;return()=>{r&&(r=!1,this.depth--)}}};function ye(e,t){for(;t<e.length;){if(e[t]==="\\"&&e[t+1]===`
65
- `){t+=2;continue}if(/\s/.test(e[t])){t++;continue}break}return t}var ys=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];function xr(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 o=0;for(let a of s){let l;if(/[0-9]/.test(a))l=a.charCodeAt(0)-48;else if(/[a-z]/.test(a))l=a.charCodeAt(0)-97+10;else if(/[A-Z]/.test(a))l=a.charCodeAt(0)-65+(i<=36?10:36);else if(a==="@")l=62;else if(a==="_")l=63;else return Number.NaN;if(l>=i)return Number.NaN;if(o=o*i+l,o>Number.MAX_SAFE_INTEGER)return Number.MAX_SAFE_INTEGER}return o}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 Tl(e,t,n,r){if(n.slice(r,r+3)!=="$((")return null;let s=r+3,i=1,o=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 a=n.slice(o,s),{expr:l}=e(t,a,0);return s+=2,{expr:{type:"ArithNested",expression:l},pos:s}}function _l(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+=`
66
- `;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 Ll(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 uh(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 oe(e,t){let n=uh(t),{expr:r,pos:s}=Yn(e,n,0),i=ye(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 Ye(e,t){return{expr:{type:"ArithSyntaxError",errorToken:e,message:`syntax error: operand expected (error token is "${e}")`},pos:t}}function Je(e,t){return ye(e,t)>=e.length}function Yn(e,t,n){return fh(e,t,n)}function Tn(e,t,n){return e.withDepth(()=>Yn(e,t,n))}function fh(e,t,n){let{expr:r,pos:s}=Pr(e,t,n);for(s=ye(t,s);t[s]===",";){if(s++,Je(t,s))return Ye(",",s);let{expr:o,pos:a}=Pr(e,t,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=ye(t,a)}return{expr:r,pos:s}}function Pr(e,t,n){let{expr:r,pos:s}=dh(e,t,n);if(s=ye(t,s),t[s]==="?"){s++;let{expr:i,pos:o}=Tn(e,t,s);if(s=ye(t,o),t[s]===":"){s++;let{expr:a,pos:l}=Tn(e,t,s);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:a},pos:l}}}return{expr:r,pos:s}}function dh(e,t,n){let{expr:r,pos:s}=Fl(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="||";){if(s+=2,Je(t,s))return Ye("||",s);let{expr:o,pos:a}=Fl(e,t,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=a}return{expr:r,pos:s}}function Fl(e,t,n){let{expr:r,pos:s}=Ml(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="&&";){if(s+=2,Je(t,s))return Ye("&&",s);let{expr:o,pos:a}=Ml(e,t,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=a}return{expr:r,pos:s}}function Ml(e,t,n){let{expr:r,pos:s}=Bl(e,t,n);for(;s=ye(t,s),t[s]==="|"&&t[s+1]!=="|";){if(s++,Je(t,s))return Ye("|",s);let{expr:o,pos:a}=Bl(e,t,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=a}return{expr:r,pos:s}}function Bl(e,t,n){let{expr:r,pos:s}=Wl(e,t,n);for(;s=ye(t,s),t[s]==="^";){if(s++,Je(t,s))return Ye("^",s);let{expr:o,pos:a}=Wl(e,t,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=a}return{expr:r,pos:s}}function Wl(e,t,n){let{expr:r,pos:s}=Vl(e,t,n);for(;s=ye(t,s),t[s]==="&"&&t[s+1]!=="&";){if(s++,Je(t,s))return Ye("&",s);let{expr:o,pos:a}=Vl(e,t,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=a}return{expr:r,pos:s}}function Vl(e,t,n){let{expr:r,pos:s}=zl(e,t,n);for(;s=ye(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 Ye(i,s);let{expr:o,pos:a}=zl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function zl(e,t,n){let{expr:r,pos:s}=qi(e,t,n);for(;;)if(s=ye(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 Ye(i,s);let{expr:o,pos:a}=qi(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 Ye(i,s);let{expr:o,pos:a}=qi(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function qi(e,t,n){let{expr:r,pos:s}=Ul(e,t,n);for(;s=ye(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 Ye(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}=jl(e,t,n);for(;s=ye(t,s),(t[s]==="+"||t[s]==="-")&&t[s+1]!==t[s];){let i=t[s];if(s++,Je(t,s))return Ye(i,s);let{expr:o,pos:a}=jl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function jl(e,t,n){let{expr:r,pos:s}=gs(e,t,n);for(;;)if(s=ye(t,s),t[s]==="*"&&t[s+1]!=="*"){if(s++,Je(t,s))return Ye("*",s);let{expr:o,pos:a}=gs(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 Ye(i,s);let{expr:o,pos:a}=gs(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function gs(e,t,n){let{expr:r,pos:s}=Gi(e,t,n),i=ye(t,s);if(t.slice(i,i+2)==="**"){if(i+=2,Je(t,i))return Ye("**",i);let{expr:a,pos:l}=e.withDepth(()=>gs(e,t,i));return{expr:{type:"ArithBinary",operator:"**",left:r,right:a},pos:l}}return{expr:r,pos:s}}function Gi(e,t,n){let r=ye(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(()=>Gi(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(()=>Gi(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}return ph(e,t,r)}function hh(e,t){let n=e[t];return n==="$"||n==="`"}function ph(e,t,n){let{expr:r,pos:s}=ql(e,t,n,!1),i=[r];for(;hh(t,s);){let{expr:a,pos:l}=ql(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}=Tn(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=ye(t,s),r.type==="ArithConcat"||r.type==="ArithVariable"||r.type==="ArithDynamicElement"){for(let a of ys)if(t.slice(s,s+a.length)===a&&t.slice(s,s+a.length+1)!=="=="){s+=a.length;let{expr:l,pos:c}=e.withDepth(()=>Pr(e,t,s));return r.type==="ArithDynamicElement"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r.nameExpr,subscript:r.subscript,value:l},pos:c}:r.type==="ArithConcat"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r,value:l},pos:c}:{expr:{type:"ArithAssignment",operator:a,variable:r.name,value:l},pos:c}}}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 ql(e,t,n,r=!1){let s=ye(t,n),i=Tl(Tn,e,t,s);if(i)return i;let o=_l(t,s);if(o)return o;let a=Ll(t,s);if(a)return a;if(t.slice(s,s+2)==="$("&&t[s+2]!=="("){s+=2;let c=1,u=s;for(;s<t.length&&c>0;)t[s]==="("?c++:t[s]===")"&&c--,c>0&&s++;let f=t.slice(u,s);return s++,{expr:{type:"ArithCommandSubst",command:f},pos:s}}if(t[s]==="`"){s++;let c=s;for(;s<t.length&&t[s]!=="`";)s++;let u=t.slice(c,s);return t[s]==="`"&&s++,{expr:{type:"ArithCommandSubst",command:u},pos:s}}if(t[s]==="("){s++;let{expr:c,pos:u}=Tn(e,t,s);return s=ye(t,u),t[s]===")"&&s++,{expr:{type:"ArithGroup",expression:c},pos:s}}if(t[s]==="'"){s++;let c="";for(;s<t.length&&t[s]!=="'";)c+=t[s],s++;t[s]==="'"&&s++;let u=Number.parseInt(c,10);return{expr:{type:"ArithSingleQuote",content:c,value:Number.isNaN(u)?0:u},pos:s}}if(t[s]==='"'){s++;let c="";for(;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?(c+=t[s+1],s+=2):(c+=t[s],s++);t[s]==='"'&&s++;let u=c.trim();if(!u)return{expr:{type:"ArithNumber",value:0},pos:s};let{expr:f}=Tn(e,u,0);return{expr:f,pos:s}}if(/[0-9]/.test(t[s])){let c="",u=!1,f=!1;for(;s<t.length;){let h=t[s];if(u)if(/[0-9a-zA-Z@_]/.test(h))c+=h,s++;else break;else if(h==="#")u=!0,c+=h,s++;else if(c==="0"&&(h==="x"||h==="X")&&s+1<t.length&&/[0-9a-fA-F]/.test(t[s+1]))f=!0,c+=h,s++;else if(f&&/[0-9a-fA-F]/.test(h))c+=h,s++;else if(!f&&/[0-9]/.test(h))c+=h,s++;else break}if(s<t.length&&/[a-zA-Z_]/.test(t[s])){let h=c;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)h+=t[s],s++;return{expr:{type:"ArithSyntaxError",errorToken:h,message:`${h}: value too great for base (error token is "${h}")`},pos:s}}if(t[s]==="."&&/[0-9]/.test(t[s+1]))throw new ue(`${c}.${t[s+1]}...: syntax error: invalid arithmetic operator`);if(t[s]==="["){let h=t.slice(s).trim();return{expr:{type:"ArithNumberSubscript",number:c,errorToken:h},pos:t.length}}return{expr:{type:"ArithNumber",value:xr(c)},pos:s}}if(t[s]==="$"&&t[s+1]==="{"){let c=s+2,u=1,f=c;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;let d=t.slice(c,f),h=f+1;if(t[h]==="#"){let p=h+1;for(;p<t.length&&/[0-9a-zA-Z@_]/.test(t[p]);)p++;let m=t.slice(h+1,p);return{expr:{type:"ArithDynamicBase",baseExpr:d,value:m},pos:p}}if(/[0-9]/.test(t[h])||t[h]==="x"||t[h]==="X"){let p=h;if(t[h]==="x"||t[h]==="X")for(p++;p<t.length&&/[0-9a-fA-F]/.test(t[p]);)p++;else for(;p<t.length&&/[0-9]/.test(t[p]);)p++;let m=t.slice(h,p);return{expr:{type:"ArithDynamicNumber",prefix:d,suffix:m},pos:p}}return s=h,{expr:{type:"ArithBracedExpansion",content:d},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[0-9]/.test(t[s+1])){s++;let c="";for(;s<t.length&&/[0-9]/.test(t[s]);)c+=t[s],s++;return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:!0},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[*@#?\-!$]/.test(t[s+1])){let c=t[s+1];return s+=2,{expr:{type:"ArithSpecialVar",name:c},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 c="";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)c+=t[s],s++;if(t[s]==="["&&!r){s++;let u;if(t[s]==="'"||t[s]==='"'){let d=t[s];for(s++,u="";s<t.length&&t[s]!==d;)u+=t[s],s++;t[s]===d&&s++,s=ye(t,s),t[s]==="]"&&s++}let f;if(u===void 0){let{expr:d,pos:h}=Tn(e,t,s);f=d,s=h,t[s]==="]"&&s++}if(s=ye(t,s),t[s]==="["&&f)return{expr:{type:"ArithDoubleSubscript",array:c,index:f},pos:s};if(!r){for(let d of ys)if(t.slice(s,s+d.length)===d&&t.slice(s,s+d.length+1)!=="=="){s+=d.length;let{expr:h,pos:p}=e.withDepth(()=>Pr(e,t,s));return{expr:{type:"ArithAssignment",operator:d,variable:c,subscript:f,stringKey:u,value:h},pos:p}}}return{expr:{type:"ArithArrayElement",array:c,index:f,stringKey:u},pos:s}}if(s=ye(t,s),!r){for(let u of ys)if(t.slice(s,s+u.length)===u&&t.slice(s,s+u.length+1)!=="=="){s+=u.length;let{expr:f,pos:d}=e.withDepth(()=>Pr(e,t,s));return{expr:{type:"ArithAssignment",operator:u,variable:c,value:f},pos:d}}}return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:l},pos:s}}if(t[s]==="#"){let c=s+1;for(;c<t.length&&t[c]!==`
67
- `;)c++;let u=t.slice(s,c).trim()||"#";return{expr:{type:"ArithSyntaxError",errorToken:u,message:`${u}: syntax error: invalid arithmetic operator (error token is "${u}")`},pos:t.length}}return{expr:{type:"ArithNumber",value:0},pos:s}}var ws=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 mh(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 Zl(e,t,n){let r=n+1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;return r}function Hi(e,t,n,r,s){let i=1,o=n+1;for(;o<t.length&&i>0;)t[o]===r?i++:t[o]===s&&i--,i>0&&o++;return i===0?o:-1}function _n(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 o=t.indexOf("'",r+1);if(o!==-1){r=o+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 Ql(e,t,n){let r=n,s=!1;for(;r<t.length;){let i=t[r];if(i==="/"&&s||i==="}")break;if(i==="'"){let o=t.indexOf("'",r+1);if(o!==-1){r=o+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 o=yh(t,r);o===-1?(s+=i,r++):(s+=t.slice(r,o+1),r=o+1)}else break}return{pattern:s,endIndex:r}}function yh(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]}]`,o=e.indexOf(i,n+2);if(o!==-1){n=o+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+=`
68
- `,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 c=t.slice(l+2,l+4),u=parseInt(c,16);if(!Number.isNaN(u)&&c.length>0)a.push(u),l+=2+c.length;else break}a.length>0?(r+=mh(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 c=parseInt(a,8);r+=String.fromCharCode(c),s=l;break}default:r+=i,s++}else r+=i,s++}return s<t.length&&t[s]==="'"&&s++,{part:M.literal(r),endIndex:s}}function Zi(e,t){let n=t.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:oe(e,n)}function Hl(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 Yl(e,t,n,r){let s=Hi(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:Hl(i).map(u=>e.withDepth(()=>({type:"Word",word:M.word(r(e,u,!1,!1,!1))})))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:Hl(i).map(u=>({type:"Word",word:M.word([M.literal(u)])}))},endIndex:s+1}:null}function Qi(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(Qi(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 Jl(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 $r(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:Dl.has(r.type)}if(n===w.FD_VARIABLE){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:Il.has(r.type)}return!e.isProcessSubstitutionStart()&&Ol.has(n)}function Es(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=Jl(e,r.type);if(r.type===w.DLESS||r.type===w.DLESSDASH)return gh(e,t,n,r.type===w.DLESSDASH);e.isWord()||e.error("Expected redirection target");let i=e.parseWord();return M.redirection(s,i,t,n)}function gh(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=M.redirection(r?"<<-":"<<",M.hereDoc(i,M.word([]),r,o),t,n);return e.addPendingHeredoc(a,i,r,o),a}function Xi(e){let t=e.getSourceLine(),n=[],r=null,s=[],i=[];for(;e.check(w.ASSIGNMENT_WORD)||$r(e);)e.checkIterationLimit(),e.check(w.ASSIGNMENT_WORD)?n.push(wh(e)):i.push(Es(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=M.word([M.literal(a.value)])}for(;(!e.isStatementEnd()||e.check(w.RBRACE))&&!e.check(w.PIPE,w.PIPE_AMP);)if(e.checkIterationLimit(),$r(e))i.push(Es(e));else if(e.check(w.ASSIGNMENT_WORD)){let a=e.advance(),l=a.value,c=l.endsWith("="),u=l.endsWith("=(");if((c||u)&&(u||e.check(w.LPAREN))){let f=u?l.slice(0,-2):l.slice(0,-1);u||e.expect(w.LPAREN);let d=Ki(e);e.expect(w.RPAREN);let h=d.map(m=>Qi(e,m)),p=`${f}=(${h.join(" ")})`;s.push(e.parseWordFromString(p,!1,!1,!0))}else{let f=e.parseWordFromString(l,a.quoted,a.singleQuoted,!0);s.push(e.parseAdjacentWordParts(f.parts,a.end,Ie.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=M.simpleCommand(r,s,n,i);return o.line=t,o}function wh(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=ws(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=Ki(e);e.expect(w.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return M.assignment(d,null,a,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 h=i!==void 0?`${s}[${i}]`:s;return M.assignment(h,null,a,d)}}let c=l?e.parseWordFromString(l,t.quoted,t.singleQuoted,!0):null;t.end===e.current().start&&e.isProcessSubstitutionStart()&&(c=e.parseAdjacentWordParts(c?.parts??[],t.end,Ie.Assignment));let u=i!==void 0?`${s}[${i}]`:s;return M.assignment(u,c,a,null)}var Eh=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()):Eh.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function Yi(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 c=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${c}'`)}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 M.ifNode(n,i,o)}function Ji(e,t){let n=e.expect(w.FOR);if(e.check(w.DPAREN_START))return Sh(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 M.forNode(s,i,o,a)}function Sh(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=oe(e,o[0].trim())),o[1].trim()&&(s=oe(e,o[1].trim())),o[2].trim()&&(i=oe(e,o[2].trim())),e.skipNewlines(),e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines();let c;e.check(w.LBRACE)?(e.advance(),c=e.parseCompoundList(),e.expect(w.RBRACE)):(e.expect(w.DO),c=e.parseCompoundList(),e.expect(w.DONE));let u=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:r,condition:s,update:i,body:c,redirections:u,line:n}}function eo(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 M.whileNode(n,r,s)}function to(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 M.untilNode(n,r,s)}function no(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=Ah(e);if(o&&r.push(o),e.skipNewlines(),e.getPos()===i&&!o)break}e.expect(w.ESAC);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.caseNode(n,r,s)}function Ah(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=";;&"),M.caseItem(t,n,r)}function ro(e,t){e.expect(w.LPAREN);let n=e.parseCompoundList();e.expect(w.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.subshell(n,r)}function so(e,t){e.expect(w.LBRACE);let n=e.parseCompoundList();e.expect(w.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.group(n,r)}var kh=["-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"],xh=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function tc(e){return e.isWord()||e.check(w.LBRACE)||e.check(w.RBRACE)||e.check(w.ASSIGNMENT_WORD)}function nc(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 oo(e){return e.skipNewlines(),Ph(e)}function Ph(e){let t=rc(e);for(e.skipNewlines();e.check(w.OR_OR);){e.advance(),e.skipNewlines();let n=rc(e);t={type:"CondOr",left:t,right:n},e.skipNewlines()}return t}function rc(e){let t=io(e);for(e.skipNewlines();e.check(w.AND_AND);){e.advance(),e.skipNewlines();let n=io(e);t={type:"CondAnd",left:t,right:n},e.skipNewlines()}return t}function io(e){return e.skipNewlines(),e.check(w.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:e.withDepth(()=>io(e))}):$h(e)}function $h(e){if(e.check(w.LPAREN)){e.advance();let t=e.withDepth(()=>oo(e));return e.expect(w.RPAREN),{type:"CondGroup",expression:t}}if(tc(e)){let t=e.current(),n=t.value;if(kh.includes(n)&&!t.quoted){if(e.advance(),e.check(w.DBRACK_END)&&e.error(`Expected operand after ${n}`),tc(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()&&xh.includes(e.current().value)){let s=e.advance().value,i;return s==="=~"?i=Ch(e):s==="=="||s==="!="?i=nc(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=nc(e);return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}e.error("Expected conditional expression")}function Ch(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 Rh(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:[M.literal("")]}function Oh(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 Dh(e,t,n){let r=n+1,s=t[r];if("@*#?$!-0123456789".includes(s))return{part:M.parameterExpansion(s),endIndex:r+1};let i="";for(;r<t.length&&/[a-zA-Z0-9_]/.test(t[r]);)i+=t[r],r++;return{part:M.parameterExpansion(i),endIndex:r}}function Ih(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 u=Hi(e,t,s,"[","]");if(a+=`[${ws(t.slice(s+1,u))}]`,s=u+1,t[s]==="["){let f=1,d=s;for(;d<t.length&&f>0;)t[d]==="{"?f++:t[d]==="}"&&f--,f>0&&d++;let h=t.slice(n+2,d);return{part:M.parameterExpansion("",{type:"BadSubstitution",text:h}),endIndex:d+1}}}if(a===""&&!i&&!o&&t[s]!=="}"){let u=1,f=s;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;if(u>0)throw new Ce("unexpected EOF while looking for matching '}'",0,0);let d=t.slice(n+2,f);return{part:M.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:f+1}}let c=null;if(i){let u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=ao(e,t,s,a,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):(c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="")}else c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="";else if(t[s]==="*"||t[s]==="@"&&!/[QPaAEKkuUL]/.test(t[s+1]||"")){let f=t[s];s++,c={type:"VarNamePrefix",prefix:a,star:f==="*"},a=""}else if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=ao(e,t,s,a,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):c={type:"Indirection"}}else c={type:"Indirection"}}else if(o)if(t[s]===":")for(c={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`):c={type:"Length"};if(!c&&s<t.length&&t[s]!=="}"){let u=ao(e,t,s,a,r);c=u.operation,s=u.endIndex}if(s<t.length&&t[s]!=="}"){let u=t[s];if(!/[:\-+=?#%/^,@[]/.test(u)){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 Ce("unexpected EOF while looking for matching '}'",0,0);return{part:M.parameterExpansion(a,c),endIndex:s+1}}function ao(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=_n(e,t,i),g=t.slice(i,S),y=e.withDepth(()=>un(e,g,!1,!1,!0,!1,s,!1,!1,!0)),b=M.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 c=_n(e,t,i),u=t.slice(i,c),f=-1,d=0,h=0;for(let E=0;E<u.length;E++){let S=u[E];if(S==="("||S==="[")d++;else if(S===")"||S==="]")d--;else if(S==="?"&&d===0)h++;else if(S===":"&&d===0)if(h>0)h--;else{f=E;break}}let p=f>=0?u.slice(0,f):u,m=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:Zi(e,p),length:m!==null?Zi(e,m):null},endIndex:c}}if("-=?+".includes(o)){i++;let l=_n(e,t,i),c=t.slice(i,l),u=e.withDepth(()=>un(e,c,!1,!1,!0,!1,s,!1,!1,!0)),f=M.word(Cr(u));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:c?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,c=o==="#"?"prefix":"suffix";i+=l?2:1;let u=_n(e,t,i),f=t.slice(i,u),d=e.withDepth(()=>un(e,f,!1,!1,!1));return{operation:{type:"PatternRemoval",pattern:M.word(Cr(d)),side:c,greedy:l},endIndex:u}}if(o==="/"){let l=a==="/";i+=l?2:1;let c=null;t[i]==="#"?(c="start",i++):t[i]==="%"&&(c="end",i++);let u;c!==null&&(t[i]==="/"||t[i]==="}")?u=i:u=Ql(e,t,i);let f=t.slice(i,u),d=e.withDepth(()=>un(e,f,!1,!1,!1)),h=M.word(Cr(d)),p=null,m=u;if(t[u]==="/"){let E=u+1,S=_n(e,t,E),g=t.slice(E,S),y=e.withDepth(()=>un(e,g,!1,!1,!1));p=M.word(Cr(y)),m=S}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:l,anchor:c},endIndex:m}}if(o==="^"||o===","){let l=a===o,c=o==="^"?"upper":"lower";i+=l?2:1;let u=_n(e,t,i),f=t.slice(i,u),d=f?M.word([M.literal(f)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:d},endIndex:u}}return o==="@"&&/[QPaAEKkuUL]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:i+2}:{operation:null,endIndex:i}}function lo(e,t,n,r=!1){let s=n+1;if(s>=t.length)return{part:M.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),c=oe(e,l);return{part:M.arithmeticExpansion(c),endIndex:a+1}}}return i==="("?e.parseCommandSubstitution(t,n):i==="{"?Ih(e,t,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Dh(e,t,n):{part:M.literal("$"),endIndex:s}}function sc(e,t){let n=[],r=0,s="",i=()=>{s&&(n.push(M.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}=lo(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 Th(e,t,n){let r=[],s=n,i="",o=()=>{i&&(r.push(M.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:c}=lo(e,t,s,!0);l&&r.push(l),s=c;continue}if(a==="`"){o();let{part:l,endIndex:c}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=c;continue}i+=a,s++}return o(),{part:M.doubleQuoted(r),endIndex:s}}function un(e,t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!0){if(r)return[M.singleQuoted(t)];if(n){let m=sc(e,t);return[M.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=sc(e,m);return[M.doubleQuoted(S)]}}let f=[],d=0,h="",p=()=>{h&&(f.push(M.literal(h)),h="")};for(;d<t.length;){let m=t[d];if(m==="\\"&&d+1<t.length){let E=t[d+1];if(l){p(),f.push(M.escaped(E)),d+=2;continue}if(!i&&!o){E!==`
69
- `&&(p(),f.push(M.escaped(E))),d+=2;continue}let S=i?E==="$"||E==="`"||E===`
67
+ `);)f=!0,u++;if(f&&u<r&&n[u]===")")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 qi=1e6,$r=1e5,mh=1e6,_l=200,Te;(function(e){e[e.Default=0]="Default",e[e.Assignment=1]="Assignment",e[e.NoBraceExpansion=2]="NoBraceExpansion",e[e.Regex=4]="Regex"})(Te||(Te={}));var Ll=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]),Fl=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS]),Ml=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]),Ce=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"}},gs=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>mh)throw new Ce("Maximum parse iterations exceeded (possible infinite loop)",t,n)}chargeTokens(t,n=1,r=1){if(this.tokens+=t,this.tokens>$r)throw new Ce(`Too many tokens: cumulative count exceeds limit of ${$r}`,n,r)}enter(t,n){if(this.depth++,this.depth>_l)throw this.depth--,new Ce(`Maximum parser nesting depth exceeded (${_l})`,t,n);let r=!0;return()=>{r&&(r=!1,this.depth--)}}};function ye(e,t){for(;t<e.length;){if(e[t]==="\\"&&e[t+1]===`
68
+ `){t+=2;continue}if(/\s/.test(e[t])){t++;continue}break}return t}var ws=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];function Cr(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 o=0;for(let a of s){let l;if(/[0-9]/.test(a))l=a.charCodeAt(0)-48;else if(/[a-z]/.test(a))l=a.charCodeAt(0)-97+10;else if(/[A-Z]/.test(a))l=a.charCodeAt(0)-65+(i<=36?10:36);else if(a==="@")l=62;else if(a==="_")l=63;else return Number.NaN;if(l>=i)return Number.NaN;if(o=o*i+l,o>Number.MAX_SAFE_INTEGER)return Number.MAX_SAFE_INTEGER}return o}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 Bl(e,t,n,r){if(n.slice(r,r+3)!=="$((")return null;let s=r+3,i=1,o=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 a=n.slice(o,s),{expr:l}=e(t,a,0);return s+=2,{expr:{type:"ArithNested",expression:l},pos:s}}function Wl(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+=`
69
+ `;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 Vl(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 yh(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=yh(t),{expr:r,pos:s}=Jn(e,n,0),i=ye(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 Je(e,t){return{expr:{type:"ArithSyntaxError",errorToken:e,message:`syntax error: operand expected (error token is "${e}")`},pos:t}}function et(e,t){return ye(e,t)>=e.length}function Jn(e,t,n){return gh(e,t,n)}function Ln(e,t,n){return e.withDepth(()=>Jn(e,t,n))}function gh(e,t,n){let{expr:r,pos:s}=Nr(e,t,n);for(s=ye(t,s);t[s]===",";){if(s++,et(t,s))return Je(",",s);let{expr:o,pos:a}=Nr(e,t,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=ye(t,a)}return{expr:r,pos:s}}function Nr(e,t,n){let{expr:r,pos:s}=wh(e,t,n);if(s=ye(t,s),t[s]==="?"){s++;let{expr:i,pos:o}=Ln(e,t,s);if(s=ye(t,o),t[s]===":"){s++;let{expr:a,pos:l}=Ln(e,t,s);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:a},pos:l}}}return{expr:r,pos:s}}function wh(e,t,n){let{expr:r,pos:s}=zl(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="||";){if(s+=2,et(t,s))return Je("||",s);let{expr:o,pos:a}=zl(e,t,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=a}return{expr:r,pos:s}}function zl(e,t,n){let{expr:r,pos:s}=Ul(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="&&";){if(s+=2,et(t,s))return Je("&&",s);let{expr:o,pos:a}=Ul(e,t,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=a}return{expr:r,pos:s}}function Ul(e,t,n){let{expr:r,pos:s}=jl(e,t,n);for(;s=ye(t,s),t[s]==="|"&&t[s+1]!=="|";){if(s++,et(t,s))return Je("|",s);let{expr:o,pos:a}=jl(e,t,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=a}return{expr:r,pos:s}}function jl(e,t,n){let{expr:r,pos:s}=ql(e,t,n);for(;s=ye(t,s),t[s]==="^";){if(s++,et(t,s))return Je("^",s);let{expr:o,pos:a}=ql(e,t,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=a}return{expr:r,pos:s}}function ql(e,t,n){let{expr:r,pos:s}=Hl(e,t,n);for(;s=ye(t,s),t[s]==="&"&&t[s+1]!=="&";){if(s++,et(t,s))return Je("&",s);let{expr:o,pos:a}=Hl(e,t,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=a}return{expr:r,pos:s}}function Hl(e,t,n){let{expr:r,pos:s}=Gl(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="=="||t.slice(s,s+2)==="!=";){let i=t.slice(s,s+2);if(s+=2,et(t,s))return Je(i,s);let{expr:o,pos:a}=Gl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function Gl(e,t,n){let{expr:r,pos:s}=Hi(e,t,n);for(;;)if(s=ye(t,s),t.slice(s,s+2)==="<="||t.slice(s,s+2)===">="){let i=t.slice(s,s+2);if(s+=2,et(t,s))return Je(i,s);let{expr:o,pos:a}=Hi(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++,et(t,s))return Je(i,s);let{expr:o,pos:a}=Hi(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function Hi(e,t,n){let{expr:r,pos:s}=Zl(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="<<"||t.slice(s,s+2)===">>";){let i=t.slice(s,s+2);if(s+=2,et(t,s))return Je(i,s);let{expr:o,pos:a}=Zl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function Zl(e,t,n){let{expr:r,pos:s}=Ql(e,t,n);for(;s=ye(t,s),(t[s]==="+"||t[s]==="-")&&t[s+1]!==t[s];){let i=t[s];if(s++,et(t,s))return Je(i,s);let{expr:o,pos:a}=Ql(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function Ql(e,t,n){let{expr:r,pos:s}=Es(e,t,n);for(;;)if(s=ye(t,s),t[s]==="*"&&t[s+1]!=="*"){if(s++,et(t,s))return Je("*",s);let{expr:o,pos:a}=Es(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++,et(t,s))return Je(i,s);let{expr:o,pos:a}=Es(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function Es(e,t,n){let{expr:r,pos:s}=Gi(e,t,n),i=ye(t,s);if(t.slice(i,i+2)==="**"){if(i+=2,et(t,i))return Je("**",i);let{expr:a,pos:l}=e.withDepth(()=>Es(e,t,i));return{expr:{type:"ArithBinary",operator:"**",left:r,right:a},pos:l}}return{expr:r,pos:s}}function Gi(e,t,n){let r=ye(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(()=>Gi(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(()=>Gi(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}return bh(e,t,r)}function Eh(e,t){let n=e[t];return n==="$"||n==="`"}function bh(e,t,n){let{expr:r,pos:s}=Kl(e,t,n,!1),i=[r];for(;Eh(t,s);){let{expr:a,pos:l}=Kl(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}=Ln(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=ye(t,s),r.type==="ArithConcat"||r.type==="ArithVariable"||r.type==="ArithDynamicElement"){for(let a of ws)if(t.slice(s,s+a.length)===a&&t.slice(s,s+a.length+1)!=="=="){s+=a.length;let{expr:l,pos:c}=e.withDepth(()=>Nr(e,t,s));return r.type==="ArithDynamicElement"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r.nameExpr,subscript:r.subscript,value:l},pos:c}:r.type==="ArithConcat"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r,value:l},pos:c}:{expr:{type:"ArithAssignment",operator:a,variable:r.name,value:l},pos:c}}}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 Kl(e,t,n,r=!1){let s=ye(t,n),i=Bl(Ln,e,t,s);if(i)return i;let o=Wl(t,s);if(o)return o;let a=Vl(t,s);if(a)return a;if(t.slice(s,s+2)==="$("&&t[s+2]!=="("){s+=2;let c=1,u=s;for(;s<t.length&&c>0;)t[s]==="("?c++:t[s]===")"&&c--,c>0&&s++;let f=t.slice(u,s);return s++,{expr:{type:"ArithCommandSubst",command:f},pos:s}}if(t[s]==="`"){s++;let c=s;for(;s<t.length&&t[s]!=="`";)s++;let u=t.slice(c,s);return t[s]==="`"&&s++,{expr:{type:"ArithCommandSubst",command:u},pos:s}}if(t[s]==="("){s++;let{expr:c,pos:u}=Ln(e,t,s);return s=ye(t,u),t[s]===")"&&s++,{expr:{type:"ArithGroup",expression:c},pos:s}}if(t[s]==="'"){s++;let c="";for(;s<t.length&&t[s]!=="'";)c+=t[s],s++;t[s]==="'"&&s++;let u=Number.parseInt(c,10);return{expr:{type:"ArithSingleQuote",content:c,value:Number.isNaN(u)?0:u},pos:s}}if(t[s]==='"'){s++;let c="";for(;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?(c+=t[s+1],s+=2):(c+=t[s],s++);t[s]==='"'&&s++;let u=c.trim();if(!u)return{expr:{type:"ArithNumber",value:0},pos:s};let{expr:f}=Ln(e,u,0);return{expr:f,pos:s}}if(/[0-9]/.test(t[s])){let c="",u=!1,f=!1;for(;s<t.length;){let h=t[s];if(u)if(/[0-9a-zA-Z@_]/.test(h))c+=h,s++;else break;else if(h==="#")u=!0,c+=h,s++;else if(c==="0"&&(h==="x"||h==="X")&&s+1<t.length&&/[0-9a-fA-F]/.test(t[s+1]))f=!0,c+=h,s++;else if(f&&/[0-9a-fA-F]/.test(h))c+=h,s++;else if(!f&&/[0-9]/.test(h))c+=h,s++;else break}if(s<t.length&&/[a-zA-Z_]/.test(t[s])){let h=c;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)h+=t[s],s++;return{expr:{type:"ArithSyntaxError",errorToken:h,message:`${h}: value too great for base (error token is "${h}")`},pos:s}}if(t[s]==="."&&/[0-9]/.test(t[s+1]))throw new ce(`${c}.${t[s+1]}...: syntax error: invalid arithmetic operator`);if(t[s]==="["){let h=t.slice(s).trim();return{expr:{type:"ArithNumberSubscript",number:c,errorToken:h},pos:t.length}}return{expr:{type:"ArithNumber",value:Cr(c)},pos:s}}if(t[s]==="$"&&t[s+1]==="{"){let c=s+2,u=1,f=c;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;let d=t.slice(c,f),h=f+1;if(t[h]==="#"){let p=h+1;for(;p<t.length&&/[0-9a-zA-Z@_]/.test(t[p]);)p++;let m=t.slice(h+1,p);return{expr:{type:"ArithDynamicBase",baseExpr:d,value:m},pos:p}}if(/[0-9]/.test(t[h])||t[h]==="x"||t[h]==="X"){let p=h;if(t[h]==="x"||t[h]==="X")for(p++;p<t.length&&/[0-9a-fA-F]/.test(t[p]);)p++;else for(;p<t.length&&/[0-9]/.test(t[p]);)p++;let m=t.slice(h,p);return{expr:{type:"ArithDynamicNumber",prefix:d,suffix:m},pos:p}}return s=h,{expr:{type:"ArithBracedExpansion",content:d},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[0-9]/.test(t[s+1])){s++;let c="";for(;s<t.length&&/[0-9]/.test(t[s]);)c+=t[s],s++;return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:!0},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[*@#?\-!$]/.test(t[s+1])){let c=t[s+1];return s+=2,{expr:{type:"ArithSpecialVar",name:c},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 c="";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)c+=t[s],s++;if(t[s]==="["&&!r){s++;let u;if(t[s]==="'"||t[s]==='"'){let d=t[s];for(s++,u="";s<t.length&&t[s]!==d;)u+=t[s],s++;t[s]===d&&s++,s=ye(t,s),t[s]==="]"&&s++}let f;if(u===void 0){let{expr:d,pos:h}=Ln(e,t,s);f=d,s=h,t[s]==="]"&&s++}if(s=ye(t,s),t[s]==="["&&f)return{expr:{type:"ArithDoubleSubscript",array:c,index:f},pos:s};if(!r){for(let d of ws)if(t.slice(s,s+d.length)===d&&t.slice(s,s+d.length+1)!=="=="){s+=d.length;let{expr:h,pos:p}=e.withDepth(()=>Nr(e,t,s));return{expr:{type:"ArithAssignment",operator:d,variable:c,subscript:f,stringKey:u,value:h},pos:p}}}return{expr:{type:"ArithArrayElement",array:c,index:f,stringKey:u},pos:s}}if(s=ye(t,s),!r){for(let u of ws)if(t.slice(s,s+u.length)===u&&t.slice(s,s+u.length+1)!=="=="){s+=u.length;let{expr:f,pos:d}=e.withDepth(()=>Nr(e,t,s));return{expr:{type:"ArithAssignment",operator:u,variable:c,value:f},pos:d}}}return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:l},pos:s}}if(t[s]==="#"){let c=s+1;for(;c<t.length&&t[c]!==`
70
+ `;)c++;let u=t.slice(s,c).trim()||"#";return{expr:{type:"ArithSyntaxError",errorToken:u,message:`${u}: syntax error: invalid arithmetic operator (error token is "${u}")`},pos:t.length}}return{expr:{type:"ArithNumber",value:0},pos:s}}var bs=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 Sh(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 Jl(e,t,n){let r=n+1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;return r}function Zi(e,t,n,r,s){let i=1,o=n+1;for(;o<t.length&&i>0;)t[o]===r?i++:t[o]===s&&i--,i>0&&o++;return i===0?o:-1}function Fn(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 o=t.indexOf("'",r+1);if(o!==-1){r=o+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 ec(e,t,n){let r=n,s=!1;for(;r<t.length;){let i=t[r];if(i==="/"&&s||i==="}")break;if(i==="'"){let o=t.indexOf("'",r+1);if(o!==-1){r=o+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 tc(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 o=Ah(t,r);o===-1?(s+=i,r++):(s+=t.slice(r,o+1),r=o+1)}else break}return{pattern:s,endIndex:r}}function Ah(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]}]`,o=e.indexOf(i,n+2);if(o!==-1){n=o+2;continue}}n++}return-1}function nc(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+=`
71
+ `,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 c=t.slice(l+2,l+4),u=parseInt(c,16);if(!Number.isNaN(u)&&c.length>0)a.push(u),l+=2+c.length;else break}a.length>0?(r+=Sh(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 c=parseInt(a,8);r+=String.fromCharCode(c),s=l;break}default:r+=i,s++}else r+=i,s++}return s<t.length&&t[s]==="'"&&s++,{part:M.literal(r),endIndex:s}}function Qi(e,t){let n=t.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:se(e,n)}function Yl(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 rc(e,t,n,r){let s=Zi(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:Yl(i).map(u=>e.withDepth(()=>({type:"Word",word:M.word(r(e,u,!1,!1,!1))})))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:Yl(i).map(u=>({type:"Word",word:M.word([M.literal(u)])}))},endIndex:s+1}:null}function Ki(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(Ki(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 sc(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 Rr(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:Fl.has(r.type)}if(n===w.FD_VARIABLE){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:Ml.has(r.type)}return!e.isProcessSubstitutionStart()&&Ll.has(n)}function Ss(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=sc(e,r.type);if(r.type===w.DLESS||r.type===w.DLESSDASH)return vh(e,t,n,r.type===w.DLESSDASH);e.isWord()||e.error("Expected redirection target");let i=e.parseWord();return M.redirection(s,i,t,n)}function vh(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=M.redirection(r?"<<-":"<<",M.hereDoc(i,M.word([]),r,o),t,n);return e.addPendingHeredoc(a,i,r,o),a}function Yi(e){let t=e.getSourceLine(),n=[],r=null,s=[],i=[];for(;e.check(w.ASSIGNMENT_WORD)||Rr(e);)e.checkIterationLimit(),e.check(w.ASSIGNMENT_WORD)?n.push(kh(e)):i.push(Ss(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=M.word([M.literal(a.value)])}for(;(!e.isStatementEnd()||e.check(w.RBRACE))&&!e.check(w.PIPE,w.PIPE_AMP);)if(e.checkIterationLimit(),Rr(e))i.push(Ss(e));else if(e.check(w.ASSIGNMENT_WORD)){let a=e.advance(),l=a.value,c=l.endsWith("="),u=l.endsWith("=(");if((c||u)&&(u||e.check(w.LPAREN))){let f=u?l.slice(0,-2):l.slice(0,-1);u||e.expect(w.LPAREN);let d=Xi(e);e.expect(w.RPAREN);let h=d.map(m=>Ki(e,m)),p=`${f}=(${h.join(" ")})`;s.push(e.parseWordFromString(p,!1,!1,!0))}else{let f=e.parseWordFromString(l,a.quoted,a.singleQuoted,!0);s.push(e.parseAdjacentWordParts(f.parts,a.end,Te.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=M.simpleCommand(r,s,n,i);return o.line=t,o}function kh(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=bs(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=Xi(e);e.expect(w.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return M.assignment(d,null,a,f)}if(l===""&&e.check(w.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let d=Xi(e);e.expect(w.RPAREN);let h=i!==void 0?`${s}[${i}]`:s;return M.assignment(h,null,a,d)}}let c=l?e.parseWordFromString(l,t.quoted,t.singleQuoted,!0):null;t.end===e.current().start&&e.isProcessSubstitutionStart()&&(c=e.parseAdjacentWordParts(c?.parts??[],t.end,Te.Assignment));let u=i!==void 0?`${s}[${i}]`:s;return M.assignment(u,c,a,null)}var xh=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 Xi(e){let t=[];for(e.skipNewlines();!e.check(w.RPAREN,w.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):xh.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function Ji(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 c=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${c}'`)}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 M.ifNode(n,i,o)}function eo(e,t){let n=e.expect(w.FOR);if(e.check(w.DPAREN_START))return $h(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 M.forNode(s,i,o,a)}function $h(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=se(e,o[0].trim())),o[1].trim()&&(s=se(e,o[1].trim())),o[2].trim()&&(i=se(e,o[2].trim())),e.skipNewlines(),e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines();let c;e.check(w.LBRACE)?(e.advance(),c=e.parseCompoundList(),e.expect(w.RBRACE)):(e.expect(w.DO),c=e.parseCompoundList(),e.expect(w.DONE));let u=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:r,condition:s,update:i,body:c,redirections:u,line:n}}function to(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 M.whileNode(n,r,s)}function no(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 M.untilNode(n,r,s)}function ro(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=Ch(e);if(o&&r.push(o),e.skipNewlines(),e.getPos()===i&&!o)break}e.expect(w.ESAC);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.caseNode(n,r,s)}function Ch(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=";;&"),M.caseItem(t,n,r)}function so(e,t){e.expect(w.LPAREN);let n=e.parseCompoundList();e.expect(w.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.subshell(n,r)}function io(e,t){e.expect(w.LBRACE);let n=e.parseCompoundList();e.expect(w.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.group(n,r)}var Rh=["-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"],Oh=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function oc(e){return e.isWord()||e.check(w.LBRACE)||e.check(w.RBRACE)||e.check(w.ASSIGNMENT_WORD)}function ac(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 ao(e){return e.skipNewlines(),Dh(e)}function Dh(e){let t=lc(e);for(e.skipNewlines();e.check(w.OR_OR);){e.advance(),e.skipNewlines();let n=lc(e);t={type:"CondOr",left:t,right:n},e.skipNewlines()}return t}function lc(e){let t=oo(e);for(e.skipNewlines();e.check(w.AND_AND);){e.advance(),e.skipNewlines();let n=oo(e);t={type:"CondAnd",left:t,right:n},e.skipNewlines()}return t}function oo(e){return e.skipNewlines(),e.check(w.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:e.withDepth(()=>oo(e))}):Ih(e)}function Ih(e){if(e.check(w.LPAREN)){e.advance();let t=e.withDepth(()=>ao(e));return e.expect(w.RPAREN),{type:"CondGroup",expression:t}}if(oc(e)){let t=e.current(),n=t.value;if(Rh.includes(n)&&!t.quoted){if(e.advance(),e.check(w.DBRACK_END)&&e.error(`Expected operand after ${n}`),oc(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()&&Oh.includes(e.current().value)){let s=e.advance().value,i;return s==="=~"?i=Th(e):s==="=="||s==="!="?i=ac(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=ac(e);return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}e.error("Expected conditional expression")}function Th(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 Lh(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 Or(e){return e.length>0?e:[M.literal("")]}function Fh(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 Mh(e,t,n){let r=n+1,s=t[r];if("@*#?$!-0123456789".includes(s))return{part:M.parameterExpansion(s),endIndex:r+1};let i="";for(;r<t.length&&/[a-zA-Z0-9_]/.test(t[r]);)i+=t[r],r++;return{part:M.parameterExpansion(i),endIndex:r}}function Bh(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 u=Zi(e,t,s,"[","]");if(a+=`[${bs(t.slice(s+1,u))}]`,s=u+1,t[s]==="["){let f=1,d=s;for(;d<t.length&&f>0;)t[d]==="{"?f++:t[d]==="}"&&f--,f>0&&d++;let h=t.slice(n+2,d);return{part:M.parameterExpansion("",{type:"BadSubstitution",text:h}),endIndex:d+1}}}if(a===""&&!i&&!o&&t[s]!=="}"){let u=1,f=s;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;if(u>0)throw new Ce("unexpected EOF while looking for matching '}'",0,0);let d=t.slice(n+2,f);return{part:M.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:f+1}}let c=null;if(i){let u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=lo(e,t,s,a,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):(c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="")}else c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="";else if(t[s]==="*"||t[s]==="@"&&!/[QPaAEKkuUL]/.test(t[s+1]||"")){let f=t[s];s++,c={type:"VarNamePrefix",prefix:a,star:f==="*"},a=""}else if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=lo(e,t,s,a,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):c={type:"Indirection"}}else c={type:"Indirection"}}else if(o)if(t[s]===":")for(c={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`):c={type:"Length"};if(!c&&s<t.length&&t[s]!=="}"){let u=lo(e,t,s,a,r);c=u.operation,s=u.endIndex}if(s<t.length&&t[s]!=="}"){let u=t[s];if(!/[:\-+=?#%/^,@[]/.test(u)){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 Ce("unexpected EOF while looking for matching '}'",0,0);return{part:M.parameterExpansion(a,c),endIndex:s+1}}function lo(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 b=Fn(e,t,i),y=t.slice(i,b),g=e.withDepth(()=>fn(e,y,!1,!1,!0,!1,s,!1,!1,!0)),S=M.word(Or(g));if(l==="-")return{operation:{type:"DefaultValue",word:S,checkEmpty:!0},endIndex:b};if(l==="=")return{operation:{type:"AssignDefault",word:S,checkEmpty:!0},endIndex:b};if(l==="?")return{operation:{type:"ErrorIfUnset",word:S,checkEmpty:!0},endIndex:b};if(l==="+")return{operation:{type:"UseAlternative",word:S,checkEmpty:!0},endIndex:b}}i++;let c=Fn(e,t,i),u=t.slice(i,c),f=-1,d=0,h=0;for(let E=0;E<u.length;E++){let b=u[E];if(b==="("||b==="[")d++;else if(b===")"||b==="]")d--;else if(b==="?"&&d===0)h++;else if(b===":"&&d===0)if(h>0)h--;else{f=E;break}}let p=f>=0?u.slice(0,f):u,m=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:Qi(e,p),length:m!==null?Qi(e,m):null},endIndex:c}}if("-=?+".includes(o)){i++;let l=Fn(e,t,i),c=t.slice(i,l),u=e.withDepth(()=>fn(e,c,!1,!1,!0,!1,s,!1,!1,!0)),f=M.word(Or(u));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:c?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,c=o==="#"?"prefix":"suffix";i+=l?2:1;let u=Fn(e,t,i),f=t.slice(i,u),d=e.withDepth(()=>fn(e,f,!1,!1,!1));return{operation:{type:"PatternRemoval",pattern:M.word(Or(d)),side:c,greedy:l},endIndex:u}}if(o==="/"){let l=a==="/";i+=l?2:1;let c=null;t[i]==="#"?(c="start",i++):t[i]==="%"&&(c="end",i++);let u;c!==null&&(t[i]==="/"||t[i]==="}")?u=i:u=ec(e,t,i);let f=t.slice(i,u),d=e.withDepth(()=>fn(e,f,!1,!1,!1)),h=M.word(Or(d)),p=null,m=u;if(t[u]==="/"){let E=u+1,b=Fn(e,t,E),y=t.slice(E,b),g=e.withDepth(()=>fn(e,y,!1,!1,!1));p=M.word(Or(g)),m=b}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:l,anchor:c},endIndex:m}}if(o==="^"||o===","){let l=a===o,c=o==="^"?"upper":"lower";i+=l?2:1;let u=Fn(e,t,i),f=t.slice(i,u),d=f?M.word([M.literal(f)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:d},endIndex:u}}return o==="@"&&/[QPaAEKkuUL]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:i+2}:{operation:null,endIndex:i}}function co(e,t,n,r=!1){let s=n+1;if(s>=t.length)return{part:M.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),c=se(e,l);return{part:M.arithmeticExpansion(c),endIndex:a+1}}}return i==="("?e.parseCommandSubstitution(t,n):i==="{"?Bh(e,t,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Mh(e,t,n):{part:M.literal("$"),endIndex:s}}function cc(e,t){let n=[],r=0,s="",i=()=>{s&&(n.push(M.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}=co(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 Wh(e,t,n){let r=[],s=n,i="",o=()=>{i&&(r.push(M.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:c}=co(e,t,s,!0);l&&r.push(l),s=c;continue}if(a==="`"){o();let{part:l,endIndex:c}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=c;continue}i+=a,s++}return o(),{part:M.doubleQuoted(r),endIndex:s}}function fn(e,t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!0){if(r)return[M.singleQuoted(t)];if(n){let m=cc(e,t);return[M.doubleQuoted(m)]}if(t.length>=2&&t[0]==='"'&&t[t.length-1]==='"'){let m=t.slice(1,-1),E=!1;for(let b=0;b<m.length;b++){if(m[b]==='"'){E=!0;break}m[b]==="\\"&&b+1<m.length&&b++}if(!E){let b=cc(e,m);return[M.doubleQuoted(b)]}}let f=[],d=0,h="",p=()=>{h&&(f.push(M.literal(h)),h="")};for(;d<t.length;){let m=t[d];if(m==="\\"&&d+1<t.length){let E=t[d+1];if(l){p(),f.push(M.escaped(E)),d+=2;continue}if(!i&&!o){E!==`
72
+ `&&(p(),f.push(M.escaped(E))),d+=2;continue}let b=i?E==="$"||E==="`"||E===`
70
73
  `:E==="$"||E==="`"||E==='"'||E==="'"||E===`
71
- `||c&&E==="}",g=o?"*?[]\\".includes(E):"*?[]\\(){}.^+".includes(E);S?E!==`
72
- `&&(h+=E):g?(p(),f.push(M.escaped(E))):h+=`\\${E}`,d+=2;continue}if(m==="'"&&!o&&!i){p();let E=t.indexOf("'",d+1);if(E===-1){h+=t.slice(d);break}f.push(M.singleQuoted(t.slice(d+1,E))),d=E+1;continue}if(m==='"'&&!i){p();let{part:E,endIndex:S}=Th(e,t,d+1);f.push(E),d=S+1;continue}if(m==="$"&&t[d+1]==="'"){p();let{part:E,endIndex:S}=Xl(e,t,d+2);f.push(E),d=S;continue}if(m==="$"){p();let{part:E,endIndex:S}=lo(e,t,d);E&&f.push(E),d=S;continue}if(m==="`"){p();let{part:E,endIndex:S}=e.parseBacktickSubstitution(t,d);f.push(E),d=S;continue}if((m==="<"||m===">")&&t[d+1]==="("&&!i&&!o){p();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&&u||E==="="||s&&E===":"){let g=Zl(e,t,d),y=t[g];if(y===void 0||y==="/"||y===":"){p();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=Oh(t,d+1);if(E!==-1){p();let S=t.slice(d,E+1);f.push({type:"Glob",pattern:S}),d=E+1;continue}}if(m==="*"||m==="?"||m==="["){p();let{pattern:E,endIndex:S}=Kl(e,t,d);f.push({type:"Glob",pattern:l?Rh(E):E}),d=S;continue}if(m==="{"&&!s&&!a&&!i){let E=Yl(e,t,d,un);if(E){p(),f.push(E.part),d=E.endIndex;continue}}h+=m,d++}return p(),f}var Q=class e{tokens=[];pos=0;pendingHeredocs=[];parseBudget;ownsParseBudget;_input="";processLineState;constructor(t){this.parseBudget=t??new ms,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>ji)throw new Ce(`Input too large: ${t.length} bytes exceeds limit of ${ji}`,1,1);this._input=t,this.processLineState=void 0;let s=new ps(t,n);if(this.tokens=s.tokenize(),this.tokens.length>kr)throw new Ce(`Too many tokens: ${this.tokens.length} exceeds limit of ${kr}`,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 Ce(n||`Expected ${t}, got ${r.type}`,r.line,r.column,r)}error(t){let n=this.current();throw new Ce(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=M.word([M.literal(n.value)]):r=this.parseWordFromString(n.value,!1,!1,!1,!0),t.redirect.target=M.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||$r(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 M.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(),M.statement([M.pipeline([M.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 c=this.parsePipeline();n.push(c)}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 M.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 c=this.parseCommand();i.push(c)}return M.pipeline(i,s,t,n,o.length>0?o:void 0)}parseCommand(){if(this.currentTokenJoinsProcessSubstitution())return Xi(this);let t=this.current();switch(t.type){case w.IF:return Yi(this);case w.FOR:return Ji(this);case w.WHILE:return eo(this);case w.UNTIL:return to(this);case w.CASE:return no(this);case w.LPAREN:return ro(this);case w.LBRACE:return so(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():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=M.subshell(t,[]);return M.subshell([M.statement([M.pipeline([r],!1,!1,!1)])],n)}isWord(){return this.isWordToken(Ie.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&Ie.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(Ie.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=Ie.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=Ie.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 M.word(t)}parseWordNoBraceExpansion(){return this.parseWord(Ie.NoBraceExpansion)}parseWordForRegex(){return this.parseWord(Ie.NoBraceExpansion|Ie.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?M.word([M.literal(t.type===w.FD_VARIABLE?`{${t.value}}`:t.value)]):this.parseWordFromString(t.value,t.quoted,t.singleQuoted,(n&Ie.Assignment)!==0,!1,(n&Ie.NoBraceExpansion)!==0,(n&Ie.Regex)!==0,r)}parseWordFromString(t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!0){let c=un(this,t,n,r,s,i,!1,o,a,!1,l);return M.word(c)}parseCommandSubstitution(t,n){return kl(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitutionFromString(t,n){return xl(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=M.script(this.parseCompoundList())}finally{this.processLineState=n}return this.check(w.EOF)&&this.error("unexpected EOF while looking for matching `)'"),this.expect(w.RPAREN),M.processSubstitution(s,t.type===w.LESS?"input":"output")}parseBacktickSubstitution(t,n,r=!1){return Pl(t,n,r,()=>new e(this.parseBudget),s=>this.error(s))}isDollarDparenSubshell(t,n){return Al(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:M.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 c=this.current().value,u=n.length>0?n[n.length-1]:"";n.length>0&&!n.endsWith(" ")&&!(c==="="&&/[|&^+\-*/%<>]$/.test(n))&&!(c==="<"&&u==="<")&&!(c===">"&&u===">")&&(n+=" "),n+=c,this.advance()}}o||this.expect(w.DPAREN_END);let a=this.parseArithmeticExpression(n.trim()),l=this.parseOptionalRedirections();return M.arithmeticCommand(a,l,this.getSourceLine(t))}parseConditionalCommand(){let t=this.expect(w.DBRACK_START),n=oo(this);this.expect(w.DBRACK_END);let r=this.parseOptionalRedirections();return M.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 Ce("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 M.functionDef(t,n,r)}parseCompoundCommandBody(t){let n=t?.forFunctionBody;if(this.check(w.LBRACE))return so(this,{skipRedirections:n});if(this.check(w.LPAREN))return ro(this,{skipRedirections:n});if(this.check(w.IF))return Yi(this,{skipRedirections:n});if(this.check(w.FOR))return Ji(this,{skipRedirections:n});if(this.check(w.WHILE))return eo(this,{skipRedirections:n});if(this.check(w.UNTIL))return to(this,{skipRedirections:n});if(this.check(w.CASE))return no(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(;$r(this);){this.checkIterationLimit();let n=this.pos;if(t.push(Es(this)),this.pos===n)break}return t}parseArithmeticExpression(t){return oe(this,t)}};function qe(e,t){return new Q().parse(e,t)}function Nr(e){return Fn(e)}function Fn(e){return e.statements.map(ic).join(`
73
- `)}function ic(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(Lh(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let n=t.join(" ");return e.background&&(n+=" &"),n}function Lh(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(oc(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 oc(e){switch(e.type){case"SimpleCommand":return Fh(e);case"If":return Gh(e);case"For":return Hh(e);case"CStyleFor":return Zh(e);case"While":return Qh(e);case"Until":return Kh(e);case"Case":return Xh(e);case"Subshell":return Jh(e);case"Group":return ep(e);case"ArithmeticCommand":return tp(e);case"ConditionalCommand":return np(e);case"FunctionDef":return rp(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function Fh(e){let t=[];for(let n of e.assignments)t.push(Mh(n));e.name&&t.push(we(e.name));for(let n of e.args)t.push(we(n));for(let n of e.redirections)t.push(cc(n));return t.join(" ")}function Mh(e){let t=e.append?"+=":"=";if(e.array){let n=e.array.map(we).join(" ");return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${we(e.value)}`:`${e.name}${t}`}function we(e){return e.parts.map(t=>bs(t,!1)).join("")}function fn(e){return e.parts.map(t=>bs(t,!0)).join("")}function bs(e,t){switch(e.type){case"Literal":return t?Wh(e.value):Bh(e.value);case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(n=>bs(n,!0)).join("")}"`;case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return ac(e);case"CommandSubstitution":return e.legacy?`\`${Fn(e.body)}\``:`$(${Fn(e.body)})`;case"ArithmeticExpansion":return`$((${pe(e.expression.expression)}))`;case"ProcessSubstitution":return e.direction==="input"?`<(${Fn(e.body)})`:`>(${Fn(e.body)})`;case"BraceExpansion":return jh(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 Bh(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,"\\$&")}function Wh(e){return e.replace(/[$`"\\]/g,"\\$&")}function Vh(e,t){return e.parts.map(n=>zh(n,t)).join("")}function zh(e,t){switch(e.type){case"Literal":return t?e.value:e.value.replace(/[$`]/g,"\\$&");case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return ac(e);case"CommandSubstitution":return e.legacy?`\`${Fn(e.body)}\``:`$(${Fn(e.body)})`;case"ArithmeticExpansion":return`$((${pe(e.expression.expression)}))`;default:return bs(e,!1)}}function ac(e){return e.operation?`\${${lc(e.parameter,e.operation)}}`:Uh(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function Uh(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function lc(e,t){switch(t.type){case"Length":return`#${e}`;case"LengthSliceError":return`#${e}:`;case"BadSubstitution":return t.text;case"DefaultValue":return`${e}${t.checkEmpty?":":""}-${fn(t.word)}`;case"AssignDefault":return`${e}${t.checkEmpty?":":""}=${fn(t.word)}`;case"ErrorIfUnset":return`${e}${t.checkEmpty?":":""}?${t.word?fn(t.word):""}`;case"UseAlternative":return`${e}${t.checkEmpty?":":""}+${fn(t.word)}`;case"Substring":{let n=pe(t.offset.expression);return t.length?`${e}:${n}:${pe(t.length.expression)}`:`${e}:${n}`}case"PatternRemoval":{let n=t.side==="prefix"?"#":"%",r=t.greedy?`${n}${n}`:n;return`${e}${r}${fn(t.pattern)}`}case"PatternReplacement":{let n="/";t.all?n="//":t.anchor==="start"?n="/#":t.anchor==="end"&&(n="/%");let r=t.replacement?`/${fn(t.replacement)}`:"";return`${e}${n}${fn(t.pattern)}${r}`}case"CaseModification":{let n=t.direction==="upper"?"^":",",r=t.all?`${n}${n}`:n,s=t.pattern?fn(t.pattern):"";return`${e}${r}${s}`}case"Transform":return`${e}@${t.operator}`;case"Indirection":return t.innerOp?`!${lc(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 jh(e){return`{${e.items.map(qh).join(",")}}`}function qh(e){if(e.type==="Word")return we(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 cc(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=Vh(n.content,n.quoted);return`${t}${e.operator}${r}
74
- ${s}${n.delimiter}`}return e.operator==="<<<"?`${t}<<< ${we(e.target)}`:e.operator==="&>"||e.operator==="&>>"?`${e.operator} ${we(e.target)}`:`${t}${e.operator} ${we(e.target)}`}function At(e){return e.length===0?"":` ${e.map(cc).join(" ")}`}function pt(e){return e.map(ic).join(`
75
- `)}function Gh(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} ${pt(r.condition)}; then
76
- ${pt(r.body)}`)}return e.elseBody&&t.push(`else
77
- ${pt(e.elseBody)}`),`${t.join(`
74
+ `||c&&E==="}",y=o?"*?[]\\".includes(E):"*?[]\\(){}.^+".includes(E);b?E!==`
75
+ `&&(h+=E):y?(p(),f.push(M.escaped(E))):h+=`\\${E}`,d+=2;continue}if(m==="'"&&!o&&!i){p();let E=t.indexOf("'",d+1);if(E===-1){h+=t.slice(d);break}f.push(M.singleQuoted(t.slice(d+1,E))),d=E+1;continue}if(m==='"'&&!i){p();let{part:E,endIndex:b}=Wh(e,t,d+1);f.push(E),d=b+1;continue}if(m==="$"&&t[d+1]==="'"){p();let{part:E,endIndex:b}=nc(e,t,d+2);f.push(E),d=b;continue}if(m==="$"){p();let{part:E,endIndex:b}=co(e,t,d);E&&f.push(E),d=b;continue}if(m==="`"){p();let{part:E,endIndex:b}=e.parseBacktickSubstitution(t,d);f.push(E),d=b;continue}if((m==="<"||m===">")&&t[d+1]==="("&&!i&&!o){p();let{part:E,endIndex:b}=e.parseProcessSubstitutionFromString(t,d);f.push(E),d=b;continue}if(m==="~"){let E=d>0?t[d-1]:"";if(d===0&&u||E==="="||s&&E===":"){let y=Jl(e,t,d),g=t[y];if(g===void 0||g==="/"||g===":"){p();let S=t.slice(d+1,y)||null;f.push({type:"TildeExpansion",user:S}),d=y;continue}}}if("@*+?!".includes(m)&&d+1<t.length&&t[d+1]==="("){let E=Fh(t,d+1);if(E!==-1){p();let b=t.slice(d,E+1);f.push({type:"Glob",pattern:b}),d=E+1;continue}}if(m==="*"||m==="?"||m==="["){p();let{pattern:E,endIndex:b}=tc(e,t,d);f.push({type:"Glob",pattern:l?Lh(E):E}),d=b;continue}if(m==="{"&&!s&&!a&&!i){let E=rc(e,t,d,fn);if(E){p(),f.push(E.part),d=E.endIndex;continue}}h+=m,d++}return p(),f}var Q=class e{tokens=[];pos=0;pendingHeredocs=[];parseBudget;ownsParseBudget;_input="";processLineState;constructor(t){this.parseBudget=t??new gs,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>qi)throw new Ce(`Input too large: ${t.length} bytes exceeds limit of ${qi}`,1,1);this._input=t,this.processLineState=void 0;let s=new ys(t,n);if(this.tokens=s.tokenize(),this.tokens.length>$r)throw new Ce(`Too many tokens: ${this.tokens.length} exceeds limit of ${$r}`,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 Ce(n||`Expected ${t}, got ${r.type}`,r.line,r.column,r)}error(t){let n=this.current();throw new Ce(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=M.word([M.literal(n.value)]):r=this.parseWordFromString(n.value,!1,!1,!1,!0),t.redirect.target=M.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||Rr(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 M.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(),M.statement([M.pipeline([M.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 c=this.parsePipeline();n.push(c)}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 M.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 c=this.parseCommand();i.push(c)}return M.pipeline(i,s,t,n,o.length>0?o:void 0)}parseCommand(){if(this.currentTokenJoinsProcessSubstitution())return Yi(this);let t=this.current();switch(t.type){case w.IF:return Ji(this);case w.FOR:return eo(this);case w.WHILE:return to(this);case w.UNTIL:return no(this);case w.CASE:return ro(this);case w.LPAREN:return so(this);case w.LBRACE:return io(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:ji(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():Yi(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=M.subshell(t,[]);return M.subshell([M.statement([M.pipeline([r],!1,!1,!1)])],n)}isWord(){return this.isWordToken(Te.Default)||this.isProcessSubstitutionStart()||this.currentTokenJoinsProcessSubstitution()}isWordToken(t){let n=this.current().type;return n===w.WORD||n===w.NAME||n===w.NUMBER||ji(n)||n===w.BANG||n===w.ASSIGNMENT_WORD&&(t&Te.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(Te.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=Te.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=Te.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 M.word(t)}parseWordNoBraceExpansion(){return this.parseWord(Te.NoBraceExpansion)}parseWordForRegex(){return this.parseWord(Te.NoBraceExpansion|Te.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?M.word([M.literal(t.type===w.FD_VARIABLE?`{${t.value}}`:t.value)]):this.parseWordFromString(t.value,t.quoted,t.singleQuoted,(n&Te.Assignment)!==0,!1,(n&Te.NoBraceExpansion)!==0,(n&Te.Regex)!==0,r)}parseWordFromString(t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!0){let c=fn(this,t,n,r,s,i,!1,o,a,!1,l);return M.word(c)}parseCommandSubstitution(t,n){return Nl(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitutionFromString(t,n){return Rl(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=M.script(this.parseCompoundList())}finally{this.processLineState=n}return this.check(w.EOF)&&this.error("unexpected EOF while looking for matching `)'"),this.expect(w.RPAREN),M.processSubstitution(s,t.type===w.LESS?"input":"output")}parseBacktickSubstitution(t,n,r=!1){return Ol(t,n,r,()=>new e(this.parseBudget),s=>this.error(s))}isDollarDparenSubshell(t,n){return $l(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:M.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 c=this.current().value,u=n.length>0?n[n.length-1]:"";n.length>0&&!n.endsWith(" ")&&!(c==="="&&/[|&^+\-*/%<>]$/.test(n))&&!(c==="<"&&u==="<")&&!(c===">"&&u===">")&&(n+=" "),n+=c,this.advance()}}o||this.expect(w.DPAREN_END);let a=this.parseArithmeticExpression(n.trim()),l=this.parseOptionalRedirections();return M.arithmeticCommand(a,l,this.getSourceLine(t))}parseConditionalCommand(){let t=this.expect(w.DBRACK_START),n=ao(this);this.expect(w.DBRACK_END);let r=this.parseOptionalRedirections();return M.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 Ce("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 M.functionDef(t,n,r)}parseCompoundCommandBody(t){let n=t?.forFunctionBody;if(this.check(w.LBRACE))return io(this,{skipRedirections:n});if(this.check(w.LPAREN))return so(this,{skipRedirections:n});if(this.check(w.IF))return Ji(this,{skipRedirections:n});if(this.check(w.FOR))return eo(this,{skipRedirections:n});if(this.check(w.WHILE))return to(this,{skipRedirections:n});if(this.check(w.UNTIL))return no(this,{skipRedirections:n});if(this.check(w.CASE))return ro(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(;Rr(this);){this.checkIterationLimit();let n=this.pos;if(t.push(Ss(this)),this.pos===n)break}return t}parseArithmeticExpression(t){return se(this,t)}};function He(e,t){return new Q().parse(e,t)}function Dr(e){return Bn(e)}function Bn(e){return e.statements.map(uc).join(`
76
+ `)}function uc(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(zh(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let n=t.join(" ");return e.background&&(n+=" &"),n}function zh(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(fc(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 fc(e){switch(e.type){case"SimpleCommand":return Uh(e);case"If":return Yh(e);case"For":return Jh(e);case"CStyleFor":return ep(e);case"While":return tp(e);case"Until":return np(e);case"Case":return rp(e);case"Subshell":return ip(e);case"Group":return op(e);case"ArithmeticCommand":return ap(e);case"ConditionalCommand":return lp(e);case"FunctionDef":return cp(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function Uh(e){let t=[];for(let n of e.assignments)t.push(jh(n));e.name&&t.push(we(e.name));for(let n of e.args)t.push(we(n));for(let n of e.redirections)t.push(pc(n));return t.join(" ")}function jh(e){let t=e.append?"+=":"=";if(e.array){let n=e.array.map(we).join(" ");return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${we(e.value)}`:`${e.name}${t}`}function we(e){return e.parts.map(t=>As(t,!1)).join("")}function dn(e){return e.parts.map(t=>As(t,!0)).join("")}function As(e,t){switch(e.type){case"Literal":return t?Hh(e.value):qh(e.value);case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(n=>As(n,!0)).join("")}"`;case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return dc(e);case"CommandSubstitution":return e.legacy?`\`${Bn(e.body)}\``:`$(${Bn(e.body)})`;case"ArithmeticExpansion":return`$((${pe(e.expression.expression)}))`;case"ProcessSubstitution":return e.direction==="input"?`<(${Bn(e.body)})`:`>(${Bn(e.body)})`;case"BraceExpansion":return Kh(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 qh(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,"\\$&")}function Hh(e){return e.replace(/[$`"\\]/g,"\\$&")}function Gh(e,t){return e.parts.map(n=>Zh(n,t)).join("")}function Zh(e,t){switch(e.type){case"Literal":return t?e.value:e.value.replace(/[$`]/g,"\\$&");case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return dc(e);case"CommandSubstitution":return e.legacy?`\`${Bn(e.body)}\``:`$(${Bn(e.body)})`;case"ArithmeticExpansion":return`$((${pe(e.expression.expression)}))`;default:return As(e,!1)}}function dc(e){return e.operation?`\${${hc(e.parameter,e.operation)}}`:Qh(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function Qh(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function hc(e,t){switch(t.type){case"Length":return`#${e}`;case"LengthSliceError":return`#${e}:`;case"BadSubstitution":return t.text;case"DefaultValue":return`${e}${t.checkEmpty?":":""}-${dn(t.word)}`;case"AssignDefault":return`${e}${t.checkEmpty?":":""}=${dn(t.word)}`;case"ErrorIfUnset":return`${e}${t.checkEmpty?":":""}?${t.word?dn(t.word):""}`;case"UseAlternative":return`${e}${t.checkEmpty?":":""}+${dn(t.word)}`;case"Substring":{let n=pe(t.offset.expression);return t.length?`${e}:${n}:${pe(t.length.expression)}`:`${e}:${n}`}case"PatternRemoval":{let n=t.side==="prefix"?"#":"%",r=t.greedy?`${n}${n}`:n;return`${e}${r}${dn(t.pattern)}`}case"PatternReplacement":{let n="/";t.all?n="//":t.anchor==="start"?n="/#":t.anchor==="end"&&(n="/%");let r=t.replacement?`/${dn(t.replacement)}`:"";return`${e}${n}${dn(t.pattern)}${r}`}case"CaseModification":{let n=t.direction==="upper"?"^":",",r=t.all?`${n}${n}`:n,s=t.pattern?dn(t.pattern):"";return`${e}${r}${s}`}case"Transform":return`${e}@${t.operator}`;case"Indirection":return t.innerOp?`!${hc(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 Kh(e){return`{${e.items.map(Xh).join(",")}}`}function Xh(e){if(e.type==="Word")return we(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 pc(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=Gh(n.content,n.quoted);return`${t}${e.operator}${r}
77
+ ${s}${n.delimiter}`}return e.operator==="<<<"?`${t}<<< ${we(e.target)}`:e.operator==="&>"||e.operator==="&>>"?`${e.operator} ${we(e.target)}`:`${t}${e.operator} ${we(e.target)}`}function xt(e){return e.length===0?"":` ${e.map(pc).join(" ")}`}function yt(e){return e.map(uc).join(`
78
+ `)}function Yh(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} ${yt(r.condition)}; then
79
+ ${yt(r.body)}`)}return e.elseBody&&t.push(`else
80
+ ${yt(e.elseBody)}`),`${t.join(`
78
81
  `)}
79
- fi${At(e.redirections)}`}function Hh(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map(we).join(" ");t=`for ${e.variable} in ${n}`}return`${t}; do
80
- ${pt(e.body)}
81
- done${At(e.redirections)}`}function Zh(e){let t=e.init?pe(e.init.expression):"",n=e.condition?pe(e.condition.expression):"",r=e.update?pe(e.update.expression):"";return`for ((${t}; ${n}; ${r})); do
82
- ${pt(e.body)}
83
- done${At(e.redirections)}`}function Qh(e){return`while ${pt(e.condition)}; do
84
- ${pt(e.body)}
85
- done${At(e.redirections)}`}function Kh(e){return`until ${pt(e.condition)}; do
86
- ${pt(e.body)}
87
- done${At(e.redirections)}`}function Xh(e){let t=e.items.map(Yh).join(`
82
+ fi${xt(e.redirections)}`}function Jh(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map(we).join(" ");t=`for ${e.variable} in ${n}`}return`${t}; do
83
+ ${yt(e.body)}
84
+ done${xt(e.redirections)}`}function ep(e){let t=e.init?pe(e.init.expression):"",n=e.condition?pe(e.condition.expression):"",r=e.update?pe(e.update.expression):"";return`for ((${t}; ${n}; ${r})); do
85
+ ${yt(e.body)}
86
+ done${xt(e.redirections)}`}function tp(e){return`while ${yt(e.condition)}; do
87
+ ${yt(e.body)}
88
+ done${xt(e.redirections)}`}function np(e){return`until ${yt(e.condition)}; do
89
+ ${yt(e.body)}
90
+ done${xt(e.redirections)}`}function rp(e){let t=e.items.map(sp).join(`
88
91
  `);return`case ${we(e.word)} in
89
92
  ${t}
90
- esac${At(e.redirections)}`}function Yh(e){let t=e.patterns.map(we).join(" | "),n=pt(e.body);return n?`${t})
93
+ esac${xt(e.redirections)}`}function sp(e){let t=e.patterns.map(we).join(" | "),n=yt(e.body);return n?`${t})
91
94
  ${n}
92
95
  ${e.terminator}`:`${t})
93
- ${e.terminator}`}function Jh(e){return`(${pt(e.body)})${At(e.redirections)}`}function ep(e){return`{ ${pt(e.body)}; }${At(e.redirections)}`}function tp(e){return`((${pe(e.expression.expression)}))${At(e.redirections)}`}function np(e){return`[[ ${Ln(e.expression)} ]]${At(e.redirections)}`}function rp(e){let t=oc(e.body);return`${e.name}() ${t}${At(e.redirections)}`}function pe(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`${pe(e.left)} ${e.operator} ${pe(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${pe(e.operand)}`:`${pe(e.operand)}${e.operator}`;case"ArithTernary":return`${pe(e.condition)} ? ${pe(e.consequent)} : ${pe(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${pe(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${pe(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${pe(e.target)}[${pe(e.subscript)}]`:pe(e.target)} ${e.operator} ${pe(e.value)}`;case"ArithDynamicElement":return`${pe(e.nameExpr)}[${pe(e.subscript)}]`;case"ArithGroup":return`(${pe(e.expression)})`;case"ArithNested":return`$((${pe(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}[${pe(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(pe).join("");case"ArithDoubleSubscript":return`${e.array}[${pe(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 Ln(e){switch(e.type){case"CondBinary":return`${we(e.left)} ${e.operator} ${we(e.right)}`;case"CondUnary":return`${e.operator} ${we(e.operand)}`;case"CondNot":return`! ${Ln(e.operand)}`;case"CondAnd":return`${Ln(e.left)} && ${Ln(e.right)}`;case"CondOr":return`${Ln(e.left)} || ${Ln(e.right)}`;case"CondGroup":return`( ${Ln(e.expression)} )`;case"CondWord":return we(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var sp="BASH_ALIAS_";function Ss(e,t,n,r){let s=W(t);if(s>n-r.value)throw new C(`alias expansion exceeds string length limit (${n} bytes)`,"string_length");return r.value+=s,e+t}function uc(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function fc(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function dc(e,t){return e.env.get(`${sp}${t}`)}function pc(e,t,n){return mc(e,t,n)}function mc(e,t,n,r=!0){if(!t.name||!uc(t.name))return t;let s=fc(t.name);if(!s)return t;let i=dc(e,s);if(!i||n.has(s))return t;try{n.add(s);let o=new Q,a={value:0},l=Ss("",i,e.limits.maxStringLength,a),c=i.endsWith(" ");if(!c)for(let h of t.args){let p=we(h);l=Ss(l,` ${p}`,e.limits.maxStringLength,a)}let u;try{u=o.parse(l)}catch(h){if(h instanceof Ce)throw h;return t}if(u.statements.length!==1||u.statements[0].pipelines.length!==1||u.statements[0].pipelines[0].commands.length!==1)return hc(e,t,i);let f=u.statements[0].pipelines[0].commands[0];if(f.type!=="SimpleCommand")return hc(e,t,i);let d={...f,assignments:[...t.assignments,...f.assignments],redirections:[...f.redirections,...t.redirections],line:t.line};if(c&&t.args.length>0){d={...d,args:[...d.args,...t.args]};let h=1;for(;r&&d.args.length>0;){let p=d.args[0];if(!uc(p))break;let m=fc(p),E=m?dc(e,m):null;if(!E)break;if(h>=e.limits.maxCallDepth)throw new C(`alias expansion depth limit exceeded (${e.limits.maxCallDepth})`,"recursion");h++;let S={type:"SimpleCommand",name:p,args:d.args.slice(1),assignments:[],redirections:[]},g=mc(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 hc(e,t,n){let r={value:0},s=Ss("",n,e.limits.maxStringLength,r);for(let c of t.args){let u=we(c);s=Ss(s,` ${u}`,e.limits.maxStringLength,r)}let i=new Q,o=i.parseWordFromString("eval",!1,!1),a=0;for(let c of s)c==="'"&&a++;if(r.value+2+a*3>e.limits.maxStringLength)throw new C(`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 ip=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 co(e){return ip.get(e)??""}function yc(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 gc(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 c=e.slice(s+2,l),u=co(c);i+=u,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,c=s+1===o;l||c?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+="$",ge(t)}function uo(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 fo(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 wc=5,dn=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=yc(i))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new C(`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 gc(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>wc))throw new C(`Glob pattern has too many ** segments (max ${wc})`,"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(c=>c!==""),s=-1;for(let c=0;c<r.length;c++)if(this.hasGlobChars(r[c])){s=c;break}if(s===-1)return[t];let i,o;if(s===0)n?(i="/",o="/"):(i=this.cwd,o="");else{let c=r.slice(0,s);n?(i=`/${c.join("/")}`,o=`/${c.join("/")}`):(i=this.fs.resolvePath(this.cwd,c.join("/")),o=c.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=[],c=[...a],u=this.dotglob||this.hasGlobignore;if(s.startsWith(".")||this.dotglob){let d=a.some(p=>p.name==="."),h=a.some(p=>p.name==="..");d||c.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),h||c.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let d of c)if(!(d.name.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d.name,s)){let h=t==="/"?`/${d.name}`:`${t}/${d.name}`,p;n===""?p=d.name:n==="/"?p=`/${d.name}`:p=`${n}/${d.name}`,i.length===0?l.push(Promise.resolve([p])):d.isDirectory&&l.push(this.expandSegments(h,p,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=[],c=[...a],u=this.dotglob||this.hasGlobignore;(s.startsWith(".")||this.dotglob)&&(a.includes(".")||c.push("."),a.includes("..")||c.push(".."));for(let d of c)if(!(d.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d,s)){let h=t==="/"?`/${d}`:`${t}/${d}`,p;n===""?p=d:n==="/"?p=`/${d}`:p=`${n}/${d}`,i.length===0?l.push(Promise.resolve([p])):l.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(h)).isDirectory)return this.expandSegments(h,p,i)}catch(m){if(m instanceof C)throw m}return[]})())}let f=await Promise.all(l);for(let d of f)o.push(...d)}}catch(a){if(a instanceof C)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 c of i){let u=t==="."?c.name:`${t}/${c.name}`;c.isDirectory&&o.push(u)}let a=t==="."?n:`${t}/${n}`,l=await this.expandRecursive(a);r.push(...l);for(let c=0;c<o.length;c+=100){let u=o.slice(c,c+100);await Promise.all(u.map(f=>this.walkDirectoryMultiGlobstar(f,n,r)))}}else{this.checkOpsLimit();let o=await this.fs.readdir(s),a=[];for(let u of o){let f=t==="."?u:`${t}/${u}`,d=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory&&a.push(f)}catch(h){if(h instanceof C)throw h}}let l=t==="."?n:`${t}/${n}`,c=await this.expandRecursive(l);r.push(...c);for(let u=0;u<a.length;u+=100){let f=a.slice(u,u+100);await Promise.all(f.map(d=>this.walkDirectoryMultiGlobstar(d,n,r)))}}}catch(i){if(i instanceof C)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 c=t==="."?l.name:`${t}/${l.name}`;l.isDirectory?a.push(c):n&&this.matchPattern(l.name,n)&&o.push(c)}r.push(...o);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u,n,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(s),o=[];for(let l=0;l<i.length;l+=100){let c=i.slice(l,l+100),u=await Promise.all(c.map(async f=>{let d=t==="."?f:`${t}/${f}`,h=this.fs.resolvePath(this.cwd,d);try{this.checkOpsLimit();let p=await this.fs.stat(h);return{name:f,path:d,isDirectory:p.isDirectory}}catch(p){if(p instanceof C)throw p;return null}}));o.push(...u.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 c=a.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u.path,n,r)))}}}catch(i){if(i instanceof C)throw i}}matchPattern(t,n){return this.patternToRegex(n).test(t)}patternToRegex(t){let n=this.patternToRegexStr(t);return ge(`^${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=uo(t,s+1);if(o!==-1){let a=t.slice(s+2,o),l=fo(a),c=l.map(f=>this.patternToRegexStr(f)),u=c.length>0?c.join("|"):"(?:)";if(i==="@")n+=`(?:${u})`;else if(i==="*")n+=`(?:${u})*`;else if(i==="+")n+=`(?:${u})+`;else if(i==="?")n+=`(?:${u})?`;else if(i==="!")if(o<t.length-1){let d=l.map(p=>this.computePatternLength(p));if(d.every(p=>p!==null)&&d.every(p=>p===d[0])&&d[0]!==null){let p=d[0];if(p===0)n+="(?:.+)";else{let m=[];p>0&&m.push(`.{0,${p-1}}`),m.push(`.{${p+1},}`),m.push(`(?!(?:${u})).{${p}}`),n+=`(?:${m.join("|")})`}}else n+=`(?:(?!(?:${u})).)*?`}else n+=`(?!(?:${u})$).*`;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 u=t.indexOf(":]",l+2);if(u!==-1){l=u+2;continue}}if(t[l]==="]")break;l++}let c=o;for(;o<t.length&&t[o]!=="]";){if(t[o]==="["&&o+1<t.length&&t[o+1]===":"){let u=t.indexOf(":]",o+2);if(u!==-1){let f=t.slice(o+2,u),d=co(f);a+=d,o=u+2;continue}}if(t[o]==="\\"&&o+1<t.length){a+=`\\${t[o+1]}`,o+=2;continue}if(t[o]==="-"){let u=o===c,f=o+1===l;u||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=uo(t,r+1);if(o!==-1){if(i==="@"){let a=t.slice(r+2,o),c=fo(a).map(u=>this.computePatternLength(u));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){n+=c[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 ho(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 op(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 Ec(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 Rr(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 c of l.parts)c.type==="ParameterExpansion"&&(c.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&(!c.operation||c.operation.type==="PatternRemoval"||c.operation.type==="PatternReplacement")&&(s=!0),(c.operation?.type==="VarNamePrefix"||c.operation?.type==="ArrayKeys")&&(o=!0),c.operation?.type==="Indirection"&&(a=!0));l.type==="CommandSubstitution"&&(n=!0),l.type==="ParameterExpansion"&&(i=!0,(l.parameter==="@"||l.parameter==="*")&&(r=!0),op(l)&&(t=!0),(l.operation?.type==="VarNamePrefix"||l.operation?.type==="ArrayKeys")&&(o=!0),l.operation?.type==="Indirection"&&(a=!0)),l.type==="Glob"&&ho(l.pattern)&&(i=!0)}return{hasQuoted:t,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:i,hasVarNamePrefixExpansion:o,hasIndirection:a}}var ap=`
94
- `;function Mn(e,t){if(e>=t)throw new C(`array element limit exceeded (${t})`,"array_elements")}function po(e,t,n,r,s){Mn(e.length,s),Mn(t.length,s),e.push(n),t.push(r)}function Pe(e){return e.get("IFS")??ap}function Te(e){return e.get("IFS")===""}function As(e){let t=Pe(e);if(t==="")return!0;for(let n of t)if(n!==" "&&n!==" "&&n!==`
95
- `)return!1;return!0}function bc(e){let t=!1,n=[];for(let r of e.split(""))r==="-"?t=!0:/[\\^$.*+?()[\]{}|]/.test(r)?n.push(`\\${r}`):r===" "?n.push("\\t"):r===`
96
- `?n.push("\\n"):n.push(r);return t&&n.push("\\-"),n.join("")}function Y(e){let t=e.get("IFS");return t===void 0?" ":t[0]||""}var lp=`
97
- `;function cp(e){return lp.includes(e)}function mo(e){let t=new Set,n=new Set;for(let r of e)cp(r)?t.add(r):n.add(r);return{whitespace:t,nonWhitespace:n}}function yo(e,t,n,r,s){if(t==="")return e===""?{words:[],wordStarts:[]}:(Mn(0,n),{words:[e],wordStarts:[0]});let{whitespace:i,nonWhitespace:o}=mo(t),a=[],l=[],c=0;for(;c<e.length&&i.has(e[c]);)c++;if(c>=e.length)return{words:[],wordStarts:[]};if(o.has(e[c]))for(po(a,l,"",c,n),c++;c<e.length&&i.has(e[c]);)c++;for(;c<e.length&&!(r!==void 0&&a.length>=r);){let u=c;for(;c<e.length;){let f=e[c];if(!s&&f==="\\"){c++,c<e.length&&c++;continue}if(i.has(f)||o.has(f))break;c++}if(po(a,l,e.substring(u,c),u,n),c>=e.length)break;for(;c<e.length&&i.has(e[c]);)c++;if(c<e.length&&o.has(e[c])){for(c++;c<e.length&&i.has(e[c]);)c++;for(;c<e.length&&o.has(e[c])&&!(r!==void 0&&a.length>=r);)for(po(a,l,"",c,n),c++;c<e.length&&i.has(e[c]);)c++}}return{words:a,wordStarts:l}}function vs(e,t,n){if(t==="")return e&&Mn(0,n),{words:e?[e]:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};if(e==="")return{words:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};let{whitespace:r,nonWhitespace:s}=mo(t),i=[],o=0,a=!1,l=!1,c=o;for(;o<e.length&&r.has(e[o]);)o++;if(o>c&&(a=!0),o>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(s.has(e[o]))for(Mn(i.length,n),i.push(""),o++;o<e.length&&r.has(e[o]);)o++;for(;o<e.length;){let u=o;for(;o<e.length;){let d=e[o];if(r.has(d)||s.has(d))break;o++}if(Mn(i.length,n),i.push(e.substring(u,o)),o>=e.length){l=!1;break}let f=o;for(;o<e.length&&r.has(e[o]);)o++;if(o<e.length&&s.has(e[o])){for(o++;o<e.length&&r.has(e[o]);)o++;for(;o<e.length&&s.has(e[o]);)for(Mn(i.length,n),i.push(""),o++;o<e.length&&r.has(e[o]);)o++}o>=e.length&&o>f&&(l=!0)}return{words:i,hadLeadingDelimiter:a,hadTrailingDelimiter:l}}function he(e,t,n){return vs(e,t,n).words}function up(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Sc(e,t,n){if(t==="")return e;let{whitespace:r,nonWhitespace:s}=mo(t),i=e.length;for(;i>0&&r.has(e[i-1]);){if(!n&&i>=2){let a=0,l=i-2;for(;l>=0&&e[l]==="\\";)a++,l--;if(a%2===1)break}i--}let o=e.substring(0,i);if(o.length>=1&&s.has(o[o.length-1])){if(!n&&o.length>=2){let l=0,c=o.length-2;for(;c>=0&&o[c]==="\\";)l++,c--;if(l%2===1)return o}let a=o.substring(0,o.length-1);if(!up(a,s))return a}return o}function fe(e,t){return e.state.namerefs?.has(t)??!1}function Qt(e,t){e.state.namerefs??=new Set,e.state.namerefs.add(t)}function Ac(e,t){e.state.namerefs?.delete(t),e.state.boundNamerefs?.delete(t),e.state.invalidNamerefs?.delete(t)}function vc(e,t){e.state.invalidNamerefs??=new Set,e.state.invalidNamerefs.add(t)}function kc(e,t){return e.state.invalidNamerefs?.has(t)??!1}function go(e,t){e.state.boundNamerefs??=new Set,e.state.boundNamerefs.add(t)}function ks(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let s=n[1],i=De(e,s),o=e.state.associativeArrays?.has(s)??!1;return i||o}return De(e,t)?!0:e.state.env.has(t)}function Ge(e,t,n=100){if(!fe(e,t)||kc(e,t))return t;let r=new Set,s=t;for(;n-- >0;){if(r.has(s))return;if(r.add(s),!fe(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 Bn(e,t){if(fe(e,t))return e.state.env.get(t)}function xs(e,t,n,r=100){if(!fe(e,t)||kc(e,t))return t;let s=new Set,i=t;for(;r-- >0;){if(s.has(i))return;if(s.add(i),!fe(e,i))return i;let o=e.state.env.get(i);if(o===void 0||o==="")return n!==void 0?/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&ks(e,n)?i:null:i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(o))return i;i=o}}function xc(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 K(e,t){return t==="FUNCNAME"?(e.state.funcNameStack??[]).map((i,o)=>[o,i]):t==="BASH_LINENO"?(e.state.callLineStack??[]).map((i,o)=>[o,String(i)]):t==="BASH_SOURCE"?(e.state.sourceStack??[]).map((i,o)=>[o,i]):e.state.associativeArrays?.has(t)?Tt(e,t).map(i=>[i,ce(e,t,i)??""]):xe(e,t).map(s=>[s,ce(e,t,s)??""])}function vt(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)?De(e,t):De(e,t)}async function le(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 o="";return o+="h",e.state.options.errexit&&(o+="e"),e.state.options.noglob&&(o+="f"),e.state.options.nounset&&(o+="u"),e.state.options.verbose&&(o+="v"),e.state.options.xtrace&&(o+="x"),o+="B",e.state.options.noclobber&&(o+="C"),o+="s",o}case"*":{let o=Number.parseInt(e.state.env.get("#")||"0",10);if(o===0)return"";let a=[];for(let l=1;l<=o;l++)a.push(e.state.env.get(String(l))||"");return a.join(Y(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 hl;case"!":return String(e.state.lastBackgroundPid);case"BASHPID":return String(e.state.bashPid);case"LINENO":return String(e.state.currentLine);case"FUNCNAME":{let o=e.state.funcNameStack?.[0];if(o!==void 0)return o;if(n&&e.state.options.nounset)throw new Ke("FUNCNAME");return""}case"BASH_LINENO":{let o=e.state.callLineStack?.[0];if(o!==void 0)return String(o);if(n&&e.state.options.nounset)throw new Ke("BASH_LINENO");return""}case"BASH_SOURCE":{let o=e.state.sourceStack?.[0];if(o!==void 0)return o;if(n&&e.state.options.nounset)throw new Ke("BASH_SOURCE");return""}}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(t))throw new rt(`\${${t}}`);let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let o=s[1],a=s[2];if(fe(e,o)){let f=Ge(e,o);if(f&&f!==o){if(f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return"";o=f}}if(a==="@"||a==="*"){let f=K(e,o);if(f.length>0)return f.map(([,h])=>h).join(" ");let d=e.state.env.get(o);return d!==void 0?d:""}if(o==="FUNCNAME"){let f=Number.parseInt(a,10);return!Number.isNaN(f)&&f>=0?e.state.funcNameStack?.[f]??"":""}if(o==="BASH_LINENO"){let f=Number.parseInt(a,10);if(!Number.isNaN(f)&&f>=0){let d=e.state.callLineStack?.[f];return d!==void 0?String(d):""}return""}if(o==="BASH_SOURCE"){let f=Number.parseInt(a,10);return!Number.isNaN(f)&&f>=0?e.state.sourceStack?.[f]??"":""}if(e.state.associativeArrays?.has(o)){let f=ds(a);f=xc(e,f);let d=ce(e,o,f);if(d===void 0&&n&&e.state.options.nounset)throw new Ke(`${o}[${a}]`);return d||""}let c;if(/^-?\d+$/.test(a))c=Number.parseInt(a,10);else try{let f=new Q,d=oe(f,a);c=await ee(e,d.expression)}catch{let f=e.state.env.get(a);c=f?Number.parseInt(f,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let f=K(e,o),d=e.state.currentLine;if(f.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${o}: bad array subscript
98
- `,"";let p=Math.max(...f.map(([E])=>typeof E=="number"?E:0))+1+c;return p<0?(e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${o}: bad array subscript
99
- `,""):ce(e,o,p)||""}let u=ce(e,o,c);if(u!==void 0)return u;if(c===0){let f=e.state.env.get(o);if(f!==void 0)return f}if(n&&e.state.options.nounset)throw new Ke(`${o}[${c}]`);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 Ke(t);return o||""}if(fe(e,t)){let o=Ge(e,t);if(o===void 0)return"";if(o!==t)return await le(e,o,n,r);let a=e.state.env.get(t);if((a===void 0||a==="")&&n&&e.state.options.nounset)throw new Ke(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(vt(e,t)){let o=ce(e,t,0);if(o!==void 0)return o;if(n&&e.state.options.nounset)throw new Ke(t);return""}if(n&&e.state.options.nounset)throw new Ke(t);return""}async function Lt(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(fe(e,s)){let l=Ge(e,s);if(l&&l!==s){if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;s=l}}if(i==="@"||i==="*")return K(e,s).length>0?!0:e.state.env.has(s);if(e.state.associativeArrays?.has(s)){let l=xc(e,ds(i));return cn(e,s,l)}let a;if(/^-?\d+$/.test(i))a=Number.parseInt(i,10);else try{let l=new Q,c=oe(l,i);a=await ee(e,c.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=K(e,s);if(l.length===0)return!1;let u=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+a;return u<0?!1:cn(e,s,u)}return cn(e,s,a)}if(fe(e,t)){let s=Ge(e,t);return s===void 0||s===t?e.state.env.has(t):Lt(e,s)}return e.state.env.has(t)?!0:vt(e,t)?cn(e,t,0):!1}async function Pc(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 le(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 le(e,i);n+=o,r=s;continue}if(/[*@#?\-!$]/.test(t[r+1]||"")){let s=t[r+1],i=await le(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 le(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 wo(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 c=n.slice(o+2,l-1);if(e.execFn){let u=await e.execFn(c,{signal:e.state.signal});i+=u.stdout.replace(/\n+$/,""),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.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 c=n.slice(o+2,l-1),u=await le(e,c);i+=u,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),c=await le(e,l);i+=c,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 c=await e.execFn(l,{signal:e.state.signal});i+=c.stdout.replace(/\n+$/,""),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr)}o=a+1}else i+=n[o],o++;return i}var Or=1e4,Eo={maxResults:Or,maxStringBytes:10*1024*1024};function Ps(e,t,n,r){if(e.length>=n.maxResults)return!1;let s=W(t);if(s>n.maxStringBytes-r.value)throw new C(`brace expansion string limit exceeded (${n.maxStringBytes} bytes)`,"string_length");return e.push(t),r.value+=s,!0}function fp(e,t,n,r,s,i=Eo){let o=n??1;o===0&&(o=1);let a=Math.abs(o),l=[],c=0;if(r?.match(/^-?0\d/)&&(c=Math.max(c,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length)),c>i.maxStringBytes)throw new C(`brace expansion padding limit exceeded (${i.maxStringBytes} bytes)`,"string_length");let u={value:0},f=d=>{if(c>0){let h=d<0,p=String(Math.abs(d)).padStart(c,"0");return h?`-${p}`:p}return String(d)};if(e<=t)for(let d=e,h=0;d<=t&&h<Or&&Ps(l,f(d),i,u);d+=a,h++);else for(let d=e,h=0;d>=t&&h<Or&&Ps(l,f(d),i,u);d-=a,h++);return l}function dp(e,t,n,r=Eo){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",c=e>="a"&&e<="z",u=t>="A"&&t<="Z",f=t>="a"&&t<="z";if(l&&f||c&&u){let p=n!==void 0?`..${n}`:"";throw new Kr(`{${e}..${t}${p}}: invalid sequence`)}let d=[],h={value:0};if(i<=o)for(let p=i,m=0;p<=o&&m<Or&&Ps(d,String.fromCharCode(p),r,h);p+=a,m++);else for(let p=i,m=0;p>=o&&m<Or&&Ps(d,String.fromCharCode(p),r,h);p-=a,m++);return d}function bo(e,t,n,r,s,i=Eo){let o=n!==void 0?`..${n}`:"";return typeof e=="number"&&typeof t=="number"?{expanded:fp(e,t,n,r,s,i),literal:`{${e}..${t}${o}}`}:typeof e=="string"&&typeof t=="string"?{expanded:dp(e,t,n,i),literal:`{${e}..${t}${o}}`}:{expanded:null,literal:`{${e}..${t}${o}}`}}function $c(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 Ft(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\(/.test(e))}function So(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 ot(e){return e.replace(/([*?[\]\\()|])/g,"\\$1")}function Jn(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}function re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function te(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=hp(e,s+1);if(o!==-1){let a=e.slice(s+2,o),c=pp(a).map(f=>te(f,t,n)),u=c.length>0?c.join("|"):"(?:)";i==="@"?r+=`(?:${u})`:i==="*"?r+=`(?:${u})*`:i==="+"?r+=`(?:${u})+`:i==="?"?r+=`(?:${u})?`:i==="!"&&(r+=`(?!(?:${u})$).*`),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=mp(e,s);if(o===-1)r+="\\[",s++;else{let a=e.slice(s+1,o);r+=yp(a),s=o+1}}else/[\^$.|+(){}]/.test(i)?(r+=`\\${i}`,s++):(r+=i,s++)}return r}function hp(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 pp(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 mp(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 yp(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+=wp(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 gp=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 wp(e){return gp.get(e)??""}function kt(e,t,n,r,s){if(r==="prefix")return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),ge(`^${n}`,"s").replace(t,"");let i=ge(`${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=ge(`^(?:.*)(${n})$`,"s").exec(t);if(!o)return t;let a=o[1]??"";return t.slice(0,t.length-a.length)}function er(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 $s(e,t,n,r,s){let i=new Hn(e.limits.maxStringLength,"pattern replacement",()=>new C(`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 Cc(e){let t=[],n=0;return{append(r){let s=W(r);if(s>e-n)throw new C(`prompt expansion exceeds string length limit (${e} bytes)`,"string_length");r&&t.push(r),n+=s},build:()=>t.join("")}}function Ep(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=Cc(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 Dr(e,t){let n=Cc(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")||"/",c=a.startsWith(l)?`~${a.slice(l.length)}`:a,u=a.split("/").pop()||a,f=new Date,d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],p=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(`
100
- `),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(o),r+=2;break;case"H":n.append(i),r+=2;break;case"w":n.append(c),r+=2;break;case"W":n.append(u),r+=2;break;case"d":{let S=String(f.getDate()).padStart(2," ");n.append(`${d[f.getDay()]} ${h[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(Ep(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(p),r+=2;break;case"!":n.append(p),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 hn(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`
101
- `: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 et(e,t){e.state.readonlyVars=e.state.readonlyVars||new Set,e.state.readonlyVars.add(t)}function He(e,t){return e.state.readonlyVars?.has(t)??!1}function de(e,t,n="bash"){if(He(e,t)){let r=`${n}: ${t}: readonly variable
102
- `;throw new G(1,"",r)}return null}function xt(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 Cs(e,t){e.state.exportedVars?.delete(t)}function pn(e,t){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))return"";let n="",r=$e(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"),fe(e,t)&&(n+="n"),He(e,t)&&(n+="r"),e.state.exportedVars?.has(t)&&(n+="x"),n}async function Nc(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 Rc(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:assign_default"),(r.isUnset||n.checkEmpty&&r.isEmpty)&&n.word){let o=await s(e,n.word.parts,r.inDoubleQuotes),a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let[,l,c]=a,u;if(/^\d+$/.test(c))u=Number.parseInt(c,10);else{try{let f=new Q,d=oe(f,c);u=await ee(e,d.expression)}catch{let f=e.state.env.get(c);u=f?Number.parseInt(f,10):0}Number.isNaN(u)&&(u=0)}H(e,l,u,o)}else e.state.env.set(t,o);return o}return r.effectiveValue}async function Oc(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:error_if_unset"),r.isUnset||n.checkEmpty&&r.isEmpty){let o=n.word?await s(e,n.word.parts,r.inDoubleQuotes):`${t}: parameter null or not set`;throw new G(1,"",`bash: ${o}
103
- `)}return r.effectiveValue}async function Dc(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 Ic(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_removal");let i="",o=e.state.shoptOptions.extglob;if(n.pattern)for(let a of n.pattern.parts)if(a.type==="Glob")i+=te(a.pattern,n.greedy,o);else if(a.type==="Literal")i+=te(a.value,n.greedy,o);else if(a.type==="SingleQuoted"||a.type==="Escaped")i+=re(a.value);else if(a.type==="DoubleQuoted"){let l=await r(e,a.parts);i+=re(l)}else if(a.type==="ParameterExpansion"){let l=await s(e,a);i+=te(l,n.greedy,o)}else{let l=await s(e,a);i+=re(l)}return kt(e,t,i,n.side,n.greedy)}async function Tc(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_replacement");let i="",o=e.state.shoptOptions.extglob;if(n.pattern)for(let c of n.pattern.parts)if(c.type==="Glob")i+=te(c.pattern,!0,o);else if(c.type==="Literal")i+=te(c.value,!0,o);else if(c.type==="SingleQuoted"||c.type==="Escaped")i+=re(c.value);else if(c.type==="DoubleQuoted"){let u=await r(e,c.parts);i+=re(u)}else if(c.type==="ParameterExpansion"){let u=await s(e,c);i+=te(u,!0,o)}else{let u=await s(e,c);i+=re(u)}let a=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 c=ge(i,l);return $s(e,t,c,a,n.all)}catch(c){if(c instanceof C)throw c;return t}}function _c(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=K(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)&&vt(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=ce(e,t,0)||"";return String([...s].length)}return String([...n].length)}async function Lc(e,t,n,r){e.coverage?.hit("bash:expansion:substring");let s=await ee(e,r.offset.expression),i=r.length?await ee(e,r.length.expression):void 0;if(t==="@"||t==="*"){let c=Number.parseInt(e.state.env.get("#")||"0",10),u=[];for(let p=1;p<=c;p++)u.push(e.state.env.get(String(p))||"");let f=e.state.env.get("0")||"bash",d,h;if(s<=0)if(d=[f,...u],s<0){if(h=d.length+s,h<0)return""}else h=0;else d=u,h=s-1;if(h<0||h>=d.length)return"";if(i!==void 0){let p=i<0?d.length+i:h+i;return d.slice(h,Math.max(h,p)).join(" ")}return d.slice(h).join(" ")}let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(o){let c=o[1];if(e.state.associativeArrays?.has(c))throw new G(1,"",`bash: \${${c}[@]: 0: 3}: bad substitution
104
- `);let u=K(e,c),f=0;if(s<0){if(u.length>0){let d=u[u.length-1][0],p=(typeof d=="number"?d:0)+1+s;if(p<0||(f=u.findIndex(([m])=>typeof m=="number"&&m>=p),f<0))return""}}else if(f=u.findIndex(([d])=>typeof d=="number"&&d>=s),f<0)return"";if(i!==void 0){if(i<0)throw new ue(`${o[1]}[@]: substring expression < 0`);return u.slice(f,f+i).map(([,d])=>d).join(" ")}return u.slice(f).map(([,d])=>d).join(" ")}let a=[...n],l=s;if(l<0&&(l=Math.max(0,a.length+l)),i!==void 0){if(i<0){let c=a.length+i;return a.slice(l,Math.max(l,c)).join("")}return a.slice(l,l+i).join("")}return a.slice(l).join("")}async function Fc(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:case_modification"),n.pattern){let i=e.state.shoptOptions.extglob,o="";for(let f of n.pattern.parts)if(f.type==="Glob")o+=te(f.pattern,!0,i);else if(f.type==="Literal")o+=te(f.value,!0,i);else if(f.type==="SingleQuoted"||f.type==="Escaped")o+=re(f.value);else if(f.type==="DoubleQuoted"){let d=await r(e,f.parts);o+=re(d)}else if(f.type==="ParameterExpansion"){let d=await s(e,f);o+=te(d,!0,i)}let a=ge(`^(?:${o})$`),l=n.direction==="upper"?f=>f.toUpperCase():f=>f.toLowerCase(),c="",u=!1;for(let f of t)!n.all&&u?c+=f:a.test(f)?(c+=l(f),u=!0):c+=f;return c}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 Mc(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 K(e,i[1]).map(([,c])=>hn(c)).join(" ");if(i&&s.operator==="a")return pn(e,i[1]);let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[.+\]$/);if(o&&s.operator==="a")return pn(e,o[1]);switch(s.operator){case"Q":return r?"":hn(n);case"P":return Dr(e,n);case"a":return pn(e,t);case"A":return r?"":`${t}=${hn(n)}`;case"E":return n.replace(/\\([\\abefnrtv'"?])/g,(a,l)=>{switch(l){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
105
- `;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?"":hn(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 Bc(e,t,n,r,s,i,o=!1){if(e.coverage?.hit("bash:expansion:indirection"),fe(e,t))return Bn(e,t)||"";let a=/^[a-zA-Z_][a-zA-Z0-9_]*\[([@*])\]$/.test(t);if(r){if(s.innerOp?.type==="UseAlternative")return"";throw new rt(`\${!${t}}`)}let l=n;if(a&&(l===""||l.includes(" ")))throw new rt(`\${!${t}}`);let c=l.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(c&&c[1].includes("~"))throw new rt(`\${!${t}}`);if(s.innerOp){let u={type:"ParameterExpansion",parameter:l,operation:s.innerOp};return i(e,u,o)}return await le(e,l)}function Wc(e,t){e.coverage?.hit("bash:expansion:array_keys");let r=K(e,t.array).map(([s])=>String(s));return t.star?r.join(Y(e.state.env)):r.join(" ")}function Vc(e,t){e.coverage?.hit("bash:expansion:var_name_prefix");let n=er(e,t.prefix);return t.star?n.join(Y(e.state.env)):n.join(" ")}function zc(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=K(e,o);if(l.length===0)return{isEmpty:!0,effectiveValue:""};if(a==="*"){let c=Y(e.state.env),u=l.map(([,f])=>f).join(c);return{isEmpty:r?u==="":!1,effectiveValue:u}}return{isEmpty:l.length===1&&l.every(([,c])=>c===""),effectiveValue:l.map(([,c])=>c).join(" ")}}return{isEmpty:n==="",effectiveValue:n}}function mn(e,t){e.lastExitCode=t,e.env.set("?",String(t)),e.lastSubstitutionExitCode=t}function bp(e){switch(e.operator){case"<":case"<&":case"<<":case"<<-":case"<<<":case"<>":return e.fd===null||e.fd===0;default:return!1}}function Ns(e,t){return t.some(bp)?0:e.lastSubstitutionExitCode??0}function Uc(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 jc(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 Q,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=ht(e.state.arrays),a=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let c=await e.executeScript(r),u=c.exitCode;return e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.suppressVerbose=l,mn(e.state,u),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr),e.state.bashPid=s,c.stdout.replace(/\n+$/,"")}catch(c){return e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.bashPid=s,e.state.suppressVerbose=l,Jr(c),c instanceof G?(mn(e.state,c.exitCode),c.stdout?.replace(/\n+$/,"")??""):""}}function Ao(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+=ot(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=Sp(e,a);n+=ot(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 Sp(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 qc(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+=ot(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 Ap(e,a);n+=ot(l),r=i+1;continue}}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=jc(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 Ap(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=jc(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 vo(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 yn(e,t){return t.split(":").map(n=>vo(e,n)).join(":")}function _e(e,t,n,r){if(e.length>n-t.length)throw new C(`${r} element limit exceeded (${n})`,"array_elements");for(let s of t)e.push(s)}async function vp(e,t,n,r){let s="";for(let i of t.parts)if(i.type==="Glob")s+=te(i.pattern,!0,e.state.shoptOptions.extglob);else if(i.type==="Literal")s+=te(i.value,!0,e.state.shoptOptions.extglob);else if(i.type==="SingleQuoted"||i.type==="Escaped")s+=re(i.value);else if(i.type==="DoubleQuoted"){let o=await n(e,i.parts);s+=re(o)}else if(i.type==="ParameterExpansion"){let o=await r(e,i);s+=te(o,!0,e.state.shoptOptions.extglob)}else{let o=await r(e,i);s+=re(o)}return s}async function Gc(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]==="*",c=i.operation,u=K(e,a),f=u.map(([,E])=>E);if(u.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="";c.pattern&&(d=await vp(e,c.pattern,n,r));let h=c.replacement?await n(e,c.replacement.parts):"",p=d;c.anchor==="start"?p=`^${d}`:c.anchor==="end"&&(p=`${d}$`);let m=[];try{let E=ge(p,c.all?"g":"");for(let S of f)m.push(E.replace(S,h))}catch{m.push(...f)}if(l){let E=Y(e.state.env);return{values:[m.join(E)],quoted:!0}}return{values:m,quoted:!0}}async function Hc(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]==="*",c=i.operation,u=K(e,a),f=u.map(([,m])=>m);if(u.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="",h=e.state.shoptOptions.extglob;if(c.pattern)for(let m of c.pattern.parts)if(m.type==="Glob")d+=te(m.pattern,c.greedy,h);else if(m.type==="Literal")d+=te(m.value,c.greedy,h);else if(m.type==="SingleQuoted"||m.type==="Escaped")d+=re(m.value);else if(m.type==="DoubleQuoted"){let E=await n(e,m.parts);d+=re(E)}else if(m.type==="ParameterExpansion"){let E=await r(e,m);d+=te(E,c.greedy,h)}else{let E=await r(e,m);d+=re(E)}let p=[];for(let m of f)p.push(kt(e,m,d,c.side,c.greedy));if(l){let m=Y(e.state.env);return{values:[p.join(m)],quoted:!0}}return{values:p,quoted:!0}}async function Zc(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 c=K(e,l),u=c.length>0||e.state.env.has(l),f=c.length===0||c.length===1&&c.every(([,h])=>h===""),d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=u&&!(d&&f):o=!u||d&&f,!o){if(c.length>0){let p=c.map(([,m])=>m);if(a){let m=Y(e.state.env);return{values:[p.join(m)],quoted:!0}}return{values:p,quoted:!0}}let h=e.state.env.get(l);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}}else{let l=r.parameter,c=await Lt(e,l),u=await le(e,l),f=u==="",d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=c&&!(d&&f):o=!c||d&&f,!o)return{values:[u],quoted:!0}}if(o&&s.word){let l=s.word.parts,c=null,u=!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){c=d[1],u=d[2]==="*";break}}if(c){let f=K(e,c);if(f.length>0){let h=f.map(([,p])=>p);if(u||a){let p=Y(e.state.env);return{values:[h.join(p)],quoted:!0}}return{values:h,quoted:!0}}let d=e.state.env.get(c);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}return null}async function Qc(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,c=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]==="*",c=E.operation;break}}}if(o===-1||o===0&&o===i.parts.length-1)return null;let u="";for(let m=0;m<o;m++)u+=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=K(e,a),h=d.map(([,m])=>m);if(d.length===0){let m=e.state.env.get(a);if(m!==void 0)h=[m];else{if(l)return{values:[u+f],quoted:!0};let E=u+f;return{values:E?[E]:[],quoted:!0}}}if(c?.type==="PatternRemoval"){let m=c,E="",S=e.state.shoptOptions.extglob;if(m.pattern)for(let g of m.pattern.parts)if(g.type==="Glob")E+=te(g.pattern,m.greedy,S);else if(g.type==="Literal")E+=te(g.value,m.greedy,S);else if(g.type==="SingleQuoted"||g.type==="Escaped")E+=re(g.value);else if(g.type==="DoubleQuoted"){let y=await s(e,g.parts);E+=re(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);E+=te(y,m.greedy,S)}else{let y=await r(e,g);E+=re(y)}h=h.map(g=>kt(e,g,E,m.side,m.greedy))}else if(c?.type==="PatternReplacement"){let m=c,E="";if(m.pattern)for(let y of m.pattern.parts)if(y.type==="Glob")E+=te(y.pattern,!0,e.state.shoptOptions.extglob);else if(y.type==="Literal")E+=te(y.value,!0,e.state.shoptOptions.extglob);else if(y.type==="SingleQuoted"||y.type==="Escaped")E+=re(y.value);else if(y.type==="DoubleQuoted"){let b=await s(e,y.parts);E+=re(b)}else if(y.type==="ParameterExpansion"){let b=await r(e,y);E+=te(b,!0,e.state.shoptOptions.extglob)}else{let b=await r(e,y);E+=re(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=ge(g,m.all?"g":"");h=h.map(b=>y.replace(b,S))}catch{}}if(l){let m=Y(e.state.env);return{values:[u+h.join(m)+f],quoted:!0}}return h.length===1?{values:[u+h[0]+f],quoted:!0}:{values:[u+h[0],...h.slice(1,-1),h[h.length-1]+f],quoted:!0}}async function Kc(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 h=0;h<s.parts.length;h++){let p=s.parts[h];if(p.type==="ParameterExpansion"&&!p.operation){let m=p.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(m){i=h,o=m[1],a=m[2]==="*";break}}}if(i===-1)return null;let l="";for(let h=0;h<i;h++)l+=await r(e,s.parts[h]);let c="";for(let h=i+1;h<s.parts.length;h++)c+=await r(e,s.parts[h]);let u=K(e,o),f=u.map(([,h])=>h);if(u.length===0){let h=e.state.env.get(o);if(h!==void 0)return{values:[l+h+c],quoted:!0};if(a)return{values:[l+c],quoted:!0};let p=l+c;return{values:p?[p]:[],quoted:!0}}if(a){let h=Y(e.state.env);return{values:[l+f.join(h)+c],quoted:!0}}return f.length===1?{values:[l+f[0]+c],quoted:!0}:{values:[l+f[0],...f.slice(1,-1),f[f.length-1]+c],quoted:!0}}async function Xc(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 G(1,"",`bash: \${${o}[@]: 0: 3}: bad substitution
106
- `);let c=l.offset?await n(e,l.offset.expression):0,u=l.length?await n(e,l.length.expression):void 0,f=K(e,o);if(f.length>e.limits.maxArrayElements)throw new C(`array transform element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let d=0;if(c<0){if(f.length>0){let p=f[f.length-1][0],E=(typeof p=="number"?p:0)+1+c;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(([p])=>typeof p=="number"&&p>=c),d<0&&(d=f.length);let h;if(u!==void 0){if(u<0)throw new ue(`${o}[@]: substring expression < 0`);h=f.slice(d,d+u).map(([,p])=>p)}else h=f.slice(d).map(([,p])=>p);if(h.length===0)return{values:[],quoted:!0};if(a){let p=Y(e.state.env);return{values:[h.join(p)],quoted:!0}}return{values:h,quoted:!0}}function Yc(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=K(e,i);if(l.length===0){let d=e.state.env.get(i);if(d!==void 0){let h;switch(a.operator){case"a":h="";break;case"P":h=Dr(e,d);break;case"Q":h=hn(d);break;default:h=d}if(W(h)>e.limits.maxStringLength)throw new C(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[h],quoted:!0}}return o?{values:[""],quoted:!0}:{values:[],quoted:!0}}let c=pn(e,i),u=[],f=0;for(let[,d]of l){let h;switch(a.operator){case"a":h=c;break;case"P":h=Dr(e,d);break;case"Q":h=hn(d);break;case"u":h=d.charAt(0).toUpperCase()+d.slice(1);break;case"U":h=d.toUpperCase();break;case"L":h=d.toLowerCase();break;default:h=d}let p=W(h);if(p>e.limits.maxStringLength-f)throw new C(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");u.push(h),f+=p}if(o){let d=Y(e.state.env);if(Math.max(0,u.length-1)*W(d)>e.limits.maxStringLength-f)throw new C(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u.join(d)],quoted:!0}}return{values:u,quoted:!0}}function Jc(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(fe(e,i)){let l=Bn(e,i);if(l?.endsWith("[@]")||l?.endsWith("[*]"))return{values:[],quoted:!0}}let o=K(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 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)return null;let s=n.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)||!fe(e,s))return null;let i=Bn(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=K(e,a);if(l.length>0)return{values:l.map(([,u])=>u),quoted:!0};let c=e.state.env.get(a);return c!==void 0?{values:[c],quoted:!0}:{values:[],quoted:!0}}async function tu(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 le(e,o.parameter),c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c){if(!a.innerOp&&(l==="@"||l==="*")){let p=Number.parseInt(e.state.env.get("#")||"0",10),m=[];for(let E=1;E<=p;E++)m.push(e.state.env.get(String(E))||"");return l==="*"?{values:[m.join(Y(e.state.env))],quoted:!0}:{values:m,quoted:!0}}return null}let u=c[1],f=c[2]==="*",d=K(e,u);if(a.innerOp){if(a.innerOp.type==="Substring")return kp(e,d,u,f,a.innerOp);if(a.innerOp.type==="DefaultValue"||a.innerOp.type==="UseAlternative"||a.innerOp.type==="AssignDefault"||a.innerOp.type==="ErrorIfUnset")return xp(e,d,u,f,a.innerOp,s);if(a.innerOp.type==="Transform"&&a.innerOp.operator==="a"){let m=pn(e,u),E=d.map(()=>m);return f?{values:[E.join(Y(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let p=[];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);p.push(g)}finally{S!==void 0?e.state.env.set("_indirect_elem_",S):e.state.env.delete("_indirect_elem_")}}return f?{values:[p.join(Y(e.state.env))],quoted:!0}:{values:p,quoted:!0}}if(d.length>0){let p=d.map(([,m])=>m);return f?{values:[p.join(Y(e.state.env))],quoted:!0}:{values:p,quoted:!0}}let h=e.state.env.get(u);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}async function kp(e,t,n,r,s){let i=s.offset?await ee(e,s.offset.expression):0,o=s.length?await ee(e,s.length.expression):void 0,a=0;if(i<0){if(t.length>0){let u=t[t.length-1][0],d=(typeof u=="number"?u:0)+1+i;if(d<0)return{values:[],quoted:!0};if(a=t.findIndex(([h])=>typeof h=="number"&&h>=d),a<0)return{values:[],quoted:!0}}}else if(a=t.findIndex(([u])=>typeof u=="number"&&u>=i),a<0)return{values:[],quoted:!0};let l;if(o!==void 0){if(o<0)throw new ue(`${n}[@]: substring expression < 0`);l=t.slice(a,a+o)}else l=t.slice(a);let c=l.map(([,u])=>u);return r?{values:[c.join(Y(e.state.env))],quoted:!0}:{values:c,quoted:!0}}async function xp(e,t,n,r,s,i){let o=s.checkEmpty??!1,a=t.map(([,u])=>u),l=t.length===0,c=t.length===0;if(s.type==="UseAlternative")return!c&&!(o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(s.type==="DefaultValue")return(c||o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:r?{values:[a.join(Y(e.state.env))],quoted:!0}:{values:a,quoted:!0};if(s.type==="AssignDefault"){if((c||o&&l)&&s.word){let f=await i(e,s.word.parts,!0);return H(e,n,0,f),{values:[f],quoted:!0}}return r?{values:[a.join(Y(e.state.env))],quoted:!0}:{values:a,quoted:!0}}return r?{values:[a.join(Y(e.state.env))],quoted:!0}:{values:a,quoted:!0}}async function nu(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 le(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!l)return null;let c=await Lt(e,n.parameter),u=await le(e,n.parameter)==="",f=r.checkEmpty??!1,d;if(r.type==="UseAlternative"?d=c&&!(f&&u):d=!c||f&&u,d){let h=l[1],p=l[2]==="*",m=K(e,h);if(m.length>0){let S=m.map(([,g])=>g);return p?{values:[S.join(Y(e.state.env))],quoted:!0}:{values:S,quoted:!0}}let E=e.state.env.get(h);return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function ru(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],c=(await le(e,a.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c)return null;let u=await le(e,n.parameter),f=await Lt(e,n.parameter),d=u==="",h=s.checkEmpty??!1,p;if(s.type==="UseAlternative"?p=f&&!(h&&d):p=!f||h&&d,p){let m=c[1],E=c[2]==="*",S=K(e,m);if(S.length>0){let y=S.map(([,b])=>b);return E?{values:[y.join(Y(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 su(e){let t=Number.parseInt(e.state.env.get("#")||"0",10);if(t>e.limits.maxArrayElements)throw new C(`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=W(i);if(o>e.limits.maxStringLength-r)throw new C(`positional parameter string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n.push(i),r+=o}return n}function Os(e,t,n){if(W(t)>n-W(e))throw new C(`positional expansion string limit exceeded (${n} bytes)`,"string_length");return e+t}function ko(e,t,n,r){if(e.length>=r.limits.maxArrayElements)throw new C(`positional expansion element limit exceeded (${r.limits.maxArrayElements})`,"array_elements");let s=W(t);if(s>r.limits.maxStringLength-n.value)throw new C(`positional expansion string limit exceeded (${r.limits.maxStringLength} bytes)`,"string_length");e.push(t),n.value+=s}async function iu(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,c=l.offset?await n(e,l.offset.expression):0,u=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 h=e.state.env.get("0")||"bash",p;if(c<=0){let g=[h,...d],y=g.length+c;if(y<0)p=[];else{let b=c<0?y:0;if(u!==void 0){let A=u<0?g.length+u:b+u;p=g.slice(b,Math.max(b,A))}else p=g.slice(b)}}else{let g=c-1;if(g>=d.length)p=[];else if(u!==void 0){let y=u<0?d.length+u:g+u;p=d.slice(g,Math.max(g,y))}else p=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(p.length===0){let g=m+E;return{values:g?[g]:[],quoted:!0}}if(o){let g=Y(e.state.env);return{values:[m+p.join(g)+E],quoted:!0}}return p.length===1?{values:[m+p[0]+E],quoted:!0}:{values:[m+p[0],...p.slice(1,-1),p[p.length-1]+E],quoted:!0}}async function ou(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,c=su(e),u="";for(let g=0;g<i;g++)u=Os(u,await n(e,s.parts[g]),e.limits.maxStringLength);let f="";for(let g=i+1;g<s.parts.length;g++)f=Os(f,await n(e,s.parts[g]),e.limits.maxStringLength);if(c.length===0){let g=u+f;return{values:g?[g]:[],quoted:!0}}let d="";if(l.pattern)for(let g of l.pattern.parts)if(g.type==="Glob")d+=te(g.pattern,!0,e.state.shoptOptions.extglob);else if(g.type==="Literal")d+=te(g.value,!0,e.state.shoptOptions.extglob);else if(g.type==="SingleQuoted"||g.type==="Escaped")d+=re(g.value);else if(g.type==="DoubleQuoted"){let y=await r(e,g.parts);d+=re(y)}else if(g.type==="ParameterExpansion"){let y=await n(e,g);d+=te(y,!0,e.state.shoptOptions.extglob)}else{let y=await n(e,g);d+=re(y)}let h=l.replacement?await r(e,l.replacement.parts):"",p=d;l.anchor==="start"?p=`^${d}`:l.anchor==="end"&&(p=`${d}$`);let m=[],E={value:0};try{let g=ge(p,l.all?"g":"");for(let y of c){let b=0;g.lastIndex=0;for(let P=g.exec(y);P&&(b++,!!l.all);P=g.exec(y))P[0].length===0&&g.lastIndex++;let A=W(y),k=W(h),v=0,$=/\$(?:\$|&|\d+|<[^>]+>|`|')/g;for(;$.exec(h)!==null;)v++;if(A+b*k+b*v*A>e.limits.maxStringLength-E.value)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");ko(m,g.replace(y,h),E,e)}}catch(g){if(g instanceof C)throw g;for(let y of c)ko(m,y,E,e)}if(o){let g=Y(e.state.env);if(E.value+Math.max(0,m.length-1)*W(g)+W(u)+W(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+m.join(g)+f],quoted:!0}}if(W(u)+E.value+W(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return m.length===1?{values:[u+m[0]+f],quoted:!0}:{values:[u+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function au(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,c=su(e),u="";for(let S=0;S<i;S++)u=Os(u,await n(e,s.parts[S]),e.limits.maxStringLength);let f="";for(let S=i+1;S<s.parts.length;S++)f=Os(f,await n(e,s.parts[S]),e.limits.maxStringLength);if(c.length===0){let S=u+f;return{values:S?[S]:[],quoted:!0}}let d="",h=e.state.shoptOptions.extglob;if(l.pattern)for(let S of l.pattern.parts)if(S.type==="Glob")d+=te(S.pattern,l.greedy,h);else if(S.type==="Literal")d+=te(S.value,l.greedy,h);else if(S.type==="SingleQuoted"||S.type==="Escaped")d+=re(S.value);else if(S.type==="DoubleQuoted"){let g=await r(e,S.parts);d+=re(g)}else if(S.type==="ParameterExpansion"){let g=await n(e,S);d+=te(g,l.greedy,h)}else{let g=await n(e,S);d+=re(g)}let p=[],m={value:0};for(let S of c)ko(p,kt(e,S,d,l.side,l.greedy),m,e);if(o){let S=Y(e.state.env);if(m.value+Math.max(0,p.length-1)*W(S)+W(u)+W(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+p.join(S)+f],quoted:!0}}if(W(u)+m.value+W(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return p.length===1?{values:[u+p[0]+f],quoted:!0}:{values:[u+p[0],...p.slice(1,-1),p[p.length-1]+f],quoted:!0}}async function lu(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 h=r.parts[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")){s=d,i=h.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 c="";for(let d=s+1;d<r.parts.length;d++)c+=await n(e,r.parts[d]);if(a===0){if(i)return{values:[l+c],quoted:!0};let d=l+c;return{values:d?[d]:[],quoted:!0}}let u=[];for(let d=1;d<=a;d++)u.push(e.state.env.get(String(d))||"");if(i){let d=Y(e.state.env);return{values:[l+u.join(d)+c],quoted:!0}}return u.length===1?{values:[l+u[0]+c],quoted:!0}:{values:[l+u[0],...u.slice(1,-1),u[u.length-1]+c],quoted:!0}}function Mt(e,t,n,r){if(t.length>=e.limits.maxArrayElements)throw new C(`unquoted expansion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let s=W(n);if(s>e.limits.maxStringLength-r.value)throw new C(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");t.push(n),r.value+=s}function xo(e,t,n,r){let s=W(n),i=Math.max(0,t.length-1);if(s>0&&i>Math.floor((e.limits.maxStringLength-r)/s))throw new C(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return t.join(n)}function Pp(e){return new dn(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 Ds(e,t){if(e.state.options.noglob)return t;let n=Pp(e),r=[];for(let s of t)if(Ft(s,e.state.shoptOptions.extglob)){let i=await n.expand(s);if(i.length>0)_e(r,i,e.limits.maxArrayElements,"unquoted glob expansion");else{if(n.hasFailglob())throw new en(s);n.hasNullglob()||r.push(s)}}else r.push(s);return r}async function cu(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,c=K(e,i),u=c.map(([,b])=>b);if(c.length===0){let b=e.state.env.get(i);b!==void 0&&(u=[b])}if(u.length===0)return{values:[],quoted:!1};let f="";if(l.pattern)for(let b of l.pattern.parts)if(b.type==="Glob")f+=te(b.pattern,!0,e.state.shoptOptions.extglob);else if(b.type==="Literal")f+=te(b.value,!0,e.state.shoptOptions.extglob);else if(b.type==="SingleQuoted"||b.type==="Escaped")f+=re(b.value);else if(b.type==="DoubleQuoted"){let A=await n(e,b.parts);f+=re(A)}else if(b.type==="ParameterExpansion"){let A=await r(e,b);f+=te(A,!0,e.state.shoptOptions.extglob)}else{let A=await r(e,b);f+=re(A)}let d=l.replacement?await n(e,l.replacement.parts):"",h=f;l.anchor==="start"?h=`^${f}`:l.anchor==="end"&&(h=`${f}$`);let p=[],m={value:0};try{let b=ge(h,l.all?"g":"");for(let A of u)Mt(e,p,$s(e,A,b,d,l.all),m)}catch(b){if(b instanceof C)throw b;for(let A of u)Mt(e,p,A,m)}let E=Pe(e.state.env),S=Te(e.state.env);if(o){let b=Y(e.state.env),A=xo(e,p,b,m.value);return S?{values:A?[A]:[],quoted:!1}:{values:he(A,E,e.limits.maxArrayElements),quoted:!1}}if(S)return{values:p,quoted:!1};let g=[],y={value:0};for(let b of p)if(b==="")Mt(e,g,"",y);else for(let A of he(b,E,e.limits.maxArrayElements))Mt(e,g,A,y);return{values:g,quoted:!1}}async function uu(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,c=K(e,i),u=c.map(([,y])=>y);if(c.length===0){let y=e.state.env.get(i);y!==void 0&&(u=[y])}if(u.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+=te(y.pattern,l.greedy,d);else if(y.type==="Literal")f+=te(y.value,l.greedy,d);else if(y.type==="SingleQuoted"||y.type==="Escaped")f+=re(y.value);else if(y.type==="DoubleQuoted"){let b=await n(e,y.parts);f+=re(b)}else if(y.type==="ParameterExpansion"){let b=await r(e,y);f+=te(b,l.greedy,d)}else{let b=await r(e,y);f+=re(b)}let h=[],p={value:0};for(let y of u)Mt(e,h,kt(e,y,f,l.side,l.greedy),p);let m=Pe(e.state.env),E=Te(e.state.env);if(o){let y=Y(e.state.env),b=xo(e,h,y,p.value);return E?{values:b?[b]:[],quoted:!1}:{values:he(b,m,e.limits.maxArrayElements),quoted:!1}}if(E)return{values:h,quoted:!1};let S=[],g={value:0};for(let y of h)if(y==="")Mt(e,S,"",g);else for(let b of he(y,m,e.limits.maxArrayElements))Mt(e,S,b,g);return{values:S,quoted:!1}}async function fu(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),c=[];for(let g=1;g<=l;g++)c.push(e.state.env.get(String(g))||"");if(c.length===0)return{values:[],quoted:!1};let u="",f=e.state.shoptOptions.extglob;if(a.pattern)for(let g of a.pattern.parts)if(g.type==="Glob")u+=te(g.pattern,a.greedy,f);else if(g.type==="Literal")u+=te(g.value,a.greedy,f);else if(g.type==="SingleQuoted"||g.type==="Escaped")u+=re(g.value);else if(g.type==="DoubleQuoted"){let y=await n(e,g.parts);u+=re(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);u+=te(y,a.greedy,f)}else{let y=await r(e,g);u+=re(y)}let d=[],h={value:0};for(let g of c)Mt(e,d,kt(e,g,u,a.side,a.greedy),h);let p=Pe(e.state.env),m=Te(e.state.env);if(i){let g=Y(e.state.env),y=xo(e,d,g,h.value);return m?{values:y?[y]:[],quoted:!1}:{values:he(y,p,e.limits.maxArrayElements),quoted:!1}}if(m)return{values:d,quoted:!1};let E=[],S={value:0};for(let g of d)if(g==="")Mt(e,E,"",S);else for(let y of he(g,p,e.limits.maxArrayElements))Mt(e,E,y,S);return{values:E,quoted:!1}}async function du(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,c=a.length?await n(e,a.length.expression):void 0,u=Number.parseInt(e.state.env.get("#")||"0",10),f=[];for(let y=1;y<=u;y++)f.push(e.state.env.get(String(y))||"");let d=e.state.env.get("0")||"bash",h;if(l<=0){let y=[d,...f],b=y.length+l;if(b<0)h=[];else{let A=l<0?b:0;if(c!==void 0){let k=c<0?y.length+c:A+c;h=y.slice(A,Math.max(A,k))}else h=y.slice(A)}}else{let y=l-1;if(y>=f.length)h=[];else if(c!==void 0){let b=c<0?f.length+c:y+c;h=f.slice(y,Math.max(y,b))}else h=f.slice(y)}let p="";for(let y=0;y<s;y++)p+=await r(e,t[y]);let m="";for(let y=s+1;y<t.length;y++)m+=await r(e,t[y]);let E=Pe(e.state.env),S=Te(e.state.env);if(h.length===0){let y=p+m;return y?S?{values:[y],quoted:!1}:{values:he(y,E,e.limits.maxArrayElements),quoted:!1}:{values:[],quoted:!1}}let g;if(i){let y=Y(e.state.env),b=p+h.join(y)+m;S?g=b?[b]:[]:g=he(b,E,e.limits.maxArrayElements)}else if(S)h.length===1?g=[p+h[0]+m]:g=[p+h[0],...h.slice(1,-1),h[h.length-1]+m];else{g=[];for(let y=0;y<h.length;y++){let b=h[y];if(y===0&&(b=p+b),y===h.length-1&&(b=b+m),b==="")g.push("");else{let A=he(b,E,e.limits.maxArrayElements);_e(g,A,e.limits.maxArrayElements,"unquoted expansion")}}}return{values:await Ds(e,g),quoted:!1}}async function hu(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 c=1;c<=r;c++)s.push(e.state.env.get(String(c))||"");let i=Pe(e.state.env),o=Te(e.state.env),a=As(e.state.env),l;if(n)if(o)l=s.filter(c=>c!=="");else{let c=Y(e.state.env),u=s.join(c);l=he(u,i,e.limits.maxArrayElements)}else if(o)l=s.filter(c=>c!=="");else if(a){l=[];for(let c of s){if(c==="")continue;let u=he(c,i,e.limits.maxArrayElements);_e(l,u,e.limits.maxArrayElements,"unquoted expansion")}}else{l=[];for(let c of s)if(c==="")l.push("");else{let u=he(c,i,e.limits.maxArrayElements);_e(l,u,e.limits.maxArrayElements,"unquoted expansion")}for(;l.length>0&&l[l.length-1]==="";)l.pop()}return{values:await Ds(e,l),quoted:!1}}async function pu(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=K(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=Pe(e.state.env),l=Te(e.state.env),c=As(e.state.env),u;if(s)if(l)u=o.filter(f=>f!=="");else{let f=Y(e.state.env),d=o.join(f);u=he(d,a,e.limits.maxArrayElements)}else if(l)u=o.filter(f=>f!=="");else if(c){u=[];for(let f of o){if(f==="")continue;let d=he(f,a,e.limits.maxArrayElements);_e(u,d,e.limits.maxArrayElements,"unquoted expansion")}}else{u=[];for(let f of o)if(f==="")u.push("");else{let d=he(f,a,e.limits.maxArrayElements);_e(u,d,e.limits.maxArrayElements,"unquoted expansion")}for(;u.length>0&&u[u.length-1]==="";)u.pop()}return{values:await Ds(e,u),quoted:!1}}function mu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="VarNamePrefix")return null;let n=t[0].operation,r=er(e,n.prefix);if(r.length===0)return{values:[],quoted:!1};let s=Pe(e.state.env),i=Te(e.state.env),o;if(n.star)if(i)o=r;else{let a=Y(e.state.env),l=r.join(a);o=he(l,s,e.limits.maxArrayElements)}else if(i)o=r;else{o=[];for(let a of r){let l=he(a,s,e.limits.maxArrayElements);_e(o,l,e.limits.maxArrayElements,"unquoted expansion")}}return{values:o,quoted:!1}}function yu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="ArrayKeys")return null;let n=t[0].operation,s=K(e,n.array).map(([l])=>String(l));if(s.length===0)return{values:[],quoted:!1};let i=Pe(e.state.env),o=Te(e.state.env),a;if(n.star)if(o)a=s;else{let l=Y(e.state.env),c=s.join(l);a=he(c,i,e.limits.maxArrayElements)}else if(o)a=s;else{a=[];for(let l of s){let c=he(l,i,e.limits.maxArrayElements);_e(a,c,e.limits.maxArrayElements,"unquoted expansion")}}return{values:a,quoted:!1}}async function gu(e,t,n){let r=-1;for(let d=0;d<t.length;d++){let h=t[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")&&!h.operation){r=d;break}}if(r===-1||t.length<=1)return null;let 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=Pe(e.state.env),c=Te(e.state.env),u=As(e.state.env);if(s===0){let d=o+a;return{values:d?[d]:[],quoted:!1}}let f;{let d=[];for(let h=0;h<i.length;h++){let p=i[h];h===0&&(p=o+p),h===i.length-1&&(p=p+a),d.push(p)}if(c)f=d.filter(h=>h!=="");else if(u){f=[];for(let h of d){if(h==="")continue;let p=he(h,l,e.limits.maxArrayElements);_e(f,p,e.limits.maxArrayElements,"unquoted expansion")}}else{f=[];for(let h of d)if(h==="")f.push("");else{let p=he(h,l,e.limits.maxArrayElements);_e(f,p,e.limits.maxArrayElements,"unquoted expansion")}for(;f.length>0&&f[f.length-1]==="";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await Ds(e,f),quoted:!1}}async function bu(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:c,hasIndirection:u}=Rr(r),d=n.hasBraceExpansion(r)?await n.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return $p(e,d,s);let h=await Cp(e,r,a,c,u,n);if(h!==null)return h;let p=await Rp(e,r,n);if(p!==null)return p;let m=await Op(e,r,n);if(m!==null)return m;let E=await Ip(e,r,n.expandPart);if(E!==null)return Eu(e,E);if((i||o||l)&&!Te(e.state.env)){let g=Pe(e.state.env),y=n.buildIfsCharClassPattern(g),b=await n.smartWordSplit(e,r,g,y,n.expandPart);return Eu(e,b)}let S=await n.expandWordAsync(e,t);return Tp(e,t,r,S,s,n.expandWordForGlobbing)}async function $p(e,t,n){let r=[];for(let s of t)if(!(!n&&s===""))if(!n&&!e.state.options.noglob&&Ft(s,e.state.shoptOptions.extglob)){let i=await Is(e,s);_e(r,i,e.limits.maxArrayElements,"brace/glob expansion")}else r.push(s);return{values:r,quoted:!1}}async function Cp(e,t,n,r,s,i){if(n){let o=Jc(e,t);if(o!==null)return o}{let o=eu(e,t);if(o!==null)return o}{let o=await Zc(e,t);if(o!==null)return o}{let o=await Qc(e,t,n,i.expandPart,i.expandWordPartsAsync);if(o!==null)return o}{let o=await Kc(e,t,n,i.expandPart);if(o!==null)return o}{let o=await Xc(e,t,i.evaluateArithmetic);if(o!==null)return o}{let o=Yc(e,t);if(o!==null)return o}{let o=await Gc(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}{let o=await Hc(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}if(r&&t.length===1&&t[0].type==="DoubleQuoted"){let o=Np(e,t);if(o!==null)return o}{let o=await tu(e,t,s,i.expandParameterAsync,i.expandWordPartsAsync);if(o!==null)return o}{let o=await nu(e,t);if(o!==null)return o}{let o=await ru(e,t);if(o!==null)return o}return null}function Np(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=er(e,r.prefix);return r.star?{values:[s.join(Y(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=K(e,r.array).map(([o])=>String(o));return r.star?{values:[i.join(Y(e.state.env))],quoted:!0}:{values:i,quoted:!0}}return null}async function Rp(e,t,n){{let r=await iu(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await ou(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await au(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await lu(e,t,n.expandPart);if(r!==null)return r}return null}async function Op(e,t,n){{let r=await cu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await uu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await fu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await du(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await hu(e,t);if(r!==null)return r}{let r=await pu(e,t);if(r!==null)return r}{let r=mu(e,t);if(r!==null)return r}{let r=yu(e,t);if(r!==null)return r}{let r=await gu(e,t,n.expandPart);if(r!==null)return r}return null}function wu(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 Dp(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=K(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=Y(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 Ip(e,t,n){if(t.length<2)return null;let r=!1;for(let l of t)if(wu(l)){r=!0;break}if(!r)return null;let s=Pe(e.state.env),i=Te(e.state.env),o=[];for(let l of t){let c=wu(l);if(c&&l.type==="DoubleQuoted"){let u=await Dp(e,l,c,n);o.push(u)}else if(l.type==="DoubleQuoted"||l.type==="SingleQuoted"){let u=await n(e,l);o.push([u])}else if(l.type==="Literal")o.push([l.value]);else if(l.type==="ParameterExpansion"){let u=await n(e,l);if(i)o.push(u?[u]:[]);else{let f=he(u,s,e.limits.maxArrayElements);o.push(f)}}else{let u=await n(e,l);if(i)o.push(u?[u]:[]);else{let f=he(u,s,e.limits.maxArrayElements);o.push(f)}}}let a=[];for(let l of o)if(l.length!==0)if(a.length===0)_e(a,l,e.limits.maxArrayElements,"word expansion");else{let c=a.length-1;a[c]=a[c]+l[0];for(let u=1;u<l.length;u++)a.push(l[u])}return a}async function Eu(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let n=[];for(let r of t)if(Ft(r,e.state.shoptOptions.extglob)){let s=await Is(e,r);_e(n,s,e.limits.maxArrayElements,"glob expansion")}else n.push(r);return{values:n,quoted:!1}}async function Is(e,t){let n=new dn(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 en(t);return n.hasNullglob()?[]:[t]}async function Tp(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(Ft(a,e.state.shoptOptions.extglob)){let c=await Is(e,a);if(c.length>0&&c[0]!==a)return{values:c,quoted:!1};if(c.length===0)return{values:[],quoted:!1}}let l=So(r);if(!Te(e.state.env)){let c=Pe(e.state.env);return{values:he(l,c,e.limits.maxArrayElements),quoted:!1}}return{values:[l],quoted:!1}}if(!s&&!e.state.options.noglob&&Ft(r,e.state.shoptOptions.extglob)){let a=await i(e,t);if(Ft(a,e.state.shoptOptions.extglob)){let l=await Is(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=So(r);if(!Te(e.state.env)){let l=Pe(e.state.env);return{values:he(a,l,e.limits.maxArrayElements),quoted:!1}}return{values:[a],quoted:!1}}return{values:[r],quoted:s}}function Ve(e,t,n){if(t.length>=e.limits.maxArrayElements)throw new C(`word splitting element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");t.push(n)}async function Au(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 Lt(e,t.parameter),o=await le(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 _p(e){return e.type==="SingleQuoted"?!0:e.type==="DoubleQuoted"?e.parts.every(n=>n.type==="Literal"):!1}async function Lp(e,t){if(t.type!=="ParameterExpansion")return null;let n=await Au(e,t);if(!n||n.length<=1)return null;let r=n.some(i=>_p(i)),s=n.some(i=>i.type==="Literal"||i.type==="ParameterExpansion"||i.type==="CommandSubstitution"||i.type==="ArithmeticExpansion");return r&&s?n:null}function Fp(e){return e.type==="DoubleQuoted"||e.type==="SingleQuoted"||e.type==="Literal"?!1:e.type==="Glob"?ho(e.pattern):!(!(e.type==="ParameterExpansion"||e.type==="CommandSubstitution"||e.type==="ArithmeticExpansion")||e.type==="ParameterExpansion"&&Ec(e))}async function vu(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:word_split"),t.length===1&&t[0].type==="ParameterExpansion"){let d=t[0],h=await Au(e,d);if(h&&h.length>0&&h.length>1&&h.some(m=>m.type==="DoubleQuoted"||m.type==="SingleQuoted")&&h.some(m=>m.type==="Literal"||m.type==="ParameterExpansion"||m.type==="CommandSubstitution"||m.type==="ArithmeticExpansion"))return Su(e,h,n,r,s)}let i=[],o=!1;for(let d of t){let h=Fp(d),p=d.type==="DoubleQuoted"||d.type==="SingleQuoted",m=h?await Lp(e,d):null,E=await s(e,d);i.push({value:E,isSplittable:h,isQuoted:p,mixedDefaultParts:m??void 0}),h&&(o=!0)}if(!o){let d=i.map(h=>h.value).join("");return d?[d]:[]}let a=[],l="",c=!1,u=!1,f=!1;for(let d of i)if(!d.isSplittable)u?d.isQuoted&&d.value===""?(l!==""&&Ve(e,a,l),Ve(e,a,""),c=!0,l="",u=!1,f=!0):d.value!==""?(l!==""&&Ve(e,a,l),l=d.value,u=!1,f=!1):(l+=d.value,f=!1):(l+=d.value,f=d.isQuoted&&d.value==="");else if(d.mixedDefaultParts){let h=await Su(e,d.mixedDefaultParts,n,r,s);if(h.length!==0)if(h.length===1)l+=h[0],c=!0;else{l+=h[0],Ve(e,a,l),c=!0;for(let p=1;p<h.length-1;p++)Ve(e,a,h[p]);l=h[h.length-1]}u=!1,f=!1}else{let{words:h,hadLeadingDelimiter:p,hadTrailingDelimiter:m}=vs(d.value,n,e.limits.maxArrayElements);if(f&&p&&l===""&&(Ve(e,a,""),c=!0),h.length===0)m&&(u=!0);else if(h.length===1)l+=h[0],c=!0,u=m;else{l+=h[0],Ve(e,a,l),c=!0;for(let E=1;E<h.length-1;E++)Ve(e,a,h[E]);l=h[h.length-1],u=m}f=!1}return l!==""?Ve(e,a,l):a.length===0&&c&&Ve(e,a,""),a}function Mp(e,t){return e.length>0&&t.includes(e[0])}async function Su(e,t,n,r,s){let i=[];for(let u of t){let d=!(u.type==="DoubleQuoted"||u.type==="SingleQuoted"),h=await s(e,u);i.push({value:h,isSplittable:d})}let o=[],a="",l=!1,c=!1;for(let u of i)if(!u.isSplittable)c&&u.value!==""?(a!==""&&Ve(e,o,a),a=u.value,c=!1):a+=u.value;else{Mp(u.value,n)&&a!==""&&(Ve(e,o,a),a="",l=!0);let{words:d,hadTrailingDelimiter:h}=vs(u.value,n,e.limits.maxArrayElements);if(d.length===0)h&&(c=!0);else if(d.length===1)a+=d[0],l=!0,c=h;else{a+=d[0],Ve(e,o,a),l=!0;for(let p=1;p<d.length-1;p++)Ve(e,o,d[p]);a=d[d.length-1],c=h}}return a!==""?Ve(e,o,a):o.length===0&&l&&Ve(e,o,""),o}function ku(e){switch(e.type){case"Literal":return e.value;case"SingleQuoted":return e.value;case"Escaped":return e.value;default:return null}}function xu(e){switch(e.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return e.value==="";default:return!1}}var Pt=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new ze,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}))}diff(t){let n=t?.space??"vfs",r=[],s=[],i=[];for(let o of this.mounts.values()){let a=o.filesystem;if(typeof a.diff!="function")throw new x("EINVAL",`mounted filesystem at '${o.mountPoint}' does not support diff()`);let l=a.diff(),c=u=>{if(n==="vfs")return o.mountPoint==="/"?u:`${o.mountPoint}${u}`;if(typeof a.rootDir!="string")throw new x("EINVAL",`cannot produce a host-space diff: mount at '${o.mountPoint}' has no real root`);return`${a.rootDir}${u}`};for(let u of l.writes)r.push({...u,path:c(u.path)});for(let u=0;u<l.deletions.length;u++)s.push(c(l.deletions[u])),i.push(l.deletionChangedAt?.[u]??0)}return{writes:r,deletions:s,...i.length>0&&{deletionChangedAt:i}}}restamp(t,n,r="full"){let{fs:s,relativePath:i}=this.routePath(t),o=s.restamp;typeof o=="function"&&o.call(s,i,n,r)}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){U(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 Gn(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:St,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:St,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:St,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:St,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 x("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 c of l)r.add(c)}catch(l){if(!ft(l,"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 x("EBUSY",`mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new x("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&&qt(t,n))throw new x("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&&qt(t,n))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);if(this.mounts.has(r))throw new x("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 sn(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 x("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=Gt(t,o),l=Gt(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 Ts="/dev/fd",$u=63,Bp=10,Pu=$u-Bp+1,Po=class extends ze{isLiveDescriptor;constructor(t){super(),this.isLiveDescriptor=t}assertLiveDescriptor(t,n){this.isLiveDescriptor(t)||this.refuse(t,n)}refuse(t,n){throw new x("EROFS",`read-only file system, ${n} '${Ts}${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 Wp(e){let t=new Po(n=>Cu(e).some(r=>r.path===`${Ts}${n}`));e.fs=new Pt({base:e.fs,mounts:[{mountPoint:Ts,filesystem:t}]}),e.state.processSubstitutionFsMounted=!0}async function Vp(e,t,n){try{await e.fs.writeFile(t,n,"binary");return}catch(r){if(e.state.processSubstitutionFsMounted)throw r;Wp(e)}await e.fs.writeFile(t,n,"binary")}async function zp(e,t){try{await e.fs.rm(t,{force:!0})}catch{}}function Cu(e){let t=e.state.processSubstitutions;if(t)return t;let n=[];return e.state.processSubstitutions=n,n}async function Nu(e,t,n){let r=e.substitutionDepth??0,s=e.limits.maxSubstitutionDepth;if(r>=s)throw new C(`Process substitution nesting limit exceeded (${s})`,"substitution_depth");let i=e.substitutionDepth,o=new Map(e.state.env),a=ht(e.state.arrays),l=e.state.cwd,c=e.state.bashPid,u=e.state.suppressVerbose,f=e.state.groupStdin,d=e.state.lastExitCode,h=e.state.env.get("?"),p=e.state.lastSubstitutionExitCode;e.substitutionDepth=r+1,e.state.bashPid=e.state.nextVirtualPid++,e.state.suppressVerbose=!0,n!==void 0&&(e.state.groupStdin=n);let m;try{m=await e.executeScript(t)}catch(E){if(E instanceof C)throw E;if(E instanceof G)return{stdout:E.stdout,stderr:E.stderr,exitCode:E.exitCode};throw E}finally{e.substitutionDepth=i,e.state.env=o,e.state.arrays=a,e.state.cwd=l,e.state.bashPid=c,e.state.suppressVerbose=u,e.state.groupStdin=f,e.state.lastExitCode=d,e.state.lastSubstitutionExitCode=p,h!==void 0?e.state.env.set("?",h):e.state.env.delete("?")}return m}async function Ru(e,t){let n=Cu(e);if(n.length>=Pu)throw new C(`Process substitution limit exceeded (${Pu} concurrent)`,"file_descriptors");let r="";if(t.direction==="input"){let o=await Nu(e,t.body,void 0);if(o.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+o.stderr),r=Ut(o),r.length>e.limits.maxStringLength)throw new C(`process substitution: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")}let s=$u-n.length,i=`${Ts}/${s}`;n.push({fd:s,path:i,direction:t.direction,body:t.body});try{await Vp(e,i,r)}catch(o){throw n.pop(),o}return i}function Ou(e){return e.state.processSubstitutions?.length??0}var Up={stdout:"",stderr:""};async function $o(e,t){let n=e.state.processSubstitutions;if(!n||n.length<=t)return Up;let r="",s="";for(;n.length>t;){let i=n[n.length-1],o="";if(i.direction==="output")try{o=await Gn(e.fs,i.path)}catch{}if(await zp(e,i.path),n.pop(),i.direction==="output"){let a=await Nu(e,i.body,o);r+=Ut(a),s+=a.stderr}}return{stdout:r,stderr:s}}function gn(e,t,n){if(e.length>t)throw new C(`${n}: string length limit exceeded (${t} bytes)`,"string_length")}async function $t(e,t,n=!1){let r=[];for(let s of t)r.push(await at(e,s,n));return r.join("")}function jp(e){return xu(e)}function Iu(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!jp(t))return!1;return!0}function qp(e,t,n=!1){let r=ku(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 Ao(e,t.pattern);default:return null}}async function ae(e,t){return No(e,t)}async function Tu(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped")n.push(Jn(r.value));else if(r.type==="SingleQuoted")n.push(r.value);else if(r.type==="DoubleQuoted"){let s=await $t(e,r.parts);n.push(s)}else if(r.type==="TildeExpansion"){let s=await at(e,r);n.push(Jn(s))}else n.push(await at(e,r));return n.join("")}async function _u(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(ot(r.value));else if(r.type==="DoubleQuoted"){let s=await $t(e,r.parts);n.push(ot(s))}else n.push(await at(e,r));return n.join("")}async function Lu(e,t){let n=[];for(let r of t.parts)if(r.type==="SingleQuoted")n.push(ot(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 $t(e,r.parts);n.push(ot(s))}else r.type==="Glob"?Uc(r.pattern)?n.push(await qc(e,r.pattern)):n.push(Ao(e,r.pattern)):r.type==="Literal"?n.push(r.value):n.push(await at(e,r));return n.join("")}function Ls(e){for(let t of e)if(t.type==="BraceExpansion"||t.type==="DoubleQuoted"&&Ls(t.parts))return!0;return!1}var Du=1e5;async function Fu(e,t,n={count:0}){let r=()=>{n.count++,e.executionScope.consumeLimited("brace_operations",1,Math.min(Du,e.limits.maxBraceExpansionResults),"brace expansion")},s=(o,a)=>{if(o.length>=e.limits.maxBraceExpansionResults)throw new C(`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,c="";for(let d of o.items)if(d.type==="Range"){let h=bo(d.start,d.end,d.step,d.startStr,d.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(h.expanded)for(let p of h.expanded)s(a,p);else{l=!0,c=h.literal;break}}else{let h=await Fu(e,d.word.parts,n);for(let p of h){let m=[];for(let E of p)typeof E=="string"?m.push(E):m.push(await at(e,E));s(a,m.join(""))}}if(l){for(let d of i)r(),d.push(c);continue}if(i.length*a.length>e.limits.maxBraceExpansionResults||n.count>Du)throw new C(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");let f=[];for(let d of i)for(let h of a){if(f.length>=e.limits.maxBraceExpansionResults)throw new C(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),f.push([...d,h])}i=f}else for(let a of i)r(),a.push(o);return i}async function Mu(e,t){let n=t.parts;if(!Ls(n))return[await ae(e,t)];let r=await Fu(e,n),s=[];for(let i of r){let o=[];for(let a of i)typeof a=="string"?o.push(a):o.push(await at(e,a));s.push(vo(e,o.join("")))}return s}function Gp(){return{expandWordAsync:No,expandWordForGlobbing:Lu,expandWordWithBracesAsync:Mu,expandWordPartsAsync:$t,expandPart:at,expandParameterAsync:_s,hasBraceExpansion:Ls,evaluateArithmetic:ee,buildIfsCharClassPattern:bc,smartWordSplit:vu}}async function Ct(e,t){return bu(e,t,Gp())}function Hp(e){for(let t of e){if(t.type==="ParameterExpansion")return t.parameter;if(t.type==="Literal")return t.value}return""}function Co(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 Bu(e,t){if(Co(e,t))return{error:`bash: $@: ambiguous redirect
107
- `};let n=t.parts,{hasQuoted:r}=Rr(n);if(Ls(n)&&(await Mu(e,t)).length>1)return{error:`bash: ${n.map(h=>h.type==="Literal"?h.value:h.type==="BraceExpansion"?`{${h.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
108
- `};let s=await No(e,t),{hasParamExpansion:i,hasCommandSub:o}=Rr(n);if((i||o)&&!r&&!Te(e.state.env)){let f=Pe(e.state.env);if(he(s,f,e.limits.maxArrayElements).length>1)return{error:`bash: $${Hp(n)}: ambiguous redirect
109
- `}}if(r||e.state.options.noglob||n.some(f=>f.type==="ProcessSubstitution"))return{target:s};let l=await Lu(e,t);if(!Ft(l,e.state.shoptOptions.extglob))return{target:s};let c=new dn(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")}),u=await c.expand(l);return u.length===0?c.hasFailglob()?{error:`bash: no match: ${s}
96
+ ${e.terminator}`}function ip(e){return`(${yt(e.body)})${xt(e.redirections)}`}function op(e){return`{ ${yt(e.body)}; }${xt(e.redirections)}`}function ap(e){return`((${pe(e.expression.expression)}))${xt(e.redirections)}`}function lp(e){return`[[ ${Mn(e.expression)} ]]${xt(e.redirections)}`}function cp(e){let t=fc(e.body);return`${e.name}() ${t}${xt(e.redirections)}`}function pe(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`${pe(e.left)} ${e.operator} ${pe(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${pe(e.operand)}`:`${pe(e.operand)}${e.operator}`;case"ArithTernary":return`${pe(e.condition)} ? ${pe(e.consequent)} : ${pe(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${pe(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${pe(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${pe(e.target)}[${pe(e.subscript)}]`:pe(e.target)} ${e.operator} ${pe(e.value)}`;case"ArithDynamicElement":return`${pe(e.nameExpr)}[${pe(e.subscript)}]`;case"ArithGroup":return`(${pe(e.expression)})`;case"ArithNested":return`$((${pe(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}[${pe(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(pe).join("");case"ArithDoubleSubscript":return`${e.array}[${pe(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 Mn(e){switch(e.type){case"CondBinary":return`${we(e.left)} ${e.operator} ${we(e.right)}`;case"CondUnary":return`${e.operator} ${we(e.operand)}`;case"CondNot":return`! ${Mn(e.operand)}`;case"CondAnd":return`${Mn(e.left)} && ${Mn(e.right)}`;case"CondOr":return`${Mn(e.left)} || ${Mn(e.right)}`;case"CondGroup":return`( ${Mn(e.expression)} )`;case"CondWord":return we(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var up="BASH_ALIAS_";function vs(e,t,n,r){let s=B(t);if(s>n-r.value)throw new C(`alias expansion exceeds string length limit (${n} bytes)`,"string_length");return r.value+=s,e+t}function mc(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function yc(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function gc(e,t){return e.env.get(`${up}${t}`)}function Ec(e,t,n){return bc(e,t,n)}function bc(e,t,n,r=!0){if(!t.name||!mc(t.name))return t;let s=yc(t.name);if(!s)return t;let i=gc(e,s);if(!i||n.has(s))return t;try{n.add(s);let o=new Q,a={value:0},l=vs("",i,e.limits.maxStringLength,a),c=i.endsWith(" ");if(!c)for(let h of t.args){let p=we(h);l=vs(l,` ${p}`,e.limits.maxStringLength,a)}let u;try{u=o.parse(l)}catch(h){if(h instanceof Ce)throw h;return t}if(u.statements.length!==1||u.statements[0].pipelines.length!==1||u.statements[0].pipelines[0].commands.length!==1)return wc(e,t,i);let f=u.statements[0].pipelines[0].commands[0];if(f.type!=="SimpleCommand")return wc(e,t,i);let d={...f,assignments:[...t.assignments,...f.assignments],redirections:[...f.redirections,...t.redirections],line:t.line};if(c&&t.args.length>0){d={...d,args:[...d.args,...t.args]};let h=1;for(;r&&d.args.length>0;){let p=d.args[0];if(!mc(p))break;let m=yc(p),E=m?gc(e,m):null;if(!E)break;if(h>=e.limits.maxCallDepth)throw new C(`alias expansion depth limit exceeded (${e.limits.maxCallDepth})`,"recursion");h++;let b={type:"SimpleCommand",name:p,args:d.args.slice(1),assignments:[],redirections:[]},y=bc(e,b,n,!1);if(y===b||(d={...d,name:y.name,args:[...y.args]},!E.endsWith(" ")))break}}return d}catch(o){throw n.delete(s),o}}function wc(e,t,n){let r={value:0},s=vs("",n,e.limits.maxStringLength,r);for(let c of t.args){let u=we(c);s=vs(s,` ${u}`,e.limits.maxStringLength,r)}let i=new Q,o=i.parseWordFromString("eval",!1,!1),a=0;for(let c of s)c==="'"&&a++;if(r.value+2+a*3>e.limits.maxStringLength)throw new C(`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 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 uo(e){return fp.get(e)??""}function Sc(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 Ac(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 c=e.slice(s+2,l),u=uo(c);i+=u,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,c=s+1===o;l||c?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+="$",ge(t)}function fo(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 ho(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 vc=5,hn=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=Sc(i))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new C(`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 Ac(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>vc))throw new C(`Glob pattern has too many ** segments (max ${vc})`,"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(c=>c!==""),s=-1;for(let c=0;c<r.length;c++)if(this.hasGlobChars(r[c])){s=c;break}if(s===-1)return[t];let i,o;if(s===0)n?(i="/",o="/"):(i=this.cwd,o="");else{let c=r.slice(0,s);n?(i=`/${c.join("/")}`,o=`/${c.join("/")}`):(i=this.fs.resolvePath(this.cwd,c.join("/")),o=c.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=[],c=[...a],u=this.dotglob||this.hasGlobignore;if(s.startsWith(".")||this.dotglob){let d=a.some(p=>p.name==="."),h=a.some(p=>p.name==="..");d||c.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),h||c.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let d of c)if(!(d.name.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d.name,s)){let h=t==="/"?`/${d.name}`:`${t}/${d.name}`,p;n===""?p=d.name:n==="/"?p=`/${d.name}`:p=`${n}/${d.name}`,i.length===0?l.push(Promise.resolve([p])):d.isDirectory&&l.push(this.expandSegments(h,p,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=[],c=[...a],u=this.dotglob||this.hasGlobignore;(s.startsWith(".")||this.dotglob)&&(a.includes(".")||c.push("."),a.includes("..")||c.push(".."));for(let d of c)if(!(d.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d,s)){let h=t==="/"?`/${d}`:`${t}/${d}`,p;n===""?p=d:n==="/"?p=`/${d}`:p=`${n}/${d}`,i.length===0?l.push(Promise.resolve([p])):l.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(h)).isDirectory)return this.expandSegments(h,p,i)}catch(m){if(m instanceof C)throw m}return[]})())}let f=await Promise.all(l);for(let d of f)o.push(...d)}}catch(a){if(a instanceof C)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 c of i){let u=t==="."?c.name:`${t}/${c.name}`;c.isDirectory&&o.push(u)}let a=t==="."?n:`${t}/${n}`,l=await this.expandRecursive(a);r.push(...l);for(let c=0;c<o.length;c+=100){let u=o.slice(c,c+100);await Promise.all(u.map(f=>this.walkDirectoryMultiGlobstar(f,n,r)))}}else{this.checkOpsLimit();let o=await this.fs.readdir(s),a=[];for(let u of o){let f=t==="."?u:`${t}/${u}`,d=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory&&a.push(f)}catch(h){if(h instanceof C)throw h}}let l=t==="."?n:`${t}/${n}`,c=await this.expandRecursive(l);r.push(...c);for(let u=0;u<a.length;u+=100){let f=a.slice(u,u+100);await Promise.all(f.map(d=>this.walkDirectoryMultiGlobstar(d,n,r)))}}}catch(i){if(i instanceof C)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 c=t==="."?l.name:`${t}/${l.name}`;l.isDirectory?a.push(c):n&&this.matchPattern(l.name,n)&&o.push(c)}r.push(...o);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u,n,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(s),o=[];for(let l=0;l<i.length;l+=100){let c=i.slice(l,l+100),u=await Promise.all(c.map(async f=>{let d=t==="."?f:`${t}/${f}`,h=this.fs.resolvePath(this.cwd,d);try{this.checkOpsLimit();let p=await this.fs.stat(h);return{name:f,path:d,isDirectory:p.isDirectory}}catch(p){if(p instanceof C)throw p;return null}}));o.push(...u.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 c=a.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u.path,n,r)))}}}catch(i){if(i instanceof C)throw i}}matchPattern(t,n){return this.patternToRegex(n).test(t)}patternToRegex(t){let n=this.patternToRegexStr(t);return ge(`^${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=fo(t,s+1);if(o!==-1){let a=t.slice(s+2,o),l=ho(a),c=l.map(f=>this.patternToRegexStr(f)),u=c.length>0?c.join("|"):"(?:)";if(i==="@")n+=`(?:${u})`;else if(i==="*")n+=`(?:${u})*`;else if(i==="+")n+=`(?:${u})+`;else if(i==="?")n+=`(?:${u})?`;else if(i==="!")if(o<t.length-1){let d=l.map(p=>this.computePatternLength(p));if(d.every(p=>p!==null)&&d.every(p=>p===d[0])&&d[0]!==null){let p=d[0];if(p===0)n+="(?:.+)";else{let m=[];p>0&&m.push(`.{0,${p-1}}`),m.push(`.{${p+1},}`),m.push(`(?!(?:${u})).{${p}}`),n+=`(?:${m.join("|")})`}}else n+=`(?:(?!(?:${u})).)*?`}else n+=`(?!(?:${u})$).*`;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 u=t.indexOf(":]",l+2);if(u!==-1){l=u+2;continue}}if(t[l]==="]")break;l++}let c=o;for(;o<t.length&&t[o]!=="]";){if(t[o]==="["&&o+1<t.length&&t[o+1]===":"){let u=t.indexOf(":]",o+2);if(u!==-1){let f=t.slice(o+2,u),d=uo(f);a+=d,o=u+2;continue}}if(t[o]==="\\"&&o+1<t.length){a+=`\\${t[o+1]}`,o+=2;continue}if(t[o]==="-"){let u=o===c,f=o+1===l;u||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=fo(t,r+1);if(o!==-1){if(i==="@"){let a=t.slice(r+2,o),c=ho(a).map(u=>this.computePatternLength(u));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){n+=c[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 po(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 dp(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 kc(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 Ir(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 c of l.parts)c.type==="ParameterExpansion"&&(c.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&(!c.operation||c.operation.type==="PatternRemoval"||c.operation.type==="PatternReplacement")&&(s=!0),(c.operation?.type==="VarNamePrefix"||c.operation?.type==="ArrayKeys")&&(o=!0),c.operation?.type==="Indirection"&&(a=!0));l.type==="CommandSubstitution"&&(n=!0),l.type==="ParameterExpansion"&&(i=!0,(l.parameter==="@"||l.parameter==="*")&&(r=!0),dp(l)&&(t=!0),(l.operation?.type==="VarNamePrefix"||l.operation?.type==="ArrayKeys")&&(o=!0),l.operation?.type==="Indirection"&&(a=!0)),l.type==="Glob"&&po(l.pattern)&&(i=!0)}return{hasQuoted:t,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:i,hasVarNamePrefixExpansion:o,hasIndirection:a}}var hp=`
97
+ `;function Wn(e,t){if(e>=t)throw new C(`array element limit exceeded (${t})`,"array_elements")}function mo(e,t,n,r,s){Wn(e.length,s),Wn(t.length,s),e.push(n),t.push(r)}function Pe(e){return e.get("IFS")??hp}function _e(e){return e.get("IFS")===""}function ks(e){let t=Pe(e);if(t==="")return!0;for(let n of t)if(n!==" "&&n!==" "&&n!==`
98
+ `)return!1;return!0}function xc(e){let t=!1,n=[];for(let r of e.split(""))r==="-"?t=!0:/[\\^$.*+?()[\]{}|]/.test(r)?n.push(`\\${r}`):r===" "?n.push("\\t"):r===`
99
+ `?n.push("\\n"):n.push(r);return t&&n.push("\\-"),n.join("")}function Y(e){let t=e.get("IFS");if(t===void 0)return" ";let n=t.codePointAt(0);return n===void 0?"":String.fromCodePoint(n)}var pp=`
100
+ `;function mp(e){return pp.includes(e)}function yo(e){let t=new Set,n=new Set;for(let r of e)mp(r)?t.add(r):n.add(r);return{whitespace:t,nonWhitespace:n}}function go(e,t,n,r,s){if(t==="")return e===""?{words:[],wordStarts:[]}:(Wn(0,n),{words:[e],wordStarts:[0]});let{whitespace:i,nonWhitespace:o}=yo(t),a=[],l=[],c=0;for(;c<e.length&&i.has(e[c]);)c++;if(c>=e.length)return{words:[],wordStarts:[]};if(o.has(e[c]))for(mo(a,l,"",c,n),c++;c<e.length&&i.has(e[c]);)c++;for(;c<e.length&&!(r!==void 0&&a.length>=r);){let u=c;for(;c<e.length;){let f=e[c];if(!s&&f==="\\"){c++,c<e.length&&c++;continue}if(i.has(f)||o.has(f))break;c++}if(mo(a,l,e.substring(u,c),u,n),c>=e.length)break;for(;c<e.length&&i.has(e[c]);)c++;if(c<e.length&&o.has(e[c])){for(c++;c<e.length&&i.has(e[c]);)c++;for(;c<e.length&&o.has(e[c])&&!(r!==void 0&&a.length>=r);)for(mo(a,l,"",c,n),c++;c<e.length&&i.has(e[c]);)c++}}return{words:a,wordStarts:l}}function xs(e,t,n){if(t==="")return e&&Wn(0,n),{words:e?[e]:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};if(e==="")return{words:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};let{whitespace:r,nonWhitespace:s}=yo(t),i=[],o=0,a=!1,l=!1,c=o;for(;o<e.length&&r.has(e[o]);)o++;if(o>c&&(a=!0),o>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(s.has(e[o]))for(Wn(i.length,n),i.push(""),o++;o<e.length&&r.has(e[o]);)o++;for(;o<e.length;){let u=o;for(;o<e.length;){let d=e[o];if(r.has(d)||s.has(d))break;o++}if(Wn(i.length,n),i.push(e.substring(u,o)),o>=e.length){l=!1;break}let f=o;for(;o<e.length&&r.has(e[o]);)o++;if(o<e.length&&s.has(e[o])){for(o++;o<e.length&&r.has(e[o]);)o++;for(;o<e.length&&s.has(e[o]);)for(Wn(i.length,n),i.push(""),o++;o<e.length&&r.has(e[o]);)o++}o>=e.length&&o>f&&(l=!0)}return{words:i,hadLeadingDelimiter:a,hadTrailingDelimiter:l}}function he(e,t,n){return xs(e,t,n).words}function yp(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Pc(e,t,n){if(t==="")return e;let{whitespace:r,nonWhitespace:s}=yo(t),i=e.length;for(;i>0&&r.has(e[i-1]);){if(!n&&i>=2){let a=0,l=i-2;for(;l>=0&&e[l]==="\\";)a++,l--;if(a%2===1)break}i--}let o=e.substring(0,i);if(o.length>=1&&s.has(o[o.length-1])){if(!n&&o.length>=2){let l=0,c=o.length-2;for(;c>=0&&o[c]==="\\";)l++,c--;if(l%2===1)return o}let a=o.substring(0,o.length-1);if(!yp(a,s))return a}return o}function fe(e,t){return e.state.namerefs?.has(t)??!1}function Kt(e,t){e.state.namerefs??=new Set,e.state.namerefs.add(t)}function $c(e,t){e.state.namerefs?.delete(t),e.state.boundNamerefs?.delete(t),e.state.invalidNamerefs?.delete(t)}function Cc(e,t){e.state.invalidNamerefs??=new Set,e.state.invalidNamerefs.add(t)}function Nc(e,t){return e.state.invalidNamerefs?.has(t)??!1}function wo(e,t){e.state.boundNamerefs??=new Set,e.state.boundNamerefs.add(t)}function Ps(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let s=n[1],i=Ie(e,s),o=e.state.associativeArrays?.has(s)??!1;return i||o}return Ie(e,t)?!0:e.state.env.has(t)}function Ge(e,t,n=100){if(!fe(e,t)||Nc(e,t))return t;let r=new Set,s=t;for(;n-- >0;){if(r.has(s))return;if(r.add(s),!fe(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 Vn(e,t){if(fe(e,t))return e.state.env.get(t)}function $s(e,t,n,r=100){if(!fe(e,t)||Nc(e,t))return t;let s=new Set,i=t;for(;r-- >0;){if(s.has(i))return;if(s.add(i),!fe(e,i))return i;let o=e.state.env.get(i);if(o===void 0||o==="")return n!==void 0?/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&Ps(e,n)?i:null:i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(o))return i;i=o}}function Rc(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 K(e,t){return t==="FUNCNAME"?(e.state.funcNameStack??[]).map((i,o)=>[o,i]):t==="BASH_LINENO"?(e.state.callLineStack??[]).map((i,o)=>[o,String(i)]):t==="BASH_SOURCE"?(e.state.sourceStack??[]).map((i,o)=>[o,i]):e.state.associativeArrays?.has(t)?Lt(e,t).map(i=>[i,le(e,t,i)??""]):xe(e,t).map(s=>[s,le(e,t,s)??""])}function Pt(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)?Ie(e,t):Ie(e,t)}async function oe(e,t,n=!0){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 i="";return i+="h",e.state.options.errexit&&(i+="e"),e.state.options.noglob&&(i+="f"),e.state.options.nounset&&(i+="u"),e.state.options.verbose&&(i+="v"),e.state.options.xtrace&&(i+="x"),i+="B",e.state.options.noclobber&&(i+="C"),i+="s",i}case"*":{let i=Number.parseInt(e.state.env.get("#")||"0",10);if(i===0)return"";let o=[];for(let a=1;a<=i;a++)o.push(e.state.env.get(String(a))||"");return o.join(Y(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 Sl;case"!":return String(e.state.lastBackgroundPid);case"BASHPID":return String(e.state.bashPid);case"LINENO":return String(e.state.currentLine);case"FUNCNAME":{let i=e.state.funcNameStack?.[0];if(i!==void 0)return i;if(n&&e.state.options.nounset)throw new Xe("FUNCNAME");return""}case"BASH_LINENO":{let i=e.state.callLineStack?.[0];if(i!==void 0)return String(i);if(n&&e.state.options.nounset)throw new Xe("BASH_LINENO");return""}case"BASH_SOURCE":{let i=e.state.sourceStack?.[0];if(i!==void 0)return i;if(n&&e.state.options.nounset)throw new Xe("BASH_SOURCE");return""}}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(t))throw new st(`\${${t}}`);let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let i=r[1],o=r[2];if(fe(e,i)){let u=Ge(e,i);if(u&&u!==i){if(u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return"";i=u}}if(o==="@"||o==="*"){let u=K(e,i);if(u.length>0){let d=o==="*"?Y(e.state.env):" ",h=B(d)*(u.length-1);for(let[,p]of u)if(h+=B(p),h>e.limits.maxStringLength)throw new C(`array expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return u.map(([,p])=>p).join(d)}let f=e.state.env.get(i);return f!==void 0?f:""}if(i==="FUNCNAME"){let u=Number.parseInt(o,10);return!Number.isNaN(u)&&u>=0?e.state.funcNameStack?.[u]??"":""}if(i==="BASH_LINENO"){let u=Number.parseInt(o,10);if(!Number.isNaN(u)&&u>=0){let f=e.state.callLineStack?.[u];return f!==void 0?String(f):""}return""}if(i==="BASH_SOURCE"){let u=Number.parseInt(o,10);return!Number.isNaN(u)&&u>=0?e.state.sourceStack?.[u]??"":""}if(e.state.associativeArrays?.has(i)){let u=ps(o);u=Rc(e,u);let f=le(e,i,u);if(f===void 0&&n&&e.state.options.nounset)throw new Xe(`${i}[${o}]`);return f||""}let l;if(/^-?\d+$/.test(o))l=Number.parseInt(o,10);else try{let u=new Q,f=se(u,o);l=await ee(e,f.expression)}catch{let u=e.state.env.get(o);l=u?Number.parseInt(u,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let u=K(e,i),f=e.state.currentLine;if(u.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${i}: bad array subscript
101
+ `,"";let h=Math.max(...u.map(([m])=>typeof m=="number"?m:0))+1+l;return h<0?(e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${i}: bad array subscript
102
+ `,""):le(e,i,h)||""}let c=le(e,i,l);if(c!==void 0)return c;if(l===0){let u=e.state.env.get(i);if(u!==void 0)return u}if(n&&e.state.options.nounset)throw new Xe(`${i}[${l}]`);return""}if(/^[1-9][0-9]*$/.test(t)){let i=e.state.env.get(t);if(i===void 0&&n&&e.state.options.nounset)throw new Xe(t);return i||""}if(fe(e,t)){let i=Ge(e,t);if(i===void 0)return"";if(i!==t)return await oe(e,i,n);let o=e.state.env.get(t);if((o===void 0||o==="")&&n&&e.state.options.nounset)throw new Xe(t);return o||""}let s=e.state.env.get(t);if(s!==void 0)return e.state.tempEnvBindings?.some(i=>i.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),s;if(Pt(e,t)){let i=le(e,t,0);if(i!==void 0)return i;if(n&&e.state.options.nounset)throw new Xe(t);return""}if(n&&e.state.options.nounset)throw new Xe(t);return""}async function Mt(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(fe(e,s)){let l=Ge(e,s);if(l&&l!==s){if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;s=l}}if(i==="@"||i==="*")return K(e,s).length>0?!0:e.state.env.has(s);if(e.state.associativeArrays?.has(s)){let l=Rc(e,ps(i));return un(e,s,l)}let a;if(/^-?\d+$/.test(i))a=Number.parseInt(i,10);else try{let l=new Q,c=se(l,i);a=await ee(e,c.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=K(e,s);if(l.length===0)return!1;let u=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+a;return u<0?!1:un(e,s,u)}return un(e,s,a)}if(fe(e,t)){let s=Ge(e,t);return s===void 0||s===t?e.state.env.has(t):Mt(e,s)}return e.state.env.has(t)?!0:Pt(e,t)?un(e,t,0):!1}async function Oc(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 oe(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 oe(e,i);n+=o,r=s;continue}if(/[*@#?\-!$]/.test(t[r+1]||"")){let s=t[r+1],i=await oe(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 oe(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 Eo(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 c=n.slice(o+2,l-1);if(e.execFn){let u=await e.execFn(c,{signal:e.state.signal});i+=u.stdout.replace(/\n+$/,""),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.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 c=n.slice(o+2,l-1),u=await oe(e,c);i+=u,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),c=await oe(e,l);i+=c,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 c=await e.execFn(l,{signal:e.state.signal});i+=c.stdout.replace(/\n+$/,""),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr)}o=a+1}else i+=n[o],o++;return i}var Tr=1e4,bo={maxResults:Tr,maxStringBytes:10*1024*1024};function Cs(e,t,n,r){if(e.length>=n.maxResults)return!1;let s=B(t);if(s>n.maxStringBytes-r.value)throw new C(`brace expansion string limit exceeded (${n.maxStringBytes} bytes)`,"string_length");return e.push(t),r.value+=s,!0}function gp(e,t,n,r,s,i=bo){let o=n??1;o===0&&(o=1);let a=Math.abs(o),l=[],c=0;if(r?.match(/^-?0\d/)&&(c=Math.max(c,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length)),c>i.maxStringBytes)throw new C(`brace expansion padding limit exceeded (${i.maxStringBytes} bytes)`,"string_length");let u={value:0},f=d=>{if(c>0){let h=d<0,p=String(Math.abs(d)).padStart(c,"0");return h?`-${p}`:p}return String(d)};if(e<=t)for(let d=e,h=0;d<=t&&h<Tr&&Cs(l,f(d),i,u);d+=a,h++);else for(let d=e,h=0;d>=t&&h<Tr&&Cs(l,f(d),i,u);d-=a,h++);return l}function wp(e,t,n,r=bo){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",c=e>="a"&&e<="z",u=t>="A"&&t<="Z",f=t>="a"&&t<="z";if(l&&f||c&&u){let p=n!==void 0?`..${n}`:"";throw new Yr(`{${e}..${t}${p}}: invalid sequence`)}let d=[],h={value:0};if(i<=o)for(let p=i,m=0;p<=o&&m<Tr&&Cs(d,String.fromCharCode(p),r,h);p+=a,m++);else for(let p=i,m=0;p>=o&&m<Tr&&Cs(d,String.fromCharCode(p),r,h);p-=a,m++);return d}function So(e,t,n,r,s,i=bo){let o=n!==void 0?`..${n}`:"";return typeof e=="number"&&typeof t=="number"?{expanded:gp(e,t,n,r,s,i),literal:`{${e}..${t}${o}}`}:typeof e=="string"&&typeof t=="string"?{expanded:wp(e,t,n,i),literal:`{${e}..${t}${o}}`}:{expanded:null,literal:`{${e}..${t}${o}}`}}function Dc(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 Bt(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\(/.test(e))}function Ao(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 lt(e){return e.replace(/([*?[\]\\()|])/g,"\\$1")}function er(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ae(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=Ep(e,s+1);if(o!==-1){let a=e.slice(s+2,o),c=bp(a).map(f=>ae(f,t,n)),u=c.length>0?c.join("|"):"(?:)";i==="@"?r+=`(?:${u})`:i==="*"?r+=`(?:${u})*`:i==="+"?r+=`(?:${u})+`:i==="?"?r+=`(?:${u})?`:i==="!"&&(r+=`(?!(?:${u})$).*`),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=Sp(e,s);if(o===-1)r+="\\[",s++;else{let a=e.slice(s+1,o);r+=Ap(a),s=o+1}}else/[\^$.|+(){}]/.test(i)?(r+=`\\${i}`,s++):(r+=i,s++)}return r}function Ep(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 bp(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 Sp(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 Ap(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+=kp(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 vp=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 kp(e){return vp.get(e)??""}async function pn(e,t,n,r,s){let i="",o=e.state.shoptOptions.extglob;for(let a of t.parts)if(a.type==="Glob")i+=ae(a.pattern,n,o);else if(a.type==="Literal")i+=ae(a.value,n,o);else if(a.type==="SingleQuoted"||a.type==="Escaped")i+=ue(a.value);else if(a.type==="DoubleQuoted"){let l=await r(e,a.parts);i+=ue(l)}else if(a.type==="ParameterExpansion"){let l=await s(e,a);i+=ae(l,n,o)}else{let l=await s(e,a);i+=ue(l)}return i}function $t(e,t,n,r,s){if(r==="prefix")return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),ge(`^${n}`,"s").replace(t,"");let i=ge(`${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=ge(`^(?:.*)(${n})$`,"s").exec(t);if(!o)return t;let a=o[1]??"";return t.slice(0,t.length-a.length)}function tr(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 Ns(e,t,n,r,s){let i=new Qn(e.limits.maxStringLength,"pattern replacement",()=>new C(`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 Ic(e){let t=[],n=0;return{append(r){let s=B(r);if(s>e-n)throw new C(`prompt expansion exceeds string length limit (${e} bytes)`,"string_length");r&&t.push(r),n+=s},build:()=>t.join("")}}function xp(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=Ic(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 _r(e,t){let n=Ic(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")||"/",c=a.startsWith(l)?`~${a.slice(l.length)}`:a,u=a.split("/").pop()||a,f=new Date,d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],p=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 b="",y=r+1;for(;y<t.length&&y<r+4&&t[y]>="0"&&t[y]<="7";)b+=t[y],y++;let g=Number.parseInt(b,8)%256;n.append(String.fromCharCode(g)),r=y;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(`
103
+ `),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(o),r+=2;break;case"H":n.append(i),r+=2;break;case"w":n.append(c),r+=2;break;case"W":n.append(u),r+=2;break;case"d":{let b=String(f.getDate()).padStart(2," ");n.append(`${d[f.getDay()]} ${h[f.getMonth()]} ${b}`),r+=2;break}case"t":{let b=String(f.getHours()).padStart(2,"0"),y=String(f.getMinutes()).padStart(2,"0"),g=String(f.getSeconds()).padStart(2,"0");n.append(`${b}:${y}:${g}`),r+=2;break}case"T":{let b=f.getHours()%12;b===0&&(b=12);let y=String(b).padStart(2,"0"),g=String(f.getMinutes()).padStart(2,"0"),S=String(f.getSeconds()).padStart(2,"0");n.append(`${y}:${g}:${S}`),r+=2;break}case"@":{let b=f.getHours()%12;b===0&&(b=12);let y=String(b).padStart(2,"0"),g=String(f.getMinutes()).padStart(2,"0"),S=f.getHours()<12?"AM":"PM";n.append(`${y}:${g} ${S}`),r+=2;break}case"A":{let b=String(f.getHours()).padStart(2,"0"),y=String(f.getMinutes()).padStart(2,"0");n.append(`${b}:${y}`),r+=2;break}case"D":if(r+2<t.length&&t[r+2]==="{"){let b=t.indexOf("}",r+3);if(b!==-1){let y=t.slice(r+3,b);n.append(xp(y,f,e.limits.maxStringLength)),r=b+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(p),r+=2;break;case"!":n.append(p),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 mn(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`
104
+ `: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 tt(e,t){e.state.readonlyVars=e.state.readonlyVars||new Set,e.state.readonlyVars.add(t)}function Ze(e,t){return e.state.readonlyVars?.has(t)??!1}function de(e,t,n="bash"){if(Ze(e,t)){let r=`${n}: ${t}: readonly variable
105
+ `;throw new H(1,"",r)}return null}function Ct(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 Rs(e,t){e.state.exportedVars?.delete(t)}function yn(e,t){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))return"";let n="",r=$e(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"),fe(e,t)&&(n+="n"),Ze(e,t)&&(n+="r"),e.state.exportedVars?.has(t)&&(n+="x"),n}async function Tc(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}function vo(e){if(/^(?:\d+|[@*#?$!-])$/.test(e))throw new H(1,"",`bash: $${e}: cannot assign in this way
106
+ `)}async function _c(e,t,n,r,s){e.coverage?.hit("bash:expansion:assign_default");let i=r.isUnset||n.checkEmpty&&r.isEmpty;if(i&&vo(t),i&&n.word){let o=await s(e,n.word.parts,r.inDoubleQuotes),a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let[,l,c]=a;if(c==="@"||c==="*")throw new H(1,"",`${e.state.expansionStderr||""}bash: ${t}: bad array subscript
107
+ `);let u;if(/^\d+$/.test(c))u=Number.parseInt(c,10);else{try{let f=new Q,d=se(f,c);u=await ee(e,d.expression)}catch{let f=e.state.env.get(c);u=f?Number.parseInt(f,10):0}Number.isNaN(u)&&(u=0)}G(e,l,u,o)}else e.state.env.set(t,o);return o}return r.effectiveValue}async function Lc(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:error_if_unset"),r.isUnset||n.checkEmpty&&r.isEmpty){let o=n.word?await s(e,n.word.parts,r.inDoubleQuotes):`${t}: parameter null or not set`;throw new H(1,"",`bash: ${o}
108
+ `)}return r.effectiveValue}async function Fc(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 Mc(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_removal");let i=n.pattern?await pn(e,n.pattern,n.greedy,r,s):"";return $t(e,t,i,n.side,n.greedy)}async function Bc(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_replacement");let i="",o=e.state.shoptOptions.extglob;if(n.pattern)for(let c of n.pattern.parts)if(c.type==="Glob")i+=ae(c.pattern,!0,o);else if(c.type==="Literal")i+=ae(c.value,!0,o);else if(c.type==="SingleQuoted"||c.type==="Escaped")i+=ue(c.value);else if(c.type==="DoubleQuoted"){let u=await r(e,c.parts);i+=ue(u)}else if(c.type==="ParameterExpansion"){let u=await s(e,c);i+=ae(u,!0,o)}else{let u=await s(e,c);i+=ue(u)}let a=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 c=ge(i,l);return Ns(e,t,c,a,n.all)}catch(c){if(c instanceof C)throw c;return t}}function ko(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=K(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)&&Pt(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=le(e,t,0)||"";return String([...s].length)}return String([...n].length)}async function Wc(e,t,n,r){e.coverage?.hit("bash:expansion:substring");let s=await ee(e,r.offset.expression),i=r.length?await ee(e,r.length.expression):void 0;if(t==="@"||t==="*"){let c=Number.parseInt(e.state.env.get("#")||"0",10),u=[];for(let p=1;p<=c;p++)u.push(e.state.env.get(String(p))||"");let f=e.state.env.get("0")||"bash",d,h;if(s<=0)if(d=[f,...u],s<0){if(h=d.length+s,h<0)return""}else h=0;else d=u,h=s-1;if(h<0||h>=d.length)return"";if(i!==void 0){let p=i<0?d.length+i:h+i;return d.slice(h,Math.max(h,p)).join(" ")}return d.slice(h).join(" ")}let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(o){let c=o[1];if(e.state.associativeArrays?.has(c))throw new H(1,"",`bash: \${${c}[@]: 0: 3}: bad substitution
109
+ `);let u=K(e,c),f=0;if(s<0){if(u.length>0){let d=u[u.length-1][0],p=(typeof d=="number"?d:0)+1+s;if(p<0||(f=u.findIndex(([m])=>typeof m=="number"&&m>=p),f<0))return""}}else if(f=u.findIndex(([d])=>typeof d=="number"&&d>=s),f<0)return"";if(i!==void 0){if(i<0)throw new ce(`${o[1]}[@]: substring expression < 0`);return u.slice(f,f+i).map(([,d])=>d).join(" ")}return u.slice(f).map(([,d])=>d).join(" ")}let a=[...n],l=s;if(l<0&&(l=Math.max(0,a.length+l)),i!==void 0){if(i<0){let c=a.length+i;return a.slice(l,Math.max(l,c)).join("")}return a.slice(l,l+i).join("")}return a.slice(l).join("")}async function Vc(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:case_modification"),n.pattern){let i=e.state.shoptOptions.extglob,o="";for(let f of n.pattern.parts)if(f.type==="Glob")o+=ae(f.pattern,!0,i);else if(f.type==="Literal")o+=ae(f.value,!0,i);else if(f.type==="SingleQuoted"||f.type==="Escaped")o+=ue(f.value);else if(f.type==="DoubleQuoted"){let d=await r(e,f.parts);o+=ue(d)}else if(f.type==="ParameterExpansion"){let d=await s(e,f);o+=ae(d,!0,i)}let a=ge(`^(?:${o})$`),l=n.direction==="upper"?f=>f.toUpperCase():f=>f.toLowerCase(),c="",u=!1;for(let f of t)!n.all&&u?c+=f:a.test(f)?(c+=l(f),u=!0):c+=f;return c}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 zc(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 K(e,i[1]).map(([,c])=>mn(c)).join(" ");if(i&&s.operator==="a")return yn(e,i[1]);let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[.+\]$/);if(o&&s.operator==="a")return yn(e,o[1]);switch(s.operator){case"Q":return r?"":mn(n);case"P":return _r(e,n);case"a":return yn(e,t);case"A":return r?"":`${t}=${mn(n)}`;case"E":return n.replace(/\\([\\abefnrtv'"?])/g,(a,l)=>{switch(l){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
110
+ `;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?"":mn(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 Uc(e,t,n,r,s,i,o=!1){if(e.coverage?.hit("bash:expansion:indirection"),fe(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 st(`\${!${t}}`)}let l=n;if(a&&(l===""||l.includes(" ")))throw new st(`\${!${t}}`);let c=l.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(c&&c[1].includes("~"))throw new st(`\${!${t}}`);if(s.innerOp){let u={type:"ParameterExpansion",parameter:l,operation:s.innerOp};return i(e,u,o)}return await oe(e,l)}function jc(e,t){e.coverage?.hit("bash:expansion:array_keys");let r=K(e,t.array).map(([s])=>String(s));return t.star?r.join(Y(e.state.env)):r.join(" ")}function qc(e,t){e.coverage?.hit("bash:expansion:var_name_prefix");let n=tr(e,t.prefix);return t.star?n.join(Y(e.state.env)):n.join(" ")}function Hc(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=K(e,o);return l.length===0?{isEmpty:!0,effectiveValue:""}:a==="*"?{isEmpty:r?n==="":!1,effectiveValue:n}:{isEmpty:l.length===1&&l.every(([,c])=>c===""),effectiveValue:n}}return{isEmpty:n==="",effectiveValue:n}}function gn(e,t){e.lastExitCode=t,e.env.set("?",String(t)),e.lastSubstitutionExitCode=t}function Pp(e){switch(e.operator){case"<":case"<&":case"<<":case"<<-":case"<<<":case"<>":return e.fd===null||e.fd===0;default:return!1}}function Os(e,t){return t.some(Pp)?0:e.lastSubstitutionExitCode??0}function Gc(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 Zc(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 Ds(e,t){let n=new Q,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=mt(e.state.arrays),a=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let c=await e.executeScript(r),u=c.exitCode;return e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.suppressVerbose=l,gn(e.state,u),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr),e.state.bashPid=s,c.stdout.replace(/\n+$/,"")}catch(c){return e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.bashPid=s,e.state.suppressVerbose=l,ns(c),c instanceof H?(gn(e.state,c.exitCode),c.stdout?.replace(/\n+$/,"")??""):""}}function xo(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+=lt(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=$p(e,a);n+=lt(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 $p(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 Qc(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+=lt(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 Cp(e,a);n+=lt(l),r=i+1;continue}}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=Zc(t,r+2);if(i!==-1){let o=t.slice(r+2,i),a=await Ds(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 Ds(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 Cp(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=Zc(t,r+2);if(i!==-1){let o=t.slice(r+2,i),a=await Ds(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 Ds(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 Po(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 wn(e,t){return t.split(":").map(n=>Po(e,n)).join(":")}function Le(e,t,n,r){if(e.length>n-t.length)throw new C(`${r} element limit exceeded (${n})`,"array_elements");for(let s of t)e.push(s)}async function Np(e,t,n,r){let s="";for(let i of t.parts)if(i.type==="Glob")s+=ae(i.pattern,!0,e.state.shoptOptions.extglob);else if(i.type==="Literal")s+=ae(i.value,!0,e.state.shoptOptions.extglob);else if(i.type==="SingleQuoted"||i.type==="Escaped")s+=ue(i.value);else if(i.type==="DoubleQuoted"){let o=await n(e,i.parts);s+=ue(o)}else if(i.type==="ParameterExpansion"){let o=await r(e,i);s+=ae(o,!0,e.state.shoptOptions.extglob)}else{let o=await r(e,i);s+=ue(o)}return s}async function Kc(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]==="*",c=i.operation,u=K(e,a),f=u.map(([,E])=>E);if(u.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="";c.pattern&&(d=await Np(e,c.pattern,n,r));let h=c.replacement?await n(e,c.replacement.parts):"",p=d;c.anchor==="start"?p=`^${d}`:c.anchor==="end"&&(p=`${d}$`);let m=[];try{let E=ge(p,c.all?"g":"");for(let b of f)m.push(E.replace(b,h))}catch{m.push(...f)}if(l){let E=Y(e.state.env);return{values:[m.join(E)],quoted:!0}}return{values:m,quoted:!0}}async function Xc(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]==="*",c=i.operation,u=K(e,a),f=u.map(([,p])=>p);if(u.length===0){let p=e.state.env.get(a);p!==void 0&&f.push(p)}if(f.length===0)return{values:[],quoted:!0};let d=c.pattern?await pn(e,c.pattern,c.greedy,n,r):"",h=[];for(let p of f)h.push($t(e,p,d,c.side,c.greedy));if(l){let p=Y(e.state.env);return{values:[h.join(p)],quoted:!0}}return{values:h,quoted:!0}}async function Yc(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];if(r.operation?.type==="AssignDefault"&&/^(?:\d+|[@*#?$!-])$/.test(r.parameter))return null;let s=r.operation,i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(s.type==="AssignDefault"&&(!i||i[2]==="*"))return null;let o,a=!1;if(i){let l=i[1];a=i[2]==="*";let c=K(e,l),u=c.length>0||e.state.env.has(l),f=c.length===0||c.length===1&&c.every(([,h])=>h===""),d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=u&&!(d&&f):o=!u||d&&f,!o){if(c.length>0){let p=c.map(([,m])=>m);if(a){let m=Y(e.state.env);return{values:[p.join(m)],quoted:!0}}return{values:p,quoted:!0}}let h=e.state.env.get(l);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}}else{let l=r.parameter,c=await Mt(e,l),u=await oe(e,l,!1),f=u==="",d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=c&&!(d&&f):o=!c||d&&f,!o)return{values:[u],quoted:!0}}if(s.type==="AssignDefault")return null;if(o&&s.word){let l=s.word.parts,c=null,u=!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){c=d[1],u=d[2]==="*";break}}if(c){let f=K(e,c);if(f.length>0){let h=f.map(([,p])=>p);if(u||a){let p=Y(e.state.env);return{values:[h.join(p)],quoted:!0}}return{values:h,quoted:!0}}let d=e.state.env.get(c);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}return null}async function Jc(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,c=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 b=E.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(b){o=m,a=b[1],l=b[2]==="*",c=E.operation;break}}}if(o===-1||o===0&&o===i.parts.length-1)return null;let u="";for(let m=0;m<o;m++)u+=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=K(e,a),h=d.map(([,m])=>m);if(d.length===0){let m=e.state.env.get(a);if(m!==void 0)h=[m];else{if(l)return{values:[u+f],quoted:!0};let E=u+f;return{values:E?[E]:[],quoted:!0}}}if(c?.type==="PatternRemoval"){let m=c,E=m.pattern?await pn(e,m.pattern,m.greedy,s,r):"";h=h.map(b=>$t(e,b,E,m.side,m.greedy))}else if(c?.type==="PatternReplacement"){let m=c,E="";if(m.pattern)for(let g of m.pattern.parts)if(g.type==="Glob")E+=ae(g.pattern,!0,e.state.shoptOptions.extglob);else if(g.type==="Literal")E+=ae(g.value,!0,e.state.shoptOptions.extglob);else if(g.type==="SingleQuoted"||g.type==="Escaped")E+=ue(g.value);else if(g.type==="DoubleQuoted"){let S=await s(e,g.parts);E+=ue(S)}else if(g.type==="ParameterExpansion"){let S=await r(e,g);E+=ae(S,!0,e.state.shoptOptions.extglob)}else{let S=await r(e,g);E+=ue(S)}let b=m.replacement?await s(e,m.replacement.parts):"",y=E;m.anchor==="start"?y=`^${E}`:m.anchor==="end"&&(y=`${E}$`);try{let g=ge(y,m.all?"g":"");h=h.map(S=>g.replace(S,b))}catch{}}if(l){let m=Y(e.state.env);return{values:[u+h.join(m)+f],quoted:!0}}return h.length===1?{values:[u+h[0]+f],quoted:!0}:{values:[u+h[0],...h.slice(1,-1),h[h.length-1]+f],quoted:!0}}async function eu(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 h=0;h<s.parts.length;h++){let p=s.parts[h];if(p.type==="ParameterExpansion"&&!p.operation){let m=p.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(m){i=h,o=m[1],a=m[2]==="*";break}}}if(i===-1)return null;let l="";for(let h=0;h<i;h++)l+=await r(e,s.parts[h]);let c="";for(let h=i+1;h<s.parts.length;h++)c+=await r(e,s.parts[h]);let u=K(e,o),f=u.map(([,h])=>h);if(u.length===0){let h=e.state.env.get(o);if(h!==void 0)return{values:[l+h+c],quoted:!0};if(a)return{values:[l+c],quoted:!0};let p=l+c;return{values:p?[p]:[],quoted:!0}}if(a){let h=Y(e.state.env);return{values:[l+f.join(h)+c],quoted:!0}}return f.length===1?{values:[l+f[0]+c],quoted:!0}:{values:[l+f[0],...f.slice(1,-1),f[f.length-1]+c],quoted:!0}}async function tu(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 H(1,"",`bash: \${${o}[@]: 0: 3}: bad substitution
111
+ `);let c=l.offset?await n(e,l.offset.expression):0,u=l.length?await n(e,l.length.expression):void 0,f=K(e,o);if(f.length>e.limits.maxArrayElements)throw new C(`array transform element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let d=0;if(c<0){if(f.length>0){let p=f[f.length-1][0],E=(typeof p=="number"?p:0)+1+c;if(E<0)return{values:[],quoted:!0};d=f.findIndex(([b])=>typeof b=="number"&&b>=E),d<0&&(d=f.length)}}else d=f.findIndex(([p])=>typeof p=="number"&&p>=c),d<0&&(d=f.length);let h;if(u!==void 0){if(u<0)throw new ce(`${o}[@]: substring expression < 0`);h=f.slice(d,d+u).map(([,p])=>p)}else h=f.slice(d).map(([,p])=>p);if(h.length===0)return{values:[],quoted:!0};if(a){let p=Y(e.state.env);return{values:[h.join(p)],quoted:!0}}return{values:h,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?.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=K(e,i);if(l.length===0){let d=e.state.env.get(i);if(d!==void 0){let h;switch(a.operator){case"a":h="";break;case"P":h=_r(e,d);break;case"Q":h=mn(d);break;default:h=d}if(B(h)>e.limits.maxStringLength)throw new C(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[h],quoted:!0}}return o?{values:[""],quoted:!0}:{values:[],quoted:!0}}let c=yn(e,i),u=[],f=0;for(let[,d]of l){let h;switch(a.operator){case"a":h=c;break;case"P":h=_r(e,d);break;case"Q":h=mn(d);break;case"u":h=d.charAt(0).toUpperCase()+d.slice(1);break;case"U":h=d.toUpperCase();break;case"L":h=d.toLowerCase();break;default:h=d}let p=B(h);if(p>e.limits.maxStringLength-f)throw new C(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");u.push(h),f+=p}if(o){let d=Y(e.state.env);if(Math.max(0,u.length-1)*B(d)>e.limits.maxStringLength-f)throw new C(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u.join(d)],quoted:!0}}return{values:u,quoted:!0}}function ru(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(fe(e,i)){let l=Vn(e,i);if(l?.endsWith("[@]")||l?.endsWith("[*]"))return{values:[],quoted:!0}}let o=K(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)||!fe(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=K(e,a);if(l.length>0)return{values:l.map(([,u])=>u),quoted:!0};let c=e.state.env.get(a);return c!==void 0?{values:[c],quoted:!0}:{values:[],quoted:!0}}async function iu(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 oe(e,o.parameter),c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c){if(!a.innerOp&&(l==="@"||l==="*")){let p=Number.parseInt(e.state.env.get("#")||"0",10),m=[];for(let E=1;E<=p;E++)m.push(e.state.env.get(String(E))||"");return l==="*"?{values:[m.join(Y(e.state.env))],quoted:!0}:{values:m,quoted:!0}}return null}let u=c[1],f=c[2]==="*",d=K(e,u);if(a.innerOp){if(a.innerOp.type==="Substring")return Rp(e,d,u,f,a.innerOp);if(a.innerOp.type==="DefaultValue"||a.innerOp.type==="UseAlternative"||a.innerOp.type==="AssignDefault"||a.innerOp.type==="ErrorIfUnset")return Op(e,d,u,f,a.innerOp,s);if(a.innerOp.type==="Transform"&&a.innerOp.operator==="a"){let m=yn(e,u),E=d.map(()=>m);return f?{values:[E.join(Y(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let p=[];for(let[,m]of d){let E={type:"ParameterExpansion",parameter:"_indirect_elem_",operation:a.innerOp},b=e.state.env.get("_indirect_elem_");e.state.env.set("_indirect_elem_",m);try{let y=await r(e,E,!0);p.push(y)}finally{b!==void 0?e.state.env.set("_indirect_elem_",b):e.state.env.delete("_indirect_elem_")}}return f?{values:[p.join(Y(e.state.env))],quoted:!0}:{values:p,quoted:!0}}if(d.length>0){let p=d.map(([,m])=>m);return f?{values:[p.join(Y(e.state.env))],quoted:!0}:{values:p,quoted:!0}}let h=e.state.env.get(u);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}async function Rp(e,t,n,r,s){let i=s.offset?await ee(e,s.offset.expression):0,o=s.length?await ee(e,s.length.expression):void 0,a=0;if(i<0){if(t.length>0){let u=t[t.length-1][0],d=(typeof u=="number"?u:0)+1+i;if(d<0)return{values:[],quoted:!0};if(a=t.findIndex(([h])=>typeof h=="number"&&h>=d),a<0)return{values:[],quoted:!0}}}else if(a=t.findIndex(([u])=>typeof u=="number"&&u>=i),a<0)return{values:[],quoted:!0};let l;if(o!==void 0){if(o<0)throw new ce(`${n}[@]: substring expression < 0`);l=t.slice(a,a+o)}else l=t.slice(a);let c=l.map(([,u])=>u);return r?{values:[c.join(Y(e.state.env))],quoted:!0}:{values:c,quoted:!0}}async function Op(e,t,n,r,s,i){let o=s.checkEmpty??!1,a=t.map(([,u])=>u),l=t.length===0,c=t.length===0;if(s.type==="UseAlternative")return!c&&!(o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(s.type==="DefaultValue")return(c||o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:r?{values:[a.join(Y(e.state.env))],quoted:!0}:{values:a,quoted:!0};if(s.type==="AssignDefault"){if((c||o&&l)&&s.word){let f=await i(e,s.word.parts,!0);return G(e,n,0,f),{values:[f],quoted:!0}}return r?{values:[a.join(Y(e.state.env))],quoted:!0}:{values:a,quoted:!0}}return r?{values:[a.join(Y(e.state.env))],quoted:!0}:{values:a,quoted:!0}}async function ou(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 oe(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!l)return null;let c=await Mt(e,n.parameter),u=await oe(e,n.parameter)==="",f=r.checkEmpty??!1,d;if(r.type==="UseAlternative"?d=c&&!(f&&u):d=!c||f&&u,d){let h=l[1],p=l[2]==="*",m=K(e,h);if(m.length>0){let b=m.map(([,y])=>y);return p?{values:[b.join(Y(e.state.env))],quoted:!0}:{values:b,quoted:!0}}let E=e.state.env.get(h);return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function au(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],c=(await oe(e,a.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c)return null;let u=await oe(e,n.parameter),f=await Mt(e,n.parameter),d=u==="",h=s.checkEmpty??!1,p;if(s.type==="UseAlternative"?p=f&&!(h&&d):p=!f||h&&d,p){let m=c[1],E=c[2]==="*",b=K(e,m);if(b.length>0){let g=b.map(([,S])=>S);return E?{values:[g.join(Y(e.state.env))],quoted:!0}:{values:g,quoted:!0}}let y=e.state.env.get(m);return y!==void 0?{values:[y],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}function lu(e){let t=Number.parseInt(e.state.env.get("#")||"0",10);if(t>e.limits.maxArrayElements)throw new C(`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=B(i);if(o>e.limits.maxStringLength-r)throw new C(`positional parameter string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n.push(i),r+=o}return n}function Is(e,t,n){if(B(t)>n-B(e))throw new C(`positional expansion string limit exceeded (${n} bytes)`,"string_length");return e+t}function $o(e,t,n,r){if(e.length>=r.limits.maxArrayElements)throw new C(`positional expansion element limit exceeded (${r.limits.maxArrayElements})`,"array_elements");let s=B(t);if(s>r.limits.maxStringLength-n.value)throw new C(`positional expansion string limit exceeded (${r.limits.maxStringLength} bytes)`,"string_length");e.push(t),n.value+=s}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 y=0;y<s.parts.length;y++){let g=s.parts[y];if(g.type==="ParameterExpansion"&&(g.parameter==="@"||g.parameter==="*")&&g.operation?.type==="Substring"){i=y,o=g.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=l.offset?await n(e,l.offset.expression):0,u=l.length?await n(e,l.length.expression):void 0,f=Number.parseInt(e.state.env.get("#")||"0",10),d=[];for(let y=1;y<=f;y++)d.push(e.state.env.get(String(y))||"");let h=e.state.env.get("0")||"bash",p;if(c<=0){let y=[h,...d],g=y.length+c;if(g<0)p=[];else{let S=c<0?g:0;if(u!==void 0){let v=u<0?y.length+u:S+u;p=y.slice(S,Math.max(S,v))}else p=y.slice(S)}}else{let y=c-1;if(y>=d.length)p=[];else if(u!==void 0){let g=u<0?d.length+u:y+u;p=d.slice(y,Math.max(y,g))}else p=d.slice(y)}let m="";for(let y=0;y<i;y++)m+=await r(e,s.parts[y]);let E="";for(let y=i+1;y<s.parts.length;y++)E+=await r(e,s.parts[y]);if(p.length===0){let y=m+E;return{values:y?[y]:[],quoted:!0}}if(o){let y=Y(e.state.env);return{values:[m+p.join(y)+E],quoted:!0}}return p.length===1?{values:[m+p[0]+E],quoted:!0}:{values:[m+p[0],...p.slice(1,-1),p[p.length-1]+E],quoted:!0}}async function uu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let y=0;y<s.parts.length;y++){let g=s.parts[y];if(g.type==="ParameterExpansion"&&(g.parameter==="@"||g.parameter==="*")&&g.operation?.type==="PatternReplacement"){i=y,o=g.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=lu(e),u="";for(let y=0;y<i;y++)u=Is(u,await n(e,s.parts[y]),e.limits.maxStringLength);let f="";for(let y=i+1;y<s.parts.length;y++)f=Is(f,await n(e,s.parts[y]),e.limits.maxStringLength);if(c.length===0){let y=u+f;return{values:y?[y]:[],quoted:!0}}let d="";if(l.pattern)for(let y of l.pattern.parts)if(y.type==="Glob")d+=ae(y.pattern,!0,e.state.shoptOptions.extglob);else if(y.type==="Literal")d+=ae(y.value,!0,e.state.shoptOptions.extglob);else if(y.type==="SingleQuoted"||y.type==="Escaped")d+=ue(y.value);else if(y.type==="DoubleQuoted"){let g=await r(e,y.parts);d+=ue(g)}else if(y.type==="ParameterExpansion"){let g=await n(e,y);d+=ae(g,!0,e.state.shoptOptions.extglob)}else{let g=await n(e,y);d+=ue(g)}let h=l.replacement?await r(e,l.replacement.parts):"",p=d;l.anchor==="start"?p=`^${d}`:l.anchor==="end"&&(p=`${d}$`);let m=[],E={value:0};try{let y=ge(p,l.all?"g":"");for(let g of c){let S=0;y.lastIndex=0;for(let P=y.exec(g);P&&(S++,!!l.all);P=y.exec(g))P[0].length===0&&y.lastIndex++;let v=B(g),k=B(h),A=0,$=/\$(?:\$|&|\d+|<[^>]+>|`|')/g;for(;$.exec(h)!==null;)A++;if(v+S*k+S*A*v>e.limits.maxStringLength-E.value)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");$o(m,y.replace(g,h),E,e)}}catch(y){if(y instanceof C)throw y;for(let g of c)$o(m,g,E,e)}if(o){let y=Y(e.state.env);if(E.value+Math.max(0,m.length-1)*B(y)+B(u)+B(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+m.join(y)+f],quoted:!0}}if(B(u)+E.value+B(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return m.length===1?{values:[u+m[0]+f],quoted:!0}:{values:[u+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function fu(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let b=0;b<s.parts.length;b++){let y=s.parts[b];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="PatternRemoval"){i=b,o=y.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=lu(e),u="";for(let b=0;b<i;b++)u=Is(u,await n(e,s.parts[b]),e.limits.maxStringLength);let f="";for(let b=i+1;b<s.parts.length;b++)f=Is(f,await n(e,s.parts[b]),e.limits.maxStringLength);if(c.length===0){let b=u+f;return{values:b?[b]:[],quoted:!0}}let d="",h=e.state.shoptOptions.extglob;if(l.pattern)for(let b of l.pattern.parts)if(b.type==="Glob")d+=ae(b.pattern,l.greedy,h);else if(b.type==="Literal")d+=ae(b.value,l.greedy,h);else if(b.type==="SingleQuoted"||b.type==="Escaped")d+=ue(b.value);else if(b.type==="DoubleQuoted"){let y=await r(e,b.parts);d+=ue(y)}else if(b.type==="ParameterExpansion"){let y=await n(e,b);d+=ae(y,l.greedy,h)}else{let y=await n(e,b);d+=ue(y)}let p=[],m={value:0};for(let b of c)$o(p,$t(e,b,d,l.side,l.greedy),m,e);if(o){let b=Y(e.state.env);if(m.value+Math.max(0,p.length-1)*B(b)+B(u)+B(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+p.join(b)+f],quoted:!0}}if(B(u)+m.value+B(f)>e.limits.maxStringLength)throw new C(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return p.length===1?{values:[u+p[0]+f],quoted:!0}:{values:[u+p[0],...p.slice(1,-1),p[p.length-1]+f],quoted:!0}}async function du(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 h=r.parts[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")){s=d,i=h.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 c="";for(let d=s+1;d<r.parts.length;d++)c+=await n(e,r.parts[d]);if(a===0){if(i)return{values:[l+c],quoted:!0};let d=l+c;return{values:d?[d]:[],quoted:!0}}let u=[];for(let d=1;d<=a;d++)u.push(e.state.env.get(String(d))||"");if(i){let d=Y(e.state.env);return{values:[l+u.join(d)+c],quoted:!0}}return u.length===1?{values:[l+u[0]+c],quoted:!0}:{values:[l+u[0],...u.slice(1,-1),u[u.length-1]+c],quoted:!0}}function Wt(e,t,n,r){if(t.length>=e.limits.maxArrayElements)throw new C(`unquoted expansion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let s=B(n);if(s>e.limits.maxStringLength-r.value)throw new C(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");t.push(n),r.value+=s}function Co(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 C(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return t.join(n)}function Dp(e){return new hn(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 Ts(e,t){if(e.state.options.noglob)return t;let n=Dp(e),r=[];for(let s of t)if(Bt(s,e.state.shoptOptions.extglob)){let i=await n.expand(s);if(i.length>0)Le(r,i,e.limits.maxArrayElements,"unquoted glob expansion");else{if(n.hasFailglob())throw new tn(s);n.hasNullglob()||r.push(s)}}else r.push(s);return r}async function hu(e,t,n,r){let s=-1,i="",o=!1;for(let S=0;S<t.length;S++){let v=t[S];if(v.type==="ParameterExpansion"&&v.operation?.type==="PatternReplacement"){let k=v.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(k){s=S,i=k[1],o=k[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,c=K(e,i),u=c.map(([,S])=>S);if(c.length===0){let S=e.state.env.get(i);S!==void 0&&(u=[S])}if(u.length===0)return{values:[],quoted:!1};let f="";if(l.pattern)for(let S of l.pattern.parts)if(S.type==="Glob")f+=ae(S.pattern,!0,e.state.shoptOptions.extglob);else if(S.type==="Literal")f+=ae(S.value,!0,e.state.shoptOptions.extglob);else if(S.type==="SingleQuoted"||S.type==="Escaped")f+=ue(S.value);else if(S.type==="DoubleQuoted"){let v=await n(e,S.parts);f+=ue(v)}else if(S.type==="ParameterExpansion"){let v=await r(e,S);f+=ae(v,!0,e.state.shoptOptions.extglob)}else{let v=await r(e,S);f+=ue(v)}let d=l.replacement?await n(e,l.replacement.parts):"",h=f;l.anchor==="start"?h=`^${f}`:l.anchor==="end"&&(h=`${f}$`);let p=[],m={value:0};try{let S=ge(h,l.all?"g":"");for(let v of u)Wt(e,p,Ns(e,v,S,d,l.all),m)}catch(S){if(S instanceof C)throw S;for(let v of u)Wt(e,p,v,m)}let E=Pe(e.state.env),b=_e(e.state.env);if(o){let S=Y(e.state.env),v=Co(e,p,S,m.value);return b?{values:v?[v]:[],quoted:!1}:{values:he(v,E,e.limits.maxArrayElements),quoted:!1}}if(b)return{values:p,quoted:!1};let y=[],g={value:0};for(let S of p)if(S==="")Wt(e,y,"",g);else for(let v of he(S,E,e.limits.maxArrayElements))Wt(e,y,v,g);return{values:y,quoted:!1}}async function pu(e,t,n,r){let s=-1,i="",o=!1;for(let y=0;y<t.length;y++){let g=t[y];if(g.type==="ParameterExpansion"&&g.operation?.type==="PatternRemoval"){let S=g.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(S){s=y,i=S[1],o=S[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,c=K(e,i),u=c.map(([,y])=>y);if(c.length===0){let y=e.state.env.get(i);y!==void 0&&(u=[y])}if(u.length===0)return{values:[],quoted:!1};let f=l.pattern?await pn(e,l.pattern,l.greedy,n,r):"",d=[],h={value:0};for(let y of u)Wt(e,d,$t(e,y,f,l.side,l.greedy),h);let p=Pe(e.state.env),m=_e(e.state.env);if(o){let y=Y(e.state.env),g=Co(e,d,y,h.value);return m?{values:g?[g]:[],quoted:!1}:{values:he(g,p,e.limits.maxArrayElements),quoted:!1}}if(m)return{values:d,quoted:!1};let E=[],b={value:0};for(let y of d)if(y==="")Wt(e,E,"",b);else for(let g of he(y,p,e.limits.maxArrayElements))Wt(e,E,g,b);return{values:E,quoted:!1}}async function mu(e,t,n,r){let s=-1,i=!1;for(let y=0;y<t.length;y++){let g=t[y];if(g.type==="ParameterExpansion"&&(g.parameter==="@"||g.parameter==="*")&&g.operation?.type==="PatternRemoval"){s=y,i=g.parameter==="*";break}}if(s===-1)return null;let a=t[s].operation,l=Number.parseInt(e.state.env.get("#")||"0",10),c=[];for(let y=1;y<=l;y++)c.push(e.state.env.get(String(y))||"");if(c.length===0)return{values:[],quoted:!1};let u="",f=e.state.shoptOptions.extglob;if(a.pattern)for(let y of a.pattern.parts)if(y.type==="Glob")u+=ae(y.pattern,a.greedy,f);else if(y.type==="Literal")u+=ae(y.value,a.greedy,f);else if(y.type==="SingleQuoted"||y.type==="Escaped")u+=ue(y.value);else if(y.type==="DoubleQuoted"){let g=await n(e,y.parts);u+=ue(g)}else if(y.type==="ParameterExpansion"){let g=await r(e,y);u+=ae(g,a.greedy,f)}else{let g=await r(e,y);u+=ue(g)}let d=[],h={value:0};for(let y of c)Wt(e,d,$t(e,y,u,a.side,a.greedy),h);let p=Pe(e.state.env),m=_e(e.state.env);if(i){let y=Y(e.state.env),g=Co(e,d,y,h.value);return m?{values:g?[g]:[],quoted:!1}:{values:he(g,p,e.limits.maxArrayElements),quoted:!1}}if(m)return{values:d,quoted:!1};let E=[],b={value:0};for(let y of d)if(y==="")Wt(e,E,"",b);else for(let g of he(y,p,e.limits.maxArrayElements))Wt(e,E,g,b);return{values:E,quoted:!1}}async function yu(e,t,n,r){let s=-1,i=!1;for(let g=0;g<t.length;g++){let S=t[g];if(S.type==="ParameterExpansion"&&(S.parameter==="@"||S.parameter==="*")&&S.operation?.type==="Substring"){s=g,i=S.parameter==="*";break}}if(s===-1)return null;let a=t[s].operation,l=a.offset?await n(e,a.offset.expression):0,c=a.length?await n(e,a.length.expression):void 0,u=Number.parseInt(e.state.env.get("#")||"0",10),f=[];for(let g=1;g<=u;g++)f.push(e.state.env.get(String(g))||"");let d=e.state.env.get("0")||"bash",h;if(l<=0){let g=[d,...f],S=g.length+l;if(S<0)h=[];else{let v=l<0?S:0;if(c!==void 0){let k=c<0?g.length+c:v+c;h=g.slice(v,Math.max(v,k))}else h=g.slice(v)}}else{let g=l-1;if(g>=f.length)h=[];else if(c!==void 0){let S=c<0?f.length+c:g+c;h=f.slice(g,Math.max(g,S))}else h=f.slice(g)}let p="";for(let g=0;g<s;g++)p+=await r(e,t[g]);let m="";for(let g=s+1;g<t.length;g++)m+=await r(e,t[g]);let E=Pe(e.state.env),b=_e(e.state.env);if(h.length===0){let g=p+m;return g?b?{values:[g],quoted:!1}:{values:he(g,E,e.limits.maxArrayElements),quoted:!1}:{values:[],quoted:!1}}let y;if(i){let g=Y(e.state.env),S=p+h.join(g)+m;b?y=S?[S]:[]:y=he(S,E,e.limits.maxArrayElements)}else if(b)h.length===1?y=[p+h[0]+m]:y=[p+h[0],...h.slice(1,-1),h[h.length-1]+m];else{y=[];for(let g=0;g<h.length;g++){let S=h[g];if(g===0&&(S=p+S),g===h.length-1&&(S=S+m),S==="")y.push("");else{let v=he(S,E,e.limits.maxArrayElements);Le(y,v,e.limits.maxArrayElements,"unquoted expansion")}}}return{values:await Ts(e,y),quoted:!1}}async function gu(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 c=1;c<=r;c++)s.push(e.state.env.get(String(c))||"");let i=Pe(e.state.env),o=_e(e.state.env),a=ks(e.state.env),l;if(n)if(o)l=s.filter(c=>c!=="");else{let c=Y(e.state.env),u=s.join(c);l=he(u,i,e.limits.maxArrayElements)}else if(o)l=s.filter(c=>c!=="");else if(a){l=[];for(let c of s){if(c==="")continue;let u=he(c,i,e.limits.maxArrayElements);Le(l,u,e.limits.maxArrayElements,"unquoted expansion")}}else{l=[];for(let c of s)if(c==="")l.push("");else{let u=he(c,i,e.limits.maxArrayElements);Le(l,u,e.limits.maxArrayElements,"unquoted expansion")}for(;l.length>0&&l[l.length-1]==="";)l.pop()}return{values:await Ts(e,l),quoted:!1}}async function wu(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=K(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=Pe(e.state.env),l=_e(e.state.env),c=ks(e.state.env),u;if(s)if(l)u=o.filter(f=>f!=="");else{let f=Y(e.state.env),d=o.join(f);u=he(d,a,e.limits.maxArrayElements)}else if(l)u=o.filter(f=>f!=="");else if(c){u=[];for(let f of o){if(f==="")continue;let d=he(f,a,e.limits.maxArrayElements);Le(u,d,e.limits.maxArrayElements,"unquoted expansion")}}else{u=[];for(let f of o)if(f==="")u.push("");else{let d=he(f,a,e.limits.maxArrayElements);Le(u,d,e.limits.maxArrayElements,"unquoted expansion")}for(;u.length>0&&u[u.length-1]==="";)u.pop()}return{values:await Ts(e,u),quoted:!1}}function Eu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="VarNamePrefix")return null;let n=t[0].operation,r=tr(e,n.prefix);if(r.length===0)return{values:[],quoted:!1};let s=Pe(e.state.env),i=_e(e.state.env),o;if(n.star)if(i)o=r;else{let a=Y(e.state.env),l=r.join(a);o=he(l,s,e.limits.maxArrayElements)}else if(i)o=r;else{o=[];for(let a of r){let l=he(a,s,e.limits.maxArrayElements);Le(o,l,e.limits.maxArrayElements,"unquoted expansion")}}return{values:o,quoted:!1}}function bu(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="ArrayKeys")return null;let n=t[0].operation,s=K(e,n.array).map(([l])=>String(l));if(s.length===0)return{values:[],quoted:!1};let i=Pe(e.state.env),o=_e(e.state.env),a;if(n.star)if(o)a=s;else{let l=Y(e.state.env),c=s.join(l);a=he(c,i,e.limits.maxArrayElements)}else if(o)a=s;else{a=[];for(let l of s){let c=he(l,i,e.limits.maxArrayElements);Le(a,c,e.limits.maxArrayElements,"unquoted expansion")}}return{values:a,quoted:!1}}async function Su(e,t,n){let r=-1;for(let d=0;d<t.length;d++){let h=t[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")&&!h.operation){r=d;break}}if(r===-1||t.length<=1)return null;let 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=Pe(e.state.env),c=_e(e.state.env),u=ks(e.state.env);if(s===0){let d=o+a;return{values:d?[d]:[],quoted:!1}}let f;{let d=[];for(let h=0;h<i.length;h++){let p=i[h];h===0&&(p=o+p),h===i.length-1&&(p=p+a),d.push(p)}if(c)f=d.filter(h=>h!=="");else if(u){f=[];for(let h of d){if(h==="")continue;let p=he(h,l,e.limits.maxArrayElements);Le(f,p,e.limits.maxArrayElements,"unquoted expansion")}}else{f=[];for(let h of d)if(h==="")f.push("");else{let p=he(h,l,e.limits.maxArrayElements);Le(f,p,e.limits.maxArrayElements,"unquoted expansion")}for(;f.length>0&&f[f.length-1]==="";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await Ts(e,f),quoted:!1}}async function ku(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:c,hasIndirection:u}=Ir(r),d=n.hasBraceExpansion(r)?await n.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return Ip(e,d,s);let h=await Tp(e,r,a,c,u,n);if(h!==null)return h;let p=await Lp(e,r,n);if(p!==null)return p;let m=await Fp(e,r,n);if(m!==null)return m;let E=await Bp(e,r,n.expandPart);if(E!==null)return vu(e,E);if((i||o||l)&&!_e(e.state.env)){let y=Pe(e.state.env),g=n.buildIfsCharClassPattern(y),S=await n.smartWordSplit(e,r,y,g,n.expandPart);return vu(e,S)}let b=await n.expandWordAsync(e,t);return Wp(e,t,r,b,s,n.expandWordForGlobbing)}async function Ip(e,t,n){let r=[];for(let s of t)if(!(!n&&s===""))if(!n&&!e.state.options.noglob&&Bt(s,e.state.shoptOptions.extglob)){let i=await _s(e,s);Le(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=ru(e,t);if(o!==null)return o}{let o=su(e,t);if(o!==null)return o}{let o=await Yc(e,t);if(o!==null)return o}{let o=await Jc(e,t,n,i.expandPart,i.expandWordPartsAsync);if(o!==null)return o}{let o=await eu(e,t,n,i.expandPart);if(o!==null)return o}{let o=await tu(e,t,i.evaluateArithmetic);if(o!==null)return o}{let o=nu(e,t);if(o!==null)return o}{let o=await Kc(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}{let o=await Xc(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}if(r&&t.length===1&&t[0].type==="DoubleQuoted"){let o=_p(e,t);if(o!==null)return o}{let o=await iu(e,t,s,i.expandParameterAsync,i.expandWordPartsAsync);if(o!==null)return o}{let o=await ou(e,t);if(o!==null)return o}{let o=await au(e,t);if(o!==null)return o}return null}function _p(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=tr(e,r.prefix);return r.star?{values:[s.join(Y(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=K(e,r.array).map(([o])=>String(o));return r.star?{values:[i.join(Y(e.state.env))],quoted:!0}:{values:i,quoted:!0}}return null}async function Lp(e,t,n){{let r=await cu(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await uu(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await fu(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await du(e,t,n.expandPart);if(r!==null)return r}return null}async function Fp(e,t,n){{let r=await hu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await pu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await mu(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await yu(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await gu(e,t);if(r!==null)return r}{let r=await wu(e,t);if(r!==null)return r}{let r=Eu(e,t);if(r!==null)return r}{let r=bu(e,t);if(r!==null)return r}{let r=await Su(e,t,n.expandPart);if(r!==null)return r}return null}function Au(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 Mp(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=K(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=Y(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 Bp(e,t,n){if(t.length<2)return null;let r=!1;for(let l of t)if(Au(l)){r=!0;break}if(!r)return null;let s=Pe(e.state.env),i=_e(e.state.env),o=[];for(let l of t){let c=Au(l);if(c&&l.type==="DoubleQuoted"){let u=await Mp(e,l,c,n);o.push(u)}else if(l.type==="DoubleQuoted"||l.type==="SingleQuoted"){let u=await n(e,l);o.push([u])}else if(l.type==="Literal")o.push([l.value]);else if(l.type==="ParameterExpansion"){let u=await n(e,l);if(i)o.push(u?[u]:[]);else{let f=he(u,s,e.limits.maxArrayElements);o.push(f)}}else{let u=await n(e,l);if(i)o.push(u?[u]:[]);else{let f=he(u,s,e.limits.maxArrayElements);o.push(f)}}}let a=[];for(let l of o)if(l.length!==0)if(a.length===0)Le(a,l,e.limits.maxArrayElements,"word expansion");else{let c=a.length-1;a[c]=a[c]+l[0];for(let u=1;u<l.length;u++)a.push(l[u])}return a}async function vu(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let n=[];for(let r of t)if(Bt(r,e.state.shoptOptions.extglob)){let s=await _s(e,r);Le(n,s,e.limits.maxArrayElements,"glob expansion")}else n.push(r);return{values:n,quoted:!1}}async function _s(e,t){let n=new hn(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 tn(t);return n.hasNullglob()?[]:[t]}async function Wp(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(Bt(a,e.state.shoptOptions.extglob)){let c=await _s(e,a);if(c.length>0&&c[0]!==a)return{values:c,quoted:!1};if(c.length===0)return{values:[],quoted:!1}}let l=Ao(r);if(!_e(e.state.env)){let c=Pe(e.state.env);return{values:he(l,c,e.limits.maxArrayElements),quoted:!1}}return{values:[l],quoted:!1}}if(!s&&!e.state.options.noglob&&Bt(r,e.state.shoptOptions.extglob)){let a=await i(e,t);if(Bt(a,e.state.shoptOptions.extglob)){let l=await _s(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=Ao(r);if(!_e(e.state.env)){let l=Pe(e.state.env);return{values:he(a,l,e.limits.maxArrayElements),quoted:!1}}return{values:[a],quoted:!1}}return{values:[r],quoted:s}}function ze(e,t,n){if(t.length>=e.limits.maxArrayElements)throw new C(`word splitting element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");t.push(n)}async function Pu(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 Mt(e,t.parameter),o=await oe(e,t.parameter,!1)==="",a=n.checkEmpty??!1,l;return n.type==="UseAlternative"?l=s&&!(a&&o):l=!s||a&&o,l?(n.type==="AssignDefault"&&vo(t.parameter),r.parts):null}function Vp(e){return e.type==="SingleQuoted"?!0:e.type==="DoubleQuoted"?e.parts.every(n=>n.type==="Literal"):!1}async function zp(e,t){if(t.type!=="ParameterExpansion")return null;let n=await Pu(e,t);if(!n||n.length<=1)return null;let r=n.some(i=>Vp(i)),s=n.some(i=>i.type==="Literal"||i.type==="ParameterExpansion"||i.type==="CommandSubstitution"||i.type==="ArithmeticExpansion");return r&&s?n:null}function Up(e){return e.type==="DoubleQuoted"||e.type==="SingleQuoted"||e.type==="Literal"?!1:e.type==="Glob"?po(e.pattern):!(!(e.type==="ParameterExpansion"||e.type==="CommandSubstitution"||e.type==="ArithmeticExpansion")||e.type==="ParameterExpansion"&&kc(e))}async function $u(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:word_split"),t.length===1&&t[0].type==="ParameterExpansion"){let d=t[0],h=await Pu(e,d);if(h&&h.length>0&&h.length>1&&h.some(m=>m.type==="DoubleQuoted"||m.type==="SingleQuoted")&&h.some(m=>m.type==="Literal"||m.type==="ParameterExpansion"||m.type==="CommandSubstitution"||m.type==="ArithmeticExpansion"))return xu(e,h,n,r,s)}let i=[],o=!1;for(let d of t){let h=Up(d),p=d.type==="DoubleQuoted"||d.type==="SingleQuoted",m=h?await zp(e,d):null,E=await s(e,d);i.push({value:E,isSplittable:h,isQuoted:p,mixedDefaultParts:m??void 0}),h&&(o=!0)}if(!o){let d=i.map(h=>h.value).join("");return d?[d]:[]}let a=[],l="",c=!1,u=!1,f=!1;for(let d of i)if(!d.isSplittable)u?d.isQuoted&&d.value===""?(l!==""&&ze(e,a,l),ze(e,a,""),c=!0,l="",u=!1,f=!0):d.value!==""?(l!==""&&ze(e,a,l),l=d.value,u=!1,f=!1):(l+=d.value,f=!1):(l+=d.value,f=d.isQuoted&&d.value==="");else if(d.mixedDefaultParts){let h=await xu(e,d.mixedDefaultParts,n,r,s);if(h.length!==0)if(h.length===1)l+=h[0],c=!0;else{l+=h[0],ze(e,a,l),c=!0;for(let p=1;p<h.length-1;p++)ze(e,a,h[p]);l=h[h.length-1]}u=!1,f=!1}else{let{words:h,hadLeadingDelimiter:p,hadTrailingDelimiter:m}=xs(d.value,n,e.limits.maxArrayElements);if(f&&p&&l===""&&(ze(e,a,""),c=!0),h.length===0)m&&(u=!0);else if(h.length===1)l+=h[0],c=!0,u=m;else{l+=h[0],ze(e,a,l),c=!0;for(let E=1;E<h.length-1;E++)ze(e,a,h[E]);l=h[h.length-1],u=m}f=!1}return l!==""?ze(e,a,l):a.length===0&&c&&ze(e,a,""),a}function jp(e,t){return e.length>0&&t.includes(e[0])}async function xu(e,t,n,r,s){let i=[];for(let u of t){let d=!(u.type==="DoubleQuoted"||u.type==="SingleQuoted"),h=await s(e,u);i.push({value:h,isSplittable:d})}let o=[],a="",l=!1,c=!1;for(let u of i)if(!u.isSplittable)c&&u.value!==""?(a!==""&&ze(e,o,a),a=u.value,c=!1):a+=u.value;else{jp(u.value,n)&&a!==""&&(ze(e,o,a),a="",l=!0);let{words:d,hadTrailingDelimiter:h}=xs(u.value,n,e.limits.maxArrayElements);if(d.length===0)h&&(c=!0);else if(d.length===1)a+=d[0],l=!0,c=h;else{a+=d[0],ze(e,o,a),l=!0;for(let p=1;p<d.length-1;p++)ze(e,o,d[p]);a=d[d.length-1],c=h}}return a!==""?ze(e,o,a):o.length===0&&l&&ze(e,o,""),o}function Cu(e){switch(e.type){case"Literal":return e.value;case"SingleQuoted":return e.value;case"Escaped":return e.value;default:return null}}function Nu(e){switch(e.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return e.value==="";default:return!1}}var Ls="/dev/fd",Ou=63,qp=10,Ru=Ou-qp+1,No=class extends Ue{isLiveDescriptor;constructor(t){super(),this.isLiveDescriptor=t}assertLiveDescriptor(t,n){this.isLiveDescriptor(t)||this.refuse(t,n)}refuse(t,n){throw new x("EROFS",`read-only file system, ${n} '${Ls}${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 Hp(e){let t=new No(n=>Du(e).some(r=>r.path===`${Ls}${n}`));e.fs=new ot({base:e.fs,mounts:[{mountPoint:Ls,filesystem:t}]}),e.state.processSubstitutionFsMounted=!0}async function Gp(e,t,n){try{await e.fs.writeFile(t,n,"binary");return}catch(r){if(e.state.processSubstitutionFsMounted)throw r;Hp(e)}await e.fs.writeFile(t,n,"binary")}async function Zp(e,t){try{await e.fs.rm(t,{force:!0})}catch{}}function Du(e){let t=e.state.processSubstitutions;if(t)return t;let n=[];return e.state.processSubstitutions=n,n}async function Iu(e,t,n){let r=e.substitutionDepth??0,s=e.limits.maxSubstitutionDepth;if(r>=s)throw new C(`Process substitution nesting limit exceeded (${s})`,"substitution_depth");let i=e.substitutionDepth,o=new Map(e.state.env),a=mt(e.state.arrays),l=e.state.cwd,c=e.state.bashPid,u=e.state.suppressVerbose,f=e.state.groupStdin,d=e.state.lastExitCode,h=e.state.env.get("?"),p=e.state.lastSubstitutionExitCode;e.substitutionDepth=r+1,e.state.bashPid=e.state.nextVirtualPid++,e.state.suppressVerbose=!0,n!==void 0&&(e.state.groupStdin=n);let m;try{m=await e.executeScript(t)}catch(E){if(E instanceof C)throw E;if(E instanceof H)return{stdout:E.stdout,stderr:E.stderr,exitCode:E.exitCode};throw E}finally{e.substitutionDepth=i,e.state.env=o,e.state.arrays=a,e.state.cwd=l,e.state.bashPid=c,e.state.suppressVerbose=u,e.state.groupStdin=f,e.state.lastExitCode=d,e.state.lastSubstitutionExitCode=p,h!==void 0?e.state.env.set("?",h):e.state.env.delete("?")}return m}async function Tu(e,t){let n=Du(e);if(n.length>=Ru)throw new C(`Process substitution limit exceeded (${Ru} concurrent)`,"file_descriptors");let r="";if(t.direction==="input"){let o=await Iu(e,t.body,void 0);if(o.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+o.stderr),r=qt(o),r.length>e.limits.maxStringLength)throw new C(`process substitution: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")}let s=Ou-n.length,i=`${Ls}/${s}`;n.push({fd:s,path:i,direction:t.direction,body:t.body});try{await Gp(e,i,r)}catch(o){throw n.pop(),o}return i}function _u(e){return e.state.processSubstitutions?.length??0}var Qp={stdout:"",stderr:""};async function Ro(e,t){let n=e.state.processSubstitutions;if(!n||n.length<=t)return Qp;let r="",s="";for(;n.length>t;){let i=n[n.length-1],o="";if(i.direction==="output")try{o=await Zn(e.fs,i.path)}catch{}if(await Zp(e,i.path),n.pop(),i.direction==="output"){let a=await Iu(e,i.body,o);r+=qt(a),s+=a.stderr}}return{stdout:r,stderr:s}}function En(e,t,n){if(e.length>t)throw new C(`${n}: string length limit exceeded (${t} bytes)`,"string_length")}async function Nt(e,t,n=!1){let r=[],s=0;for(let i of t){let o=await ct(e,i,n);if(s+=B(o),s>e.limits.maxStringLength)throw new C(`parameter word string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");r.push(o)}return r.join("")}function Kp(e){return Nu(e)}function Fu(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!Kp(t))return!1;return!0}function Xp(e,t,n=!1){let r=Cu(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 xo(e,t.pattern);default:return null}}async function ie(e,t){return Do(e,t)}async function Mu(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped")n.push(er(r.value));else if(r.type==="SingleQuoted")n.push(r.value);else if(r.type==="DoubleQuoted"){let s=await Nt(e,r.parts);n.push(s)}else if(r.type==="TildeExpansion"){let s=await ct(e,r);n.push(er(s))}else n.push(await ct(e,r));return n.join("")}async function Bu(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(lt(r.value));else if(r.type==="DoubleQuoted"){let s=await Nt(e,r.parts);n.push(lt(s))}else n.push(await ct(e,r));return n.join("")}async function Wu(e,t){let n=[];for(let r of t.parts)if(r.type==="SingleQuoted")n.push(lt(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 Nt(e,r.parts);n.push(lt(s))}else r.type==="Glob"?Gc(r.pattern)?n.push(await Qc(e,r.pattern)):n.push(xo(e,r.pattern)):r.type==="Literal"?n.push(r.value):n.push(await ct(e,r));return n.join("")}function Ms(e){for(let t of e)if(t.type==="BraceExpansion"||t.type==="DoubleQuoted"&&Ms(t.parts))return!0;return!1}var Lu=1e5;async function Vu(e,t,n={count:0}){let r=()=>{n.count++,e.executionScope.consumeLimited("brace_operations",1,Math.min(Lu,e.limits.maxBraceExpansionResults),"brace expansion")},s=(o,a)=>{if(o.length>=e.limits.maxBraceExpansionResults)throw new C(`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,c="";for(let d of o.items)if(d.type==="Range"){let h=So(d.start,d.end,d.step,d.startStr,d.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(h.expanded)for(let p of h.expanded)s(a,p);else{l=!0,c=h.literal;break}}else{let h=await Vu(e,d.word.parts,n);for(let p of h){let m=[];for(let E of p)typeof E=="string"?m.push(E):m.push(await ct(e,E));s(a,m.join(""))}}if(l){for(let d of i)r(),d.push(c);continue}if(i.length*a.length>e.limits.maxBraceExpansionResults||n.count>Lu)throw new C(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");let f=[];for(let d of i)for(let h of a){if(f.length>=e.limits.maxBraceExpansionResults)throw new C(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),f.push([...d,h])}i=f}else for(let a of i)r(),a.push(o);return i}async function zu(e,t){let n=t.parts;if(!Ms(n))return[await ie(e,t)];let r=await Vu(e,n),s=[];for(let i of r){let o=[];for(let a of i)typeof a=="string"?o.push(a):o.push(await ct(e,a));s.push(Po(e,o.join("")))}return s}function Yp(){return{expandWordAsync:Do,expandWordForGlobbing:Wu,expandWordWithBracesAsync:zu,expandWordPartsAsync:Nt,expandPart:ct,expandParameterAsync:Fs,hasBraceExpansion:Ms,evaluateArithmetic:ee,buildIfsCharClassPattern:xc,smartWordSplit:$u}}async function Rt(e,t){return ku(e,t,Yp())}function Jp(e){for(let t of e){if(t.type==="ParameterExpansion")return t.parameter;if(t.type==="Literal")return t.value}return""}function Oo(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 Uu(e,t){if(Oo(e,t))return{error:`bash: $@: ambiguous redirect
112
+ `};let n=t.parts,{hasQuoted:r}=Ir(n);if(Ms(n)&&(await zu(e,t)).length>1)return{error:`bash: ${n.map(h=>h.type==="Literal"?h.value:h.type==="BraceExpansion"?`{${h.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
113
+ `};let s=await Do(e,t),{hasParamExpansion:i,hasCommandSub:o}=Ir(n);if((i||o)&&!r&&!_e(e.state.env)){let f=Pe(e.state.env);if(he(s,f,e.limits.maxArrayElements).length>1)return{error:`bash: $${Jp(n)}: ambiguous redirect
114
+ `}}if(r||e.state.options.noglob||n.some(f=>f.type==="ProcessSubstitution"))return{target:s};let l=await Wu(e,t);if(!Bt(l,e.state.shoptOptions.extglob))return{target:s};let c=new hn(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")}),u=await c.expand(l);return u.length===0?c.hasFailglob()?{error:`bash: no match: ${s}
110
115
  `}:{target:s}:u.length===1?{target:u[0]}:{error:`bash: ${s}: ambiguous redirect
111
- `}}async function No(e,t){let n=t.parts,r=n.length;if(r===1){let o=await at(e,n[0]);return gn(o,e.limits.maxStringLength,"word expansion"),o}let s=[];for(let o=0;o<r;o++)s.push(await at(e,n[o]));let i=s.join("");return gn(i,e.limits.maxStringLength,"word expansion"),i}async function at(e,t,n=!1){if(t.type==="ParameterExpansion")return _s(e,t,n);let r=qp(e,t,n);if(r!==null)return r;switch(t.type){case"DoubleQuoted":{let s=[];for(let i of t.parts)s.push(await at(e,i,!0));return s.join("")}case"CommandSubstitution":{let s=$c(t.body);if(s)try{let h=await ae(e,s.target),p=h.startsWith("/")?h:`${e.state.cwd}/${h}`,m=await e.fs.readFile(p);mn(e.state,0);let E=m.replace(/\n+$/,"");return gn(E,e.limits.maxStringLength,"command substitution"),E}catch(h){if(h instanceof C)throw h;return mn(e.state,1),""}let i=e.substitutionDepth??0,o=e.limits.maxSubstitutionDepth;if(i>=o)throw new C(`Command substitution nesting limit exceeded (${o})`,"substitution_depth");let a=e.substitutionDepth;e.substitutionDepth=i+1;let l=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let c=new Map(e.state.env),u=ht(e.state.arrays),f=e.state.cwd,d=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let h=await e.executeScript(t.body),p=h.exitCode;e.state.env=c,e.state.arrays=u,e.state.cwd=f,e.state.suppressVerbose=d,mn(e.state,p),h.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+h.stderr),e.state.bashPid=l,e.substitutionDepth=a;let m=h.stdout.replace(/\n+$/,"");return gn(m,e.limits.maxStringLength,"command substitution"),m}catch(h){if(e.state.env=c,e.state.arrays=u,e.state.cwd=f,e.state.bashPid=l,e.substitutionDepth=a,e.state.suppressVerbose=d,h instanceof C)throw h;if(h instanceof G){mn(e.state,h.exitCode),h.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+h.stderr);let p=h.stdout.replace(/\n+$/,"");return gn(p,e.limits.maxStringLength,"command substitution"),p}throw h}}case"ProcessSubstitution":return Ru(e,t);case"ArithmeticExpansion":{let s=t.expression.originalText;if(s&&/\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(s)){let o=await Pc(e,s),a=new Q,l=oe(a,o);return String(await ee(e,l.expression,!0))}return String(await ee(e,t.expression.expression,!0))}case"BraceExpansion":{let s=[];for(let i of t.items)if(i.type==="Range"){let o=bo(i.start,i.end,i.step,i.startStr,i.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(o.expanded)s.push(...o.expanded);else return o.literal}else s.push(await ae(e,i.word));return s.join(" ")}default:return""}}async function _s(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,h]=i;if(e.state.associativeArrays?.has(d)||h.includes("$(")||h.includes("`")||h.includes("${")){let m=await wo(e,h);r=`${d}[${m}]`}}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&fe(e,r)){let d=Ge(e,r);if(d&&d!==r){let h=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,p,m]=h;if(e.state.associativeArrays?.has(p)||m.includes("$(")||m.includes("`")||m.includes("${")){let S=await wo(e,m);r=`${p}[${S}]`}}}}let o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=await le(e,r,!o);if(!s)return a;let l=!await Lt(e,r),{isEmpty:c,effectiveValue:u}=zc(e,r,a,n),f={value:a,isUnset:l,isEmpty:c,effectiveValue:u,inDoubleQuotes:n};switch(s.type){case"DefaultValue":return Nc(e,s,f,$t);case"AssignDefault":return Rc(e,r,s,f,$t);case"ErrorIfUnset":return Oc(e,r,s,f,$t);case"UseAlternative":return Dc(e,s,f,$t);case"PatternRemoval":{let d=await Ic(e,a,s,$t,at);return gn(d,e.limits.maxStringLength,"pattern removal"),d}case"PatternReplacement":{let d=await Tc(e,a,s,$t,at);return gn(d,e.limits.maxStringLength,"pattern replacement"),d}case"Length":return _c(e,r,a);case"LengthSliceError":throw new rt(r);case"BadSubstitution":throw new rt(s.text);case"Substring":return Lc(e,r,a,s);case"CaseModification":{let d=await Fc(e,a,s,$t,_s);return gn(d,e.limits.maxStringLength,"case modification"),d}case"Transform":return Mc(e,r,a,l,s);case"Indirection":return Bc(e,r,a,l,s,_s,n);case"ArrayKeys":return Wc(e,s);case"VarNamePrefix":return Vc(e,s);default:return a}}function Vu(){return{visited:new Set,depth:0}}function Zp(e,t,n){switch(n){case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":if(t===0)throw new ue("division by 0");return Math.trunc(e/t);case"%":if(t===0)throw new ue("division by 0");return e%t;case"**":if(t<0)throw new ue("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 Wu(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 Qp(e,t){switch(t){case"-":return-e;case"+":return+e;case"!":return e===0?1:0;case"~":return~e;default:return e}}async function Kp(e,t){let n=e.state.env.get(t);if(n!==void 0)return n;let r=ce(e,t,0);return r!==void 0?r:await le(e,t)}async function Xp(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 Q,{expr:o,pos:a}=Yn(i,s,0);if(a<s.length){let l=s.slice(a).trim(),c=l.split(/\s+/)[0]||l;throw new ue(`syntax error in expression (error token is "${c}")`,"","")}return await nr(e,o,!1,n)}async function Fs(e,t,n,r){if(r.depth>100)throw new ue("maximum variable indirection depth exceeded");if(r.visited.has(t))throw new ue(`arithmetic variable cycle detected at ${t}`);r.visited.add(t),r.depth++;try{return await Xp(e,n,r)}finally{r.depth--,r.visited.delete(t)}}async function Ro(e,t,n){if(n.depth>100)throw new ue("maximum variable indirection depth exceeded");if(n.visited.has(t))throw new ue(`arithmetic variable cycle detected at ${t}`);n.visited.add(t),n.depth++;try{let r=await Kp(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 Ro(e,i,n);let o=new Q,{expr:a,pos:l}=Yn(o,i,0);if(l<i.length){let c=i.slice(l).trim(),u=c.split(/\s+/)[0]||c;throw new ue(`${i}: syntax error in expression (error token is "${u}")`)}return await nr(e,a,!1,n)}finally{n.depth--,n.visited.delete(t)}}async function Ms(e,t){if(t.startsWith("#")){let f=t.slice(1),d=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let p=d[1],m=K(e,p);return String(m.length)}let h=e.state.env.get(f)||"";return String(h.length)}if(t.startsWith("!")){let f=t.slice(1),d=e.state.env.get(f)||"";return e.state.env.get(d)||""}let 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 le(e,t);let i=t.slice(0,r),o=t.slice(r+s.length),a=e.state.env.get(i),l=a===void 0,c=a==="",u=s.startsWith(":");switch(s){case":-":case"-":return l||u&&c?o:a||"";case":=":case"=":return l||u&&c?(e.state.env.set(i,o),o):a||"";case":+":case"+":return!(l||u&&c)?o:"";case":?":case"?":{if(l||u&&c)throw new Error(o||`${i}: parameter null or not set`);return a||""}default:return a||""}}async function ee(e,t,n=!1){return nr(e,t,n,Vu())}async function nr(e,t,n,r){let s=(i,o=n)=>nr(e,i,o,r);switch(t.type){case"ArithNumber":if(Number.isNaN(t.value))throw new ue("value too great for base");return t.value;case"ArithVariable":return await Ro(e,t.name,r);case"ArithSpecialVar":{let o=(await le(e,t.name)).trim();if(!o)return 0;let a=Number.parseInt(o,10);if(!Number.isNaN(a)&&/^-?\d+$/.test(o))return a;let l=new Q,{expr:c}=Yn(l,o,0);return await s(c)}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 o=i.stdout.trim();return Number.parseInt(o,10)||0}return 0}case"ArithBracedExpansion":{let i=await Ms(e,t.content);return Number.parseInt(i,10)||0}case"ArithDynamicBase":{let i=await Ms(e,t.baseExpr),o=Number.parseInt(i,10);if(o<2||o>64)return 0;let a=`${o}#${t.value}`;return xr(a)}case"ArithDynamicNumber":{let o=await Ms(e,t.prefix)+t.suffix;return xr(o)}case"ArithArrayElement":{let i=e.state.associativeArrays?.has(t.array),o=async a=>{let l=ce(e,t.array,a);return l!==void 0?await Fs(e,`${t.array}[${a}]`,l,r):0};if(t.stringKey!==void 0)return await o(t.stringKey);if(i&&t.index?.type==="ArithVariable"&&!t.index.hasDollarPrefix)return await o(t.index.name);if(i&&t.index?.type==="ArithVariable"&&t.index.hasDollarPrefix){let a=await le(e,t.index.name);return await o(a)}if(t.index){let a=await s(t.index);if(a<0){let u=K(e,t.array),f=e.state.currentLine;if(u.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${t.array}: bad array subscript
116
+ `}}async function Do(e,t){let n=t.parts,r=n.length;if(r===1){let o=await ct(e,n[0]);return En(o,e.limits.maxStringLength,"word expansion"),o}let s=[];for(let o=0;o<r;o++)s.push(await ct(e,n[o]));let i=s.join("");return En(i,e.limits.maxStringLength,"word expansion"),i}async function ct(e,t,n=!1){if(t.type==="ParameterExpansion")return Fs(e,t,n);let r=Xp(e,t,n);if(r!==null)return r;switch(t.type){case"DoubleQuoted":{let s=[];for(let i of t.parts)s.push(await ct(e,i,!0));return s.join("")}case"CommandSubstitution":{let s=Dc(t.body);if(s)try{let h=await ie(e,s.target),p=h.startsWith("/")?h:`${e.state.cwd}/${h}`,m=await e.fs.readFile(p);gn(e.state,0);let E=m.replace(/\n+$/,"");return En(E,e.limits.maxStringLength,"command substitution"),E}catch(h){if(h instanceof C)throw h;return gn(e.state,1),""}let i=e.substitutionDepth??0,o=e.limits.maxSubstitutionDepth;if(i>=o)throw new C(`Command substitution nesting limit exceeded (${o})`,"substitution_depth");let a=e.substitutionDepth;e.substitutionDepth=i+1;let l=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let c=new Map(e.state.env),u=mt(e.state.arrays),f=e.state.cwd,d=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let h=await e.executeScript(t.body),p=h.exitCode;e.state.env=c,e.state.arrays=u,e.state.cwd=f,e.state.suppressVerbose=d,gn(e.state,p),h.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+h.stderr),e.state.bashPid=l,e.substitutionDepth=a;let m=h.stdout.replace(/\n+$/,"");return En(m,e.limits.maxStringLength,"command substitution"),m}catch(h){if(e.state.env=c,e.state.arrays=u,e.state.cwd=f,e.state.bashPid=l,e.substitutionDepth=a,e.state.suppressVerbose=d,h instanceof C)throw h;if(h instanceof H){gn(e.state,h.exitCode),h.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+h.stderr);let p=h.stdout.replace(/\n+$/,"");return En(p,e.limits.maxStringLength,"command substitution"),p}throw h}}case"ProcessSubstitution":return Tu(e,t);case"ArithmeticExpansion":{let s=t.expression.originalText;if(s&&/\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(s)){let o=await Oc(e,s),a=new Q,l=se(a,o);return String(await ee(e,l.expression,!0))}return String(await ee(e,t.expression.expression,!0))}case"BraceExpansion":{let s=[];for(let i of t.items)if(i.type==="Range"){let o=So(i.start,i.end,i.step,i.startStr,i.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(o.expanded)s.push(...o.expanded);else return o.literal}else s.push(await ie(e,i.word));return s.join(" ")}default:return""}}async function Fs(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,h]=i;if(e.state.associativeArrays?.has(d)||h.includes("$(")||h.includes("`")||h.includes("${")){let m=await Eo(e,h);r=`${d}[${m}]`}}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&fe(e,r)){let d=Ge(e,r);if(d&&d!==r){let h=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,p,m]=h;if(e.state.associativeArrays?.has(p)||m.includes("$(")||m.includes("`")||m.includes("${")){let b=await Eo(e,m);r=`${p}[${b}]`}}}}if(s?.type==="Length"&&/^[a-zA-Z_][a-zA-Z0-9_]*\[[@*]\]$/.test(r))return ko(e,r,"");let o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=await oe(e,r,!o);if(!s)return a;let l=!await Mt(e,r),{isEmpty:c,effectiveValue:u}=Hc(e,r,a,n),f={value:a,isUnset:l,isEmpty:c,effectiveValue:u,inDoubleQuotes:n};switch(s.type){case"DefaultValue":return Tc(e,s,f,Nt);case"AssignDefault":return _c(e,r,s,f,Nt);case"ErrorIfUnset":return Lc(e,r,s,f,Nt);case"UseAlternative":return Fc(e,s,f,Nt);case"PatternRemoval":{let d=await Mc(e,a,s,Nt,ct);return En(d,e.limits.maxStringLength,"pattern removal"),d}case"PatternReplacement":{let d=await Bc(e,a,s,Nt,ct);return En(d,e.limits.maxStringLength,"pattern replacement"),d}case"Length":return ko(e,r,a);case"LengthSliceError":throw new st(r);case"BadSubstitution":throw new st(s.text);case"Substring":return Wc(e,r,a,s);case"CaseModification":{let d=await Vc(e,a,s,Nt,Fs);return En(d,e.limits.maxStringLength,"case modification"),d}case"Transform":return zc(e,r,a,l,s);case"Indirection":return Uc(e,r,a,l,s,Fs,n);case"ArrayKeys":return jc(e,s);case"VarNamePrefix":return qc(e,s);default:return a}}function qu(){return{visited:new Set,depth:0}}function em(e,t,n){switch(n){case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":if(t===0)throw new ce("division by 0");return Math.trunc(e/t);case"%":if(t===0)throw new ce("division by 0");return e%t;case"**":if(t<0)throw new ce("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 ju(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 tm(e,t){switch(t){case"-":return-e;case"+":return+e;case"!":return e===0?1:0;case"~":return~e;default:return e}}async function nm(e,t){let n=e.state.env.get(t);if(n!==void 0)return n;let r=le(e,t,0);return r!==void 0?r:await oe(e,t)}async function rm(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 Q,{expr:o,pos:a}=Jn(i,s,0);if(a<s.length){let l=s.slice(a).trim(),c=l.split(/\s+/)[0]||l;throw new ce(`syntax error in expression (error token is "${c}")`,"","")}return await rr(e,o,!1,n)}async function Bs(e,t,n,r){if(r.depth>100)throw new ce("maximum variable indirection depth exceeded");if(r.visited.has(t))throw new ce(`arithmetic variable cycle detected at ${t}`);r.visited.add(t),r.depth++;try{return await rm(e,n,r)}finally{r.depth--,r.visited.delete(t)}}async function Io(e,t,n){if(n.depth>100)throw new ce("maximum variable indirection depth exceeded");if(n.visited.has(t))throw new ce(`arithmetic variable cycle detected at ${t}`);n.visited.add(t),n.depth++;try{let r=await nm(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 Io(e,i,n);let o=new Q,{expr:a,pos:l}=Jn(o,i,0);if(l<i.length){let c=i.slice(l).trim(),u=c.split(/\s+/)[0]||c;throw new ce(`${i}: syntax error in expression (error token is "${u}")`)}return await rr(e,a,!1,n)}finally{n.depth--,n.visited.delete(t)}}async function Ws(e,t){if(t.startsWith("#")){let f=t.slice(1),d=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let p=d[1],m=K(e,p);return String(m.length)}let h=e.state.env.get(f)||"";return String(h.length)}if(t.startsWith("!")){let f=t.slice(1),d=e.state.env.get(f)||"";return e.state.env.get(d)||""}let 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 oe(e,t);let i=t.slice(0,r),o=t.slice(r+s.length),a=e.state.env.get(i),l=a===void 0,c=a==="",u=s.startsWith(":");switch(s){case":-":case"-":return l||u&&c?o:a||"";case":=":case"=":return l||u&&c?(e.state.env.set(i,o),o):a||"";case":+":case"+":return!(l||u&&c)?o:"";case":?":case"?":{if(l||u&&c)throw new Error(o||`${i}: parameter null or not set`);return a||""}default:return a||""}}async function ee(e,t,n=!1){return rr(e,t,n,qu())}async function rr(e,t,n,r){let s=(i,o=n)=>rr(e,i,o,r);switch(t.type){case"ArithNumber":if(Number.isNaN(t.value))throw new ce("value too great for base");return t.value;case"ArithVariable":return await Io(e,t.name,r);case"ArithSpecialVar":{let o=(await oe(e,t.name)).trim();if(!o)return 0;let a=Number.parseInt(o,10);if(!Number.isNaN(a)&&/^-?\d+$/.test(o))return a;let l=new Q,{expr:c}=Jn(l,o,0);return await s(c)}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 o=i.stdout.trim();return Number.parseInt(o,10)||0}return 0}case"ArithBracedExpansion":{let i=await Ws(e,t.content);return Number.parseInt(i,10)||0}case"ArithDynamicBase":{let i=await Ws(e,t.baseExpr),o=Number.parseInt(i,10);if(o<2||o>64)return 0;let a=`${o}#${t.value}`;return Cr(a)}case"ArithDynamicNumber":{let o=await Ws(e,t.prefix)+t.suffix;return Cr(o)}case"ArithArrayElement":{let i=e.state.associativeArrays?.has(t.array),o=async a=>{let l=le(e,t.array,a);return l!==void 0?await Bs(e,`${t.array}[${a}]`,l,r):0};if(t.stringKey!==void 0)return await o(t.stringKey);if(i&&t.index?.type==="ArithVariable"&&!t.index.hasDollarPrefix)return await o(t.index.name);if(i&&t.index?.type==="ArithVariable"&&t.index.hasDollarPrefix){let a=await oe(e,t.index.name);return await o(a)}if(t.index){let a=await s(t.index);if(a<0){let u=K(e,t.array),f=e.state.currentLine;if(u.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${t.array}: bad array subscript
112
117
  `,0;let h=Math.max(...u.map(([p])=>typeof p=="number"?p:0))+1+a;if(h<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${t.array}: bad array subscript
113
- `,0;a=h}let l=`${t.array}[${a}]`,c=ce(e,t.array,a);if(c!==void 0)return Fs(e,l,c,r);if(a===0){let u=e.state.env.get(t.array);if(u!==void 0)return Fs(e,t.array,u,r)}if(e.state.options.nounset&&!(e.state.env.has(t.array)||De(e,t.array)))throw new Ke(`${t.array}[${a}]`);return 0}return 0}case"ArithDoubleSubscript":throw new ue("double subscript","","");case"ArithNumberSubscript":throw new ue(`${t.number}${t.errorToken}: syntax error: invalid arithmetic operator (error token is "${t.errorToken}")`);case"ArithSyntaxError":throw new ue(t.message,"","",!0);case"ArithSingleQuote":{if(n)throw new ue(`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),o=await s(t.right);return Zp(i,o,t.operator)}case"ArithUnary":{let i=await s(t.operand);if(t.operator==="++"||t.operator==="--"){if(t.operand.type==="ArithVariable"){let o=t.operand.name,a=Number.parseInt(await le(e,o),10)||0,l=t.operator==="++"?a+1:a-1;return e.state.env.set(o,String(l)),t.prefix?l:a}if(t.operand.type==="ArithArrayElement"){let o=t.operand.array,a=e.state.associativeArrays?.has(o),l;if(t.operand.stringKey!==void 0)l=t.operand.stringKey;else if(a&&t.operand.index?.type==="ArithVariable"&&!t.operand.index.hasDollarPrefix)l=t.operand.index.name;else if(a&&t.operand.index?.type==="ArithVariable"&&t.operand.index.hasDollarPrefix)l=await le(e,t.operand.index.name);else if(t.operand.index){let f=await s(t.operand.index);l=String(f)}else return i;let c=Number.parseInt(ce(e,o,l)||"0",10)||0,u=t.operator==="++"?c+1:c-1;return H(e,o,l,String(u),a?"associative":"indexed"),t.prefix?u:c}if(t.operand.type==="ArithConcat"){let o="";for(let a of t.operand.parts)o+=await tr(e,a,n,r);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=Number.parseInt(e.state.env.get(o)||"0",10)||0,l=t.operator==="++"?a+1:a-1;return e.state.env.set(o,String(l)),t.prefix?l:a}}if(t.operand.type==="ArithDynamicElement"){let o="";if(t.operand.nameExpr.type==="ArithConcat")for(let a of t.operand.nameExpr.parts)o+=await tr(e,a,n,r);else t.operand.nameExpr.type==="ArithVariable"&&(o=t.operand.nameExpr.hasDollarPrefix?await le(e,t.operand.nameExpr.name):t.operand.nameExpr.name);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=await s(t.operand.subscript),l=Number.parseInt(ce(e,o,a)||"0",10)||0,c=t.operator==="++"?l+1:l-1;return H(e,o,a,String(c)),t.prefix?c:l}}return i}return Qp(i,t.operator)}case"ArithTernary":return await s(t.condition)?await s(t.consequent):await s(t.alternate);case"ArithAssignment":{let i=t.variable,o=i,a;if(t.stringKey!==void 0)a=t.stringKey;else if(t.subscript){let d=e.state.associativeArrays?.has(i);if(d&&t.subscript.type==="ArithVariable"&&!t.subscript.hasDollarPrefix)a=t.subscript.name;else if(d&&t.subscript.type==="ArithVariable"&&t.subscript.hasDollarPrefix)a=await le(e,t.subscript.name)||"\\";else if(d){let h=await s(t.subscript);a=String(h)}else{let h=await s(t.subscript);if(h<0){let p=K(e,i);p.length>0&&(h=Math.max(...p.map(([E])=>typeof E=="number"?E:0))+1+h)}a=String(h)}}let l=a===void 0?e.state.env.get(o):ce(e,i,a),c=Number.parseInt(l||"0",10)||0,u=await s(t.value),f=Wu(c,u,t.operator);return a===void 0?e.state.env.set(o,String(f)):H(e,i,a,String(f),e.state.associativeArrays?.has(i)?"associative":"indexed"),f}case"ArithGroup":return await s(t.expression);case"ArithConcat":{let i="";for(let o of t.parts)i+=await tr(e,o,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?await Ro(e,i,r):Number.parseInt(i,10)||0}case"ArithDynamicAssignment":{let i="";if(t.target.type==="ArithConcat")for(let u of t.target.parts)i+=await tr(e,u,n,r);else t.target.type==="ArithVariable"&&(i=t.target.hasDollarPrefix?await le(e,t.target.name):t.target.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=i;if(t.subscript){let u=await s(t.subscript);o=`${i}_${u}`}let a=Number.parseInt(e.state.env.get(o)||"0",10)||0,l=await s(t.value),c=Wu(a,l,t.operator);return e.state.env.set(o,String(c)),c}case"ArithDynamicElement":{let i="";if(t.nameExpr.type==="ArithConcat")for(let c of t.nameExpr.parts)i+=await tr(e,c,n,r);else t.nameExpr.type==="ArithVariable"&&(i=t.nameExpr.hasDollarPrefix?await le(e,t.nameExpr.name):t.nameExpr.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=await s(t.subscript),a=`${i}_${o}`,l=e.state.env.get(a);return l!==void 0?Fs(e,a,l,r):0}default:return 0}}async function tr(e,t,n=!1,r=Vu()){switch(t.type){case"ArithNumber":return String(t.value);case"ArithSingleQuote":return String(await nr(e,t,n,r));case"ArithVariable":return t.hasDollarPrefix?await le(e,t.name):t.name;case"ArithSpecialVar":return await le(e,t.name);case"ArithBracedExpansion":return await Ms(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 tr(e,i,n,r);return s}default:return String(await nr(e,t,n,r))}}async function zu(e,t){let n="",r=0;for(let A of t.parts){let k=A.type==="Literal"?A.value:"\0",v=W(k);if(v>e.limits.maxStringLength-r)throw new C(`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],o=[],a=[],l=!1,c="",u=0,f=0,d=!1,h=!0,p=A=>{let k=W(A);if(k>e.limits.maxStringLength-f-u)throw new C(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");c+=A,u+=k},m=(A,k=!1)=>{if(o.length>=e.limits.maxArrayElements)throw new C(`array assignment element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let v=W(A);if(v>e.limits.maxStringLength-f)throw new C(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");o.push(A),a.push(k),f+=v},E=()=>{m(c,h),c="",u=0,d=!1,h=!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)?(c||d)&&E():p(v)}}else if(l)if(A.type==="BraceExpansion")if(/^\[.+\]=/.test(c))p(Kn({type:"Word",parts:[A]}));else{(c||d)&&E();let v=await Ct(e,{type:"Word",parts:[A]});for(let $ of v.values)m($)}else{(A.type==="SingleQuoted"||A.type==="DoubleQuoted"||A.type==="Escaped")&&(d=!0),h=!1;let k=await ae(e,{type:"Word",parts:[A]});p(k)}(c||d)&&E();let S=o.splice(0),g=a.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 $=yn(e,v[2]);k=v[1]+$}if(k.includes("{")&&k.includes("}")){let $=new Q().parseWordFromString(k,!1,!1);if($.parts.some(O=>O.type==="BraceExpansion")){let O=await Ct(e,$);for(let P of O.values)m(P);continue}}m(k)}let y=[`${i}=(`],b=W(y[0]);for(let A=0;A<o.length;A++){let k=o[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}`,O=W($);if(O+1>e.limits.maxStringLength-b)throw new C(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");y.push($),b+=O}return y.push(")"),y.join("")}async function Uu(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),o=t.parts[n];if(o.type!=="Literal")return null;let a=s?2:1,l=o.value.slice(0,r),c=o.value.slice(r+a),u=t.parts.slice(n+1),f="";for(let m of i)f+=await ae(e,{type:"Word",parts:[m]});f+=l;let d={type:"Word",parts:c!==""?[{type:"Literal",value:c},...u]:u},h=d.parts.length>0?await ae(e,d):"";return`${f}${s?"+=":"="}${h}`}var Yp=["tar","yq","xan","sqlite3","python3","python"];function ju(e){return Yp.includes(e)}var se=Object.freeze({stdout:"",stderr:"",exitCode:0,internalStdinConsumed:0});function ne(e=""){return{stdout:e,stderr:"",exitCode:0}}function _(e,t=1){return{stdout:"",stderr:e,exitCode:t}}function F(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function Se(e){return{stdout:"",stderr:"",exitCode:e?0:1,internalStdinConsumed:0}}function wn(e,t,n="",r=""){throw new C(e,t,n,r)}function qu(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new C(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors")}function Oo(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new tn;return se}if(t.length>1)throw new G(1,"",`bash: break: too many arguments
114
- `);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new G(128,"",`bash: break: ${t[0]}: numeric argument required
115
- `);n=r}throw new tt(n)}async function Do(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 o=t.slice(i);if(o.length===0||o[0]==="~"?n=e.state.env.get("HOME")||"/":o[0]==="-"?(n=e.state.previousDir,r=!0):n=o[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let f=e.state.env.get("CDPATH");if(f){let d=f.split(":").filter(h=>h);for(let h of d){let p=h.startsWith("/")?`${h}/${n}`:`${e.state.cwd}/${h}/${n}`;try{if((await e.fs.stat(p)).isDirectory){n=p,r=!0;break}}catch{}}}}let l=(n.startsWith("/")?n:`${e.state.cwd}/${n}`).split("/").filter(f=>f&&f!=="."),c="";for(let f of l)if(f==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await e.fs.stat(c)).isDirectory)return _(`bash: cd: ${n}: Not a directory
116
- `)}catch{return _(`bash: cd: ${n}: No such file or directory
117
- `)}}let u=c||"/";if(s)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,e.state.env.set("PWD",e.state.cwd),e.state.env.set("OLDPWD",e.state.previousDir),ne(r?`${u}
118
- `:"")}function Io(e,t){return e.fs.resolvePath(e.state.cwd,t)}var Jp=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function Bs(e){return Jp.includes(e)}async function Ws(e,t,n){let r=Io(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 em=["-nt","-ot","-ef"];function Vs(e){return em.includes(e)}async function zs(e,t,n,r){let s=Io(e,n),i=Io(e,r);switch(t){case"-nt":{let[o,a]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return o!==null&&(a===null||o.mtime>a.mtime)}case"-ot":{let[o,a]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return a!==null&&(o===null||o.mtime<a.mtime)}case"-ef":try{let[o,a]=await Promise.all([e.fs.realpath(s),e.fs.realpath(i)]);if(o===a)return!0;let[l,c]=await Promise.all([e.fs.stat(s),e.fs.stat(i)]);return l.dev!==void 0&&l.ino!==void 0&&c.dev!==void 0&&c.ino!==void 0?l.dev===c.dev&&l.ino===c.ino:l.identity&&c.identity?l.identity===c.identity:!1}catch{return!1}default:return!1}}var tm=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function Us(e){return tm.has(e)}function js(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 Ir(e){return e==="="||e==="=="||e==="!="}function qs(e,t,n,r=!1,s=!1,i=!1,o=256){if(r){let l=rr(t,n,s,i,o);return e==="!="?!l:l}if(s){let l=t.toLowerCase()===n.toLowerCase();return e==="!="?!l:l}let a=t===n;return e==="!="?!a:a}var nm=new Set(["-z","-n"]);function Gs(e){return nm.has(e)}function Hs(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function Zs(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 a=s;return(a.startsWith("'")&&a.endsWith("'")||a.startsWith('"')&&a.endsWith('"'))&&(a=a.slice(1,-1)),a=a.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,c)=>e.state.env.get(c)||""),cn(e,r,a)}let o;try{let a=new Q,l=oe(a,s);o=await ee(e,l.expression)}catch{if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else{let a=e.state.env.get(s);o=a?Number.parseInt(a,10):0}}if(o<0){let a=xe(e,r),l=e.state.currentLine;if(a.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${l}: ${r}: bad array subscript
118
+ `,0;a=h}let l=`${t.array}[${a}]`,c=le(e,t.array,a);if(c!==void 0)return Bs(e,l,c,r);if(a===0){let u=e.state.env.get(t.array);if(u!==void 0)return Bs(e,t.array,u,r)}if(e.state.options.nounset&&!(e.state.env.has(t.array)||Ie(e,t.array)))throw new Xe(`${t.array}[${a}]`);return 0}return 0}case"ArithDoubleSubscript":throw new ce("double subscript","","");case"ArithNumberSubscript":throw new ce(`${t.number}${t.errorToken}: syntax error: invalid arithmetic operator (error token is "${t.errorToken}")`);case"ArithSyntaxError":throw new ce(t.message,"","",!0);case"ArithSingleQuote":{if(n)throw new ce(`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),o=await s(t.right);return em(i,o,t.operator)}case"ArithUnary":{let i=await s(t.operand);if(t.operator==="++"||t.operator==="--"){if(t.operand.type==="ArithVariable"){let o=t.operand.name,a=Number.parseInt(await oe(e,o),10)||0,l=t.operator==="++"?a+1:a-1;return e.state.env.set(o,String(l)),t.prefix?l:a}if(t.operand.type==="ArithArrayElement"){let o=t.operand.array,a=e.state.associativeArrays?.has(o),l;if(t.operand.stringKey!==void 0)l=t.operand.stringKey;else if(a&&t.operand.index?.type==="ArithVariable"&&!t.operand.index.hasDollarPrefix)l=t.operand.index.name;else if(a&&t.operand.index?.type==="ArithVariable"&&t.operand.index.hasDollarPrefix)l=await oe(e,t.operand.index.name);else if(t.operand.index){let f=await s(t.operand.index);l=String(f)}else return i;let c=Number.parseInt(le(e,o,l)||"0",10)||0,u=t.operator==="++"?c+1:c-1;return G(e,o,l,String(u),a?"associative":"indexed"),t.prefix?u:c}if(t.operand.type==="ArithConcat"){let o="";for(let a of t.operand.parts)o+=await nr(e,a,n,r);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=Number.parseInt(e.state.env.get(o)||"0",10)||0,l=t.operator==="++"?a+1:a-1;return e.state.env.set(o,String(l)),t.prefix?l:a}}if(t.operand.type==="ArithDynamicElement"){let o="";if(t.operand.nameExpr.type==="ArithConcat")for(let a of t.operand.nameExpr.parts)o+=await nr(e,a,n,r);else t.operand.nameExpr.type==="ArithVariable"&&(o=t.operand.nameExpr.hasDollarPrefix?await oe(e,t.operand.nameExpr.name):t.operand.nameExpr.name);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=await s(t.operand.subscript),l=Number.parseInt(le(e,o,a)||"0",10)||0,c=t.operator==="++"?l+1:l-1;return G(e,o,a,String(c)),t.prefix?c:l}}return i}return tm(i,t.operator)}case"ArithTernary":return await s(t.condition)?await s(t.consequent):await s(t.alternate);case"ArithAssignment":{let i=t.variable,o=i,a;if(t.stringKey!==void 0)a=t.stringKey;else if(t.subscript){let d=e.state.associativeArrays?.has(i);if(d&&t.subscript.type==="ArithVariable"&&!t.subscript.hasDollarPrefix)a=t.subscript.name;else if(d&&t.subscript.type==="ArithVariable"&&t.subscript.hasDollarPrefix)a=await oe(e,t.subscript.name)||"\\";else if(d){let h=await s(t.subscript);a=String(h)}else{let h=await s(t.subscript);if(h<0){let p=K(e,i);p.length>0&&(h=Math.max(...p.map(([E])=>typeof E=="number"?E:0))+1+h)}a=String(h)}}let l=a===void 0?e.state.env.get(o):le(e,i,a),c=Number.parseInt(l||"0",10)||0,u=await s(t.value),f=ju(c,u,t.operator);return a===void 0?e.state.env.set(o,String(f)):G(e,i,a,String(f),e.state.associativeArrays?.has(i)?"associative":"indexed"),f}case"ArithGroup":return await s(t.expression);case"ArithConcat":{let i="";for(let o of t.parts)i+=await nr(e,o,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?await Io(e,i,r):Number.parseInt(i,10)||0}case"ArithDynamicAssignment":{let i="";if(t.target.type==="ArithConcat")for(let u of t.target.parts)i+=await nr(e,u,n,r);else t.target.type==="ArithVariable"&&(i=t.target.hasDollarPrefix?await oe(e,t.target.name):t.target.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=i;if(t.subscript){let u=await s(t.subscript);o=`${i}_${u}`}let a=Number.parseInt(e.state.env.get(o)||"0",10)||0,l=await s(t.value),c=ju(a,l,t.operator);return e.state.env.set(o,String(c)),c}case"ArithDynamicElement":{let i="";if(t.nameExpr.type==="ArithConcat")for(let c of t.nameExpr.parts)i+=await nr(e,c,n,r);else t.nameExpr.type==="ArithVariable"&&(i=t.nameExpr.hasDollarPrefix?await oe(e,t.nameExpr.name):t.nameExpr.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=await s(t.subscript),a=`${i}_${o}`,l=e.state.env.get(a);return l!==void 0?Bs(e,a,l,r):0}default:return 0}}async function nr(e,t,n=!1,r=qu()){switch(t.type){case"ArithNumber":return String(t.value);case"ArithSingleQuote":return String(await rr(e,t,n,r));case"ArithVariable":return t.hasDollarPrefix?await oe(e,t.name):t.name;case"ArithSpecialVar":return await oe(e,t.name);case"ArithBracedExpansion":return await Ws(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 nr(e,i,n,r);return s}default:return String(await rr(e,t,n,r))}}async function Hu(e,t){let n="",r=0;for(let k of t.parts){let A=k.type==="Literal"?k.value:"\0",$=B(A);if($>e.limits.maxStringLength-r)throw new C(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n+=A,r+=$}let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\+?=)\(/);if(!s||!n.endsWith(")"))return null;let i=s[1],o=s[2],a=[],l=[],c=!1,u="",f=0,d=0,h=!1,p=!0,m=k=>{let A=B(k);if(A>e.limits.maxStringLength-d-f)throw new C(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");u+=k,f+=A},E=(k,A=!1)=>{if(a.length>=e.limits.maxArrayElements)throw new C(`array assignment element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let $=B(k);if($>e.limits.maxStringLength-d)throw new C(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");a.push(k),l.push(A),d+=$},b=()=>{E(u,p),u="",f=0,h=!1,p=!0};for(let k of t.parts)if(k.type==="Literal"){let A=k.value;if(!c){let $=A.indexOf("=(");$!==-1&&(c=!0,A=A.slice($+2))}if(c){A.endsWith(")")&&(A=A.slice(0,-1));for(let $ of A)/\s/.test($)?(u||h)&&b():m($)}}else if(c)if(k.type==="BraceExpansion")if(/^\[.+\]=/.test(u))m(Xn({type:"Word",parts:[k]}));else{(u||h)&&b();let $=await Rt(e,{type:"Word",parts:[k]});for(let R of $.values)E(R)}else{(k.type==="SingleQuoted"||k.type==="DoubleQuoted"||k.type==="Escaped")&&(h=!0),p=!1;let A=await ie(e,{type:"Word",parts:[k]});m(A)}(u||h)&&b();let y=a.splice(0),g=l.splice(0);d=0;for(let k=0;k<y.length;k++){let A=y[k];if(!g[k]){E(A);continue}let $=A.match(/^(\[[^\]]+\]=)(.*)$/s);if($){let R=wn(e,$[2]);A=$[1]+R}if(A.includes("{")&&A.includes("}")){let R=new Q().parseWordFromString(A,!1,!1);if(R.parts.some(P=>P.type==="BraceExpansion")){let P=await Rt(e,R);for(let N of P.values)E(N);continue}}E(A)}let S=[`${i}${o}(`],v=B(S[0]);for(let k=0;k<a.length;k++){let A=a[k],$,R=A.match(/^(\[[^\]]+\]=)(.*)$/s);if(R){let I=R[2].replace(/\\/g,"\\\\").replace(/"/g,'\\"');$=`${R[1]}"${I}"`}else A===""?$="''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(A)&&!A.startsWith("'")&&!A.startsWith('"')?$=`'${A.replace(/'/g,"'\\''")}'`:$=A;let P=`${k>0?" ":""}${$}`,N=B(P);if(N+1>e.limits.maxStringLength-v)throw new C(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");S.push(P),v+=N}return S.push(")"),S.join("")}async function Gu(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 b=E.value.indexOf("+=");if(b!==-1){let g=E.value.slice(0,b);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)){n=m,r=b,s=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(g)){n=m,r=b,s=!0;break}}let y=E.value.indexOf("=");if(y!==-1&&(y===0||E.value[y-1]!=="+")){let g=E.value.slice(0,y);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(g)){n=m,r=y;break}}}}if(n===-1)return null;let i=t.parts.slice(0,n),o=t.parts[n];if(o.type!=="Literal")return null;let a=s?2:1,l=o.value.slice(0,r),c=o.value.slice(r+a),u=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:c!==""?[{type:"Literal",value:c},...u]:u},h=d.parts.length>0?await ie(e,d):"";return`${f}${s?"+=":"="}${h}`}var sm=["tar","yq","xan","sqlite3","python3","python"];function Zu(e){return sm.includes(e)}var ne=Object.freeze({stdout:"",stderr:"",exitCode:0,internalStdinConsumed:0});function te(e=""){return{stdout:e,stderr:"",exitCode:0}}function L(e,t=1){return{stdout:"",stderr:e,exitCode:t}}function F(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function Se(e){return{stdout:"",stderr:"",exitCode:e?0:1,internalStdinConsumed:0}}function bn(e,t,n="",r=""){throw new C(e,t,n,r)}function Qu(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new C(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors")}function To(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new nn;return ne}if(t.length>1)throw new H(1,"",`bash: break: too many arguments
119
+ `);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new H(128,"",`bash: break: ${t[0]}: numeric argument required
120
+ `);n=r}throw new nt(n)}async function _o(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 o=t.slice(i);if(o.length===0||o[0]==="~"?n=e.state.env.get("HOME")||"/":o[0]==="-"?(n=e.state.previousDir,r=!0):n=o[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let f=e.state.env.get("CDPATH");if(f){let d=f.split(":").filter(h=>h);for(let h of d){let p=h.startsWith("/")?`${h}/${n}`:`${e.state.cwd}/${h}/${n}`;try{if((await e.fs.stat(p)).isDirectory){n=p,r=!0;break}}catch{}}}}let l=(n.startsWith("/")?n:`${e.state.cwd}/${n}`).split("/").filter(f=>f&&f!=="."),c="";for(let f of l)if(f==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await e.fs.stat(c)).isDirectory)return L(`bash: cd: ${n}: Not a directory
121
+ `)}catch{return L(`bash: cd: ${n}: No such file or directory
122
+ `)}}let u=c||"/";if(s)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,e.state.env.set("PWD",e.state.cwd),e.state.env.set("OLDPWD",e.state.previousDir),te(r?`${u}
123
+ `:"")}function Lo(e,t){return e.fs.resolvePath(e.state.cwd,t)}var im=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function Vs(e){return im.includes(e)}async function zs(e,t,n){let r=Lo(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 om=["-nt","-ot","-ef"];function Us(e){return om.includes(e)}async function js(e,t,n,r){let s=Lo(e,n),i=Lo(e,r);switch(t){case"-nt":{let[o,a]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return o!==null&&(a===null||o.mtime>a.mtime)}case"-ot":{let[o,a]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return a!==null&&(o===null||o.mtime<a.mtime)}case"-ef":try{let[o,a]=await Promise.all([e.fs.realpath(s),e.fs.realpath(i)]);if(o===a)return!0;let[l,c]=await Promise.all([e.fs.stat(s),e.fs.stat(i)]);return l.dev!==void 0&&l.ino!==void 0&&c.dev!==void 0&&c.ino!==void 0?l.dev===c.dev&&l.ino===c.ino:l.identity&&c.identity?l.identity===c.identity:!1}catch{return!1}default:return!1}}var am=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function qs(e){return am.has(e)}function Hs(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 Lr(e){return e==="="||e==="=="||e==="!="}function Gs(e,t,n,r=!1,s=!1,i=!1,o=256){if(r){let l=sr(t,n,s,i,o);return e==="!="?!l:l}if(s){let l=t.toLowerCase()===n.toLowerCase();return e==="!="?!l:l}let a=t===n;return e==="!="?!a:a}var lm=new Set(["-z","-n"]);function Zs(e){return lm.has(e)}function Qs(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function Ks(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 a=s;return(a.startsWith("'")&&a.endsWith("'")||a.startsWith('"')&&a.endsWith('"'))&&(a=a.slice(1,-1)),a=a.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,c)=>e.state.env.get(c)||""),un(e,r,a)}let o;try{let a=new Q,l=se(a,s);o=await ee(e,l.expression)}catch{if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else{let a=e.state.env.get(s);o=a?Number.parseInt(a,10):0}}if(o<0){let a=xe(e,r),l=e.state.currentLine;if(a.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${l}: ${r}: bad array subscript
119
124
  `,!1;if(o=Math.max(...a)+1+o,o<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${l}: ${r}: bad array subscript
120
- `,!1}return cn(e,r,o)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Tt(e,t).length>0:xe(e,t).length>0}async function En(e,t){switch(t.type){case"CondBinary":{let n=await ae(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 ae(e,t.right);s=Jn(i)}else s=await Tu(e,t.right);else Ir(t.operator)&&!r?s=await _u(e,t.right):s=await ae(e,t.right);if(Ir(t.operator)){let i=e.state.shoptOptions.nocasematch;return qs(t.operator,n,s,!r,i,!0,e.limits.maxCallDepth)}if(Us(t.operator))return js(t.operator,await Hu(e,n),await Hu(e,s));if(Vs(t.operator))return zs(e,t.operator,n,s);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,o=am(s),l=ge(o,i?"i":"").match(n);if(be(e,"BASH_REMATCH"),l)for(let c=0;c<l.length;c++)H(e,"BASH_REMATCH",c,l[c]||"");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 ae(e,t.operand);return Bs(t.operator)?Ws(e,t.operator,n):Gs(t.operator)?Hs(t.operator,n):t.operator==="-v"?await Zs(e,n):t.operator==="-o"?_o(e,n):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await ae(e,t.operand.expression.word)})`!=="":!await En(e,t.operand);case"CondAnd":return await En(e,t.left)?await En(e,t.right):!1;case"CondOr":return await En(e,t.left)?!0:await En(e,t.right);case"CondGroup":return await En(e,t.expression);case"CondWord":return await ae(e,t.word)!=="";default:return!1}}async function sr(e,t){if(t.length===0)return F("","",1);if(t.length===1)return Se(!!t[0]);if(t.length===2){let r=t[0],s=t[1];return r==="("?_(`test: '(' without matching ')'
121
- `,2):Bs(r)?Se(await Ws(e,r,s)):Gs(r)?Se(Hs(r,s)):r==="!"?Se(!s):r==="-v"?Se(await Zs(e,s)):r==="-o"?Se(_o(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"?_(`test: ${r}: unary operator expected
122
- `,2):F("","",1)}if(t.length===3){let r=t[0],s=t[1],i=t[2];if(Ir(s))return Se(qs(s,r,i));if(Us(s)){let o=Qs(r),a=Qs(i);return!o.valid||!a.valid?F("","",2):Se(js(s,o.value,a.value))}if(Vs(s))return Se(await zs(e,s,r,i));switch(s){case"-a":return Se(r!==""&&i!=="");case"-o":return Se(r!==""||i!=="");case">":return Se(r>i);case"<":return Se(r<i)}if(r==="!"){let o=await sr(e,[s,i]);return F("",o.stderr,o.exitCode===0?1:o.exitCode===1?0:o.exitCode)}if(r==="("&&i===")")return Se(s!=="")}if(t.length===4){if(t[0]==="!"){let r=await sr(e,t.slice(1));return F("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return sr(e,[t[1],t[2]])}let n=await Qu(e,t,0);return n.pos<t.length?_(`test: too many arguments
123
- `,2):Se(n.value)}async function Qu(e,t,n){return rm(e,t,n)}async function rm(e,t,n){let{value:r,pos:s}=await Gu(e,t,n);for(;t[s]==="-o";){let i=await Gu(e,t,s+1);r=r||i.value,s=i.pos}return{value:r,pos:s}}async function Gu(e,t,n){let{value:r,pos:s}=await To(e,t,n);for(;t[s]==="-a";){let i=await To(e,t,s+1);r=r&&i.value,s=i.pos}return{value:r,pos:s}}async function To(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 To(e,t,n+1);return{value:!s,pos:i}}return sm(e,t,n)}finally{r.release()}}async function sm(e,t,n){let r=t[n];if(r==="("){let{value:i,pos:o}=await Qu(e,t,n+1);return{value:i,pos:t[o]===")"?o+1:o}}let s=t[n+1];if(Ir(s)){let i=r,o=t[n+2]??"";return{value:qs(s,i,o),pos:n+3}}if(Us(s)){let i=Qs(r),o=Qs(t[n+2]??"0");return!i.valid||!o.valid?{value:!1,pos:n+3}:{value:js(s,i.value,o.value),pos:n+3}}if(Vs(s)){let i=r,o=t[n+2]??"";return{value:await zs(e,s,i,o),pos:n+3}}if(Bs(r)){let i=t[n+1]??"";return{value:await Ws(e,r,i),pos:n+2}}if(Gs(r)){let i=t[n+1]??"";return{value:Hs(r,i),pos:n+2}}if(r==="-v"){let i=t[n+1]??"";return{value:await Zs(e,i),pos:n+2}}if(r==="-o"){let i=t[n+1]??"";return{value:_o(e,i),pos:n+2}}return{value:r!==void 0&&r!=="",pos:n+1}}function rr(e,t,n=!1,r=!1,s=256){r&&im(t,s);let i=`^${Ku(t,r)}$`;return ge(i,n?"is":"s").test(e)}function im(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 C(`extglob maximum depth (${t}) exceeded`,"recursion")}else e[s]===")"&&r.length>0&&r.pop()&&n--}}function Ku(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=Xu(e,r+1);if(i!==-1){let o=e.slice(r+2,i),a=Yu(o),l=a.map(u=>Ku(u,t)),c=l.length>0?l.join("|"):"(?:)";if(s==="@")n+=`(?:${c})`;else if(s==="*")n+=`(?:${c})*`;else if(s==="+")n+=`(?:${c})+`;else if(s==="?")n+=`(?:${c})?`;else if(s==="!")if(i<e.length-1){let f=a.map(h=>Ju(h,t));if(f.every(h=>h!==null)&&f.every(h=>h===f[0])&&f[0]!==null){let h=f[0];if(h===0)n+="(?:.+)";else{let p=[];h>0&&p.push(`.{0,${h-1}}`),p.push(`.{${h+1},}`),p.push(`(?!(?:${c})).{${h}}`),n+=`(?:${p.join("|")})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;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 Xu(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 Yu(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 Ju(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=Xu(e,r+1);if(i!==-1){if(s==="@"){let o=e.slice(r+2,i),l=Yu(o).map(c=>Ju(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===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 _o(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 Hu(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 Zu(t);try{let n=new Q,r=oe(n,t);return await ee(e,r.expression)}catch{return Zu(t)}}function om(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 Zu(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=om(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 Qs(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 am(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=lm(e,n);t+=r.converted,n=r.endIndex}else t+=e[n],n++;return t}function lm(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 o="",a=!1;for(;n<e.length;){let l=e[n];if(l==="]"){a=!0,n++;break}if(l==="["&&n+1<e.length&&e[n+1]===":"){let c=e.indexOf(":]",n+2);if(c!==-1){let u=e.slice(n+2,c);o+=cm(u),n=c+2;continue}}if(l==="["&&n+1<e.length){let c=e[n+1];if(c==="."||c==="="){let u=`${c}]`,f=e.indexOf(u,n+2);if(f!==-1){let d=e.slice(n+2,f);o+=d,n=f+2;continue}}}if(l==="\\"&&n+1<e.length){o+=l+e[n+1],n+=2;continue}o+=l,n++}return a?(s&&(r+="\\]"),i&&(r+="\\["),r+=o,r+="]",{converted:r,endIndex:n}):{converted:"\\[",endIndex:t+1}}function cm(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 Lo(e,t,n){if(n&&e.length>=n.maxElements)throw new C(`array element limit exceeded (${n.maxElements})`,"array_elements");e.push(t)}function Kt(e,t){if(t&&W(e)>t.maxStringBytes)throw new C(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,"string_length");let n=[],r="",s=!1,i=!1,o=!1,a=!1;for(let l of e){if(o){r+=l,o=!1,a=!0;continue}if(l==="\\"){o=!0;continue}if(l==="'"&&!i){s||(a=!0),s=!s;continue}if(l==='"'&&!s){i||(a=!0),i=!i;continue}if((l===" "||l===" "||l===`
124
- `)&&!s&&!i){a&&(Lo(n,r,t),r="",a=!1);continue}r+=l,a=!0}return a&&Lo(n,r,t),n}function Ks(e,t){if(t&&W(e)>t.maxStringBytes)throw new C(`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 o=e[r];for(r++;r<e.length&&e[r]!==o;)s+=e[r],r++;e[r]===o&&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 o=e[r];for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"&&r+1<e.length&&r++,i+=e[r],r++;e[r]===o&&r++}else for(;r<e.length&&!/\s/.test(e[r]);)i+=e[r],r++;Lo(n,[s,i],t)}return n}function ef(e,t){let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(n)return{name:n[1],isArray:!0,arrayElements:Kt(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 um(e,t){try{let n=new Q,r=oe(n,t);return await ee(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}async function tf(e,t,n={}){let{name:r,isArray:s,arrayElements:i,value:o,arrayIndex:a}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=n;if(c){let u=de(e,r);if(u)return u}if(s&&i){e.executionScope.consumeWork(i.length,"array assignment");let u=$e(e,r),f=u?je(u):void 0,d=e.state.env.get(r);try{be(e,r);for(let h=0;h<i.length;h++)H(e,r,h,i[h]);e.state.env.delete(r)}catch(h){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),h}}else if(a!==void 0&&o!==void 0){let u=await um(e,a);H(e,r,u,o)}else o!==void 0&&e.state.env.set(r,o);return l&&et(e,r),null}function bn(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function Fo(e,t){return e.state.localVarDepth?.get(t)}function Xs(e,t){e.state.localVarDepth?.delete(t)}function nf(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 Ys(e,t){let n=e.state.localVarStack?.get(t);if(!(!n||n.length===0))return n.pop()}function rf(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 Mo="__file__:",Bo="__file_append__:",zo="__rw__:",Wo="__dupout__:",Vo="__dupin__:",Ae=3;function fm(e){let t=e.slice(zo.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),o=t.slice(s+r+1),a=o.indexOf(":");if(a===-1)return null;let l=Number.parseInt(o.slice(0,a),10);return Number.isNaN(l)||l<0?null:{path:i,position:l,content:o.slice(a+1)}}function sf(e,t){let n=Number.parseInt(e.slice(t.length),10);return Number.isNaN(n)?null:n}function dm(e){if(e.startsWith(Mo))return{kind:"output",path:e.slice(Mo.length),append:!1};if(e.startsWith(Bo))return{kind:"output",path:e.slice(Bo.length),append:!0};if(e.startsWith(zo)){let t=fm(e);if(t)return{kind:"readwrite",...t}}if(e.startsWith(Wo)){let t=sf(e,Wo);if(t!==null)return{kind:"dup-out",sourceFd:t}}if(e.startsWith(Vo)){let t=sf(e,Vo);if(t!==null)return{kind:"dup-in",sourceFd:t}}return{kind:"input",content:e}}function Uo(e){switch(e.kind){case"input":return e.content;case"output":return`${e.append?Bo:Mo}${e.path}`;case"readwrite":return`${zo}${e.path.length}:${e.path}:${e.position}:${e.content}`;case"dup-out":return`${Wo}${e.sourceFd}`;case"dup-in":return`${Vo}${e.sourceFd}`;case"closed":throw new Error("Closed descriptors have no table encoding")}}function hm(e){return e.state.fileDescriptors??=new Map,e.state.fileDescriptors}function pm(e,t,n){n?(e.state.inputFds??=new Set,e.state.inputFds.add(t)):e.state.inputFds?.delete(t)}function ir(e,t){return e.state.fdAliases?.get(t)}function Sn(e,t){return[...ir(e,t)??[t]]}function of(e,t){let n=ir(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 jo(e,t,n){if(t===n)return;e.state.fdAliases??=new Map;let r=ir(e,n)??new Set([n]);r.add(t);for(let s of r)e.state.fdAliases.set(s,r)}function Js(e,t){return e.state.fileDescriptors?.get(t)}function lt(e,t){let n=Js(e,t);if(n!==void 0)return e.state.inputFds?.has(t)?{kind:"input",content:n}:dm(n)}function Wn(e,t){return e.state.fileDescriptors?.has(t)===!0}function qo(e,t,n,r){let s=hm(e);s.has(t)||qu(e),s.set(t,n),pm(e,t,r)}function ei(e,t,n,r=!1){of(e,t),qo(e,t,n,r)}function mt(e,t,n){ei(e,t,Uo(n),n.kind==="input")}function Bt(e,t){e.state.fileDescriptors?.delete(t),e.state.inputFds?.delete(t),of(e,t)}function ti(e,t,n){let r=Js(e,n);return r===void 0?!1:(ei(e,t,r,e.state.inputFds?.has(n)===!0),jo(e,t,n),!0)}function Go(e,t,n){let r=Js(e,n);if(r===void 0)return!1;if(t===n)return!0;let s=e.state.inputFds?.has(n)===!0,i=[...ir(e,n)??[]].filter(a=>a!==n);Bt(e,n),ei(e,t,r,s);let o=i.find(a=>Wn(e,a));return o!==void 0&&jo(e,t,o),!0}function ni(e,t){let n=lt(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 An(e,t,n){let r=lt(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=Uo(s),o=s.kind==="input";for(let a of ir(e,t)??[t])qo(e,a,i,o)}async function Ho(e,t,n,r,s){if(t.kind==="output")return await e.fs.appendFile(t.path,r,s),!0;let o=n.map(u=>lt(e,u)).find(u=>u?.kind==="readwrite")??t;if(o.kind!=="readwrite")return!1;let a=o.content.slice(0,o.position)+r+o.content.slice(o.position+r.length),l={...o,position:o.position+r.length,content:a};await e.fs.writeFile(o.path,a,s);let c=Uo(l);for(let u of n)Wn(e,u)&&qo(e,u,c,!1);return!0}function vn(e,t,n){if(t.has(n))return;let r=ir(e,n);t.set(n,{raw:Js(e,n),isInput:e.state.inputFds?.has(n)===!0,aliases:r?[...r].filter(s=>s!==n):[]})}function ri(e,t){let n=e.state.fileDescriptors;if(n)for(let[r,{raw:s,isInput:i,aliases:o}]of t){if(s===void 0){Bt(e,r);continue}ei(e,r,s,i);let a=o.find(l=>n.has(l));a!==void 0&&jo(e,r,a)}}function Zo(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 af(e){if(e.fdVariable)return!1;let t=Zo(e);return t!==null&&t>=Ae}async function mm(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
125
+ `,!1}return un(e,r,o)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Lt(e,t).length>0:xe(e,t).length>0}async function Sn(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=er(i)}else s=await Mu(e,t.right);else Lr(t.operator)&&!r?s=await Bu(e,t.right):s=await ie(e,t.right);if(Lr(t.operator)){let i=e.state.shoptOptions.nocasematch;return Gs(t.operator,n,s,!r,i,!0,e.limits.maxCallDepth)}if(qs(t.operator))return Hs(t.operator,await Xu(e,n),await Xu(e,s));if(Us(t.operator))return js(e,t.operator,n,s);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,o=hm(s),l=ge(o,i?"i":"").match(n);if(be(e,"BASH_REMATCH"),l)for(let c=0;c<l.length;c++)G(e,"BASH_REMATCH",c,l[c]||"");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 Vs(t.operator)?zs(e,t.operator,n):Zs(t.operator)?Qs(t.operator,n):t.operator==="-v"?await Ks(e,n):t.operator==="-o"?Mo(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 Sn(e,t.operand);case"CondAnd":return await Sn(e,t.left)?await Sn(e,t.right):!1;case"CondOr":return await Sn(e,t.left)?!0:await Sn(e,t.right);case"CondGroup":return await Sn(e,t.expression);case"CondWord":return await ie(e,t.word)!=="";default:return!1}}async function ir(e,t){if(t.length===0)return F("","",1);if(t.length===1)return Se(!!t[0]);if(t.length===2){let r=t[0],s=t[1];return r==="("?L(`test: '(' without matching ')'
126
+ `,2):Vs(r)?Se(await zs(e,r,s)):Zs(r)?Se(Qs(r,s)):r==="!"?Se(!s):r==="-v"?Se(await Ks(e,s)):r==="-o"?Se(Mo(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
127
+ `,2):F("","",1)}if(t.length===3){let r=t[0],s=t[1],i=t[2];if(Lr(s))return Se(Gs(s,r,i));if(qs(s)){let o=Xs(r),a=Xs(i);return!o.valid||!a.valid?F("","",2):Se(Hs(s,o.value,a.value))}if(Us(s))return Se(await js(e,s,r,i));switch(s){case"-a":return Se(r!==""&&i!=="");case"-o":return Se(r!==""||i!=="");case">":return Se(r>i);case"<":return Se(r<i)}if(r==="!"){let o=await ir(e,[s,i]);return F("",o.stderr,o.exitCode===0?1:o.exitCode===1?0:o.exitCode)}if(r==="("&&i===")")return Se(s!=="")}if(t.length===4){if(t[0]==="!"){let r=await ir(e,t.slice(1));return F("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return ir(e,[t[1],t[2]])}let n=await Ju(e,t,0);return n.pos<t.length?L(`test: too many arguments
128
+ `,2):Se(n.value)}async function Ju(e,t,n){return cm(e,t,n)}async function cm(e,t,n){let{value:r,pos:s}=await Ku(e,t,n);for(;t[s]==="-o";){let i=await Ku(e,t,s+1);r=r||i.value,s=i.pos}return{value:r,pos:s}}async function Ku(e,t,n){let{value:r,pos:s}=await Fo(e,t,n);for(;t[s]==="-a";){let i=await Fo(e,t,s+1);r=r&&i.value,s=i.pos}return{value:r,pos:s}}async function Fo(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 Fo(e,t,n+1);return{value:!s,pos:i}}return um(e,t,n)}finally{r.release()}}async function um(e,t,n){let r=t[n];if(r==="("){let{value:i,pos:o}=await Ju(e,t,n+1);return{value:i,pos:t[o]===")"?o+1:o}}let s=t[n+1];if(Lr(s)){let i=r,o=t[n+2]??"";return{value:Gs(s,i,o),pos:n+3}}if(qs(s)){let i=Xs(r),o=Xs(t[n+2]??"0");return!i.valid||!o.valid?{value:!1,pos:n+3}:{value:Hs(s,i.value,o.value),pos:n+3}}if(Us(s)){let i=r,o=t[n+2]??"";return{value:await js(e,s,i,o),pos:n+3}}if(Vs(r)){let i=t[n+1]??"";return{value:await zs(e,r,i),pos:n+2}}if(Zs(r)){let i=t[n+1]??"";return{value:Qs(r,i),pos:n+2}}if(r==="-v"){let i=t[n+1]??"";return{value:await Ks(e,i),pos:n+2}}if(r==="-o"){let i=t[n+1]??"";return{value:Mo(e,i),pos:n+2}}return{value:r!==void 0&&r!=="",pos:n+1}}function sr(e,t,n=!1,r=!1,s=256){r&&fm(t,s);let i=`^${ef(t,r)}$`;return ge(i,n?"is":"s").test(e)}function fm(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 C(`extglob maximum depth (${t}) exceeded`,"recursion")}else e[s]===")"&&r.length>0&&r.pop()&&n--}}function ef(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=tf(e,r+1);if(i!==-1){let o=e.slice(r+2,i),a=nf(o),l=a.map(u=>ef(u,t)),c=l.length>0?l.join("|"):"(?:)";if(s==="@")n+=`(?:${c})`;else if(s==="*")n+=`(?:${c})*`;else if(s==="+")n+=`(?:${c})+`;else if(s==="?")n+=`(?:${c})?`;else if(s==="!")if(i<e.length-1){let f=a.map(h=>rf(h,t));if(f.every(h=>h!==null)&&f.every(h=>h===f[0])&&f[0]!==null){let h=f[0];if(h===0)n+="(?:.+)";else{let p=[];h>0&&p.push(`.{0,${h-1}}`),p.push(`.{${h+1},}`),p.push(`(?!(?:${c})).{${h}}`),n+=`(?:${p.join("|")})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;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 tf(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 nf(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 rf(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=tf(e,r+1);if(i!==-1){if(s==="@"){let o=e.slice(r+2,i),l=nf(o).map(c=>rf(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===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 Mo(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 Xu(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 Yu(t);try{let n=new Q,r=se(n,t);return await ee(e,r.expression)}catch{return Yu(t)}}function dm(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 Yu(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=dm(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 Xs(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 hm(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=pm(e,n);t+=r.converted,n=r.endIndex}else t+=e[n],n++;return t}function pm(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 o="",a=!1;for(;n<e.length;){let l=e[n];if(l==="]"){a=!0,n++;break}if(l==="["&&n+1<e.length&&e[n+1]===":"){let c=e.indexOf(":]",n+2);if(c!==-1){let u=e.slice(n+2,c);o+=mm(u),n=c+2;continue}}if(l==="["&&n+1<e.length){let c=e[n+1];if(c==="."||c==="="){let u=`${c}]`,f=e.indexOf(u,n+2);if(f!==-1){let d=e.slice(n+2,f);o+=d,n=f+2;continue}}}if(l==="\\"&&n+1<e.length){o+=l+e[n+1],n+=2;continue}o+=l,n++}return a?(s&&(r+="\\]"),i&&(r+="\\["),r+=o,r+="]",{converted:r,endIndex:n}):{converted:"\\[",endIndex:t+1}}function mm(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 Bo(e,t,n){if(n&&e.length>=n.maxElements)throw new C(`array element limit exceeded (${n.maxElements})`,"array_elements");e.push(t)}function Xt(e,t){if(t&&B(e)>t.maxStringBytes)throw new C(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,"string_length");let n=[],r="",s=!1,i=!1,o=!1,a=!1;for(let l of e){if(o){r+=l,o=!1,a=!0;continue}if(l==="\\"){o=!0;continue}if(l==="'"&&!i){s||(a=!0),s=!s;continue}if(l==='"'&&!s){i||(a=!0),i=!i;continue}if((l===" "||l===" "||l===`
129
+ `)&&!s&&!i){a&&(Bo(n,r,t),r="",a=!1);continue}r+=l,a=!0}return a&&Bo(n,r,t),n}function Ys(e,t){if(t&&B(e)>t.maxStringBytes)throw new C(`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 o=e[r];for(r++;r<e.length&&e[r]!==o;)s+=e[r],r++;e[r]===o&&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 o=e[r];for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"&&r+1<e.length&&r++,i+=e[r],r++;e[r]===o&&r++}else for(;r<e.length&&!/\s/.test(e[r]);)i+=e[r],r++;Bo(n,[s,i],t)}return n}function sf(e,t){let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(n)return{name:n[1],isArray:!0,arrayElements:Xt(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 ym(e,t){try{let n=new Q,r=se(n,t);return await ee(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}async function of(e,t,n={}){let{name:r,isArray:s,arrayElements:i,value:o,arrayIndex:a}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=n;if(c){let u=de(e,r);if(u)return u}if(s&&i){e.executionScope.consumeWork(i.length,"array assignment");let u=$e(e,r),f=u?qe(u):void 0,d=e.state.env.get(r);try{be(e,r);for(let h=0;h<i.length;h++)G(e,r,h,i[h]);e.state.env.delete(r)}catch(h){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),h}}else if(a!==void 0&&o!==void 0){let u=await ym(e,a);G(e,r,u,o)}else o!==void 0&&e.state.env.set(r,o);return l&&tt(e,r),null}function An(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function Wo(e,t){return e.state.localVarDepth?.get(t)}function Js(e,t){e.state.localVarDepth?.delete(t)}function af(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 ei(e,t){let n=e.state.localVarStack?.get(t);if(!(!n||n.length===0))return n.pop()}function lf(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 Vo="__file__:",zo="__file_append__:",qo="__rw__:",Uo="__dupout__:",jo="__dupin__:",Ae=3;function gm(e){let t=e.slice(qo.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),o=t.slice(s+r+1),a=o.indexOf(":");if(a===-1)return null;let l=Number.parseInt(o.slice(0,a),10);return Number.isNaN(l)||l<0?null:{path:i,position:l,content:o.slice(a+1)}}function cf(e,t){let n=Number.parseInt(e.slice(t.length),10);return Number.isNaN(n)?null:n}function wm(e){if(e.startsWith(Vo))return{kind:"output",path:e.slice(Vo.length),append:!1};if(e.startsWith(zo))return{kind:"output",path:e.slice(zo.length),append:!0};if(e.startsWith(qo)){let t=gm(e);if(t)return{kind:"readwrite",...t}}if(e.startsWith(Uo)){let t=cf(e,Uo);if(t!==null)return{kind:"dup-out",sourceFd:t}}if(e.startsWith(jo)){let t=cf(e,jo);if(t!==null)return{kind:"dup-in",sourceFd:t}}return{kind:"input",content:e}}function Ho(e){switch(e.kind){case"input":return e.content;case"output":return`${e.append?zo:Vo}${e.path}`;case"readwrite":return`${qo}${e.path.length}:${e.path}:${e.position}:${e.content}`;case"dup-out":return`${Uo}${e.sourceFd}`;case"dup-in":return`${jo}${e.sourceFd}`;case"closed":throw new Error("Closed descriptors have no table encoding")}}function Em(e){return e.state.fileDescriptors??=new Map,e.state.fileDescriptors}function bm(e,t,n){n?(e.state.inputFds??=new Set,e.state.inputFds.add(t)):e.state.inputFds?.delete(t)}function or(e,t){return e.state.fdAliases?.get(t)}function vn(e,t){return[...or(e,t)??[t]]}function uf(e,t){let n=or(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 Go(e,t,n){if(t===n)return;e.state.fdAliases??=new Map;let r=or(e,n)??new Set([n]);r.add(t);for(let s of r)e.state.fdAliases.set(s,r)}function ti(e,t){return e.state.fileDescriptors?.get(t)}function ut(e,t){let n=ti(e,t);if(n!==void 0)return e.state.inputFds?.has(t)?{kind:"input",content:n}:wm(n)}function zn(e,t){return e.state.fileDescriptors?.has(t)===!0}function Zo(e,t,n,r){let s=Em(e);s.has(t)||Qu(e),s.set(t,n),bm(e,t,r)}function ni(e,t,n,r=!1){uf(e,t),Zo(e,t,n,r)}function gt(e,t,n){ni(e,t,Ho(n),n.kind==="input")}function Vt(e,t){e.state.fileDescriptors?.delete(t),e.state.inputFds?.delete(t),uf(e,t)}function ri(e,t,n){let r=ti(e,n);return r===void 0?!1:(ni(e,t,r,e.state.inputFds?.has(n)===!0),Go(e,t,n),!0)}function Qo(e,t,n){let r=ti(e,n);if(r===void 0)return!1;if(t===n)return!0;let s=e.state.inputFds?.has(n)===!0,i=[...or(e,n)??[]].filter(a=>a!==n);Vt(e,n),ni(e,t,r,s);let o=i.find(a=>zn(e,a));return o!==void 0&&Go(e,t,o),!0}function si(e,t){let n=ut(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 kn(e,t,n){let r=ut(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=Ho(s),o=s.kind==="input";for(let a of or(e,t)??[t])Zo(e,a,i,o)}async function Ko(e,t,n,r,s){if(t.kind==="output")return await e.fs.appendFile(t.path,r,s),!0;let o=n.map(u=>ut(e,u)).find(u=>u?.kind==="readwrite")??t;if(o.kind!=="readwrite")return!1;let a=o.content.slice(0,o.position)+r+o.content.slice(o.position+r.length),l={...o,position:o.position+r.length,content:a};await e.fs.writeFile(o.path,a,s);let c=Ho(l);for(let u of n)zn(e,u)&&Zo(e,u,c,!1);return!0}function xn(e,t,n){if(t.has(n))return;let r=or(e,n);t.set(n,{raw:ti(e,n),isInput:e.state.inputFds?.has(n)===!0,aliases:r?[...r].filter(s=>s!==n):[]})}function ii(e,t){let n=e.state.fileDescriptors;if(n)for(let[r,{raw:s,isInput:i,aliases:o}]of t){if(s===void 0){Vt(e,r);continue}ni(e,r,s,i);let a=o.find(l=>n.has(l));a!==void 0&&Go(e,r,a)}}function Xo(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 ff(e){if(e.fdVariable)return!1;let t=Xo(e);return t!==null&&t>=Ae}async function Sm(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
125
130
  `;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&n!=="/dev/null")return`bash: ${n}: cannot overwrite existing file
126
131
  `}catch{return`bash: ${n}: cannot open redirect target
127
- `}return null}function lf(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 Tr="scoped",uf="bare",ff="persistent",ym=e=>new C(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors"),gm=(e,t)=>Wn(e,t)||(e.state.fileDescriptors?.size??0)<e.limits.maxFileDescriptors,cf=e=>{let t=Math.max(e.state.nextFd??10,10);for(;Wn(e,t);)t+=1;return t},si=e=>{let t=e.endsWith("-"),n=t?e.slice(0,-1):e;return/^\d+$/.test(n)?{sourceFd:Number.parseInt(n,10),move:t}:null},wm=(e,t,n)=>{let r=lt(e,t);return t<Ae?r?{kind:"entry",entry:r,descriptors:Sn(e,t)}:{kind:"standard",fd:t}:r?n?r.kind==="input"||r.kind==="readwrite"||r.kind==="dup-in"?{kind:"entry",entry:r,descriptors:Sn(e,t)}:null:r.kind==="output"||r.kind==="readwrite"||r.kind==="dup-out"?{kind:"entry",entry:r,descriptors:Sn(e,t)}:null:null};async function or(e,t,n,r,s=!0){let i=e.fs.resolvePath(e.state.cwd,t),o=await mm(e,i,t,{checkNoclobber:!n,isClobber:r});if(o)return{error:F("",o,1)};if(t==="/dev/full")return{error:F("",`bash: /dev/full: No space left on device
128
- `,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(a){if(!s)throw a;return{error:F("",`bash: ${t}: cannot open redirect target
129
- `,1)}}return{entry:{kind:"output",path:i,append:n}}}async function Qo(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:F("",`bash: ${t}: No such file or directory
132
+ `}return null}function df(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 Fr="scoped",pf="bare",mf="persistent",Am=e=>new C(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors"),vm=(e,t)=>zn(e,t)||(e.state.fileDescriptors?.size??0)<e.limits.maxFileDescriptors,hf=e=>{let t=Math.max(e.state.nextFd??10,10);for(;zn(e,t);)t+=1;return t},oi=e=>{let t=e.endsWith("-"),n=t?e.slice(0,-1):e;return/^\d+$/.test(n)?{sourceFd:Number.parseInt(n,10),move:t}:null},km=(e,t,n)=>{let r=ut(e,t);return t<Ae?r?{kind:"entry",entry:r,descriptors:vn(e,t)}:{kind:"standard",fd:t}:r?n?r.kind==="input"||r.kind==="readwrite"||r.kind==="dup-in"?{kind:"entry",entry:r,descriptors:vn(e,t)}:null:r.kind==="output"||r.kind==="readwrite"||r.kind==="dup-out"?{kind:"entry",entry:r,descriptors:vn(e,t)}:null:null};async function ar(e,t,n,r){let s=e.fs.resolvePath(e.state.cwd,t),i=await Sm(e,s,t,{checkNoclobber:!n,isClobber:r});if(i)return{error:F("",i,1)};if(t==="/dev/full")return{error:F("",`bash: /dev/full: No space left on device
133
+ `,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(s,"","binary"):await e.fs.writeFile(s,"","binary")}catch(o){let a="cannot open redirect target";return De(o,"EROFS")?a="Read-only file system":De(o,"EACCES")?a="Permission denied":De(o,"ENOENT")?a="No such file or directory":De(o,"EISDIR")&&(a="Is a directory"),{error:F("",`bash: ${t}: ${a}
134
+ `,1)}}return{entry:{kind:"output",path:s,append:n}}}async function Yo(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:F("",`bash: ${t}: No such file or directory
130
135
  `,1)};try{return await e.fs.writeFile(r,"","binary"),{entry:{kind:"readwrite",path:r,position:0,content:""}}}catch{return{error:F("",`bash: ${t}: No such file or directory
131
- `,1)}}}}var Em=async(e,t)=>{let n=await ae(e,t.content);return t.stripTabs?n.split(`
136
+ `,1)}}}}var xm=async(e,t)=>{let n=await ie(e,t.content);return t.stripTabs?n.split(`
132
137
  `).map(r=>r.replace(/^\t+/,"")).join(`
133
- `):n};async function bm(e,t,n,r){let s=new Map,i=new Map,o=(g,y)=>e.state.closedStandardFds?.has(g)?{kind:"closed"}:lt(e,g)??y,a=new Map([[0,o(0,{kind:"dup-in",sourceFd:0})],[1,o(1,{kind:"dup-out",sourceFd:1})],[2,o(2,{kind:"dup-out",sourceFd:2})]]),l=r.numericSnapshot,c,u=-1,f=a.get(0);f?.kind==="input"?(c=f.content,u=0):f?.kind==="readwrite"&&(c=f.content.slice(f.position),u=0);let d=()=>({targets:s,dupSources:i,standardRoutes:a,stdin:c,stdinSourceFd:u,error:null}),h=async(g,y,b)=>{let A={...d(),error:await kn(e,g,t.slice(0,y),s,i,a)};return b?{...A,errorCause:b}:A},p=async(g,y)=>{if(gm(e,g))return null;let b=ym(e);return h(F("",b.stderr,C.EXIT_CODE),y,b)},m=(g,y)=>{g!==null&&g<Ae&&a.set(g,y),r.policy==="persistent"&&g!==null&&g<Ae&&(e.state.closedStandardFds?.delete(g),mt(e,g,y))},E=(g,y)=>{a.set(g,y),vn(e,r.standardSnapshot,g),r.standardClosedSnapshot.has(g)||r.standardClosedSnapshot.set(g,e.state.closedStandardFds?.has(g)===!0),e.state.closedStandardFds?.delete(g),mt(e,g,y)},S=(g,y)=>{if(g<Ae){let b=a.get(g);return b?.kind==="closed"?null:b?{kind:"entry",entry:b,descriptors:Sn(e,g)}:{kind:"standard",fd:g}}return wm(e,g,y)};for(let g=0;g<t.length;g++){let y=t[g],b=Zo(y);if(y.target.type==="HereDoc"){let v=await Em(e,y.target);if(y.fdVariable){try{de(e,y.fdVariable)}catch(P){if(!(P instanceof G))throw P;return h(F(P.stdout,P.stderr,P.exitCode),g,P)}let $=cf(e),O=await p($,g);if(O)return O;vn(e,r.fdVariableSnapshot,$),r.fdVariableEnv.has(y.fdVariable)||r.fdVariableEnv.set(y.fdVariable,e.state.env.get(y.fdVariable)),mt(e,$,{kind:"input",content:v}),e.state.env.set(y.fdVariable,String($)),e.state.nextFd=$+1}else if(b!==null&&b>=Ae){let $=await p(b,g);if($)return $;vn(e,l,b),mt(e,b,{kind:"input",content:v})}else if(b===0||b===null)c=Yt(v),u=-1,m(b,{kind:"input",content:c});else{let $={kind:"input",content:v};r.policy==="persistent"?m(b,$):E(b,$)}continue}let A,k=y.operator===">&"||y.operator==="<&";if(k){if(Co(e,y.target))return h(F("",`bash: $@: ambiguous redirect
134
- `,1),g);A=await ae(e,y.target)}else if(y.operator==="<<<")A=await ae(e,y.target);else{let v=await Bu(e,y.target);if("error"in v)return h(F("",v.error,1),g);A=v.target}if(s.set(g,A),A.includes("\0"))return h(F("",`bash: ${A.replace(/\0/g,"")}: No such file or directory
135
- `,1),g);if(y.fdVariable){try{de(e,y.fdVariable)}catch(D){if(!(D instanceof G))throw D;return h(F(D.stdout,D.stderr,D.exitCode),g,D)}if(k&&A==="-"){let D=Number.parseInt(e.state.env.get(y.fdVariable)??"",10);Number.isNaN(D)||(vn(e,r.fdVariableSnapshot,D),Bt(e,D));continue}let v=cf(e),$=k?si(A):null;if($&&!S($.sourceFd,y.operator==="<&"))return h(F("",`bash: ${$.sourceFd}: Bad file descriptor
136
- `,1),g);if(!($?.move===!0&&$.sourceFd>=Ae)){let D=await p(v,g);if(D)return D}vn(e,r.fdVariableSnapshot,v),r.fdVariableEnv.has(y.fdVariable)||r.fdVariableEnv.set(y.fdVariable,e.state.env.get(y.fdVariable));let P,N;if(k){let D=$;if(D){let V=S(D.sourceFd,y.operator==="<&");if(!V)return h(F("",`bash: ${D.sourceFd}: Bad file descriptor
137
- `,1),g);N=D,V.kind==="standard"?P={kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:V.fd}:D.sourceFd<Ae&&(P=V.entry)}else{if(y.operator==="<&")return h(F("",`bash: ${A}: ambiguous redirect
138
- `,1),g);let V=await or(e,A,!1,!1);if(V.error)return h(V.error,g);P=V.entry}}else if(y.operator===">"||y.operator===">|"||y.operator===">>"||y.operator==="&>"||y.operator==="&>>"){let D=y.operator===">>"||y.operator==="&>>",V=await or(e,A,D,y.operator===">|");if(V.error)return h(V.error,g);P=V.entry}else if(y.operator==="<<<")P={kind:"input",content:`${A}
139
- `};else if(y.operator==="<"||y.operator==="<>"){let D=await Qo(e,A,y.operator==="<>");if(D.error)return h(D.error,g);P=D.entry}if(N&&N.sourceFd>=Ae){if(!(N.move?Go(e,v,N.sourceFd):ti(e,v,N.sourceFd)))return h(F("",`bash: ${N.sourceFd}: Bad file descriptor
140
- `,1),g)}else P&&mt(e,v,P);N?.move&&N.sourceFd!==v&&N.sourceFd<Ae&&Bt(e,N.sourceFd),e.state.env.set(y.fdVariable,String(v)),e.state.nextFd=v+1;continue}if(af(y)){let v=b;if(k&&A==="-"){vn(e,l,v),Bt(e,v);continue}let $=k?si(A):null;if($&&!S($.sourceFd,y.operator==="<&"))return h(F("",`bash: ${$.sourceFd}: Bad file descriptor
141
- `,1),g);if(!($?.move===!0&&$.sourceFd>=Ae)){let P=await p(v,g);if(P)return P}if(vn(e,l,v),k){let P=$;if(!P){if(y.operator==="<&")return h(F("",`bash: ${A}: ambiguous redirect
142
- `,1),g);let D=await or(e,A,!1,!1);if(D.error)return h(D.error,g);mt(e,v,D.entry);continue}let N=S(P.sourceFd,y.operator==="<&");if(!N)return h(F("",`bash: ${P.sourceFd}: Bad file descriptor
143
- `,1),g);if(N.kind==="standard")mt(e,v,{kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:N.fd});else if(P.sourceFd<Ae)mt(e,v,N.entry);else if(!(P.move?Go(e,v,P.sourceFd):ti(e,v,P.sourceFd)))return h(F("",`bash: ${P.sourceFd}: Bad file descriptor
144
- `,1),g);P.move&&P.sourceFd!==v&&P.sourceFd<Ae&&Bt(e,P.sourceFd);continue}if(y.operator===">"||y.operator===">|"||y.operator===">>"){let P=await or(e,A,y.operator===">>",y.operator===">|");if(P.error)return h(P.error,g);mt(e,v,P.entry)}else if(y.operator==="<<<")mt(e,v,{kind:"input",content:`${A}
145
- `});else if(y.operator==="<"||y.operator==="<>"){let P=await Qo(e,A,y.operator==="<>");if(P.error)return h(P.error,g);mt(e,v,P.entry)}continue}if(k){if(A==="-"){b===0&&(c="",u=-1),b!==null&&b<Ae&&(a.set(b,{kind:"closed"}),r.policy==="persistent"&&(Bt(e,b),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(b)));continue}let v=si(A);if(!v){if(y.operator==="<&")return h(F("",`bash: ${A}: ambiguous redirect
146
- `,1),g);let O=await or(e,A,!1,!1,!1);if(O.error)return h(O.error,g);let P=O.entry;i.set(g,{kind:"entry",entry:P,descriptors:[]}),y.fd==null?(m(1,P),m(2,P)):m(b,P);continue}let $=S(v.sourceFd,y.operator==="<&");if(!$)return h(F("",`bash: ${v.sourceFd}: Bad file descriptor
147
- `,1),g);if(i.set(g,$),$.kind==="entry"&&r.policy==="persistent"&&b!==null&&b<Ae&&v.sourceFd>=Ae){if(!ti(e,b,v.sourceFd))return h(F("",`bash: ${v.sourceFd}: Bad file descriptor
148
- `,1),g);a.set(b,lt(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")c=$.fd===0?n:"",u=-1;else if($.entry.kind==="input"||$.entry.kind==="readwrite"){let O=v.sourceFd<Ae&&!Wn(e,v.sourceFd)?{content:$.entry.kind==="input"?$.entry.content:$.entry.content.slice($.entry.position)}:ni(e,v.sourceFd);if("error"in O)return h(F("",`bash: ${v.sourceFd}: Bad file descriptor
149
- `,1),g);c=O.content,u=Wn(e,v.sourceFd)?v.sourceFd:-1}else c=n,u=-1;v.move&&(v.sourceFd>=Ae?Bt(e,v.sourceFd):(a.set(v.sourceFd,{kind:"closed"}),r.policy==="persistent"&&(Bt(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 or(e,A,y.operator===">>"||y.operator==="&>>",y.operator===">|",!1);if(v.error)return h(v.error,g);let $=v.entry;y.operator==="&>"||y.operator==="&>>"?(m(1,$),m(2,$)):m(b,$);continue}if(y.operator==="<<<")c=Yt(`${A}
150
- `),u=-1,m(b,{kind:"input",content:c});else if(y.operator==="<"){let v=e.fs.resolvePath(e.state.cwd,A);try{c=await Gn(e.fs,v),u=-1,m(b,{kind:"input",content:c})}catch{return h(F("",`bash: ${A}: No such file or directory
151
- `,1),g)}}else if(y.operator==="<>"){let v=await Qo(e,A,!0);if(v.error)return h(v.error,g);let $=v.entry;m(b,$),b===0&&$.kind==="readwrite"&&(c=$.content,u=-1)}}return d()}function ar(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="")=>bm(e,t,i,r),finish:()=>{if(!s){if(s=!0,n!=="persistent"&&ri(e,r.numericSnapshot),n!=="persistent"){ri(e,r.standardSnapshot);for(let[i,o]of r.standardClosedSnapshot)o?(e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(i)):e.state.closedStandardFds?.delete(i)}if(n==="bare"){ri(e,r.fdVariableSnapshot);for(let[i,o]of r.fdVariableEnv)o===void 0?e.state.env.delete(i):e.state.env.set(i,o);e.state.nextFd=r.nextFd}}}}}function lr(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 Ko(e,t,n,r){let s=t instanceof G||t instanceof We||t instanceof Qe?t.exitCode:t instanceof C?C.EXIT_CODE:0,i=await kn(e,F(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:W(i.stdout),stderr:W(i.stderr)}}async function ct(e,t,n,r){let s=ar(e,t,Tr),i;try{if(i=await s.prepare(n),i.error)return lr(i);let o=e.state.groupStdin,a=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 kn(e,l,t,i.targets,i.dupSources,i.standardRoutes)}finally{i.stdin!==void 0&&(e.state.groupStdin=o,e.state.groupStdinSourceFd=a)}}catch(o){throw!(o instanceof Jt)||!i||await Ko(e,o,t,i),o}finally{s.finish()}}async function kn(e,t,n,r,s=new Map,i=new Map,o="bash",a=!1){n.length>0&&(t=e.executionScope.accountResult(t,"redirection"));let{stdout:l,stderr:c,exitCode:u}=t,d=t.stdoutKind==="bytes"||t.stdoutKind===void 0&&t.stdoutEncoding==="binary"?"binary":"utf8",h=b=>d,p={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?p:b.fd===2?m:null},S=b=>{let A=i.get(b)??lt(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:Sn(e,b)}}:null:null};p=S(1)??p,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=p);break}if(k==="/dev/stderr"){v===1&&(p=m);break}if(k==="/dev/full"){c+=`bash: echo: write error: No space left on device
152
- `,u=1,v===1&&(l="");break}if(k==="/dev/null"&&v===2){m={kind:"discard"};break}let O=e.fs.resolvePath(e.state.cwd,k);v===1?p={kind:"file",path:O,append:$}:m={kind:"file",path:O,append:$};break}case">&":case"<&":{let v=A.fd??(A.operator==="<&"?0:1);if(v>=Ae||v===0)break;if(k==="-"){v===1?p={kind:"discard"}:m={kind:"discard"};break}let $=E(s.get(b));if(!$)break;A.fd==null&&si(k)===null?(p=$,m=$):v===1?p=$:v===2&&(m=$);break}case"&>":{p={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!1},m=p;break}case"&>>":{p={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!0},m=p;break}}}if(l!==""||c!==""){let b=l,A=c;l="",c="",p.kind==="invalid-output"&&b!==""&&(b="",A+=`${a?"":"bash: "}${o}: write error: Bad file descriptor
153
- `,u=1),m.kind==="invalid-output"&&(A="");let k=async(v,$,O)=>{v.append?await e.fs.appendFile(v.path,$,O):await e.fs.writeFile(v.path,$,O)};if(p===m&&(p.kind==="file"||p.kind==="descriptor")){let v=b+A;v!==""&&(p.kind==="file"?await k(p,v,h(v)):await Ho(e,p.source.entry,p.source.descriptors,v,h(v)))}else for(let[v,$,O]of[[b,p,!0],[A,m,!1]])if(v!=="")switch($.kind){case"live-stdout":l+=v;break;case"live-stderr":c+=v;break;case"file":await k($,v,O?h(v):lf(v));break;case"descriptor":await Ho(e,$.source.entry,$.source.descriptors,v,O?h(v):lf(v));break;case"invalid-output":break;case"discard":break}}let g=F(l,c,u);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=W(g.stdout),k=W(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 df(e,t){if(e.state.options.posix&&Ar.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
154
- `;throw new G(2,"",r)}let n={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,n),se}async function ii(e,t,n,r="",s,i=!1){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,wn(`${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 o=new Map,a=Number.parseInt(e.state.env.get("#")??"0",10),l=Math.max(n.length,a);for(let h=0;h<l;h++){let p=String(h+1);o.set(p,e.state.env.get(p)),h<n.length?e.state.env.set(p,n[h]):e.state.env.delete(p)}o.set("@",e.state.env.get("@")),o.set("#",e.state.env.get("#")),e.state.env.set("@",n.join(" ")),e.state.env.set("#",String(n.length));let c=!1,u=()=>{if(c)return;c=!0;let h=e.state.localScopes.length-1,p=e.state.localScopes.pop(),m=e.state.localArrayScopes?.pop();if(p)for(let[E,S]of p)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,je(S)),e.state.associativeArrays??=new Set,S.kind==="associative"?e.state.associativeArrays.add(E):e.state.associativeArrays.delete(E))}if(rf(e,h),e.state.fullyUnsetLocals)for(let[E,S]of e.state.fullyUnsetLocals.entries())S===h&&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 o)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=ar(e,t.redirections,Tr);try{if(f=await d.prepare(r),f.error)return lr(f);let h=f.stdin??r,p=i||f.stdin!==void 0||r!=="",m=await e.executeCommand(t.body,h,p);return kn(e,m,t.redirections,f.targets,f.dupSources,f.standardRoutes)}catch(h){if(h instanceof Jt&&f&&(await Ko(e,h,t.redirections,f),h instanceof We))return F(h.stdout,h.stderr,h.exitCode);throw h}finally{d.finish(),u()}}function Wt(e,t,n,r){let s=n+W(t)+1;if(s>r)throw new C(`shopt: output size limit exceeded (${r} bytes)`,"output_size");return e.push(t),s}var ai=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],hf=["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"],pf=[...ai,...hf];function oi(e){return ai.includes(e)}function Sm(e){return hf.includes(e)}function mf(e,t){let n=e.limits.maxArrayElements;if(t.length>n)throw new C(`shopt: argument limit exceeded (${n})`,"array_elements");let r=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),s=!1,i=!1,o=!1,a=!1,l=!1,c=[],u=0;for(;u<t.length;){let E=t[u];if(E==="--"){u++;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":o=!0;break;case"q":a=!0;break;case"o":l=!0;break;default:return{exitCode:2,stdout:"",stderr:`shopt: -${g}: invalid option
155
- `}}}u++}else break}for(;u<t.length;)c.push(t[u]),u++;if(l)return Am(e,c,s,i,o,a);if(s&&i)return{exitCode:1,stdout:"",stderr:`shopt: cannot set and unset shell options simultaneously
156
- `};if(c.length===0){if(s||i){let S=[];for(let g of ai){let y=e.state.shoptOptions[g];s&&y?S.push(o?`shopt -s ${g}`:`${g} on`):i&&!y&&S.push(o?`shopt -u ${g}`:`${g} off`)}return{exitCode:0,stdout:S.length>0?`${S.join(`
138
+ `):n};async function Pm(e,t,n,r){let s=new Map,i=new Map,o=(y,g)=>e.state.closedStandardFds?.has(y)?{kind:"closed"}:ut(e,y)??g,a=new Map([[0,o(0,{kind:"dup-in",sourceFd:0})],[1,o(1,{kind:"dup-out",sourceFd:1})],[2,o(2,{kind:"dup-out",sourceFd:2})]]),l=r.numericSnapshot,c,u=-1,f=a.get(0);f?.kind==="input"?(c=f.content,u=0):f?.kind==="readwrite"&&(c=f.content.slice(f.position),u=0);let d=()=>({targets:s,dupSources:i,standardRoutes:a,stdin:c,stdinSourceFd:u,error:null}),h=async(y,g,S)=>{let v={...d(),error:await Pn(e,y,t.slice(0,g),s,i,a)};return S?{...v,errorCause:S}:v},p=async(y,g)=>{if(vm(e,y))return null;let S=Am(e);return h(F("",S.stderr,C.EXIT_CODE),g,S)},m=(y,g)=>{y!==null&&y<Ae&&a.set(y,g),r.policy==="persistent"&&y!==null&&y<Ae&&(e.state.closedStandardFds?.delete(y),gt(e,y,g))},E=(y,g)=>{a.set(y,g),xn(e,r.standardSnapshot,y),r.standardClosedSnapshot.has(y)||r.standardClosedSnapshot.set(y,e.state.closedStandardFds?.has(y)===!0),e.state.closedStandardFds?.delete(y),gt(e,y,g)},b=(y,g)=>{if(y<Ae){let S=a.get(y);return S?.kind==="closed"?null:S?{kind:"entry",entry:S,descriptors:vn(e,y)}:{kind:"standard",fd:y}}return km(e,y,g)};for(let y=0;y<t.length;y++){let g=t[y],S=Xo(g);if(g.target.type==="HereDoc"){let A=await xm(e,g.target);if(g.fdVariable){try{de(e,g.fdVariable)}catch(P){if(!(P instanceof H))throw P;return h(F(P.stdout,P.stderr,P.exitCode),y,P)}let $=hf(e),R=await p($,y);if(R)return R;xn(e,r.fdVariableSnapshot,$),r.fdVariableEnv.has(g.fdVariable)||r.fdVariableEnv.set(g.fdVariable,e.state.env.get(g.fdVariable)),gt(e,$,{kind:"input",content:A}),e.state.env.set(g.fdVariable,String($)),e.state.nextFd=$+1}else if(S!==null&&S>=Ae){let $=await p(S,y);if($)return $;xn(e,l,S),gt(e,S,{kind:"input",content:A})}else if(S===0||S===null)c=Jt(A),u=-1,m(S,{kind:"input",content:c});else{let $={kind:"input",content:A};r.policy==="persistent"?m(S,$):E(S,$)}continue}let v,k=g.operator===">&"||g.operator==="<&";if(k){if(Oo(e,g.target))return h(F("",`bash: $@: ambiguous redirect
139
+ `,1),y);v=await ie(e,g.target)}else if(g.operator==="<<<")v=await ie(e,g.target);else{let A=await Uu(e,g.target);if("error"in A)return h(F("",A.error,1),y);v=A.target}if(s.set(y,v),v.includes("\0"))return h(F("",`bash: ${v.replace(/\0/g,"")}: No such file or directory
140
+ `,1),y);if(g.fdVariable){try{de(e,g.fdVariable)}catch(I){if(!(I instanceof H))throw I;return h(F(I.stdout,I.stderr,I.exitCode),y,I)}if(k&&v==="-"){let I=Number.parseInt(e.state.env.get(g.fdVariable)??"",10);Number.isNaN(I)||(xn(e,r.fdVariableSnapshot,I),Vt(e,I));continue}let A=hf(e),$=k?oi(v):null;if($&&!b($.sourceFd,g.operator==="<&"))return h(F("",`bash: ${$.sourceFd}: Bad file descriptor
141
+ `,1),y);if(!($?.move===!0&&$.sourceFd>=Ae)){let I=await p(A,y);if(I)return I}xn(e,r.fdVariableSnapshot,A),r.fdVariableEnv.has(g.fdVariable)||r.fdVariableEnv.set(g.fdVariable,e.state.env.get(g.fdVariable));let P,N;if(k){let I=$;if(I){let z=b(I.sourceFd,g.operator==="<&");if(!z)return h(F("",`bash: ${I.sourceFd}: Bad file descriptor
142
+ `,1),y);N=I,z.kind==="standard"?P={kind:g.operator==="<&"?"dup-in":"dup-out",sourceFd:z.fd}:I.sourceFd<Ae&&(P=z.entry)}else{if(g.operator==="<&")return h(F("",`bash: ${v}: ambiguous redirect
143
+ `,1),y);let z=await ar(e,v,!1,!1);if(z.error)return h(z.error,y);P=z.entry}}else if(g.operator===">"||g.operator===">|"||g.operator===">>"||g.operator==="&>"||g.operator==="&>>"){let I=g.operator===">>"||g.operator==="&>>",z=await ar(e,v,I,g.operator===">|");if(z.error)return h(z.error,y);P=z.entry}else if(g.operator==="<<<")P={kind:"input",content:`${v}
144
+ `};else if(g.operator==="<"||g.operator==="<>"){let I=await Yo(e,v,g.operator==="<>");if(I.error)return h(I.error,y);P=I.entry}if(N&&N.sourceFd>=Ae){if(!(N.move?Qo(e,A,N.sourceFd):ri(e,A,N.sourceFd)))return h(F("",`bash: ${N.sourceFd}: Bad file descriptor
145
+ `,1),y)}else P&&gt(e,A,P);N?.move&&N.sourceFd!==A&&N.sourceFd<Ae&&Vt(e,N.sourceFd),e.state.env.set(g.fdVariable,String(A)),e.state.nextFd=A+1;continue}if(ff(g)){let A=S;if(k&&v==="-"){xn(e,l,A),Vt(e,A);continue}let $=k?oi(v):null;if($&&!b($.sourceFd,g.operator==="<&"))return h(F("",`bash: ${$.sourceFd}: Bad file descriptor
146
+ `,1),y);if(!($?.move===!0&&$.sourceFd>=Ae)){let P=await p(A,y);if(P)return P}if(xn(e,l,A),k){let P=$;if(!P){if(g.operator==="<&")return h(F("",`bash: ${v}: ambiguous redirect
147
+ `,1),y);let I=await ar(e,v,!1,!1);if(I.error)return h(I.error,y);gt(e,A,I.entry);continue}let N=b(P.sourceFd,g.operator==="<&");if(!N)return h(F("",`bash: ${P.sourceFd}: Bad file descriptor
148
+ `,1),y);if(N.kind==="standard")gt(e,A,{kind:g.operator==="<&"?"dup-in":"dup-out",sourceFd:N.fd});else if(P.sourceFd<Ae)gt(e,A,N.entry);else if(!(P.move?Qo(e,A,P.sourceFd):ri(e,A,P.sourceFd)))return h(F("",`bash: ${P.sourceFd}: Bad file descriptor
149
+ `,1),y);P.move&&P.sourceFd!==A&&P.sourceFd<Ae&&Vt(e,P.sourceFd);continue}if(g.operator===">"||g.operator===">|"||g.operator===">>"){let P=await ar(e,v,g.operator===">>",g.operator===">|");if(P.error)return h(P.error,y);gt(e,A,P.entry)}else if(g.operator==="<<<")gt(e,A,{kind:"input",content:`${v}
150
+ `});else if(g.operator==="<"||g.operator==="<>"){let P=await Yo(e,v,g.operator==="<>");if(P.error)return h(P.error,y);gt(e,A,P.entry)}continue}if(k){if(v==="-"){S===0&&(c="",u=-1),S!==null&&S<Ae&&(a.set(S,{kind:"closed"}),r.policy==="persistent"&&(Vt(e,S),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(S)));continue}let A=oi(v);if(!A){if(g.operator==="<&")return h(F("",`bash: ${v}: ambiguous redirect
151
+ `,1),y);let R=await ar(e,v,!1,!1);if(R.error)return h(R.error,y);let P=R.entry;i.set(y,{kind:"entry",entry:P,descriptors:[]}),g.fd==null?(m(1,P),m(2,P)):m(S,P);continue}let $=b(A.sourceFd,g.operator==="<&");if(!$)return h(F("",`bash: ${A.sourceFd}: Bad file descriptor
152
+ `,1),y);if(i.set(y,$),$.kind==="entry"&&r.policy==="persistent"&&S!==null&&S<Ae&&A.sourceFd>=Ae){if(!ri(e,S,A.sourceFd))return h(F("",`bash: ${A.sourceFd}: Bad file descriptor
153
+ `,1),y);a.set(S,ut(e,S)),e.state.closedStandardFds?.delete(S)}else $.kind==="standard"?m(S,{kind:g.operator==="<&"?"dup-in":"dup-out",sourceFd:$.fd}):m(S,$.entry);if(g.operator==="<&"&&S===0)if($.kind==="standard")c=$.fd===0?n:"",u=-1;else if($.entry.kind==="input"||$.entry.kind==="readwrite"){let R=A.sourceFd<Ae&&!zn(e,A.sourceFd)?{content:$.entry.kind==="input"?$.entry.content:$.entry.content.slice($.entry.position)}:si(e,A.sourceFd);if("error"in R)return h(F("",`bash: ${A.sourceFd}: Bad file descriptor
154
+ `,1),y);c=R.content,u=zn(e,A.sourceFd)?A.sourceFd:-1}else c=n,u=-1;A.move&&(A.sourceFd>=Ae?Vt(e,A.sourceFd):(a.set(A.sourceFd,{kind:"closed"}),r.policy==="persistent"&&(Vt(e,A.sourceFd),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(A.sourceFd))));continue}if(g.operator===">"||g.operator===">|"||g.operator===">>"||g.operator==="&>"||g.operator==="&>>"){let A=await ar(e,v,g.operator===">>"||g.operator==="&>>",g.operator===">|");if(A.error)return h(A.error,y);let $=A.entry;g.operator==="&>"||g.operator==="&>>"?(m(1,$),m(2,$)):m(S,$);continue}if(g.operator==="<<<")c=Jt(`${v}
155
+ `),u=-1,m(S,{kind:"input",content:c});else if(g.operator==="<"){let A=e.fs.resolvePath(e.state.cwd,v);try{c=await Zn(e.fs,A),u=-1,m(S,{kind:"input",content:c})}catch{return h(F("",`bash: ${v}: No such file or directory
156
+ `,1),y)}}else if(g.operator==="<>"){let A=await Yo(e,v,!0);if(A.error)return h(A.error,y);let $=A.entry;m(S,$),S===0&&$.kind==="readwrite"&&(c=$.content,u=-1)}}return d()}function lr(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="")=>Pm(e,t,i,r),finish:()=>{if(!s){if(s=!0,n!=="persistent"&&ii(e,r.numericSnapshot),n!=="persistent"){ii(e,r.standardSnapshot);for(let[i,o]of r.standardClosedSnapshot)o?(e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(i)):e.state.closedStandardFds?.delete(i)}if(n==="bare"){ii(e,r.fdVariableSnapshot);for(let[i,o]of r.fdVariableEnv)o===void 0?e.state.env.delete(i):e.state.env.set(i,o);e.state.nextFd=r.nextFd}}}}}function cr(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 Jo(e,t,n,r){let s=t instanceof H||t instanceof Ve||t instanceof Ke?t.exitCode:t instanceof C?C.EXIT_CODE:0,i=await Pn(e,F(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 ft(e,t,n,r){let s=lr(e,t,Fr),i;try{if(i=await s.prepare(n),i.error)return cr(i);let o=e.state.groupStdin,a=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 Pn(e,l,t,i.targets,i.dupSources,i.standardRoutes)}finally{i.stdin!==void 0&&(e.state.groupStdin=o,e.state.groupStdinSourceFd=a)}}catch(o){throw!(o instanceof en)||!i||await Jo(e,o,t,i),o}finally{s.finish()}}async function Pn(e,t,n,r,s=new Map,i=new Map,o="bash",a=!1){n.length>0&&(t=e.executionScope.accountResult(t,"redirection"));let{stdout:l,stderr:c,exitCode:u}=t,d=t.stdoutKind==="bytes"||t.stdoutKind===void 0&&t.stdoutEncoding==="binary"?"binary":"utf8",h=S=>d,p={kind:"live-stdout"},m={kind:"live-stderr"},E=S=>{if(!S)return null;if(S.kind==="entry"){if(S.entry.kind==="dup-out"){if(S.entry.sourceFd===1)return{kind:"live-stdout"};if(S.entry.sourceFd===2)return{kind:"live-stderr"}}return S.entry.kind==="output"||S.entry.kind==="readwrite"?{kind:"descriptor",source:S}:null}return S.fd===1?p:S.fd===2?m:null},b=S=>{let v=i.get(S)??ut(e,S);return v?v.kind==="closed"?{kind:"invalid-output",fd:S}:v.kind==="input"||v.kind==="dup-in"?{kind:"invalid-output",fd:S}:v.kind==="dup-out"?v.sourceFd===1?{kind:"live-stdout"}:v.sourceFd===2?{kind:"live-stderr"}:null:v.kind==="output"||v.kind==="readwrite"?{kind:"descriptor",source:{kind:"entry",entry:v,descriptors:vn(e,S)}}:null:null};p=b(1)??p,m=b(2)??m;for(let S=0;S<n.length;S++){let v=n[S];if(v.target.type==="HereDoc"||v.fdVariable)continue;let k=r.get(S);if(k!==void 0)switch(v.operator){case">":case">|":case">>":{let A=v.fd??1;if(A!==1&&A!==2)break;let $=v.operator===">>";if(k==="/dev/stdout"){A===2&&(m=p);break}if(k==="/dev/stderr"){A===1&&(p=m);break}if(k==="/dev/full"){c+=`bash: echo: write error: No space left on device
157
+ `,u=1,A===1&&(l="");break}if(k==="/dev/null"&&A===2){m={kind:"discard"};break}let R=e.fs.resolvePath(e.state.cwd,k);A===1?p={kind:"file",path:R,append:$}:m={kind:"file",path:R,append:$};break}case">&":case"<&":{let A=v.fd??(v.operator==="<&"?0:1);if(A>=Ae||A===0)break;if(k==="-"){A===1?p={kind:"discard"}:m={kind:"discard"};break}let $=E(s.get(S));if(!$)break;v.fd==null&&oi(k)===null?(p=$,m=$):A===1?p=$:A===2&&(m=$);break}case"&>":{p={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!1},m=p;break}case"&>>":{p={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!0},m=p;break}}}if(l!==""||c!==""){let S=l,v=c;l="",c="",p.kind==="invalid-output"&&S!==""&&(S="",v+=`${a?"":"bash: "}${o}: write error: Bad file descriptor
158
+ `,u=1),m.kind==="invalid-output"&&(v="");let k=async(A,$,R)=>{A.append?await e.fs.appendFile(A.path,$,R):await e.fs.writeFile(A.path,$,R)};if(p===m&&(p.kind==="file"||p.kind==="descriptor")){let A=S+v;A!==""&&(p.kind==="file"?await k(p,A,h(A)):await Ko(e,p.source.entry,p.source.descriptors,A,h(A)))}else for(let[A,$,R]of[[S,p,!0],[v,m,!1]])if(A!=="")switch($.kind){case"live-stdout":l+=A;break;case"live-stderr":c+=A;break;case"file":await k($,A,R?h(A):df(A));break;case"descriptor":await Ko(e,$.source.entry,$.source.descriptors,A,R?h(A):df(A));break;case"invalid-output":break;case"discard":break}}let y=F(l,c,u);if(t.stdoutKind&&(y.stdoutKind=t.stdoutKind),t.stdoutEncoding==="binary"&&(y.stdoutEncoding="binary"),t.internalPipeStatusOverride&&(y.internalPipeStatusOverride=t.internalPipeStatusOverride),n.length>0||e.state.fileDescriptors?.has(1)===!0||e.state.fileDescriptors?.has(2)===!0){let S=(t.internalOutputAccounting?.stdout??0)+(t.internalOutputAccounting?.stderr??0),v=B(y.stdout),k=B(y.stderr),A=Math.min(v,S);y.internalOutputAccounting={stdout:A,stderr:Math.min(k,S-A)},e.executionScope.accountResult(y,"redirection")}else t.internalOutputAccounting&&(y.internalOutputAccounting=t.internalOutputAccounting);return y}function yf(e,t){if(e.state.options.posix&&xr.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
159
+ `;throw new H(2,"",r)}let n={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,n),ne}async function ai(e,t,n,r="",s,i=!1){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,bn(`${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 o=new Map,a=Number.parseInt(e.state.env.get("#")??"0",10),l=Math.max(n.length,a);for(let h=0;h<l;h++){let p=String(h+1);o.set(p,e.state.env.get(p)),h<n.length?e.state.env.set(p,n[h]):e.state.env.delete(p)}o.set("@",e.state.env.get("@")),o.set("#",e.state.env.get("#")),e.state.env.set("@",n.join(" ")),e.state.env.set("#",String(n.length));let c=!1,u=()=>{if(c)return;c=!0;let h=e.state.localScopes.length-1,p=e.state.localScopes.pop(),m=e.state.localArrayScopes?.pop();if(p)for(let[E,b]of p)b===void 0?e.state.env.delete(E):e.state.env.set(E,b);if(m){e.state.arrays??=new Map;for(let[E,b]of m)b===void 0?(e.state.arrays.delete(E),e.state.associativeArrays?.delete(E)):(e.state.arrays.set(E,qe(b)),e.state.associativeArrays??=new Set,b.kind==="associative"?e.state.associativeArrays.add(E):e.state.associativeArrays.delete(E))}if(lf(e,h),e.state.fullyUnsetLocals)for(let[E,b]of e.state.fullyUnsetLocals.entries())b===h&&e.state.fullyUnsetLocals.delete(E);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let E=e.state.localExportedVars.pop();if(E)for(let b of E)e.state.exportedVars?.delete(b)}for(let[E,b]of o)b===void 0?e.state.env.delete(E):e.state.env.set(E,b);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},f=null,d=lr(e,t.redirections,Fr);try{if(f=await d.prepare(r),f.error)return cr(f);let h=f.stdin??r,p=i||f.stdin!==void 0||r!=="",m=await e.executeCommand(t.body,h,p);return Pn(e,m,t.redirections,f.targets,f.dupSources,f.standardRoutes)}catch(h){if(h instanceof en&&f&&(await Jo(e,h,t.redirections,f),h instanceof Ve))return F(h.stdout,h.stderr,h.exitCode);throw h}finally{d.finish(),u()}}function zt(e,t,n,r){let s=n+B(t)+1;if(s>r)throw new C(`shopt: output size limit exceeded (${r} bytes)`,"output_size");return e.push(t),s}var ci=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],gf=["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"],wf=[...ci,...gf];function li(e){return ci.includes(e)}function $m(e){return gf.includes(e)}function Ef(e,t){let n=e.limits.maxArrayElements;if(t.length>n)throw new C(`shopt: argument limit exceeded (${n})`,"array_elements");let r=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),s=!1,i=!1,o=!1,a=!1,l=!1,c=[],u=0;for(;u<t.length;){let E=t[u];if(E==="--"){u++;break}if(E.startsWith("-")&&E.length>1){for(let b=1;b<E.length;b++){let y=E[b];switch(y){case"s":s=!0;break;case"u":i=!0;break;case"p":o=!0;break;case"q":a=!0;break;case"o":l=!0;break;default:return{exitCode:2,stdout:"",stderr:`shopt: -${y}: invalid option
160
+ `}}}u++}else break}for(;u<t.length;)c.push(t[u]),u++;if(l)return Cm(e,c,s,i,o,a);if(s&&i)return{exitCode:1,stdout:"",stderr:`shopt: cannot set and unset shell options simultaneously
161
+ `};if(c.length===0){if(s||i){let b=[];for(let y of ci){let g=e.state.shoptOptions[y];s&&g?b.push(o?`shopt -s ${y}`:`${y} on`):i&&!g&&b.push(o?`shopt -u ${y}`:`${y} off`)}return{exitCode:0,stdout:b.length>0?`${b.join(`
157
162
  `)}
158
- `:"",stderr:""}}let E=[];for(let S of ai){let g=e.state.shoptOptions[S];E.push(o?`shopt ${g?"-s":"-u"} ${S}`:`${S} ${g?"on":"off"}`)}return{exitCode:0,stdout:`${E.join(`
163
+ `:"",stderr:""}}let E=[];for(let b of ci){let y=e.state.shoptOptions[b];E.push(o?`shopt ${y?"-s":"-u"} ${b}`:`${b} ${y?"on":"off"}`)}return{exitCode:0,stdout:`${E.join(`
159
164
  `)}
160
- `,stderr:""}}let f=!1,d=[],h=0,p=[],m=0;for(let E of c){if(!oi(E)&&!Sm(E)){h=Wt(d,`shopt: ${E}: invalid shell option name`,h,r),f=!0;continue}if(s)oi(E)&&(e.state.shoptOptions[E]=!0,Vi(e));else if(i)oi(E)&&(e.state.shoptOptions[E]=!1,Vi(e));else if(oi(E)){let S=e.state.shoptOptions[E];a?S||(f=!0):o?(m=Wt(p,`shopt ${S?"-s":"-u"} ${E}`,m,r),S||(f=!0)):(m=Wt(p,`${E} ${S?"on":"off"}`,m,r),S||(f=!0))}else a?f=!0:o?(m=Wt(p,`shopt -u ${E}`,m,r),f=!0):(m=Wt(p,`${E} off`,m,r),f=!0)}return{exitCode:f?1:0,stdout:p.length>0?`${p.join(`
165
+ `,stderr:""}}let f=!1,d=[],h=0,p=[],m=0;for(let E of c){if(!li(E)&&!$m(E)){h=zt(d,`shopt: ${E}: invalid shell option name`,h,r),f=!0;continue}if(s)li(E)&&(e.state.shoptOptions[E]=!0,zi(e));else if(i)li(E)&&(e.state.shoptOptions[E]=!1,zi(e));else if(li(E)){let b=e.state.shoptOptions[E];a?b||(f=!0):o?(m=zt(p,`shopt ${b?"-s":"-u"} ${E}`,m,r),b||(f=!0)):(m=zt(p,`${E} ${b?"on":"off"}`,m,r),b||(f=!0))}else a?f=!0:o?(m=zt(p,`shopt -u ${E}`,m,r),f=!0):(m=zt(p,`${E} off`,m,r),f=!0)}return{exitCode:f?1:0,stdout:p.length>0?`${p.join(`
161
166
  `)}
162
167
  `:"",stderr:d.length>0?`${d.join(`
163
168
  `)}
164
- `:""}}function Am(e,t,n,r,s,i){let o=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),a=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),l=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],c=[...a.keys(),...l].sort();if(t.length===0){let m=[];for(let E of c){let S=l.includes(E),g=a.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(`
169
+ `:""}}function Cm(e,t,n,r,s,i){let o=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),a=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),l=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],c=[...a.keys(),...l].sort();if(t.length===0){let m=[];for(let E of c){let b=l.includes(E),y=a.get(E),g=b||!y?!1:e.state.options[y];n&&!g||r&&g||m.push(s?`set ${g?"-o":"+o"} ${E}`:`${E} ${g?"on":"off"}`)}return{exitCode:0,stdout:m.length>0?`${m.join(`
165
170
  `)}
166
- `:"",stderr:""}}let u=!1,f=[],d=0,h=[],p=0;for(let m of t){let E=a.has(m),S=l.includes(m);if(!E&&!S){d=Wt(f,`shopt: ${m}: invalid option name`,d,o),u=!0;continue}if(S){n||r||(i?u=!0:s?(p=Wt(h,`set +o ${m}`,p,o),u=!0):(p=Wt(h,`${m} off`,p,o),u=!0));continue}let g=a.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,Xn(e);else if(r)e.state.options[g]=!1,Xn(e);else{let y=e.state.options[g];i?y||(u=!0):s?(p=Wt(h,`set ${y?"-o":"+o"} ${m}`,p,o),y||(u=!0)):(p=Wt(h,`${m} ${y?"on":"off"}`,p,o),y||(u=!0))}}return{exitCode:u?1:0,stdout:h.length>0?`${h.join(`
171
+ `:"",stderr:""}}let u=!1,f=[],d=0,h=[],p=0;for(let m of t){let E=a.has(m),b=l.includes(m);if(!E&&!b){d=zt(f,`shopt: ${m}: invalid option name`,d,o),u=!0;continue}if(b){n||r||(i?u=!0:s?(p=zt(h,`set +o ${m}`,p,o),u=!0):(p=zt(h,`${m} off`,p,o),u=!0));continue}let y=a.get(m);if(y)if(n)y==="vi"?e.state.options.emacs=!1:y==="emacs"&&(e.state.options.vi=!1),e.state.options[y]=!0,Yn(e);else if(r)e.state.options[y]=!1,Yn(e);else{let g=e.state.options[y];i?g||(u=!0):s?(p=zt(h,`set ${g?"-o":"+o"} ${m}`,p,o),g||(u=!0)):(p=zt(h,`${m} ${g?"on":"off"}`,p,o),g||(u=!0))}}return{exitCode:u?1:0,stdout:h.length>0?`${h.join(`
167
172
  `)}
168
173
  `:"",stderr:f.length>0?`${f.join(`
169
174
  `)}
170
- `:""}}var gf=e=>e.type==="Escaped"?M.literal(`\\${e.value}`):e.type==="DoubleQuoted"?{...e,parts:e.parts.map(gf)}:e,wf=vr,Jo=Dt,vm=pf,km=Jo;async function ea(e,t){let n=[],r=null,s="",i="",o=null,a=!1,l=!1,c=!1,u=null,f=null,d=null,h=[],p=["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 _(`compgen: -A: option requires an argument
171
- `,2);let $=t[k];if(!p.includes($))return _(`compgen: ${$}: invalid action name
172
- `,2);n.push($)}else if(v==="-W"){if(k++,k>=t.length)return _(`compgen: -W: option requires an argument
173
- `,2);r=t[k]}else if(v==="-P"){if(k++,k>=t.length)return _(`compgen: -P: option requires an argument
174
- `,2);s=t[k]}else if(v==="-S"){if(k++,k>=t.length)return _(`compgen: -S: option requires an argument
175
- `,2);i=t[k]}else if(v==="-o"){if(k++,k>=t.length)return _(`compgen: -o: option requires an argument
176
- `,2);let $=t[k];if($==="plusdirs")a=!0;else if($==="dirnames")l=!0;else if($==="default")c=!0;else if(!($==="filenames"||$==="nospace"||$==="bashdefault"||$==="noquote"))return _(`compgen: ${$}: invalid option name
177
- `,2)}else if(v==="-F"){if(k++,k>=t.length)return _(`compgen: -F: option requires an argument
178
- `,2);f=t[k]}else if(v==="-C"){if(k++,k>=t.length)return _(`compgen: -C: option requires an argument
179
- `,2);d=t[k]}else if(v==="-X"){if(k++,k>=t.length)return _(`compgen: -X: option requires an argument
180
- `,2);u=t[k]}else if(v==="-G"){if(k++,k>=t.length)return _(`compgen: -G: option requires an argument
181
- `,2)}else if(v==="--"){h.push(...t.slice(k+1));break}else v.startsWith("-")||h.push(v)}o=h[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 C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(W(v)>e.limits.maxStringLength)throw new C(`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 Xo(e,o,S());g(k)}if(c){let k=await yf(e,o,S());g(k)}for(let k of n)if(k==="variable"){let v=xm(e,o,S());g(v)}else if(k==="export"){let v=Pm(e,o,S());g(v)}else if(k==="function"){let v=$m(e,o,S());g(v)}else if(k==="builtin"){let v=Cm(e,o,S());g(v)}else if(k==="keyword"){let v=Nm(e,o,S());g(v)}else if(k==="alias"){let v=Rm(e,o,S());g(v)}else if(k==="shopt"){let v=Om(e,o,S());g(v)}else if(k==="helptopic"){let v=Dm(e,o,S());g(v)}else if(k==="directory"){let v=await Xo(e,o,S());g(v)}else if(k==="file"){let v=await yf(e,o,S());g(v)}else if(k==="user"){let v=Im(e,o,S());g(v)}else if(k==="command"){let v=await Tm(e,o,S());g(v)}if(r!==null)try{let k=await _m(e,r),v=Lm(e,k,S(),o);for(let $ of v)g([$])}catch(k){if(k instanceof C)throw k;return F("","",1)}if(a){let k=await Xo(e,o,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,$=$e(e,"COMP_WORDS"),O=$?je($):void 0;be(e,"COMP_WORDS"),br(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 P=$e(e,"COMPREPLY"),N=P?je(P):void 0,D=e.state.env.get("COMPREPLY");be(e,"COMPREPLY"),e.state.env.delete("COMPREPLY");let V=["compgen",h[0]??"",""];try{let X=await ii(e,k,V,"");if(X.exitCode!==0)return Yo(e,v),cr(e,"COMP_WORDS",O),cr(e,"COMPREPLY",N),D!==void 0&&e.state.env.set("COMPREPLY",D),F("",X.stderr,1);y=X.stdout;let R=Fm(e,S());g(R)}catch(X){if(X instanceof C)throw X;return Yo(e,v),cr(e,"COMP_WORDS",O),cr(e,"COMPREPLY",N),D!==void 0&&e.state.env.set("COMPREPLY",D),F("","",1)}Yo(e,v),cr(e,"COMP_WORDS",O),cr(e,"COMPREPLY",N),D!==void 0&&e.state.env.set("COMPREPLY",D)}}if(d!==null)try{let k=qe(d),v=await e.executeScript(k);if(v.exitCode!==0)return F("",v.stderr,v.exitCode);if(v.stdout)for(let $ of Mm(v.stdout))$.length>0&&g([$])}catch(k){if(k.name==="ParseException")return _(`compgen: -C: ${k.message}
182
- `,2);throw k}let b=m;if(u!==null){let k=u.startsWith("!"),v=k?u.slice(1):u;b=m.filter($=>{let O=rr($,v,!1,!0,e.limits.maxCallDepth);return k?O:!O})}if(b.length===0&&o!==null)return F(y,"",1);let A=new Hn(e.limits.maxOutputSize,"compgen");A.append(y);for(let k of b)A.append(s).append(k).append(i).append(`
183
- `);return ne(A.build())}function xm(e,t,n){let r=yt(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 Pm(e,t,n){let r=yt(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 $m(e,t,n){let r=yt(e,t,n);for(let s of e.state.functions.keys())r.add(s);return r.build()}function Cm(e,t,n){let r=yt(e,t,n);for(let s of Jo)r.add(s);return r.build()}function Nm(e,t,n){let r=yt(e,t,n);for(let s of wf)r.add(s);return r.build()}function Rm(e,t,n){let r=yt(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 Om(e,t,n){let r=yt(e,t,n);for(let s of vm)r.add(s);return r.build()}function Dm(e,t,n){let r=yt(e,t,n);for(let s of km)r.add(s);return r.build()}async function Xo(e,t,n=e.limits.maxArrayElements,r){let s=yt(e,null,n,r);try{let i=e.state.cwd,o=t??"";if(t){let l=t.lastIndexOf("/");if(l!==-1){let c=t.slice(0,l)||"/";o=t.slice(l+1),c.startsWith("/")?i=c:i=`${e.state.cwd}/${c}`}}let a=await e.fs.readdir(i);for(let l of a){e.executionScope.consumeWork(1,"compgen directory scan");let c=`${i}/${l}`;try{if((await e.fs.stat(c)).isDirectory&&(!o||l.startsWith(o)))if(t?.includes("/")){let f=t.lastIndexOf("/"),d=t.slice(0,f+1);s.add(d+l)}else s.add(l)}catch(u){if(u instanceof C)throw u}}}catch(i){if(i instanceof C)throw i}return s.build()}async function yf(e,t,n=e.limits.maxArrayElements){let r=yt(e,null,n);try{let s=e.state.cwd,i=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let l=t.slice(0,a)||"/";i=t.slice(a+1),l.startsWith("/")?s=l:s=`${e.state.cwd}/${l}`}}let o=await e.fs.readdir(s);for(let a of o)if(e.executionScope.consumeWork(1,"compgen file scan"),!i||a.startsWith(i))if(t?.includes("/")){let l=t.lastIndexOf("/"),c=t.slice(0,l+1);r.add(c+a)}else r.add(a)}catch(s){if(s instanceof C)throw s}return r.build()}function Im(e,t,n){let r=yt(e,t,n);return r.add("root"),r.add("nobody"),r.build()}async function Tm(e,t,n){let r=yt(e,t,n);for(let i of Jo)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 wf)r.add(i);let s=e.state.env.get("PATH")??"/usr/bin:/bin";for(let i of s.split(":"))if(i)try{let o=await e.fs.readdir(i);for(let a of o)r.add(a)}catch(o){if(o instanceof C)throw o}return r.build()}function yt(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 C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(W(i)>e.limits.maxStringLength)throw new C(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");s.add(i)}},build(){return Array.from(s).sort()}}}async function _m(e,t){let r=new Q().parseWordFromString(t,!1,!1);return await ae(e,M.word(r.parts.map(gf)))}function Lm(e,t,n,r){let s=e.state.env.get("IFS")??`
184
- `;if(s.length===0){if(r!==null&&!t.startsWith(r))return[];if(n===0)throw new C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");return[t]}let i=new Set(s.split("")),o=[],a=u=>{if(!(r!==null&&!u.startsWith(r))){if(o.length>=n)throw new C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");o.push(u)}},l="",c=0;for(;c<t.length;){let u=t[c];if(u==="\\"&&c+1<t.length){let f=t[c+1];l+=f,c+=2}else i.has(u)?(l.length>0&&(a(l),l=""),c++):(l+=u,c++)}return l.length>0&&a(l),o}function Yo(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function cr(e,t,n){e.state.arrays??=new Map,n?e.state.arrays.set(t,je(n)):e.state.arrays.delete(t)}function Fm(e,t){let n=[],r=s=>{if(n.length>=t)throw new C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");n.push(s)};if(De(e,"COMPREPLY")){let s=K(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*Mm(e){let t=0;for(;t<=e.length;){let n=e.indexOf(`
185
- `,t),r=n===-1?e.length:n;if(r>t&&(yield e.slice(t,r)),n===-1)return;t=n+1}}function _r(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function ta(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 Ef(e){if(_r(e))return bf(e);if(e==="")return 2;if(/^[a-zA-Z0-9_/.:\-@%+,=]+$/.test(e))return W(e);let t=W(e)+2;for(let n of e)n==="'"&&(t+=3);return t}function ve(e){return _r(e)?ta(e):e===""?"''":/^[a-zA-Z0-9_/.:\-@%+,=]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function li(e){if(_r(e))return bf(e);let t=W(e)+2;for(let n of e)(n==="\\"||n==='"'||n==="$"||n==="`")&&t++;return t}function xn(e){return _r(e)?ta(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}function bf(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+=W(n)}return t}function Lr(e){return _r(e)?ta(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}var Bm=["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,o,a,l=[],c=[],u=[];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 _(`complete: -W: option requires an argument
186
- `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return _(`complete: -F: option requires an argument
187
- `,2);o=t[f]}else if(d==="-o"){if(f++,f>=t.length)return _(`complete: -o: option requires an argument
188
- `,2);let h=t[f];if(!Bm.includes(h))return _(`complete: ${h}: invalid option name
189
- `,2);l.push(h)}else if(d==="-A"){if(f++,f>=t.length)return _(`complete: -A: option requires an argument
190
- `,2);c.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return _(`complete: -C: option requires an argument
191
- `,2);a=t[f]}else if(d==="-G"){if(f++,f>=t.length)return _(`complete: -G: option requires an argument
192
- `,2)}else if(d==="-P"){if(f++,f>=t.length)return _(`complete: -P: option requires an argument
193
- `,2)}else if(d==="-S"){if(f++,f>=t.length)return _(`complete: -S: option requires an argument
194
- `,2)}else if(d==="-X"){if(f++,f>=t.length)return _(`complete: -X: option requires an argument
195
- `,2)}else if(d==="--"){u.push(...t.slice(f+1));break}else d.startsWith("-")||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),e.state.defaultCompletionSpec=void 0,e.state.emptyCompletionSpec=void 0,ne("");for(let f of u)e.state.completionSpecs.delete(f);return ne("")}if(n)return u.length===0?na(e):na(e,u);if(t.length===0||u.length===0&&!i&&!o&&!a&&l.length===0&&c.length===0&&!s)return na(e);if(o&&u.length===0&&!s)return _(`complete: -F: option requires a command name
196
- `,2);if(s){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),o!==void 0&&(f.function=o),a!==void 0&&(f.command=a),l.length>0&&(f.options=l),c.length>0&&(f.actions=c),e.state.defaultCompletionSpec=f,ne("")}for(let f of u){let d=Object.create(null);i!==void 0&&(d.wordlist=i),o!==void 0&&(d.function=o),a!==void 0&&(d.command=a),l.length>0&&(d.options=l),c.length>0&&(d.actions=c),e.state.completionSpecs.set(f,d)}return ne("")}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 o of t)i+=`complete: ${o}: no completion specification
197
- `;return F("",i,1)}return ne("")}let r=[],s=t||Array.from(n.keys());for(let i of s){let o=n.get(i);if(!o){if(t)return F(r.join(`
175
+ `:""}}var Sf=e=>e.type==="Escaped"?M.literal(`\\${e.value}`):e.type==="DoubleQuoted"?{...e,parts:e.parts.map(Sf)}:e,Af=Pr,na=Tt,Nm=wf,Rm=na;async function ra(e,t){let n=[],r=null,s="",i="",o=null,a=!1,l=!1,c=!1,u=null,f=null,d=null,h=[],p=["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 A=t[k];if(A==="-v")n.push("variable");else if(A==="-e")n.push("export");else if(A==="-f")n.push("file");else if(A==="-d")n.push("directory");else if(A==="-k")n.push("keyword");else if(A==="-A"){if(k++,k>=t.length)return L(`compgen: -A: option requires an argument
176
+ `,2);let $=t[k];if(!p.includes($))return L(`compgen: ${$}: invalid action name
177
+ `,2);n.push($)}else if(A==="-W"){if(k++,k>=t.length)return L(`compgen: -W: option requires an argument
178
+ `,2);r=t[k]}else if(A==="-P"){if(k++,k>=t.length)return L(`compgen: -P: option requires an argument
179
+ `,2);s=t[k]}else if(A==="-S"){if(k++,k>=t.length)return L(`compgen: -S: option requires an argument
180
+ `,2);i=t[k]}else if(A==="-o"){if(k++,k>=t.length)return L(`compgen: -o: option requires an argument
181
+ `,2);let $=t[k];if($==="plusdirs")a=!0;else if($==="dirnames")l=!0;else if($==="default")c=!0;else if(!($==="filenames"||$==="nospace"||$==="bashdefault"||$==="noquote"))return L(`compgen: ${$}: invalid option name
182
+ `,2)}else if(A==="-F"){if(k++,k>=t.length)return L(`compgen: -F: option requires an argument
183
+ `,2);f=t[k]}else if(A==="-C"){if(k++,k>=t.length)return L(`compgen: -C: option requires an argument
184
+ `,2);d=t[k]}else if(A==="-X"){if(k++,k>=t.length)return L(`compgen: -X: option requires an argument
185
+ `,2);u=t[k]}else if(A==="-G"){if(k++,k>=t.length)return L(`compgen: -G: option requires an argument
186
+ `,2)}else if(A==="--"){h.push(...t.slice(k+1));break}else A.startsWith("-")||h.push(A)}o=h[0]??null;let m=[],E=new Set,b=()=>e.limits.maxArrayElements-m.length,y=k=>{for(let A of k){if(m.length>=e.limits.maxArrayElements)throw new C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(A)>e.limits.maxStringLength)throw new C(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");e.executionScope.consumeWork(1,"compgen completion"),m.push(A),E.add(A)}};if(l){let k=await ea(e,o,b());y(k)}if(c){let k=await bf(e,o,b());y(k)}for(let k of n)if(k==="variable"){let A=Om(e,o,b());y(A)}else if(k==="export"){let A=Dm(e,o,b());y(A)}else if(k==="function"){let A=Im(e,o,b());y(A)}else if(k==="builtin"){let A=Tm(e,o,b());y(A)}else if(k==="keyword"){let A=_m(e,o,b());y(A)}else if(k==="alias"){let A=Lm(e,o,b());y(A)}else if(k==="shopt"){let A=Fm(e,o,b());y(A)}else if(k==="helptopic"){let A=Mm(e,o,b());y(A)}else if(k==="directory"){let A=await ea(e,o,b());y(A)}else if(k==="file"){let A=await bf(e,o,b());y(A)}else if(k==="user"){let A=Bm(e,o,b());y(A)}else if(k==="command"){let A=await Wm(e,o,b());y(A)}if(r!==null)try{let k=await Vm(e,r),A=zm(e,k,b(),o);for(let $ of A)y([$])}catch(k){if(k instanceof C)throw k;return F("","",1)}if(a){let k=await ea(e,o,b(),E);for(let A of k)E.has(A)||y([A])}let g="";if(f!==null){let k=e.state.functions.get(f);if(k){let A=new Map,$=$e(e,"COMP_WORDS"),R=$?qe($):void 0;be(e,"COMP_WORDS"),vr(e,"COMP_WORDS"),A.set("COMP_CWORD",e.state.env.get("COMP_CWORD")),e.state.env.set("COMP_CWORD","-1"),A.set("COMP_LINE",e.state.env.get("COMP_LINE")),e.state.env.set("COMP_LINE",""),A.set("COMP_POINT",e.state.env.get("COMP_POINT")),e.state.env.set("COMP_POINT","0");let P=$e(e,"COMPREPLY"),N=P?qe(P):void 0,I=e.state.env.get("COMPREPLY");be(e,"COMPREPLY"),e.state.env.delete("COMPREPLY");let z=["compgen",h[0]??"",""];try{let X=await ai(e,k,z,"");if(X.exitCode!==0)return ta(e,A),ur(e,"COMP_WORDS",R),ur(e,"COMPREPLY",N),I!==void 0&&e.state.env.set("COMPREPLY",I),F("",X.stderr,1);g=X.stdout;let O=Um(e,b());y(O)}catch(X){if(X instanceof C)throw X;return ta(e,A),ur(e,"COMP_WORDS",R),ur(e,"COMPREPLY",N),I!==void 0&&e.state.env.set("COMPREPLY",I),F("","",1)}ta(e,A),ur(e,"COMP_WORDS",R),ur(e,"COMPREPLY",N),I!==void 0&&e.state.env.set("COMPREPLY",I)}}if(d!==null)try{let k=He(d),A=await e.executeScript(k);if(A.exitCode!==0)return F("",A.stderr,A.exitCode);if(A.stdout)for(let $ of jm(A.stdout))$.length>0&&y([$])}catch(k){if(k.name==="ParseException")return L(`compgen: -C: ${k.message}
187
+ `,2);throw k}let S=m;if(u!==null){let k=u.startsWith("!"),A=k?u.slice(1):u;S=m.filter($=>{let R=sr($,A,!1,!0,e.limits.maxCallDepth);return k?R:!R})}if(S.length===0&&o!==null)return F(g,"",1);let v=new Qn(e.limits.maxOutputSize,"compgen");v.append(g);for(let k of S)v.append(s).append(k).append(i).append(`
188
+ `);return te(v.build())}function Om(e,t,n){let r=wt(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 Dm(e,t,n){let r=wt(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 Im(e,t,n){let r=wt(e,t,n);for(let s of e.state.functions.keys())r.add(s);return r.build()}function Tm(e,t,n){let r=wt(e,t,n);for(let s of na)r.add(s);return r.build()}function _m(e,t,n){let r=wt(e,t,n);for(let s of Af)r.add(s);return r.build()}function Lm(e,t,n){let r=wt(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 Fm(e,t,n){let r=wt(e,t,n);for(let s of Nm)r.add(s);return r.build()}function Mm(e,t,n){let r=wt(e,t,n);for(let s of Rm)r.add(s);return r.build()}async function ea(e,t,n=e.limits.maxArrayElements,r){let s=wt(e,null,n,r);try{let i=e.state.cwd,o=t??"";if(t){let l=t.lastIndexOf("/");if(l!==-1){let c=t.slice(0,l)||"/";o=t.slice(l+1),c.startsWith("/")?i=c:i=`${e.state.cwd}/${c}`}}let a=await e.fs.readdir(i);for(let l of a){e.executionScope.consumeWork(1,"compgen directory scan");let c=`${i}/${l}`;try{if((await e.fs.stat(c)).isDirectory&&(!o||l.startsWith(o)))if(t?.includes("/")){let f=t.lastIndexOf("/"),d=t.slice(0,f+1);s.add(d+l)}else s.add(l)}catch(u){if(u instanceof C)throw u}}}catch(i){if(i instanceof C)throw i}return s.build()}async function bf(e,t,n=e.limits.maxArrayElements){let r=wt(e,null,n);try{let s=e.state.cwd,i=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let l=t.slice(0,a)||"/";i=t.slice(a+1),l.startsWith("/")?s=l:s=`${e.state.cwd}/${l}`}}let o=await e.fs.readdir(s);for(let a of o)if(e.executionScope.consumeWork(1,"compgen file scan"),!i||a.startsWith(i))if(t?.includes("/")){let l=t.lastIndexOf("/"),c=t.slice(0,l+1);r.add(c+a)}else r.add(a)}catch(s){if(s instanceof C)throw s}return r.build()}function Bm(e,t,n){let r=wt(e,t,n);return r.add("root"),r.add("nobody"),r.build()}async function Wm(e,t,n){let r=wt(e,t,n);for(let i of na)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 Af)r.add(i);let s=e.state.env.get("PATH")??"/usr/bin:/bin";for(let i of s.split(":"))if(i)try{let o=await e.fs.readdir(i);for(let a of o)r.add(a)}catch(o){if(o instanceof C)throw o}return r.build()}function wt(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 C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(i)>e.limits.maxStringLength)throw new C(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");s.add(i)}},build(){return Array.from(s).sort()}}}async function Vm(e,t){let r=new Q().parseWordFromString(t,!1,!1);return await ie(e,M.word(r.parts.map(Sf)))}function zm(e,t,n,r){let s=e.state.env.get("IFS")??`
189
+ `;if(s.length===0){if(r!==null&&!t.startsWith(r))return[];if(n===0)throw new C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");return[t]}let i=new Set(s.split("")),o=[],a=u=>{if(!(r!==null&&!u.startsWith(r))){if(o.length>=n)throw new C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");o.push(u)}},l="",c=0;for(;c<t.length;){let u=t[c];if(u==="\\"&&c+1<t.length){let f=t[c+1];l+=f,c+=2}else i.has(u)?(l.length>0&&(a(l),l=""),c++):(l+=u,c++)}return l.length>0&&a(l),o}function ta(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function ur(e,t,n){e.state.arrays??=new Map,n?e.state.arrays.set(t,qe(n)):e.state.arrays.delete(t)}function Um(e,t){let n=[],r=s=>{if(n.length>=t)throw new C(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");n.push(s)};if(Ie(e,"COMPREPLY")){let s=K(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*jm(e){let t=0;for(;t<=e.length;){let n=e.indexOf(`
190
+ `,t),r=n===-1?e.length:n;if(r>t&&(yield e.slice(t,r)),n===-1)return;t=n+1}}function Mr(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function sa(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 vf(e){if(Mr(e))return kf(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 ve(e){return Mr(e)?sa(e):e===""?"''":/^[a-zA-Z0-9_/.:\-@%+,=]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function ui(e){if(Mr(e))return kf(e);let t=B(e)+2;for(let n of e)(n==="\\"||n==='"'||n==="$"||n==="`")&&t++;return t}function $n(e){return Mr(e)?sa(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}function kf(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 Br(e){return Mr(e)?sa(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}var qm=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function oa(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,s=!1,i,o,a,l=[],c=[],u=[];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
191
+ `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return L(`complete: -F: option requires an argument
192
+ `,2);o=t[f]}else if(d==="-o"){if(f++,f>=t.length)return L(`complete: -o: option requires an argument
193
+ `,2);let h=t[f];if(!qm.includes(h))return L(`complete: ${h}: invalid option name
194
+ `,2);l.push(h)}else if(d==="-A"){if(f++,f>=t.length)return L(`complete: -A: option requires an argument
195
+ `,2);c.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return L(`complete: -C: option requires an argument
196
+ `,2);a=t[f]}else if(d==="-G"){if(f++,f>=t.length)return L(`complete: -G: option requires an argument
197
+ `,2)}else if(d==="-P"){if(f++,f>=t.length)return L(`complete: -P: option requires an argument
198
+ `,2)}else if(d==="-S"){if(f++,f>=t.length)return L(`complete: -S: option requires an argument
199
+ `,2)}else if(d==="-X"){if(f++,f>=t.length)return L(`complete: -X: option requires an argument
200
+ `,2)}else if(d==="--"){u.push(...t.slice(f+1));break}else d.startsWith("-")||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),e.state.defaultCompletionSpec=void 0,e.state.emptyCompletionSpec=void 0,te("");for(let f of u)e.state.completionSpecs.delete(f);return te("")}if(n)return u.length===0?ia(e):ia(e,u);if(t.length===0||u.length===0&&!i&&!o&&!a&&l.length===0&&c.length===0&&!s)return ia(e);if(o&&u.length===0&&!s)return L(`complete: -F: option requires a command name
201
+ `,2);if(s){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),o!==void 0&&(f.function=o),a!==void 0&&(f.command=a),l.length>0&&(f.options=l),c.length>0&&(f.actions=c),e.state.defaultCompletionSpec=f,te("")}for(let f of u){let d=Object.create(null);i!==void 0&&(d.wordlist=i),o!==void 0&&(d.function=o),a!==void 0&&(d.command=a),l.length>0&&(d.options=l),c.length>0&&(d.actions=c),e.state.completionSpecs.set(f,d)}return te("")}function ia(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 o of t)i+=`complete: ${o}: no completion specification
202
+ `;return F("",i,1)}return te("")}let r=[],s=t||Array.from(n.keys());for(let i of s){let o=n.get(i);if(!o){if(t)return F(r.join(`
198
203
  `)+(r.length>0?`
199
204
  `:""),`complete: ${i}: no completion specification
200
- `,1);continue}let a="complete";if(o.options)for(let l of o.options)a+=` -o ${ve(l)}`;if(o.actions)for(let l of o.actions)a+=` -A ${ve(l)}`;o.wordlist!==void 0&&(o.wordlist.includes(" ")||o.wordlist.includes("'")?a+=` -W ${ve(o.wordlist)}`:a+=` -W ${ve(o.wordlist)}`),o.function!==void 0&&(a+=` -F ${ve(o.function)}`),o.command!==void 0&&(a+=` -C ${ve(o.command)}`),o.isDefault&&(a+=" -D"),a+=`${i.startsWith("-")?" -- ":" "}${ve(i)}`,r.push(a)}if(!t&&e.state.defaultCompletionSpec){let i=e.state.defaultCompletionSpec,o="complete";for(let a of i.options??[])o+=` -o ${ve(a)}`;for(let a of i.actions??[])o+=` -A ${ve(a)}`;i.wordlist!==void 0&&(o+=` -W ${ve(i.wordlist)}`),i.function!==void 0&&(o+=` -F ${ve(i.function)}`),i.command!==void 0&&(o+=` -C ${ve(i.command)}`),o+=" -D",r.push(o)}return r.length===0?ne(""):ne(`${r.join(`
205
+ `,1);continue}let a="complete";if(o.options)for(let l of o.options)a+=` -o ${ve(l)}`;if(o.actions)for(let l of o.actions)a+=` -A ${ve(l)}`;o.wordlist!==void 0&&(o.wordlist.includes(" ")||o.wordlist.includes("'")?a+=` -W ${ve(o.wordlist)}`:a+=` -W ${ve(o.wordlist)}`),o.function!==void 0&&(a+=` -F ${ve(o.function)}`),o.command!==void 0&&(a+=` -C ${ve(o.command)}`),o.isDefault&&(a+=" -D"),a+=`${i.startsWith("-")?" -- ":" "}${ve(i)}`,r.push(a)}if(!t&&e.state.defaultCompletionSpec){let i=e.state.defaultCompletionSpec,o="complete";for(let a of i.options??[])o+=` -o ${ve(a)}`;for(let a of i.actions??[])o+=` -A ${ve(a)}`;i.wordlist!==void 0&&(o+=` -W ${ve(i.wordlist)}`),i.function!==void 0&&(o+=` -F ${ve(i.function)}`),i.command!==void 0&&(o+=` -C ${ve(i.command)}`),o+=" -D",r.push(o)}return r.length===0?te(""):te(`${r.join(`
201
206
  `)}
202
- `)}var Sf=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function sa(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,s=[],i=[],o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l==="-D")n=!0;else if(l==="-E")r=!0;else if(l==="-o"){if(a++,a>=t.length)return _(`compopt: -o: option requires an argument
203
- `,2);let c=t[a];if(!Sf.includes(c))return _(`compopt: ${c}: invalid option name
204
- `,2);s.push(c)}else if(l==="+o"){if(a++,a>=t.length)return _(`compopt: +o: option requires an argument
205
- `,2);let c=t[a];if(!Sf.includes(c))return _(`compopt: ${c}: invalid option name
206
- `,2);i.push(c)}else if(l==="--"){o.push(...t.slice(a+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&o.push(l)}if(n){let a=e.state.defaultCompletionSpec??{isDefault:!0},l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.defaultCompletionSpec=a,ne("")}if(r){let a=e.state.emptyCompletionSpec??Object.create(null),l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.emptyCompletionSpec=a,ne("")}if(o.length>0){for(let a of o){let l=e.state.completionSpecs.get(a)??{},c=new Set(l.options??[]);for(let u of s)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set(a,l)}return ne("")}return _(`compopt: not currently executing completion function
207
- `,1)}function ia(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new tn;return se}if(t.length>1)throw new G(1,"",`bash: continue: too many arguments
208
- `);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new G(1,"",`bash: continue: ${t[0]}: numeric argument required
209
- `);n=r}throw new nt(n)}function Af(e,t){let n="";return e.state.integerVars?.has(t)&&(n+="i"),e.state.lowercaseVars?.has(t)&&(n+="l"),fe(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 ve(e)}function aa(e){return`'${e.replace(/'/g,"'\\''")}'`}function vf(e,t){let n="",r="",s=!1;for(let i of t){let o=Af(e,i);if(e.state.associativeArrays?.has(i)){let u=Tt(e,i);if(u.length===0)n+=`declare -A ${i}=()
210
- `;else{let f=u.map(d=>{let h=ce(e,i,d)??"",p=oa(h);return`[${aa(d)}]=${p}`});n+=`declare -A ${i}=(${f.join(" ")})
211
- `}continue}let l=xe(e,i);if(l.length>0){let u=l.map(f=>{let d=ce(e,i,f)??"";return`[${f}]=${xn(d)}`});n+=`declare -a ${i}=(${u.join(" ")})
212
- `;continue}if(De(e,i)){n+=`declare -a ${i}=()
213
- `;continue}let c=e.state.env.get(i);if(c!==void 0)n+=`declare ${o} ${i}=${Lr(c)}
207
+ `)}var xf=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function aa(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,s=[],i=[],o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l==="-D")n=!0;else if(l==="-E")r=!0;else if(l==="-o"){if(a++,a>=t.length)return L(`compopt: -o: option requires an argument
208
+ `,2);let c=t[a];if(!xf.includes(c))return L(`compopt: ${c}: invalid option name
209
+ `,2);s.push(c)}else if(l==="+o"){if(a++,a>=t.length)return L(`compopt: +o: option requires an argument
210
+ `,2);let c=t[a];if(!xf.includes(c))return L(`compopt: ${c}: invalid option name
211
+ `,2);i.push(c)}else if(l==="--"){o.push(...t.slice(a+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&o.push(l)}if(n){let a=e.state.defaultCompletionSpec??{isDefault:!0},l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.defaultCompletionSpec=a,te("")}if(r){let a=e.state.emptyCompletionSpec??Object.create(null),l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.emptyCompletionSpec=a,te("")}if(o.length>0){for(let a of o){let l=e.state.completionSpecs.get(a)??{},c=new Set(l.options??[]);for(let u of s)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set(a,l)}return te("")}return L(`compopt: not currently executing completion function
212
+ `,1)}function la(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new nn;return ne}if(t.length>1)throw new H(1,"",`bash: continue: too many arguments
213
+ `);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new H(1,"",`bash: continue: ${t[0]}: numeric argument required
214
+ `);n=r}throw new rt(n)}function Pf(e,t){let n="";return e.state.integerVars?.has(t)&&(n+="i"),e.state.lowercaseVars?.has(t)&&(n+="l"),fe(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 ca(e){return ve(e)}function ua(e){return`'${e.replace(/'/g,"'\\''")}'`}function $f(e,t){let n="",r="",s=!1;for(let i of t){let o=Pf(e,i);if(e.state.associativeArrays?.has(i)){let u=Lt(e,i);if(u.length===0)n+=`declare -A ${i}=()
215
+ `;else{let f=u.map(d=>{let h=le(e,i,d)??"",p=ca(h);return`[${ua(d)}]=${p}`});n+=`declare -A ${i}=(${f.join(" ")})
216
+ `}continue}let l=xe(e,i);if(l.length>0){let u=l.map(f=>{let d=le(e,i,f)??"";return`[${f}]=${$n(d)}`});n+=`declare -a ${i}=(${u.join(" ")})
217
+ `;continue}if(Ie(e,i)){n+=`declare -a ${i}=()
218
+ `;continue}let c=e.state.env.get(i);if(c!==void 0)n+=`declare ${o} ${i}=${Br(c)}
214
219
  `;else{let u=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);u||f?n+=`declare ${o} ${i}
215
220
  `:(r+=`bash: declare: ${i}: not found
216
- `,s=!0)}}return F(n,r,s?1:0)}function kf(e,t){let{filterExport:n,filterReadonly:r,filterNameref:s,filterIndexedArray:i,filterAssocArray:o}=t,a=n||r||s||i||o,l="",c=new Set;for(let f of e.state.env.keys())f.startsWith("BASH_")||c.add(f);for(let f of e.state.arrays?.keys()??[])c.add(f);if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())c.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)c.add(f);let u=Array.from(c).sort();for(let f of u){let d=Af(e,f),h=e.state.associativeArrays?.has(f),p=xe(e,f),m=!h&&De(e,f);if(a&&(o&&!h||i&&!m||n&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||s&&!fe(e,f)))continue;if(h){let S=Tt(e,f);if(S.length===0)l+=`declare -A ${f}=()
217
- `;else{let g=S.map(y=>{let b=ce(e,f,y)??"",A=oa(b);return`[${aa(y)}]=${A}`});l+=`declare -A ${f}=(${g.join(" ")})
218
- `}continue}if(p.length>0){let S=p.map(g=>{let y=ce(e,f,g)??"";return`[${g}]=${xn(y)}`});l+=`declare -a ${f}=(${S.join(" ")})
219
- `;continue}if(De(e,f)){l+=`declare -a ${f}=()
220
- `;continue}let E=e.state.env.get(f);E!==void 0&&(l+=`declare ${d} ${f}=${Lr(E)}
221
- `)}return ne(l)}function xf(e){let t="",n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let s=Tt(e,r);if(s.length===0)t+=`declare -A ${r}=()
222
- `;else{let i=s.map(o=>{let a=ce(e,r,o)??"",l=oa(a);return`[${aa(o)}]=${l}`});t+=`declare -A ${r}=(${i.join(" ")})
223
- `}}return ne(t)}function Pf(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=xe(e,s);if(i.length===0)t+=`declare -a ${s}=()
224
- `;else{let o=i.map(a=>{let l=ce(e,s,a)??"";return`[${a}]=${xn(l)}`});t+=`declare -a ${s}=(${o.join(" ")})
225
- `}}return ne(t)}function $f(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)||xe(e,s).length>0||De(e,s))continue;let a=e.state.env.get(s);a!==void 0&&(t+=`${s}=${ve(a)}
226
- `)}return ne(t)}function la(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Fr(e,t){return e.state.integerVars?.has(t)??!1}function ca(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Wm(e,t){return e.state.lowercaseVars?.has(t)??!1}function ua(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Vm(e,t){return e.state.uppercaseVars?.has(t)??!1}function ur(e,t,n){return Wm(e,t)?n.toLowerCase():Vm(e,t)?n.toUpperCase():n}async function Cf(e,t){try{let n=new Q,r=oe(n,t),s=await ee(e,r.expression);return String(s)}catch{return"0"}}function zm(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 o=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let a=e.slice(r);return{name:n,indexExpr:o,value:a}}async function ci(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!1,f=!1,d=!1,h=!1,p=!1,m=!1,E=!1,S=!1,g=[];for(let P=0;P<t.length;P++){let N=t[P];if(N==="-a")r=!0;else if(N==="-A")s=!0;else if(N==="-r")i=!0;else if(N==="-x")o=!0;else if(N==="-p")a=!0;else if(N==="-n")l=!0;else if(N==="+n")c=!0;else if(N==="+a")u=!0;else if(N==="+x")f=!0;else if(N==="--"){g.push(...t.slice(P+1));break}else if(N.startsWith("+")){for(let D of N.slice(1))if(D==="n")c=!0;else if(D==="a")u=!0;else if(D==="x")f=!0;else if(D!=="r"){if(D!=="i"){if(!(D==="f"||D==="F"))return F("",`bash: typeset: +${D}: invalid option
227
- `,2)}}}else if(N==="-i")d=!0;else if(N==="-l")h=!0;else if(N==="-u")p=!0;else if(N==="-f")m=!0;else if(N==="-F")E=!0;else if(N==="-g")S=!0;else if(N.startsWith("-"))for(let D of N.slice(1))if(D==="a")r=!0;else if(D==="A")s=!0;else if(D==="r")i=!0;else if(D==="x")o=!0;else if(D==="p")a=!0;else if(D==="n")l=!0;else if(D==="i")d=!0;else if(D==="l")h=!0;else if(D==="u")p=!0;else if(D==="f")m=!0;else if(D==="F")E=!0;else if(D==="g")S=!0;else return F("",`bash: typeset: -${D}: invalid option
228
- `,2);else g.push(N)}let b=e.state.localScopes.length>0&&!S,A=P=>{if(!b)return;let N=e.state.localScopes[e.state.localScopes.length-1];N.has(P)||N.set(P,e.state.env.get(P))},k=P=>{if(!b)return;let N=e.state.localScopes[e.state.localScopes.length-1];for(N.has(P)||N.set(P,e.state.env.get(P)),e.state.localArrayScopes??=[];e.state.localArrayScopes.length<e.state.localScopes.length;)e.state.localArrayScopes.push(new Map);let D=e.state.localArrayScopes.at(-1);if(D&&!D.has(P)){let V=$e(e,P);D.set(P,V?je(V):void 0)}},v=P=>{b&&bn(e,P)};if(E){if(g.length===0){let D=Array.from(e.state.functions.keys()).sort(),V="";for(let X of D)V+=`declare -f ${X}
229
- `;return ne(V)}let P=!0,N="";for(let D of g)e.state.functions.has(D)?N+=`${D}
230
- `:P=!1;return F(N,"",P?0:1)}if(m){if(g.length===0){let N="",D=Array.from(e.state.functions.keys()).sort();for(let V of D)N+=`${V} ()
221
+ `,s=!0)}}return F(n,r,s?1:0)}function Cf(e,t){let{filterExport:n,filterReadonly:r,filterNameref:s,filterIndexedArray:i,filterAssocArray:o}=t,a=n||r||s||i||o,l="",c=new Set;for(let f of e.state.env.keys())f.startsWith("BASH_")||c.add(f);for(let f of e.state.arrays?.keys()??[])c.add(f);if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())c.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)c.add(f);let u=Array.from(c).sort();for(let f of u){let d=Pf(e,f),h=e.state.associativeArrays?.has(f),p=xe(e,f),m=!h&&Ie(e,f);if(a&&(o&&!h||i&&!m||n&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||s&&!fe(e,f)))continue;if(h){let b=Lt(e,f);if(b.length===0)l+=`declare -A ${f}=()
222
+ `;else{let y=b.map(g=>{let S=le(e,f,g)??"",v=ca(S);return`[${ua(g)}]=${v}`});l+=`declare -A ${f}=(${y.join(" ")})
223
+ `}continue}if(p.length>0){let b=p.map(y=>{let g=le(e,f,y)??"";return`[${y}]=${$n(g)}`});l+=`declare -a ${f}=(${b.join(" ")})
224
+ `;continue}if(Ie(e,f)){l+=`declare -a ${f}=()
225
+ `;continue}let E=e.state.env.get(f);E!==void 0&&(l+=`declare ${d} ${f}=${Br(E)}
226
+ `)}return te(l)}function Nf(e){let t="",n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let s=Lt(e,r);if(s.length===0)t+=`declare -A ${r}=()
227
+ `;else{let i=s.map(o=>{let a=le(e,r,o)??"",l=ca(a);return`[${ua(o)}]=${l}`});t+=`declare -A ${r}=(${i.join(" ")})
228
+ `}}return te(t)}function Rf(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=xe(e,s);if(i.length===0)t+=`declare -a ${s}=()
229
+ `;else{let o=i.map(a=>{let l=le(e,s,a)??"";return`[${a}]=${$n(l)}`});t+=`declare -a ${s}=(${o.join(" ")})
230
+ `}}return te(t)}function Of(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)||xe(e,s).length>0||Ie(e,s))continue;let a=e.state.env.get(s);a!==void 0&&(t+=`${s}=${ve(a)}
231
+ `)}return te(t)}function fa(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Wr(e,t){return e.state.integerVars?.has(t)??!1}function da(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Hm(e,t){return e.state.lowercaseVars?.has(t)??!1}function ha(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Gm(e,t){return e.state.uppercaseVars?.has(t)??!1}function fr(e,t,n){return Hm(e,t)?n.toLowerCase():Gm(e,t)?n.toUpperCase():n}async function Df(e,t){try{let n=new Q,r=se(n,t),s=await ee(e,r.expression);return String(s)}catch{return"0"}}function Zm(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 o=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let a=e.slice(r);return{name:n,indexExpr:o,value:a}}async function fi(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!1,f=!1,d=!1,h=!1,p=!1,m=!1,E=!1,b=!1,y=[];for(let P=0;P<t.length;P++){let N=t[P];if(N==="-a")r=!0;else if(N==="-A")s=!0;else if(N==="-r")i=!0;else if(N==="-x")o=!0;else if(N==="-p")a=!0;else if(N==="-n")l=!0;else if(N==="+n")c=!0;else if(N==="+a")u=!0;else if(N==="+x")f=!0;else if(N==="--"){y.push(...t.slice(P+1));break}else if(N.startsWith("+")){for(let I of N.slice(1))if(I==="n")c=!0;else if(I==="a")u=!0;else if(I==="x")f=!0;else if(I!=="r"){if(I!=="i"){if(!(I==="f"||I==="F"))return F("",`bash: typeset: +${I}: invalid option
232
+ `,2)}}}else if(N==="-i")d=!0;else if(N==="-l")h=!0;else if(N==="-u")p=!0;else if(N==="-f")m=!0;else if(N==="-F")E=!0;else if(N==="-g")b=!0;else if(N.startsWith("-"))for(let I of N.slice(1))if(I==="a")r=!0;else if(I==="A")s=!0;else if(I==="r")i=!0;else if(I==="x")o=!0;else if(I==="p")a=!0;else if(I==="n")l=!0;else if(I==="i")d=!0;else if(I==="l")h=!0;else if(I==="u")p=!0;else if(I==="f")m=!0;else if(I==="F")E=!0;else if(I==="g")b=!0;else return F("",`bash: typeset: -${I}: invalid option
233
+ `,2);else y.push(N)}let S=e.state.localScopes.length>0&&!b,v=P=>{if(!S)return;let N=e.state.localScopes[e.state.localScopes.length-1];N.has(P)||N.set(P,e.state.env.get(P))},k=P=>{if(!S)return;let N=e.state.localScopes[e.state.localScopes.length-1];for(N.has(P)||N.set(P,e.state.env.get(P)),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(P)){let z=$e(e,P);I.set(P,z?qe(z):void 0)}},A=P=>{S&&An(e,P)};if(E){if(y.length===0){let I=Array.from(e.state.functions.keys()).sort(),z="";for(let X of I)z+=`declare -f ${X}
234
+ `;return te(z)}let P=!0,N="";for(let I of y)e.state.functions.has(I)?N+=`${I}
235
+ `:P=!1;return F(N,"",P?0:1)}if(m){if(y.length===0){let N="",I=Array.from(e.state.functions.keys()).sort();for(let z of I)N+=`${z} ()
231
236
  {
232
237
  # function body
233
238
  }
234
- `;return ne(N)}let P=!0;for(let N of g)e.state.functions.has(N)||(P=!1);return F("","",P?0:1)}if(a&&g.length>0)return vf(e,g);if(a&&g.length===0)return kf(e,{filterExport:o,filterReadonly:i,filterNameref:l,filterIndexedArray:r,filterAssocArray:s});if(g.length===0&&s&&!a)return xf(e);if(g.length===0&&r&&!a)return Pf(e);if(g.length===0&&!a)return $f(e);let $="",O=0;for(let P of g){let N=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(N&&!u){let R=N[1],j=N[2],q=de(e,R);if(q)return q;if(s&&xe(e,R).length>0){$+=`bash: declare: ${R}: cannot convert indexed to associative array
235
- `,O=1;continue}if((r||!s&&!r)&&e.state.associativeArrays?.has(R)){$+=`bash: declare: ${R}: cannot convert associative to indexed array
236
- `,O=1;continue}let I=s&&j.includes("[")?Ks(j,n):void 0,T=I===void 0?Kt(j,{...n,maxElements:s?n.maxElements*2:n.maxElements}):void 0;if(e.executionScope.consumeWork(I?.length??T?.length??0,"declare array assignment"),k(R),s?(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(R),ln(e,R,"associative")):ln(e,R,"indexed"),be(e,R),e.state.env.delete(R),s&&j.includes("["))for(let[B,ie]of I??[])H(e,R,B,yn(e,ie),"associative");else if(s){let B=T??[];for(let ie=0;ie<B.length;ie+=2){let J=B[ie],Be=ie+1<B.length?B[ie+1]:"";H(e,R,J,Be,"associative")}}else{let B=T??[];if(B.some(J=>/^\[[^\]]+\]=/.test(J))){let J=0;for(let Be of B){let wt=Be.match(/^\[([^\]]+)\]=(.*)$/);if(wt){let Vt=wt[1],Et=wt[2],bt;if(/^-?\d+$/.test(Vt))bt=Number.parseInt(Vt,10);else try{let zt=new Q,Rd=oe(zt,Vt);bt=await ee(e,Rd.expression)}catch{bt=0}H(e,R,bt,yn(e,Et)),J=bt+1}else H(e,R,J,Be),J++}}else for(let J=0;J<B.length;J++)H(e,R,J,B[J])}v(R),i&&et(e,R),o&&xt(e,R);continue}if(c){let R=P.includes("=")?P.slice(0,P.indexOf("=")):P;if(Ac(e,R),!P.includes("="))continue}if(f){let R=P.includes("=")?P.slice(0,P.indexOf("=")):P;if(Cs(e,R),!P.includes("="))continue}let D=zm(P);if(D){let{name:R,indexExpr:j,value:q}=D,I=de(e,R);if(I)return I;k(R);let T;try{let B=new Q,ie=oe(B,j);T=await ee(e,ie.expression)}catch{let B=parseInt(j,10);T=Number.isNaN(B)?0:B}H(e,R,T,q),v(R),i&&et(e,R),o&&xt(e,R);continue}let V=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(V&&!u){let R=V[1],j=V[2],q=de(e,R);if(q)return q;k(R);let I=Kt(j,n);if(e.state.associativeArrays?.has(R)){let T=Ks(j,n);e.executionScope.consumeWork(T.length,"declare array append"),Dn(e,R,T.map(([B])=>B));for(let[B,ie]of T)H(e,R,B,ie,"associative")}else{e.executionScope.consumeWork(I.length,"declare array append");let T=xe(e,R),B=0,ie=e.state.env.get(R);T.length===0&&ie!==void 0?(H(e,R,0,ie),e.state.env.delete(R),B=1):T.length>0&&(B=Math.max(...T)+1),Dn(e,R,Array.from({length:I.length},(J,Be)=>B+Be));for(let J=0;J<I.length;J++)H(e,R,B+J,I[J])}v(R),i&&et(e,R),o&&xt(e,R);continue}let X=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(X){let R=X[1],j=X[2],q=de(e,R);if(q)return q;A(R),d&&la(e,R),h&&ca(e,R),p&&ua(e,R);let T=xe(e,R).length>0||e.state.associativeArrays?.has(R);if(Fr(e,R)){let B=e.state.env.get(R)??"0",ie=parseInt(B,10)||0,J=parseInt(await Cf(e,j),10)||0;j=String(ie+J),e.state.env.set(R,j)}else if(T){j=ur(e,R,j);let B=ce(e,R,0)??"";H(e,R,0,nn([B,j],"",e.limits.maxStringLength,"declare append"))}else{j=ur(e,R,j);let B=e.state.env.get(R)??"";e.state.env.set(R,nn([B,j],"",e.limits.maxStringLength,"declare append"))}v(R),i&&et(e,R),o&&xt(e,R),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(R));continue}if(P.includes("=")){let R=P.indexOf("="),j=P.slice(0,R),q=P.slice(R+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(j)){$+=`bash: typeset: \`${j}': not a valid identifier
237
- `,O=1;continue}let I=de(e,j);if(I)return I;if(A(j),l){if(q!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(q)){$+=`bash: declare: \`${q}': invalid variable name for name reference
238
- `,O=1;continue}e.state.env.set(j,q),Qt(e,j),q!==""&&ks(e,q)&&go(e,j),v(j),i&&et(e,j),o&&xt(e,j);continue}if(d&&la(e,j),h&&ca(e,j),p&&ua(e,j),Fr(e,j)&&(q=await Cf(e,q)),q=ur(e,j,q),fe(e,j)){let T=Ge(e,j);T&&T!==j?e.state.env.set(T,q):e.state.env.set(j,q)}else e.state.env.set(j,q);v(j),i&&et(e,j),o&&xt(e,j),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(j))}else{let R=P;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(R)){$+=`bash: typeset: \`${R}': not a valid identifier
239
- `,O=1;continue}if(r||s?k(R):A(R),l){Qt(e,R);let q=e.state.env.get(R);q!==void 0&&q!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(q)?vc(e,R):q&&ks(e,q)&&go(e,R),v(R),i&&et(e,R),o&&xt(e,R);continue}if(d&&la(e,R),h&&ca(e,R),p&&ua(e,R),s){if(xe(e,R).length>0){$+=`bash: declare: ${R}: cannot convert indexed to associative array
240
- `,O=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(R),ln(e,R,"associative")}let j=De(e,R);!e.state.env.has(R)&&!j&&(r||s?ln(e,R,s?"associative":"indexed"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(R))),v(R),i&&et(e,R),o&&xt(e,R)}}return F("",$,O)}async function fa(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l==="-a")r=!0;else if(l==="-A")s=!0;else if(l==="-p")i=!0;else if(l==="--"){o.push(...t.slice(a+1));break}else l.startsWith("-")||o.push(l)}if(o.length===0){let a="",l=Array.from(e.state.readonlyVars||[]).sort();for(let c of l){let u=e.state.env.get(c);if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${c}="${f}"
241
- `}}return ne(a)}for(let a of o){let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(l){let d=l[1],h=l[2],p=de(e,d);if(p)return p;let m=Kt(h,n);if(e.state.associativeArrays?.has(d)){let E=Ks(h,n);e.executionScope.consumeWork(E.length,"readonly array append"),Dn(e,d,E.map(([S])=>S));for(let[S,g]of E)H(e,d,S,g,"associative")}else{e.executionScope.consumeWork(m.length,"readonly array append");let E=xe(e,d),S=0,g=e.state.env.get(d);E.length===0&&g!==void 0?(H(e,d,0,g),e.state.env.delete(d),S=1):E.length>0&&(S=Math.max(...E)+1),Dn(e,d,Array.from({length:m.length},(y,b)=>S+b));for(let y=0;y<m.length;y++)H(e,d,S+y,m[y])}et(e,d);continue}let c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c){let d=c[1],h=c[2],p=de(e,d);if(p)return p;let m=e.state.env.get(d)??"";e.state.env.set(d,nn([m,h],"",e.limits.maxStringLength,"readonly append")),et(e,d);continue}let u=ef(a,n);if(u.value===void 0&&!u.isArray){et(e,u.name);continue}let f=await tf(e,u,{makeReadonly:!0});if(f)return f}return se}function da(e){return e.state.directoryStack??=[],e.state.directoryStack}function Mr(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Um(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 ha(e,t){let n=da(e),r;for(let a=0;a<t.length;a++){let l=t[a];if(l==="--"){if(a+1<t.length){if(r!==void 0)return _(`bash: pushd: too many arguments
242
- `,2);r=t[a+1],a++}}else{if(l.startsWith("-")&&l!=="-")return _(`bash: pushd: ${l}: invalid option
243
- `,2);if(r!==void 0)return _(`bash: pushd: too many arguments
244
- `,2);r=l}}if(r===void 0){if(n.length<2)return _(`bash: pushd: no other directory
245
- `,1);let a=n[0];n[0]=n[1],n[1]=a,r=n[0]}let s;if(r.startsWith("/"))s=r;else if(r===".."){let a=e.state.cwd.split("/").filter(l=>l);a.pop(),s=`/${a.join("/")}`}else r==="."?s=e.state.cwd:r.startsWith("~")?s=(e.state.env.get("HOME")||"/")+r.slice(1):s=`${e.state.cwd}/${r}`;s=Um(s);try{if(!(await e.fs.stat(s)).isDirectory)return _(`bash: pushd: ${r}: Not a directory
246
- `,1)}catch{return _(`bash: pushd: ${r}: No such file or directory
247
- `,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")||"",o=`${[s,...n].map(a=>Mr(a,i)).join(" ")}
248
- `;return ne(o)}function pa(e,t){let n=da(e);for(let o of t)if(o!=="--")return o.startsWith("-")&&o!=="-"?_(`bash: popd: ${o}: invalid option
249
- `,2):_(`bash: popd: too many arguments
250
- `,2);if(n.length===0)return _(`bash: popd: directory stack empty
251
- `,1);let r=n.shift();if(!r)return _(`bash: popd: directory stack empty
252
- `,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(o=>Mr(o,s)).join(" ")}
253
- `;return ne(i)}function ma(e,t){let n=da(e),r=!1,s=!1,i=!1,o=!1;for(let u of t)if(u!=="--")if(u.startsWith("-"))for(let f of u.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,o=!0;else return _(`bash: dirs: -${f}: invalid option
254
- `,2);else return _(`bash: dirs: too many arguments
255
- `,1);if(r)return e.state.directoryStack=[],se;let a=[e.state.cwd,...n],l=e.state.env.get("HOME")||"",c;return o?(c=a.map((u,f)=>{let d=s?u:Mr(u,l);return` ${f} ${d}`}).join(`
239
+ `;return te(N)}let P=!0;for(let N of y)e.state.functions.has(N)||(P=!1);return F("","",P?0:1)}if(a&&y.length>0)return $f(e,y);if(a&&y.length===0)return Cf(e,{filterExport:o,filterReadonly:i,filterNameref:l,filterIndexedArray:r,filterAssocArray:s});if(y.length===0&&s&&!a)return Nf(e);if(y.length===0&&r&&!a)return Rf(e);if(y.length===0&&!a)return Of(e);let $="",R=0;for(let P of y){let N=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(N&&!u){let O=N[1],j=N[2],q=de(e,O);if(q)return q;if(s&&xe(e,O).length>0){$+=`bash: declare: ${O}: cannot convert indexed to associative array
240
+ `,R=1;continue}if((r||!s&&!r)&&e.state.associativeArrays?.has(O)){$+=`bash: declare: ${O}: cannot convert associative to indexed array
241
+ `,R=1;continue}let T=s&&j.includes("[")?Ys(j,n):void 0,_=T===void 0?Xt(j,{...n,maxElements:s?n.maxElements*2:n.maxElements}):void 0;if(e.executionScope.consumeWork(T?.length??_?.length??0,"declare array assignment"),k(O),s?(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(O),cn(e,O,"associative")):cn(e,O,"indexed"),be(e,O),e.state.env.delete(O),s&&j.includes("["))for(let[W,re]of T??[])G(e,O,W,wn(e,re),"associative");else if(s){let W=_??[];for(let re=0;re<W.length;re+=2){let J=W[re],We=re+1<W.length?W[re+1]:"";G(e,O,J,We,"associative")}}else{let W=_??[];if(W.some(J=>/^\[[^\]]+\]=/.test(J))){let J=0;for(let We of W){let bt=We.match(/^\[([^\]]+)\]=(.*)$/);if(bt){let Ut=bt[1],St=bt[2],At;if(/^-?\d+$/.test(Ut))At=Number.parseInt(Ut,10);else try{let jt=new Q,Td=se(jt,Ut);At=await ee(e,Td.expression)}catch{At=0}G(e,O,At,wn(e,St)),J=At+1}else G(e,O,J,We),J++}}else for(let J=0;J<W.length;J++)G(e,O,J,W[J])}A(O),i&&tt(e,O),o&&Ct(e,O);continue}if(c){let O=P.includes("=")?P.slice(0,P.indexOf("=")):P;if($c(e,O),!P.includes("="))continue}if(f){let O=P.includes("=")?P.slice(0,P.indexOf("=")):P;if(Rs(e,O),!P.includes("="))continue}let I=Zm(P);if(I){let{name:O,indexExpr:j,value:q}=I,T=de(e,O);if(T)return T;k(O);let _;try{let W=new Q,re=se(W,j);_=await ee(e,re.expression)}catch{let W=parseInt(j,10);_=Number.isNaN(W)?0:W}G(e,O,_,q),A(O),i&&tt(e,O),o&&Ct(e,O);continue}let z=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(z&&!u){let O=z[1],j=z[2],q=de(e,O);if(q)return q;k(O);let T=Xt(j,n);if(e.state.associativeArrays?.has(O)){let _=Ys(j,n);e.executionScope.consumeWork(_.length,"declare array append"),Tn(e,O,_.map(([W])=>W));for(let[W,re]of _)G(e,O,W,re,"associative")}else{e.executionScope.consumeWork(T.length,"declare array append");let _=xe(e,O),W=0,re=e.state.env.get(O);_.length===0&&re!==void 0?(G(e,O,0,re),e.state.env.delete(O),W=1):_.length>0&&(W=Math.max(..._)+1),Tn(e,O,Array.from({length:T.length},(J,We)=>W+We));for(let J=0;J<T.length;J++)G(e,O,W+J,T[J])}A(O),i&&tt(e,O),o&&Ct(e,O);continue}let X=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(X){let O=X[1],j=X[2],q=de(e,O);if(q)return q;v(O),d&&fa(e,O),h&&da(e,O),p&&ha(e,O);let _=xe(e,O).length>0||e.state.associativeArrays?.has(O);if(Wr(e,O)){let W=e.state.env.get(O)??"0",re=parseInt(W,10)||0,J=parseInt(await Df(e,j),10)||0;j=String(re+J),e.state.env.set(O,j)}else if(_){j=fr(e,O,j);let W=le(e,O,0)??"";G(e,O,0,rn([W,j],"",e.limits.maxStringLength,"declare append"))}else{j=fr(e,O,j);let W=e.state.env.get(O)??"";e.state.env.set(O,rn([W,j],"",e.limits.maxStringLength,"declare append"))}A(O),i&&tt(e,O),o&&Ct(e,O),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(O));continue}if(P.includes("=")){let O=P.indexOf("="),j=P.slice(0,O),q=P.slice(O+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(j)){$+=`bash: typeset: \`${j}': not a valid identifier
242
+ `,R=1;continue}let T=de(e,j);if(T)return T;if(v(j),l){if(q!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(q)){$+=`bash: declare: \`${q}': invalid variable name for name reference
243
+ `,R=1;continue}e.state.env.set(j,q),Kt(e,j),q!==""&&Ps(e,q)&&wo(e,j),A(j),i&&tt(e,j),o&&Ct(e,j);continue}if(d&&fa(e,j),h&&da(e,j),p&&ha(e,j),Wr(e,j)&&(q=await Df(e,q)),q=fr(e,j,q),fe(e,j)){let _=Ge(e,j);_&&_!==j?e.state.env.set(_,q):e.state.env.set(j,q)}else e.state.env.set(j,q);A(j),i&&tt(e,j),o&&Ct(e,j),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(j))}else{let O=P;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(O)){$+=`bash: typeset: \`${O}': not a valid identifier
244
+ `,R=1;continue}if(r||s?k(O):v(O),l){Kt(e,O);let q=e.state.env.get(O);q!==void 0&&q!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(q)?Cc(e,O):q&&Ps(e,q)&&wo(e,O),A(O),i&&tt(e,O),o&&Ct(e,O);continue}if(d&&fa(e,O),h&&da(e,O),p&&ha(e,O),s){if(xe(e,O).length>0){$+=`bash: declare: ${O}: cannot convert indexed to associative array
245
+ `,R=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(O),cn(e,O,"associative")}let j=Ie(e,O);!e.state.env.has(O)&&!j&&(r||s?cn(e,O,s?"associative":"indexed"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(O))),A(O),i&&tt(e,O),o&&Ct(e,O)}}return F("",$,R)}async function pa(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l==="-a")r=!0;else if(l==="-A")s=!0;else if(l==="-p")i=!0;else if(l==="--"){o.push(...t.slice(a+1));break}else l.startsWith("-")||o.push(l)}if(o.length===0){let a="",l=Array.from(e.state.readonlyVars||[]).sort();for(let c of l){let u=e.state.env.get(c);if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${c}="${f}"
246
+ `}}return te(a)}for(let a of o){let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(l){let d=l[1],h=l[2],p=de(e,d);if(p)return p;let m=Xt(h,n);if(e.state.associativeArrays?.has(d)){let E=Ys(h,n);e.executionScope.consumeWork(E.length,"readonly array append"),Tn(e,d,E.map(([b])=>b));for(let[b,y]of E)G(e,d,b,y,"associative")}else{e.executionScope.consumeWork(m.length,"readonly array append");let E=xe(e,d),b=0,y=e.state.env.get(d);E.length===0&&y!==void 0?(G(e,d,0,y),e.state.env.delete(d),b=1):E.length>0&&(b=Math.max(...E)+1),Tn(e,d,Array.from({length:m.length},(g,S)=>b+S));for(let g=0;g<m.length;g++)G(e,d,b+g,m[g])}tt(e,d);continue}let c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c){let d=c[1],h=c[2],p=de(e,d);if(p)return p;let m=e.state.env.get(d)??"";e.state.env.set(d,rn([m,h],"",e.limits.maxStringLength,"readonly append")),tt(e,d);continue}let u=sf(a,n);if(u.value===void 0&&!u.isArray){tt(e,u.name);continue}let f=await of(e,u,{makeReadonly:!0});if(f)return f}return ne}function ma(e){return e.state.directoryStack??=[],e.state.directoryStack}function Vr(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Qm(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 ya(e,t){let n=ma(e),r;for(let a=0;a<t.length;a++){let l=t[a];if(l==="--"){if(a+1<t.length){if(r!==void 0)return L(`bash: pushd: too many arguments
247
+ `,2);r=t[a+1],a++}}else{if(l.startsWith("-")&&l!=="-")return L(`bash: pushd: ${l}: invalid option
248
+ `,2);if(r!==void 0)return L(`bash: pushd: too many arguments
249
+ `,2);r=l}}if(r===void 0){if(n.length<2)return L(`bash: pushd: no other directory
250
+ `,1);let a=n[0];n[0]=n[1],n[1]=a,r=n[0]}let s;if(r.startsWith("/"))s=r;else if(r===".."){let a=e.state.cwd.split("/").filter(l=>l);a.pop(),s=`/${a.join("/")}`}else r==="."?s=e.state.cwd:r.startsWith("~")?s=(e.state.env.get("HOME")||"/")+r.slice(1):s=`${e.state.cwd}/${r}`;s=Qm(s);try{if(!(await e.fs.stat(s)).isDirectory)return L(`bash: pushd: ${r}: Not a directory
251
+ `,1)}catch{return L(`bash: pushd: ${r}: No such file or directory
252
+ `,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")||"",o=`${[s,...n].map(a=>Vr(a,i)).join(" ")}
253
+ `;return te(o)}function ga(e,t){let n=ma(e);for(let o of t)if(o!=="--")return o.startsWith("-")&&o!=="-"?L(`bash: popd: ${o}: invalid option
254
+ `,2):L(`bash: popd: too many arguments
255
+ `,2);if(n.length===0)return L(`bash: popd: directory stack empty
256
+ `,1);let r=n.shift();if(!r)return L(`bash: popd: directory stack empty
257
+ `,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(o=>Vr(o,s)).join(" ")}
258
+ `;return te(i)}function wa(e,t){let n=ma(e),r=!1,s=!1,i=!1,o=!1;for(let u of t)if(u!=="--")if(u.startsWith("-"))for(let f of u.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,o=!0;else return L(`bash: dirs: -${f}: invalid option
259
+ `,2);else return L(`bash: dirs: too many arguments
260
+ `,1);if(r)return e.state.directoryStack=[],ne;let a=[e.state.cwd,...n],l=e.state.env.get("HOME")||"",c;return o?(c=a.map((u,f)=>{let d=s?u:Vr(u,l);return` ${f} ${d}`}).join(`
256
261
  `),c+=`
257
- `):i?c=a.map(u=>s?u:Mr(u,l)).join(`
262
+ `):i?c=a.map(u=>s?u:Vr(u,l)).join(`
258
263
  `)+`
259
- `:c=a.map(u=>s?u:Mr(u,l)).join(" ")+`
260
- `,ne(c)}async function ya(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 _(`bash: eval: ${l}: invalid option
264
+ `:c=a.map(u=>s?u:Vr(u,l)).join(" ")+`
265
+ `,te(c)}async function Ea(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
261
266
  eval: usage: eval [arg ...]
262
- `,2)}if(s.length===0)return se;let i=s.join(" ");if(i.trim()==="")return se;let o=e.state.groupStdin,a=r||n!==void 0&&n!=="";a&&(e.state.groupStdin=n??"");try{let l=qe(i);return await e.executeScript(l)}catch(l){if(l instanceof tt||l instanceof nt||l instanceof We||l instanceof G||l instanceof Oe)throw l;if(l.name==="ParseException")return _(`bash: eval: ${l.message}
263
- `);throw l}finally{(a||o!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=o)}}function ga(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
264
- `,n=2;else{let i=BigInt(s);n=Number((i%256n+256n)%256n)}}throw new G(n,"",r)}function wa(e,t){let n=!1,r=[];for(let o of t)o==="-n"?n=!0:o==="-p"||o==="--"||r.push(o);if(r.length===0&&!n){let o="",a=e.state.exportedVars??new Set,l=Array.from(a).sort();for(let c of l){let u=e.state.env.get(c);u!==void 0&&(o+=`declare -x ${c}=${Lr(u)}
265
- `)}return ne(o)}if(n){for(let o of r){let a,l;if(o.includes("=")){let c=o.indexOf("=");a=o.slice(0,c),l=o.slice(c+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return F("",`bash: export: \`${o}': not a valid identifier
266
- `,1);l!==void 0&&(de(e,a),e.state.env.set(a,l)),Cs(e,a)}return se}let s="",i=0;for(let o of r){let a,l,c=!1,u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)a=u[1],l=u[2],c=!0;else if(o.includes("=")){let f=o.indexOf("=");a=o.slice(0,f),l=o.slice(f+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${o}': not a valid identifier
267
- `,i=1;continue}if(l!==void 0)if(de(e,a),c){let f=e.state.env.get(a)??"";e.state.env.set(a,f+l)}else e.state.env.set(a,l);else e.state.env.has(a)||e.state.env.set(a,"");xt(e,a)}return F("",s,i)}function ui(e,t){if(t.length<2)return _(`bash: getopts: usage: getopts optstring name [arg ...]
268
- `);let n=t[0],r=t[1],s=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=n.startsWith(":"),o=i?n.slice(1):n,a;if(t.length>2)a=t.slice(2);else{let m=Number.parseInt(e.state.env.get("#")||"0",10);a=[];for(let E=1;E<=m;E++)a.push(e.state.env.get(String(E))||"")}let l=Number.parseInt(e.state.env.get("OPTIND")||"1",10);l<1&&(l=1);let c=Number.parseInt(e.state.env.get("__GETOPTS_CHARINDEX")||"0",10);if(e.state.env.set("OPTARG",""),l>a.length)return s||e.state.env.set(r,"?"),e.state.env.set("OPTIND",String(a.length+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:1,stdout:"",stderr:""};let u=a[l-1];if(!u||u==="-"||!u.startsWith("-"))return s||e.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};if(u==="--")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=c===0?1:c,d=u[f];if(!d)return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),ui(e,t);let h=o.indexOf(d);if(h===-1){let m="";return i?e.state.env.set("OPTARG",d):m=`bash: illegal option -- ${d}
267
+ `,2)}if(s.length===0)return ne;let i=s.join(" ");if(i.trim()==="")return ne;let o=e.state.groupStdin,a=r||n!==void 0&&n!=="";a&&(e.state.groupStdin=n??"");try{let l=He(i);return await e.executeScript(l)}catch(l){if(l instanceof nt||l instanceof rt||l instanceof Ve||l instanceof H||l instanceof Oe)throw l;if(l.name==="ParseException")return L(`bash: eval: ${l.message}
268
+ `);throw l}finally{(a||o!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=o)}}function ba(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
269
+ `,n=2;else{let i=BigInt(s);n=Number((i%256n+256n)%256n)}}throw new H(n,"",r)}function Sa(e,t){let n=!1,r=[];for(let o of t)o==="-n"?n=!0:o==="-p"||o==="--"||r.push(o);if(r.length===0&&!n){let o="",a=e.state.exportedVars??new Set,l=Array.from(a).sort();for(let c of l){let u=e.state.env.get(c);u!==void 0&&(o+=`declare -x ${c}=${Br(u)}
270
+ `)}return te(o)}if(n){for(let o of r){let a,l;if(o.includes("=")){let c=o.indexOf("=");a=o.slice(0,c),l=o.slice(c+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return F("",`bash: export: \`${o}': not a valid identifier
271
+ `,1);l!==void 0&&(de(e,a),e.state.env.set(a,l)),Rs(e,a)}return ne}let s="",i=0;for(let o of r){let a,l,c=!1,u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)a=u[1],l=u[2],c=!0;else if(o.includes("=")){let f=o.indexOf("=");a=o.slice(0,f),l=o.slice(f+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${o}': not a valid identifier
272
+ `,i=1;continue}if(l!==void 0)if(de(e,a),c){let f=e.state.env.get(a)??"";e.state.env.set(a,f+l)}else e.state.env.set(a,l);else e.state.env.has(a)||e.state.env.set(a,"");Ct(e,a)}return F("",s,i)}function di(e,t){if(t.length<2)return L(`bash: getopts: usage: getopts optstring name [arg ...]
273
+ `);let n=t[0],r=t[1],s=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=n.startsWith(":"),o=i?n.slice(1):n,a;if(t.length>2)a=t.slice(2);else{let m=Number.parseInt(e.state.env.get("#")||"0",10);a=[];for(let E=1;E<=m;E++)a.push(e.state.env.get(String(E))||"")}let l=Number.parseInt(e.state.env.get("OPTIND")||"1",10);l<1&&(l=1);let c=Number.parseInt(e.state.env.get("__GETOPTS_CHARINDEX")||"0",10);if(e.state.env.set("OPTARG",""),l>a.length)return s||e.state.env.set(r,"?"),e.state.env.set("OPTIND",String(a.length+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:1,stdout:"",stderr:""};let u=a[l-1];if(!u||u==="-"||!u.startsWith("-"))return s||e.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};if(u==="--")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=c===0?1:c,d=u[f];if(!d)return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),di(e,t);let h=o.indexOf(d);if(h===-1){let m="";return i?e.state.env.set("OPTARG",d):m=`bash: illegal option -- ${d}
269
274
  `,s||e.state.env.set(r,"?"),f+1<u.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(h+1<o.length&&o[h+1]===":")if(f+1<u.length)e.state.env.set("OPTARG",u.slice(f+1)),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0");else{if(l>=a.length){let m="";return i?(e.state.env.set("OPTARG",d),s||e.state.env.set(r,":")):(m=`bash: option requires an argument -- ${d}
270
- `,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",a[l]),e.state.env.set("OPTIND",String(l+2)),e.state.env.set("__GETOPTS_CHARINDEX","0")}else f+1<u.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 Ea(e,t){e.state.hashTable||(e.state.hashTable=new Map);let n=!1,r=!1,s=!1,i=!1,o=!1,a="",l=[],c=0;for(;c<t.length;){let p=t[c];if(p==="--"){c++,l.push(...t.slice(c));break}if(p==="-r")n=!0,c++;else if(p==="-d")r=!0,c++;else if(p==="-l")s=!0,c++;else if(p==="-t")o=!0,c++;else if(p==="-p"){if(i=!0,c++,c>=t.length)return _(`bash: hash: -p: option requires an argument
271
- `,1);a=t[c],c++}else if(p.startsWith("-")&&p.length>1){for(let m of p.slice(1))if(m==="r")n=!0;else if(m==="d")r=!0;else if(m==="l")s=!0;else if(m==="t")o=!0;else return m==="p"?_(`bash: hash: -p: option requires an argument
272
- `,1):_(`bash: hash: -${m}: invalid option
273
- `,1);c++}else l.push(p),c++}if(n)return e.state.hashTable.clear(),se;if(r){if(l.length===0)return _(`bash: hash: -d: option requires an argument
275
+ `,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",a[l]),e.state.env.set("OPTIND",String(l+2)),e.state.env.set("__GETOPTS_CHARINDEX","0")}else f+1<u.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 Aa(e,t){e.state.hashTable||(e.state.hashTable=new Map);let n=!1,r=!1,s=!1,i=!1,o=!1,a="",l=[],c=0;for(;c<t.length;){let p=t[c];if(p==="--"){c++,l.push(...t.slice(c));break}if(p==="-r")n=!0,c++;else if(p==="-d")r=!0,c++;else if(p==="-l")s=!0,c++;else if(p==="-t")o=!0,c++;else if(p==="-p"){if(i=!0,c++,c>=t.length)return L(`bash: hash: -p: option requires an argument
276
+ `,1);a=t[c],c++}else if(p.startsWith("-")&&p.length>1){for(let m of p.slice(1))if(m==="r")n=!0;else if(m==="d")r=!0;else if(m==="l")s=!0;else if(m==="t")o=!0;else return m==="p"?L(`bash: hash: -p: option requires an argument
277
+ `,1):L(`bash: hash: -${m}: invalid option
278
+ `,1);c++}else l.push(p),c++}if(n)return e.state.hashTable.clear(),ne;if(r){if(l.length===0)return L(`bash: hash: -d: option requires an argument
274
279
  `,1);let p=!1,m="";for(let E of l)e.state.hashTable.has(E)?e.state.hashTable.delete(E):(m+=`bash: hash: ${E}: not found
275
- `,p=!0);return p?_(m,1):se}if(o){if(l.length===0)return _(`bash: hash: -t: option requires an argument
276
- `,1);let p="",m=!1,E="";for(let S of l){let g=e.state.hashTable.get(S);g?l.length>1?p+=`${S} ${g}
277
- `:p+=`${g}
278
- `:(E+=`bash: hash: ${S}: not found
279
- `,m=!0)}return m?{exitCode:1,stdout:p,stderr:E}:ne(p)}if(i){if(l.length===0)return _(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
280
- `,1);let p=l[0];return e.state.hashTable.set(p,a),se}if(l.length===0){if(e.state.hashTable.size===0)return ne(`hash: hash table empty
281
- `);let p="";if(s)for(let[m,E]of e.state.hashTable){let S=m.startsWith("-")?" --":"";p+=`builtin hash -p ${ve(E)}${S} ${ve(m)}
280
+ `,p=!0);return p?L(m,1):ne}if(o){if(l.length===0)return L(`bash: hash: -t: option requires an argument
281
+ `,1);let p="",m=!1,E="";for(let b of l){let y=e.state.hashTable.get(b);y?l.length>1?p+=`${b} ${y}
282
+ `:p+=`${y}
283
+ `:(E+=`bash: hash: ${b}: not found
284
+ `,m=!0)}return m?{exitCode:1,stdout:p,stderr:E}:te(p)}if(i){if(l.length===0)return L(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
285
+ `,1);let p=l[0];return e.state.hashTable.set(p,a),ne}if(l.length===0){if(e.state.hashTable.size===0)return te(`hash: hash table empty
286
+ `);let p="";if(s)for(let[m,E]of e.state.hashTable){let b=m.startsWith("-")?" --":"";p+=`builtin hash -p ${ve(E)}${b} ${ve(m)}
282
287
  `}else{p=`hits command
283
288
  `;for(let[,m]of e.state.hashTable)p+=` 1 ${m}
284
- `}return ne(p)}let u=!1,f="",h=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let p of l){if(p.includes("/")){f+=`bash: hash: ${p}: cannot use / in name
285
- `,u=!0;continue}let m=!1;for(let E of h){if(!E)continue;let S=`${E}/${p}`;if(await e.fs.exists(S)){e.state.hashTable.set(p,S),m=!0;break}}m||(f+=`bash: hash: ${p}: not found
286
- `,u=!0)}return u?_(f,1):se}var Nf=new Map([[":",[": [arguments]",`Null command.
289
+ `}return te(p)}let u=!1,f="",h=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let p of l){if(p.includes("/")){f+=`bash: hash: ${p}: cannot use / in name
290
+ `,u=!0;continue}let m=!1;for(let E of h){if(!E)continue;let b=`${E}/${p}`;if(await e.fs.exists(b)){e.state.hashTable.set(p,b),m=!0;break}}m||(f+=`bash: hash: ${p}: not found
291
+ `,u=!0)}return u?L(f,1):ne}var If=new Map([[":",[": [arguments]",`Null command.
287
292
  No effect; the command does nothing.
288
293
  Exit Status:
289
294
  Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
@@ -633,37 +638,37 @@ eval: usage: eval [arg ...]
633
638
  job specification, and reports its termination status.
634
639
  Exit Status:
635
640
  Returns the status of the last ID; fails if ID is invalid or an invalid
636
- option is given.`]]]),Rf=[...Nf.keys()].sort();function ba(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 c=1;c<l.length;c++){let u=l[c];if(u==="s")n=!0;else return _(`bash: help: -${u}: invalid option
637
- `,2)}s++}else r.push(l),s++}if(r.length===0)return qm();let i="",o=!1,a="";for(let l of r){let c=jm(l);if(c.length===0){a+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
638
- `,o=!0;continue}for(let u of c){let f=Nf.get(u);if(!f)continue;let[d,h]=f;n?i+=`${u}: ${d}
641
+ option is given.`]]]),Tf=[...If.keys()].sort();function va(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 c=1;c<l.length;c++){let u=l[c];if(u==="s")n=!0;else return L(`bash: help: -${u}: invalid option
642
+ `,2)}s++}else r.push(l),s++}if(r.length===0)return Xm();let i="",o=!1,a="";for(let l of r){let c=Km(l);if(c.length===0){a+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
643
+ `,o=!0;continue}for(let u of c){let f=If.get(u);if(!f)continue;let[d,h]=f;n?i+=`${u}: ${d}
639
644
  `:i+=`${u}: ${d}
640
645
  ${h}
641
- `}}return{exitCode:o?1:0,stdout:i,stderr:a}}function jm(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),n=ge(`^${t}$`);return Rf.filter(r=>n.test(r))}function qm(){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=Rf.slice(),r=Math.ceil(n.length/2);for(let s=0;s<r;s++){let i=n[s]||"",o=n[s+r]||"",a=i.padEnd(t);e.push(o?`${a}${o}`:i)}return ne(`${e.join(`
646
+ `}}return{exitCode:o?1:0,stdout:i,stderr:a}}function Km(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),n=ge(`^${t}$`);return Tf.filter(r=>n.test(r))}function Xm(){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=Tf.slice(),r=Math.ceil(n.length/2);for(let s=0;s<r;s++){let i=n[s]||"",o=n[s+r]||"",a=i.padEnd(t);e.push(o?`${a}${o}`:i)}return te(`${e.join(`
642
647
  `)}
643
- `)}function Gm(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 Sa(e,t){if(t.length===0)return _(`bash: let: expression expected
644
- `);let n=Gm(t),r=0;for(let s of n)try{let o=qe(`(( ${s} ))`).statements[0];if(o&&o.pipelines.length>0&&o.pipelines[0].commands.length>0){let a=o.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await ee(e,a.expression.expression))}}catch(i){return _(`bash: let: ${s}: ${i.message}
645
- `)}return F("","",r===0?1:0)}async function Aa(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength};if(e.state.localScopes.length===0)return _(`bash: local: can only be used in a function
646
- `);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 h=$e(e,d);s.set(d,h?je(h):void 0)}},o="",a=0,l=!1,c=!1,u=!1,f=[];for(let d of t)if(d==="-n")l=!0;else if(d==="-a")c=!0;else if(d==="-p")u=!0;else if(d.startsWith("-")&&!d.includes("="))for(let h of d.slice(1))h==="n"?l=!0:h==="a"?c=!0:h==="p"&&(u=!0);else f.push(d);if(f.length===0){let d="",h=Array.from(r.keys()).sort();for(let p of h){let m=e.state.env.get(p);m!==void 0&&(d+=`${p}=${m}
647
- `)}return F(d,"",0)}for(let d of f){let h,p,m=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(m){h=m[1];let b=m[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(h)){o+=`bash: local: \`${d}': not a valid identifier
648
- `,a=1;continue}de(e,h,"bash");let A=Kt(b,n);e.executionScope.consumeWork(A.length,"local array assignment"),i(h),be(e,h),ln(e,h,"indexed");for(let k=0;k<A.length;k++)H(e,h,k,A[k]);bn(e,h),l&&Qt(e,h);continue}let E=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(E){h=E[1];let b=E[2];de(e,h,"bash"),i(h);let A=Kt(b,n);e.executionScope.consumeWork(A.length,"local array append");let k=xe(e,h),v=0,$=e.state.env.get(h);k.length===0&&$!==void 0?(H(e,h,0,$),e.state.env.delete(h),v=1):k.length>0&&(v=Math.max(...k)+1),Dn(e,h,Array.from({length:A.length},(O,P)=>v+P));for(let O=0;O<A.length;O++)H(e,h,v+O,A[O]);bn(e,h),l&&Qt(e,h);continue}let S=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(S){h=S[1];let b=S[2];de(e,h,"bash"),r.has(h)||r.set(h,e.state.env.get(h));let A=e.state.env.get(h)??"";e.state.env.set(h,nn([A,b],"",e.limits.maxStringLength,"local append")),bn(e,h),l&&Qt(e,h);continue}let g=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(g){h=g[1];let b=g[2],A=g[3];de(e,h,"bash"),i(h);let k;try{let v=new Q,$=oe(v,b);k=await ee(e,$.expression)}catch{let v=parseInt(b,10);k=Number.isNaN(v)?0:v}H(e,h,k,A),bn(e,h),l&&Qt(e,h);continue}if(d.includes("=")){let b=d.indexOf("=");h=d.slice(0,b),p=d.slice(b+1)}else h=d;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(h)){o+=`bash: local: \`${d}': not a valid identifier
649
- `,a=1;continue}let y=r.has(h);if(p!==void 0){let b=e.state.env.get(h);if(e.state.tempEnvBindings){let A=e.state.accessedTempEnvVars?.has(h),k=e.state.mutatedTempEnvVars?.has(h);if(!A&&!k)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let $=e.state.tempEnvBindings[v];if($.has(h)){b=$.get(h);break}}}nf(e,h,b)}if(!y){let b=e.state.env.get(h);if(e.state.tempEnvBindings)for(let A=e.state.tempEnvBindings.length-1;A>=0;A--){let k=e.state.tempEnvBindings[A];if(k.has(h)){b=k.get(h);break}}r.set(h,b),c&&i(h)}if(c&&p===void 0)be(e,h),ln(e,h,"indexed");else if(p!==void 0){if(de(e,h,"bash"),l&&p!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(p)){o+=`bash: local: \`${p}': invalid variable name for name reference
650
- `,a=1;continue}e.state.env.set(h,p),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(h))}else{let b=e.state.tempEnvBindings?.some(A=>A.has(h));!y&&!b&&e.state.env.delete(h)}bn(e,h),l&&Qt(e,h)}return F("",o,a)}function fi(e,t,n){let r=`
651
- `,s=0,i=0,o=0,a=!1,l="MAPFILE",c=0;for(;c<t.length;){let g=t[c];g==="-d"&&c+1<t.length?(r=t[c+1]===""?"\0":t[c+1]||`
652
- `,c+=2):g==="-n"&&c+1<t.length?(s=Number.parseInt(t[c+1],10)||0,c+=2):g==="-O"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):g==="-s"&&c+1<t.length?(o=Number.parseInt(t[c+1],10)||0,c+=2):g==="-t"?(a=!0,c++):g==="-u"||g==="-C"||g==="-c"?c+=2:(g.startsWith("-")||(l=g),c++)}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l))return F("",`mapfile: ${l}: not a valid identifier
648
+ `)}function Ym(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 ka(e,t){if(t.length===0)return L(`bash: let: expression expected
649
+ `);let n=Ym(t),r=0;for(let s of n)try{let o=He(`(( ${s} ))`).statements[0];if(o&&o.pipelines.length>0&&o.pipelines[0].commands.length>0){let a=o.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await ee(e,a.expression.expression))}}catch(i){return L(`bash: let: ${s}: ${i.message}
650
+ `)}return F("","",r===0?1:0)}async function xa(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
651
+ `);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 h=$e(e,d);s.set(d,h?qe(h):void 0)}},o="",a=0,l=!1,c=!1,u=!1,f=[];for(let d of t)if(d==="-n")l=!0;else if(d==="-a")c=!0;else if(d==="-p")u=!0;else if(d.startsWith("-")&&!d.includes("="))for(let h of d.slice(1))h==="n"?l=!0:h==="a"?c=!0:h==="p"&&(u=!0);else f.push(d);if(f.length===0){let d="",h=Array.from(r.keys()).sort();for(let p of h){let m=e.state.env.get(p);m!==void 0&&(d+=`${p}=${m}
652
+ `)}return F(d,"",0)}for(let d of f){let h,p,m=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(m){h=m[1];let S=m[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(h)){o+=`bash: local: \`${d}': not a valid identifier
653
+ `,a=1;continue}de(e,h,"bash");let v=Xt(S,n);e.executionScope.consumeWork(v.length,"local array assignment"),i(h),be(e,h),cn(e,h,"indexed");for(let k=0;k<v.length;k++)G(e,h,k,v[k]);An(e,h),l&&Kt(e,h);continue}let E=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(E){h=E[1];let S=E[2];de(e,h,"bash"),i(h);let v=Xt(S,n);e.executionScope.consumeWork(v.length,"local array append");let k=xe(e,h),A=0,$=e.state.env.get(h);k.length===0&&$!==void 0?(G(e,h,0,$),e.state.env.delete(h),A=1):k.length>0&&(A=Math.max(...k)+1),Tn(e,h,Array.from({length:v.length},(R,P)=>A+P));for(let R=0;R<v.length;R++)G(e,h,A+R,v[R]);An(e,h),l&&Kt(e,h);continue}let b=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(b){h=b[1];let S=b[2];de(e,h,"bash"),r.has(h)||r.set(h,e.state.env.get(h));let v=e.state.env.get(h)??"";e.state.env.set(h,rn([v,S],"",e.limits.maxStringLength,"local append")),An(e,h),l&&Kt(e,h);continue}let y=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(y){h=y[1];let S=y[2],v=y[3];de(e,h,"bash"),i(h);let k;try{let A=new Q,$=se(A,S);k=await ee(e,$.expression)}catch{let A=parseInt(S,10);k=Number.isNaN(A)?0:A}G(e,h,k,v),An(e,h),l&&Kt(e,h);continue}if(d.includes("=")){let S=d.indexOf("=");h=d.slice(0,S),p=d.slice(S+1)}else h=d;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(h)){o+=`bash: local: \`${d}': not a valid identifier
654
+ `,a=1;continue}let g=r.has(h);if(p!==void 0){let S=e.state.env.get(h);if(e.state.tempEnvBindings){let v=e.state.accessedTempEnvVars?.has(h),k=e.state.mutatedTempEnvVars?.has(h);if(!v&&!k)for(let A=e.state.tempEnvBindings.length-1;A>=0;A--){let $=e.state.tempEnvBindings[A];if($.has(h)){S=$.get(h);break}}}af(e,h,S)}if(!g){let S=e.state.env.get(h);if(e.state.tempEnvBindings)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let k=e.state.tempEnvBindings[v];if(k.has(h)){S=k.get(h);break}}r.set(h,S),c&&i(h)}if(c&&p===void 0)be(e,h),cn(e,h,"indexed");else if(p!==void 0){if(de(e,h,"bash"),l&&p!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(p)){o+=`bash: local: \`${p}': invalid variable name for name reference
655
+ `,a=1;continue}e.state.env.set(h,p),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(h))}else{let S=e.state.tempEnvBindings?.some(v=>v.has(h));!g&&!S&&e.state.env.delete(h)}An(e,h),l&&Kt(e,h)}return F("",o,a)}function hi(e,t,n){let r=`
656
+ `,s=0,i=0,o=0,a=!1,l="MAPFILE",c=0;for(;c<t.length;){let y=t[c];y==="-d"&&c+1<t.length?(r=t[c+1]===""?"\0":t[c+1]||`
657
+ `,c+=2):y==="-n"&&c+1<t.length?(s=Number.parseInt(t[c+1],10)||0,c+=2):y==="-O"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):y==="-s"&&c+1<t.length?(o=Number.parseInt(t[c+1],10)||0,c+=2):y==="-t"?(a=!0,c++):y==="-u"||y==="-C"||y==="-c"?c+=2:(y.startsWith("-")||(l=y),c++)}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l))return F("",`mapfile: ${l}: not a valid identifier
653
658
  `,1);if(!Number.isSafeInteger(i)||i<0)return F("",`mapfile: invalid array origin
654
- `,1);de(e,l,"mapfile");let u=n;!u&&e.state.groupStdin!==void 0&&(u=e.state.groupStdin);let f=[],d=0,h=0,p=0,m=e.limits.maxArrayElements,E=g=>{if(W(g)>e.limits.maxStringLength)throw new C(`mapfile: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");f.push(g)};for(;d<u.length;){e.executionScope.consumeWork(1,"mapfile input");let g=u.indexOf(r,d);if(g===-1){if(d<u.length){if(p<o)p++;else if(s===0||h<s){let A=u.slice(d),k=A.indexOf("\0");if(k!==-1&&(A=A.substring(0,k)),f.length>=m)return F("",`mapfile: array element limit exceeded (${m})
655
- `,1);E(A),h++}}break}let y=u.slice(d,g),b=y.indexOf("\0");if(b!==-1&&(y=y.substring(0,b)),!a&&r!=="\0"&&(y+=r),d=g+r.length,p<o){p++;continue}if(s>0&&h>=s)break;if(f.length>=m)return F("",`mapfile: array element limit exceeded (${m})
656
- `,1);E(y),h++}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 F("",`mapfile: array element limit exceeded (${m})
657
- `,1);i===0&&be(e,l);for(let g=0;g<f.length;g++)H(e,l,i+g,f[g]);return e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=""),{...F("","",0),internalStdinConsumed:u.length}}function va(e,t,n,r=-1){let s=!1,i=`
658
- `,o="",a=-1,l=-1,c=null,u=-1,f=-1,d=[],h=0,p=!1,m=(I,T)=>{let B=1;for(;B<I.length;){let ie=I[B];if(ie==="r")s=!0,B++;else if(ie==="s")B++;else{if(ie==="d")return B+1<I.length?(i=I.substring(B+1),{nextArgIndex:T+1}):T+1<t.length?(i=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(ie==="n"){if(B+1<I.length){let J=I.substring(B+1);return a=Number.parseInt(J,10),(Number.isNaN(a)||a<0)&&(p=!0,a=0),{nextArgIndex:T+1}}else if(T+1<t.length)return a=Number.parseInt(t[T+1],10),(Number.isNaN(a)||a<0)&&(p=!0,a=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(ie==="N"){if(B+1<I.length){let J=I.substring(B+1);return l=Number.parseInt(J,10),(Number.isNaN(l)||l<0)&&(p=!0,l=0),{nextArgIndex:T+1}}else if(T+1<t.length)return l=Number.parseInt(t[T+1],10),(Number.isNaN(l)||l<0)&&(p=!0,l=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else{if(ie==="a")return B+1<I.length?(c=I.substring(B+1),{nextArgIndex:T+1}):T+1<t.length?(c=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(ie==="p")return B+1<I.length?(o=I.substring(B+1),{nextArgIndex:T+1}):T+1<t.length?(o=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(ie==="u"){if(B+1<I.length){let J=I.substring(B+1);return u=Number.parseInt(J,10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:T+1}}else if(T+1<t.length)return u=Number.parseInt(t[T+1],10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(ie==="t"){if(B+1<I.length){let J=I.substring(B+1);return f=Number.parseFloat(J),Number.isNaN(f)&&(f=0),{nextArgIndex:T+1}}else if(T+1<t.length)return f=Number.parseFloat(t[T+1]),Number.isNaN(f)&&(f=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(ie==="e"||ie==="i"||ie==="P"){if(ie==="i"&&T+1<t.length)return{nextArgIndex:T+2};B++}else B++}}}return{nextArgIndex:T+1}};for(;h<t.length;){let I=t[h];if(I.startsWith("-")&&I.length>1&&I!=="--"){let T=m(I,h);if(T.nextArgIndex===-1)return{stdout:"",stderr:"",exitCode:2};if(T.nextArgIndex===-2)return{stdout:"",stderr:"",exitCode:1};h=T.nextArgIndex}else if(I==="--")for(h++;h<t.length;)d.push(t[h]),h++;else d.push(I),h++}if(p)return F("","",1);d.length===0&&c===null&&d.push("REPLY");let E=new Set;c&&E.add(c);for(let I of d)E.add(I);l>=0&&d.length===0&&E.add("REPLY");for(let I of E){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(I))return F("",`bash: read: \`${I}': not a valid identifier
659
- `,1);de(e,I,"bash")}if(f===0){if(c)be(e,c);else{for(let I of d)e.state.env.set(I,"");d.length===0&&e.state.env.set("REPLY","")}return F("","",0)}if(f<0&&f!==-1)return F("","",1);let S=n,g=lt(e,u),y=u>0&&!(g?.kind==="dup-in"&&g.sourceFd===0);if(y){let I=ni(e,u);if("error"in I){let B=I.error==="write-only"||u===1||u===2?`bash: read: read error: ${u}: Bad file descriptor
659
+ `,1);de(e,l,"mapfile");let u=n;!u&&e.state.groupStdin!==void 0&&(u=e.state.groupStdin);let f=[],d=0,h=0,p=0,m=e.limits.maxArrayElements,E=y=>{if(B(y)>e.limits.maxStringLength)throw new C(`mapfile: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");f.push(y)};for(;d<u.length;){e.executionScope.consumeWork(1,"mapfile input");let y=u.indexOf(r,d);if(y===-1){if(d<u.length){if(p<o)p++;else if(s===0||h<s){let v=u.slice(d),k=v.indexOf("\0");if(k!==-1&&(v=v.substring(0,k)),f.length>=m)return F("",`mapfile: array element limit exceeded (${m})
660
+ `,1);E(v),h++}}break}let g=u.slice(d,y),S=g.indexOf("\0");if(S!==-1&&(g=g.substring(0,S)),!a&&r!=="\0"&&(g+=r),d=y+r.length,p<o){p++;continue}if(s>0&&h>=s)break;if(f.length>=m)return F("",`mapfile: array element limit exceeded (${m})
661
+ `,1);E(g),h++}let b=new Set(i===0?[]:e.state.arrays?.get(l)?.elements.keys()??[]);for(let y=0;y<f.length;y++)if(b.add(String(i+y)),b.size>m)return F("",`mapfile: array element limit exceeded (${m})
662
+ `,1);i===0&&be(e,l);for(let y=0;y<f.length;y++)G(e,l,i+y,f[y]);return e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=""),{...F("","",0),internalStdinConsumed:u.length}}function Pa(e,t,n,r=-1){let s=!1,i=`
663
+ `,o="",a=-1,l=-1,c=null,u=-1,f=-1,d=[],h=0,p=!1,m=(T,_)=>{let W=1;for(;W<T.length;){let re=T[W];if(re==="r")s=!0,W++;else if(re==="s")W++;else{if(re==="d")return W+1<T.length?(i=T.substring(W+1),{nextArgIndex:_+1}):_+1<t.length?(i=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(re==="n"){if(W+1<T.length){let J=T.substring(W+1);return a=Number.parseInt(J,10),(Number.isNaN(a)||a<0)&&(p=!0,a=0),{nextArgIndex:_+1}}else if(_+1<t.length)return a=Number.parseInt(t[_+1],10),(Number.isNaN(a)||a<0)&&(p=!0,a=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(re==="N"){if(W+1<T.length){let J=T.substring(W+1);return l=Number.parseInt(J,10),(Number.isNaN(l)||l<0)&&(p=!0,l=0),{nextArgIndex:_+1}}else if(_+1<t.length)return l=Number.parseInt(t[_+1],10),(Number.isNaN(l)||l<0)&&(p=!0,l=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else{if(re==="a")return W+1<T.length?(c=T.substring(W+1),{nextArgIndex:_+1}):_+1<t.length?(c=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(re==="p")return W+1<T.length?(o=T.substring(W+1),{nextArgIndex:_+1}):_+1<t.length?(o=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(re==="u"){if(W+1<T.length){let J=T.substring(W+1);return u=Number.parseInt(J,10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:_+1}}else if(_+1<t.length)return u=Number.parseInt(t[_+1],10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(re==="t"){if(W+1<T.length){let J=T.substring(W+1);return f=Number.parseFloat(J),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};W++}else W++}}}return{nextArgIndex:_+1}};for(;h<t.length;){let T=t[h];if(T.startsWith("-")&&T.length>1&&T!=="--"){let _=m(T,h);if(_.nextArgIndex===-1)return{stdout:"",stderr:"",exitCode:2};if(_.nextArgIndex===-2)return{stdout:"",stderr:"",exitCode:1};h=_.nextArgIndex}else if(T==="--")for(h++;h<t.length;)d.push(t[h]),h++;else d.push(T),h++}if(p)return F("","",1);d.length===0&&c===null&&d.push("REPLY");let E=new Set;c&&E.add(c);for(let T of d)E.add(T);l>=0&&d.length===0&&E.add("REPLY");for(let T of E){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(T))return F("",`bash: read: \`${T}': not a valid identifier
664
+ `,1);de(e,T,"bash")}if(f===0){if(c)be(e,c);else{for(let T of d)e.state.env.set(T,"");d.length===0&&e.state.env.set("REPLY","")}return F("","",0)}if(f<0&&f!==-1)return F("","",1);let b=n,y=ut(e,u),g=u>0&&!(y?.kind==="dup-in"&&y.sourceFd===0);if(g){let T=si(e,u);if("error"in T){let W=T.error==="write-only"||u===1||u===2?`bash: read: read error: ${u}: Bad file descriptor
660
665
  `:`bash: read: ${u}: invalid file descriptor: Bad file descriptor
661
- `;return F("",B,1)}S=I.content}else!S&&e.state.groupStdin!==void 0&&(S=e.state.groupStdin);let b=i===""?"\0":i,A="",k=0,v=I=>{let T=W(I);if(T>e.limits.maxStringLength-k)throw new C(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");A+=I,k+=T},$=I=>{if(W(I)>e.limits.maxStringLength)throw new C(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")},O=0,P=!0,N=I=>{y?An(e,u,I):r>=0?An(e,r,I):e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=S.substring(I),e.state.groupStdinSourceFd!==void 0&&An(e,e.state.groupStdinSourceFd,I))};if(l>=0){let I=Math.min(l,S.length);A=S.substring(0,I),$(A),O=I,P=I>=l,N(O);let T=d[0]||"REPLY";e.state.env.set(T,A);for(let B=1;B<d.length;B++)e.state.env.set(d[B],"");return F("","",P?0:1)}else if(a>=0){let I=0,T=0,B=!1;for(;T<S.length&&I<a;){let ie=S[T];if(ie===b){O=T+1,B=!0;break}if(!s&&ie==="\\"&&T+1<S.length){let J=S[T+1];if(J===b&&b===`
662
- `){T+=2,O=T;continue}if(J===b){T+=2,I++,v(J),O=T;continue}v(J),T+=2,I++,O=T}else v(ie),T++,I++,O=T}P=I>=a||B,N(O)}else{O=0;let I=0;for(;I<S.length;){let T=S[I];if(T===b){O=I+b.length,P=!0;break}if(!s&&T==="\\"&&I+1<S.length){let B=S[I+1];if(B===`
663
- `){I+=2;continue}if(B===b){v(B),I+=2;continue}v(T),v(B),I+=2;continue}v(T),I++}if(I>=S.length&&(P=!1,O=I,A.length===0&&S.length===0)){for(let T of d)e.state.env.set(T,"");return c&&be(e,c),F("","",1)}N(O)}b===`
664
- `&&A.endsWith(`
665
- `)&&(A=A.slice(0,-1));let D=I=>s?I:I.replace(/\\(.)/g,"$1");if(d.length===1&&d[0]==="REPLY")return e.state.env.set("REPLY",D(A)),F("","",P?0:1);let V=Pe(e.state.env),X=e.limits.maxArrayElements;if(c){let{words:I}=yo(A,V,X,void 0,s);be(e,c);for(let T=0;T<I.length;T++)H(e,c,T,D(I[T]));return F("","",P?0:1)}let R=d.length,{words:j,wordStarts:q}=yo(A,V,X,R,s);for(let I=0;I<d.length;I++){let T=d[I];if(I<d.length-1)e.state.env.set(T,D(j[I]??""));else if(I<q.length){let B=A.substring(q[I]);B=Sc(B,V,s),B=D(B),e.state.env.set(T,B)}else e.state.env.set(T,"")}return F("","",P?0:1)}function ka(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return _("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 _(`bash: return: ${r}: numeric argument required
666
- `,2);n=(s%256+256)%256}throw new We(n)}var Br=`set: usage: set [-eux] [+eux] [-o option] [+o option]
666
+ `;return F("",W,1)}b=T.content}else!b&&e.state.groupStdin!==void 0&&(b=e.state.groupStdin);let S=i===""?"\0":i,v="",k=0,A=T=>{let _=B(T);if(_>e.limits.maxStringLength-k)throw new C(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");v+=T,k+=_},$=T=>{if(B(T)>e.limits.maxStringLength)throw new C(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")},R=0,P=!0,N=T=>{g?kn(e,u,T):r>=0?kn(e,r,T):e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=b.substring(T),e.state.groupStdinSourceFd!==void 0&&kn(e,e.state.groupStdinSourceFd,T))};if(l>=0){let T=Math.min(l,b.length);v=b.substring(0,T),$(v),R=T,P=T>=l,N(R);let _=d[0]||"REPLY";e.state.env.set(_,v);for(let W=1;W<d.length;W++)e.state.env.set(d[W],"");return F("","",P?0:1)}else if(a>=0){let T=0,_=0,W=!1;for(;_<b.length&&T<a;){let re=b[_];if(re===S){R=_+1,W=!0;break}if(!s&&re==="\\"&&_+1<b.length){let J=b[_+1];if(J===S&&S===`
667
+ `){_+=2,R=_;continue}if(J===S){_+=2,T++,A(J),R=_;continue}A(J),_+=2,T++,R=_}else A(re),_++,T++,R=_}P=T>=a||W,N(R)}else{R=0;let T=0;for(;T<b.length;){let _=b[T];if(_===S){R=T+S.length,P=!0;break}if(!s&&_==="\\"&&T+1<b.length){let W=b[T+1];if(W===`
668
+ `){T+=2;continue}if(W===S){A(W),T+=2;continue}A(_),A(W),T+=2;continue}A(_),T++}if(T>=b.length&&(P=!1,R=T,v.length===0&&b.length===0)){for(let _ of d)e.state.env.set(_,"");return c&&be(e,c),F("","",1)}N(R)}S===`
669
+ `&&v.endsWith(`
670
+ `)&&(v=v.slice(0,-1));let I=T=>s?T:T.replace(/\\(.)/g,"$1");if(d.length===1&&d[0]==="REPLY")return e.state.env.set("REPLY",I(v)),F("","",P?0:1);let z=Pe(e.state.env),X=e.limits.maxArrayElements;if(c){let{words:T}=go(v,z,X,void 0,s);be(e,c);for(let _=0;_<T.length;_++)G(e,c,_,I(T[_]));return F("","",P?0:1)}let O=d.length,{words:j,wordStarts:q}=go(v,z,X,O,s);for(let T=0;T<d.length;T++){let _=d[T];if(T<d.length-1)e.state.env.set(_,I(j[T]??""));else if(T<q.length){let W=v.substring(q[T]);W=Pc(W,z,s),W=I(W),e.state.env.set(_,W)}else e.state.env.set(_,"")}return F("","",P?0:1)}function $a(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
671
+ `,2);n=(s%256+256)%256}throw new Ve(n)}var zr=`set: usage: set [-eux] [+eux] [-o option] [+o option]
667
672
  Options:
668
673
  -e Exit immediately if a command exits with non-zero status
669
674
  +e Disable -e
@@ -679,80 +684,80 @@ Options:
679
684
  +o pipefail Disable pipefail
680
685
  -o xtrace Same as -x
681
686
  +o xtrace Disable xtrace
682
- `,Of=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]]),di=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]]),Tf=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],_f=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function xa(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,Xn(e))}function Hm(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function Zm(e,t,n){let r=xe(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],o=ce(e,n,i)??"";s>0&&t.append(" "),t.append(`[${i}]=`),t.reserve(li(o)),t.append(xn(o))}t.append(")")}function Qm(e,t){if(/^[a-zA-Z0-9_]+$/.test(t)){e.append(t);return}e.reserve(li(t)),e.append(xn(t))}function Km(e,t,n){let r=Tt(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],o=ce(e,n,i)??"";s>0&&t.append(" "),t.append("["),Qm(t,i),t.append("]="),t.reserve(li(o)),t.append(xn(o))}t.append(" )")}function Xm(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 Ym(e){return e.state.associativeArrays??new Set}function Df(e){let t=Tf.map(r=>`${r.padEnd(16)}${e.state.options[r]?"on":"off"}`),n=_f.map(r=>`${r.padEnd(16)}off`);return`${[...t,...n].sort().join(`
687
+ `,_f=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]]),pi=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]]),Mf=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],Bf=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function Ca(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,Yn(e))}function Jm(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function ey(e,t,n){let r=xe(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],o=le(e,n,i)??"";s>0&&t.append(" "),t.append(`[${i}]=`),t.reserve(ui(o)),t.append($n(o))}t.append(")")}function ty(e,t){if(/^[a-zA-Z0-9_]+$/.test(t)){e.append(t);return}e.reserve(ui(t)),e.append($n(t))}function ny(e,t,n){let r=Lt(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],o=le(e,n,i)??"";s>0&&t.append(" "),t.append("["),ty(t,i),t.append("]="),t.reserve(ui(o)),t.append($n(o))}t.append(" )")}function ry(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 sy(e){return e.state.associativeArrays??new Set}function Lf(e){let t=Mf.map(r=>`${r.padEnd(16)}${e.state.options[r]?"on":"off"}`),n=Bf.map(r=>`${r.padEnd(16)}off`);return`${[...t,...n].sort().join(`
683
688
  `)}
684
- `}function If(e){let t=Tf.map(r=>`set ${e.state.options[r]?"-o":"+o"} ${r}`),n=_f.map(r=>`set +o ${r}`);return`${[...t,...n].sort().join(`
689
+ `}function Ff(e){let t=Mf.map(r=>`set ${e.state.options[r]?"-o":"+o"} ${r}`),n=Bf.map(r=>`set +o ${r}`);return`${[...t,...n].sort().join(`
685
690
  `)}
686
- `}function $a(e,t){if(t.includes("--help"))return ne(Br);if(t.length===0){let i=Xm(e),o=Ym(e),a=[];for(let[u,f]of e.state.env)/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)&&(i.has(u)||o.has(u)||a.push([u,f]));let l=[...a.map(([u,f])=>({kind:"scalar",name:u,value:f})),...Array.from(i,u=>({kind:"indexed",name:u})),...Array.from(o,u=>({kind:"associative",name:u}))];l.sort((u,f)=>u.name<f.name?-1:u.name>f.name?1:0);let c=new Hn(e.limits.maxOutputSize,"set");for(let u of l)e.executionScope.consumeWork(1,"set variable listing"),u.kind==="scalar"?(c.append(u.name).append("="),c.reserve(Ef(u.value)),c.append(ve(u.value))):u.kind==="indexed"?Zm(e,c,u.name):Km(e,c,u.name),c.append(`
687
- `);return ne(c.build())}let n=[],r=()=>n.length>0?ne(n.join("")):se,s=0;for(;s<t.length;){let i=t[s];if((i==="-o"||i==="+o")&&Hm(t,s)){let o=t[s+1];if(!di.has(o)){let a=`bash: set: ${o}: invalid option name
688
- ${Br}`;if(e.state.options.posix)throw new ut(1,"",a);return _(a)}xa(e,di.get(o)??null,i==="-o"),s+=2;continue}if(i==="-o"){n.push(Df(e)),s++;continue}if(i==="+o"){n.push(If(e)),s++;continue}if(i.length>1&&(i[0]==="-"||i[0]==="+")&&i[1]!=="-"){let o=i[0]==="-",a=0;for(let l=1;l<i.length;l++){let c=i[l];if(c==="o"){let u=s+1+a;if(u<t.length&&!t[u].startsWith("-")&&!t[u].startsWith("+")){let d=t[u];if(!di.has(d)){let h=`bash: set: ${d}: invalid option name
689
- ${Br}`;if(e.state.options.posix)throw new ut(1,"",h);return _(h)}xa(e,di.get(d)??null,o),a++;continue}n.push(o?Df(e):If(e));continue}if(!Of.has(c)){let u=`bash: set: ${i[0]}${c}: invalid option
690
- ${Br}`;if(e.state.options.posix)throw new ut(1,"",u);return _(u)}xa(e,Of.get(c)??null,o)}s+=1+a;continue}if(i==="--")return Pa(e,t.slice(s+1)),r();if(i==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,Xn(e),s+1<t.length)return Pa(e,t.slice(s+1)),r();s++;continue}if(i==="+"){s++;continue}if(i.startsWith("-")||i.startsWith("+")){let o=`bash: set: ${i}: invalid option
691
- ${Br}`;if(e.state.options.posix)throw new ut(1,"",o);return _(o)}return Pa(e,t.slice(s)),r()}return r()}function Pa(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 Ca(e,t){let n=1;if(t.length>0){let o=Number.parseInt(t[0],10);if(Number.isNaN(o)||o<0){let a=`bash: shift: ${t[0]}: numeric argument required
692
- `;if(e.state.options.posix)throw new ut(1,"",a);return _(a)}n=o}let r=Number.parseInt(e.state.env.get("#")||"0",10);if(n>r){let o=`bash: shift: shift count out of range
693
- `;if(e.state.options.posix)throw new ut(1,"",o);return _(o)}if(n===0)return se;let s=[];for(let o=1;o<=r;o++)s.push(e.state.env.get(String(o))||"");let i=s.slice(n);for(let o=1;o<=r;o++)e.state.env.delete(String(o));for(let o=0;o<i.length;o++)e.state.env.set(String(o+1),i[o]);return e.state.env.set("#",String(i.length)),e.state.env.set("@",i.join(" ")),se}async function hi(e,t){let n=t;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return F("",`bash: source: filename argument required
694
- `,2);let r=n[0],s=null,i=null;if(r.includes("/")){let c=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(c),s=c}catch{}}else{let u=(e.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of u){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 _(`bash: ${r}: No such file or directory
695
- `);let o=new Map;if(n.length>1){for(let u=1;u<=9;u++)o.set(String(u),e.state.env.get(String(u)));o.set("#",e.state.env.get("#")),o.set("@",e.state.env.get("@"));let c=n.slice(1);e.state.env.set("#",String(c.length)),e.state.env.set("@",c.join(" "));for(let u=0;u<c.length&&u<9;u++)e.state.env.set(String(u+1),c[u]);for(let u=c.length+1;u<=9;u++)e.state.env.delete(String(u))}let a=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=a,n.length>1)for(let[c,u]of o)u===void 0?e.state.env.delete(c):e.state.env.set(c,u)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new C(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,"recursion");e.state.currentSource=r;try{let c=qe(i),u=await e.executeScript(c);return l(),u}catch(c){if(l(),c instanceof G)throw c;if(c instanceof We)return F(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return _(`bash: ${r}: ${c.message}
696
- `);throw c}}function Lf(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Jm(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function Ff(e,t){if(Jm(t))return null;try{let n=new Q,r=oe(n,t);return await ee(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}function Mf(e,t){if(e.state.localVarStack?.has(t)){let r=Ys(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)Xs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),Na(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),Xs(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 o=!1;for(let a=r-1;a>=0;a--)if(e.state.localScopes[a].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,a+1),o=!0;break}return o||Xs(e,t),!0}}return!1}function Na(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 Bf(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 Q().parseWordFromString(n,!0,!1);return ae(e,s)}if(t.includes("$")){let r=new Q().parseWordFromString(t,!1,!1);return ae(e,r)}return t}async function Ra(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 c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let d=c[1],h=c[2];if(He(e,d)){r+=`bash: unset: ${d}: cannot unset: readonly variable
697
- `,s=1;continue}if(h==="@"||h==="*"){Sr(e,d),e.state.env.delete(d);continue}let p=e.state.associativeArrays?.has(d);if(p){let y=await Bf(e,h);In(e,d,y);continue}let m=vt(e,d),E=e.state.declaredVars?.has(d);if((e.state.env.has(d)||E)&&!m&&!p){r+=`bash: unset: ${d}: not an array variable
698
- `,s=1;continue}let g=await Ff(e,h);if(g===null&&m){r+=`bash: unset: ${h}: not a valid identifier
699
- `,s=1;continue}if(g===null)continue;if(g<0){let y=K(e,d),b=y.length,A=e.state.currentLine;if(b===0){r+=`bash: line ${A}: unset: [${g}]: bad array subscript
700
- `,s=1;continue}let k=b+g;if(k<0){r+=`bash: line ${A}: unset: [${g}]: bad array subscript
701
- `,s=1;continue}let v=y[k][0];In(e,d,v);continue}In(e,d,g);continue}if(!Lf(i)){r+=`bash: unset: \`${i}': not a valid identifier
702
- `,s=1;continue}let u=i;if(fe(e,i)){let d=Ge(e,i);d&&d!==i&&(u=d)}if(He(e,u)){r+=`bash: unset: ${u}: cannot unset: readonly variable
703
- `,s=1;continue}Sr(e,u);let f=Fo(e,u);if(f!==void 0&&f!==e.state.callDepth)Mf(e,u);else if(e.state.fullyUnsetLocals?.has(u))e.state.env.delete(u);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(u),h=e.state.mutatedTempEnvVars?.has(u);if((d||h)&&e.state.localVarStack?.has(u)){let p=Ys(e,u);p?p.value===void 0?e.state.env.delete(u):e.state.env.set(u,p.value):e.state.env.delete(u)}else e.state.env.delete(u)}else Na(e,u)||e.state.env.delete(u);e.state.exportedVars?.delete(u);continue}let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let c=o[1],u=o[2];if(He(e,c)){r+=`bash: unset: ${c}: cannot unset: readonly variable
704
- `,s=1;continue}if(u==="@"||u==="*"){Sr(e,c),e.state.env.delete(c);continue}let f=e.state.associativeArrays?.has(c);if(f){let m=await Bf(e,u);In(e,c,m);continue}let d=vt(e,c);if(e.state.env.has(c)&&!d&&!f){r+=`bash: unset: ${c}: not an array variable
705
- `,s=1;continue}let p=await Ff(e,u);if(p===null&&d){r+=`bash: unset: ${u}: not a valid identifier
706
- `,s=1;continue}if(p===null)continue;if(p<0){let m=K(e,c),E=m.length,S=e.state.currentLine;if(E===0){r+=`bash: line ${S}: unset: [${p}]: bad array subscript
707
- `,s=1;continue}let g=E+p;if(g<0){r+=`bash: line ${S}: unset: [${p}]: bad array subscript
708
- `,s=1;continue}let y=m[g][0];In(e,c,y);continue}In(e,c,p);continue}if(!Lf(i)){r+=`bash: unset: \`${i}': not a valid identifier
709
- `,s=1;continue}let a=i;if(fe(e,i)){let c=Ge(e,i);c&&c!==i&&(a=c)}if(He(e,a)){r+=`bash: unset: ${a}: cannot unset: readonly variable
710
- `,s=1;continue}Sr(e,a);let l=Fo(e,a);if(l!==void 0&&l!==e.state.callDepth)Mf(e,a);else if(e.state.fullyUnsetLocals?.has(a))e.state.env.delete(a);else if(l!==void 0){let c=e.state.accessedTempEnvVars?.has(a),u=e.state.mutatedTempEnvVars?.has(a);if((c||u)&&e.state.localVarStack?.has(a)){let f=Ys(e,a);f?f.value===void 0?e.state.env.delete(a):e.state.env.set(a,f.value):e.state.env.delete(a)}else e.state.env.delete(a)}else Na(e,a)||e.state.env.delete(a);e.state.exportedVars?.delete(a),e.state.functions.delete(i)}return F("",r,s)}function ey(e){return e!==null&&typeof e=="object"&&"then"in e&&typeof e.then=="function"}function me(e,t,n,r){return((...s)=>{wr(t,n,`${r} call`);let i=e(...s);return ey(i)?i.then(o=>(wr(t,n,`${r} post-await`),o),o=>{throw wr(t,n,`${r} post-await`),o}):(wr(t,n,`${r} return`),i)})}function ty(e,t,n){let r={readFile:me(e.readFile.bind(e),t,n,"fs.readFile"),...typeof e.readFileBytes=="function"?{readFileBytes:me(e.readFileBytes.bind(e),t,n,"fs.readFileBytes")}:Object.create(null),readFileBuffer:me(e.readFileBuffer.bind(e),t,n,"fs.readFileBuffer"),writeFile:me(e.writeFile.bind(e),t,n,"fs.writeFile"),appendFile:me(e.appendFile.bind(e),t,n,"fs.appendFile"),exists:me(e.exists.bind(e),t,n,"fs.exists"),stat:me(e.stat.bind(e),t,n,"fs.stat"),mkdir:me(e.mkdir.bind(e),t,n,"fs.mkdir"),readdir:me(e.readdir.bind(e),t,n,"fs.readdir"),rm:me(e.rm.bind(e),t,n,"fs.rm"),cp:me(e.cp.bind(e),t,n,"fs.cp"),mv:me(e.mv.bind(e),t,n,"fs.mv"),resolvePath:me(e.resolvePath.bind(e),t,n,"fs.resolvePath"),getAllPaths:me(e.getAllPaths.bind(e),t,n,"fs.getAllPaths"),chmod:me(e.chmod.bind(e),t,n,"fs.chmod"),symlink:me(e.symlink.bind(e),t,n,"fs.symlink"),link:me(e.link.bind(e),t,n,"fs.link"),readlink:me(e.readlink.bind(e),t,n,"fs.readlink"),lstat:me(e.lstat.bind(e),t,n,"fs.lstat"),realpath:me(e.realpath.bind(e),t,n,"fs.realpath"),utimes:me(e.utimes.bind(e),t,n,"fs.utimes")};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=me(e.readdirWithFileTypes.bind(e),t,n,"fs.readdirWithFileTypes")),r}function Oa(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r=Object.getOwnPropertyDescriptors(e);r.fs={value:ty(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=me(e.exec,e.requireDefenseContext,n,"exec")),e.origCommand&&(s.origCommand=me(e.origCommand,e.requireDefenseContext,n,"origCommand")),e.fetch&&(s.fetch=me(e.fetch,e.requireDefenseContext,n,"fetch")),e.sleep&&(s.sleep=me(e.sleep,e.requireDefenseContext,n,"sleep")),e.getRegisteredCommands&&(s.getRegisteredCommands=me(e.getRegisteredCommands,e.requireDefenseContext,n,"getRegisteredCommands")),s}var Wf="+ ";async function Vf(e){let t=e.state.env.get("PS4");if(t===void 0)return Wf;if(t==="")return"";let n=e.state.options.xtrace;e.state.options.xtrace=!1;let r=e.state.lastExitCode,s=e.state.env.get("?"),i=e.state.lastSubstitutionExitCode;try{let a=new Q().parseWordFromString(t,!1,!1);return await ae(e,a)}catch(o){if(o instanceof ue&&!o.fatal)return t;if(o instanceof Jt||o instanceof Error&&o.name==="AbortError")throw o;return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${t}: bad substitution
711
- `,t||Wf}finally{e.state.options.xtrace=n,e.state.lastExitCode=r,e.state.lastSubstitutionExitCode=i,s===void 0?e.state.env.delete("?"):e.state.env.set("?",s)}}function ny(e){return e.map(t=>ry(t)).join(" ")}function ry(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let n=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
691
+ `}function Ra(e,t){if(t.includes("--help"))return te(zr);if(t.length===0){let i=ry(e),o=sy(e),a=[];for(let[u,f]of e.state.env)/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)&&(i.has(u)||o.has(u)||a.push([u,f]));let l=[...a.map(([u,f])=>({kind:"scalar",name:u,value:f})),...Array.from(i,u=>({kind:"indexed",name:u})),...Array.from(o,u=>({kind:"associative",name:u}))];l.sort((u,f)=>u.name<f.name?-1:u.name>f.name?1:0);let c=new Qn(e.limits.maxOutputSize,"set");for(let u of l)e.executionScope.consumeWork(1,"set variable listing"),u.kind==="scalar"?(c.append(u.name).append("="),c.reserve(vf(u.value)),c.append(ve(u.value))):u.kind==="indexed"?ey(e,c,u.name):ny(e,c,u.name),c.append(`
692
+ `);return te(c.build())}let n=[],r=()=>n.length>0?te(n.join("")):ne,s=0;for(;s<t.length;){let i=t[s];if((i==="-o"||i==="+o")&&Jm(t,s)){let o=t[s+1];if(!pi.has(o)){let a=`bash: set: ${o}: invalid option name
693
+ ${zr}`;if(e.state.options.posix)throw new dt(1,"",a);return L(a)}Ca(e,pi.get(o)??null,i==="-o"),s+=2;continue}if(i==="-o"){n.push(Lf(e)),s++;continue}if(i==="+o"){n.push(Ff(e)),s++;continue}if(i.length>1&&(i[0]==="-"||i[0]==="+")&&i[1]!=="-"){let o=i[0]==="-",a=0;for(let l=1;l<i.length;l++){let c=i[l];if(c==="o"){let u=s+1+a;if(u<t.length&&!t[u].startsWith("-")&&!t[u].startsWith("+")){let d=t[u];if(!pi.has(d)){let h=`bash: set: ${d}: invalid option name
694
+ ${zr}`;if(e.state.options.posix)throw new dt(1,"",h);return L(h)}Ca(e,pi.get(d)??null,o),a++;continue}n.push(o?Lf(e):Ff(e));continue}if(!_f.has(c)){let u=`bash: set: ${i[0]}${c}: invalid option
695
+ ${zr}`;if(e.state.options.posix)throw new dt(1,"",u);return L(u)}Ca(e,_f.get(c)??null,o)}s+=1+a;continue}if(i==="--")return Na(e,t.slice(s+1)),r();if(i==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,Yn(e),s+1<t.length)return Na(e,t.slice(s+1)),r();s++;continue}if(i==="+"){s++;continue}if(i.startsWith("-")||i.startsWith("+")){let o=`bash: set: ${i}: invalid option
696
+ ${zr}`;if(e.state.options.posix)throw new dt(1,"",o);return L(o)}return Na(e,t.slice(s)),r()}return r()}function Na(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 Oa(e,t){let n=1;if(t.length>0){let o=Number.parseInt(t[0],10);if(Number.isNaN(o)||o<0){let a=`bash: shift: ${t[0]}: numeric argument required
697
+ `;if(e.state.options.posix)throw new dt(1,"",a);return L(a)}n=o}let r=Number.parseInt(e.state.env.get("#")||"0",10);if(n>r){let o=`bash: shift: shift count out of range
698
+ `;if(e.state.options.posix)throw new dt(1,"",o);return L(o)}if(n===0)return ne;let s=[];for(let o=1;o<=r;o++)s.push(e.state.env.get(String(o))||"");let i=s.slice(n);for(let o=1;o<=r;o++)e.state.env.delete(String(o));for(let o=0;o<i.length;o++)e.state.env.set(String(o+1),i[o]);return e.state.env.set("#",String(i.length)),e.state.env.set("@",i.join(" ")),ne}async function mi(e,t){let n=t;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return F("",`bash: source: filename argument required
699
+ `,2);let r=n[0],s=null,i=null;if(r.includes("/")){let c=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(c),s=c}catch{}}else{let u=(e.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of u){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
700
+ `);let o=new Map;if(n.length>1){for(let u=1;u<=9;u++)o.set(String(u),e.state.env.get(String(u)));o.set("#",e.state.env.get("#")),o.set("@",e.state.env.get("@"));let c=n.slice(1);e.state.env.set("#",String(c.length)),e.state.env.set("@",c.join(" "));for(let u=0;u<c.length&&u<9;u++)e.state.env.set(String(u+1),c[u]);for(let u=c.length+1;u<=9;u++)e.state.env.delete(String(u))}let a=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=a,n.length>1)for(let[c,u]of o)u===void 0?e.state.env.delete(c):e.state.env.set(c,u)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new C(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,"recursion");e.state.currentSource=r;try{let c=He(i),u=await e.executeScript(c);return l(),u}catch(c){if(l(),c instanceof H)throw c;if(c instanceof Ve)return F(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return L(`bash: ${r}: ${c.message}
701
+ `);throw c}}function Wf(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function iy(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function Vf(e,t){if(iy(t))return null;try{let n=new Q,r=se(n,t);return await ee(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}function zf(e,t){if(e.state.localVarStack?.has(t)){let r=ei(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)Js(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),Da(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),Js(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 o=!1;for(let a=r-1;a>=0;a--)if(e.state.localScopes[a].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,a+1),o=!0;break}return o||Js(e,t),!0}}return!1}function Da(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 Uf(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 Q().parseWordFromString(n,!0,!1);return ie(e,s)}if(t.includes("$")){let r=new Q().parseWordFromString(t,!1,!1);return ie(e,r)}return t}async function Ia(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 c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let d=c[1],h=c[2];if(Ze(e,d)){r+=`bash: unset: ${d}: cannot unset: readonly variable
702
+ `,s=1;continue}if(h==="@"||h==="*"){kr(e,d),e.state.env.delete(d);continue}let p=e.state.associativeArrays?.has(d);if(p){let g=await Uf(e,h);_n(e,d,g);continue}let m=Pt(e,d),E=e.state.declaredVars?.has(d);if((e.state.env.has(d)||E)&&!m&&!p){r+=`bash: unset: ${d}: not an array variable
703
+ `,s=1;continue}let y=await Vf(e,h);if(y===null&&m){r+=`bash: unset: ${h}: not a valid identifier
704
+ `,s=1;continue}if(y===null)continue;if(y<0){let g=K(e,d),S=g.length,v=e.state.currentLine;if(S===0){r+=`bash: line ${v}: unset: [${y}]: bad array subscript
705
+ `,s=1;continue}let k=S+y;if(k<0){r+=`bash: line ${v}: unset: [${y}]: bad array subscript
706
+ `,s=1;continue}let A=g[k][0];_n(e,d,A);continue}_n(e,d,y);continue}if(!Wf(i)){r+=`bash: unset: \`${i}': not a valid identifier
707
+ `,s=1;continue}let u=i;if(fe(e,i)){let d=Ge(e,i);d&&d!==i&&(u=d)}if(Ze(e,u)){r+=`bash: unset: ${u}: cannot unset: readonly variable
708
+ `,s=1;continue}kr(e,u);let f=Wo(e,u);if(f!==void 0&&f!==e.state.callDepth)zf(e,u);else if(e.state.fullyUnsetLocals?.has(u))e.state.env.delete(u);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(u),h=e.state.mutatedTempEnvVars?.has(u);if((d||h)&&e.state.localVarStack?.has(u)){let p=ei(e,u);p?p.value===void 0?e.state.env.delete(u):e.state.env.set(u,p.value):e.state.env.delete(u)}else e.state.env.delete(u)}else Da(e,u)||e.state.env.delete(u);e.state.exportedVars?.delete(u);continue}let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let c=o[1],u=o[2];if(Ze(e,c)){r+=`bash: unset: ${c}: cannot unset: readonly variable
709
+ `,s=1;continue}if(u==="@"||u==="*"){kr(e,c),e.state.env.delete(c);continue}let f=e.state.associativeArrays?.has(c);if(f){let m=await Uf(e,u);_n(e,c,m);continue}let d=Pt(e,c);if(e.state.env.has(c)&&!d&&!f){r+=`bash: unset: ${c}: not an array variable
710
+ `,s=1;continue}let p=await Vf(e,u);if(p===null&&d){r+=`bash: unset: ${u}: not a valid identifier
711
+ `,s=1;continue}if(p===null)continue;if(p<0){let m=K(e,c),E=m.length,b=e.state.currentLine;if(E===0){r+=`bash: line ${b}: unset: [${p}]: bad array subscript
712
+ `,s=1;continue}let y=E+p;if(y<0){r+=`bash: line ${b}: unset: [${p}]: bad array subscript
713
+ `,s=1;continue}let g=m[y][0];_n(e,c,g);continue}_n(e,c,p);continue}if(!Wf(i)){r+=`bash: unset: \`${i}': not a valid identifier
714
+ `,s=1;continue}let a=i;if(fe(e,i)){let c=Ge(e,i);c&&c!==i&&(a=c)}if(Ze(e,a)){r+=`bash: unset: ${a}: cannot unset: readonly variable
715
+ `,s=1;continue}kr(e,a);let l=Wo(e,a);if(l!==void 0&&l!==e.state.callDepth)zf(e,a);else if(e.state.fullyUnsetLocals?.has(a))e.state.env.delete(a);else if(l!==void 0){let c=e.state.accessedTempEnvVars?.has(a),u=e.state.mutatedTempEnvVars?.has(a);if((c||u)&&e.state.localVarStack?.has(a)){let f=ei(e,a);f?f.value===void 0?e.state.env.delete(a):e.state.env.set(a,f.value):e.state.env.delete(a)}else e.state.env.delete(a)}else Da(e,a)||e.state.env.delete(a);e.state.exportedVars?.delete(a),e.state.functions.delete(i)}return F("",r,s)}function oy(e){return e!==null&&typeof e=="object"&&"then"in e&&typeof e.then=="function"}function me(e,t,n,r){return((...s)=>{Sr(t,n,`${r} call`);let i=e(...s);return oy(i)?i.then(o=>(Sr(t,n,`${r} post-await`),o),o=>{throw Sr(t,n,`${r} post-await`),o}):(Sr(t,n,`${r} return`),i)})}function ay(e,t,n){let r={readFile:me(e.readFile.bind(e),t,n,"fs.readFile"),...typeof e.readFileBytes=="function"?{readFileBytes:me(e.readFileBytes.bind(e),t,n,"fs.readFileBytes")}:Object.create(null),readFileBuffer:me(e.readFileBuffer.bind(e),t,n,"fs.readFileBuffer"),writeFile:me(e.writeFile.bind(e),t,n,"fs.writeFile"),appendFile:me(e.appendFile.bind(e),t,n,"fs.appendFile"),exists:me(e.exists.bind(e),t,n,"fs.exists"),stat:me(e.stat.bind(e),t,n,"fs.stat"),mkdir:me(e.mkdir.bind(e),t,n,"fs.mkdir"),readdir:me(e.readdir.bind(e),t,n,"fs.readdir"),rm:me(e.rm.bind(e),t,n,"fs.rm"),cp:me(e.cp.bind(e),t,n,"fs.cp"),mv:me(e.mv.bind(e),t,n,"fs.mv"),resolvePath:me(e.resolvePath.bind(e),t,n,"fs.resolvePath"),getAllPaths:me(e.getAllPaths.bind(e),t,n,"fs.getAllPaths"),chmod:me(e.chmod.bind(e),t,n,"fs.chmod"),symlink:me(e.symlink.bind(e),t,n,"fs.symlink"),link:me(e.link.bind(e),t,n,"fs.link"),readlink:me(e.readlink.bind(e),t,n,"fs.readlink"),lstat:me(e.lstat.bind(e),t,n,"fs.lstat"),realpath:me(e.realpath.bind(e),t,n,"fs.realpath"),utimes:me(e.utimes.bind(e),t,n,"fs.utimes")};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=me(e.readdirWithFileTypes.bind(e),t,n,"fs.readdirWithFileTypes")),e.createExclusive&&(r.createExclusive=me(e.createExclusive.bind(e),t,n,"fs.createExclusive")),r}function Ta(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r=Object.getOwnPropertyDescriptors(e);r.fs={value:ay(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=me(e.exec,e.requireDefenseContext,n,"exec")),e.origCommand&&(s.origCommand=me(e.origCommand,e.requireDefenseContext,n,"origCommand")),e.fetch&&(s.fetch=me(e.fetch,e.requireDefenseContext,n,"fetch")),e.sleep&&(s.sleep=me(e.sleep,e.requireDefenseContext,n,"sleep")),e.getRegisteredCommands&&(s.getRegisteredCommands=me(e.getRegisteredCommands,e.requireDefenseContext,n,"getRegisteredCommands")),s}var jf="+ ";async function qf(e){let t=e.state.env.get("PS4");if(t===void 0)return jf;if(t==="")return"";let n=e.state.options.xtrace;e.state.options.xtrace=!1;let r=e.state.lastExitCode,s=e.state.env.get("?"),i=e.state.lastSubstitutionExitCode;try{let a=new Q().parseWordFromString(t,!1,!1);return await ie(e,a)}catch(o){if(o instanceof ce&&!o.fatal)return t;if(o instanceof en||o instanceof Error&&o.name==="AbortError")throw o;return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${t}: bad substitution
716
+ `,t||jf}finally{e.state.options.xtrace=n,e.state.lastExitCode=r,e.state.lastSubstitutionExitCode=i,s===void 0?e.state.env.delete("?"):e.state.env.set("?",s)}}function ly(e){return e.map(t=>cy(t)).join(" ")}function cy(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let n=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
712
717
  `),s=e.includes(" "),i=e.includes("\\"),o=e.includes("'");if(n||r||s||i){let l="";for(let c of e){let u=c.charCodeAt(0);c===`
713
- `?l+="\\n":c===" "?l+="\\t":c==="\\"?l+="\\\\":c==="'"?l+="'":c==='"'?l+='"':u<32||u===127?u<256?l+=`\\x${u.toString(16).padStart(2,"0")}`:l+=`\\u${u.toString(16).padStart(4,"0")}`:l+=c}return`$'${l}'`}return o?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function zf(e,t,n){if(!e.state.options.xtrace)return"";let r=await Vf(e),s=[t,...n],i=ny(s);return`${r}${i}
714
- `}async function Uf(e,t,n){return e.state.options.xtrace?`${await Vf(e)}${t}=${n}
715
- `:""}function pi(e,t,n){return nn([t,n],"",e.limits.maxStringLength,"array assignment")}async function jf(e,t){let n=new Map,r="";for(let s of t.assignments){let i=s.name;if(s.array){let u=await sy(e,t,i,s.array,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};if(r+=u.xtraceOutput,u.continueToNext)continue}let o=s.value?await ae(e,s.value):"";if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:F("",`bash: ${i}: bad array subscript
716
- `,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let u=await cy(e,t,l[1],l[2],o,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};if(u.continueToNext)continue}let c=await uy(e,t,i,o,s.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function sy(e,t,n,r,s,i){let o="";if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: ${n}: cannot assign list to array member
717
- `,1)};if(fe(e,n)){let p=Bn(e,n);if(p===void 0||p==="")throw new G(1,"","");let m=Ge(e,n);if(m&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(m))return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: ${n}: cannot assign list to array member
718
- `,1)}}if(He(e,n)){if(t.name)return o+=`bash: ${n}: readonly variable
719
- `,{continueToNext:!0,xtraceOutput:o};let p=de(e,n);if(p)return{continueToNext:!1,xtraceOutput:"",error:p}}let a=e.state.associativeArrays?.has(n),l=$e(e,n),c=l?je(l):void 0,u=e.state.env.get(n),f=()=>{e.state.arrays??=new Map,c?e.state.arrays.set(n,c):e.state.arrays.delete(n),u===void 0?e.state.env.delete(n):e.state.env.set(n,u)},d=iy(r),h=()=>{be(e,n),e.state.env.delete(n)};try{a&&d?await oy(e,t,n,r,s,h,p=>{o+=p}):d?await ay(e,n,r,s,h):await ly(e,n,r,s,h)}catch(p){throw f(),p}if(t.name){i.set(n,e.state.env.get(n));let m=`(${r.map(E=>Kn(E)).join(" ")})`;e.state.env.set(n,m)}return{continueToNext:!0,xtraceOutput:o}}function iy(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 oy(e,t,n,r,s,i,o){let a=[];for(let l of r){if(a.length>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let c=Mi(l);if(c){let{key:u,valueParts:f,append:d}=c,h;f.length>0?(h=await ae(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(h=yn(e,h))):h="",a.push({type:"keyed",key:u,value:h,append:d})}else{let u=await ae(e,l);a.push({type:"invalid",expandedValue:u})}}e.executionScope.consumeWork(a.length,"associative array assignment"),s||i();for(let l of a)if(l.type==="keyed")if(l.append){let c=ce(e,n,l.key)??"";H(e,n,l.key,pi(e,c,l.value),"associative")}else H(e,n,l.key,l.value,"associative");else{let c=t.line??e.state.currentLine??1;o(`bash: line ${c}: ${n}: ${l.expandedValue}: must use subscript when assigning associative array
720
- `)}}async function ay(e,t,n,r,s){let i=[],o=0;for(let l of n){let c=Mi(l);if(c){if(o>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let{key:u,valueParts:f,append:d}=c,h;f.length>0?(h=await ae(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(h=yn(e,h))):h="",i.push({type:"keyed",indexExpr:u,value:h,append:d}),o++}else{let u=await Ct(e,l);if(u.values.length>e.limits.maxArrayElements-o)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push({type:"non-keyed",values:u.values}),o+=u.values.length}}e.executionScope.consumeWork(o,"indexed array assignment"),r||s();let a=0;for(let l of i)if(l.type==="keyed"){let c;try{let u=new Q,f=oe(u,l.indexExpr);c=await ee(e,f.expression,!1)}catch{if(/^-?\d+$/.test(l.indexExpr))c=Number.parseInt(l.indexExpr,10);else{let u=e.state.env.get(l.indexExpr);c=u?Number.parseInt(u,10):0,Number.isNaN(c)&&(c=0)}}if(l.append){let u=ce(e,t,c)??"";H(e,t,c,pi(e,u,l.value))}else H(e,t,c,l.value);a=c+1}else for(let c of l.values)H(e,t,a++,c)}async function ly(e,t,n,r,s){let i=[];for(let a of n){let l=await Ct(e,a);for(let c of l.values){if(i.length>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push(c)}}let o=0;if(e.executionScope.consumeWork(i.length,"indexed array assignment"),r){let a=K(e,t);if(a.length>0)o=Math.max(...a.map(([c])=>typeof c=="number"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(H(e,t,0,l),e.state.env.delete(t),o=1)}}else s();for(let a=0;a<i.length;a++)H(e,t,o+a,i[a])}async function cy(e,t,n,r,s,i,o){let a=n;if(fe(e,n)){let f=Ge(e,n);if(f&&f!==n){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: \`${f}': not a valid identifier
721
- `,1)};a=f}}if(He(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=de(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(a),c;if(l)c=await qf(e,r);else{let f=await Da(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};c=String(f.index)}let u=i?pi(e,ce(e,a,c)||"",s):s;return t.name||H(e,a,c,u,l?"associative":"indexed"),{continueToNext:!0,xtraceOutput:""}}async function qf(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 Q().parseWordFromString(r,!0,!1);n=await ae(e,i)}else if(t.includes("$")){let s=new Q().parseWordFromString(t,!1,!1);n=await ae(e,s)}else n=t;return n}async function Da(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 Q,o=oe(i,r);s=await ee(e,o.expression,!1)}catch(i){if(i instanceof G||i instanceof Oe)throw i;if(i instanceof ue){let l=`bash: line ${e.state.currentLine}: ${n}: ${i.message}
722
- `;if(i.fatal)throw new G(1,"",l);return{index:0,error:F("",l,1)}}let o=e.state.currentLine;return{index:0,error:F("",`bash: line ${o}: ${t}[${n}]: bad array subscript
718
+ `?l+="\\n":c===" "?l+="\\t":c==="\\"?l+="\\\\":c==="'"?l+="'":c==='"'?l+='"':u<32||u===127?u<256?l+=`\\x${u.toString(16).padStart(2,"0")}`:l+=`\\u${u.toString(16).padStart(4,"0")}`:l+=c}return`$'${l}'`}return o?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function Hf(e,t,n){if(!e.state.options.xtrace)return"";let r=await qf(e),s=[t,...n],i=ly(s);return`${r}${i}
719
+ `}async function Gf(e,t,n){return e.state.options.xtrace?`${await qf(e)}${t}=${n}
720
+ `:""}function yi(e,t,n){return rn([t,n],"",e.limits.maxStringLength,"array assignment")}async function Zf(e,t){let n=new Map,r="";for(let s of t.assignments){let i=s.name;if(s.array){let u=await uy(e,t,i,s.array,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};if(r+=u.xtraceOutput,u.continueToNext)continue}let o=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:F("",`bash: ${i}: bad array subscript
721
+ `,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let u=await my(e,t,l[1],l[2],o,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};if(u.continueToNext)continue}let c=await yy(e,t,i,o,s.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function uy(e,t,n,r,s,i){let o="";if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: ${n}: cannot assign list to array member
722
+ `,1)};if(fe(e,n)){let p=Vn(e,n);if(p===void 0||p==="")throw new H(1,"","");let m=Ge(e,n);if(m&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(m))return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: ${n}: cannot assign list to array member
723
+ `,1)}}if(Ze(e,n)){if(t.name)return o+=`bash: ${n}: readonly variable
724
+ `,{continueToNext:!0,xtraceOutput:o};let p=de(e,n);if(p)return{continueToNext:!1,xtraceOutput:"",error:p}}let a=e.state.associativeArrays?.has(n),l=$e(e,n),c=l?qe(l):void 0,u=e.state.env.get(n),f=()=>{e.state.arrays??=new Map,c?e.state.arrays.set(n,c):e.state.arrays.delete(n),u===void 0?e.state.env.delete(n):e.state.env.set(n,u)},d=fy(r),h=()=>{be(e,n),e.state.env.delete(n)};try{a&&d?await dy(e,t,n,r,s,h,p=>{o+=p}):d?await hy(e,n,r,s,h):await py(e,n,r,s,h)}catch(p){throw f(),p}if(t.name){i.set(n,e.state.env.get(n));let m=`(${r.map(E=>Xn(E)).join(" ")})`;e.state.env.set(n,m)}return{continueToNext:!0,xtraceOutput:o}}function fy(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 dy(e,t,n,r,s,i,o){let a=[];for(let l of r){if(a.length>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let c=Bi(l);if(c){let{key:u,valueParts:f,append:d}=c,h;f.length>0?(h=await ie(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(h=wn(e,h))):h="",a.push({type:"keyed",key:u,value:h,append:d})}else{let u=await ie(e,l);a.push({type:"invalid",expandedValue:u})}}e.executionScope.consumeWork(a.length,"associative array assignment"),s||i();for(let l of a)if(l.type==="keyed")if(l.append){let c=le(e,n,l.key)??"";G(e,n,l.key,yi(e,c,l.value),"associative")}else G(e,n,l.key,l.value,"associative");else{let c=t.line??e.state.currentLine??1;o(`bash: line ${c}: ${n}: ${l.expandedValue}: must use subscript when assigning associative array
725
+ `)}}async function hy(e,t,n,r,s){let i=[],o=0;for(let l of n){let c=Bi(l);if(c){if(o>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let{key:u,valueParts:f,append:d}=c,h;f.length>0?(h=await ie(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(h=wn(e,h))):h="",i.push({type:"keyed",indexExpr:u,value:h,append:d}),o++}else{let u=await Rt(e,l);if(u.values.length>e.limits.maxArrayElements-o)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push({type:"non-keyed",values:u.values}),o+=u.values.length}}e.executionScope.consumeWork(o,"indexed array assignment"),r||s();let a=0;for(let l of i)if(l.type==="keyed"){let c;try{let u=new Q,f=se(u,l.indexExpr);c=await ee(e,f.expression,!1)}catch{if(/^-?\d+$/.test(l.indexExpr))c=Number.parseInt(l.indexExpr,10);else{let u=e.state.env.get(l.indexExpr);c=u?Number.parseInt(u,10):0,Number.isNaN(c)&&(c=0)}}if(l.append){let u=le(e,t,c)??"";G(e,t,c,yi(e,u,l.value))}else G(e,t,c,l.value);a=c+1}else for(let c of l.values)G(e,t,a++,c)}async function py(e,t,n,r,s){let i=[];for(let a of n){let l=await Rt(e,a);for(let c of l.values){if(i.length>=e.limits.maxArrayElements)throw new C(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push(c)}}let o=0;if(e.executionScope.consumeWork(i.length,"indexed array assignment"),r){let a=K(e,t);if(a.length>0)o=Math.max(...a.map(([c])=>typeof c=="number"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(G(e,t,0,l),e.state.env.delete(t),o=1)}}else s();for(let a=0;a<i.length;a++)G(e,t,o+a,i[a])}async function my(e,t,n,r,s,i,o){let a=n;if(fe(e,n)){let f=Ge(e,n);if(f&&f!==n){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: \`${f}': not a valid identifier
726
+ `,1)};a=f}}if(Ze(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=de(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(a),c;if(l)c=await Qf(e,r);else{let f=await _a(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};c=String(f.index)}let u=i?yi(e,le(e,a,c)||"",s):s;return t.name||G(e,a,c,u,l?"associative":"indexed"),{continueToNext:!0,xtraceOutput:""}}async function Qf(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 Q().parseWordFromString(r,!0,!1);n=await ie(e,i)}else if(t.includes("$")){let s=new Q().parseWordFromString(t,!1,!1);n=await ie(e,s)}else n=t;return n}async function _a(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 Q,o=se(i,r);s=await ee(e,o.expression,!1)}catch(i){if(i instanceof H||i instanceof Oe)throw i;if(i instanceof ce){let l=`bash: line ${e.state.currentLine}: ${n}: ${i.message}
727
+ `;if(i.fatal)throw new H(1,"",l);return{index:0,error:F("",l,1)}}let o=e.state.currentLine;return{index:0,error:F("",`bash: line ${o}: ${t}[${n}]: bad array subscript
723
728
  `,1)}}Number.isNaN(s)&&(s=0)}if(s<0){let i=K(e,t);if(i.length===0){let a=e.state.currentLine;return{index:0,error:F("",`bash: line ${a}: ${t}[${n}]: bad array subscript
724
729
  `,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:F("",`bash: line ${a}: ${t}[${n}]: bad array subscript
725
- `,1)}}}return{index:s}}async function uy(e,t,n,r,s,i){let o="",a=n,l=null;if(fe(e,n)){let f=xs(e,n,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: ${n}: circular name reference
726
- `,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(He(e,a)){if(t.name)return o+=`bash: ${a}: readonly variable
727
- `,{continueToNext:!0,xtraceOutput:o};let f=de(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let c;if(Fr(e,a))try{let f=new Q;if(s){let h=`(${e.state.env.get(a)||"0"}) + (${r})`,p=oe(f,h);c=String(await ee(e,p.expression))}else{let d=oe(f,r);c=String(await ee(e,d.expression))}}catch{c="0"}else{let f=vt(e,a)?ce(e,a,0):e.state.env.get(a);c=s?pi(e,f||"",r):r}c=ur(e,a,c),o+=await Uf(e,a,c);let u;return l?u=await fy(e,l):vt(e,a)&&(u="0"),t.name?u===void 0&&(i.set(a,e.state.env.get(a)),e.state.env.set(a,c)):(u===void 0?e.state.env.set(a,c):H(e,a,u,c),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 fy(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return qf(e,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new Q,a=oe(o,r);i=await ee(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=K(e,n);o.length>0&&(i=Math.max(...o.map(l=>l[0]))+1+i)}return String(i)}async function Zf(e,t,n,r){let s=!1,i=!1,o=!1,a=!1,l=!1,c=[];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 c.push(m);let u="",f="",d=0,h=!1,p=!1;for(let m of c){let E=!1;if(o){if(a){let k=await r(m);if(k.length>0){for(let v of k)u+=`${v}
730
+ `,1)}}}return{index:s}}async function yy(e,t,n,r,s,i){let o="",a=n,l=null;if(fe(e,n)){let f=$s(e,n,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:"",error:F("",`bash: ${n}: circular name reference
731
+ `,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(Ze(e,a)){if(t.name)return o+=`bash: ${a}: readonly variable
732
+ `,{continueToNext:!0,xtraceOutput:o};let f=de(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let c;if(Wr(e,a))try{let f=new Q;if(s){let h=`(${e.state.env.get(a)||"0"}) + (${r})`,p=se(f,h);c=String(await ee(e,p.expression))}else{let d=se(f,r);c=String(await ee(e,d.expression))}}catch{c="0"}else{let f=Pt(e,a)?le(e,a,0):e.state.env.get(a);c=s?yi(e,f||"",r):r}c=fr(e,a,c),o+=await Gf(e,a,c);let u;return l?u=await gy(e,l):Pt(e,a)&&(u="0"),t.name?u===void 0&&(i.set(a,e.state.env.get(a)),e.state.env.set(a,c)):(u===void 0?e.state.env.set(a,c):G(e,a,u,c),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 gy(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return Qf(e,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new Q,a=se(o,r);i=await ee(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=K(e,n);o.length>0&&(i=Math.max(...o.map(l=>l[0]))+1+i)}return String(i)}async function Yf(e,t,n,r){let s=!1,i=!1,o=!1,a=!1,l=!1,c=[];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 c.push(m);let u="",f="",d=0,h=!1,p=!1;for(let m of c){let E=!1;if(o){if(a){let k=await r(m);if(k.length>0){for(let A of k)u+=`${A}
728
733
  `;h=!0,E=!0}}else{let k=await n(m);k&&(u+=`${k}
729
- `,h=!0,E=!0)}E||(p=!0);continue}let S=!l&&e.state.functions.has(m);if(a&&S){if(!i)if(s)u+=`function
730
- `;else{let k=e.state.functions.get(m),v=k?Gf(m,k):`${m} is a function
731
- `;u+=v}E=!0}let g=e.state.env.get(`BASH_ALIAS_${m}`);if(g!==void 0&&(a||!E)&&(i||(s?u+=`alias
732
- `:u+=`${m} is aliased to \`${g}'
733
- `),E=!0,!a)||vr.has(m)&&(a||!E)&&(i||(s?u+=`keyword
734
+ `,h=!0,E=!0)}E||(p=!0);continue}let b=!l&&e.state.functions.has(m);if(a&&b){if(!i)if(s)u+=`function
735
+ `;else{let k=e.state.functions.get(m),A=k?Kf(m,k):`${m} is a function
736
+ `;u+=A}E=!0}let y=e.state.env.get(`BASH_ALIAS_${m}`);if(y!==void 0&&(a||!E)&&(i||(s?u+=`alias
737
+ `:u+=`${m} is aliased to \`${y}'
738
+ `),E=!0,!a)||Pr.has(m)&&(a||!E)&&(i||(s?u+=`keyword
734
739
  `:u+=`${m} is a shell keyword
735
- `),E=!0,!a))continue;if(!a&&S&&!E){if(!i)if(s)u+=`function
736
- `;else{let k=e.state.functions.get(m),v=k?Gf(m,k):`${m} is a function
737
- `;u+=v}E=!0;continue}if(!(Dt.has(m)&&(a||!E)&&(i||(s?u+=`builtin
740
+ `),E=!0,!a))continue;if(!a&&b&&!E){if(!i)if(s)u+=`function
741
+ `;else{let k=e.state.functions.get(m),A=k?Kf(m,k):`${m} is a function
742
+ `;u+=A}E=!0;continue}if(!(Tt.has(m)&&(a||!E)&&(i||(s?u+=`builtin
738
743
  `:u+=`${m} is a shell builtin
739
- `),E=!0,!a))){if(a){let k=await r(m);for(let v of k)i?u+=`${v}
744
+ `),E=!0,!a))){if(a){let k=await r(m);for(let A of k)i?u+=`${A}
740
745
  `:s?u+=`file
741
- `:u+=`${m} is ${v}
746
+ `:u+=`${m} is ${A}
742
747
  `,h=!0,E=!0}else if(!E){let k=await n(m);k&&(i?u+=`${k}
743
748
  `:s?u+=`file
744
749
  `:u+=`${m} is ${k}
745
- `,h=!0,E=!0)}if(!E&&(p=!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
746
- `)}}}return i?d=p&&!h?1:0:d=p?1:0,F(u,f,d)}function Gf(e,t){let n;return t.body.type==="Group"?n=t.body.body.map(s=>Wr(s)).join("; "):n=Wr(t.body),`${e} is a function
750
+ `,h=!0,E=!0)}if(!E&&(p=!0,!s&&!i)){let k=!0;if(m.includes("/")){let A=e.fs.resolvePath(e.state.cwd,m);await e.fs.exists(A)&&(k=!1)}k&&(f+=`bash: type: ${m}: not found
751
+ `)}}}return i?d=p&&!h?1:0:d=p?1:0,F(u,f,d)}function Kf(e,t){let n;return t.body.type==="Group"?n=t.body.body.map(s=>Ur(s)).join("; "):n=Ur(t.body),`${e} is a function
747
752
  ${e} ()
748
753
  {
749
754
  ${n}
750
755
  }
751
- `}function Wr(e){if(Array.isArray(e))return e.map(t=>Wr(t)).join("; ");if(e.type==="Statement"){let t=[];for(let n=0;n<e.pipelines.length;n++){let r=e.pipelines[n];t.push(dy(r)),e.operators[n]&&t.push(e.operators[n])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,n=[];t.name&&n.push(Hf(t.name));for(let r of t.args)n.push(Hf(r));return n.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>Wr(r)).join("; ")}; }`:"..."}function Hf(e){return e.parts.map(Qf).join("")}function Qf(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(Qf).join("")}"`;default:return we(M.word([e]))}}function dy(e){let t=e.commands.map(n=>Wr(n));return(e.negated?"! ":"")+t.join(" | ")}async function Kf(e,t,n,r){let s="",i="",o=0;for(let a of t){if(!a){o=1;continue}let l=e.state.env.get(`BASH_ALIAS_${a}`);if(l!==void 0)r?s+=`${a} is an alias for "${l}"
756
+ `}function Ur(e){if(Array.isArray(e))return e.map(t=>Ur(t)).join("; ");if(e.type==="Statement"){let t=[];for(let n=0;n<e.pipelines.length;n++){let r=e.pipelines[n];t.push(wy(r)),e.operators[n]&&t.push(e.operators[n])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,n=[];t.name&&n.push(Xf(t.name));for(let r of t.args)n.push(Xf(r));return n.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>Ur(r)).join("; ")}; }`:"..."}function Xf(e){return e.parts.map(Jf).join("")}function Jf(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(Jf).join("")}"`;default:return we(M.word([e]))}}function wy(e){let t=e.commands.map(n=>Ur(n));return(e.negated?"! ":"")+t.join(" | ")}async function ed(e,t,n,r){let s="",i="",o=0;for(let a of t){if(!a){o=1;continue}let l=e.state.env.get(`BASH_ALIAS_${a}`);if(l!==void 0)r?s+=`${a} is an alias for "${l}"
752
757
  `:s+=`alias ${a}='${l}'
753
- `;else if(vr.has(a))r?s+=`${a} is a shell keyword
758
+ `;else if(Pr.has(a))r?s+=`${a} is a shell keyword
754
759
  `:s+=`${a}
755
- `;else if(Dt.has(a))r?s+=`${a} is a shell builtin
760
+ `;else if(Tt.has(a))r?s+=`${a} is a shell builtin
756
761
  `:s+=`${a}
757
762
  `;else if(e.state.functions.has(a))r?s+=`${a} is a function
758
763
  `:s+=`${a}
@@ -762,53 +767,54 @@ ${e} ()
762
767
  `),o=1)}else if(e.commands.has(a)){let u=(e.state.env.get("PATH")??"/usr/bin:/bin").split(":"),f=null;for(let d of u){if(!d)continue;let h=`${d}/${a}`;try{let p=await e.fs.stat(h);if(!p.isDirectory&&(p.mode&73)!==0){f=h;break}}catch{}}f||(f=`/usr/bin/${a}`),r?s+=`${a} is ${f}
763
768
  `:s+=`${f}
764
769
  `}else r&&(i+=`${a}: not found
765
- `),o=1}return F(s,i,o)}async function Xf(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 o=`${s.startsWith("/")?s:e.fs.resolvePath(e.state.cwd,s)}/${t}`;if(await e.fs.exists(o)){try{let a=await e.fs.stat(o);if(a.isDirectory||(a.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 Yf(e,t){let n=!0,r=e.signal?new AbortController:void 0,s=new WeakMap,i=()=>{if(!n)throw new st("",`bash: ${t} used its context after cancellation
766
- `)},o=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"&&ol(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(),o(S)));return s.set(f,E),E}if(typeof f=="function"){let E=function(...S){return i(),o(Reflect.apply(f,this,S))};return s.set(f,E),E}let h=Object.getPrototypeOf(f);if(Array.isArray(f)||h===Object.prototype||h===null){let E=Array.isArray(f)?[]:Object.create(h);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(),o(Reflect.apply(y,f,b))):o(y)}if(g.get){let y=g.get;g.get=()=>(i(),o(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 p=new Map,m=new Xa(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 o(g);if(p.has(S))return p.get(S);let y=(...b)=>(i(),o(Reflect.apply(g,E,b)));return p.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},a=f=>o(f),l=f=>f&&((...d)=>(i(),o(f(...d)))),c=f=>({value:f,enumerable:!0,configurable:!0,writable:!0}),u=Object.getOwnPropertyDescriptors(e);return Object.assign(u,{fs:c(a(e.fs)),env:c(a(e.env)),limits:c(Object.freeze({...e.limits})),exportedEnv:c(e.exportedEnv?Object.freeze({...e.exportedEnv}):void 0),executionScope:c(e.executionScope?a(e.executionScope):void 0),fileDescriptors:c(e.fileDescriptors?a(e.fileDescriptors):void 0),coverage:c(e.coverage?a(e.coverage):void 0),assignShellVariable:c(l(e.assignShellVariable)),exec:c(l(e.exec)),origCommand:c(l(e.origCommand)),execWithInheritedStdin:c(l(e.execWithInheritedStdin)),fetch:c(l(e.fetch)),getRegisteredCommands:c(l(e.getRegisteredCommands)),sleep:c(l(e.sleep)),trace:c(l(e.trace)),invokeTool:c(l(e.invokeTool)),signal:c(r?.signal)}),{context:Object.defineProperties(Object.create(Object.getPrototypeOf(e)),u),revoke(){n=!1,r?.signal.aborted||r?.abort(new st("",`bash: ${t} context revoked
767
- `))}}}async function hy(e,t,n,r,s,i){let o=s.remainingTimeMs()??t.limits.maxExecutionTimeMs,a=t.limits.maxExtensionCleanupTimeMs,l,c,u,d=Promise.resolve().then(e).then(p=>({kind:"result",result:p}),p=>({kind:"error",error:p})),h=new Promise(p=>{let m=()=>{n(),p({kind:"abort"})};c=m,i?.addEventListener("abort",m,{once:!0}),i?.aborted&&m(),l=pr(()=>{n(),p({kind:"deadline"})},o)});try{let p=await Promise.race([d,h]);if(p.kind==="result")return p.result;if(p.kind==="error")throw p.error;n();let m=await Promise.race([d.then(()=>!0),new Promise(S=>{u=pr(()=>S(!1),a)})]),E=p.kind==="deadline"?new st("",`bash: ${r} exceeded its execution deadline
768
- `):new st("",`bash: execution aborted
769
- `);throw m||s.poisonAfterAbort(E),E}finally{n(),mr(l),mr(u),c&&i?.removeEventListener("abort",c)}}var Jf={export:(e,t)=>wa(e.ctx,t),unset:(e,t)=>Ra(e.ctx,t),exit:(e,t)=>ga(e.ctx,t),local:(e,t)=>Aa(e.ctx,t),set:(e,t)=>$a(e.ctx,t),break:(e,t)=>Oo(e.ctx,t),continue:(e,t)=>ia(e.ctx,t),return:(e,t)=>ka(e.ctx,t),shift:(e,t)=>Ca(e.ctx,t),getopts:(e,t)=>ui(e.ctx,t),compgen:(e,t)=>ea(e.ctx,t),complete:(e,t)=>ra(e.ctx,t),compopt:(e,t)=>sa(e.ctx,t),pushd:(e,t)=>ha(e.ctx,t),popd:(e,t)=>pa(e.ctx,t),dirs:(e,t)=>ma(e.ctx,t),source:(e,t)=>hi(e.ctx,t),".":(e,t)=>hi(e.ctx,t),read:(e,t,n)=>va(e.ctx,t,n.stdin,n.stdinSourceFd),mapfile:(e,t,n)=>fi(e.ctx,t,n.stdin),readarray:(e,t,n)=>fi(e.ctx,t,n.stdin),declare:(e,t)=>ci(e.ctx,t),typeset:(e,t)=>ci(e.ctx,t),readonly:(e,t)=>fa(e.ctx,t),eval:(e,t,n)=>ya(e.ctx,t,n.stdin,n.stdinRedirected),cd:(e,t)=>Do(e.ctx,t),":":()=>se,true:()=>se,false:()=>Se(!1),let:(e,t)=>Sa(e.ctx,t),command:(e,t,n)=>py(e,t,n.stdin,n.stdinRedirected),builtin:(e,t,n)=>my(e,t,n.stdin,n.stdinRedirected),shopt:(e,t)=>mf(e.ctx,t),exec:async(e,t,n)=>{if(t.length===0)return se;let[r,...s]=t;return{...await e.runCommand(r,s,[],n.stdin,!1,!1,-1,n.stdinRedirected),internalProducerOmitsShellPrefix:!0}},wait:()=>se,type:(e,t)=>Zf(e.ctx,t,n=>Xf(e.ctx,n),n=>fs(e.ctx,n)),hash:(e,t)=>Ea(e.ctx,t),help:(e,t)=>ba(e.ctx,t),"[":(e,t)=>t[t.length-1]!=="]"?_("[: missing `]'\n",2):sr(e.ctx,t.slice(0,-1)),test:(e,t)=>sr(e.ctx,t)};async function ed(e,t,n,r,s,i,o,a,l=!1){let{ctx:c}=e;c.coverage&&Dt.has(t)&&c.coverage.hit(`bash:builtin:${t}`);let u={stdin:s,stdinRedirected:l,stdinSourceFd:a},f=gl(t),d=(f==="early"||f==="late")&&Object.hasOwn(Jf,t)?Jf[t]:void 0;if(d&&(f==="early"||c.state.options.posix&&wl(t)))return d(e,n,u);if(!i){let h=c.state.functions.get(t);if(h)return ii(c,h,n,s,void 0,l)}if(t==="__just_bash_tee_restore"){if(n.length===0||n.length>c.limits.maxArrayElements)return _(`bash: invalid internal pipeline status restore
770
- `,2);let h=[];for(let E of n){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(E))return _(`bash: invalid internal pipeline status restore
771
- `,2);let S=Number(E);if(!Number.isSafeInteger(S)||S>255)return _(`bash: invalid internal pipeline status restore
772
- `,2);h.push(S)}let p=h[h.length-1]??0,m=[...h].reverse().find(E=>E!==0);return{stdout:"",stderr:"",exitCode:c.state.options.pipefail&&m!==void 0?m:p,internalPipeStatusOverride:h}}return d&&f==="late"?d(e,n,u):null}async function py(e,t,n,r=!1){let{ctx:s,runCommand:i}=e;if(t.length===0)return se;let o=!1,a=!1,l=!1,c=t;for(;c.length>0&&c[0].startsWith("-");){let d=c[0];if(d==="--"){c=c.slice(1);break}for(let h of d.slice(1))h==="p"?o=!0:h==="V"?a=!0:h==="v"&&(l=!0);c=c.slice(1)}if(c.length===0)return se;if(l||a)return await Kf(s,c,l,a);let[u,...f]=c;return i(u,f,[],n,!0,o,-1,r)}async function my(e,t,n,r=!1){let{runCommand:s}=e;if(t.length===0)return se;let i=t;if(i[0]==="--"&&(i=i.slice(1),i.length===0))return se;let o=i[0];if(o!=="__just_bash_tee_restore"&&!Dt.has(o))return _(`bash: builtin: ${o}: not a shell builtin
773
- `);let[,...a]=i;return s(o,a,[],n,!0,!1,-1,r)}async function td(e,t,n,r,s){let{ctx:i,buildExportedEnv:o,executeUserScript:a}=e,c=await us(i,t,s?"/usr/bin:/bin":void 0);if(!c){i.executionScope.recordUnresolvedCommand(t);let A=i.executionScope.abortOnUnresolvedCommands;if(ju(t)){let k=`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
774
- `;if(A)throw new Oe(t,"",k);return _(k,127)}if(A)throw new Oe(t,"",`bash: ${t}: command not found
775
- `);return _(`bash: ${t}: command not found
776
- `,127)}if("error"in c)return c.error==="permission_denied"?_(`bash: ${t}: Permission denied
777
- `,126):_(`bash: ${t}: No such file or directory
778
- `,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||"",h=!1,p=o();i.state.fileDescriptors??=new Map;let m={fs:i.fs,fsIdentity:ss(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}]`,O=xs(i,A,k);if(O===void 0)throw new Error(`${A}: circular name reference`);if(O===null)return;let P=O.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(?:\[(.*)\])?$/);if(!P)throw new Error(`${$}: not a valid identifier`);let N=P[1],D=P[2]??v;if(He(i,A)||He(i,N))throw new Error(`${N}: readonly variable`);if(D===void 0)i.state.env.set(N,k);else{let V=i.state.associativeArrays?.has(N)?"associative":"indexed";if(V==="associative"){H(i,N,D,k,V);return}let X=await Da(i,N,D);if(X.error)throw new G(X.error.exitCode,X.error.stdout,X.error.stderr);H(i,N,X.index,k,V)}},exportedEnv:p,get stdin(){return h=!0,d},limits:i.limits,executionScope:u.internalIsExtension?fl(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=u.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=Yf(k,E.name),$=Oa(v.context,E.name);S=v.revoke,m.origCommand=O=>{let P=()=>E.execute(O,$);return E.trusted?Re.runTrustedAsync(P):Re.runUntrustedAsync(P)}}let g=Yf(m,t),y=Oa(g.context,t),b=()=>{g.revoke(),S()};try{let A=()=>Ka(i.requireDefenseContext,"command",`${t} execution`,()=>u.execute(n,y)),k=()=>hy(A,y,b,t,i.executionScope,i.state.signal),v=u.trusted?await Re.runTrustedAsync(k):await k();return{...v,internalStdinConsumed:v.internalStdinConsumed??(h?r.length:0)}}catch(A){return Jr(A),_(`${t}: ${Ot(jt(A))}
779
- `)}}async function Ia(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=new an(e.executionScope,"condition"),s=0;try{for(let i of t){let o=await e.executeStatement(i);r.appendResult(o),s=o.exitCode}}catch(i){throw r.prependTo(i),i}finally{e.state.inCondition=n}return r.build(s)}function Vr(e,t,n,r){if(e instanceof tt)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 nt)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(Yr(e)||e instanceof We||e instanceof Qe||e instanceof G)return e instanceof Jt&&e.prependOutput(t,n),{action:"rethrow",stdout:t,stderr:n,error:e};let s=jt(e);return{action:"error",stdout:t,stderr:`${n}${s}
780
- `,exitCode:1}}function nd(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=W(t)+W(n);r>this.ctx.limits.maxOutputSize-this.totalBytes&&wn(`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:W(n),stderr:W(r)}}}};async function Ta(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(Xr(s)||s instanceof Qe||s instanceof G||s instanceof Oe||s instanceof C||s instanceof tn)throw s.prependOutput(n.stdout,n.stderr),s;return n.appendUnaccounted("",`${jt(s)}
781
- `),n.build(1)}return n.build(r)}async function rd(e,t){return ct(e,t.redirections,"",()=>yy(e,t))}async function yy(e,t){let n=new Pn(e);for(let r of t.clauses){let s=await Ia(e,r.condition);if(n.append(s.stdout,s.stderr),s.exitCode===0)return Ta(e,r.body,n)}return t.elseBody?Ta(e,t.elseBody,n):n.build(0)}async function sd(e,t){return ct(e,t.redirections,"",()=>gy(e,t))}async function gy(e,t){let n=new Pn(e),r=0,s=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return _(`bash: \`${t.variable}': not a valid identifier
782
- `);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 o of t.words){let a=await Ct(e,o);_e(i,a.values,e.limits.maxArrayElements,"for-loop expansion")}}catch(o){if(o instanceof en)return{stdout:"",stderr:o.stderr,exitCode:1};throw o}e.state.loopDepth++;try{for(let o of i){s++,s>e.limits.maxLoopIterations&&wn(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n.stdout,n.stderr),e.state.env.set(t.variable,o);try{for(let a of t.body){let l=await e.executeStatement(a);n.append(l.stdout,l.stderr),r=l.exitCode}}catch(a){let l=Vr(a,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 id(e,t){return ct(e,t.redirections,"",()=>wy(e,t))}async function wy(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 ee(e,t.init.expression),e.state.loopDepth++;try{for(;i++,i>e.limits.maxLoopIterations&&wn(`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 ee(e,t.condition.expression)===0));){try{for(let o of t.body){let a=await e.executeStatement(o);r.append(a.stdout,a.stderr),s=a.exitCode}}catch(o){let a=Vr(o,r.stdout,r.stderr,e.state.loopDepth);if(r.replace(a.stdout,a.stderr),a.action==="break")break;if(a.action==="continue"){t.update&&await ee(e,t.update.expression);continue}if(a.action==="error")return r.build(a.exitCode??1);throw a.error}t.update&&await ee(e,t.update.expression)}}finally{e.state.loopDepth--}return r.build(s)}async function od(e,t,n=""){return ct(e,t.redirections,n,r=>Ey(e,t,n,r))}async function Ey(e,t,n,r){let s=new Pn(e),i=0,o=0,a=nd(r.stdin,n),l=e.state.groupStdin;a.owns&&(e.state.groupStdin=a.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&wn(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=0,u=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let h of t.condition){let p=await e.executeStatement(h);s.append(p.stdout,p.stderr),c=p.exitCode}}catch(h){if(h instanceof tt){if(s.append(h.stdout,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,e.state.inCondition=d,h;u=!0}else if(h instanceof nt){if(s.append(h.stdout,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,e.state.inCondition=d,h;f=!0}else throw e.state.inCondition=d,h}finally{e.state.inCondition=d}if(u)break;if(!f){if(c!==0)break;try{for(let h of t.body){let p=await e.executeStatement(h);s.append(p.stdout,p.stderr),i=p.exitCode}}catch(h){let p=Vr(h,s.stdout,s.stderr,e.state.loopDepth);if(s.replace(p.stdout,p.stderr),p.action==="break")break;if(p.action==="continue")continue;if(p.action==="error")return s.build(p.exitCode??1);throw p.error}}}}finally{e.state.loopDepth--,a.owns&&(e.state.groupStdin=l)}return s.build(i)}async function ad(e,t,n=""){return ct(e,t.redirections,n,r=>by(e,t,n,r))}async function by(e,t,n,r){let s=new Pn(e),i=0,o=0,a=nd(r.stdin,n),l=e.state.groupStdin;a.owns&&(e.state.groupStdin=a.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&wn(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=await Ia(e,t.condition);if(s.append(c.stdout,c.stderr),c.exitCode===0)break;try{for(let u of t.body){let f=await e.executeStatement(u);s.append(f.stdout,f.stderr),i=f.exitCode}}catch(u){let f=Vr(u,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--,a.owns&&(e.state.groupStdin=l)}return s.build(i)}async function ld(e,t){return ct(e,t.redirections,"",()=>Sy(e,t))}async function Sy(e,t){let n=new Pn(e),r=0,s=await ae(e,t.word),i=!1;for(let o=0;o<t.items.length;o++){let a=t.items[o],l=i;if(!i)for(let c of a.patterns){let u=await ae(e,c);Iu(c)&&(u=ot(u));let f=e.state.shoptOptions.nocasematch,d=e.state.shoptOptions.extglob;if(rr(s,u,f,d,e.limits.maxCallDepth)){l=!0;break}}if(l){let c=await Ta(e,a.body,n);if(n.replace(c.stdout,c.stderr),r=c.exitCode,a.terminator===";;")break;a.terminator===";&"?i=!0:i=!1}else i=!1}return n.build(r)}function _a(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 cd(e,t,n){let r=t.timed?Ii():0,s="",i=se,o=0,a=[],l="",c=0,u=t.commands.length>1,f=e.state.lastArg,d=e.state.groupStdin,h=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;u&&(e.state.lastArg="",e.state.groupStdin=A?d:void 0,e.state.groupStdinSourceFd=A?h:void 0);let k=u&&(!b||!e.state.shoptOptions.lastpipe),v=k?new Map(e.state.env):null,$=k?ht(e.state.arrays):null,O,P=e.executionScope.outputBytesUsed;try{e.state.commandCount=e.executionScope.chargeCommand(),O=await n(y,s)}catch(N){if(N instanceof rt)O={stdout:N.stdout,stderr:N.stderr,exitCode:1};else if(N instanceof G&&t.commands.length>1)O={stdout:N.stdout,stderr:N.stderr,exitCode:N.exitCode};else if(N instanceof Qe&&t.commands.length>1)O={stdout:N.stdout,stderr:N.stderr,exitCode:N.exitCode};else throw v&&(e.state.env=v,e.state.arrays=$??new Map),N}finally{u&&(A&&(d=e.state.groupStdin,h=e.state.groupStdinSourceFd),e.state.groupStdin=d,e.state.groupStdinSourceFd=h)}if(v&&(e.state.env=v,e.state.arrays=$??new Map),O=e.executionScope.accountResult(O,"pipeline",e.executionScope.outputBytesUsed-P),!b){let N=t.pipeStderr?.[g]??!1,D=O.internalOutputAccounting?.stdout??0,V=N?O.internalOutputAccounting?.stderr??0:0;dl(e.executionScope,D+V,"pipeline"),O={...O,internalOutputAccounting:{stdout:0,stderr:N?0:O.internalOutputAccounting?.stderr??0}}}a.push(O.exitCode),O.exitCode!==0&&(o=O.exitCode),b?i=O:(t.pipeStderr?.[g]??!1?s=Yt(O.stderr)+Ut(O):(s=Ut(O),l+=O.stderr,c+=O.internalOutputAccounting?.stderr??0),i={stdout:"",stderr:"",exitCode:O.exitCode})}l&&(i={...i,stderr:l+i.stderr,internalOutputAccounting:{stdout:i.internalOutputAccounting?.stdout??0,stderr:c+(i.internalOutputAccounting?.stderr??0)}});let p=t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand",m=i.internalPipeStatusOverride??a;if(p){be(e,"PIPESTATUS");for(let g=0;g<m.length;g++)H(e,"PIPESTATUS",g,String(m[g]))}if(e.state.options.pipefail&&o!==0&&(i={...i,exitCode:o}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let y=(Ii()-r)/1e3,b=Math.floor(y/60),A=y%60,k;t.timePosix?k=`real ${y.toFixed(2)}
770
+ `),o=1}return F(s,i,o)}async function td(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 o=`${s.startsWith("/")?s:e.fs.resolvePath(e.state.cwd,s)}/${t}`;if(await e.fs.exists(o)){try{let a=await e.fs.stat(o);if(a.isDirectory||(a.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 nd(e,t){let n=!0,r=e.signal?new AbortController:void 0,s=new WeakMap,i=()=>{if(!n)throw new it("",`bash: ${t} used its context after cancellation
771
+ `)},o=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"&&pl(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(b=>(i(),o(b)));return s.set(f,E),E}if(typeof f=="function"){let E=function(...b){return i(),o(Reflect.apply(f,this,b))};return s.set(f,E),E}let h=Object.getPrototypeOf(f);if(Array.isArray(f)||h===Object.prototype||h===null){let E=Array.isArray(f)?[]:Object.create(h);s.set(f,E);let b=Object.getOwnPropertyDescriptors(f);for(let y of Object.values(b)){if("value"in y){let g=y.value;y.value=typeof g=="function"?(...S)=>(i(),o(Reflect.apply(g,f,S))):o(g)}if(y.get){let g=y.get;y.get=()=>(i(),o(Reflect.apply(g,f,[])))}if(y.set){let g=y.set;y.set=S=>{i(),Reflect.apply(g,f,[S])}}}return Object.defineProperties(E,b),E}let p=new Map,m=new tl(f,{get(E,b){if(i(),b==="constructor"||b==="prototype"||b==="__proto__")throw new Error(`${t}: unsafe context property access`);let y=Reflect.get(E,b,E);if(typeof y!="function")return o(y);if(p.has(b))return p.get(b);let g=(...S)=>(i(),o(Reflect.apply(y,E,S)));return p.set(b,g),g},set(E,b,y){if(i(),b==="constructor"||b==="prototype"||b==="__proto__")throw new Error(`${t}: unsafe context property access`);return Reflect.set(E,b,y,E)}});return s.set(f,m),m},a=f=>o(f),l=f=>f&&((...d)=>(i(),o(f(...d)))),c=f=>({value:f,enumerable:!0,configurable:!0,writable:!0}),u=Object.getOwnPropertyDescriptors(e);return Object.assign(u,{fs:c(a(e.fs)),env:c(a(e.env)),limits:c(Object.freeze({...e.limits})),exportedEnv:c(e.exportedEnv?Object.freeze({...e.exportedEnv}):void 0),executionScope:c(e.executionScope?a(e.executionScope):void 0),fileDescriptors:c(e.fileDescriptors?a(e.fileDescriptors):void 0),coverage:c(e.coverage?a(e.coverage):void 0),assignShellVariable:c(l(e.assignShellVariable)),exec:c(l(e.exec)),origCommand:c(l(e.origCommand)),execWithInheritedStdin:c(l(e.execWithInheritedStdin)),fetch:c(l(e.fetch)),getRegisteredCommands:c(l(e.getRegisteredCommands)),sleep:c(l(e.sleep)),trace:c(l(e.trace)),invokeTool:c(l(e.invokeTool)),signal:c(r?.signal)}),{context:Object.defineProperties(Object.create(Object.getPrototypeOf(e)),u),revoke(){n=!1,r?.signal.aborted||r?.abort(new it("",`bash: ${t} context revoked
772
+ `))}}}async function Ey(e,t,n,r,s,i){let o=s.remainingTimeMs()??t.limits.maxExecutionTimeMs,a=t.limits.maxExtensionCleanupTimeMs,l,c,u,d=Promise.resolve().then(e).then(p=>({kind:"result",result:p}),p=>({kind:"error",error:p})),h=new Promise(p=>{let m=()=>{n(),p({kind:"abort"})};c=m,i?.addEventListener("abort",m,{once:!0}),i?.aborted&&m(),l=yr(()=>{n(),p({kind:"deadline"})},o)});try{let p=await Promise.race([d,h]);if(p.kind==="result")return p.result;if(p.kind==="error")throw p.error;n();let m=await Promise.race([d.then(()=>!0),new Promise(b=>{u=yr(()=>b(!1),a)})]),E=p.kind==="deadline"?new it("",`bash: ${r} exceeded its execution deadline
773
+ `):new it("",`bash: execution aborted
774
+ `);throw m||s.poisonAfterAbort(E),E}finally{n(),gr(l),gr(u),c&&i?.removeEventListener("abort",c)}}var rd={export:(e,t)=>Sa(e.ctx,t),unset:(e,t)=>Ia(e.ctx,t),exit:(e,t)=>ba(e.ctx,t),local:(e,t)=>xa(e.ctx,t),set:(e,t)=>Ra(e.ctx,t),break:(e,t)=>To(e.ctx,t),continue:(e,t)=>la(e.ctx,t),return:(e,t)=>$a(e.ctx,t),shift:(e,t)=>Oa(e.ctx,t),getopts:(e,t)=>di(e.ctx,t),compgen:(e,t)=>ra(e.ctx,t),complete:(e,t)=>oa(e.ctx,t),compopt:(e,t)=>aa(e.ctx,t),pushd:(e,t)=>ya(e.ctx,t),popd:(e,t)=>ga(e.ctx,t),dirs:(e,t)=>wa(e.ctx,t),source:(e,t)=>mi(e.ctx,t),".":(e,t)=>mi(e.ctx,t),read:(e,t,n)=>Pa(e.ctx,t,n.stdin,n.stdinSourceFd),mapfile:(e,t,n)=>hi(e.ctx,t,n.stdin),readarray:(e,t,n)=>hi(e.ctx,t,n.stdin),declare:(e,t)=>fi(e.ctx,t),typeset:(e,t)=>fi(e.ctx,t),readonly:(e,t)=>pa(e.ctx,t),eval:(e,t,n)=>Ea(e.ctx,t,n.stdin,n.stdinRedirected),cd:(e,t)=>_o(e.ctx,t),":":()=>ne,true:()=>ne,false:()=>Se(!1),let:(e,t)=>ka(e.ctx,t),command:(e,t,n)=>by(e,t,n.stdin,n.stdinRedirected),builtin:(e,t,n)=>Sy(e,t,n.stdin,n.stdinRedirected),shopt:(e,t)=>Ef(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)=>Yf(e.ctx,t,n=>td(e.ctx,n),n=>hs(e.ctx,n)),hash:(e,t)=>Aa(e.ctx,t),help:(e,t)=>va(e.ctx,t),"[":(e,t)=>t[t.length-1]!=="]"?L("[: missing `]'\n",2):ir(e.ctx,t.slice(0,-1)),test:(e,t)=>ir(e.ctx,t)};async function sd(e,t,n,r,s,i,o,a,l=!1){let{ctx:c}=e;c.coverage&&Tt.has(t)&&c.coverage.hit(`bash:builtin:${t}`);let u={stdin:s,stdinRedirected:l,stdinSourceFd:a},f=sl(t),d=(f==="early"||f==="late")&&Object.hasOwn(rd,t)?rd[t]:void 0;if(d&&(f==="early"||c.state.options.posix&&il(t)))return d(e,n,u);if(!i){let h=c.state.functions.get(t);if(h)return ai(c,h,n,s,void 0,l)}if(t==="__just_bash_tee_restore"){if(n.length===0||n.length>c.limits.maxArrayElements)return L(`bash: invalid internal pipeline status restore
775
+ `,2);let h=[];for(let E of n){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(E))return L(`bash: invalid internal pipeline status restore
776
+ `,2);let b=Number(E);if(!Number.isSafeInteger(b)||b>255)return L(`bash: invalid internal pipeline status restore
777
+ `,2);h.push(b)}let p=h[h.length-1]??0,m=[...h].reverse().find(E=>E!==0);return{stdout:"",stderr:"",exitCode:c.state.options.pipefail&&m!==void 0?m:p,internalPipeStatusOverride:h}}return d&&f==="late"?d(e,n,u):null}async function by(e,t,n,r=!1){let{ctx:s,runCommand:i}=e;if(t.length===0)return ne;let o=!1,a=!1,l=!1,c=t;for(;c.length>0&&c[0].startsWith("-");){let d=c[0];if(d==="--"){c=c.slice(1);break}for(let h of d.slice(1))h==="p"?o=!0:h==="V"?a=!0:h==="v"&&(l=!0);c=c.slice(1)}if(c.length===0)return ne;if(l||a)return await ed(s,c,l,a);let[u,...f]=c;return i(u,f,[],n,!0,o,-1,r)}async function Sy(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 o=i[0];if(o!=="__just_bash_tee_restore"&&!Tt.has(o))return L(`bash: builtin: ${o}: not a shell builtin
778
+ `);let[,...a]=i;return s(o,a,[],n,!0,!1,-1,r)}async function id(e,t,n,r,s){let{ctx:i,buildExportedEnv:o,executeUserScript:a}=e,c=await ds(i,t,s?"/usr/bin:/bin":void 0);if(!c){i.executionScope.recordUnresolvedCommand(t);let v=i.executionScope.abortOnUnresolvedCommands;if(Zu(t)){let k=`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
779
+ `;if(v)throw new Oe(t,"",k);return L(k,127)}if(v)throw new Oe(t,"",`bash: ${t}: command not found
780
+ `);return L(`bash: ${t}: command not found
781
+ `,127)}if("error"in c)return c.error==="permission_denied"?L(`bash: ${t}: Permission denied
782
+ `,126):L(`bash: ${t}: No such file or directory
783
+ `,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||"",h=!1,p=o();i.state.fileDescriptors??=new Map;let m={fs:i.fs,fsIdentity:as(i.fs),cwd:i.state.cwd,env:i.state.env,assignShellVariable:async(v,k,A)=>{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(v))throw new Error(`${v}: not a valid identifier`);let $=A===void 0?v:`${v}[${A}]`,R=$s(i,v,k);if(R===void 0)throw new Error(`${v}: circular name reference`);if(R===null)return;let P=R.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(?:\[(.*)\])?$/);if(!P)throw new Error(`${$}: not a valid identifier`);let N=P[1],I=P[2]??A;if(Ze(i,v)||Ze(i,N))throw new Error(`${N}: readonly variable`);if(I===void 0)i.state.env.set(N,k);else{let z=i.state.associativeArrays?.has(N)?"associative":"indexed";if(z==="associative"){G(i,N,I,k,z);return}let X=await _a(i,N,I);if(X.error)throw new H(X.error.exitCode,X.error.stdout,X.error.stderr);G(i,N,X.index,k,z)}},exportedEnv:p,get stdin(){return h=!0,d},limits:i.limits,executionScope:u.internalIsExtension?El(i.executionScope):i.executionScope,exec:(v,k)=>i.execFn(v,k,!1),execWithInheritedStdin:(v,k)=>i.execFn(v,{...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=u.internalOriginalCommand,b=()=>{};if(E){let v=Object.getOwnPropertyDescriptors(m);v.executionScope={value:i.executionScope,enumerable:!0,configurable:!0,writable:!0};let k=Object.defineProperties(Object.create(Object.getPrototypeOf(m)),v),A=nd(k,E.name),$=Ta(A.context,E.name);b=A.revoke,m.origCommand=R=>{let P=()=>E.execute(R,$);return E.trusted?Re.runTrustedAsync(P):Re.runUntrustedAsync(P)}}let y=nd(m,t),g=Ta(y.context,t),S=()=>{y.revoke(),b()};try{if(!u.handlesOwnVersion&&n.slice(0,n.indexOf("--")===-1?void 0:n.indexOf("--")).includes("--version"))return{stdout:`${t} (just-bash)
784
+ `,stderr:"",exitCode:0};let v=()=>el(i.requireDefenseContext,"command",`${t} execution`,()=>u.execute(n,g)),k=()=>Ey(v,g,S,t,i.executionScope,i.state.signal),A=u.trusted?await Re.runTrustedAsync(k):await k();return{...A,internalStdinConsumed:A.internalStdinConsumed??(h?r.length:0)}}catch(v){return ns(v),L(`${t}: ${It(Ht(v))}
785
+ `)}}async function La(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=new ln(e.executionScope,"condition"),s=0;try{for(let i of t){let o=await e.executeStatement(i);r.appendResult(o),s=o.exitCode}}catch(i){throw r.prependTo(i),i}finally{e.state.inCondition=n}return r.build(s)}var gi=0;function dr(e,t){return e.state.lastExitCode=t,e.state.env.set("?",String(t)),t}function jr(e,t,n,r){if(e instanceof nt)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,exitCode:gi};if(e instanceof rt)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,exitCode:gi};if(ts(e)||e instanceof Ve||e instanceof Ke||e instanceof H)return e instanceof en&&e.prependOutput(t,n),{action:"rethrow",stdout:t,stderr:n,error:e};let s=Ht(e);return{action:"error",stdout:t,stderr:`${n}${s}
786
+ `,exitCode:1}}function od(e,t){return e!==void 0?{owns:!0,stdin:e}:t!==""?{owns:!0,stdin:t}:{owns:!1}}var Cn=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&&bn(`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 Fa(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(Jr(s)||s instanceof Ke||s instanceof H||s instanceof Oe||s instanceof C||s instanceof nn)throw s.prependOutput(n.stdout,n.stderr),s;return n.appendUnaccounted("",`${Ht(s)}
787
+ `),n.build(1)}return n.build(r)}async function ad(e,t){return ft(e,t.redirections,"",()=>Ay(e,t))}async function Ay(e,t){let n=new Cn(e);for(let r of t.clauses){let s=await La(e,r.condition);if(n.append(s.stdout,s.stderr),s.exitCode===0)return Fa(e,r.body,n)}return t.elseBody?Fa(e,t.elseBody,n):n.build(0)}async function ld(e,t){return ft(e,t.redirections,"",()=>vy(e,t))}async function vy(e,t){let n=new Cn(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
788
+ `);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 o of t.words){let a=await Rt(e,o);Le(i,a.values,e.limits.maxArrayElements,"for-loop expansion")}}catch(o){if(o instanceof tn)return{stdout:"",stderr:o.stderr,exitCode:1};throw o}e.state.loopDepth++;try{for(let o of i){s++,s>e.limits.maxLoopIterations&&bn(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n.stdout,n.stderr),e.state.env.set(t.variable,o);try{for(let a of t.body){let l=await e.executeStatement(a);n.append(l.stdout,l.stderr),r=l.exitCode}}catch(a){let l=jr(a,n.stdout,n.stderr,e.state.loopDepth);if(n.replace(l.stdout,l.stderr),l.exitCode!==void 0&&(r=dr(e,l.exitCode)),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 cd(e,t){return ft(e,t.redirections,"",()=>ky(e,t))}async function ky(e,t){let n=t.line;n!==void 0&&(e.state.currentLine=n);let r=new Cn(e),s=0,i=0;t.init&&await ee(e,t.init.expression),e.state.loopDepth++;try{for(;i++,i>e.limits.maxLoopIterations&&bn(`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 ee(e,t.condition.expression)===0));){try{for(let o of t.body){let a=await e.executeStatement(o);r.append(a.stdout,a.stderr),s=a.exitCode}}catch(o){let a=jr(o,r.stdout,r.stderr,e.state.loopDepth);if(r.replace(a.stdout,a.stderr),a.exitCode!==void 0&&(s=dr(e,a.exitCode)),a.action==="break")break;if(a.action==="continue"){t.update&&await ee(e,t.update.expression);continue}if(a.action==="error")return r.build(a.exitCode??1);throw a.error}t.update&&await ee(e,t.update.expression)}}finally{e.state.loopDepth--}return r.build(s)}async function ud(e,t,n=""){return ft(e,t.redirections,n,r=>xy(e,t,n,r))}async function xy(e,t,n,r){let s=new Cn(e),i=0,o=0,a=od(r.stdin,n),l=e.state.groupStdin;a.owns&&(e.state.groupStdin=a.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&bn(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=0,u=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let h of t.condition){let p=await e.executeStatement(h);s.append(p.stdout,p.stderr),c=p.exitCode}}catch(h){if(h instanceof nt){if(s.append(h.stdout,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,e.state.inCondition=d,h;u=!0}else if(h instanceof rt){if(s.append(h.stdout,h.stderr),h.levels>1&&e.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,e.state.inCondition=d,h;f=!0}else throw e.state.inCondition=d,h}finally{e.state.inCondition=d}if((u||f)&&(i=dr(e,gi)),u)break;if(!f){if(c!==0)break;try{for(let h of t.body){let p=await e.executeStatement(h);s.append(p.stdout,p.stderr),i=p.exitCode}}catch(h){let p=jr(h,s.stdout,s.stderr,e.state.loopDepth);if(s.replace(p.stdout,p.stderr),p.exitCode!==void 0&&(i=dr(e,p.exitCode)),p.action==="break")break;if(p.action==="continue")continue;if(p.action==="error")return s.build(p.exitCode??1);throw p.error}}}}finally{e.state.loopDepth--,a.owns&&(e.state.groupStdin=l)}return s.build(i)}async function fd(e,t,n=""){return ft(e,t.redirections,n,r=>Py(e,t,n,r))}async function Py(e,t,n,r){let s=new Cn(e),i=0,o=0,a=od(r.stdin,n),l=e.state.groupStdin;a.owns&&(e.state.groupStdin=a.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&bn(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=await La(e,t.condition);if(s.append(c.stdout,c.stderr),c.exitCode===0)break;try{for(let u of t.body){let f=await e.executeStatement(u);s.append(f.stdout,f.stderr),i=f.exitCode}}catch(u){let f=jr(u,s.stdout,s.stderr,e.state.loopDepth);if(s.replace(f.stdout,f.stderr),f.exitCode!==void 0&&(i=dr(e,f.exitCode)),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--,a.owns&&(e.state.groupStdin=l)}return s.build(i)}async function dd(e,t){return ft(e,t.redirections,"",()=>$y(e,t))}async function $y(e,t){let n=new Cn(e),r=0,s=await ie(e,t.word),i=!1;for(let o=0;o<t.items.length;o++){let a=t.items[o],l=i;if(!i)for(let c of a.patterns){let u=await ie(e,c);Fu(c)&&(u=lt(u));let f=e.state.shoptOptions.nocasematch,d=e.state.shoptOptions.extglob;if(sr(s,u,f,d,e.limits.maxCallDepth)){l=!0;break}}if(l){let c=await Fa(e,a.body,n);if(n.replace(c.stdout,c.stderr),r=c.exitCode,a.terminator===";;")break;a.terminator===";&"?i=!0:i=!1}else i=!1}return n.build(r)}function Ma(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 hd(e,t,n){let r=t.timed?Li():0,s="",i=ne,o=0,a=[],l="",c=0,u=t.commands.length>1,f=e.state.lastArg,d=e.state.groupStdin,h=e.state.groupStdinSourceFd;for(let y=0;y<t.commands.length;y++){let g=t.commands[y],S=y===t.commands.length-1,v=y===0;u&&(e.state.lastArg="",e.state.groupStdin=v?d:void 0,e.state.groupStdinSourceFd=v?h:void 0);let k=u&&(!S||!e.state.shoptOptions.lastpipe),A=k?new Map(e.state.env):null,$=k?mt(e.state.arrays):null,R,P=e.executionScope.outputBytesUsed;try{e.state.commandCount=e.executionScope.chargeCommand(),R=await n(g,s)}catch(N){if(N instanceof st)R={stdout:N.stdout,stderr:N.stderr,exitCode:1};else if(N instanceof H&&t.commands.length>1)R={stdout:N.stdout,stderr:N.stderr,exitCode:N.exitCode};else if(N instanceof Ke&&t.commands.length>1)R={stdout:N.stdout,stderr:N.stderr,exitCode:N.exitCode};else throw A&&(e.state.env=A,e.state.arrays=$??new Map),N}finally{u&&(v&&(d=e.state.groupStdin,h=e.state.groupStdinSourceFd),e.state.groupStdin=d,e.state.groupStdinSourceFd=h)}if(A&&(e.state.env=A,e.state.arrays=$??new Map),R=e.executionScope.accountResult(R,"pipeline",e.executionScope.outputBytesUsed-P),!S){let N=t.pipeStderr?.[y]??!1,I=R.internalOutputAccounting?.stdout??0,z=N?R.internalOutputAccounting?.stderr??0:0;bl(e.executionScope,I+z,"pipeline"),R={...R,internalOutputAccounting:{stdout:0,stderr:N?0:R.internalOutputAccounting?.stderr??0}}}a.push(R.exitCode),R.exitCode!==0&&(o=R.exitCode),S?i=R:(t.pipeStderr?.[y]??!1?s=Jt(R.stderr)+qt(R):(s=qt(R),l+=R.stderr,c+=R.internalOutputAccounting?.stderr??0),i={stdout:"",stderr:"",exitCode:R.exitCode})}l&&(i={...i,stderr:l+i.stderr,internalOutputAccounting:{stdout:i.internalOutputAccounting?.stdout??0,stderr:c+(i.internalOutputAccounting?.stderr??0)}});let p=t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand",m=i.internalPipeStatusOverride??a;if(p){be(e,"PIPESTATUS");for(let y=0;y<m.length;y++)G(e,"PIPESTATUS",y,String(m[y]))}if(e.state.options.pipefail&&o!==0&&(i={...i,exitCode:o}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let g=(Li()-r)/1e3,S=Math.floor(g/60),v=g%60,k;t.timePosix?k=`real ${g.toFixed(2)}
783
789
  user 0.00
784
790
  sys 0.00
785
791
  `:k=`
786
- real ${`${b}m${A.toFixed(3)}s`}
792
+ real ${`${S}m${v.toFixed(3)}s`}
787
793
  user 0m0.000s
788
794
  sys 0m0.000s
789
- `,i={...i,stderr:i.stderr+k}}u&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=f),i=e.executionScope.accountResult(i,"pipeline");let{internalPipeStatusOverride:E,...S}=i;return S}function La(e){return e?{...e,options:e.options?[...e.options]:void 0,actions:e.actions?[...e.actions]:void 0}:void 0}function Ay(e){return e?new Map(Array.from(e,([t,n])=>[t,La(n)])):void 0}function vy(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 ky(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 xy(e){return e?new Map(Array.from(e,([t,n])=>[t,n.map(r=>({...r}))])):void 0}function Fa(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=ht(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=vy(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=ky(e.localArrayScopes),e.localVarDepth=e.localVarDepth?new Map(e.localVarDepth):void 0,e.localVarStack=xy(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=Ay(e.completionSpecs),e.defaultCompletionSpec=La(e.defaultCompletionSpec),e.emptyCompletionSpec=La(e.emptyCompletionSpec);let n=!1;return()=>{n||(n=!0,Object.assign(e,t))}}async function ud(e,t,n,r,s=!1){let i=e.state.loopDepth,o=new Map;for(let l of e.state.fileDescriptors?.keys()??[]){let c=lt(e,l);c&&o.set(l,c)}let a=Fa(e.state);e.state.parentHasLoopContext=i>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;try{return await ct(e,t.redirections,n,l=>Py(e,t,l.stdin??n,r,s||l.stdin!==void 0))}finally{let l=new Map;for(let[c,u]of o){let f=lt(e,c),d=u.kind==="input"&&f?.kind==="input"?u.content.length-f.content.length:u.kind==="readwrite"&&f?.kind==="readwrite"&&u.path===f.path?f.position-u.position:0;if(d<=0)continue;let h=Math.min(...Sn(e,c));l.set(h,Math.max(l.get(h)??0,d))}a();for(let[c,u]of l)An(e,c,u)}}async function Py(e,t,n,r,s){(s||n)&&(e.state.groupStdin=n);let i=new an(e.executionScope,"subshell"),o=0;try{for(let a of t.body){let l=await r(a);i.appendResult(l),o=l.exitCode}}catch(a){if(a instanceof C)throw i.prependTo(a),a;if(a instanceof tn||a instanceof tt||a instanceof nt)return i.append("stdout",a.stdout,a.internalOutputAccounting.stdout),i.append("stderr",a.stderr,a.internalOutputAccounting.stderr),i.build(0);if(a instanceof G||a instanceof We||a instanceof Qe)return i.append("stdout",a.stdout,a.internalOutputAccounting.stdout),i.append("stderr",a.stderr,a.internalOutputAccounting.stderr),i.build(a.exitCode);if(a instanceof Oe)throw a.prependOutput(i.stdout,i.stderr),a;return i.append("stderr",`${jt(a)}
790
- `),i.build(1)}return i.build(o)}async function fd(e,t,n,r,s=!1){return ct(e,t.redirections,n,i=>$y(e,t,n,r,s,i))}async function $y(e,t,n,r,s,i){let o=new an(e.executionScope,"group"),a=0,l=i.stdin??n,c=s||n!==""||i.stdin!==void 0,u=e.state.groupStdin;c&&(e.state.groupStdin=l);let f=()=>{(c||u!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=u)};try{for(let d of t.body){let h=await r(d);o.appendResult(h),a=h.exitCode}}catch(d){if(f(),d instanceof C)throw o.prependTo(d),d;if(Xr(d)||d instanceof Qe||d instanceof G||d instanceof Oe)throw d.prependOutput(o.stdout,o.stderr),d;return o.append("stderr",`${jt(d)}
791
- `),o.build(1)}return f(),o.build(a)}async function dd(e,t,n,r,s){let i;try{i=await e.fs.readFile(t)}catch{return _(`bash: ${t}: No such file or directory
795
+ `,i={...i,stderr:i.stderr+k}}u&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=f),i=e.executionScope.accountResult(i,"pipeline");let{internalPipeStatusOverride:E,...b}=i;return b}function Ba(e){return e?{...e,options:e.options?[...e.options]:void 0,actions:e.actions?[...e.actions]:void 0}:void 0}function Cy(e){return e?new Map(Array.from(e,([t,n])=>[t,Ba(n)])):void 0}function Ny(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 Ry(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 Oy(e){return e?new Map(Array.from(e,([t,n])=>[t,n.map(r=>({...r}))])):void 0}function Wa(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=mt(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=Ny(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=Ry(e.localArrayScopes),e.localVarDepth=e.localVarDepth?new Map(e.localVarDepth):void 0,e.localVarStack=Oy(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=Cy(e.completionSpecs),e.defaultCompletionSpec=Ba(e.defaultCompletionSpec),e.emptyCompletionSpec=Ba(e.emptyCompletionSpec);let n=!1;return()=>{n||(n=!0,Object.assign(e,t))}}async function pd(e,t,n,r,s=!1){let i=e.state.loopDepth,o=new Map;for(let l of e.state.fileDescriptors?.keys()??[]){let c=ut(e,l);c&&o.set(l,c)}let a=Wa(e.state);e.state.parentHasLoopContext=i>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;try{return await ft(e,t.redirections,n,l=>Dy(e,t,l.stdin??n,r,s||l.stdin!==void 0))}finally{let l=new Map;for(let[c,u]of o){let f=ut(e,c),d=u.kind==="input"&&f?.kind==="input"?u.content.length-f.content.length:u.kind==="readwrite"&&f?.kind==="readwrite"&&u.path===f.path?f.position-u.position:0;if(d<=0)continue;let h=Math.min(...vn(e,c));l.set(h,Math.max(l.get(h)??0,d))}a();for(let[c,u]of l)kn(e,c,u)}}async function Dy(e,t,n,r,s){(s||n)&&(e.state.groupStdin=n);let i=new ln(e.executionScope,"subshell"),o=0;try{for(let a of t.body){let l=await r(a);i.appendResult(l),o=l.exitCode}}catch(a){if(a instanceof C)throw i.prependTo(a),a;if(a instanceof nn||a instanceof nt||a instanceof rt)return i.append("stdout",a.stdout,a.internalOutputAccounting.stdout),i.append("stderr",a.stderr,a.internalOutputAccounting.stderr),i.build(0);if(a instanceof H||a instanceof Ve||a instanceof Ke)return i.append("stdout",a.stdout,a.internalOutputAccounting.stdout),i.append("stderr",a.stderr,a.internalOutputAccounting.stderr),i.build(a.exitCode);if(a instanceof Oe)throw a.prependOutput(i.stdout,i.stderr),a;return i.append("stderr",`${Ht(a)}
796
+ `),i.build(1)}return i.build(o)}async function md(e,t,n,r,s=!1){return ft(e,t.redirections,n,i=>Iy(e,t,n,r,s,i))}async function Iy(e,t,n,r,s,i){let o=new ln(e.executionScope,"group"),a=0,l=i.stdin??n,c=s||n!==""||i.stdin!==void 0,u=e.state.groupStdin;c&&(e.state.groupStdin=l);let f=()=>{(c||u!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=u)};try{for(let d of t.body){let h=await r(d);o.appendResult(h),a=h.exitCode}}catch(d){if(f(),d instanceof C)throw o.prependTo(d),d;if(Jr(d)||d instanceof Ke||d instanceof H||d instanceof Oe)throw d.prependOutput(o.stdout,o.stderr),d;return o.append("stderr",`${Ht(d)}
797
+ `),o.build(1)}return f(),o.build(a)}async function yd(e,t,n,r,s){let i;try{i=await e.fs.readFile(t)}catch{return L(`bash: ${t}: No such file or directory
792
798
  `,127)}if(i.startsWith("#!")){let l=i.indexOf(`
793
- `);l!==-1&&(i=i.slice(l+1))}let o=e.state.loopDepth,a=Fa(e.state);e.state.parentHasLoopContext=o>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 c=new Q().parse(i),u=await s(c);return a(),u}catch(l){if(a(),l instanceof G)return F(l.stdout,l.stderr,l.exitCode);if(l instanceof Oe||l instanceof C)throw l;if(l.name==="ParseException")return _(`bash: ${t}: ${l.message}
794
- `);throw l}}function Cy(e){throw new TypeError(`Unsupported command node: ${JSON.stringify(e)}`)}var zr=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||Re.isInSandboxedContext())return;let n=`interpreter ${t} attempted outside defense context`;throw new qn(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:Re.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 o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(t){this.assertDefenseContext("execution");let n=0,r=new an(this.ctx.executionScope,"script");for(let s of t.statements)try{let i=await this.executeStatement(s);r.appendResult(i,Oi(i)),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(i){if(i instanceof G||i instanceof Oe)throw i.prependOutput(r.stdout,r.stderr),i;if(i instanceof ut)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:on(this.ctx.state.env)};if(Yr(i))throw r.prependTo(i),i;if(i instanceof Qe)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:on(this.ctx.state.env)};if(i instanceof Ke)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:on(this.ctx.state.env)};if(i instanceof rt)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:on(this.ctx.state.env)};if(i instanceof ue){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 Kr){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 tt||i instanceof nt){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 We&&i.prependOutput(r.stdout,r.stderr),i}return{...r.build(n),env:on(this.ctx.state.env)}}async executeUserScript(t,n,r=""){return dd(this.ctx,t,n,r,s=>this.executeScript(s))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new st;if(t.deferredError)throw new Ce(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return se;this.ctx.state.errexitSafe=!1;let n=new an(this.ctx.executionScope,"statement");this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&n.append("stderr",`${t.sourceText}
795
- `);let r=0,s=-1,i=!1;try{for(let l=0;l<t.pipelines.length;l++){let c=t.pipelines[l],u=l>0?t.operators[l-1]:null;if(u==="&&"&&r!==0||u==="||"&&r===0)continue;let f=await this.executePipeline(c);n.appendResult(f,Oi(f)),r=f.exitCode,s=l,i=c.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set("?",String(r))}}catch(l){throw n.prependTo(l),l}let o=s<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||i||a,this.ctx.state.options.errexit&&r!==0&&s===t.pipelines.length-1&&!i&&!this.ctx.state.inCondition&&!a){let l=new Qe(r);throw l.prependOutput(n.stdout,n.stderr),l}return n.build(r)}async executePipeline(t){return cd(this.ctx,t,(n,r)=>this.executeCommand(n,r))}async executeCommand(t,n,r=!1){let s=Ou(this.ctx),i;try{i=await this.executeCommandInner(t,n,r)}catch(a){throw await $o(this.ctx,s).catch(()=>{}),a}let o=await $o(this.ctx,s);return!o.stdout&&!o.stderr?i:{...i,stdout:o.stdout?Ut(i)+o.stdout:i.stdout,stdoutKind:o.stdout?"bytes":i.stdoutKind,stderr:i.stderr+o.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 rd(this.ctx,t);case"For":return sd(this.ctx,t);case"CStyleFor":return id(this.ctx,t);case"While":return od(this.ctx,t,n);case"Until":return ad(this.ctx,t,n);case"Case":return ld(this.ctx,t);case"Subshell":return this.executeSubshell(t,n,r);case"Group":return this.executeGroup(t,n,r);case"FunctionDef":return df(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return Cy(t)}}async executeSimpleCommand(t,n){let r;try{return await this.executeSimpleCommandInner(t,n,s=>{r=s})}catch(s){if(r?.finish(),s instanceof en)return _(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 P=t,N=0;for(;;){let D=this.expandAlias(P);if(D===P)break;if(N>=this.ctx.limits.maxCallDepth)throw new C(`alias expansion depth limit exceeded (${this.ctx.limits.maxCallDepth})`,"recursion");N++,P=D}this.aliasExpansionStack.clear(),P!==t&&(t=P)}this.ctx.state.expansionStderr="",this.ctx.state.lastSubstitutionExitCode=null;let s=await jf(this.ctx,t);if(s.error)return s.error;let i=s.tempAssignments,o=s.xtraceOutput,a=()=>{for(let[P,N]of i)N===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,N)};if(!t.name){if(t.redirections.length>0){let N=ar(this.ctx,t.redirections,uf);r(N);let D=await N.prepare(n);if(D.error){if(a(),!D.errorCause)return N.finish(),D.error;try{return lr(D)}finally{N.finish()}}let V=F("",o,Ns(this.ctx.state,t.redirections)),X=await kn(this.ctx,V,t.redirections,D.targets,D.dupSources,D.standardRoutes);return N.finish(),X}this.ctx.state.lastArg="";let P=(this.ctx.state.expansionStderr||"")+o;return this.ctx.state.expansionStderr="",F("",P,Ns(this.ctx.state,[]))}let l=t.name&&_a(t.name,["local","declare","typeset","export","readonly"]),c=Array.from(i.keys());if(c.length>0&&!l){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let P of c)this.ctx.state.tempExportedVars.add(P)}let u=await ae(this.ctx,t.name),f=[],d=[],h=(P,N)=>{if(f.length>=this.ctx.limits.maxArrayElements)throw new C(`expanded argument element limit exceeded (${this.ctx.limits.maxArrayElements})`,"array_elements");f.push(P),d.push(N)};if(_a(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let P of t.args){let N=await zu(this.ctx,P);if(N)h(N,!0);else{let D=await Uu(this.ctx,P);if(D!==null)h(D,!0);else{let V=await Ct(this.ctx,P);for(let X of V.values)h(X,V.quoted)}}}else for(let P of t.args){let N=await Ct(this.ctx,P);for(let D of N.values)h(D,N.quoted)}let m=t.name.parts.every(P=>P.type==="CommandSubstitution"||P.type==="ParameterExpansion"||P.type==="ArithmeticExpansion");!u&&m&&f.length>0&&(u=f.shift(),d.shift());let E=ar(this.ctx,t.redirections,u==="exec"?ff:Tr);r(E);let S=await E.prepare(n);if(S.error)return a(),S.errorCause?lr(S):(E.finish(),S.error);let g=S.stdinSourceFd,y=S.stdin!==void 0;if(S.stdin!==void 0&&(n=S.stdin),!u)return m?(E.finish(),F("","",Ns(this.ctx.state,t.redirections))):(E.finish(),_(`bash: : command not found
796
- `,127));if(u==="exec"&&(f.length===0||f[0]==="--")){for(let[P,N]of i)N===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,N);if(this.ctx.state.tempExportedVars)for(let P of i.keys())this.ctx.state.tempExportedVars.delete(P);return E.finish(),se}if(this.ctx.state.extraArgs){let P=this.ctx.state.extraArgs;this.ctx.state.extraArgs=void 0;for(let N of P)h(N,!0)}let b=await zf(this.ctx,u,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(u,f,d,n,!1,!1,g,y)}catch(P){if(P instanceof tt||P instanceof nt)k=P,A=se;else throw P}g>=0&&u!=="read"&&An(this.ctx,g,A.internalStdinConsumed??0);let v=o+b;if(v&&(A={...A,stderr:v+A.stderr}),A=await kn(this.ctx,A,t.redirections,S.targets,S.dupSources,S.standardRoutes,A.internalProducerCommand??u,A.internalProducerOmitsShellPrefix),E.finish(),k)throw k;if(f.length>0){let P=f[f.length-1];if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(P)){let N=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);N&&(P=N[1])}this.ctx.state.lastArg=P}else this.ctx.state.lastArg=u;let $=Sl(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!$)for(let[P,N]of i)this.ctx.state.fullyUnsetLocals?.has(P)||(N===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,N));if(this.ctx.state.tempExportedVars)for(let P of i.keys())this.ctx.state.tempExportedVars.delete(P);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,o=!1,a=-1,l=!1){let c={ctx:this.ctx,runCommand:(d,h,p,m,E,S,g,y)=>this.runCommand(d,h,p,m,E,S,g,y),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(d,h,p)=>this.executeUserScript(d,h,p)},u=await ed(c,t,n,r,s,i,o,a,l);return u!==null?u.internalProducerCommand===void 0?{...u,internalProducerCommand:t}:u:{...await td(c,t,n,s,o),internalProducerCommand:t}}aliasExpansionStack=new Set;expandAlias(t){return pc({env:this.ctx.state.env,limits:this.ctx.limits},t,this.aliasExpansionStack)}async findCommandInPath(t){return fs(this.ctx,t)}async executeSubshell(t,n="",r=!1){return ud(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeGroup(t,n="",r=!1){return fd(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeArithmeticCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),ct(this.ctx,t.redirections,"",async()=>{try{let n=await ee(this.ctx,t.expression.expression),r=Se(n!==0);return this.ctx.state.expansionStderr&&(r={...r,stderr:this.ctx.state.expansionStderr+r.stderr},this.ctx.state.expansionStderr=""),r}catch(n){return _(`bash: arithmetic expression: ${n.message}
797
- `)}})}async executeConditionalCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),ct(this.ctx,t.redirections,"",async()=>{try{let n=await En(this.ctx,t.expression),r=Se(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 ue?1:2;return _(`bash: conditional expression: ${n.message}
798
- `,r)}})}};function Ma(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Ny(e){let t=Ma(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}var Ry=3;function hd(e){let t=e;for(let n=0;n<Ry;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 Oy(e,t){return t==="/"||t===""?!0:t.endsWith("/")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function Ba(e,t){let n=Ma(e);if(!n)return!1;let r=Ny(t);return!r||n.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&hd(n.pathname)?!1:Oy(n.pathname,r.pathPrefix)}function pd(e){return typeof e=="string"?e:e.url}function md(e,t){return!t||t.length===0?!1:t.some(n=>Ba(e,pd(n)))}function Wa(e){let t=Dy(e);if(t==="localhost"||t.endsWith(".localhost"))return!0;let n=yd(t);if(n)return mi(n);let r=Ty(t);return r?_y(r):!1}function Dy(e){let t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Iy(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 yd(e){let t=e.split(".");if(t.length===0||t.length>4)return null;let n=t.map(l=>Iy(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,c]=r;return l>255||c>16777215?null:[l,c>>>16&255,c>>>8&255,c&255]}if(t.length===3){let[l,c,u]=r;return l>255||c>255||u>65535?null:[l,c,u>>>8&255,u&255]}let[s,i,o,a]=r;return s>255||i>255||o>255||a>255?null:[s,i,o,a]}function Ty(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=yd(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("::"),o=s?s.split(":").filter(Boolean):[],a=i?i.split(":").filter(Boolean):[],l=m=>/^[0-9a-f]{1,4}$/i.test(m)?Number.parseInt(m,16):null,c=o.map(l),u=a.map(l);if(c.some(m=>m===null)||u.some(m=>m===null))return null;let f=n?2:0,d=c.length+u.length+f,h=0;if(r===1){if(h=8-d,h<0)return null}else if(d!==8)return null;let p=[...c,...new Array(h).fill(0),...u];return n&&(p.push(n[0]<<8|n[1]),p.push(n[2]<<8|n[3])),p.length===8?p:null}function mi(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 _y(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 mi(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 mi(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 mi(s)}return!1}function gd(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=pd(n);if(!Ma(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!==""&&hd(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 gt=class extends Error{constructor(t,n){let r=n??"URL not in allow-list";super(`Network access denied: ${r}: ${t}`),this.name="NetworkAccessDeniedError"}},Vn=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},Xt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},yi=class extends Error{constructor(t,n){super(`HTTP method '${t}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}},zn=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Ly=20,Fy=3e4,My=10485760,By=["GET","HEAD"],Ur;typeof __BROWSER__<"u"&&__BROWSER__?Ur=null:(Ur=import("guarded-fetch"),Ur.catch(()=>{}));var Wy=new Set(["GET","HEAD","OPTIONS"]),Vy=new Set([301,302,303,307,308]);function jr(e){return e.reason instanceof Error?e.reason:new DOMException("The operation was aborted","AbortError")}function zy(e){if(e?.aborted)throw jr(e)}function za(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=gd(t);if(b.length>0)throw new Error(`Invalid network allow-list:
799
- ${b.join(`
800
- `)}`)}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(Ba(b,k.url)&&k.transform){A||(A=new Headers);for(let v of k.transform)for(let[$,O]of Object.entries(v.headers))A.set($,O)}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??Ly,o=e.timeoutMs??Fy,a=e.maxResponseSize??My,l=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??By,c=e.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),u=[];for(let b of t){let A=typeof b=="string"?b:b.url;try{u.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?c?{allowedHosts:void 0,skipSsrfCheckForAllowedHosts:void 0}:{allowedHosts:[f(b)],skipSsrfCheckForAllowedHosts:!0}:{allowedHosts:u,skipSsrfCheckForAllowedHosts:!c}}function h(b){try{return Wa(new URL(b).hostname)}catch{return!1}}async function p(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&&!md(b,t))throw new gt(b)}function E(b){if(!c)return;let A;try{A=new URL(b)}catch{throw new gt(b,"invalid URL")}if(Wa(A.hostname))throw new gt(b,"private/loopback IP address blocked")}function S(b){if(e.dangerouslyAllowFullInternetAccess)return;let A=b.toUpperCase();if(!l.includes(A))throw new yi(A,l)}function g(b,A,k,v){if(!k.isGuardedFetchError(b))return b;let $=b,{onRedirectHop:O,subReason:P}=v;switch($.code){case"host_not_allowed":case"protocol_not_allowed":return O?new Xt(A):new gt(A);case"hostname_unsafe":return O?new Xt(A):new gt(A,P==="dns_resolution_failed"?"DNS resolution failed for private IP check":"hostname resolves to private/loopback IP address");case"redirect_to_unsafe_host":return new Xt(A);case"too_many_redirects":return new Vn(i);case"response_too_large":return new zn(a);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,O=Math.min(i,$),P=A.timeoutMs!==void 0?Math.min(A.timeoutMs,o):o,N=new AbortController,D=Hr(()=>N.abort(new DOMException("The operation was aborted","AbortError")),P),V=Qr(A.signal,N.signal);try{m(b),E(b),S(k);let X=Ur?await Ur:null,R=b,j=0,q=[],I=k,T=A.body,B=A.headers,ie=!1;for(;;){zy(V.signal);let J=await Re.runTrustedAsync(async()=>{let Be=B;if(ie&&Be){let zt=Be instanceof Headers?new Headers(Be):new Headers(Be);zt.delete("authorization"),zt.delete("cookie"),Be=zt}let wt=s(R),Vt=jy(Be,wt),Et={method:I,headers:Vt,signal:V.signal,followRedirects:!1,timeoutMs:P,sanitizeHeaders:!1};if(T&&!Wy.has(I)&&(Et.body=T),Object.assign(Et,d(R)),!X||h(R)){if(c)throw new gt(R,"DNS pinning unavailable for private IP enforcement");return await p(R,Et)}c?n&&(Et.fetch=n):(Et.fetch=n??globalThis.fetch,Et.dispatcher=null);let bt;Et.onUrlBlocked=zt=>{bt=zt.subReason};try{return await X.guardedFetch(R,Et)}catch(zt){throw g(zt,R,X,{onRedirectHop:j>0,subReason:bt})}});if(Vy.has(J.status)&&v){let Be=J.headers.get("location");if(!Be)return await wd(J,R,a,V.signal,q);q.push({status:J.status,statusText:J.statusText,headers:Ed(J.headers)});let wt=new URL(Be,R).href;await Va(Uy(J),V.signal);try{m(wt),E(wt)}catch(bt){throw V.signal?.aborted?jr(V.signal):bt instanceof gt?new Xt(wt):bt}let Vt=J.status;if(((Vt===301||Vt===302)&&I==="POST"||Vt===303&&I!=="GET"&&I!=="HEAD")&&(I="GET",T=void 0,S(I)),new URL(wt).origin!==new URL(R).origin&&(ie=!0),j++,j>O)throw new Vn(O);R=wt;continue}return await wd(J,R,a,V.signal,q)}}finally{Zr(D),V.cleanup()}}return y}async function Va(e,t){if(!t)return e;if(t.aborted)throw e.catch(()=>{}),jr(t);let n,r=new Promise((s,i)=>{n=()=>i(jr(t)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,r])}finally{n&&t.removeEventListener("abort",n)}}async function Uy(e){e.body&&!e.body.locked&&await e.body.cancel()}function jy(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 Ed(e){let t=Object.create(null);return e.forEach((n,r)=>{t[r.toLowerCase()]=n}),t}async function wd(e,t,n,r,s){let i=Ed(e.headers);if(n>0){let l=e.headers.get("content-length");if(l){let c=parseInt(l,10);if(!Number.isNaN(c)&&c>n)throw new zn(n)}}let o;if(n>0&&e.body){let l=e.body.getReader(),c=[],u=0;try{for(;;){let{done:d,value:h}=await Va(l.read(),r);if(d)break;if(h){if(u+=h.byteLength,u>n)throw await l.cancel(),new zn(n);c.push(h)}}}catch(d){throw r?.aborted&&await l.cancel(jr(r)).catch(()=>{}),d}o=new Uint8Array(u);let f=0;for(let d of c)o.set(d,f),f+=d.byteLength}else{let l=await Va(e.arrayBuffer(),r);if(n>0&&l.byteLength>n)throw new zn(n);o=new Uint8Array(l)}let a={status:e.status,statusText:e.statusText,headers:i,body:o,url:t};return s&&s.length>0&&(a.redirectChain=s),a}function fr(e,t){if(e.length>t||W(e)>t)throw new C(`script input size limit exceeded (${t} bytes)`,"string_length")}var Un=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=is({...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 ze(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",`
801
- `],["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=za(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,lastSubstitutionExitCode:null,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",Bi(this.state.options)),this.state.env.set("BASHOPTS",Wi(this.state.shoptOptions)),ml(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&n instanceof ze)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of el(t.commands))this.registerBundledCommand(o);if(t.fetch||t.network)for(let o of tl())this.registerBundledCommand(o);if(t.python)for(let o of nl())this.registerBundledCommand(o);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);if(t.javascript||i.invokeTool){for(let o of rl())this.registerBundledCommand(o);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(t.customCommands)for(let o of t.customCommands)if(ll(o)){let a=cl(o);this.registerCommandInternal(a,!0)}else this.registerCommandInternal(o,!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,o={name:t.name,trusted:r,internalIsExtension:n,internalOriginalCommand:i,execute:(l,c)=>t.execute(l,c)};this.commands.set(t.name,o);let a=this.fs;if(typeof a.writeFileSync=="function"){let l=`#!/bin/bash
799
+ `);l!==-1&&(i=i.slice(l+1))}let o=e.state.loopDepth,a=Wa(e.state);e.state.parentHasLoopContext=o>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 c=new Q().parse(i),u=await s(c);return a(),u}catch(l){if(a(),l instanceof H)return F(l.stdout,l.stderr,l.exitCode);if(l instanceof Oe||l instanceof C)throw l;if(l.name==="ParseException")return L(`bash: ${t}: ${l.message}
800
+ `);throw l}}function Ty(e){throw new TypeError(`Unsupported command node: ${JSON.stringify(e)}`)}var qr=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||Re.isInSandboxedContext())return;let n=`interpreter ${t} attempted outside defense context`;throw new Gn(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:Re.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 o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(t){this.assertDefenseContext("execution");let n=0,r=new ln(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 H||i instanceof Oe)throw i.prependOutput(r.stdout,r.stderr),i;if(i instanceof dt)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:an(this.ctx.state.env)};if(ts(i))throw r.prependTo(i),i;if(i instanceof Ke)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:an(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:an(this.ctx.state.env)};if(i instanceof st)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:an(this.ctx.state.env)};if(i instanceof ce){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 Yr){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 nt||i instanceof rt){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 Ve&&i.prependOutput(r.stdout,r.stderr),i}return{...r.build(n),env:an(this.ctx.state.env)}}async executeUserScript(t,n,r=""){return yd(this.ctx,t,n,r,s=>this.executeScript(s))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new it;if(t.deferredError)throw new Ce(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return ne;this.ctx.state.errexitSafe=!1;let n=new ln(this.ctx.executionScope,"statement");this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&n.append("stderr",`${t.sourceText}
801
+ `);let r=0,s=-1,i=!1;try{for(let l=0;l<t.pipelines.length;l++){let c=t.pipelines[l],u=l>0?t.operators[l-1]:null;if(u==="&&"&&r!==0||u==="||"&&r===0)continue;let f=await this.executePipeline(c);n.appendResult(f,Ti(f)),r=f.exitCode,s=l,i=c.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set("?",String(r))}}catch(l){throw n.prependTo(l),l}let o=s<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||i||a,this.ctx.state.options.errexit&&r!==0&&s===t.pipelines.length-1&&!i&&!this.ctx.state.inCondition&&!a){let l=new Ke(r);throw l.prependOutput(n.stdout,n.stderr),l}return n.build(r)}async executePipeline(t){return hd(this.ctx,t,(n,r)=>this.executeCommand(n,r))}async executeCommand(t,n,r=!1){let s=_u(this.ctx),i;try{i=await this.executeCommandInner(t,n,r)}catch(a){throw await Ro(this.ctx,s).catch(()=>{}),a}let o=await Ro(this.ctx,s);return!o.stdout&&!o.stderr?i:{...i,stdout:o.stdout?qt(i)+o.stdout:i.stdout,stdoutKind:o.stdout?"bytes":i.stdoutKind,stderr:i.stderr+o.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 ad(this.ctx,t);case"For":return ld(this.ctx,t);case"CStyleFor":return cd(this.ctx,t);case"While":return ud(this.ctx,t,n);case"Until":return fd(this.ctx,t,n);case"Case":return dd(this.ctx,t);case"Subshell":return this.executeSubshell(t,n,r);case"Group":return this.executeGroup(t,n,r);case"FunctionDef":return yf(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return Ty(t)}}async executeSimpleCommand(t,n){let r;try{return await this.executeSimpleCommandInner(t,n,s=>{r=s})}catch(s){if(r?.finish(),s instanceof tn)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 P=t,N=0;for(;;){let I=this.expandAlias(P);if(I===P)break;if(N>=this.ctx.limits.maxCallDepth)throw new C(`alias expansion depth limit exceeded (${this.ctx.limits.maxCallDepth})`,"recursion");N++,P=I}this.aliasExpansionStack.clear(),P!==t&&(t=P)}this.ctx.state.expansionStderr="",this.ctx.state.lastSubstitutionExitCode=null;let s=await Zf(this.ctx,t);if(s.error)return s.error;let i=s.tempAssignments,o=s.xtraceOutput,a=()=>{for(let[P,N]of i)N===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,N)};if(!t.name){if(t.redirections.length>0){let N=lr(this.ctx,t.redirections,pf);r(N);let I=await N.prepare(n);if(I.error){if(a(),!I.errorCause)return N.finish(),I.error;try{return cr(I)}finally{N.finish()}}let z=F("",o,Os(this.ctx.state,t.redirections)),X=await Pn(this.ctx,z,t.redirections,I.targets,I.dupSources,I.standardRoutes);return N.finish(),X}this.ctx.state.lastArg="";let P=(this.ctx.state.expansionStderr||"")+o;return this.ctx.state.expansionStderr="",F("",P,Os(this.ctx.state,[]))}let l=t.name&&Ma(t.name,["local","declare","typeset","export","readonly"]),c=Array.from(i.keys());if(c.length>0&&!l){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let P of c)this.ctx.state.tempExportedVars.add(P)}let u=await ie(this.ctx,t.name),f=[],d=[],h=(P,N)=>{if(f.length>=this.ctx.limits.maxArrayElements)throw new C(`expanded argument element limit exceeded (${this.ctx.limits.maxArrayElements})`,"array_elements");f.push(P),d.push(N)};if(Ma(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let P of t.args){let N=await Hu(this.ctx,P);if(N)h(N,!0);else{let I=await Gu(this.ctx,P);if(I!==null)h(I,!0);else{let z=await Rt(this.ctx,P);for(let X of z.values)h(X,z.quoted)}}}else for(let P of t.args){let N=await Rt(this.ctx,P);for(let I of N.values)h(I,N.quoted)}let m=t.name.parts.every(P=>P.type==="CommandSubstitution"||P.type==="ParameterExpansion"||P.type==="ArithmeticExpansion");!u&&m&&f.length>0&&(u=f.shift(),d.shift());let E=lr(this.ctx,t.redirections,u==="exec"?mf:Fr);r(E);let b=await E.prepare(n);if(b.error)return a(),b.errorCause?cr(b):(E.finish(),b.error);let y=b.stdinSourceFd,g=b.stdin!==void 0;if(b.stdin!==void 0&&(n=b.stdin),!u)return m?(E.finish(),F("","",Os(this.ctx.state,t.redirections))):(E.finish(),L(`bash: : command not found
802
+ `,127));if(u==="exec"&&(f.length===0||f[0]==="--")){for(let[P,N]of i)N===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,N);if(this.ctx.state.tempExportedVars)for(let P of i.keys())this.ctx.state.tempExportedVars.delete(P);return E.finish(),ne}if(this.ctx.state.extraArgs){let P=this.ctx.state.extraArgs;this.ctx.state.extraArgs=void 0;for(let N of P)h(N,!0)}let S=await Hf(this.ctx,u,f);i.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(i)));let v,k=null;try{v=await this.runCommand(u,f,d,n,!1,!1,y,g)}catch(P){if(P instanceof nt||P instanceof rt)k=P,v=ne;else throw P}y>=0&&u!=="read"&&kn(this.ctx,y,v.internalStdinConsumed??0);let A=o+S;if(A&&(v={...v,stderr:A+v.stderr}),v=await Pn(this.ctx,v,t.redirections,b.targets,b.dupSources,b.standardRoutes,v.internalProducerCommand??u,v.internalProducerOmitsShellPrefix),E.finish(),k)throw k;if(f.length>0){let P=f[f.length-1];if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(P)){let N=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);N&&(P=N[1])}this.ctx.state.lastArg=P}else this.ctx.state.lastArg=u;let $=Pl(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!$)for(let[P,N]of i)this.ctx.state.fullyUnsetLocals?.has(P)||(N===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,N));if(this.ctx.state.tempExportedVars)for(let P of i.keys())this.ctx.state.tempExportedVars.delete(P);return i.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(v={...v,stderr:this.ctx.state.expansionStderr+v.stderr},this.ctx.state.expansionStderr=""),v}async runCommand(t,n,r,s,i=!1,o=!1,a=-1,l=!1){let c={ctx:this.ctx,runCommand:(d,h,p,m,E,b,y,g)=>this.runCommand(d,h,p,m,E,b,y,g),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(d,h,p)=>this.executeUserScript(d,h,p)},u=await sd(c,t,n,r,s,i,o,a,l);return u!==null?u.internalProducerCommand===void 0?{...u,internalProducerCommand:t}:u:{...await id(c,t,n,s,o),internalProducerCommand:t}}aliasExpansionStack=new Set;expandAlias(t){return Ec({env:this.ctx.state.env,limits:this.ctx.limits},t,this.aliasExpansionStack)}async findCommandInPath(t){return hs(this.ctx,t)}async executeSubshell(t,n="",r=!1){return pd(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeGroup(t,n="",r=!1){return md(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeArithmeticCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),ft(this.ctx,t.redirections,"",async()=>{try{let n=await ee(this.ctx,t.expression.expression),r=Se(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}
803
+ `)}})}async executeConditionalCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),ft(this.ctx,t.redirections,"",async()=>{try{let n=await Sn(this.ctx,t.expression),r=Se(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 ce?1:2;return L(`bash: conditional expression: ${n.message}
804
+ `,r)}})}};function Va(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function _y(e){let t=Va(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}var Ly=3;function gd(e){let t=e;for(let n=0;n<Ly;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 Fy(e,t){return t==="/"||t===""?!0:t.endsWith("/")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function za(e,t){let n=Va(e);if(!n)return!1;let r=_y(t);return!r||n.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&gd(n.pathname)?!1:Fy(n.pathname,r.pathPrefix)}function wd(e){return typeof e=="string"?e:e.url}function Ed(e,t){return!t||t.length===0?!1:t.some(n=>za(e,wd(n)))}function Ua(e){let t=My(e);if(t==="localhost"||t.endsWith(".localhost"))return!0;let n=bd(t);if(n)return wi(n);let r=Wy(t);return r?Vy(r):!1}function My(e){let t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function By(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 bd(e){let t=e.split(".");if(t.length===0||t.length>4)return null;let n=t.map(l=>By(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,c]=r;return l>255||c>16777215?null:[l,c>>>16&255,c>>>8&255,c&255]}if(t.length===3){let[l,c,u]=r;return l>255||c>255||u>65535?null:[l,c,u>>>8&255,u&255]}let[s,i,o,a]=r;return s>255||i>255||o>255||a>255?null:[s,i,o,a]}function Wy(e){let t=e,n=null;if(t.includes(".")){let m=t.lastIndexOf(":");if(m<0)return null;let E=t.slice(m+1),b=bd(E);if(!b)return null;n=b,t=t.slice(0,m)}let r=t.includes("::")?t.split("::").length-1:0;if(r>1)return null;let[s,i]=t.split("::"),o=s?s.split(":").filter(Boolean):[],a=i?i.split(":").filter(Boolean):[],l=m=>/^[0-9a-f]{1,4}$/i.test(m)?Number.parseInt(m,16):null,c=o.map(l),u=a.map(l);if(c.some(m=>m===null)||u.some(m=>m===null))return null;let f=n?2:0,d=c.length+u.length+f,h=0;if(r===1){if(h=8-d,h<0)return null}else if(d!==8)return null;let p=[...c,...new Array(h).fill(0),...u];return n&&(p.push(n[0]<<8|n[1]),p.push(n[2]<<8|n[3])),p.length===8?p:null}function wi(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 Vy(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 wi(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 wi(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 wi(s)}return!1}function Sd(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=wd(n);if(!Va(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!==""&&gd(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 Et=class extends Error{constructor(t,n){let r=n??"URL not in allow-list";super(`Network access denied: ${r}: ${t}`),this.name="NetworkAccessDeniedError"}},Un=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},Yt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Ei=class extends Error{constructor(t,n){super(`HTTP method '${t}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}},jn=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var zy=20,Uy=3e4,jy=10485760,qy=["GET","HEAD"],Hr;typeof __BROWSER__<"u"&&__BROWSER__?Hr=null:(Hr=import("guarded-fetch"),Hr.catch(()=>{}));var Hy=new Set(["GET","HEAD","OPTIONS"]),Gy=new Set([301,302,303,307,308]);function Gr(e){return e.reason instanceof Error?e.reason:new DOMException("The operation was aborted","AbortError")}function Zy(e){if(e?.aborted)throw Gr(e)}function qa(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 S=Sd(t);if(S.length>0)throw new Error(`Invalid network allow-list:
805
+ ${S.join(`
806
+ `)}`)}let r=[];for(let S of t)typeof S=="object"&&S.transform&&S.transform.length>0&&r.push(S);function s(S){if(r.length===0)return null;let v=null;for(let k of r)if(za(S,k.url)&&k.transform){v||(v=new Headers);for(let A of k.transform)for(let[$,R]of Object.entries(A.headers))v.set($,R)}return v}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??zy,o=e.timeoutMs??Uy,a=e.maxResponseSize??jy,l=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??qy,c=e.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),u=[];for(let S of t){let v=typeof S=="string"?S:S.url;try{u.push(new URL(v).hostname)}catch{}}function f(S){try{return new URL(S).hostname||"localhost.invalid"}catch{return"localhost.invalid"}}function d(S){return e.dangerouslyAllowFullInternetAccess?c?{allowedHosts:void 0,skipSsrfCheckForAllowedHosts:void 0}:{allowedHosts:[f(S)],skipSsrfCheckForAllowedHosts:!0}:{allowedHosts:u,skipSsrfCheckForAllowedHosts:!c}}function h(S){try{return Ua(new URL(S).hostname)}catch{return!1}}async function p(S,v){let k={method:v.method,headers:v.headers,signal:v.signal,redirect:"manual"};return v.body!==void 0&&(k.body=v.body),await(n??globalThis.fetch)(S,k)}function m(S){if(!e.dangerouslyAllowFullInternetAccess&&!Ed(S,t))throw new Et(S)}function E(S){if(!c)return;let v;try{v=new URL(S)}catch{throw new Et(S,"invalid URL")}if(Ua(v.hostname))throw new Et(S,"private/loopback IP address blocked")}function b(S){if(e.dangerouslyAllowFullInternetAccess)return;let v=S.toUpperCase();if(!l.includes(v))throw new Ei(v,l)}function y(S,v,k,A){if(!k.isGuardedFetchError(S))return S;let $=S,{onRedirectHop:R,subReason:P}=A;switch($.code){case"host_not_allowed":case"protocol_not_allowed":return R?new Yt(v):new Et(v);case"hostname_unsafe":return R?new Yt(v):new Et(v,P==="dns_resolution_failed"?"DNS resolution failed for private IP check":"hostname resolves to private/loopback IP address");case"redirect_to_unsafe_host":return new Yt(v);case"too_many_redirects":return new Un(i);case"response_too_large":return new jn(a);default:return S}}async function g(S,v={}){let k=v.method?.toUpperCase()??"GET",A=v.followRedirects??!0;if(v.maxRedirects!==void 0&&(!Number.isSafeInteger(v.maxRedirects)||v.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let $=v.maxRedirects??i,R=Math.min(i,$),P=v.timeoutMs!==void 0?Math.min(v.timeoutMs,o):o,N=new AbortController,I=Kr(()=>N.abort(new DOMException("The operation was aborted","AbortError")),P),z=es(v.signal,N.signal);try{m(S),E(S),b(k);let X=Hr?await Hr:null,O=S,j=0,q=[],T=k,_=v.body,W=v.headers,re=!1;for(;;){Zy(z.signal);let J=await Re.runTrustedAsync(async()=>{let We=W;if(re&&We){let jt=We instanceof Headers?new Headers(We):new Headers(We);jt.delete("authorization"),jt.delete("cookie"),We=jt}let bt=s(O),Ut=Ky(We,bt),St={method:T,headers:Ut,signal:z.signal,followRedirects:!1,timeoutMs:P,sanitizeHeaders:!1};if(_&&!Hy.has(T)&&(St.body=_),Object.assign(St,d(O)),!X||h(O)){if(c)throw new Et(O,"DNS pinning unavailable for private IP enforcement");return await p(O,St)}c?n&&(St.fetch=n):(St.fetch=n??globalThis.fetch,St.dispatcher=null);let At;St.onUrlBlocked=jt=>{At=jt.subReason};try{return await X.guardedFetch(O,St)}catch(jt){throw y(jt,O,X,{onRedirectHop:j>0,subReason:At})}});if(Gy.has(J.status)&&A){let We=J.headers.get("location");if(!We)return await Ad(J,O,a,z.signal,q);q.push({status:J.status,statusText:J.statusText,headers:vd(J.headers)});let bt=new URL(We,O).href;await ja(Qy(J),z.signal);try{m(bt),E(bt)}catch(At){throw z.signal?.aborted?Gr(z.signal):At instanceof Et?new Yt(bt):At}let Ut=J.status;if(((Ut===301||Ut===302)&&T==="POST"||Ut===303&&T!=="GET"&&T!=="HEAD")&&(T="GET",_=void 0,b(T)),new URL(bt).origin!==new URL(O).origin&&(re=!0),j++,j>R)throw new Un(R);O=bt;continue}return await Ad(J,O,a,z.signal,q)}}finally{Xr(I),z.cleanup()}}return g}async function ja(e,t){if(!t)return e;if(t.aborted)throw e.catch(()=>{}),Gr(t);let n,r=new Promise((s,i)=>{n=()=>i(Gr(t)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,r])}finally{n&&t.removeEventListener("abort",n)}}async function Qy(e){e.body&&!e.body.locked&&await e.body.cancel()}function Ky(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 vd(e){let t=Object.create(null);return e.forEach((n,r)=>{t[r.toLowerCase()]=n}),t}async function Ad(e,t,n,r,s){let i=vd(e.headers);if(n>0){let l=e.headers.get("content-length");if(l){let c=parseInt(l,10);if(!Number.isNaN(c)&&c>n)throw new jn(n)}}let o;if(n>0&&e.body){let l=e.body.getReader(),c=[],u=0;try{for(;;){let{done:d,value:h}=await ja(l.read(),r);if(d)break;if(h){if(u+=h.byteLength,u>n)throw await l.cancel(),new jn(n);c.push(h)}}}catch(d){throw r?.aborted&&await l.cancel(Gr(r)).catch(()=>{}),d}o=new Uint8Array(u);let f=0;for(let d of c)o.set(d,f),f+=d.byteLength}else{let l=await ja(e.arrayBuffer(),r);if(n>0&&l.byteLength>n)throw new jn(n);o=new Uint8Array(l)}let a={status:e.status,statusText:e.statusText,headers:i,body:o,url:t};return s&&s.length>0&&(a.redirectChain=s),a}function hr(e,t){if(e.length>t||B(e)>t)throw new C(`script input size limit exceeded (${t} bytes)`,"string_length")}var qn=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=ls({...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 Ue(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",`
807
+ `],["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=qa(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,lastSubstitutionExitCode:null,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",Wi(this.state.options)),this.state.env.set("BASHOPTS",Vi(this.state.shoptOptions)),vl(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&(n instanceof Ue||n instanceof ot))try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of ll(t.commands))this.registerBundledCommand(o);if(t.fetch||t.network)for(let o of cl())this.registerBundledCommand(o);if(t.python)for(let o of ul())this.registerBundledCommand(o);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);if(t.javascript||i.invokeTool){for(let o of fl())this.registerBundledCommand(o);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(t.customCommands)for(let o of t.customCommands)if(yl(o)){let a=gl(o);this.registerCommandInternal(a,!0)}else this.registerCommandInternal(o,!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,o={name:t.name,trusted:r,internalIsExtension:n,internalOriginalCommand:i,handlesOwnVersion:t.handlesOwnVersion,execute:(l,c)=>t.execute(l,c)};this.commands.set(t.name,o);let a=this.fs;if(typeof a.writeFileSync=="function"){let l=`#!/bin/bash
802
808
  # Built-in command: ${t.name}
803
- `;try{a.writeFileSync(`/bin/${t.name}`,l)}catch{}try{a.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=bd(t.stdout),t.stderr=bd(t.stderr),t}async exec(t,n){let r=new os(this.limits,n?.signal,this.abortOnUnresolvedCommands),s;try{s=await this.execInScope(t,n,r,0,n?.signal,!1,!1)}catch(o){try{await r.close()}catch{}throw o}let i=s;try{await r.close()}catch{i={...s,stderr:`${s.stderr}bash: execution cleanup failed
804
- `,exitCode:126}}return i.unresolvedCommands=r.unresolvedCommandNames,t.trim()?this.logResult(i):i}async execInScope(t,n,r,s,i,o=!1,a=!0){let l=f=>a?this.logResult(f):f,c=Qr(i,n?.signal),u=n?{...n,signal:c.signal}:{signal:c.signal};try{if(r.assertExecDepth(s),fr(t,this.limits.maxSourceBytes),!t.trim())return{stdout:"",stderr:"",exitCode:0,env:Xe(this.state.env,u.env)};this.logger?.info("exec",{command:t});let f=u.cwd??this.state.cwd,d,h=f;if(u.cwd)if(u.env&&"PWD"in u.env)d=u.env.PWD;else if(u.env&&!("PWD"in u.env))try{d=await this.fs.realpath(f),h=d}catch{d=f}else d=f;let p=u.replaceEnv?new Map:new Map(this.state.env);if(u.env)for(let[y,b]of Object.entries(u.env))p.set(y,b);d!==void 0&&p.set("PWD",d);let m={...this.state,env:p,arrays:u.replaceEnv?new Map:ht(this.state.arrays),cwd:h,previousDir:u.env?.OLDPWD??this.state.previousDir,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:Hy(u.stdin,u.stdinKind,this.limits.maxInputBytes,this.limits.maxStringLength,r,o),signal:u.signal,extraArgs:u.args},E=t;u.rawScript||(E=Ua(t));let S=this.defenseInDepthConfig?Re.getInstance(this.defenseInDepthConfig):null,g=S?.activate();try{let y=async()=>{let b=qe(E,{maxHeredocSize:this.limits.maxHeredocSize}),A;if(this.transformPlugins.length>0){let P=Object.create(null);for(let N of this.transformPlugins){let D=N.transform({ast:b,metadata:P});b=D.ast,D.metadata&&(P=Er(P,D.metadata))}A=P}let k={fs:this.fs,commands:this.commands,limits:this.limits,executionScope:r,exec:(P,N,D=!1)=>this.execInScope(P,N,r,s+1,u.signal,D),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:S?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},O=await new zr(k,m).executeScript(b);return A&&(O.metadata=A),l(O)};return g?await g.run(y):await y()}catch(y){if(y instanceof G)return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,internalOutputAccounting:y.internalOutputAccounting,env:Xe(this.state.env,u.env)});if(y instanceof Oe){if(s>0)throw y;return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,internalOutputAccounting:y.internalOutputAccounting,env:Xe(this.state.env,u.env)})}if(y instanceof ut)return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,env:Xe(this.state.env,u.env)});if(y instanceof ue)return l({stdout:y.stdout,stderr:y.stderr,exitCode:1,env:Xe(this.state.env,u.env)});if(y instanceof st)return l({stdout:y.stdout,stderr:y.stderr,exitCode:124,env:Xe(this.state.env,u.env)});if(y instanceof C)return l({stdout:y.stdout,stderr:Ot(y.stderr),exitCode:C.EXIT_CODE,internalOutputAccounting:y.internalOutputAccounting,env:Xe(this.state.env,u.env)});if(y instanceof qn)return l({stdout:"",stderr:`bash: security violation: ${Ot(y.message)}
805
- `,exitCode:1,env:Xe(this.state.env,u.env)});if(y.name==="ParseException")return l({stdout:"",stderr:`bash: syntax error: ${Ot(y.message)}
806
- `,exitCode:2,env:Xe(this.state.env,u.env)});if(y instanceof it)return l({stdout:"",stderr:`bash: ${Ot(y.message)}
807
- `,exitCode:2,env:Xe(this.state.env,u.env)});if(y instanceof RangeError)return l({stdout:"",stderr:`bash: ${Ot(y.message)}
808
- `,exitCode:1,env:Xe(this.state.env,u.env)});throw y}finally{g?.deactivate()}}catch(f){if(f instanceof st)return l({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:Xe(this.state.env,u.env)});if(f instanceof C)return l({stdout:f.stdout,stderr:Ot(f.stderr),exitCode:C.EXIT_CODE,internalOutputAccounting:f.internalOutputAccounting,env:Xe(this.state.env,u.env)});throw f}finally{c.cleanup()}}async readFile(t){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),n)}getCwd(){return this.state.cwd}getEnv(){return on(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){fr(t,this.limits.maxSourceBytes);let n=Ua(t),r=qe(n,{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let i of this.transformPlugins){let o=i.transform({ast:r,metadata:s});r=o.ast,o.metadata&&(s=Er(s,o.metadata))}return{script:Nr(r),ast:r,metadata:s}}async analyzeCommands(t){fr(t,this.limits.maxSourceBytes);let n=qe(Ua(t),{maxHeredocSize:this.limits.maxHeredocSize}),{commands:r,definedFunctions:s,definedAliases:i}=ls(n),o=[];for(let a of r)s.has(a)||i.has(a)||await this.resolvesCommandForAnalysis(a)||o.push(a);return{commands:r,unresolved:o}}async resolvesCommandForAnalysis(t){if((Ar.has(t)||Dt.has(t))&&!yl.has(t)||this.state.functions.has(t))return!0;let n=await us({fs:this.fs,state:{...this.state,hashTable:new Map},commands:this.commands},t);return n!==null&&!("error"in n)}};function qy(e,t){let n=t;for(let r=0;r<e.length;r++){let s=e[r];if(n==="single")s==="'"&&(n="none");else if(n==="double")s==="\\"?r++:s==='"'&&(n="none");else if(s==="'")n="single";else if(s==='"')n="double";else if(s==="\\")r++;else if(s==="#"&&(r===0||/\s/.test(e[r-1])))break}return n}function Ua(e){let t=e.split(`
809
- `),n=[],r=[],s="none";for(let i=0;i<t.length;i++){let o=t[i];if(r.length>0){let u=r[r.length-1];if((u.stripTabs?o.replace(/^\t+/,""):o)===u.delimiter){n.push(o.trimStart()),r.pop();continue}n.push(o);continue}let a=s,l=a==="none"?o.trimStart():o;if(n.push(l),s=qy(o,a),a!=="none")continue;let c=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let u of l.matchAll(c)){let f=u[1]==="-",d=u[3];r.push({delimiter:d,stripTabs:f})}}return n.join(`
810
- `)}var Gy=new TextDecoder("utf-8",{fatal:!0});function bd(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>255)return e;s>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);try{return Gy.decode(n)}catch{return e}}function Hy(e,t,n,r,s,i){if(e===void 0)return;let o=t==="bytes"?e.length:W(e);if(o>n||o>r)throw new C(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),t==="bytes"?e:Yt(e)}import*as ke from"node:fs";import*as gi from"node:path";function dr(e){return ke.realpathSync(e)}function ja(e){ke.rmSync(e,{recursive:!0,force:!0})}function Ad(e,t){let n;try{n=ke.lstatSync(e)}catch{return!1}return t?!n.isDirectory():n.isDirectory()}function Sd(e,t){Ad(e,t)&&ke.rmSync(e,{recursive:!0,force:!0})}function qa(e,t){if(t.nodeType==="directory"){Sd(e,!0),ke.mkdirSync(e,{recursive:!0}),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime);return}if(ke.mkdirSync(gi.dirname(e),{recursive:!0}),t.nodeType==="symlink"){ke.rmSync(e,{force:!0,recursive:!0}),ke.symlinkSync(new TextDecoder().decode(t.content),e);return}if(t.metadataOnly&&Ad(e,!1))throw new x("EINVAL",`metadata-only entry over a different on-disk type: '${e}'`);t.metadataOnly||(Sd(e,!1),ke.writeFileSync(e,t.content)),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime)}function wi(e){for(let r of[...e.deletions,...e.writes.map(s=>s.path)])if(gi.resolve(r)!==r)throw new x("EINVAL",`change-set path is not normalized: '${r}'`);let t=[...e.deletions].sort((r,s)=>s.length-r.length||(r<s?-1:r>s?1:0));for(let r of t)ja(r);let n=[...e.writes].sort((r,s)=>r.path.length-s.path.length||(r.path<s.path?-1:r.path>s.path?1:0));for(let{path:r,...s}of n)qa(r,s)}import*as Ee from"node:fs";import*as Fe from"node:path";import*as Ze from"node:fs";import*as Ne from"node:path";function Le(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?Ne.win32:Ne.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function jn(e,t){try{let n=Ze.realpathSync(e);return Le(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=Ne.dirname(e);if(r===e)return null;let s=jn(r,t);if(s===null)return null;try{if(Ze.lstatSync(e).isSymbolicLink()){let o=Ze.readlinkSync(e),a=Ne.isAbsolute(o)?o:Ne.resolve(Ne.dirname(e),o),l=jn(a,t);return l===null?null:l}}catch{}return Ne.join(s,Ne.basename(e))}return null}}function Ei(e,t,n){let r=jn(e,n);if(r===null)return null;let s=Ne.resolve(e),i=s.slice(t.length),o=r.slice(n.length);if(i!==o)return null;try{if(Ze.lstatSync(s).isSymbolicLink())return null}catch{}return r}function bi(e,t){if(!Ze.existsSync(e))throw new Error(`${t} root does not exist`);if(!Ze.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function vd(e,t){if(!Ne.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=Ze.realpathSync(e)}catch{n=Ne.resolve(e)}return Le(n,t)?{withinRoot:!0,relativePath:Nn(n.slice(t.length))||"/"}:{withinRoot:!1,safeName:Ne.basename(e)}}function Si(e,t,n,r){let s=e;if(s.path===void 0){for(let o of r)if(s.message?.includes(o))throw e}let i=s.code||"EIO";throw new x(i,`${n} '${t}'`)}async function Nt(e){return kd(await Ze.promises.lstat(e))}function Ga(e){return kd(Ze.lstatSync(e))}function kd(e){return process.platform==="win32"&&e.isDirectory()&&(e.mode=e.mode&-512|493),e}function Ai(e){let t=e.content.byteLength;for(let n of e.appendChunks??[])t+=n.byteLength;return t}function $d(e){return Ai(e)}function ki(e,t){if(!e.appendChunks||e.appendChunks.length===0)return e.content;let n=e.appendChunks.reduce((i,o)=>i+o.byteLength,e.content.byteLength);if(!Number.isSafeInteger(n))throw new x("EFBIG",`file too large, read '${t}'`);let r=new Uint8Array(n);r.set(e.content);let s=e.content.byteLength;for(let i of e.appendChunks)r.set(i,s),s+=i.byteLength;return e.content=r,e.appendChunks=void 0,r}function xd(e){return!e||e.type!=="file"?0:Ai(e)}function qr(){return{type:"directory",children:new Map,changedAt:Date.now(),mode:St,mtime:new Date}}function Gr(e){return e.split("/").filter(Boolean)}var vi=class e{maxMemoryBytes;rootNode=qr();bytes=0;mutationSeq_=0;constructor(t){this.maxMemoryBytes=t}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(t){let n=Gr(t),r=[this.rootNode],s=this.rootNode;for(let i=0;i<n.length;i++){let o=s.children.get(n[i]);if(o===void 0)return{kind:"missing",stack:r,missingAt:i};if(i===n.length-1)return{kind:"found",stack:r,node:o};if(o.type==="whiteout")return{kind:"blocked",stack:r,blockedAt:i};if(o.type!=="directory")return{kind:"notdir",stack:r,notdirAt:i};r.push(o),s=o}return{kind:"found",stack:[],node:this.rootNode}}ensureDirs(t,n){let r=this.rootNode,s="";for(let i of Gr(t)){s=`${s}/${i}`;let o=r.children.get(i);if(o===void 0)o=qr(),r.children.set(i,o);else if(o.type==="whiteout")o=this.resurrectDir(r,i,s,o.changedAt??0,n);else if(o.type!=="directory")throw new x("ENOTDIR",`not a directory, mkdir '${t}'`);r=o}return r}resurrectDir(t,n,r,s,i){let o=qr();t.children.set(n,o);let a=i?.(r);if(a)for(let l of a)o.children.has(l)||o.children.set(l,{type:"whiteout",changedAt:s});return o}attach(t,n){n.changedAt=Date.now();let r=Gr(t);if(r.length===0)throw new x("EINVAL",`cannot attach at root, attach '${t}'`);let s=this.parentDirOf(r,t),i=s.children.get(r[r.length-1]);if(i?.type==="directory"&&n.type!=="directory")throw new x("EISDIR",`cannot replace directory with ${n.type}, attach '${t}'`);if(i!==void 0&&n.type==="directory")throw new x("EEXIST",`cannot replace ${i.type} with directory, attach '${t}'`);let o=xd(i),a=xd(n);this.assertCapacity(a,o),s.children.set(r[r.length-1],n),this.bytes+=a-o}detach(t){let n=Gr(t);if(n.length===0)return;let r=this.descend(t);return r.kind!=="found"?void 0:(r.stack[r.stack.length-1].children.delete(n[n.length-1]),this.bytes-=e.subtreeBytes(r.node),r.node)}putWhiteout(t){let n=Gr(t);if(n.length===0)throw new x("EINVAL",`cannot whiteout the root, rm '${t}'`);let r=this.rootNode;for(let o=0;o<n.length-1;o++)r=this.ensureChildDir(r,n[o],t);let s=n[n.length-1],i=r.children.get(s);i?.type!=="whiteout"&&(this.bytes-=e.subtreeBytes(i),r.children.set(s,{type:"whiteout",changedAt:Date.now()}))}appendChunk(t,n){this.assertCapacity(n.byteLength),t.appendChunks||(t.appendChunks=[]),t.appendChunks.push(n),this.bytes+=n.byteLength,this.touch(t)}touch(t){t.seq=++this.mutationSeq_,t.changedAt=Date.now()}detachIfUnchanged(t,n,r){let s=this.descend(t);return s.kind!=="found"||s.node!==n||n.seq!==r||n.type==="directory"&&n.children.size>0?!1:(this.detach(t),!0)}*preOrder(){let t=[{path:"/",node:this.rootNode}];for(;t.length>0;){let n=t.pop();if(yield n,n.node.type==="directory"){let r=[...n.node.children.entries()];for(let s=r.length-1;s>=0;s--){let[i,o]=r[s];t.push({path:Pd(n.path,i),node:o})}}}}*postOrder(){let t=[],n=[{path:"/",node:this.rootNode}];for(;n.length>0;){let r=n.pop();if(t.push(r),r.node.type==="directory")for(let[s,i]of r.node.children)n.push({path:Pd(r.path,s),node:i})}for(let r=t.length-1;r>=0;r--)yield t[r]}clear(){this.rootNode=qr(),this.bytes=0}static subtreeBytes(t){if(t===void 0)return 0;if(t.type==="file")return Ai(t);if(t.type!=="directory")return 0;let n=0,r=[t];for(;r.length>0;){let s=r.pop();for(let i of s.children.values())i.type==="file"?n+=Ai(i):i.type==="directory"&&r.push(i)}return n}parentDirOf(t,n){let r=this.rootNode;for(let s=0;s<t.length-1;s++){let i=r.children.get(t[s]);if(i?.type!=="directory")throw new x("ENOTDIR",`not a directory, attach '${n}'`);r=i}return r}ensureChildDir(t,n,r){let s=t.children.get(n);if(s===void 0||s.type==="whiteout")s=qr(),t.children.set(n,s);else if(s.type!=="directory")throw new x("ENOTDIR",`not a directory, rm '${r}'`);return s}assertCapacity(t,n=0){if(!Number.isSafeInteger(t)||t<0||t>this.maxMemoryBytes-this.bytes+n)throw new x("ENOSPC",`overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function Pd(e,t){return e==="/"?`/${t}`:`${e}/${t}`}var Zy=["ELOOP","EFBIG","EPERM"],Qy="/home/user/project",Rt=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;get rootDir(){return this.root}restamp(t,n,r="full"){let s=z(t),i=c=>{let u=this.tree.descend(c);u.kind==="found"&&(u.node.changedAt=n)},o=c=>{let u=this.tree.descend(c);if(u.kind==="found"){let f=u.node;(f.changedAt??0)>n&&(f.changedAt=n,f.mtime=new Date(n))}};r==="full"&&i(s);let a=s;for(;;){let c=a.lastIndexOf("/");if(c<=0)break;a=a.slice(0,c),o(a)}if(r==="ancestors")return;let l=[s];for(;l.length>0;){let c=l.pop(),u=this.tree.descend(c);if(!(u.kind!=="found"||u.node.type!=="directory"))for(let f of u.node.children.keys()){let d=`${c==="/"?"":c}/${f}`;o(d),l.push(d)}}}identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Fe.resolve(t.root);let n=t.mountPoint??Qy;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxMemoryBytes=t.maxMemoryBytes??1024*1024*1024,!Number.isSafeInteger(this.maxMemoryBytes)||this.maxMemoryBytes<0)throw new Error("OverlayFs: invalid maxMemoryBytes");this.allowSymlinks=t.allowSymlinks??!1,bi(this.root,"OverlayFs"),this.canonicalRoot=Ee.realpathSync(this.root),this.tree=new vi(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new x("EROFS",`read-only file system, ${t}`)}createMountPointDirs(){this.tree.ensureDirs(this.mountPoint)}getMountPoint(){return this.mountPoint}diff(){let t=[],n=[],r=[];for(let{path:i,node:o}of this.tree.preOrder()){let a=this.getRelativeToMount(i);if(!(a===null||a==="/")){if(o.type==="whiteout"){this.existsOnRealFs(i)&&(n.push(a),r.push(o.changedAt??0));continue}if(o.type==="file")if(o.metacopy){if(!this.existsOnRealFs(i))continue;t.push({path:a,nodeType:"file",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0,metadataOnly:!0})}else t.push({path:a,nodeType:"file",content:ki(o,i),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0});else o.type==="directory"?t.push({path:a,nodeType:"directory",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0}):t.push({path:a,nodeType:"symlink",content:new TextEncoder().encode(o.target),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0})}}t.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0);let s=n.map((i,o)=>({path:i,changedAt:r[o]}));return s.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),{writes:t,deletions:s.map(i=>i.path),...s.length>0&&{deletionChangedAt:s.map(i=>i.changedAt)}}}async sync(){for(let{path:t,node:n}of this.tree.postOrder()){let r=this.getRelativeToMount(t);if(r===null||r==="/")continue;if(n.type==="whiteout"){this.existsOnRealFs(t)||this.tree.detach(t);continue}if(n.type==="directory"&&n.children.size>0)continue;let s=n.seq;await this.nodeMatchesDisk(t,n)&&this.tree.detachIfUnchanged(t,n,s)}}reset(){this.tree.clear(),this.createMountPointDirs()}drop(t){let n=t.map(r=>{let s=z(r);if(s==="/")throw new x("EINVAL",`invalid argument, drop '${r}'`);return this.mountPoint==="/"?s:`${this.mountPoint}${s}`});n.sort((r,s)=>s.length-r.length);for(let r of n){let s=this.tree.descend(r);if(s.kind!=="found")continue;let i=s.node;i.type==="directory"&&i.children.size>0||this.tree.detach(r)}}async lstatLower(t){let n=this.resolveRealPathParent_(this.toRealPath(t));if(!n)return null;try{return{canonical:n,stat:await Nt(n)}}catch{return null}}async nodeMatchesDisk(t,n){if(n.type==="directory")return(await this.lstatLower(t))?.stat.isDirectory()??!1;if(n.type==="symlink"){if(!this.allowSymlinks)return!1;let s=await this.lstatLower(t);if(!s?.stat.isSymbolicLink())return!1;try{let i=await Ee.promises.readlink(s.canonical);return this.realTargetToVirtual(i)===n.target}catch{return!1}}if(n.metacopy){let s=await this.lstatLower(t);if(!s?.stat.isFile())return!1;let{stat:i}=s;return!(i.mtime.getTime()!==n.mtime.getTime()||process.platform!=="win32"&&(i.mode&4095)!==(n.mode&4095))}let r=this.resolveRealPath_(this.toRealPath(t));if(!r)return!1;try{let s=await Nt(r);if(!s.isFile())return!1;let i=ki(n,t);if(s.size!==i.byteLength)return!1;let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(r,o),l;try{l=new Uint8Array(await a.readFile())}finally{await a.close()}for(let c=0;c<l.byteLength;c++)if(l[c]!==i[c])return!1;return!0}catch{return!1}}mkdirSync(t,n){this.tree.ensureDirs(z(t),r=>this.lowerChildren(r))}writeFileSync(t,n){let r=z(t);this.ensureParentDirs(r);let s=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.tree.attach(r,{type:"file",content:s,mode:rn,mtime:new Date})}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let n=z(t),r=this.getRelativeToMount(n);if(r===null)return null;let s=Fe.join(this.root,r),i=Fe.resolve(s);return Le(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?jn(t,this.canonicalRoot):Ei(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Fe.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Fe.join(r,Fe.basename(t))}sanitizeError(t,n,r){Si(t,n,r,Zy)}ensureParentDirs(t){let n=Zn(t);n!=="/"&&this.tree.ensureDirs(n,r=>this.lowerChildren(r))}lowerChildren(t){let n=this.resolveRealPath_(this.toRealPath(t));if(!n)return null;try{return Ee.readdirSync(n)}catch{return null}}async existsInOverlay(t){let n=z(t),r=this.tree.descend(n);if(r.kind==="found")return r.node.type!=="whiteout";if(r.kind==="blocked"||r.kind==="notdir")return!1;let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)return!1;try{return await Nt(s),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t,n=new Set){U(t,"open");let r=z(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, open '${t}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.type==="symlink"){let a=this.resolveSymlink(r,i.target);return this.readFileBuffer(a,n)}if(i.type!=="file")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(!i.metacopy)return ki(i,t);let o=await this.readLowerFileBytes(r,t,n);if(process.platform==="win32")try{this.tree.attach(r,{type:"file",content:o,mode:i.mode,mtime:i.mtime})}catch(a){if(!ft(a,"ENOSPC"))throw a}return o}return this.readLowerFileBytes(r,t,n)}async readLowerFileBytes(t,n,r){let s=this.resolveRealPath_(this.toRealPath(t));if(!s)throw new x("ENOENT",`no such file or directory, open '${n}'`);try{let i=await Nt(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, open '${n}'`);let l=await Ee.promises.readlink(s),c=this.realTargetToVirtual(l),u=this.resolveSymlink(t,c);return this.readFileBuffer(u,r)}if(i.isDirectory())throw new x("EISDIR",`illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(s,o);try{let l=await a.readFile();return new Uint8Array(l)}finally{await a.close()}}catch(i){let o=i.code;if(o==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${n}'`);if(o==="ELOOP")throw new x("ENOENT",`no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(t,n,r){U(t,"write"),this.assertWritable(`write '${t}'`);let s=z(t);this.ensureParentDirs(s);let i=dt(r),o=Ht(n,i);this.tree.attach(s,{type:"file",content:o,mode:await this.inheritedMode(s),mtime:new Date})}async inheritedMode(t){let n=this.entryAt(t);if(n?.type==="file")return n.mode;if(n?.type==="directory")return rn;if(process.platform==="win32")return rn;try{let r=await this.stat(t);if(r.isFile)return r.mode}catch{}return rn}async appendFile(t,n,r){U(t,"append"),this.assertWritable(`append '${t}'`);let s=z(t),i=dt(r),o=Ht(n,i),a=this.tree.descend(s);if(a.kind==="found"&&a.node.type==="file"){await this.appendToExisting_(s,a.node,o,t);return}if(a.kind==="blocked")throw new x("ENOENT",`no such file or directory, append '${t}'`);if(a.kind==="notdir")throw new x("ENOTDIR",`not a directory, append '${t}'`);let l;try{l=await this.readFileBuffer(s)}catch(f){if(!ft(f,"ENOENT"))throw f;l=new Uint8Array(0)}let c=await this.inheritedMode(s),u=this.tree.descend(s);if(u.kind==="found"&&u.node.type==="file"){await this.appendToExisting_(s,u.node,o,t);return}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[o],mode:c,mtime:new Date})}async appendToExisting_(t,n,r,s){if(n.metacopy){let i=await this.readLowerFileBytes(t,s,new Set),o=this.tree.descend(t);if(o.kind==="found"&&o.node.type==="file"&&!o.node.metacopy){this.tree.appendChunk(o.node,r),o.node.mtime=new Date;return}this.tree.attach(t,{type:"file",content:i,appendChunks:[r],mode:n.mode,mtime:new Date});return}this.tree.appendChunk(n,r),n.mtime=new Date}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,n=new Set){U(t,"stat");let r=z(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, stat '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, stat '${t}'`);if(s.kind==="found"){let o=s.node;if(o.type==="whiteout")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(o.type==="symlink"){let a=this.resolveSymlink(r,o.target);return this.stat(a,n)}return this.memoryEntryStat(o)}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new x("ENOENT",`no such file or directory, stat '${t}'`);try{let o=await Nt(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, stat '${t}'`);let a=await Ee.promises.readlink(i),l=this.realTargetToVirtual(a),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime,dev:o.dev,ino:o.ino}}catch(o){if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){U(t,"lstat");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, lstat '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, lstat '${t}'`);try{let i=await Nt(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}memoryEntryStat(t){if(t.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:t.mode,size:t.target.length,mtime:t.mtime};let n=0;return t.type==="file"&&(n=t.metacopy?t.lowerSize??0:$d(t)),{isFile:t.type==="file",isDirectory:t.type==="directory",isSymbolicLink:!1,mode:t.mode,size:n,mtime:t.mtime,identity:this.identityFor(t)}}resolveSymlink(t,n){return Qn(t,n)}realTargetToVirtual(t){let n=vd(t,this.canonicalRoot);if(n.withinRoot){if(!Fe.isAbsolute(t))return t;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(t,n){U(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=z(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new x("EEXIST",`file already exists, mkdir '${t}'`);return}let i=Zn(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.tree.ensureDirs(r,o=>this.lowerChildren(o))}async readdirCore(t,n){let r=new Map,s=new Set,i=this.tree.descend(n);if(i.kind==="blocked")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.kind==="notdir")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);let o;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(l.type!=="directory")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);o=l;for(let[c,u]of l.children){if(u.type==="whiteout"){s.add(c);continue}r.set(c,{name:c,isFile:u.type==="file",isDirectory:u.type==="directory",isSymbolicLink:u.type==="symlink"})}}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await Nt(a)).isSymbolicLink()){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);return r}let l=await Ee.promises.readdir(a,{withFileTypes:!0});for(let c of l)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,t,"scandir")}return r}async resolveForReaddir(t,n=!1){let r=z(t),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let c=l.node;if(c.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new x("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,c.target)}if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let a=this.resolveRealPath_(this.toRealPath(r));if(!a)return{normalized:r,outsideOverlay:!0};try{if((await Nt(a)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let c=await Ee.promises.readlink(a),u=this.realTargetToVirtual(c),f=this.resolveSymlink(r,u);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,n){U(t,"rm"),this.assertWritable(`rm '${t}'`);let r=z(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}let i=!1;try{(await this.stat(r)).isDirectory&&(i=(await this.readdir(r)).length>0)}catch{}if(i&&!n?.recursive)throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.existsOnRealFs(r)?this.tree.putWhiteout(r):this.tree.detach(r)}existsOnRealFs(t){let n=this.toRealPath(t),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return Ga(r),!0}catch{return!1}}async cp(t,n,r){U(t,"cp"),U(n,"cp"),this.assertWritable(`cp '${n}'`);let s=z(t),i=z(n);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, cp '${t}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new x("EISDIR",`is a directory, cp '${t}'`);if(qt(s,i))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,n){this.assertWritable(`mv '${n}'`),await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return sn(t,n)}getAllPaths(){let t=new Set;for(let{path:n,node:r}of this.tree.preOrder())r.type!=="whiteout"&&t.add(n);return this.scanRealFs(this.mountPoint,t),Array.from(t)}scanRealFs(t,n){if(this.lowerHidden(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let s=Ee.readdirSync(r);for(let i of s){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.lowerHidden(o))continue;n.add(o);let a=Fe.join(r,i);Ga(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}lowerHidden(t){let n=this.tree.descend(t);switch(n.kind){case"blocked":case"notdir":return!0;case"found":return n.node.type!=="directory";default:return!1}}entryAt(t){let n=this.tree.descend(t);if(n.kind==="found"&&n.node.type!=="whiteout")return n.node}async chmod(t,n){U(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=z(t);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, chmod '${t}'`);let i=this.entryAt(r);if(i){i.mode=n,this.tree.touch(i);return}let o=await this.stat(r);this.attachMetacopyShadow(r,o,n,o.isFile?o.mtime:new Date)}attachMetacopyShadow(t,n,r,s){this.ensureParentDirs(t),n.isFile?this.tree.attach(t,{type:"file",content:new Uint8Array(0),metacopy:!0,lowerSize:n.size,mode:r,mtime:s}):n.isDirectory&&this.tree.attach(t,{type:"directory",children:new Map,mode:r,mtime:s})}async symlink(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=z(n);if(await this.existsInOverlay(r))throw new x("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:t,mode:es,mtime:new Date})}async link(t,n){U(t,"link"),U(n,"link"),this.assertWritable(`link '${n}'`);let r=z(t),s=z(n);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new x("EPERM",`operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new x("EEXIST",`file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,mode:o.mode,mtime:new Date,identity:o.identity??`overlay:${this.nextMemoryIdentity++}`})}async readlink(t){U(t,"readlink");let n=z(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, readlink '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.type!=="symlink")throw new x("EINVAL",`invalid argument, readlink '${t}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, readlink '${t}'`);try{let i=await Ee.promises.readlink(s);if(!Fe.isAbsolute(i)){let o=Fe.resolve(Fe.dirname(s),i),a;try{a=Ee.realpathSync(o)}catch{a=o}if(!Le(a,this.canonicalRoot))return Fe.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){U(t,"realpath");let n=z(t),r=new Set,s=l=>{let c=this.tree.descend(l);if(c.kind==="blocked"||c.kind==="found"&&c.node.type==="whiteout")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return c.kind==="found"?c.node:void 0},i=async l=>{let c=l==="/"?[]:l.slice(1).split("/"),u="";for(let f of c){if(u=`${u}/${f}`,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);let d=s(u),h=0,p=gr;for(;d&&d.type==="symlink"&&h<p;){if(r.add(u),u=this.resolveSymlink(u,d.target),h++,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);d=s(u)}if(h>=p)throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);if(!d){let m=this.toRealPath(u),E=this.resolveRealPath_(m);if(E)try{if((await Nt(E)).isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, realpath '${t}'`);let g=await Ee.promises.readlink(E),y=this.realTargetToVirtual(g);return r.add(u),u=this.resolveSymlink(u,y),i(u)}}catch(S){if(S.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(S,t,"realpath")}else if(!this.allowSymlinks){let S=this.resolveRealPathParent_(m);if(S)try{if((await Nt(S)).isSymbolicLink())throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}catch(g){if(ft(g,"ENOENT")||ft(g,"ELOOP"))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(g,t,"realpath")}}}}return u||"/"},o=await i(n);if(!await this.existsInOverlay(o))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return o}async utimes(t,n,r){U(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=z(t);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, utimes '${t}'`);let o=this.entryAt(s);if(o){o.mtime=r,this.tree.touch(o);return}let a=await this.stat(s);this.attachMetacopyShadow(s,a,a.mode,r)}};var xi=class{bash;overlays;constructor(t={}){let{home:n,project:r,cwd:s,env:i,...o}=t,a=new Map,l=[],c=n?dr(n):null,u=r?dr(r):null,f=c&&u&&(()=>{let p=Me.relative(c,u);return p!==".."&&!p.startsWith(`..${Me.sep}`)&&!Me.isAbsolute(p)})();if(c){let p=new Rt({root:c,mountPoint:"/"});a.set("/home/user",{root:c,fs:p}),l.push({mountPoint:"/home/user",filesystem:p})}let d="/home/user";if(u)if(f&&c){let p=Me.relative(c,u);d=p?`/home/user/${p.split(Me.sep).join("/")}`:"/home/user"}else{let p=new Rt({root:u,mountPoint:"/"});a.set("/project",{root:u,fs:p}),l.push({mountPoint:"/project",filesystem:p}),d="/project"}let h=new Pt({base:new ze,mounts:l});this.overlays=a,this.bash=new Un({...o,env:{HOME:"/home/user",...i},cwd:s??d,fs:h})}analyzeCommands(t){return this.bash.analyzeCommands(t)}exec(t){return this.bash.exec(t)}diff(){let t=[],n=[];for(let{root:r,fs:s}of this.overlays.values()){let i=s.diff();for(let{path:o,...a}of i.writes)t.push({...a,path:Me.join(r,o)});for(let o=0;o<i.deletions.length;o++)n.push({path:Me.join(r,i.deletions[o]),changedAt:i.deletionChangedAt?.[o]})}return t.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),n.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),{writes:t,deletions:n.map(r=>r.path),...n.length>0&&{deletionChangedAt:n.map(r=>r.changedAt??0)}}}async applyChanges(t=this.diff()){let n=new Map,r=s=>{let i=this.findOverlay(s);if(!i)return;let o=`/${Me.relative(i.root,s).split(Me.sep).join("/")}`;if(o==="/")return;let a=n.get(i.fs);a?a.push(o):n.set(i.fs,[o])};try{for(let s of t.deletions)ja(s),r(s);for(let s of t.writes)qa(s.path,s),r(s.path)}finally{for(let[s,i]of n)s.drop(i)}}findOverlayEntry(t){let n=null;for(let[r,s]of this.overlays)(t===s.root||t.startsWith(s.root+Me.sep))&&(!n||s.root.length>n.root.length)&&(n={mountPoint:r,root:s.root,fs:s.fs});return n}findOverlay(t){return this.findOverlayEntry(t)}resolveRealPath(t){let n=this.findOverlayEntry(t);if(!n)return null;let r=`/${Me.relative(n.root,t).split(Me.sep).join("/")}`;return{mountPoint:n.mountPoint,overlay:n.fs,path:r}}toRealPath(t){let n=t.startsWith("/")?t:`/${t}`,r=null;for(let[s,i]of this.overlays)(n===s||n.startsWith(`${s}/`))&&(!r||s.length>r.mountPoint.length)&&(r={mountPoint:s,root:i.root});return r?Me.join(r.root,n.slice(r.mountPoint.length)):null}async sync(){for(let{fs:t}of this.overlays.values())await t.sync()}reset(){for(let{fs:t}of this.overlays.values())t.reset()}};function Ky(e={}){return new xi(e)}import{randomBytes as Xy}from"node:crypto";import*as L from"node:fs";import*as Z from"node:path";var Yy=["EACCES","escaping sandbox","EFBIG","ENOTSUP"],Pi=class e{static activeMutationRoots=new Set;static pendingMutations=[];root;canonicalRoot;maxFileReadSize;maxCopyOnWriteSize;maxCopySize;allowSymlinks;constructor(t){this.root=Z.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxCopyOnWriteSize=t.maxCopyOnWriteSize??104857600,this.maxCopySize=t.maxCopySize??0,this.allowSymlinks=t.allowSymlinks??!1,bi(this.root,"ReadWriteFs"),this.canonicalRoot=L.realpathSync(this.root)}resolveAndValidate(t,n){let r=this.allowSymlinks?jn(t,this.canonicalRoot):Ei(t,this.root,this.canonicalRoot);if(r===null)throw new x("EACCES",`permission denied, '${n}' resolves outside sandbox`);return r}validateParent(t,n){let r=Z.dirname(t),s=this.resolveAndValidate(r,n);return Z.join(s,Z.basename(t))}toRealPath(t){let n=z(t),r=Z.join(this.root,n);return Z.resolve(r)}async readFile(t,n){let r=await this.readFileBuffer(t),s=dt(n);return Zt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Zt(n,"binary")}async readFileBuffer(t){U(t,"open");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=this.allowSymlinks?L.constants.O_RDONLY:L.constants.O_RDONLY|L.constants.O_NOFOLLOW,i=await L.promises.open(r,s);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.code==="EISDIR")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(i.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(s,t,"open")}}async writeFile(t,n,r){await this.withFilesystemMutation(()=>this.writeFileUnlocked(t,n,r))}async writeFileUnlocked(t,n,r){U(t,"write");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t),o=dt(r),a=Ht(n,o),l=Z.dirname(i);try{await L.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:L.constants.O_NOFOLLOW,u=null;try{let f=await L.promises.lstat(i);if(!f.isFile()&&!f.isDirectory())throw new x("EACCES",`cannot write special file '${t}'`);let d=await L.promises.open(i,L.constants.O_WRONLY|L.constants.O_NONBLOCK|c);try{if(u=await d.stat(),!u.isFile())throw new x("EACCES",`cannot write special file '${t}'`);if(u.nlink<=1){await d.truncate(0),await d.writeFile(a);return}}finally{await d.close()}}catch(f){if(f.code!=="ENOENT")throw f}await this.replaceFile(i,a,u)}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"write")}}async appendFile(t,n,r){await this.withFilesystemMutation(()=>this.appendFileUnlocked(t,n,r))}async appendFileUnlocked(t,n,r){U(t,"append");let s=this.toRealPath(t),i=dt(r),o=Ht(n,i),a=this.resolveAndValidate(s,t),l=Z.dirname(a);try{await L.promises.mkdir(l,{recursive:!0}),a=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:L.constants.O_NOFOLLOW,u=null;try{let d=await L.promises.lstat(a);if(!d.isFile()&&!d.isDirectory())throw new x("EACCES",`cannot append special file '${t}'`);let h=await L.promises.open(a,L.constants.O_WRONLY|L.constants.O_APPEND|L.constants.O_NONBLOCK|c);try{if(u=await h.stat(),!u.isFile())throw new x("EACCES",`cannot append special file '${t}'`);if(u.nlink<=1){await h.writeFile(o);return}}finally{await h.close()}}catch(d){if(d.code!=="ENOENT")throw d}if(!u){await this.replaceFile(a,o,null);return}this.assertCopyOnWriteSize(u.size,"append",t);let f=await this.openCopySource(a);try{let d=await f.stat();if(!d.isFile()||d.dev!==u.dev||d.ino!==u.ino)throw new x("EACCES",`file identity changed, append '${t}'`);await this.replaceFile(a,o,d,{handle:f,size:u.size})}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"append")}}async withFilesystemMutation(t){return new Promise((n,r)=>{e.pendingMutations.push({root:this.canonicalRoot,start:()=>{e.activeMutationRoots.add(this.canonicalRoot),t().then(n,r).finally(()=>{e.activeMutationRoots.delete(this.canonicalRoot),e.drainMutationQueue()})}}),e.drainMutationQueue()})}static drainMutationQueue(){for(let t=0;t<e.pendingMutations.length;){let n=e.pendingMutations[t];if([...e.activeMutationRoots].some(s=>Le(n.root,s)||Le(s,n.root))){t++;continue}e.pendingMutations.splice(t,1),n.start()}}assertCopyOnWriteSize(t,n,r){if(this.maxCopyOnWriteSize>0&&t>this.maxCopyOnWriteSize)throw new x("EFBIG",`file too large for copy-on-write ${n} '${r}' (${t} bytes, max ${this.maxCopyOnWriteSize})`)}assertCopySize(t,n){if(this.maxCopySize>0&&t.size>this.maxCopySize)throw new x("EFBIG",`file too large to copy '${n}' (${t.size} bytes, max ${this.maxCopySize})`)}randomTransactionToken(){return Xy(16).toString("hex")}async openCopySource(t){let n=this.allowSymlinks?0:L.constants.O_NOFOLLOW,r=L.constants.O_RDONLY|L.constants.O_NONBLOCK|n,s=L.constants.O_NOATIME;if(process.platform!=="linux"||s===void 0)return L.promises.open(t,r);try{return await L.promises.open(t,r|s)}catch(i){if(i.code!=="EPERM")throw i;return L.promises.open(t,r)}}async replaceFile(t,n,r,s,i,o=!1){let a=Z.dirname(t),l="",c=null,u=r===null?438:384;for(let p=0;p<16;p++){l=Z.join(a,`.just-bash-write-${this.randomTransactionToken()}`);try{c=await L.promises.open(l,L.constants.O_WRONLY|L.constants.O_CREAT|L.constants.O_EXCL,u);break}catch(m){if(m.code!=="EEXIST")throw m}}if(!c)throw new x("EEXIST",`replacement write '${t}'`);let f=c,d=await f.stat(),h=!1;try{try{let m=0,E=async S=>{let g=0;for(;g<S.byteLength;){let{bytesWritten:y}=await f.write(S,g,S.byteLength-g,m+g);if(y===0)throw new x("EIO","replacement write made no progress");g+=y}m+=g};if(s){let S=Buffer.allocUnsafe(65536),g=0,y=s.size;for(;y>0;){let b=Math.min(S.length,y),{bytesRead:A}=await s.handle.read(S,0,b,g);if(A===0)break;await E(S.subarray(0,A)),g+=A,y-=A}}if(await E(n),r!==null&&await f.chmod(r.mode&(o?4095:511)),i)await f.utimes(i.atime,i.mtime);else if(r!==null){let S=await f.stat();await f.utimes(r.atime,S.mtime)}}finally{await f.close(),c=null}let p=await L.promises.lstat(l);if(!p.isFile()||p.dev!==d.dev||p.ino!==d.ino)throw new x("EACCES","replacement staging entry changed");await L.promises.rename(l,t),h=!0}finally{c&&await c.close().catch(()=>{}),h||await L.promises.rm(l,{force:!0}).catch(()=>{})}}async exists(t){if(t.includes("\0"))return!1;let n=this.toRealPath(t);try{let r=this.resolveAndValidate(n,t);return await L.promises.access(r),!0}catch{return!1}}async stat(t){U(t,"stat");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=await L.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(s,t,"stat")}}async lstat(t){U(t,"lstat");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await L.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(s,t,"lstat")}}async mkdir(t,n){await this.withFilesystemMutation(()=>this.mkdirUnlocked(t,n))}async mkdirUnlocked(t,n){U(t,"mkdir");let r=this.toRealPath(t),s=r===this.root?this.resolveAndValidate(r,t):this.validateParent(r,t);try{await L.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new x("EEXIST",`file already exists, mkdir '${t}'`);if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.sanitizeError(i,t,"mkdir")}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){U(t,"scandir");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{if(!this.allowSymlinks&&(await L.promises.lstat(r)).isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return(await L.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.code==="ENOTDIR")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);this.sanitizeError(s,t,"scandir")}}async rm(t,n){await this.withFilesystemMutation(()=>this.rmUnlocked(t,n))}async rmUnlocked(t,n){U(t,"rm");let r=this.toRealPath(t),s=this.validateParent(r,t);try{let i=await L.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);await L.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}if(o.code==="ENOTEMPTY")throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,n,r){await this.withFilesystemMutation(()=>this.cpUnlocked(t,n,r))}async cpUnlocked(t,n,r){U(t,"cp"),U(n,"cp");let s=this.toRealPath(t),i=this.toRealPath(n),o=this.validateParent(s,t),a=this.resolveAndValidate(i,n),l;try{l=await L.promises.lstat(o)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}if(l.isDirectory()&&Le(a,o))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);if(!l.isDirectory())try{let c=this.validateParent(i,n),u=await L.promises.lstat(c);if(l.dev===u.dev&&l.ino===u.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}if(l.isFile())try{let c=await L.promises.stat(a);if(l.dev===c.dev&&l.ino===c.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}try{await this.preflightCopyTree(o,t)}catch(c){this.sanitizeError(c,t,"cp")}if(l.isFile()||l.isSymbolicLink())try{await L.promises.mkdir(Z.dirname(a),{recursive:!0}),this.resolveAndValidate(i,n)}catch(c){this.sanitizeError(c,n,"cp")}try{await this.copyTreeEntry(o,i,t,n,r?.recursive??!1)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);if(u.code==="EISDIR")throw new x("EISDIR",`is a directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}}async copyTreeEntry(t,n,r,s,i){let o=await L.promises.lstat(t);if(o.isFile()){this.assertCopySize(o,r);let a=this.resolveAndValidate(n,s),l=await this.assertCopyDestinationWritable(a,s),c=await this.openCopySource(t);try{let u=await c.stat();if(!u.isFile()||u.dev!==o.dev||u.ino!==o.ino)throw new x("EACCES",`file identity changed, cp '${r}'`);await this.replaceFile(a,new Uint8Array(0),l??o,{handle:c,size:o.size})}finally{await c.close()}return}if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${r}' contains a symlink`);let a=await L.promises.readlink(t),l=Z.isAbsolute(a)?await this.toVirtualAbsoluteSymlinkTarget(a,r):a;await this.replaceSymlink(n,s,l);return}if(o.isDirectory()){if(!i)throw new x("EISDIR",`is a directory, cp '${r}'`);let a=this.resolveAndValidate(n,s);await L.promises.mkdir(a,{recursive:!0}),a=this.resolveAndValidate(n,s);for(let l of await L.promises.readdir(t))await this.copyTreeEntry(Z.join(t,l),Z.join(n,l),Z.join(r,l),Z.join(s,l),!0);await L.promises.chmod(a,o.mode&4095);return}throw new x("EINVAL",`unsupported file type, cp '${r}'`)}async assertCopyDestinationWritable(t,n){let r;try{r=await L.promises.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}if(!r.isFile()){if(r.isDirectory())return r;throw new x("EACCES",`cannot copy over special file '${n}'`)}let s=this.allowSymlinks?0:L.constants.O_NOFOLLOW,i=await L.promises.open(t,L.constants.O_WRONLY|L.constants.O_NONBLOCK|s);try{let o=await i.stat();if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)throw new x("EACCES",`destination changed, cp '${n}'`)}finally{await i.close()}return r}async replaceSymlink(t,n,r){let s=this.validateParent(t,n),i=Z.dirname(z(n)),o="",a="",l="",c=null;for(let f=0;f<16;f++){let d=`.just-bash-copy-link-${this.randomTransactionToken()}`;o=i==="/"?`/${d}`:`${i}/${d}`,a=this.toRealPath(o);try{await this.symlinkUnlocked(r,o),l=this.validateParent(a,o),c=await L.promises.lstat(l);break}catch(h){if(!ft(h,"EEXIST"))throw h}}if(!c)throw new x("EEXIST",`replacement symlink '${n}'`);let u=!1;try{let f=await L.promises.lstat(l);if(!f.isSymbolicLink()||f.dev!==c.dev||f.ino!==c.ino)throw new x("EACCES","replacement symlink entry changed");await L.promises.rename(l,s),u=!0}finally{!u&&l&&await L.promises.rm(l,{force:!0}).catch(()=>{})}}async toVirtualAbsoluteSymlinkTarget(t,n){let r=Z.resolve(t),s=await L.promises.realpath(r),i=await L.promises.realpath(Z.dirname(r)),o=Z.join(i,Z.basename(r));if(!Le(s,this.canonicalRoot)||!Le(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return Nn(o.slice(this.canonicalRoot.length))||"/"}async preflightCopyTree(t,n,r=new Set){let s=await L.promises.lstat(t),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new x("ELOOP",`cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${n}' contains a symlink`);let o=await L.promises.realpath(t);if(!Le(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let o=await L.promises.readdir(t);for(let a of o)await this.preflightCopyTree(Z.join(t,a),Z.join(n,a),r)}finally{r.delete(i)}}}async mv(t,n){await this.withFilesystemMutation(()=>this.mvUnlocked(t,n))}async mvUnlocked(t,n){U(t,"mv"),U(n,"mv");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.validateParent(r,t),o=this.validateParent(s,n),a;try{a=await L.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);this.sanitizeError(c,t,"mv")}if(a.isDirectory()&&this.isSameOrDescendantIdentity(i,o))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);try{if(a.isSymbolicLink()){let c=await L.promises.readlink(i),u=Z.resolve(Z.dirname(o),c),f=await L.promises.realpath(u).catch(()=>u);if(!Le(f,this.canonicalRoot))throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(ft(u,"EACCES"))throw c}let l=Z.dirname(o);try{await L.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await L.promises.rename(i,o)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(t,n);return}this.sanitizeError(c,t,"mv")}try{if(L.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await L.promises.rename(o,i),new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(ft(c,"EACCES"))throw c;await L.promises.rename(o,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(t,n){let r=t,s=n;try{r=L.realpathSync(t)}catch{}try{s=L.realpathSync(n)}catch{try{let i=L.realpathSync(Z.dirname(n));s=Z.join(i,Z.basename(n))}catch{}}return Le(s,r)}async uniqueTransactionPath(t,n){let r=Z.posix.dirname(t);for(let s=0;s<16;s++){let i=Z.posix.join(r,`.just-bash-mv-${n}-${this.randomTransactionToken()}`);if(!await this.exists(i))return i}throw new x("EEXIST",`mv '${t}'`)}async moveAcrossDevices(t,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(t,"source"),o=this.validateParent(this.toRealPath(r),r),a=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(t),t),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,h=!1,p=async()=>{h&&await L.promises.rename(c,l).catch(()=>{}),d&&await L.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await L.promises.rename(a,u).catch(()=>{}),await L.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cpUnlocked(t,r,{recursive:!0}),(await L.promises.lstat(o)).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`);try{await L.promises.rename(u,a),f=!0}catch(E){if(E.code!=="ENOENT")throw E}await L.promises.rename(o,u),d=!0,await L.promises.rename(l,c),h=!0,await L.promises.rm(c,{recursive:!0,force:!1}),h=!1,f&&await L.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await p(),this.sanitizeError(m,t,"mv")}}resolvePath(t,n){return sn(t,n)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,n,r){Si(t,n,r,Yy)}findEscapingSymlinks(t){let n=[],r=L.readdirSync(t);for(let s of r){let i=Z.join(t,s),o=L.lstatSync(i);if(o.isSymbolicLink()){let a=L.readlinkSync(i),l=Z.resolve(t,a),c;try{c=L.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}Le(c,this.canonicalRoot)||n.push(i)}else o.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(t,n){let r=this.toRealPath(t),s;try{s=this.resolveAndValidate(r,t)}catch{return}try{let i=L.readdirSync(s);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`;n.push(a);let l=Z.join(s,o);L.lstatSync(l).isDirectory()&&this.scanDir(a,n)}}catch{}}async chmod(t,n){await this.withFilesystemMutation(()=>this.chmodUnlocked(t,n))}async chmodUnlocked(t,n){U(t,"chmod");let r=this.toRealPath(t),s=this.resolveAndValidate(r,t);try{let i=await L.promises.lstat(s);if(!i.isFile()){if(!i.isDirectory()&&i.nlink>1)throw new x("EACCES",`cannot chmod multiply-linked special file '${t}'`);await L.promises.chmod(s,n);return}if(i.nlink<=1){await L.promises.chmod(s,n);return}this.assertCopyOnWriteSize(i.size,"chmod",t);let o=await this.openCopySource(s);try{let a=await o.stat();if(!a.isFile())throw new x("EACCES",`file type changed, chmod '${t}'`);await this.replaceFile(s,new Uint8Array(0),{mode:n,atime:a.atime,mtime:a.mtime},{handle:o,size:a.size},{atime:a.atime,mtime:a.mtime},!0)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, chmod '${t}'`);if(o.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,"chmod")}}async symlink(t,n){await this.withFilesystemMutation(()=>this.symlinkUnlocked(t,n))}async symlinkUnlocked(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=z(n),o=z(Z.dirname(i)),a=t.startsWith("/")?z(t):z(o==="/"?`/${t}`:`${o}/${t}`),l=Z.join(this.canonicalRoot,a),c=Z.dirname(s),u=t.startsWith("/")?l:Z.relative(c,l)||".";try{await L.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new x("EEXIST",`file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(t,n){await this.withFilesystemMutation(()=>this.linkUnlocked(t,n))}async linkUnlocked(t,n){U(t,"link"),U(n,"link");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.resolveAndValidate(r,t),o=s===this.root?this.resolveAndValidate(s,n):this.validateParent(s,n);try{await L.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new x("ENOENT",`no such file or directory, link '${t}'`);if(l.code==="EEXIST")throw new x("EEXIST",`file already exists, link '${n}'`);if(l.code==="EPERM")throw new x("EPERM",`operation not permitted, link '${t}'`);this.sanitizeError(a,t,"link")}}async readlink(t){U(t,"readlink");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await L.promises.readlink(r),i=z(t),o=Z.dirname(i),a=Z.isAbsolute(s)?s:Z.resolve(Z.dirname(r),s),l=await L.promises.realpath(a).catch(()=>a);if(Le(l,this.canonicalRoot)){let c=Nn(l.slice(this.canonicalRoot.length))||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:Nn(Z.relative(o,c))}return Z.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(s,t,"readlink")}}async realpath(t){U(t,"realpath");let n=this.toRealPath(t);try{this.resolveAndValidate(n,t)}catch{throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}let r;try{r=await L.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);if(i.code==="ELOOP")throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(s,t,"realpath")}if(Le(r,this.canonicalRoot))return Nn(r.slice(this.canonicalRoot.length))||"/";throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}async utimes(t,n,r){await this.withFilesystemMutation(()=>this.utimesUnlocked(t,n,r))}async utimesUnlocked(t,n,r){U(t,"utimes");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t);try{let o=await L.promises.lstat(i);if(!o.isFile()){if(!o.isDirectory()&&o.nlink>1)throw new x("EACCES",`cannot change times on multiply-linked special file '${t}'`);await L.promises.utimes(i,n,r);return}if(o.nlink<=1){await L.promises.utimes(i,n,r);return}this.assertCopyOnWriteSize(o.size,"utimes",t);let a=await this.openCopySource(i);try{let l=await a.stat();if(!l.isFile())throw new x("EACCES",`file type changed, utimes '${t}'`);await this.replaceFile(i,new Uint8Array(0),l,{handle:a,size:l.size},{atime:n,mtime:r},!0)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new x("ENOENT",`no such file or directory, utimes '${t}'`);if(a.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(o,t,"utimes")}}};import $n from"node:path";function Jy(e){if(e.mounts.length===0)throw new x("EINVAL","createVfsTemplate needs at least one mount");let t=e.mounts.map(({at:c,root:u})=>{let f=dr(u);return{at:(c.startsWith("/")?c:`/${c}`).replace(/\/+$/,"")||"/",root:f}}),n=new Set;for(let{at:c}of t){if(n.has(c))throw new x("EINVAL",`duplicate mount point '${c}' in createVfsTemplate`);if(n.add(c),c==="/")throw new x("EINVAL","mount point '/' would swallow the shared scratch space");for(let u of n)if(u!==c&&c.startsWith(`${u}/`))throw new x("EINVAL",`mount point '${c}' is nested inside '${u}'`)}let r=[];for(let{root:c}of t){for(let u of r){let f=$n.sep;if(c!==u&&(c.startsWith(u+f)||u.startsWith(c+f)))throw new x("EINVAL",`nested template roots share one real subtree: '${c}' and '${u}'`)}r.push(c)}let s=new ze,i=()=>{let c=new Pt({base:s});for(let{at:u,root:f}of t)c.mount(u,new Rt({root:f,mountPoint:"/",...e.readOnly!==void 0&&{readOnly:e.readOnly},...e.maxMemoryBytes!==void 0&&{maxMemoryBytes:e.maxMemoryBytes}}));return c};return{fork:()=>i(),merge:async c=>{let u=[],f=0;for(let h of c){let p=h instanceof Pt?h.diff({space:"vfs"}):h;for(let m of p.writes){let E=m.changedAt??0;u.push({kind:"write",changedAt:E,order:f++,write:m})}for(let m=0;m<p.deletions.length;m++){let E=p.deletionChangedAt?.[m]??0;u.push({kind:"delete",changedAt:E,order:f++,path:p.deletions[m]})}}u.sort((h,p)=>h.changedAt!==p.changedAt?h.changedAt-p.changedAt:h.order-p.order);let d=i();for(let h of u){if(h.kind==="write"&&h.write.metadataOnly&&h.write.mode===void 0&&h.write.mtime===void 0)continue;let p=!1;try{if(h.kind==="delete")await d.rm(h.path,{recursive:!0});else{let m=h.write;m.metadataOnly?(m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="directory"?(await d.mkdir(m.path,{recursive:!0}),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="symlink"?await d.symlink(new TextDecoder().decode(m.content),m.path):(await d.writeFile(m.path,m.content),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime))}p=!0}catch{}p?d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt):d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt,"ancestors")}return d},apply:c=>{let u={writes:c.writes.map(f=>({...f,path:$n.normalize(f.path)})),deletions:c.deletions.map(f=>$n.normalize(f)),...c.deletionChangedAt&&{deletionChangedAt:c.deletionChangedAt}};for(let f of u.writes)if(f.nodeType==="symlink")throw new x("EINVAL",`change-set contains a symlink write: '${f.path}'`);for(let f of[...u.deletions,...u.writes.map(d=>d.path)]){if(!t.some(({root:m})=>f===m||f.startsWith(m+$n.sep)))throw new x("EINVAL",`change-set entry outside every template root: '${f}'`);if(u.deletions.includes(f)&&t.some(({root:E})=>f===E))throw new x("EINVAL",`change-set deletes a registered root: '${f}'`);let h=eg(f);if(!t.some(({root:m})=>h===m||h.startsWith(m+$n.sep)))throw new x("EINVAL",`change-set entry escapes its root through a symlink: '${f}'`)}wi(u)}}}function eg(e){let t=e,n=[];for(;;)try{let r=dr(t);return n.length===0?r:$n.join(r,...n.reverse())}catch{let r=$n.dirname(t);if(r===t)return e;n.push($n.basename(t)),t=r}}var hr=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,n,r,s,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=Hr(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(Zr(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener("abort",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let t={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let n=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=n.exitCode,n}finally{this.cleanupCancellation()}}async*logs(){let t=await this.resultPromise;t.stdout&&(yield{type:"stdout",data:t.stdout,timestamp:new Date}),t.stderr&&(yield{type:"stderr",data:t.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdout+t.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error("command killed"))}};var $i=class e{bashEnv;timeoutMs;constructor(t,n){this.bashEnv=t,this.timeoutMs=n}static async create(t){let n=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Rt({root:t.overlayRoot})}let r=new Un({env:t?.env,cwd:t?.cwd,fs:n,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network,defenseInDepth:t?.defenseInDepth,python:t?.python,javascript:t?.javascript,commands:t?.commands,customCommands:t?.customCommands,fetch:t?.fetch});return new e(r,t?.timeoutMs)}async runCommand(t,n,r){let s,i,o,a,l=!1,c,u;if(typeof t=="object"){let m=t,E=[m.cmd,...m.args??[]];s=Di(E),i=m.cwd,o=m.env,a=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=Di([t,...n]),a=m?.signal}else{s=t;let m=n;i=m?.cwd,o=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new hr(this.bashEnv,s,f,o,d,a,this.timeoutMs);if(l)return h;let p=await h.wait();if(c){let m=await h.stdout();m&&c.write(m)}if(u){let m=await h.stderr();m&&u.write(m)}return p}async writeFiles(t){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(t)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let o=this.bashEnv.fs.resolvePath(n,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(t,n){let r=await this.bashEnv.readFile(t);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Ci=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,maxViolationsTotal:t.maxViolationsTotal??1e3,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let n=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(n),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)s.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:n,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(s)})}return t.sort((n,r)=>r.count-n.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function Cd(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
809
+ `;try{a.writeFileSync(`/bin/${t.name}`,l)}catch{}try{a.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=kd(t.stdout),t.stderr=kd(t.stderr),t}async exec(t,n){let r=new cs(this.limits,n?.signal,this.abortOnUnresolvedCommands),s;try{s=await this.execInScope(t,n,r,0,n?.signal,!1,!1)}catch(o){try{await r.close()}catch{}throw o}let i=s;try{await r.close()}catch{i={...s,stderr:`${s.stderr}bash: execution cleanup failed
810
+ `,exitCode:126}}return i.unresolvedCommands=r.unresolvedCommandNames,t.trim()?this.logResult(i):i}async execInScope(t,n,r,s,i,o=!1,a=!0){let l=f=>a?this.logResult(f):f,c=es(i,n?.signal),u=n?{...n,signal:c.signal}:{signal:c.signal};try{if(r.assertExecDepth(s),hr(t,this.limits.maxSourceBytes),!t.trim())return{stdout:"",stderr:"",exitCode:0,env:Ye(this.state.env,u.env)};this.logger?.info("exec",{command:t});let f=u.cwd??this.state.cwd,d,h=f;if(u.cwd)if(u.env&&"PWD"in u.env)d=u.env.PWD;else if(u.env&&!("PWD"in u.env))try{d=await this.fs.realpath(f),h=d}catch{d=f}else d=f;let p=u.replaceEnv?new Map:new Map(this.state.env);if(u.env)for(let[g,S]of Object.entries(u.env))p.set(g,S);d!==void 0&&p.set("PWD",d);let m={...this.state,env:p,arrays:u.replaceEnv?new Map:mt(this.state.arrays),cwd:h,previousDir:u.env?.OLDPWD??this.state.previousDir,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:Jy(u.stdin,u.stdinKind,this.limits.maxInputBytes,this.limits.maxStringLength,r,o),signal:u.signal,extraArgs:u.args},E=t;u.rawScript||(E=Ha(t));let b=this.defenseInDepthConfig?Re.getInstance(this.defenseInDepthConfig):null,y=b?.activate();try{let g=async()=>{let S=He(E,{maxHeredocSize:this.limits.maxHeredocSize}),v;if(this.transformPlugins.length>0){let P=Object.create(null);for(let N of this.transformPlugins){let I=N.transform({ast:S,metadata:P});S=I.ast,I.metadata&&(P=Ar(P,I.metadata))}v=P}let k={fs:this.fs,commands:this.commands,limits:this.limits,executionScope:r,exec:(P,N,I=!1)=>this.execInScope(P,N,r,s+1,u.signal,I),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:b?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},R=await new qr(k,m).executeScript(S);return v&&(R.metadata=v),l(R)};return y?await y.run(g):await g()}catch(g){if(g instanceof H)return l({stdout:g.stdout,stderr:g.stderr,exitCode:g.exitCode,internalOutputAccounting:g.internalOutputAccounting,env:Ye(this.state.env,u.env)});if(g instanceof Oe){if(s>0)throw g;return l({stdout:g.stdout,stderr:g.stderr,exitCode:g.exitCode,internalOutputAccounting:g.internalOutputAccounting,env:Ye(this.state.env,u.env)})}if(g instanceof dt)return l({stdout:g.stdout,stderr:g.stderr,exitCode:g.exitCode,env:Ye(this.state.env,u.env)});if(g instanceof ce)return l({stdout:g.stdout,stderr:g.stderr,exitCode:1,env:Ye(this.state.env,u.env)});if(g instanceof it)return l({stdout:g.stdout,stderr:g.stderr,exitCode:124,env:Ye(this.state.env,u.env)});if(g instanceof C)return l({stdout:g.stdout,stderr:It(g.stderr),exitCode:C.EXIT_CODE,internalOutputAccounting:g.internalOutputAccounting,env:Ye(this.state.env,u.env)});if(g instanceof Gn)return l({stdout:"",stderr:`bash: security violation: ${It(g.message)}
811
+ `,exitCode:1,env:Ye(this.state.env,u.env)});if(g.name==="ParseException")return l({stdout:"",stderr:`bash: syntax error: ${It(g.message)}
812
+ `,exitCode:2,env:Ye(this.state.env,u.env)});if(g instanceof at)return l({stdout:"",stderr:`bash: ${It(g.message)}
813
+ `,exitCode:2,env:Ye(this.state.env,u.env)});if(g instanceof RangeError)return l({stdout:"",stderr:`bash: ${It(g.message)}
814
+ `,exitCode:1,env:Ye(this.state.env,u.env)});throw g}finally{y?.deactivate()}}catch(f){if(f instanceof it)return l({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:Ye(this.state.env,u.env)});if(f instanceof C)return l({stdout:f.stdout,stderr:It(f.stderr),exitCode:C.EXIT_CODE,internalOutputAccounting:f.internalOutputAccounting,env:Ye(this.state.env,u.env)});throw f}finally{c.cleanup()}}async readFile(t){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),n)}getCwd(){return this.state.cwd}getEnv(){return an(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){hr(t,this.limits.maxSourceBytes);let n=Ha(t),r=He(n,{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let i of this.transformPlugins){let o=i.transform({ast:r,metadata:s});r=o.ast,o.metadata&&(s=Ar(s,o.metadata))}return{script:Dr(r),ast:r,metadata:s}}async analyzeCommands(t){hr(t,this.limits.maxSourceBytes);let n=He(Ha(t),{maxHeredocSize:this.limits.maxHeredocSize}),{commands:r,definedFunctions:s,definedAliases:i}=us(n),o=[];for(let a of r)s.has(a)||i.has(a)||await this.resolvesCommandForAnalysis(a)||o.push(a);return{commands:r,unresolved:o}}async resolvesCommandForAnalysis(t){if((xr.has(t)||Tt.has(t))&&!rl.has(t)||this.state.functions.has(t))return!0;let n=await ds({fs:this.fs,state:{...this.state,hashTable:new Map},commands:this.commands},t);return n!==null&&!("error"in n)}};function Xy(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 Ha(e){let t=e.split(`
815
+ `),n=[],r=[],s="none";for(let i=0;i<t.length;i++){let o=t[i];if(r.length>0){let u=r[r.length-1];if((u.stripTabs?o.replace(/^\t+/,""):o)===u.delimiter){n.push(o.trimStart()),r.pop();continue}n.push(o);continue}let a=s,l=a==="none"?o.trimStart():o;if(n.push(l),s=Xy(o,a),a!=="none")continue;let c=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let u of l.matchAll(c)){let f=u[1]==="-",d=u[3];r.push({delimiter:d,stripTabs:f})}}return n.join(`
816
+ `)}var Yy=new TextDecoder("utf-8",{fatal:!0});function kd(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 Yy.decode(n)}catch{return e}}function Jy(e,t,n,r,s,i){if(e===void 0)return;let o=t==="bytes"?e.length:B(e);if(o>n||o>r)throw new C(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),t==="bytes"?e:Jt(e)}import*as ke from"node:fs";import*as bi from"node:path";function pr(e){return ke.realpathSync(e)}function Ga(e){ke.rmSync(e,{recursive:!0,force:!0})}function Pd(e,t){let n;try{n=ke.lstatSync(e)}catch{return!1}return t?!n.isDirectory():n.isDirectory()}function xd(e,t){Pd(e,t)&&ke.rmSync(e,{recursive:!0,force:!0})}function Za(e,t){if(t.nodeType==="directory"){xd(e,!0),ke.mkdirSync(e,{recursive:!0}),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime);return}if(ke.mkdirSync(bi.dirname(e),{recursive:!0}),t.nodeType==="symlink"){ke.rmSync(e,{force:!0,recursive:!0}),ke.symlinkSync(new TextDecoder().decode(t.content),e);return}if(t.metadataOnly&&Pd(e,!1))throw new x("EINVAL",`metadata-only entry over a different on-disk type: '${e}'`);t.metadataOnly||(xd(e,!1),ke.writeFileSync(e,t.content)),process.platform!=="win32"&&ke.chmodSync(e,t.mode),ke.utimesSync(e,t.mtime,t.mtime)}function Si(e){for(let r of[...e.deletions,...e.writes.map(s=>s.path)])if(bi.resolve(r)!==r)throw new x("EINVAL",`change-set path is not normalized: '${r}'`);let t=[...e.deletions].sort((r,s)=>s.length-r.length||(r<s?-1:r>s?1:0));for(let r of t)Ga(r);let n=[...e.writes].sort((r,s)=>r.path.length-s.path.length||(r.path<s.path?-1:r.path>s.path?1:0));for(let{path:r,...s}of n)Za(r,s)}import*as Ee from"node:fs";import*as Me from"node:path";import*as Qe from"node:fs";import*as Ne from"node:path";function Fe(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?Ne.win32:Ne.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function Hn(e,t){try{let n=Qe.realpathSync(e);return Fe(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=Ne.dirname(e);if(r===e)return null;let s=Hn(r,t);if(s===null)return null;try{if(Qe.lstatSync(e).isSymbolicLink()){let o=Qe.readlinkSync(e),a=Ne.isAbsolute(o)?o:Ne.resolve(Ne.dirname(e),o),l=Hn(a,t);return l===null?null:l}}catch{}return Ne.join(s,Ne.basename(e))}return null}}function Ai(e,t,n){let r=Hn(e,n);if(r===null)return null;let s=Ne.resolve(e),i=s.slice(t.length),o=r.slice(n.length);if(i!==o)return null;try{if(Qe.lstatSync(s).isSymbolicLink())return null}catch{}return r}function vi(e,t){if(!Qe.existsSync(e))throw new Error(`${t} root does not exist`);if(!Qe.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function $d(e,t){if(!Ne.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=Qe.realpathSync(e)}catch{n=Ne.resolve(e)}return Fe(n,t)?{withinRoot:!0,relativePath:On(n.slice(t.length))||"/"}:{withinRoot:!1,safeName:Ne.basename(e)}}function ki(e,t,n,r){let s=e;if(s.path===void 0){for(let o of r)if(s.message?.includes(o))throw e}let i=s.code||"EIO";throw new x(i,`${n} '${t}'`)}async function Ot(e){return Cd(await Qe.promises.lstat(e))}function Qa(e){return Cd(Qe.lstatSync(e))}function Cd(e){return process.platform==="win32"&&e.isDirectory()&&(e.mode=e.mode&-512|493),e}function xi(e){let t=e.content.byteLength;for(let n of e.appendChunks??[])t+=n.byteLength;return t}function Od(e){return xi(e)}function $i(e,t){if(!e.appendChunks||e.appendChunks.length===0)return e.content;let n=e.appendChunks.reduce((i,o)=>i+o.byteLength,e.content.byteLength);if(!Number.isSafeInteger(n))throw new x("EFBIG",`file too large, read '${t}'`);let r=new Uint8Array(n);r.set(e.content);let s=e.content.byteLength;for(let i of e.appendChunks)r.set(i,s),s+=i.byteLength;return e.content=r,e.appendChunks=void 0,r}function Nd(e){return!e||e.type!=="file"?0:xi(e)}function Zr(){return{type:"directory",children:new Map,changedAt:Date.now(),mode:vt,mtime:new Date}}function Qr(e){return e.split("/").filter(Boolean)}var Pi=class e{maxMemoryBytes;rootNode=Zr();bytes=0;mutationSeq_=0;constructor(t){this.maxMemoryBytes=t}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(t){let n=Qr(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 Qr(t)){s=`${s}/${i}`;let o=r.children.get(i);if(o===void 0)o=Zr(),r.children.set(i,o);else if(o.type==="whiteout")o=this.resurrectDir(r,i,s,o.changedAt??0,n);else if(o.type!=="directory")throw new x("ENOTDIR",`not a directory, mkdir '${t}'`);r=o}return r}resurrectDir(t,n,r,s,i){let o=Zr();t.children.set(n,o);let a=i?.(r);if(a)for(let l of a)o.children.has(l)||o.children.set(l,{type:"whiteout",changedAt:s});return o}attach(t,n){n.changedAt=Date.now();let r=Qr(t);if(r.length===0)throw new x("EINVAL",`cannot attach at root, attach '${t}'`);let s=this.parentDirOf(r,t),i=s.children.get(r[r.length-1]);if(i?.type==="directory"&&n.type!=="directory")throw new x("EISDIR",`cannot replace directory with ${n.type}, attach '${t}'`);if(i!==void 0&&n.type==="directory")throw new x("EEXIST",`cannot replace ${i.type} with directory, attach '${t}'`);let o=Nd(i),a=Nd(n);this.assertCapacity(a,o),s.children.set(r[r.length-1],n),this.bytes+=a-o}detach(t){let n=Qr(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=Qr(t);if(n.length===0)throw new x("EINVAL",`cannot whiteout the root, rm '${t}'`);let r=this.rootNode;for(let o=0;o<n.length-1;o++)r=this.ensureChildDir(r,n[o],t);let s=n[n.length-1],i=r.children.get(s);i?.type!=="whiteout"&&(this.bytes-=e.subtreeBytes(i),r.children.set(s,{type:"whiteout",changedAt:Date.now()}))}appendChunk(t,n){this.assertCapacity(n.byteLength),t.appendChunks||(t.appendChunks=[]),t.appendChunks.push(n),this.bytes+=n.byteLength,this.touch(t)}touch(t){t.seq=++this.mutationSeq_,t.changedAt=Date.now()}detachIfUnchanged(t,n,r){let s=this.descend(t);return s.kind!=="found"||s.node!==n||n.seq!==r||n.type==="directory"&&n.children.size>0?!1:(this.detach(t),!0)}*preOrder(){let t=[{path:"/",node:this.rootNode}];for(;t.length>0;){let n=t.pop();if(yield n,n.node.type==="directory"){let r=[...n.node.children.entries()];for(let s=r.length-1;s>=0;s--){let[i,o]=r[s];t.push({path:Rd(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:Rd(r.path,s),node:i})}for(let r=t.length-1;r>=0;r--)yield t[r]}clear(){this.rootNode=Zr(),this.bytes=0}static subtreeBytes(t){if(t===void 0)return 0;if(t.type==="file")return xi(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+=xi(i):i.type==="directory"&&r.push(i)}return n}parentDirOf(t,n){let r=this.rootNode;for(let s=0;s<t.length-1;s++){let i=r.children.get(t[s]);if(i?.type!=="directory")throw new x("ENOTDIR",`not a directory, attach '${n}'`);r=i}return r}ensureChildDir(t,n,r){let s=t.children.get(n);if(s===void 0||s.type==="whiteout")s=Zr(),t.children.set(n,s);else if(s.type!=="directory")throw new x("ENOTDIR",`not a directory, rm '${r}'`);return s}assertCapacity(t,n=0){if(!Number.isSafeInteger(t)||t<0||t>this.maxMemoryBytes-this.bytes+n)throw new x("ENOSPC",`overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function Rd(e,t){return e==="/"?`/${t}`:`${e}/${t}`}var eg=["ELOOP","EFBIG","EPERM"],tg="/home/user/project",Dt=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;get rootDir(){return this.root}restamp(t,n,r="full"){let s=V(t),i=c=>{let u=this.tree.descend(c);u.kind==="found"&&(u.node.changedAt=n)},o=c=>{let u=this.tree.descend(c);if(u.kind==="found"){let f=u.node;(f.changedAt??0)>n&&(f.changedAt=n,f.mtime=new Date(n))}};r==="full"&&i(s);let a=s;for(;;){let c=a.lastIndexOf("/");if(c<=0)break;a=a.slice(0,c),o(a)}if(r==="ancestors")return;let l=[s];for(;l.length>0;){let c=l.pop(),u=this.tree.descend(c);if(!(u.kind!=="found"||u.node.type!=="directory"))for(let f of u.node.children.keys()){let d=`${c==="/"?"":c}/${f}`;o(d),l.push(d)}}}identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Me.resolve(t.root);let n=t.mountPoint??tg;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,vi(this.root,"OverlayFs"),this.canonicalRoot=Ee.realpathSync(this.root),this.tree=new Pi(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new x("EROFS",`read-only file system, ${t}`)}createMountPointDirs(){this.tree.ensureDirs(this.mountPoint)}getMountPoint(){return this.mountPoint}diff(){let t=[],n=[],r=[];for(let{path:i,node:o}of this.tree.preOrder()){let a=this.getRelativeToMount(i);if(!(a===null||a==="/")){if(o.type==="whiteout"){this.existsOnRealFs(i)&&(n.push(a),r.push(o.changedAt??0));continue}if(o.type==="file")if(o.metacopy){if(!this.existsOnRealFs(i))continue;t.push({path:a,nodeType:"file",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0,metadataOnly:!0})}else t.push({path:a,nodeType:"file",content:$i(o,i),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0});else o.type==="directory"?t.push({path:a,nodeType:"directory",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0}):t.push({path:a,nodeType:"symlink",content:new TextEncoder().encode(o.target),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0})}}t.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0);let s=n.map((i,o)=>({path:i,changedAt:r[o]}));return s.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),{writes:t,deletions:s.map(i=>i.path),...s.length>0&&{deletionChangedAt:s.map(i=>i.changedAt)}}}async sync(){for(let{path:t,node:n}of this.tree.postOrder()){let r=this.getRelativeToMount(t);if(r===null||r==="/")continue;if(n.type==="whiteout"){this.existsOnRealFs(t)||this.tree.detach(t);continue}if(n.type==="directory"&&n.children.size>0)continue;let s=n.seq;await this.nodeMatchesDisk(t,n)&&this.tree.detachIfUnchanged(t,n,s)}}reset(){this.tree.clear(),this.createMountPointDirs()}drop(t){let n=t.map(r=>{let s=V(r);if(s==="/")throw new x("EINVAL",`invalid argument, drop '${r}'`);return this.mountPoint==="/"?s:`${this.mountPoint}${s}`});n.sort((r,s)=>s.length-r.length);for(let r of n){let s=this.tree.descend(r);if(s.kind!=="found")continue;let i=s.node;i.type==="directory"&&i.children.size>0||this.tree.detach(r)}}async lstatLower(t){let n=this.resolveRealPathParent_(this.toRealPath(t));if(!n)return null;try{return{canonical:n,stat:await Ot(n)}}catch{return null}}async nodeMatchesDisk(t,n){if(n.type==="directory")return(await this.lstatLower(t))?.stat.isDirectory()??!1;if(n.type==="symlink"){if(!this.allowSymlinks)return!1;let s=await this.lstatLower(t);if(!s?.stat.isSymbolicLink())return!1;try{let i=await Ee.promises.readlink(s.canonical);return this.realTargetToVirtual(i)===n.target}catch{return!1}}if(n.metacopy){let s=await this.lstatLower(t);if(!s?.stat.isFile())return!1;let{stat:i}=s;return!(i.mtime.getTime()!==n.mtime.getTime()||process.platform!=="win32"&&(i.mode&4095)!==(n.mode&4095))}let r=this.resolveRealPath_(this.toRealPath(t));if(!r)return!1;try{let s=await Ot(r);if(!s.isFile())return!1;let i=$i(n,t);if(s.size!==i.byteLength)return!1;let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(r,o),l;try{l=new Uint8Array(await a.readFile())}finally{await a.close()}for(let c=0;c<l.byteLength;c++)if(l[c]!==i[c])return!1;return!0}catch{return!1}}mkdirSync(t,n){this.tree.ensureDirs(V(t),r=>this.lowerChildren(r))}writeFileSync(t,n){let r=V(t);this.ensureParentDirs(r);let s=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.tree.attach(r,{type:"file",content:s,mode:sn,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=V(t),r=this.getRelativeToMount(n);if(r===null)return null;let s=Me.join(this.root,r),i=Me.resolve(s);return Fe(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?Hn(t,this.canonicalRoot):Ai(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Me.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Me.join(r,Me.basename(t))}sanitizeError(t,n,r){ki(t,n,r,eg)}ensureParentDirs(t){let n=kt(t);n!=="/"&&this.tree.ensureDirs(n,r=>this.lowerChildren(r))}lowerChildren(t){let n=this.resolveRealPath_(this.toRealPath(t));if(!n)return null;try{return Ee.readdirSync(n)}catch{return null}}async existsInOverlay(t){let n=V(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 Ot(s),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=pt(n);return Qt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Qt(n,"binary")}async readFileBuffer(t,n=new Set){U(t,"open");let r=V(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, open '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, open '${t}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.type==="symlink"){let a=this.resolveSymlink(r,i.target);return this.readFileBuffer(a,n)}if(i.type!=="file")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(!i.metacopy)return $i(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(!De(a,"ENOSPC"))throw a}return o}return this.readLowerFileBytes(r,t,n)}async readLowerFileBytes(t,n,r){let s=this.resolveRealPath_(this.toRealPath(t));if(!s)throw new x("ENOENT",`no such file or directory, open '${n}'`);try{let i=await Ot(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, open '${n}'`);let l=await Ee.promises.readlink(s),c=this.realTargetToVirtual(l),u=this.resolveSymlink(t,c);return this.readFileBuffer(u,r)}if(i.isDirectory())throw new x("EISDIR",`illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?Ee.constants.O_RDONLY:Ee.constants.O_RDONLY|Ee.constants.O_NOFOLLOW,a=await Ee.promises.open(s,o);try{let l=await a.readFile();return new Uint8Array(l)}finally{await a.close()}}catch(i){let o=i.code;if(o==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${n}'`);if(o==="ELOOP")throw new x("ENOENT",`no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(t,n,r){U(t,"write"),this.assertWritable(`write '${t}'`);let s=V(t);this.ensureParentDirs(s);let i=pt(r),o=Zt(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 sn;if(process.platform==="win32")return sn;try{let r=await this.stat(t);if(r.isFile)return r.mode}catch{}return sn}async appendFile(t,n,r){U(t,"append"),this.assertWritable(`append '${t}'`);let s=V(t),i=pt(r),o=Zt(n,i),a=this.tree.descend(s);if(a.kind==="found"&&a.node.type==="file"){await this.appendToExisting_(s,a.node,o,t);return}if(a.kind==="blocked")throw new x("ENOENT",`no such file or directory, append '${t}'`);if(a.kind==="notdir")throw new x("ENOTDIR",`not a directory, append '${t}'`);let l;try{l=await this.readFileBuffer(s)}catch(f){if(!De(f,"ENOENT"))throw f;l=new Uint8Array(0)}let c=await this.inheritedMode(s),u=this.tree.descend(s);if(u.kind==="found"&&u.node.type==="file"){await this.appendToExisting_(s,u.node,o,t);return}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[o],mode:c,mtime:new Date})}async appendToExisting_(t,n,r,s){if(n.metacopy){let i=await this.readLowerFileBytes(t,s,new Set),o=this.tree.descend(t);if(o.kind==="found"&&o.node.type==="file"&&!o.node.metacopy){this.tree.appendChunk(o.node,r),o.node.mtime=new Date;return}this.tree.attach(t,{type:"file",content:i,appendChunks:[r],mode:n.mode,mtime:new Date});return}this.tree.appendChunk(n,r),n.mtime=new Date}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,n=new Set){U(t,"stat");let r=V(t);if(n.has(r))throw new x("ELOOP",`too many levels of symbolic links, stat '${t}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(s.kind==="notdir")throw new x("ENOTDIR",`not a directory, stat '${t}'`);if(s.kind==="found"){let o=s.node;if(o.type==="whiteout")throw new x("ENOENT",`no such file or directory, stat '${t}'`);if(o.type==="symlink"){let a=this.resolveSymlink(r,o.target);return this.stat(a,n)}return this.memoryEntryStat(o)}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new x("ENOENT",`no such file or directory, stat '${t}'`);try{let o=await Ot(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, stat '${t}'`);let a=await Ee.promises.readlink(i),l=this.realTargetToVirtual(a),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime,dev:o.dev,ino:o.ino}}catch(o){if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){U(t,"lstat");let n=V(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, lstat '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, lstat '${t}'`);try{let i=await Ot(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}memoryEntryStat(t){if(t.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:t.mode,size:t.target.length,mtime:t.mtime};let n=0;return t.type==="file"&&(n=t.metacopy?t.lowerSize??0:Od(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 Kn(t,n)}realTargetToVirtual(t){let n=$d(t,this.canonicalRoot);if(n.withinRoot){if(!Me.isAbsolute(t))return t;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(t,n){U(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=V(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new x("EEXIST",`file already exists, mkdir '${t}'`);return}let i=kt(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.tree.ensureDirs(r,o=>this.lowerChildren(o))}async createExclusive(t,n){let r=n.directory?"mkdir":"open";U(t,r),this.assertWritable(`${r} '${t}'`);let s=V(t);if(await this.existsInOverlay(s))throw new x("EEXIST",`file already exists, ${r} '${t}'`);let i=kt(s),o=s;if(i!=="/"){let l;try{l=await this.realpath(i)}catch{throw new x("ENOENT",`no such file or directory, ${r} '${t}'`)}let c=await this.stat(l).catch(()=>null);if(!c)throw new x("ENOENT",`no such file or directory, ${r} '${t}'`);if(!c.isDirectory)throw new x("ENOTDIR",`not a directory, ${r} '${t}'`);if(o=ht(l,s.slice(s.lastIndexOf("/")+1)),o!==s&&await this.existsInOverlay(o))throw new x("EEXIST",`file already exists, ${r} '${t}'`)}if(n.directory){let l=this.tree.descend(o);if(l.kind==="found"&&l.node.type!=="whiteout")throw new x("EEXIST",`file already exists, ${r} '${t}'`);let c=this.tree.ensureDirs(o,u=>this.lowerChildren(u));c.mode=n.mode;return}this.ensureParentDirs(o);let a=this.tree.descend(o);if(a.kind==="found"&&a.node.type!=="whiteout")throw new x("EEXIST",`file already exists, ${r} '${t}'`);this.tree.attach(o,{type:"file",content:new Uint8Array(0),mode:n.mode,mtime:new Date})}async readdirCore(t,n){let r=new Map,s=new Set,i=this.tree.descend(n);if(i.kind==="blocked")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.kind==="notdir")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);let o;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(l.type!=="directory")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);o=l;for(let[c,u]of l.children){if(u.type==="whiteout"){s.add(c);continue}r.set(c,{name:c,isFile:u.type==="file",isDirectory:u.type==="directory",isSymbolicLink:u.type==="symlink"})}}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await Ot(a)).isSymbolicLink()){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`);return r}let l=await Ee.promises.readdir(a,{withFileTypes:!0});for(let c of l)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!o)throw new x("ENOENT",`no such file or directory, scandir '${t}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,t,"scandir")}return r}async resolveForReaddir(t,n=!1){let r=V(t),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let c=l.node;if(c.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new x("ELOOP",`too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,c.target)}if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let a=this.resolveRealPath_(this.toRealPath(r));if(!a)return{normalized:r,outsideOverlay:!0};try{if((await Ot(a)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let c=await Ee.promises.readlink(a),u=this.realTargetToVirtual(c),f=this.resolveSymlink(r,u);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){U(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,n){U(t,"rm"),this.assertWritable(`rm '${t}'`);let r=V(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}let i=!1;try{(await this.stat(r)).isDirectory&&(i=(await this.readdir(r)).length>0)}catch{}if(i&&!n?.recursive)throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.existsOnRealFs(r)?this.tree.putWhiteout(r):this.tree.detach(r)}existsOnRealFs(t){let n=this.toRealPath(t),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return Qa(r),!0}catch{return!1}}async cp(t,n,r){U(t,"cp"),U(n,"cp"),this.assertWritable(`cp '${n}'`);let s=V(t),i=V(n);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, cp '${t}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new x("EISDIR",`is a directory, cp '${t}'`);if(Gt(s,i))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,n){this.assertWritable(`mv '${n}'`),await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return on(t,n)}getAllPaths(){let t=new Set;for(let{path:n,node:r}of this.tree.preOrder())r.type!=="whiteout"&&t.add(n);return this.scanRealFs(this.mountPoint,t),Array.from(t)}scanRealFs(t,n){if(this.lowerHidden(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let s=Ee.readdirSync(r);for(let i of s){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.lowerHidden(o))continue;n.add(o);let a=Me.join(r,i);Qa(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}lowerHidden(t){let n=this.tree.descend(t);switch(n.kind){case"blocked":case"notdir":return!0;case"found":return n.node.type!=="directory";default:return!1}}entryAt(t){let n=this.tree.descend(t);if(n.kind==="found"&&n.node.type!=="whiteout")return n.node}async chmod(t,n){U(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=V(t);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, chmod '${t}'`);let i=this.entryAt(r);if(i){i.mode=n,this.tree.touch(i);return}let o=await this.stat(r);this.attachMetacopyShadow(r,o,n,o.isFile?o.mtime:new Date)}attachMetacopyShadow(t,n,r,s){this.ensureParentDirs(t),n.isFile?this.tree.attach(t,{type:"file",content:new Uint8Array(0),metacopy:!0,lowerSize:n.size,mode:r,mtime:s}):n.isDirectory&&this.tree.attach(t,{type:"directory",children:new Map,mode:r,mtime:s})}async symlink(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=V(n);if(await this.existsInOverlay(r))throw new x("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:t,mode:rs,mtime:new Date})}async link(t,n){U(t,"link"),U(n,"link"),this.assertWritable(`link '${n}'`);let r=V(t),s=V(n);if(!await this.existsInOverlay(r))throw new x("ENOENT",`no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new x("EPERM",`operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new x("EEXIST",`file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,mode:o.mode,mtime:new Date,identity:o.identity??`overlay:${this.nextMemoryIdentity++}`})}async readlink(t){U(t,"readlink");let n=V(t),r=this.tree.descend(n);if(r.kind==="blocked")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(r.kind==="notdir")throw new x("ENOTDIR",`not a directory, readlink '${t}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.type!=="symlink")throw new x("EINVAL",`invalid argument, readlink '${t}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new x("ENOENT",`no such file or directory, readlink '${t}'`);try{let i=await Ee.promises.readlink(s);if(!Me.isAbsolute(i)){let o=Me.resolve(Me.dirname(s),i),a;try{a=Ee.realpathSync(o)}catch{a=o}if(!Fe(a,this.canonicalRoot))return Me.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){U(t,"realpath");let n=V(t),r=new Set,s=l=>{let c=this.tree.descend(l);if(c.kind==="blocked"||c.kind==="found"&&c.node.type==="whiteout")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return c.kind==="found"?c.node:void 0},i=async l=>{let c=l==="/"?[]:l.slice(1).split("/"),u="";for(let f of c){if(u=`${u}/${f}`,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);let d=s(u),h=0,p=br;for(;d&&d.type==="symlink"&&h<p;){if(r.add(u),u=this.resolveSymlink(u,d.target),h++,r.has(u))throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);d=s(u)}if(h>=p)throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);if(!d){let m=this.toRealPath(u),E=this.resolveRealPath_(m);if(E)try{if((await Ot(E)).isSymbolicLink()){if(!this.allowSymlinks)throw new x("ENOENT",`no such file or directory, realpath '${t}'`);let y=await Ee.promises.readlink(E),g=this.realTargetToVirtual(y);return r.add(u),u=this.resolveSymlink(u,g),i(u)}}catch(b){if(b.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(b,t,"realpath")}else if(!this.allowSymlinks){let b=this.resolveRealPathParent_(m);if(b)try{if((await Ot(b)).isSymbolicLink())throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}catch(y){if(De(y,"ENOENT")||De(y,"ELOOP"))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);this.sanitizeError(y,t,"realpath")}}}}return u||"/"},o=await i(n);if(!await this.existsInOverlay(o))throw new x("ENOENT",`no such file or directory, realpath '${t}'`);return o}async utimes(t,n,r){U(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=V(t);if(!await this.existsInOverlay(s))throw new x("ENOENT",`no such file or directory, utimes '${t}'`);let o=this.entryAt(s);if(o){o.mtime=r,this.tree.touch(o);return}let a=await this.stat(s);this.attachMetacopyShadow(s,a,a.mode,r)}};var Ci=class{bash;overlays;constructor(t={}){let{home:n,project:r,cwd:s,env:i,...o}=t,a=new Map,l=[],c=n?pr(n):null,u=r?pr(r):null,f=c&&u&&(()=>{let p=Be.relative(c,u);return p!==".."&&!p.startsWith(`..${Be.sep}`)&&!Be.isAbsolute(p)})();if(c){let p=new Dt({root:c,mountPoint:"/"});a.set("/home/user",{root:c,fs:p}),l.push({mountPoint:"/home/user",filesystem:p})}let d="/home/user";if(u)if(f&&c){let p=Be.relative(c,u);d=p?`/home/user/${p.split(Be.sep).join("/")}`:"/home/user"}else{let p=new Dt({root:u,mountPoint:"/"});a.set("/project",{root:u,fs:p}),l.push({mountPoint:"/project",filesystem:p}),d="/project"}let h=new ot({base:new Ue,mounts:l});this.overlays=a,this.bash=new qn({...o,env:{HOME:"/home/user",...i},cwd:s??d,fs:h})}analyzeCommands(t){return this.bash.analyzeCommands(t)}exec(t){return this.bash.exec(t)}diff(){let t=[],n=[];for(let{root:r,fs:s}of this.overlays.values()){let i=s.diff();for(let{path:o,...a}of i.writes)t.push({...a,path:Be.join(r,o)});for(let o=0;o<i.deletions.length;o++)n.push({path:Be.join(r,i.deletions[o]),changedAt:i.deletionChangedAt?.[o]})}return t.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),n.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),{writes:t,deletions:n.map(r=>r.path),...n.length>0&&{deletionChangedAt:n.map(r=>r.changedAt??0)}}}async applyChanges(t=this.diff()){let n=new Map,r=s=>{let i=this.findOverlay(s);if(!i)return;let o=`/${Be.relative(i.root,s).split(Be.sep).join("/")}`;if(o==="/")return;let a=n.get(i.fs);a?a.push(o):n.set(i.fs,[o])};try{for(let s of t.deletions)Ga(s),r(s);for(let s of t.writes)Za(s.path,s),r(s.path)}finally{for(let[s,i]of n)s.drop(i)}}findOverlayEntry(t){let n=null;for(let[r,s]of this.overlays)(t===s.root||t.startsWith(s.root+Be.sep))&&(!n||s.root.length>n.root.length)&&(n={mountPoint:r,root:s.root,fs:s.fs});return n}findOverlay(t){return this.findOverlayEntry(t)}resolveRealPath(t){let n=this.findOverlayEntry(t);if(!n)return null;let r=`/${Be.relative(n.root,t).split(Be.sep).join("/")}`;return{mountPoint:n.mountPoint,overlay:n.fs,path:r}}toRealPath(t){let n=t.startsWith("/")?t:`/${t}`,r=null;for(let[s,i]of this.overlays)(n===s||n.startsWith(`${s}/`))&&(!r||s.length>r.mountPoint.length)&&(r={mountPoint:s,root:i.root});return r?Be.join(r.root,n.slice(r.mountPoint.length)):null}async sync(){for(let{fs:t}of this.overlays.values())await t.sync()}reset(){for(let{fs:t}of this.overlays.values())t.reset()}};function ng(e={}){return new Ci(e)}import{randomBytes as rg}from"node:crypto";import*as D from"node:fs";import*as Z from"node:path";var sg=["EACCES","escaping sandbox","EFBIG","ENOTSUP"],Ni=class e{static activeMutationRoots=new Set;static pendingMutations=[];root;canonicalRoot;maxFileReadSize;maxCopyOnWriteSize;maxCopySize;allowSymlinks;constructor(t){this.root=Z.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxCopyOnWriteSize=t.maxCopyOnWriteSize??104857600,this.maxCopySize=t.maxCopySize??0,this.allowSymlinks=t.allowSymlinks??!1,vi(this.root,"ReadWriteFs"),this.canonicalRoot=D.realpathSync(this.root)}resolveAndValidate(t,n){let r=this.allowSymlinks?Hn(t,this.canonicalRoot):Ai(t,this.root,this.canonicalRoot);if(r===null)throw new x("EACCES",`permission denied, '${n}' resolves outside sandbox`);return r}validateParent(t,n){let r=Z.dirname(t),s=this.resolveAndValidate(r,n);return Z.join(s,Z.basename(t))}toRealPath(t){let n=V(t),r=Z.join(this.root,n);return Z.resolve(r)}async readFile(t,n){let r=await this.readFileBuffer(t),s=pt(n);return Qt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Qt(n,"binary")}async readFileBuffer(t){U(t,"open");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=this.allowSymlinks?D.constants.O_RDONLY:D.constants.O_RDONLY|D.constants.O_NOFOLLOW,i=await D.promises.open(r,s);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new x("EFBIG",`file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, open '${t}'`);if(i.code==="EISDIR")throw new x("EISDIR",`illegal operation on a directory, read '${t}'`);if(i.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(s,t,"open")}}async writeFile(t,n,r){await this.withFilesystemMutation(()=>this.writeFileUnlocked(t,n,r))}async writeFileUnlocked(t,n,r){U(t,"write");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t),o=pt(r),a=Zt(n,o),l=Z.dirname(i);try{await D.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:D.constants.O_NOFOLLOW,u=null;try{let f=await D.promises.lstat(i);if(!f.isFile()&&!f.isDirectory())throw new x("EACCES",`cannot write special file '${t}'`);let d=await D.promises.open(i,D.constants.O_WRONLY|D.constants.O_NONBLOCK|c);try{if(u=await d.stat(),!u.isFile())throw new x("EACCES",`cannot write special file '${t}'`);if(u.nlink<=1){await d.truncate(0),await d.writeFile(a);return}}finally{await d.close()}}catch(f){if(f.code!=="ENOENT")throw f}await this.replaceFile(i,a,u)}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"write")}}async appendFile(t,n,r){await this.withFilesystemMutation(()=>this.appendFileUnlocked(t,n,r))}async appendFileUnlocked(t,n,r){U(t,"append");let s=this.toRealPath(t),i=pt(r),o=Zt(n,i),a=this.resolveAndValidate(s,t),l=Z.dirname(a);try{await D.promises.mkdir(l,{recursive:!0}),a=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:D.constants.O_NOFOLLOW,u=null;try{let d=await D.promises.lstat(a);if(!d.isFile()&&!d.isDirectory())throw new x("EACCES",`cannot append special file '${t}'`);let h=await D.promises.open(a,D.constants.O_WRONLY|D.constants.O_APPEND|D.constants.O_NONBLOCK|c);try{if(u=await h.stat(),!u.isFile())throw new x("EACCES",`cannot append special file '${t}'`);if(u.nlink<=1){await h.writeFile(o);return}}finally{await h.close()}}catch(d){if(d.code!=="ENOENT")throw d}if(!u){await this.replaceFile(a,o,null);return}this.assertCopyOnWriteSize(u.size,"append",t);let f=await this.openCopySource(a);try{let d=await f.stat();if(!d.isFile()||d.dev!==u.dev||d.ino!==u.ino)throw new x("EACCES",`file identity changed, append '${t}'`);await this.replaceFile(a,o,d,{handle:f,size:u.size})}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"append")}}async withFilesystemMutation(t){return new Promise((n,r)=>{e.pendingMutations.push({root:this.canonicalRoot,start:()=>{e.activeMutationRoots.add(this.canonicalRoot),t().then(n,r).finally(()=>{e.activeMutationRoots.delete(this.canonicalRoot),e.drainMutationQueue()})}}),e.drainMutationQueue()})}static drainMutationQueue(){for(let t=0;t<e.pendingMutations.length;){let n=e.pendingMutations[t];if([...e.activeMutationRoots].some(s=>Fe(n.root,s)||Fe(s,n.root))){t++;continue}e.pendingMutations.splice(t,1),n.start()}}assertCopyOnWriteSize(t,n,r){if(this.maxCopyOnWriteSize>0&&t>this.maxCopyOnWriteSize)throw new x("EFBIG",`file too large for copy-on-write ${n} '${r}' (${t} bytes, max ${this.maxCopyOnWriteSize})`)}assertCopySize(t,n){if(this.maxCopySize>0&&t.size>this.maxCopySize)throw new x("EFBIG",`file too large to copy '${n}' (${t.size} bytes, max ${this.maxCopySize})`)}randomTransactionToken(){return rg(16).toString("hex")}async openCopySource(t){let n=this.allowSymlinks?0:D.constants.O_NOFOLLOW,r=D.constants.O_RDONLY|D.constants.O_NONBLOCK|n,s=D.constants.O_NOATIME;if(process.platform!=="linux"||s===void 0)return D.promises.open(t,r);try{return await D.promises.open(t,r|s)}catch(i){if(i.code!=="EPERM")throw i;return D.promises.open(t,r)}}async replaceFile(t,n,r,s,i,o=!1){let a=Z.dirname(t),l="",c=null,u=r===null?438:384;for(let p=0;p<16;p++){l=Z.join(a,`.just-bash-write-${this.randomTransactionToken()}`);try{c=await D.promises.open(l,D.constants.O_WRONLY|D.constants.O_CREAT|D.constants.O_EXCL,u);break}catch(m){if(m.code!=="EEXIST")throw m}}if(!c)throw new x("EEXIST",`replacement write '${t}'`);let f=c,d=await f.stat(),h=!1;try{try{let m=0,E=async b=>{let y=0;for(;y<b.byteLength;){let{bytesWritten:g}=await f.write(b,y,b.byteLength-y,m+y);if(g===0)throw new x("EIO","replacement write made no progress");y+=g}m+=y};if(s){let b=Buffer.allocUnsafe(65536),y=0,g=s.size;for(;g>0;){let S=Math.min(b.length,g),{bytesRead:v}=await s.handle.read(b,0,S,y);if(v===0)break;await E(b.subarray(0,v)),y+=v,g-=v}}if(await E(n),r!==null&&await f.chmod(r.mode&(o?4095:511)),i)await f.utimes(i.atime,i.mtime);else if(r!==null){let b=await f.stat();await f.utimes(r.atime,b.mtime)}}finally{await f.close(),c=null}let p=await D.promises.lstat(l);if(!p.isFile()||p.dev!==d.dev||p.ino!==d.ino)throw new x("EACCES","replacement staging entry changed");await D.promises.rename(l,t),h=!0}finally{c&&await c.close().catch(()=>{}),h||await D.promises.rm(l,{force:!0}).catch(()=>{})}}async exists(t){if(t.includes("\0"))return!1;let n=this.toRealPath(t);try{let r=this.resolveAndValidate(n,t);return await D.promises.access(r),!0}catch{return!1}}async stat(t){U(t,"stat");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=await D.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, stat '${t}'`);this.sanitizeError(s,t,"stat")}}async lstat(t){U(t,"lstat");let n=this.toRealPath(t),r=n===this.root?this.resolveAndValidate(n,t):this.validateParent(n,t);try{let s=await D.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new x("ENOENT",`no such file or directory, lstat '${t}'`);this.sanitizeError(s,t,"lstat")}}async mkdir(t,n){await this.withFilesystemMutation(()=>this.mkdirUnlocked(t,n))}async createExclusive(t,n){await this.withFilesystemMutation(()=>this.createExclusiveUnlocked(t,n))}async createExclusiveUnlocked(t,n){let r=n.directory?"mkdir":"open";U(t,r);let s=this.toRealPath(t),i=s===this.root?this.resolveAndValidate(s,t):this.validateParent(s,t);try{if(n.directory){await D.promises.mkdir(i,{mode:n.mode});let l=await D.promises.open(i,D.constants.O_RDONLY|(D.constants.O_DIRECTORY??0)|(this.allowSymlinks?0:D.constants.O_NOFOLLOW));try{await this.assertCreatedInsideRoot(i,s,t,r,await l.stat())}finally{await l.close()}return}let o=this.allowSymlinks?0:D.constants.O_NOFOLLOW,a=await D.promises.open(i,D.constants.O_WRONLY|D.constants.O_CREAT|D.constants.O_EXCL|o,n.mode);try{await this.assertCreatedInsideRoot(i,s,t,r,await a.stat())}finally{await a.close()}}catch(o){let a=o;if(a.code==="EEXIST")throw new x("EEXIST",`file already exists, ${r} '${t}'`);if(a.code==="ENOENT")throw new x("ENOENT",`no such file or directory, ${r} '${t}'`);this.sanitizeError(o,t,r)}}async assertCreatedInsideRoot(t,n,r,s,i){let o=!1;try{let a=this.resolveAndValidate(n,r),l=await D.promises.lstat(a);o=a===t&&l.dev===i.dev&&l.ino===i.ino}catch{o=!1}if(!o)throw new x("EACCES",`permission denied, '${r}' resolves outside sandbox during ${s}`)}async mkdirUnlocked(t,n){U(t,"mkdir");let r=this.toRealPath(t),s=r===this.root?this.resolveAndValidate(r,t):this.validateParent(r,t);try{await D.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new x("EEXIST",`file already exists, mkdir '${t}'`);if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mkdir '${t}'`);this.sanitizeError(i,t,"mkdir")}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){U(t,"scandir");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{if(!this.allowSymlinks&&(await D.promises.lstat(r)).isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);return(await D.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, scandir '${t}'`);if(i.code==="ENOTDIR")throw new x("ENOTDIR",`not a directory, scandir '${t}'`);this.sanitizeError(s,t,"scandir")}}async rm(t,n){await this.withFilesystemMutation(()=>this.rmUnlocked(t,n))}async rmUnlocked(t,n){U(t,"rm");let r=this.toRealPath(t),s=this.validateParent(r,t);try{let i=await D.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new x("EACCES",`permission denied, '${t}' is a symlink`);await D.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"){if(n?.force)return;throw new x("ENOENT",`no such file or directory, rm '${t}'`)}if(o.code==="ENOTEMPTY")throw new x("ENOTEMPTY",`directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,n,r){await this.withFilesystemMutation(()=>this.cpUnlocked(t,n,r))}async cpUnlocked(t,n,r){U(t,"cp"),U(n,"cp");let s=this.toRealPath(t),i=this.toRealPath(n),o=this.validateParent(s,t),a=this.resolveAndValidate(i,n),l;try{l=await D.promises.lstat(o)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}if(l.isDirectory()&&Fe(a,o))throw new x("EINVAL",`cannot copy '${t}' into itself, '${n}'`);if(!l.isDirectory())try{let c=this.validateParent(i,n),u=await D.promises.lstat(c);if(l.dev===u.dev&&l.ino===u.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}if(l.isFile())try{let c=await D.promises.stat(a);if(l.dev===c.dev&&l.ino===c.ino)throw new x("EINVAL",`cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}try{await this.preflightCopyTree(o,t)}catch(c){this.sanitizeError(c,t,"cp")}if(l.isFile()||l.isSymbolicLink())try{await D.promises.mkdir(Z.dirname(a),{recursive:!0}),this.resolveAndValidate(i,n)}catch(c){this.sanitizeError(c,n,"cp")}try{await this.copyTreeEntry(o,i,t,n,r?.recursive??!1)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, cp '${t}'`);if(u.code==="EISDIR")throw new x("EISDIR",`is a directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}}async copyTreeEntry(t,n,r,s,i){let o=await D.promises.lstat(t);if(o.isFile()){this.assertCopySize(o,r);let a=this.resolveAndValidate(n,s),l=await this.assertCopyDestinationWritable(a,s),c=await this.openCopySource(t);try{let u=await c.stat();if(!u.isFile()||u.dev!==o.dev||u.ino!==o.ino)throw new x("EACCES",`file identity changed, cp '${r}'`);await this.replaceFile(a,new Uint8Array(0),l??o,{handle:c,size:o.size})}finally{await c.close()}return}if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${r}' contains a symlink`);let a=await D.promises.readlink(t),l=Z.isAbsolute(a)?await this.toVirtualAbsoluteSymlinkTarget(a,r):a;await this.replaceSymlink(n,s,l);return}if(o.isDirectory()){if(!i)throw new x("EISDIR",`is a directory, cp '${r}'`);let a=this.resolveAndValidate(n,s);await D.promises.mkdir(a,{recursive:!0}),a=this.resolveAndValidate(n,s);for(let l of await D.promises.readdir(t))await this.copyTreeEntry(Z.join(t,l),Z.join(n,l),Z.join(r,l),Z.join(s,l),!0);await D.promises.chmod(a,o.mode&4095);return}throw new x("EINVAL",`unsupported file type, cp '${r}'`)}async assertCopyDestinationWritable(t,n){let r;try{r=await D.promises.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}if(!r.isFile()){if(r.isDirectory())return r;throw new x("EACCES",`cannot copy over special file '${n}'`)}let s=this.allowSymlinks?0:D.constants.O_NOFOLLOW,i=await D.promises.open(t,D.constants.O_WRONLY|D.constants.O_NONBLOCK|s);try{let o=await i.stat();if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)throw new x("EACCES",`destination changed, cp '${n}'`)}finally{await i.close()}return r}async replaceSymlink(t,n,r){let s=this.validateParent(t,n),i=Z.dirname(V(n)),o="",a="",l="",c=null;for(let f=0;f<16;f++){let d=`.just-bash-copy-link-${this.randomTransactionToken()}`;o=i==="/"?`/${d}`:`${i}/${d}`,a=this.toRealPath(o);try{await this.symlinkUnlocked(r,o),l=this.validateParent(a,o),c=await D.promises.lstat(l);break}catch(h){if(!De(h,"EEXIST"))throw h}}if(!c)throw new x("EEXIST",`replacement symlink '${n}'`);let u=!1;try{let f=await D.promises.lstat(l);if(!f.isSymbolicLink()||f.dev!==c.dev||f.ino!==c.ino)throw new x("EACCES","replacement symlink entry changed");await D.promises.rename(l,s),u=!0}finally{!u&&l&&await D.promises.rm(l,{force:!0}).catch(()=>{})}}async toVirtualAbsoluteSymlinkTarget(t,n){let r=Z.resolve(t),s=await D.promises.realpath(r),i=await D.promises.realpath(Z.dirname(r)),o=Z.join(i,Z.basename(r));if(!Fe(s,this.canonicalRoot)||!Fe(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return On(o.slice(this.canonicalRoot.length))||"/"}async preflightCopyTree(t,n,r=new Set){let s=await D.promises.lstat(t),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new x("ELOOP",`cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new x("EACCES",`permission denied, cp '${n}' contains a symlink`);let o=await D.promises.realpath(t);if(!Fe(o,this.canonicalRoot))throw new x("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let o=await D.promises.readdir(t);for(let a of o)await this.preflightCopyTree(Z.join(t,a),Z.join(n,a),r)}finally{r.delete(i)}}}async mv(t,n){await this.withFilesystemMutation(()=>this.mvUnlocked(t,n))}async mvUnlocked(t,n){U(t,"mv"),U(n,"mv");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.validateParent(r,t),o=this.validateParent(s,n),a;try{a=await D.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);this.sanitizeError(c,t,"mv")}if(a.isDirectory()&&this.isSameOrDescendantIdentity(i,o))throw new x("EINVAL",`cannot move '${t}' into itself, '${n}'`);try{if(a.isSymbolicLink()){let c=await D.promises.readlink(i),u=Z.resolve(Z.dirname(o),c),f=await D.promises.realpath(u).catch(()=>u);if(!Fe(f,this.canonicalRoot))throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(De(u,"EACCES"))throw c}let l=Z.dirname(o);try{await D.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await D.promises.rename(i,o)}catch(c){let u=c;if(u.code==="ENOENT")throw new x("ENOENT",`no such file or directory, mv '${t}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(t,n);return}this.sanitizeError(c,t,"mv")}try{if(D.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await D.promises.rename(o,i),new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(De(c,"EACCES"))throw c;await D.promises.rename(o,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(t,n){let r=t,s=n;try{r=D.realpathSync(t)}catch{}try{s=D.realpathSync(n)}catch{try{let i=D.realpathSync(Z.dirname(n));s=Z.join(i,Z.basename(n))}catch{}}return Fe(s,r)}async uniqueTransactionPath(t,n){let r=Z.posix.dirname(t);for(let s=0;s<16;s++){let i=Z.posix.join(r,`.just-bash-mv-${n}-${this.randomTransactionToken()}`);if(!await this.exists(i))return i}throw new x("EEXIST",`mv '${t}'`)}async moveAcrossDevices(t,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(t,"source"),o=this.validateParent(this.toRealPath(r),r),a=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(t),t),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,h=!1,p=async()=>{h&&await D.promises.rename(c,l).catch(()=>{}),d&&await D.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await D.promises.rename(a,u).catch(()=>{}),await D.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cpUnlocked(t,r,{recursive:!0}),(await D.promises.lstat(o)).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw new x("EACCES",`permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`);try{await D.promises.rename(u,a),f=!0}catch(E){if(E.code!=="ENOENT")throw E}await D.promises.rename(o,u),d=!0,await D.promises.rename(l,c),h=!0,await D.promises.rm(c,{recursive:!0,force:!1}),h=!1,f&&await D.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await p(),this.sanitizeError(m,t,"mv")}}resolvePath(t,n){return on(t,n)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,n,r){ki(t,n,r,sg)}findEscapingSymlinks(t){let n=[],r=D.readdirSync(t);for(let s of r){let i=Z.join(t,s),o=D.lstatSync(i);if(o.isSymbolicLink()){let a=D.readlinkSync(i),l=Z.resolve(t,a),c;try{c=D.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}Fe(c,this.canonicalRoot)||n.push(i)}else o.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(t,n){let r=this.toRealPath(t),s;try{s=this.resolveAndValidate(r,t)}catch{return}try{let i=D.readdirSync(s);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`;n.push(a);let l=Z.join(s,o);D.lstatSync(l).isDirectory()&&this.scanDir(a,n)}}catch{}}async chmod(t,n){await this.withFilesystemMutation(()=>this.chmodUnlocked(t,n))}async chmodUnlocked(t,n){U(t,"chmod");let r=this.toRealPath(t),s=this.resolveAndValidate(r,t);try{let i=await D.promises.lstat(s);if(!i.isFile()){if(!i.isDirectory()&&i.nlink>1)throw new x("EACCES",`cannot chmod multiply-linked special file '${t}'`);await D.promises.chmod(s,n);return}if(i.nlink<=1){await D.promises.chmod(s,n);return}this.assertCopyOnWriteSize(i.size,"chmod",t);let o=await this.openCopySource(s);try{let a=await o.stat();if(!a.isFile())throw new x("EACCES",`file type changed, chmod '${t}'`);await this.replaceFile(s,new Uint8Array(0),{mode:n,atime:a.atime,mtime:a.mtime},{handle:o,size:a.size},{atime:a.atime,mtime:a.mtime},!0)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new x("ENOENT",`no such file or directory, chmod '${t}'`);if(o.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,"chmod")}}async symlink(t,n){await this.withFilesystemMutation(()=>this.symlinkUnlocked(t,n))}async symlinkUnlocked(t,n){if(!this.allowSymlinks)throw new x("EPERM",`operation not permitted, symlink '${n}'`);U(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=V(n),o=V(Z.dirname(i)),a=t.startsWith("/")?V(t):V(o==="/"?`/${t}`:`${o}/${t}`),l=Z.join(this.canonicalRoot,a),c=Z.dirname(s),u=t.startsWith("/")?l:Z.relative(c,l)||".";try{await D.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new x("EEXIST",`file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(t,n){await this.withFilesystemMutation(()=>this.linkUnlocked(t,n))}async linkUnlocked(t,n){U(t,"link"),U(n,"link");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.resolveAndValidate(r,t),o=s===this.root?this.resolveAndValidate(s,n):this.validateParent(s,n);try{await D.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new x("ENOENT",`no such file or directory, link '${t}'`);if(l.code==="EEXIST")throw new x("EEXIST",`file already exists, link '${n}'`);if(l.code==="EPERM")throw new x("EPERM",`operation not permitted, link '${t}'`);this.sanitizeError(a,t,"link")}}async readlink(t){U(t,"readlink");let n=this.toRealPath(t),r=n===this.root?this.resolveAndValidate(n,t):this.validateParent(n,t);try{let s=await D.promises.readlink(r),i=V(t),o=Z.dirname(i),a=Z.isAbsolute(s)?s:Z.resolve(Z.dirname(r),s),l=await D.promises.realpath(a).catch(()=>a);if(Fe(l,this.canonicalRoot)){let c=On(l.slice(this.canonicalRoot.length))||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:On(Z.relative(o,c))}return Z.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new x("EINVAL",`invalid argument, readlink '${t}'`);this.sanitizeError(s,t,"readlink")}}async realpath(t){U(t,"realpath");let n=this.toRealPath(t);try{this.resolveAndValidate(n,t)}catch{throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}let r;try{r=await D.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new x("ENOENT",`no such file or directory, realpath '${t}'`);if(i.code==="ELOOP")throw new x("ELOOP",`too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(s,t,"realpath")}if(Fe(r,this.canonicalRoot))return On(r.slice(this.canonicalRoot.length))||"/";throw new x("ENOENT",`no such file or directory, realpath '${t}'`)}async utimes(t,n,r){await this.withFilesystemMutation(()=>this.utimesUnlocked(t,n,r))}async utimesUnlocked(t,n,r){U(t,"utimes");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t);try{let o=await D.promises.lstat(i);if(!o.isFile()){if(!o.isDirectory()&&o.nlink>1)throw new x("EACCES",`cannot change times on multiply-linked special file '${t}'`);await D.promises.utimes(i,n,r);return}if(o.nlink<=1){await D.promises.utimes(i,n,r);return}this.assertCopyOnWriteSize(o.size,"utimes",t);let a=await this.openCopySource(i);try{let l=await a.stat();if(!l.isFile())throw new x("EACCES",`file type changed, utimes '${t}'`);await this.replaceFile(i,new Uint8Array(0),l,{handle:a,size:l.size},{atime:n,mtime:r},!0)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new x("ENOENT",`no such file or directory, utimes '${t}'`);if(a.code==="ELOOP")throw new x("EACCES",`permission denied, '${t}' is a symlink`);this.sanitizeError(o,t,"utimes")}}};import Nn from"node:path";function ig(e){if(e.mounts.length===0)throw new x("EINVAL","createVfsTemplate needs at least one mount");let t=e.mounts.map(({at:c,root:u})=>{let f=pr(u);return{at:(c.startsWith("/")?c:`/${c}`).replace(/\/+$/,"")||"/",root:f}}),n=new Set;for(let{at:c}of t){if(n.has(c))throw new x("EINVAL",`duplicate mount point '${c}' in createVfsTemplate`);if(n.add(c),c==="/")throw new x("EINVAL","mount point '/' would swallow the shared scratch space");for(let u of n)if(u!==c&&c.startsWith(`${u}/`))throw new x("EINVAL",`mount point '${c}' is nested inside '${u}'`)}let r=[];for(let{root:c}of t){for(let u of r){let f=Nn.sep;if(c!==u&&(c.startsWith(u+f)||u.startsWith(c+f)))throw new x("EINVAL",`nested template roots share one real subtree: '${c}' and '${u}'`)}r.push(c)}let s=new Ue,i=()=>{let c=new ot({base:s});for(let{at:u,root:f}of t)c.mount(u,new Dt({root:f,mountPoint:"/",...e.readOnly!==void 0&&{readOnly:e.readOnly},...e.maxMemoryBytes!==void 0&&{maxMemoryBytes:e.maxMemoryBytes}}));return c};return{fork:()=>i(),merge:async c=>{let u=[],f=0;for(let h of c){let p=h instanceof ot?h.diff({space:"vfs"}):h;for(let m of p.writes){let E=m.changedAt??0;u.push({kind:"write",changedAt:E,order:f++,write:m})}for(let m=0;m<p.deletions.length;m++){let E=p.deletionChangedAt?.[m]??0;u.push({kind:"delete",changedAt:E,order:f++,path:p.deletions[m]})}}u.sort((h,p)=>h.changedAt!==p.changedAt?h.changedAt-p.changedAt:h.order-p.order);let d=i();for(let h of u){if(h.kind==="write"&&h.write.metadataOnly&&h.write.mode===void 0&&h.write.mtime===void 0)continue;let p=!1;try{if(h.kind==="delete")await d.rm(h.path,{recursive:!0});else{let m=h.write;m.metadataOnly?(m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="directory"?(await d.mkdir(m.path,{recursive:!0}),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="symlink"?await d.symlink(new TextDecoder().decode(m.content),m.path):(await d.writeFile(m.path,m.content),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime))}p=!0}catch{}p?d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt):d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt,"ancestors")}return d},apply:c=>{let u={writes:c.writes.map(f=>({...f,path:Nn.normalize(f.path)})),deletions:c.deletions.map(f=>Nn.normalize(f)),...c.deletionChangedAt&&{deletionChangedAt:c.deletionChangedAt}};for(let f of u.writes)if(f.nodeType==="symlink")throw new x("EINVAL",`change-set contains a symlink write: '${f.path}'`);for(let f of[...u.deletions,...u.writes.map(d=>d.path)]){if(!t.some(({root:m})=>f===m||f.startsWith(m+Nn.sep)))throw new x("EINVAL",`change-set entry outside every template root: '${f}'`);if(u.deletions.includes(f)&&t.some(({root:E})=>f===E))throw new x("EINVAL",`change-set deletes a registered root: '${f}'`);let h=og(f);if(!t.some(({root:m})=>h===m||h.startsWith(m+Nn.sep)))throw new x("EINVAL",`change-set entry escapes its root through a symlink: '${f}'`)}Si(u)}}}function og(e){let t=e,n=[];for(;;)try{let r=pr(t);return n.length===0?r:Nn.join(r,...n.reverse())}catch{let r=Nn.dirname(t);if(r===t)return e;n.push(Nn.basename(t)),t=r}}var mr=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,n,r,s,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=Kr(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(Xr(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener("abort",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let t={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let n=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=n.exitCode,n}finally{this.cleanupCancellation()}}async*logs(){let t=await this.resultPromise;t.stdout&&(yield{type:"stdout",data:t.stdout,timestamp:new Date}),t.stderr&&(yield{type:"stderr",data:t.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdout+t.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error("command killed"))}};var Ri=class e{bashEnv;timeoutMs;constructor(t,n){this.bashEnv=t,this.timeoutMs=n}static async create(t){let n=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Dt({root:t.overlayRoot})}let r=new qn({env:t?.env,cwd:t?.cwd,fs:n,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network,defenseInDepth:t?.defenseInDepth,python:t?.python,javascript:t?.javascript,commands:t?.commands,customCommands:t?.customCommands,fetch:t?.fetch});return new e(r,t?.timeoutMs)}async runCommand(t,n,r){let s,i,o,a,l=!1,c,u;if(typeof t=="object"){let m=t,E=[m.cmd,...m.args??[]];s=_i(E),i=m.cwd,o=m.env,a=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=_i([t,...n]),a=m?.signal}else{s=t;let m=n;i=m?.cwd,o=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new mr(this.bashEnv,s,f,o,d,a,this.timeoutMs);if(l)return h;let p=await h.wait();if(c){let m=await h.stdout();m&&c.write(m)}if(u){let m=await h.stderr();m&&u.write(m)}return p}async writeFiles(t){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(t)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let o=this.bashEnv.fs.resolvePath(n,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(t,n){let r=await this.bashEnv.readFile(t);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Oi=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,maxViolationsTotal:t.maxViolationsTotal??1e3,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let n=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(n),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)s.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:n,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(s)})}return t.sort((n,r)=>r.count-n.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function Dd(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
811
817
  Type: ${e.type}`,`
812
818
  Path: ${e.path}`,`
813
819
  Message: ${e.message}`,e.executionId?`
814
- ExecutionId: ${e.executionId}`:"")}}var Nd=null;try{let e=process.getBuiltinModule,t=typeof e=="function"?e("module"):typeof Ni=="function"?Ni("node:module"):null;Nd=t?.Module??t?.default??null,typeof e=="function"&&e("worker_threads")?.isMainThread===!1&&e("crypto")?.randomUUID?.()}catch{Nd=null}var Ha=class{maxSourceBytes;plugins=[];constructor(t=67108864){if(this.maxSourceBytes=t,!Number.isSafeInteger(t)||t<0)throw new Error("BashTransformPipeline: invalid maxSourceBytes")}use(t){return this.plugins.push(t),this}transform(t){fr(t,this.maxSourceBytes);let n=qe(t),r=Object.create(null);for(let s of this.plugins){let i=s.transform({ast:n,metadata:r});n=i.ast,i.metadata&&(r=Er(r,i.metadata))}return{script:Nr(n),ast:n,metadata:r}}};var Za=class{name="command-collector";transform(t){let{commands:n}=ls(t.ast);return{ast:t.ast,metadata:{commands:n.sort()}}}};var Qa=class{name="tee";options;counter=0;constructor(t){this.options=t}transform(t){let n=[],r=this.options.timestamp??new Date;return{ast:this.transformScript(t.ast,n,r),metadata:{teeFiles:n}}}formatTimestamp(t){return t.toISOString().replace(/:/g,"-")}generateStdoutPath(t,n,r){let s=this.formatTimestamp(r),i=String(t).padStart(3,"0");if(U(this.options.outputDir,"create tee output"),!this.options.outputDir.startsWith("/")||this.options.outputDir.split("/").includes(".."))throw new Error("tee output directory must be an absolute safe path");let o=z(this.options.outputDir),a=this.encodeCommandName(n),l=z(`${o}/${s}-${i}-${a}.stdout.txt`);if(o!=="/"&&!l.startsWith(`${o}/`))throw new Error("tee output path escapes configured output directory");return l}encodeCommandName(t){if(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(t))return t;let n=2166136261;for(let s=0;s<t.length;s++)n^=t.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return`${t.replace(/[^A-Za-z0-9_-]/g,"_").replace(/^_+|_+$/g,"").slice(0,32)||"command"}-${n.toString(16).padStart(8,"0")}`}transformScript(t,n,r){return{...t,statements:t.statements.map(s=>this.transformStatement(s,n,r))}}transformStatement(t,n,r){let s=[],i=[];for(let o=0;o<t.pipelines.length;o++){let a=t.pipelines[o];o>0&&i.push(t.operators[o-1]);let l=this.transformPipeline(a,n,r);s.push(l.pipeline),l.origCmdNewIndices!==null&&(i.push(";"),s.push(this.makePipestatusRestore(l.origCmdNewIndices,l.negated)))}return{...t,pipelines:s,operators:i}}transformPipeline(t,n,r){if(t.commands.length<=1)return{pipeline:t,origCmdNewIndices:null,negated:!1};let s=[],i=[],o=[],a=!1;for(let l=0;l<t.commands.length;l++){let c=t.commands[l],u=l===t.commands.length-1;if(c.type!=="SimpleCommand"||!c.name||!this.shouldTarget(c)){o.push(s.length),s.push(c),u||i.push(t.pipeStderr?.[l]??!1);continue}let f=this.getCommandName(c.name)??"unknown",d=this.counter++,h=this.generateStdoutPath(d,f,r),p=this.makeTeeCommand(h),m=this.serializeCommand(c);n.push({commandIndex:d,commandName:f,command:m,stdoutFile:h}),o.push(s.length),s.push(c),i.push(t.pipeStderr?.[l]??!1),s.push(p),u||i.push(!1),a=!0}return a?{pipeline:{...t,negated:!1,commands:s,pipeStderr:i.length>0?i:void 0},origCmdNewIndices:o,negated:t.negated}:{pipeline:t,origCmdNewIndices:null,negated:!1}}makePipestatusRestore(t,n){return{type:"Pipeline",commands:[{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"builtin"}]},args:[{type:"Word",parts:[{type:"Literal",value:"__just_bash_tee_restore"}]},...t.map(r=>({type:"Word",parts:[{type:"ParameterExpansion",parameter:`PIPESTATUS[${r}]`,operation:null}]}))],redirections:[]}],negated:n}}shouldTarget(t){if(!this.options.targetCommandPattern)return!0;let n=this.getCommandName(t.name);return n!==null&&this.options.targetCommandPattern.test(n)}getCommandName(t){return t&&t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}serializeCommand(t){let n=[];t.name&&n.push(we(t.name));for(let r of t.args)n.push(we(r));return n.join(" ")}makeTeeCommand(t){return{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"tee"}]},args:[{type:"Word",parts:[{type:"Literal",value:t}]}],redirections:[]}}};export{xi as AgentSandbox,Un as Bash,Ha as BashTransformPipeline,Za as CommandCollectorPlugin,Re as DefenseInDepthBox,Ri as EMPTY_BYTES,x as FsError,ze as InMemoryFs,Pt as MountableFs,gt as NetworkAccessDeniedError,Rt as OverlayFs,Pi as ReadWriteFs,Xt as RedirectNotAllowedError,$i as Sandbox,hr as SandboxCommand,qn as SecurityViolationError,Ci as SecurityViolationLogger,Qa as TeePlugin,Vn as TooManyRedirectsError,wi as applyDiffToRealFs,Td as bytesOutput,Ky as createAgentSandbox,zd as createCommandContext,Cd as createConsoleViolationCallback,Jy as createVfsTemplate,Od as decodeBytesToUtf8,Ud as defineCommand,Yt as encodeUtf8ToBytes,_d as fsErrorCode,Fd as getCommandNames,Wd as getJavaScriptCommandNames,Md as getNetworkCommandNames,Bd as getPythonCommandNames,ft as isFsErrorCode,Cn as latin1FromBytes,qe as parse,Nr as serialize,Ut as stdoutAsBytes,Dd as stdoutKind,Id as textOutput,Ld as toFsError,yr as unsafeBytesFromLatin1};
820
+ ExecutionId: ${e.executionId}`:"")}}var Id=null;try{let e=process.getBuiltinModule,t=typeof e=="function"?e("module"):typeof Di=="function"?Di("node:module"):null;Id=t?.Module??t?.default??null,typeof e=="function"&&e("worker_threads")?.isMainThread===!1&&e("crypto")?.randomUUID?.()}catch{Id=null}var Ka=class{maxSourceBytes;plugins=[];constructor(t=67108864){if(this.maxSourceBytes=t,!Number.isSafeInteger(t)||t<0)throw new Error("BashTransformPipeline: invalid maxSourceBytes")}use(t){return this.plugins.push(t),this}transform(t){hr(t,this.maxSourceBytes);let n=He(t),r=Object.create(null);for(let s of this.plugins){let i=s.transform({ast:n,metadata:r});n=i.ast,i.metadata&&(r=Ar(r,i.metadata))}return{script:Dr(n),ast:n,metadata:r}}};var Xa=class{name="command-collector";transform(t){let{commands:n}=us(t.ast);return{ast:t.ast,metadata:{commands:n.sort()}}}};var Ya=class{name="tee";options;counter=0;constructor(t){this.options=t}transform(t){let n=[],r=this.options.timestamp??new Date;return{ast:this.transformScript(t.ast,n,r),metadata:{teeFiles:n}}}formatTimestamp(t){return t.toISOString().replace(/:/g,"-")}generateStdoutPath(t,n,r){let s=this.formatTimestamp(r),i=String(t).padStart(3,"0");if(U(this.options.outputDir,"create tee output"),!this.options.outputDir.startsWith("/")||this.options.outputDir.split("/").includes(".."))throw new Error("tee output directory must be an absolute safe path");let o=V(this.options.outputDir),a=this.encodeCommandName(n),l=V(`${o}/${s}-${i}-${a}.stdout.txt`);if(o!=="/"&&!l.startsWith(`${o}/`))throw new Error("tee output path escapes configured output directory");return l}encodeCommandName(t){if(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(t))return t;let n=2166136261;for(let s=0;s<t.length;s++)n^=t.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return`${t.replace(/[^A-Za-z0-9_-]/g,"_").replace(/^_+|_+$/g,"").slice(0,32)||"command"}-${n.toString(16).padStart(8,"0")}`}transformScript(t,n,r){return{...t,statements:t.statements.map(s=>this.transformStatement(s,n,r))}}transformStatement(t,n,r){let s=[],i=[];for(let o=0;o<t.pipelines.length;o++){let a=t.pipelines[o];o>0&&i.push(t.operators[o-1]);let l=this.transformPipeline(a,n,r);s.push(l.pipeline),l.origCmdNewIndices!==null&&(i.push(";"),s.push(this.makePipestatusRestore(l.origCmdNewIndices,l.negated)))}return{...t,pipelines:s,operators:i}}transformPipeline(t,n,r){if(t.commands.length<=1)return{pipeline:t,origCmdNewIndices:null,negated:!1};let s=[],i=[],o=[],a=!1;for(let l=0;l<t.commands.length;l++){let c=t.commands[l],u=l===t.commands.length-1;if(c.type!=="SimpleCommand"||!c.name||!this.shouldTarget(c)){o.push(s.length),s.push(c),u||i.push(t.pipeStderr?.[l]??!1);continue}let f=this.getCommandName(c.name)??"unknown",d=this.counter++,h=this.generateStdoutPath(d,f,r),p=this.makeTeeCommand(h),m=this.serializeCommand(c);n.push({commandIndex:d,commandName:f,command:m,stdoutFile:h}),o.push(s.length),s.push(c),i.push(t.pipeStderr?.[l]??!1),s.push(p),u||i.push(!1),a=!0}return a?{pipeline:{...t,negated:!1,commands:s,pipeStderr:i.length>0?i:void 0},origCmdNewIndices:o,negated:t.negated}:{pipeline:t,origCmdNewIndices:null,negated:!1}}makePipestatusRestore(t,n){return{type:"Pipeline",commands:[{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"builtin"}]},args:[{type:"Word",parts:[{type:"Literal",value:"__just_bash_tee_restore"}]},...t.map(r=>({type:"Word",parts:[{type:"ParameterExpansion",parameter:`PIPESTATUS[${r}]`,operation:null}]}))],redirections:[]}],negated:n}}shouldTarget(t){if(!this.options.targetCommandPattern)return!0;let n=this.getCommandName(t.name);return n!==null&&this.options.targetCommandPattern.test(n)}getCommandName(t){return t&&t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}serializeCommand(t){let n=[];t.name&&n.push(we(t.name));for(let r of t.args)n.push(we(r));return n.join(" ")}makeTeeCommand(t){return{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"tee"}]},args:[{type:"Word",parts:[{type:"Literal",value:t}]}],redirections:[]}}};export{Ci as AgentSandbox,qn as Bash,Ka as BashTransformPipeline,Xa as CommandCollectorPlugin,Re as DefenseInDepthBox,Ii as EMPTY_BYTES,x as FsError,Ue as InMemoryFs,ot as MountableFs,Et as NetworkAccessDeniedError,Dt as OverlayFs,Ni as ReadWriteFs,Yt as RedirectNotAllowedError,Ri as Sandbox,mr as SandboxCommand,Gn as SecurityViolationError,Oi as SecurityViolationLogger,Ya as TeePlugin,Un as TooManyRedirectsError,Si as applyDiffToRealFs,Md as bytesOutput,ng as createAgentSandbox,Gd as createCommandContext,Dd as createConsoleViolationCallback,ig as createVfsTemplate,_d as decodeBytesToUtf8,Zd as defineCommand,Jt as encodeUtf8ToBytes,Bd as fsErrorCode,Vd as getCommandNames,jd as getJavaScriptCommandNames,zd as getNetworkCommandNames,Ud as getPythonCommandNames,De as isFsErrorCode,Rn as latin1FromBytes,He as parse,Dr as serialize,qt as stdoutAsBytes,Ld as stdoutKind,Fd as textOutput,Wd as toFsError,wr as unsafeBytesFromLatin1};