typescript-virtual-container 1.4.3 → 1.4.4

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 (596) hide show
  1. package/.vscode/settings.json +2 -1
  2. package/README.md +137 -19
  3. package/benchmark-results.txt +21 -21
  4. package/builds/self-standalone.js +200 -193
  5. package/builds/self-standalone.js.map +4 -4
  6. package/builds/standalone-wo-sftp.js +166 -159
  7. package/builds/standalone-wo-sftp.js.map +4 -4
  8. package/builds/standalone.js +168 -161
  9. package/builds/standalone.js.map +4 -4
  10. package/builds/web-full-api.min.js +5 -5
  11. package/builds/web-full-api.min.js.map +3 -3
  12. package/builds/web.min.js +5 -5
  13. package/builds/web.min.js.map +3 -3
  14. package/bun.lock +4 -6
  15. package/examples/web.min.js +5 -5
  16. package/package.json +4 -3
  17. package/src/Honeypot/index.d.ts.map +1 -0
  18. package/src/SSHClient/index.d.ts.map +1 -0
  19. package/src/SSHMimic/exec.d.ts.map +1 -0
  20. package/src/SSHMimic/executor.d.ts.map +1 -0
  21. package/src/SSHMimic/hostKey.d.ts.map +1 -0
  22. package/src/SSHMimic/index.d.ts.map +1 -0
  23. package/src/SSHMimic/loginBanner.d.ts.map +1 -0
  24. package/src/SSHMimic/loginFormat.d.ts.map +1 -0
  25. package/src/SSHMimic/prompt.d.ts.map +1 -0
  26. package/src/SSHMimic/sftp.d.ts.map +1 -0
  27. package/src/VirtualFileSystem/binaryPack.d.ts.map +1 -0
  28. package/src/VirtualFileSystem/index.d.ts.map +1 -0
  29. package/src/VirtualFileSystem/index.ts +11 -9
  30. package/src/VirtualFileSystem/internalTypes.d.ts.map +1 -0
  31. package/src/VirtualFileSystem/path.d.ts.map +1 -0
  32. package/src/VirtualPackageManager/index.d.ts.map +1 -0
  33. package/src/VirtualShell/index.d.ts.map +1 -0
  34. package/src/VirtualShell/shell.d.ts.map +1 -0
  35. package/src/VirtualShell/shellParser.d.ts.map +1 -0
  36. package/{dist → src}/VirtualShell/shellParser.js +2 -1
  37. package/src/VirtualShell/shellParser.ts +3 -2
  38. package/src/VirtualUserManager/index.d.ts.map +1 -0
  39. package/src/bun.d.ts +1 -0
  40. package/src/commands/adduser.d.ts.map +1 -0
  41. package/src/commands/alias.d.ts.map +1 -0
  42. package/src/commands/apt.d.ts.map +1 -0
  43. package/src/commands/awk.d.ts.map +1 -0
  44. package/{dist → src}/commands/awk.js +1 -2
  45. package/src/commands/awk.ts +1 -2
  46. package/src/commands/base64.d.ts.map +1 -0
  47. package/src/commands/cat.d.ts.map +1 -0
  48. package/src/commands/cd.d.ts.map +1 -0
  49. package/{dist → src}/commands/cd.js +2 -2
  50. package/src/commands/cd.ts +2 -2
  51. package/src/commands/chmod.d.ts.map +1 -0
  52. package/src/commands/clear.d.ts.map +1 -0
  53. package/src/commands/command-helpers.d.ts.map +1 -0
  54. package/src/commands/cp.d.ts.map +1 -0
  55. package/src/commands/curl.d.ts.map +1 -0
  56. package/src/commands/cut.d.ts.map +1 -0
  57. package/src/commands/date.d.ts.map +1 -0
  58. package/src/commands/declare.d.ts.map +1 -0
  59. package/src/commands/deluser.d.ts.map +1 -0
  60. package/src/commands/df.d.ts.map +1 -0
  61. package/src/commands/diff.d.ts.map +1 -0
  62. package/src/commands/dpkg.d.ts.map +1 -0
  63. package/src/commands/du.d.ts.map +1 -0
  64. package/src/commands/echo.d.ts.map +1 -0
  65. package/src/commands/env.d.ts.map +1 -0
  66. package/src/commands/exit.d.ts.map +1 -0
  67. package/src/commands/export.d.ts.map +1 -0
  68. package/src/commands/find.d.ts.map +1 -0
  69. package/src/commands/free.d.ts.map +1 -0
  70. package/src/commands/grep.d.ts.map +1 -0
  71. package/src/commands/groups.d.ts.map +1 -0
  72. package/src/commands/gzip.d.ts.map +1 -0
  73. package/src/commands/head.d.ts.map +1 -0
  74. package/src/commands/help.d.ts.map +1 -0
  75. package/src/commands/helpers.d.ts.map +1 -0
  76. package/{dist → src}/commands/helpers.js +3 -0
  77. package/src/commands/helpers.ts +3 -0
  78. package/src/commands/history.d.ts.map +1 -0
  79. package/src/commands/hostname.d.ts.map +1 -0
  80. package/src/commands/htop.d.ts.map +1 -0
  81. package/src/commands/id.d.ts.map +1 -0
  82. package/src/commands/index.d.ts.map +1 -0
  83. package/src/commands/kill.d.ts.map +1 -0
  84. package/src/commands/ln.d.ts.map +1 -0
  85. package/src/commands/ls.d.ts.map +1 -0
  86. package/src/commands/ls.js +200 -0
  87. package/src/commands/ls.ts +210 -41
  88. package/src/commands/lsb-release.d.ts.map +1 -0
  89. package/src/commands/man.d.ts.map +1 -0
  90. package/src/commands/mkdir.d.ts.map +1 -0
  91. package/src/commands/mv.d.ts.map +1 -0
  92. package/src/commands/nano.d.ts.map +1 -0
  93. package/src/commands/neofetch.d.ts.map +1 -0
  94. package/src/commands/node.d.ts.map +1 -0
  95. package/src/commands/npm.d.ts.map +1 -0
  96. package/src/commands/passwd.d.ts.map +1 -0
  97. package/src/commands/ping.d.ts.map +1 -0
  98. package/src/commands/printf.d.ts.map +1 -0
  99. package/src/commands/ps.d.ts.map +1 -0
  100. package/src/commands/pwd.d.ts.map +1 -0
  101. package/src/commands/python.d.ts.map +1 -0
  102. package/src/commands/read.d.ts.map +1 -0
  103. package/src/commands/registry.d.ts.map +1 -0
  104. package/src/commands/rm.d.ts.map +1 -0
  105. package/src/commands/runtime.d.ts.map +1 -0
  106. package/{dist → src}/commands/runtime.js +36 -0
  107. package/src/commands/runtime.ts +56 -3
  108. package/src/commands/sed.d.ts.map +1 -0
  109. package/src/commands/seq.d.ts.map +1 -0
  110. package/src/commands/set.d.ts.map +1 -0
  111. package/src/commands/sh.d.ts.map +1 -0
  112. package/{dist → src}/commands/sh.js +8 -4
  113. package/src/commands/sh.ts +7 -4
  114. package/src/commands/shift.d.ts.map +1 -0
  115. package/src/commands/sleep.d.ts.map +1 -0
  116. package/src/commands/sort.d.ts.map +1 -0
  117. package/src/commands/source.d.ts.map +1 -0
  118. package/src/commands/stat.d.ts.map +1 -0
  119. package/src/commands/su.d.ts.map +1 -0
  120. package/src/commands/sudo.d.ts.map +1 -0
  121. package/src/commands/tail.d.ts.map +1 -0
  122. package/src/commands/tar.d.ts.map +1 -0
  123. package/src/commands/tee.d.ts.map +1 -0
  124. package/src/commands/test.d.ts.map +1 -0
  125. package/src/commands/test.ts +4 -2
  126. package/src/commands/touch.d.ts.map +1 -0
  127. package/src/commands/tr.d.ts.map +1 -0
  128. package/src/commands/tree.d.ts.map +1 -0
  129. package/src/commands/true.d.ts.map +1 -0
  130. package/src/commands/type.d.ts.map +1 -0
  131. package/src/commands/uname.d.ts.map +1 -0
  132. package/src/commands/uniq.d.ts.map +1 -0
  133. package/src/commands/unset.d.ts.map +1 -0
  134. package/src/commands/uptime.d.ts.map +1 -0
  135. package/src/commands/wc.d.ts.map +1 -0
  136. package/{dist → src}/commands/wc.js +1 -1
  137. package/src/commands/wc.ts +1 -1
  138. package/src/commands/wget.d.ts.map +1 -0
  139. package/src/commands/which.d.ts.map +1 -0
  140. package/src/commands/who.d.ts.map +1 -0
  141. package/src/commands/whoami.d.ts.map +1 -0
  142. package/src/commands/xargs.d.ts.map +1 -0
  143. package/src/index.d.ts.map +1 -0
  144. package/src/modules/linuxRootfs.d.ts +59 -0
  145. package/src/modules/linuxRootfs.d.ts.map +1 -0
  146. package/src/modules/linuxRootfs.js +619 -0
  147. package/src/modules/linuxRootfs.ts +420 -231
  148. package/src/modules/neofetch.d.ts.map +1 -0
  149. package/src/modules/shellInteractive.d.ts.map +1 -0
  150. package/src/modules/shellRuntime.d.ts.map +1 -0
  151. package/{dist → src}/self-standalone.d.ts.map +1 -1
  152. package/src/standalone-wo-sftp.d.ts.map +1 -0
  153. package/{dist → src}/standalone.d.ts.map +1 -1
  154. package/{dist → src}/types/commands.d.ts +1 -1
  155. package/src/types/commands.d.ts.map +1 -0
  156. package/src/types/commands.ts +1 -1
  157. package/src/types/pipeline.d.ts.map +1 -0
  158. package/src/types/streams.d.ts.map +1 -0
  159. package/src/types/vfs.d.ts.map +1 -0
  160. package/{dist → src}/utils/expand.d.ts +2 -2
  161. package/src/utils/expand.d.ts.map +1 -0
  162. package/src/utils/expand.js +476 -0
  163. package/src/utils/expand.ts +256 -76
  164. package/src/utils/perfLogger.d.ts.map +1 -0
  165. package/src/utils/tokenize.d.ts.map +1 -0
  166. package/src/utils/vfsDiff.d.ts.map +1 -0
  167. package/src/web-api.d.ts.map +1 -0
  168. package/src/web-full.d.ts.map +1 -0
  169. package/src/web.d.ts.map +1 -0
  170. package/tests/command-helpers.test.d.ts +2 -0
  171. package/tests/command-helpers.test.d.ts.map +1 -0
  172. package/tests/command-helpers.test.js +92 -0
  173. package/tests/command-helpers.test.ts +80 -0
  174. package/tests/commands-admin-net.test.d.ts +2 -0
  175. package/tests/commands-admin-net.test.d.ts.map +1 -0
  176. package/tests/commands-admin-net.test.js +353 -0
  177. package/tests/commands-admin-net.test.ts +441 -0
  178. package/tests/commands-advanced.test.d.ts +2 -0
  179. package/tests/commands-advanced.test.d.ts.map +1 -0
  180. package/tests/commands-advanced.test.js +378 -0
  181. package/tests/commands-advanced.test.ts +456 -0
  182. package/tests/commands-core.test.d.ts +2 -0
  183. package/tests/commands-core.test.d.ts.map +1 -0
  184. package/tests/commands-core.test.js +477 -0
  185. package/tests/commands-core.test.ts +562 -0
  186. package/tests/commands-missing.test.d.ts +2 -0
  187. package/tests/commands-missing.test.d.ts.map +1 -0
  188. package/tests/commands-missing.test.js +470 -0
  189. package/tests/commands-missing.test.ts +570 -0
  190. package/tests/commands-specific-units.test.d.ts +2 -0
  191. package/tests/commands-specific-units.test.d.ts.map +1 -0
  192. package/tests/commands-specific-units.test.js +264 -0
  193. package/tests/commands-specific-units.test.ts +327 -0
  194. package/tests/commands-text-sys.test.d.ts +2 -0
  195. package/tests/commands-text-sys.test.d.ts.map +1 -0
  196. package/tests/commands-text-sys.test.js +366 -0
  197. package/tests/commands-text-sys.test.ts +445 -0
  198. package/tests/expand.test.d.ts +2 -0
  199. package/tests/expand.test.d.ts.map +1 -0
  200. package/tests/expand.test.js +138 -0
  201. package/tests/expand.test.ts +170 -0
  202. package/tests/helpers.test.d.ts +2 -0
  203. package/tests/helpers.test.d.ts.map +1 -0
  204. package/tests/helpers.test.js +52 -0
  205. package/tests/helpers.test.ts +75 -0
  206. package/tests/new-features.test.d.ts +2 -0
  207. package/tests/new-features.test.d.ts.map +1 -0
  208. package/tests/new-features.test.js +850 -0
  209. package/tests/parser-executor.test.d.ts +2 -0
  210. package/tests/parser-executor.test.d.ts.map +1 -0
  211. package/tests/parser-executor.test.js +25 -0
  212. package/tests/sftp.test.d.ts +2 -0
  213. package/tests/sftp.test.d.ts.map +1 -0
  214. package/tests/sftp.test.js +246 -0
  215. package/tests/ssh-exec.test.d.ts +2 -0
  216. package/tests/ssh-exec.test.d.ts.map +1 -0
  217. package/tests/ssh-exec.test.js +39 -0
  218. package/tests/test-helper.d.ts +56 -0
  219. package/tests/test-helper.d.ts.map +1 -0
  220. package/tests/test-helper.js +71 -0
  221. package/tests/test-helper.ts +79 -0
  222. package/tests/users.test.d.ts +2 -0
  223. package/tests/users.test.d.ts.map +1 -0
  224. package/tests/users.test.js +71 -0
  225. package/tests/web.test.d.ts +2 -0
  226. package/tests/web.test.d.ts.map +1 -0
  227. package/tests/web.test.js +149 -0
  228. package/tsconfig.json +2 -4
  229. package/dist/Honeypot/index.d.ts.map +0 -1
  230. package/dist/SSHClient/index.d.ts.map +0 -1
  231. package/dist/SSHMimic/exec.d.ts.map +0 -1
  232. package/dist/SSHMimic/executor.d.ts.map +0 -1
  233. package/dist/SSHMimic/hostKey.d.ts.map +0 -1
  234. package/dist/SSHMimic/index.d.ts.map +0 -1
  235. package/dist/SSHMimic/loginBanner.d.ts.map +0 -1
  236. package/dist/SSHMimic/loginFormat.d.ts.map +0 -1
  237. package/dist/SSHMimic/prompt.d.ts.map +0 -1
  238. package/dist/SSHMimic/sftp.d.ts.map +0 -1
  239. package/dist/VirtualFileSystem/binaryPack.d.ts.map +0 -1
  240. package/dist/VirtualFileSystem/index.d.ts.map +0 -1
  241. package/dist/VirtualFileSystem/internalTypes.d.ts.map +0 -1
  242. package/dist/VirtualFileSystem/path.d.ts.map +0 -1
  243. package/dist/VirtualPackageManager/index.d.ts.map +0 -1
  244. package/dist/VirtualShell/index.d.ts.map +0 -1
  245. package/dist/VirtualShell/shell.d.ts.map +0 -1
  246. package/dist/VirtualShell/shellParser.d.ts.map +0 -1
  247. package/dist/VirtualUserManager/index.d.ts.map +0 -1
  248. package/dist/commands/adduser.d.ts.map +0 -1
  249. package/dist/commands/alias.d.ts.map +0 -1
  250. package/dist/commands/apt.d.ts.map +0 -1
  251. package/dist/commands/awk.d.ts.map +0 -1
  252. package/dist/commands/base64.d.ts.map +0 -1
  253. package/dist/commands/cat.d.ts.map +0 -1
  254. package/dist/commands/cd.d.ts.map +0 -1
  255. package/dist/commands/chmod.d.ts.map +0 -1
  256. package/dist/commands/clear.d.ts.map +0 -1
  257. package/dist/commands/command-helpers.d.ts.map +0 -1
  258. package/dist/commands/cp.d.ts.map +0 -1
  259. package/dist/commands/curl.d.ts.map +0 -1
  260. package/dist/commands/cut.d.ts.map +0 -1
  261. package/dist/commands/date.d.ts.map +0 -1
  262. package/dist/commands/declare.d.ts.map +0 -1
  263. package/dist/commands/deluser.d.ts.map +0 -1
  264. package/dist/commands/df.d.ts.map +0 -1
  265. package/dist/commands/diff.d.ts.map +0 -1
  266. package/dist/commands/dpkg.d.ts.map +0 -1
  267. package/dist/commands/du.d.ts.map +0 -1
  268. package/dist/commands/echo.d.ts.map +0 -1
  269. package/dist/commands/env.d.ts.map +0 -1
  270. package/dist/commands/exit.d.ts.map +0 -1
  271. package/dist/commands/export.d.ts.map +0 -1
  272. package/dist/commands/find.d.ts.map +0 -1
  273. package/dist/commands/free.d.ts.map +0 -1
  274. package/dist/commands/grep.d.ts.map +0 -1
  275. package/dist/commands/groups.d.ts.map +0 -1
  276. package/dist/commands/gzip.d.ts.map +0 -1
  277. package/dist/commands/head.d.ts.map +0 -1
  278. package/dist/commands/help.d.ts.map +0 -1
  279. package/dist/commands/helpers.d.ts.map +0 -1
  280. package/dist/commands/history.d.ts.map +0 -1
  281. package/dist/commands/hostname.d.ts.map +0 -1
  282. package/dist/commands/htop.d.ts.map +0 -1
  283. package/dist/commands/id.d.ts.map +0 -1
  284. package/dist/commands/index.d.ts.map +0 -1
  285. package/dist/commands/kill.d.ts.map +0 -1
  286. package/dist/commands/ln.d.ts.map +0 -1
  287. package/dist/commands/ls.d.ts.map +0 -1
  288. package/dist/commands/ls.js +0 -67
  289. package/dist/commands/lsb-release.d.ts.map +0 -1
  290. package/dist/commands/man.d.ts.map +0 -1
  291. package/dist/commands/mkdir.d.ts.map +0 -1
  292. package/dist/commands/mv.d.ts.map +0 -1
  293. package/dist/commands/nano.d.ts.map +0 -1
  294. package/dist/commands/neofetch.d.ts.map +0 -1
  295. package/dist/commands/node.d.ts.map +0 -1
  296. package/dist/commands/npm.d.ts.map +0 -1
  297. package/dist/commands/passwd.d.ts.map +0 -1
  298. package/dist/commands/ping.d.ts.map +0 -1
  299. package/dist/commands/printf.d.ts.map +0 -1
  300. package/dist/commands/ps.d.ts.map +0 -1
  301. package/dist/commands/pwd.d.ts.map +0 -1
  302. package/dist/commands/python.d.ts.map +0 -1
  303. package/dist/commands/read.d.ts.map +0 -1
  304. package/dist/commands/registry.d.ts.map +0 -1
  305. package/dist/commands/rm.d.ts.map +0 -1
  306. package/dist/commands/runtime.d.ts.map +0 -1
  307. package/dist/commands/sed.d.ts.map +0 -1
  308. package/dist/commands/seq.d.ts.map +0 -1
  309. package/dist/commands/set.d.ts.map +0 -1
  310. package/dist/commands/sh.d.ts.map +0 -1
  311. package/dist/commands/shift.d.ts.map +0 -1
  312. package/dist/commands/sleep.d.ts.map +0 -1
  313. package/dist/commands/sort.d.ts.map +0 -1
  314. package/dist/commands/source.d.ts.map +0 -1
  315. package/dist/commands/stat.d.ts.map +0 -1
  316. package/dist/commands/su.d.ts.map +0 -1
  317. package/dist/commands/sudo.d.ts.map +0 -1
  318. package/dist/commands/tail.d.ts.map +0 -1
  319. package/dist/commands/tar.d.ts.map +0 -1
  320. package/dist/commands/tee.d.ts.map +0 -1
  321. package/dist/commands/test.d.ts.map +0 -1
  322. package/dist/commands/touch.d.ts.map +0 -1
  323. package/dist/commands/tr.d.ts.map +0 -1
  324. package/dist/commands/tree.d.ts.map +0 -1
  325. package/dist/commands/true.d.ts.map +0 -1
  326. package/dist/commands/type.d.ts.map +0 -1
  327. package/dist/commands/uname.d.ts.map +0 -1
  328. package/dist/commands/uniq.d.ts.map +0 -1
  329. package/dist/commands/unset.d.ts.map +0 -1
  330. package/dist/commands/uptime.d.ts.map +0 -1
  331. package/dist/commands/wc.d.ts.map +0 -1
  332. package/dist/commands/wget.d.ts.map +0 -1
  333. package/dist/commands/which.d.ts.map +0 -1
  334. package/dist/commands/who.d.ts.map +0 -1
  335. package/dist/commands/whoami.d.ts.map +0 -1
  336. package/dist/commands/xargs.d.ts.map +0 -1
  337. package/dist/index.d.ts.map +0 -1
  338. package/dist/modules/linuxRootfs.d.ts +0 -41
  339. package/dist/modules/linuxRootfs.d.ts.map +0 -1
  340. package/dist/modules/linuxRootfs.js +0 -440
  341. package/dist/modules/neofetch.d.ts.map +0 -1
  342. package/dist/modules/shellInteractive.d.ts.map +0 -1
  343. package/dist/modules/shellRuntime.d.ts.map +0 -1
  344. package/dist/standalone-wo-sftp.d.ts.map +0 -1
  345. package/dist/types/commands.d.ts.map +0 -1
  346. package/dist/types/pipeline.d.ts.map +0 -1
  347. package/dist/types/streams.d.ts.map +0 -1
  348. package/dist/types/vfs.d.ts.map +0 -1
  349. package/dist/utils/expand.d.ts.map +0 -1
  350. package/dist/utils/expand.js +0 -265
  351. package/dist/utils/perfLogger.d.ts.map +0 -1
  352. package/dist/utils/tokenize.d.ts.map +0 -1
  353. package/dist/utils/vfsDiff.d.ts.map +0 -1
  354. package/dist/web-api.d.ts.map +0 -1
  355. package/dist/web-full.d.ts.map +0 -1
  356. package/dist/web.d.ts.map +0 -1
  357. package/tests/bun-test-shim.ts +0 -9
  358. /package/{dist → src}/Honeypot/index.d.ts +0 -0
  359. /package/{dist → src}/Honeypot/index.js +0 -0
  360. /package/{dist → src}/SSHClient/index.d.ts +0 -0
  361. /package/{dist → src}/SSHClient/index.js +0 -0
  362. /package/{dist → src}/SSHMimic/exec.d.ts +0 -0
  363. /package/{dist → src}/SSHMimic/exec.js +0 -0
  364. /package/{dist → src}/SSHMimic/executor.d.ts +0 -0
  365. /package/{dist → src}/SSHMimic/executor.js +0 -0
  366. /package/{dist → src}/SSHMimic/hostKey.d.ts +0 -0
  367. /package/{dist → src}/SSHMimic/hostKey.js +0 -0
  368. /package/{dist → src}/SSHMimic/index.d.ts +0 -0
  369. /package/{dist → src}/SSHMimic/index.js +0 -0
  370. /package/{dist → src}/SSHMimic/loginBanner.d.ts +0 -0
  371. /package/{dist → src}/SSHMimic/loginBanner.js +0 -0
  372. /package/{dist → src}/SSHMimic/loginFormat.d.ts +0 -0
  373. /package/{dist → src}/SSHMimic/loginFormat.js +0 -0
  374. /package/{dist → src}/SSHMimic/prompt.d.ts +0 -0
  375. /package/{dist → src}/SSHMimic/prompt.js +0 -0
  376. /package/{dist → src}/SSHMimic/sftp.d.ts +0 -0
  377. /package/{dist → src}/SSHMimic/sftp.js +0 -0
  378. /package/{dist → src}/VirtualFileSystem/binaryPack.d.ts +0 -0
  379. /package/{dist → src}/VirtualFileSystem/binaryPack.js +0 -0
  380. /package/{dist → src}/VirtualFileSystem/index.d.ts +0 -0
  381. /package/{dist → src}/VirtualFileSystem/index.js +0 -0
  382. /package/{dist → src}/VirtualFileSystem/internalTypes.d.ts +0 -0
  383. /package/{dist → src}/VirtualFileSystem/internalTypes.js +0 -0
  384. /package/{dist → src}/VirtualFileSystem/path.d.ts +0 -0
  385. /package/{dist → src}/VirtualFileSystem/path.js +0 -0
  386. /package/{dist → src}/VirtualPackageManager/index.d.ts +0 -0
  387. /package/{dist → src}/VirtualPackageManager/index.js +0 -0
  388. /package/{dist → src}/VirtualShell/index.d.ts +0 -0
  389. /package/{dist → src}/VirtualShell/index.js +0 -0
  390. /package/{dist → src}/VirtualShell/shell.d.ts +0 -0
  391. /package/{dist → src}/VirtualShell/shell.js +0 -0
  392. /package/{dist → src}/VirtualShell/shellParser.d.ts +0 -0
  393. /package/{dist → src}/VirtualUserManager/index.d.ts +0 -0
  394. /package/{dist → src}/VirtualUserManager/index.js +0 -0
  395. /package/{dist → src}/commands/adduser.d.ts +0 -0
  396. /package/{dist → src}/commands/adduser.js +0 -0
  397. /package/{dist → src}/commands/alias.d.ts +0 -0
  398. /package/{dist → src}/commands/alias.js +0 -0
  399. /package/{dist → src}/commands/apt.d.ts +0 -0
  400. /package/{dist → src}/commands/apt.js +0 -0
  401. /package/{dist → src}/commands/awk.d.ts +0 -0
  402. /package/{dist → src}/commands/base64.d.ts +0 -0
  403. /package/{dist → src}/commands/base64.js +0 -0
  404. /package/{dist → src}/commands/cat.d.ts +0 -0
  405. /package/{dist → src}/commands/cat.js +0 -0
  406. /package/{dist → src}/commands/cd.d.ts +0 -0
  407. /package/{dist → src}/commands/chmod.d.ts +0 -0
  408. /package/{dist → src}/commands/chmod.js +0 -0
  409. /package/{dist → src}/commands/clear.d.ts +0 -0
  410. /package/{dist → src}/commands/clear.js +0 -0
  411. /package/{dist → src}/commands/command-helpers.d.ts +0 -0
  412. /package/{dist → src}/commands/command-helpers.js +0 -0
  413. /package/{dist → src}/commands/cp.d.ts +0 -0
  414. /package/{dist → src}/commands/cp.js +0 -0
  415. /package/{dist → src}/commands/curl.d.ts +0 -0
  416. /package/{dist → src}/commands/curl.js +0 -0
  417. /package/{dist → src}/commands/cut.d.ts +0 -0
  418. /package/{dist → src}/commands/cut.js +0 -0
  419. /package/{dist → src}/commands/date.d.ts +0 -0
  420. /package/{dist → src}/commands/date.js +0 -0
  421. /package/{dist → src}/commands/declare.d.ts +0 -0
  422. /package/{dist → src}/commands/declare.js +0 -0
  423. /package/{dist → src}/commands/deluser.d.ts +0 -0
  424. /package/{dist → src}/commands/deluser.js +0 -0
  425. /package/{dist → src}/commands/df.d.ts +0 -0
  426. /package/{dist → src}/commands/df.js +0 -0
  427. /package/{dist → src}/commands/diff.d.ts +0 -0
  428. /package/{dist → src}/commands/diff.js +0 -0
  429. /package/{dist → src}/commands/dpkg.d.ts +0 -0
  430. /package/{dist → src}/commands/dpkg.js +0 -0
  431. /package/{dist → src}/commands/du.d.ts +0 -0
  432. /package/{dist → src}/commands/du.js +0 -0
  433. /package/{dist → src}/commands/echo.d.ts +0 -0
  434. /package/{dist → src}/commands/echo.js +0 -0
  435. /package/{dist → src}/commands/env.d.ts +0 -0
  436. /package/{dist → src}/commands/env.js +0 -0
  437. /package/{dist → src}/commands/exit.d.ts +0 -0
  438. /package/{dist → src}/commands/exit.js +0 -0
  439. /package/{dist → src}/commands/export.d.ts +0 -0
  440. /package/{dist → src}/commands/export.js +0 -0
  441. /package/{dist → src}/commands/find.d.ts +0 -0
  442. /package/{dist → src}/commands/find.js +0 -0
  443. /package/{dist → src}/commands/free.d.ts +0 -0
  444. /package/{dist → src}/commands/free.js +0 -0
  445. /package/{dist → src}/commands/grep.d.ts +0 -0
  446. /package/{dist → src}/commands/grep.js +0 -0
  447. /package/{dist → src}/commands/groups.d.ts +0 -0
  448. /package/{dist → src}/commands/groups.js +0 -0
  449. /package/{dist → src}/commands/gzip.d.ts +0 -0
  450. /package/{dist → src}/commands/gzip.js +0 -0
  451. /package/{dist → src}/commands/head.d.ts +0 -0
  452. /package/{dist → src}/commands/head.js +0 -0
  453. /package/{dist → src}/commands/help.d.ts +0 -0
  454. /package/{dist → src}/commands/help.js +0 -0
  455. /package/{dist → src}/commands/helpers.d.ts +0 -0
  456. /package/{dist → src}/commands/history.d.ts +0 -0
  457. /package/{dist → src}/commands/history.js +0 -0
  458. /package/{dist → src}/commands/hostname.d.ts +0 -0
  459. /package/{dist → src}/commands/hostname.js +0 -0
  460. /package/{dist → src}/commands/htop.d.ts +0 -0
  461. /package/{dist → src}/commands/htop.js +0 -0
  462. /package/{dist → src}/commands/id.d.ts +0 -0
  463. /package/{dist → src}/commands/id.js +0 -0
  464. /package/{dist → src}/commands/index.d.ts +0 -0
  465. /package/{dist → src}/commands/index.js +0 -0
  466. /package/{dist → src}/commands/kill.d.ts +0 -0
  467. /package/{dist → src}/commands/kill.js +0 -0
  468. /package/{dist → src}/commands/ln.d.ts +0 -0
  469. /package/{dist → src}/commands/ln.js +0 -0
  470. /package/{dist → src}/commands/ls.d.ts +0 -0
  471. /package/{dist → src}/commands/lsb-release.d.ts +0 -0
  472. /package/{dist → src}/commands/lsb-release.js +0 -0
  473. /package/{dist → src}/commands/man.d.ts +0 -0
  474. /package/{dist → src}/commands/man.js +0 -0
  475. /package/{dist → src}/commands/mkdir.d.ts +0 -0
  476. /package/{dist → src}/commands/mkdir.js +0 -0
  477. /package/{dist → src}/commands/mv.d.ts +0 -0
  478. /package/{dist → src}/commands/mv.js +0 -0
  479. /package/{dist → src}/commands/nano.d.ts +0 -0
  480. /package/{dist → src}/commands/nano.js +0 -0
  481. /package/{dist → src}/commands/neofetch.d.ts +0 -0
  482. /package/{dist → src}/commands/neofetch.js +0 -0
  483. /package/{dist → src}/commands/node.d.ts +0 -0
  484. /package/{dist → src}/commands/node.js +0 -0
  485. /package/{dist → src}/commands/npm.d.ts +0 -0
  486. /package/{dist → src}/commands/npm.js +0 -0
  487. /package/{dist → src}/commands/passwd.d.ts +0 -0
  488. /package/{dist → src}/commands/passwd.js +0 -0
  489. /package/{dist → src}/commands/ping.d.ts +0 -0
  490. /package/{dist → src}/commands/ping.js +0 -0
  491. /package/{dist → src}/commands/printf.d.ts +0 -0
  492. /package/{dist → src}/commands/printf.js +0 -0
  493. /package/{dist → src}/commands/ps.d.ts +0 -0
  494. /package/{dist → src}/commands/ps.js +0 -0
  495. /package/{dist → src}/commands/pwd.d.ts +0 -0
  496. /package/{dist → src}/commands/pwd.js +0 -0
  497. /package/{dist → src}/commands/python.d.ts +0 -0
  498. /package/{dist → src}/commands/python.js +0 -0
  499. /package/{dist → src}/commands/read.d.ts +0 -0
  500. /package/{dist → src}/commands/read.js +0 -0
  501. /package/{dist → src}/commands/registry.d.ts +0 -0
  502. /package/{dist → src}/commands/registry.js +0 -0
  503. /package/{dist → src}/commands/rm.d.ts +0 -0
  504. /package/{dist → src}/commands/rm.js +0 -0
  505. /package/{dist → src}/commands/runtime.d.ts +0 -0
  506. /package/{dist → src}/commands/sed.d.ts +0 -0
  507. /package/{dist → src}/commands/sed.js +0 -0
  508. /package/{dist → src}/commands/seq.d.ts +0 -0
  509. /package/{dist → src}/commands/seq.js +0 -0
  510. /package/{dist → src}/commands/set.d.ts +0 -0
  511. /package/{dist → src}/commands/set.js +0 -0
  512. /package/{dist → src}/commands/sh.d.ts +0 -0
  513. /package/{dist → src}/commands/shift.d.ts +0 -0
  514. /package/{dist → src}/commands/shift.js +0 -0
  515. /package/{dist → src}/commands/sleep.d.ts +0 -0
  516. /package/{dist → src}/commands/sleep.js +0 -0
  517. /package/{dist → src}/commands/sort.d.ts +0 -0
  518. /package/{dist → src}/commands/sort.js +0 -0
  519. /package/{dist → src}/commands/source.d.ts +0 -0
  520. /package/{dist → src}/commands/source.js +0 -0
  521. /package/{dist → src}/commands/stat.d.ts +0 -0
  522. /package/{dist → src}/commands/stat.js +0 -0
  523. /package/{dist → src}/commands/su.d.ts +0 -0
  524. /package/{dist → src}/commands/su.js +0 -0
  525. /package/{dist → src}/commands/sudo.d.ts +0 -0
  526. /package/{dist → src}/commands/sudo.js +0 -0
  527. /package/{dist → src}/commands/tail.d.ts +0 -0
  528. /package/{dist → src}/commands/tail.js +0 -0
  529. /package/{dist → src}/commands/tar.d.ts +0 -0
  530. /package/{dist → src}/commands/tar.js +0 -0
  531. /package/{dist → src}/commands/tee.d.ts +0 -0
  532. /package/{dist → src}/commands/tee.js +0 -0
  533. /package/{dist → src}/commands/test.d.ts +0 -0
  534. /package/{dist → src}/commands/test.js +0 -0
  535. /package/{dist → src}/commands/touch.d.ts +0 -0
  536. /package/{dist → src}/commands/touch.js +0 -0
  537. /package/{dist → src}/commands/tr.d.ts +0 -0
  538. /package/{dist → src}/commands/tr.js +0 -0
  539. /package/{dist → src}/commands/tree.d.ts +0 -0
  540. /package/{dist → src}/commands/tree.js +0 -0
  541. /package/{dist → src}/commands/true.d.ts +0 -0
  542. /package/{dist → src}/commands/true.js +0 -0
  543. /package/{dist → src}/commands/type.d.ts +0 -0
  544. /package/{dist → src}/commands/type.js +0 -0
  545. /package/{dist → src}/commands/uname.d.ts +0 -0
  546. /package/{dist → src}/commands/uname.js +0 -0
  547. /package/{dist → src}/commands/uniq.d.ts +0 -0
  548. /package/{dist → src}/commands/uniq.js +0 -0
  549. /package/{dist → src}/commands/unset.d.ts +0 -0
  550. /package/{dist → src}/commands/unset.js +0 -0
  551. /package/{dist → src}/commands/uptime.d.ts +0 -0
  552. /package/{dist → src}/commands/uptime.js +0 -0
  553. /package/{dist → src}/commands/wc.d.ts +0 -0
  554. /package/{dist → src}/commands/wget.d.ts +0 -0
  555. /package/{dist → src}/commands/wget.js +0 -0
  556. /package/{dist → src}/commands/which.d.ts +0 -0
  557. /package/{dist → src}/commands/which.js +0 -0
  558. /package/{dist → src}/commands/who.d.ts +0 -0
  559. /package/{dist → src}/commands/who.js +0 -0
  560. /package/{dist → src}/commands/whoami.d.ts +0 -0
  561. /package/{dist → src}/commands/whoami.js +0 -0
  562. /package/{dist → src}/commands/xargs.d.ts +0 -0
  563. /package/{dist → src}/commands/xargs.js +0 -0
  564. /package/{dist → src}/index.d.ts +0 -0
  565. /package/{dist → src}/index.js +0 -0
  566. /package/{dist → src}/modules/neofetch.d.ts +0 -0
  567. /package/{dist → src}/modules/neofetch.js +0 -0
  568. /package/{dist → src}/modules/shellInteractive.d.ts +0 -0
  569. /package/{dist → src}/modules/shellInteractive.js +0 -0
  570. /package/{dist → src}/modules/shellRuntime.d.ts +0 -0
  571. /package/{dist → src}/modules/shellRuntime.js +0 -0
  572. /package/{dist → src}/self-standalone.d.ts +0 -0
  573. /package/{dist → src}/self-standalone.js +0 -0
  574. /package/{dist → src}/standalone-wo-sftp.d.ts +0 -0
  575. /package/{dist → src}/standalone-wo-sftp.js +0 -0
  576. /package/{dist → src}/standalone.d.ts +0 -0
  577. /package/{dist → src}/standalone.js +0 -0
  578. /package/{dist → src}/types/commands.js +0 -0
  579. /package/{dist → src}/types/pipeline.d.ts +0 -0
  580. /package/{dist → src}/types/pipeline.js +0 -0
  581. /package/{dist → src}/types/streams.d.ts +0 -0
  582. /package/{dist → src}/types/streams.js +0 -0
  583. /package/{dist → src}/types/vfs.d.ts +0 -0
  584. /package/{dist → src}/types/vfs.js +0 -0
  585. /package/{dist → src}/utils/perfLogger.d.ts +0 -0
  586. /package/{dist → src}/utils/perfLogger.js +0 -0
  587. /package/{dist → src}/utils/tokenize.d.ts +0 -0
  588. /package/{dist → src}/utils/tokenize.js +0 -0
  589. /package/{dist → src}/utils/vfsDiff.d.ts +0 -0
  590. /package/{dist → src}/utils/vfsDiff.js +0 -0
  591. /package/{dist → src}/web-api.d.ts +0 -0
  592. /package/{dist → src}/web-api.js +0 -0
  593. /package/{dist → src}/web-full.d.ts +0 -0
  594. /package/{dist → src}/web-full.js +0 -0
  595. /package/{dist → src}/web.d.ts +0 -0
  596. /package/{dist → src}/web.js +0 -0
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{readFile as Gi,unlink as Zi,writeFile as Ji}from"node:fs/promises";import*as Ss from"node:path";import{basename as Qi}from"node:path";import{stdin as it,stdout as rt}from"node:process";import{createInterface as Yi}from"node:readline";var _e={name:"adduser",description:"Add a new user",category:"users",params:["<username>"],run:({authUser:r,shell:t,args:e})=>{if(r!=="root")return{stderr:`adduser: permission denied
2
+ var ks=Object.defineProperty;var Ms=(r,t)=>()=>(r&&(t=r(r=0)),t);var Fs=(r,t)=>{for(var e in t)ks(r,e,{get:t[e],enumerable:!0})};var we={};Fs(we,{evalArith:()=>dr,expandAsync:()=>_t,expandBraces:()=>Rt,expandSync:()=>Zt});function dr(r,t){let e=r.replace(/\b([A-Za-z_][A-Za-z0-9_]*)\b/g,(n,i)=>{let s=t[i];return s!==void 0&&s!==""?s:"0"});if(!/^[\d\s+\-*/%()^!&|<>=,. ]+$/.test(e))return NaN;try{let n=Function(`"use strict"; return (${e.replace(/\*\*/g,"**")});`)();return typeof n=="number"?Math.trunc(n):NaN}catch{return NaN}}function Rs(r,t){let e=[],n=0;for(;n<r.length;){let i=r.indexOf("'",n);if(i===-1){e.push(t(r.slice(n)));break}e.push(t(r.slice(n,i)));let s=r.indexOf("'",i+1);if(s===-1){e.push(r.slice(i));break}e.push(r.slice(i,s+1)),n=s+1}return e.join("")}function Rt(r){let t=0,e=-1;for(let n=0;n<r.length;n++){let i=r[n];if(i==="{"&&r[n-1]!=="$")t===0&&(e=n),t++;else if(i==="}"&&(t--,t===0&&e!==-1)){let s=r.slice(0,e),o=r.slice(e+1,n),a=r.slice(n+1),l=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.-?(\d+))?$/)||o.match(/^([a-z])\.\.([a-z])$/);if(l){let m=[];if(/\d/.test(l[1])){let y=parseInt(l[1],10),g=parseInt(l[2],10),f=l[3]?parseInt(l[3],10):1,$=y<=g?f:-f;for(let N=y;y<=g?N<=g:N>=g;N+=$)m.push(String(N))}else{let y=l[1].charCodeAt(0),g=l[2].charCodeAt(0),f=y<=g?1:-1;for(let $=y;y<=g?$<=g:$>=g;$+=f)m.push(String.fromCharCode($))}return m.map(y=>`${s}${y}${a}`).flatMap(Rt)}let c=[],u="",d=0;for(let m of o)m==="{"?(d++,u+=m):m==="}"?(d--,u+=m):m===","&&d===0?(c.push(u),u=""):u+=m;if(c.push(u),c.length>1)return c.map(p=>`${s}${p}${a}`).flatMap(Rt);break}}return[r]}function Zt(r,t,e=0,n){let i=n??t.HOME??"/home/user";return Rs(r,s=>{let o=s;return o=o.replace(/(^|[\s:])~(\/|$)/g,(a,l,c)=>`${l}${i}${c}`),o=o.replace(/\$\?/g,String(e)),o=o.replace(/\$\$/g,"1"),o=o.replace(/\$#/g,"0"),o=o.replace(/\$\(\(([^)]+(?:\([^)]*\)[^)]*)*)\)\)/g,(a,l)=>{let c=dr(l,t);return Number.isNaN(c)?"0":String(c)}),o=o.replace(/\$\{#([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,l)=>String((t[l]??"").length)),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):-([^}]*)\}/g,(a,l,c)=>t[l]!==void 0&&t[l]!==""?t[l]:c),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):=([^}]*)\}/g,(a,l,c)=>((t[l]===void 0||t[l]==="")&&(t[l]=c),t[l])),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):\+([^}]*)\}/g,(a,l,c)=>t[l]!==void 0&&t[l]!==""?c:""),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,l)=>t[l]??""),o=o.replace(/\$([A-Za-z_][A-Za-z0-9_]*|\d+)/g,(a,l)=>t[l]??""),o})}async function _t(r,t,e,n){if(r.includes("$(")){let i="",s=!1,o=0;for(;o<r.length;){let a=r[o];if(a==="'"&&!s){s=!0,i+=a,o++;continue}if(a==="'"&&s){s=!1,i+=a,o++;continue}if(!s&&a==="$"&&r[o+1]==="("){if(r[o+2]==="("){i+=a,o++;continue}let l=0,c=o+1;for(;c<r.length;){if(r[c]==="(")l++;else if(r[c]===")"&&(l--,l===0))break;c++}let u=r.slice(o+2,c).trim(),d=(await n(u)).replace(/\n$/,"");i+=d,o=c+1;continue}i+=a,o++}r=i}return Zt(r,t,e)}var kt=Ms(()=>{"use strict"});import{readFile as ro,unlink as no,writeFile as so}from"node:fs/promises";import*as Ps from"node:path";import{basename as io}from"node:path";import{stdin as at,stdout as nt}from"node:process";import{createInterface as oo}from"node:readline";var Te={name:"adduser",description:"Add a new user",category:"users",params:["<username>"],run:({authUser:r,shell:t,args:e})=>{if(r!=="root")return{stderr:`adduser: permission denied
3
3
  `,exitCode:1};let n=e[0];if(!n)return{stderr:`Usage: adduser <username>
4
4
  `,exitCode:1};if(t.users.listUsers().includes(n))return{stderr:`adduser: user '${n}' already exists
5
5
  `,exitCode:1};let i="",s="new";return{sudoChallenge:{username:n,targetUser:n,commandLine:null,loginShell:!1,prompt:"New password: ",mode:"passwd",onPassword:async(a,l)=>s==="new"?a.length<1?{result:{stderr:`adduser: password cannot be empty
6
6
  `,exitCode:1}}:(i=a,s="retype",{result:null,nextPrompt:"Retype new password: "}):a!==i?{result:{stderr:`adduser: passwords do not match \u2014 user not created
7
7
  `,exitCode:1}}:(await l.users.addUser(n,i),{result:{stdout:`${[`Adding user '${n}' ...`,`Adding new group '${n}' (1001) ...`,`Adding new user '${n}' (1001) with group '${n}' ...`,`Creating home directory '/home/${n}' ...`,`passwd: password set for '${n}'`,"adduser: done."].join(`
8
8
  `)}
9
- `,exitCode:0}})},exitCode:0}}};function ze(r){return Array.isArray(r)?r:[r]}function Ht(r,t){if(r===t)return{matched:!0,inlineValue:null};let e=`${t}=`;return r.startsWith(e)?{matched:!0,inlineValue:r.slice(e.length)}:t.length===2&&t.startsWith("-")&&!t.startsWith("--")&&r.startsWith(t)&&r.length>t.length?{matched:!0,inlineValue:r.slice(t.length)}:{matched:!1,inlineValue:null}}function xs(r,t={}){let e=new Set(t.flags??[]),n=new Set(t.flagsWithValue??[]),i=[],s=!1;for(let o=0;o<r.length;o+=1){let a=r[o];if(s){i.push(a);continue}if(a==="--"){s=!0;continue}let l=!1;for(let c of e){let{matched:u}=Ht(a,c);if(u){l=!0;break}}if(!l){for(let c of n){let u=Ht(a,c);if(u.matched){l=!0,u.inlineValue===null&&o+1<r.length&&(o+=1);break}}l||i.push(a)}}return i}function y(r,t){let e=ze(t);for(let n of r)for(let i of e)if(Ht(n,i).matched)return!0;return!1}function st(r,t){let e=ze(t);for(let n=0;n<r.length;n+=1){let i=r[n];for(let s of e){let o=Ht(i,s);if(!o.matched)continue;if(o.inlineValue!==null)return o.inlineValue;let a=r[n+1];return a!==void 0&&a!=="--"?a:!0}}}function St(r,t,e={}){return xs(r,e)[t]}function nt(r,t={}){let e=new Set,n=new Map,i=[],s=new Set(t.flags??[]),o=new Set(t.flagsWithValue??[]),a=!1;for(let l=0;l<r.length;l+=1){let c=r[l];if(a){i.push(c);continue}if(c==="--"){a=!0;continue}if(s.has(c)){e.add(c);continue}if(o.has(c)){let d=r[l+1];d&&!d.startsWith("-")?(n.set(c,d),l+=1):n.set(c,"");continue}let u=Array.from(o).find(d=>c.startsWith(`${d}=`));if(u){n.set(u,c.slice(u.length+1));continue}i.push(c)}return{flags:e,flagsWithValues:n,positionals:i}}var Le={name:"alias",description:"Define or display aliases",category:"shell",params:["[name[=value] ...]"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};if(r.length===0)return{stdout:Object.entries(t.vars).filter(([i])=>i.startsWith("__alias_")).map(([i,s])=>`alias ${i.slice(8)}='${s}'`).join(`
9
+ `,exitCode:0}})},exitCode:0}}};function Ue(r){return Array.isArray(r)?r:[r]}function Gt(r,t){if(r===t)return{matched:!0,inlineValue:null};let e=`${t}=`;return r.startsWith(e)?{matched:!0,inlineValue:r.slice(e.length)}:t.length===2&&t.startsWith("-")&&!t.startsWith("--")&&r.startsWith(t)&&r.length>t.length?{matched:!0,inlineValue:r.slice(t.length)}:{matched:!1,inlineValue:null}}function As(r,t={}){let e=new Set(t.flags??[]),n=new Set(t.flagsWithValue??[]),i=[],s=!1;for(let o=0;o<r.length;o+=1){let a=r[o];if(s){i.push(a);continue}if(a==="--"){s=!0;continue}let l=!1;for(let c of e){let{matched:u}=Gt(a,c);if(u){l=!0;break}}if(!l){for(let c of n){let u=Gt(a,c);if(u.matched){l=!0,u.inlineValue===null&&o+1<r.length&&(o+=1);break}}l||i.push(a)}}return i}function w(r,t){let e=Ue(t);for(let n of r)for(let i of e)if(Gt(n,i).matched)return!0;return!1}function it(r,t){let e=Ue(t);for(let n=0;n<r.length;n+=1){let i=r[n];for(let s of e){let o=Gt(i,s);if(!o.matched)continue;if(o.inlineValue!==null)return o.inlineValue;let a=r[n+1];return a!==void 0&&a!=="--"?a:!0}}}function xt(r,t,e={}){return As(r,e)[t]}function st(r,t={}){let e=new Set,n=new Map,i=[],s=new Set(t.flags??[]),o=new Set(t.flagsWithValue??[]),a=!1;for(let l=0;l<r.length;l+=1){let c=r[l];if(a){i.push(c);continue}if(c==="--"){a=!0;continue}if(s.has(c)){e.add(c);continue}if(o.has(c)){let d=r[l+1];d&&!d.startsWith("-")?(n.set(c,d),l+=1):n.set(c,"");continue}let u=Array.from(o).find(d=>c.startsWith(`${d}=`));if(u){n.set(u,c.slice(u.length+1));continue}i.push(c)}return{flags:e,flagsWithValues:n,positionals:i}}var Be={name:"alias",description:"Define or display aliases",category:"shell",params:["[name[=value] ...]"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};if(r.length===0)return{stdout:Object.entries(t.vars).filter(([i])=>i.startsWith("__alias_")).map(([i,s])=>`alias ${i.slice(8)}='${s}'`).join(`
10
10
  `)||"",exitCode:0};let e=[];for(let n of r){let i=n.indexOf("=");if(i===-1){let s=t.vars[`__alias_${n}`];if(s)e.push(`alias ${n}='${s}'`);else return{stderr:`alias: ${n}: not found`,exitCode:1}}else{let s=n.slice(0,i),o=n.slice(i+1).replace(/^['"]|['"]$/g,"");t.vars[`__alias_${s}`]=o}}return{stdout:e.join(`
11
- `)||void 0,exitCode:0}}},Ue={name:"unalias",description:"Remove alias definitions",category:"shell",params:["<name...> | -a"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};if(y(r,["-a"])){for(let e of Object.keys(t.vars))e.startsWith("__alias_")&&delete t.vars[e];return{exitCode:0}}for(let e of r)delete t.vars[`__alias_${e}`];return{exitCode:0}}};import*as ut from"node:path";var bs=["/.virtual-env-js/.auth","/etc/htpasswd"];function x(r,t){return!t||t.trim()===""?r:t.startsWith("/")?ut.posix.normalize(t):ut.posix.normalize(ut.posix.join(r,t))}function Cs(r){let t=r.startsWith("/")?ut.posix.normalize(r):ut.posix.normalize(`/${r}`);return bs.some(e=>t===e||t.startsWith(`${e}/`))}function _(r,t,e){if(r!=="root"&&Cs(t))throw new Error(`${e}: permission denied: ${t}`)}function Te(r){let e=(r.split("?")[0]?.split("#")[0]??r).split("/").filter(Boolean).pop();return e&&e.length>0?e:"index.html"}function vs(r,t){let e=Array.from({length:r.length+1},()=>Array(t.length+1).fill(0));for(let n=0;n<=r.length;n+=1)e[n][0]=n;for(let n=0;n<=t.length;n+=1)e[0][n]=n;for(let n=1;n<=r.length;n+=1)for(let i=1;i<=t.length;i+=1){let s=r[n-1]===t[i-1]?0:1;e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+s)}return e[r.length][t.length]}function Be(r,t,e){let n=x(t,e);if(r.exists(n))return n;let i=ut.posix.dirname(n),s=ut.posix.basename(n),o=r.list(i),a=o.filter(c=>c.toLowerCase()===s.toLowerCase());if(a.length===1)return ut.posix.join(i,a[0]);let l=o.filter(c=>vs(c.toLowerCase(),s.toLowerCase())<=1);return l.length===1?ut.posix.join(i,l[0]):n}function We(r,t,e){return t.map(n=>{let i=x(r,n);return e(i).type==="directory"?`${n}/`:n}).join(" ")}function Pt(r){return r.packageManager}var Oe={name:"apt",aliases:["apt-get"],description:"Package manager",category:"package",params:["<install|remove|update|upgrade|search|show|list> [pkg...]"],run:({args:r,shell:t,authUser:e})=>{let n=Pt(t);if(!n)return{stderr:"apt: package manager not initialised",exitCode:1};let i=r[0]?.toLowerCase(),s=r.slice(1),o=y(s,["-q","--quiet","-qq"]),a=y(s,["--purge"]),l=s.filter(u=>!u.startsWith("-"));if(["install","remove","purge","upgrade","update"].includes(i??"")&&e!=="root")return{stderr:`E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
11
+ `)||void 0,exitCode:0}}},Oe={name:"unalias",description:"Remove alias definitions",category:"shell",params:["<name...> | -a"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};if(w(r,["-a"])){for(let e of Object.keys(t.vars))e.startsWith("__alias_")&&delete t.vars[e];return{exitCode:0}}for(let e of r)delete t.vars[`__alias_${e}`];return{exitCode:0}}};import*as pt from"node:path";var Es=["/.virtual-env-js/.auth","/etc/htpasswd"];function S(r,t){return!t||t.trim()===""?r:t.startsWith("/")?pt.posix.normalize(t):pt.posix.normalize(pt.posix.join(r,t))}function Ns(r){let t=r.startsWith("/")?pt.posix.normalize(r):pt.posix.normalize(`/${r}`);return Es.some(e=>t===e||t.startsWith(`${e}/`))}function D(r,t,e){if(r!=="root"&&Ns(t))throw new Error(`${e}: permission denied: ${t}`)}function We(r){let e=(r.split("?")[0]?.split("#")[0]??r).split("/").filter(Boolean).pop();return e&&e.length>0?e:"index.html"}function Is(r,t){let e=Array.from({length:r.length+1},()=>Array(t.length+1).fill(0));for(let n=0;n<=r.length;n+=1)e[n][0]=n;for(let n=0;n<=t.length;n+=1)e[0][n]=n;for(let n=1;n<=r.length;n+=1)for(let i=1;i<=t.length;i+=1){let s=r[n-1]===t[i-1]?0:1;e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+s)}return e[r.length][t.length]}function je(r,t,e){let n=S(t,e);if(r.exists(n))return n;let i=pt.posix.dirname(n),s=pt.posix.basename(n),o=r.list(i),a=o.filter(c=>c.toLowerCase()===s.toLowerCase());if(a.length===1)return pt.posix.join(i,a[0]);let l=o.filter(c=>Is(c.toLowerCase(),s.toLowerCase())<=1);return l.length===1?pt.posix.join(i,l[0]):n}function He(r,t,e){return t.map(n=>{let i=S(r,n);return e(i).type==="directory"?`${n}/`:n}).join(" ")}function Pt(r){return r.packageManager}var qe={name:"apt",aliases:["apt-get"],description:"Package manager",category:"package",params:["<install|remove|update|upgrade|search|show|list> [pkg...]"],run:({args:r,shell:t,authUser:e})=>{let n=Pt(t);if(!n)return{stderr:"apt: package manager not initialised",exitCode:1};let i=r[0]?.toLowerCase(),s=r.slice(1),o=w(s,["-q","--quiet","-qq"]),a=w(s,["--purge"]),l=s.filter(u=>!u.startsWith("-"));if(["install","remove","purge","upgrade","update"].includes(i??"")&&e!=="root")return{stderr:`E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
12
12
  E: Unable to acquire the dpkg frontend lock, are you root?`,exitCode:100};switch(i){case"install":{if(l.length===0)return{stderr:"apt: no packages specified",exitCode:1};let{output:u,exitCode:d}=n.install(l,{quiet:o});return{stdout:u||void 0,exitCode:d}}case"remove":case"purge":{if(l.length===0)return{stderr:"apt: no packages specified",exitCode:1};let{output:u,exitCode:d}=n.remove(l,{purge:i==="purge"||a,quiet:o});return{stdout:u||void 0,exitCode:d}}case"update":return{stdout:["Hit:1 fortune://packages.fortune.local aurora InRelease","Hit:2 fortune://security.fortune.local aurora-security InRelease","Reading package lists... Done","Building dependency tree... Done","Reading state information... Done","All packages are up to date."].join(`
13
13
  `),exitCode:0};case"upgrade":return{stdout:["Reading package lists... Done","Building dependency tree... Done","Reading state information... Done","Calculating upgrade... Done","0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded."].join(`
14
14
  `),exitCode:0};case"search":{let u=l[0];if(!u)return{stderr:"apt: search requires a term",exitCode:1};let d=n.search(u);return d.length===0?{stdout:`Sorting... Done
@@ -17,29 +17,29 @@ Full Text Search... Done
17
17
  Full Text Search... Done
18
18
  ${d.map(p=>`${p.name}/${p.section??"misc"} ${p.version} amd64
19
19
  ${p.shortDesc??p.description}`).join(`
20
- `)}`,exitCode:0}}case"show":{let u=l[0];if(!u)return{stderr:"apt: show requires a package name",exitCode:1};let d=n.show(u);return d?{stdout:d,exitCode:0}:{stderr:`N: Unable to locate package ${u}`,exitCode:100}}case"list":{if(y(s,["--installed"])){let p=n.listInstalled();return p.length===0?{stdout:`Listing... Done
20
+ `)}`,exitCode:0}}case"show":{let u=l[0];if(!u)return{stderr:"apt: show requires a package name",exitCode:1};let d=n.show(u);return d?{stdout:d,exitCode:0}:{stderr:`N: Unable to locate package ${u}`,exitCode:100}}case"list":{if(w(s,["--installed"])){let p=n.listInstalled();return p.length===0?{stdout:`Listing... Done
21
21
  (no packages installed)`,exitCode:0}:{stdout:`Listing... Done
22
22
  ${p.map(g=>`${g.name}/${g.section} ${g.version} ${g.architecture} [installed]`).join(`
23
23
  `)}`,exitCode:0}}return{stdout:`Listing... Done
24
24
  ${n.listAvailable().map(p=>`${p.name}/${p.section??"misc"} ${p.version} amd64`).join(`
25
25
  `)}`,exitCode:0}}default:return{stdout:["Usage: apt [options] command","","Commands:"," install <pkg...> Install packages"," remove <pkg...> Remove packages"," purge <pkg...> Remove packages and config files"," update Refresh package index"," upgrade Upgrade all packages"," search <term> Search in package descriptions"," show <pkg> Show package details"," list [--installed] List packages"].join(`
26
- `),exitCode:0}}}},je={name:"apt-cache",description:"Query the package cache",category:"package",params:["<search|show|policy> [pkg]"],run:({args:r,shell:t})=>{let e=Pt(t);if(!e)return{stderr:"apt-cache: package manager not initialised",exitCode:1};let n=r[0]?.toLowerCase(),i=r[1];switch(n){case"search":return i?{stdout:e.search(i).map(o=>`${o.name} - ${o.shortDesc??o.description}`).join(`
26
+ `),exitCode:0}}}},Ke={name:"apt-cache",description:"Query the package cache",category:"package",params:["<search|show|policy> [pkg]"],run:({args:r,shell:t})=>{let e=Pt(t);if(!e)return{stderr:"apt-cache: package manager not initialised",exitCode:1};let n=r[0]?.toLowerCase(),i=r[1];switch(n){case"search":return i?{stdout:e.search(i).map(o=>`${o.name} - ${o.shortDesc??o.description}`).join(`
27
27
  `)||"(no results)",exitCode:0}:{stderr:"Need a search term",exitCode:1};case"show":{if(!i)return{stderr:"Need a package name",exitCode:1};let s=e.show(i);return s?{stdout:s,exitCode:0}:{stderr:`N: Unable to locate package ${i}`,exitCode:100}}case"policy":{if(!i)return{stderr:"Need a package name",exitCode:1};let s=e.findInRegistry(i);if(!s)return{stderr:`N: Unable to locate package ${i}`,exitCode:100};let o=e.isInstalled(i);return{stdout:[`${i}:`,` Installed: ${o?s.version:"(none)"}`,` Candidate: ${s.version}`," Version table:",` ${s.version} 500`," 500 fortune://packages.fortune.local aurora/main amd64 Packages"].join(`
28
- `),exitCode:0}}default:return{stderr:`apt-cache: unknown command '${n??""}'`,exitCode:1}}}};var He={name:"awk",description:"Pattern scanning and processing language",category:"text",params:["[-F <sep>] '<program>' [file]"],run:({authUser:r,args:t,stdin:e,cwd:n,shell:i})=>{let s=st(t,["-F"])??" ",o=t.filter(S=>!S.startsWith("-")&&S!==s),a=o[0],l=o[1];if(!a)return{stderr:"awk: no program",exitCode:1};let c=e??"";if(l){let S=x(n,l);try{_(r,S,"awk"),c=i.vfs.readFile(S)}catch{return{stderr:`awk: ${l}: No such file or directory`,exitCode:1}}}let u=c.split(`
29
- `);u[u.length-1]===""&&u.pop();let d=[],m=a.trim();if(!m.startsWith("{")&&!m.includes("{"))d.push({pattern:m,action:"print $0"});else{let S=/([^{]*)\{([^}]*)\}/g,k=S.exec(m);for(;k!==null;)d.push({pattern:k[1].trim(),action:k[2].trim()}),k=S.exec(m);d.length===0&&d.push({pattern:"",action:m.replace(/[{}]/g,"").trim()})}let p=[],w=d.find(S=>S.pattern==="BEGIN"),g=d.find(S=>S.pattern==="END"),f=d.filter(S=>S.pattern!=="BEGIN"&&S.pattern!=="END");function $(S){return s===" "?S.trim().split(/\s+/).filter(Boolean):S.split(s)}function E(S,k,V){let b=$(k),P=b.length,R=C=>{if(C=C.trim(),C==="NR")return String(V);if(C==="NF")return String(P);if(C==="$0")return k;if(C==="$NF")return b[P-1]??"";if(/^\$\d+$/.test(C))return b[parseInt(C.slice(1),10)-1]??"";let N=C.replace(/\bNR\b/g,String(V)).replace(/\bNF\b/g,String(P));if(/^[\d\s+\-*/()]+$/.test(N))try{return String(Function(`"use strict"; return (${N});`)())}catch{}return C.replace(/"/g,"")},v=S.split(";").map(C=>C.trim()).filter(Boolean);for(let C of v)if(C==="print"||C==="print $0")p.push(k);else if(C.startsWith("print ")){let N=C.slice(6).split(/\s*,\s*/);p.push(N.map(R).join(" "))}}function F(S,k,V){if(!S||S==="1")return!0;let b=S.match(/^NR\s*([=!<>]=?|==)\s*(\d+)$/);if(b){let v=b[1],C=parseInt(b[2],10);switch(v){case"==":return V===C;case"!=":return V!==C;case">":return V>C;case">=":return V>=C;case"<":return V<C;case"<=":return V<=C}}let P=S.match(/^NR%(\d+)==(\d+)$/);if(P)return V%parseInt(P[1],10)===parseInt(P[2],10);if(S.startsWith("/")&&S.endsWith("/"))try{return new RegExp(S.slice(1,-1)).test(k)}catch{return!1}let R=S.match(/^\$(\d+)~\/(.*)\/$/);if(R){let C=$(k)[parseInt(R[1],10)-1]??"";try{return new RegExp(R[2]).test(C)}catch{return!1}}return!1}w&&E(w.action,"",0);for(let S=1;S<=u.length;S++){let k=u[S-1];for(let V of f)F(V.pattern,k,S)&&E(V.action,k,S)}return g&&E(g.action,"",u.length+1),{stdout:p.join(`
28
+ `),exitCode:0}}default:return{stderr:`apt-cache: unknown command '${n??""}'`,exitCode:1}}}};var Ge={name:"awk",description:"Pattern scanning and processing language",category:"text",params:["[-F <sep>] '<program>' [file]"],run:({authUser:r,args:t,stdin:e,cwd:n,shell:i})=>{let s=it(t,["-F"])??" ",o=t.filter(x=>!x.startsWith("-")&&x!==s),a=o[0],l=o[1];if(!a)return{stderr:"awk: no program",exitCode:1};let c=e??"";if(l){let x=S(n,l);try{D(r,x,"awk"),c=i.vfs.readFile(x)}catch{return{stderr:`awk: ${l}: No such file or directory`,exitCode:1}}}let u=c.split(`
29
+ `);u[u.length-1]===""&&u.pop();let d=[],m=a.trim();if(!m.startsWith("{")&&!m.includes("{"))d.push({pattern:m,action:"print $0"});else{let x=/([^{]*)\{([^}]*)\}/g,k=x.exec(m);for(;k!==null;)d.push({pattern:k[1].trim(),action:k[2].trim()}),k=x.exec(m);d.length===0&&d.push({pattern:"",action:m.replace(/[{}]/g,"").trim()})}let p=[],y=d.find(x=>x.pattern==="BEGIN"),g=d.find(x=>x.pattern==="END"),f=d.filter(x=>x.pattern!=="BEGIN"&&x.pattern!=="END");function $(x){return s===" "?x.trim().split(/\s+/).filter(Boolean):x.split(s)}function N(x,k,A){let b=$(k),P=b.length,R=C=>{if(C=C.trim(),C==="NR")return String(A);if(C==="NF")return String(P);if(C==="$0")return k;if(C==="$NF")return b[P-1]??"";if(/^\$\d+$/.test(C))return b[parseInt(C.slice(1),10)-1]??"";let I=C.replace(/\bNR\b/g,String(A)).replace(/\bNF\b/g,String(P));if(/^[\d\s+\-*/()]+$/.test(I))try{return String(Function(`"use strict"; return (${I});`)())}catch{}return C.replace(/"/g,"")},v=x.split(";").map(C=>C.trim()).filter(Boolean);for(let C of v)if(C==="print"||C==="print $0")p.push(k);else if(C.startsWith("print ")){let I=C.slice(6).split(/\s*,\s*/);p.push(I.map(R).join(" "))}}function M(x,k,A){if(!x||x==="1")return!0;let b=x.match(/^NR\s*([=!<>]=?|==)\s*(\d+)$/);if(b){let v=b[1],C=parseInt(b[2],10);switch(v){case"==":return A===C;case"!=":return A!==C;case">":return A>C;case">=":return A>=C;case"<":return A<C;case"<=":return A<=C}}let P=x.match(/^NR%(\d+)==(\d+)$/);if(P)return A%parseInt(P[1],10)===parseInt(P[2],10);if(x.startsWith("/")&&x.endsWith("/"))try{return new RegExp(x.slice(1,-1)).test(k)}catch{return!1}let R=x.match(/^\$(\d+)~\/(.*)\/$/);if(R){let C=$(k)[parseInt(R[1],10)-1]??"";try{return new RegExp(R[2]).test(C)}catch{return!1}}return!1}y&&N(y.action,"",0);for(let x=1;x<=u.length;x++){let k=u[x-1];for(let A of f)M(A.pattern,k,x)&&N(A.action,k,x)}return g&&N(g.action,"",u.length+1),{stdout:p.join(`
30
30
  `)+(p.length>0?`
31
- `:""),exitCode:0}}};var qe={name:"base64",description:"Encode/decode base64",category:"text",params:["[-d] [file]"],run:({args:r,stdin:t})=>{let e=y(r,["-d","--decode"]),n=t??"";if(e)try{return{stdout:Buffer.from(n.trim(),"base64").toString("utf8"),exitCode:0}}catch{return{stderr:"base64: invalid input",exitCode:1}}return{stdout:Buffer.from(n).toString("base64"),exitCode:0}}};var Ke={name:"cat",description:"Concatenate and print files",category:"files",params:["[-n] [-b] <file...>"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=y(n,["-n","--number"]),o=y(n,["-b","--number-nonblank"]),a=n.filter(m=>!m.startsWith("-"));if(a.length===0&&i!==void 0)return{stdout:i,exitCode:0};if(a.length===0)return{stderr:"cat: missing file operand",exitCode:1};let l=[];for(let m of a){let p=Be(t.vfs,e,m);_(r,p,"cat"),l.push(t.vfs.readFile(p))}let c=l.join("");if(!s&&!o)return{stdout:c,exitCode:0};let u=1;return{stdout:c.split(`
31
+ `:""),exitCode:0}}};var Ze={name:"base64",description:"Encode/decode base64",category:"text",params:["[-d] [file]"],run:({args:r,stdin:t})=>{let e=w(r,["-d","--decode"]),n=t??"";if(e)try{return{stdout:Buffer.from(n.trim(),"base64").toString("utf8"),exitCode:0}}catch{return{stderr:"base64: invalid input",exitCode:1}}return{stdout:Buffer.from(n).toString("base64"),exitCode:0}}};var Je={name:"cat",description:"Concatenate and print files",category:"files",params:["[-n] [-b] <file...>"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=w(n,["-n","--number"]),o=w(n,["-b","--number-nonblank"]),a=n.filter(m=>!m.startsWith("-"));if(a.length===0&&i!==void 0)return{stdout:i,exitCode:0};if(a.length===0)return{stderr:"cat: missing file operand",exitCode:1};let l=[];for(let m of a){let p=je(t.vfs,e,m);D(r,p,"cat"),l.push(t.vfs.readFile(p))}let c=l.join("");if(!s&&!o)return{stdout:c,exitCode:0};let u=1;return{stdout:c.split(`
32
32
  `).map(m=>o&&m.trim()===""?m:`${String(u++).padStart(6)} ${m}`).join(`
33
- `),exitCode:0}}};var Ge={name:"cd",description:"Change directory",category:"navigation",params:["[path]"],run:({authUser:r,shell:t,cwd:e,args:n,mode:i})=>{let s=x(e,n[0]??"/virtual-env-js");return _(r,s,"cd"),t.vfs.stat(s).type!=="directory"?{stderr:`cd: not a directory: ${s}`,exitCode:1}:{nextCwd:s,exitCode:0}}};function $s(r,t){let e=/^([ugoa]*)([+\-=])([rwx]*)$/,n=t.split(","),i=r;for(let s of n){let o=s.trim().match(e);if(!o)return null;let[,a="a",l,c=""]=o,u=a===""||a==="a"?["u","g","o"]:a.split(""),d={u:{r:256,w:128,x:64},g:{r:32,w:16,x:8},o:{r:4,w:2,x:1}};for(let m of u)for(let p of c.split("")){let w=d[m]?.[p];if(w!==void 0){if(l==="+")i|=w;else if(l==="-")i&=~w;else if(l==="="){let g=Object.values(d[m]??{}).reduce((f,$)=>f|$,0);i=i&~g|w}}}}return i}var Ze={name:"chmod",description:"Change file permissions",category:"files",params:["<mode> <file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let[i,s]=n;if(!i||!s)return{stderr:"chmod: missing operand",exitCode:1};let o=x(e,s);try{if(_(r,o,"chmod"),!t.vfs.exists(o))return{stderr:`chmod: ${s}: No such file or directory`,exitCode:1};let a,l=parseInt(i,8);if(!Number.isNaN(l)&&/^[0-7]+$/.test(i))a=l;else{let c=t.vfs.stat(o).mode,u=$s(c,i);if(u===null)return{stderr:`chmod: invalid mode: ${i}`,exitCode:1};a=u}return t.vfs.chmod(o,a),{exitCode:0}}catch(a){return{stderr:`chmod: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}}};var Je={name:"clear",description:"Clear the terminal screen",category:"shell",params:[],run:()=>({clearScreen:!0,stdout:"",exitCode:0})};var Qe={name:"cp",description:"Copy files or directories",category:"files",params:["[-r] <source> <dest>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=y(n,["-r","-R","--recursive"]),s=n.filter(u=>!u.startsWith("-")),[o,a]=s;if(!o||!a)return{stderr:"cp: missing operand",exitCode:1};let l=x(e,o),c=x(e,a);try{if(_(r,l,"cp"),_(r,c,"cp"),!t.vfs.exists(l))return{stderr:`cp: ${o}: No such file or directory`,exitCode:1};if(t.vfs.stat(l).type==="directory"){if(!i)return{stderr:`cp: ${o}: is a directory (use -r)`,exitCode:1};let d=(p,w)=>{t.vfs.mkdir(w,493);for(let g of t.vfs.list(p)){let f=`${p}/${g}`,$=`${w}/${g}`;if(t.vfs.stat(f).type==="directory")d(f,$);else{let F=t.vfs.readFileRaw(f);t.writeFileAsUser(r,$,F)}}},m=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c;d(l,m)}else{let d=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c,m=t.vfs.readFileRaw(l);t.writeFileAsUser(r,d,m)}return{exitCode:0}}catch(u){return{stderr:`cp: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}};var Ye={name:"curl",description:"Transfer data from or to a server (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:r,cwd:t,args:e,shell:n})=>{let{flagsWithValues:i,positionals:s}=nt(e,{flagsWithValue:["-o","--output","-X","--request","-d","--data","-H","--header","-u","--user"]});if(y(e,["--help","-h"]))return{stdout:["Usage: curl [options] <url>"," -o, --output <file> Write to file"," -X, --request <method> HTTP method"," -d, --data <data> POST data"," -H, --header <hdr> Extra header"," -s, --silent Silent mode"," -I, --head Fetch headers only"," -L, --location Follow redirects"," -v, --verbose Verbose"].join(`
34
- `),exitCode:0};let o=s[0];if(!o)return{stderr:"curl: no URL specified",exitCode:1};let a=i.get("-o")??i.get("--output")??null,l=(i.get("-X")??i.get("--request")??"GET").toUpperCase(),c=i.get("-d")??i.get("--data")??null,u=i.get("-H")??i.get("--header")??null,d=y(e,["-s","--silent"]),m=y(e,["-I","--head"]),p=y(e,["-L","--location"]),w=y(e,["-v","--verbose"]),g={"User-Agent":"curl/7.88.1"};if(u){let k=u.indexOf(":");k!==-1&&(g[u.slice(0,k).trim()]=u.slice(k+1).trim())}let f=c&&l==="GET"?"POST":l,$={method:f,headers:g,redirect:p?"follow":"manual"};c&&(g["Content-Type"]??="application/x-www-form-urlencoded",$.body=c);let E=[];w&&(E.push(`* Trying ${o}...`,"* Connected"),E.push(`> ${f} / HTTP/1.1`,`> Host: ${new URL(o).host}`));let F;try{let k=o.startsWith("http://")||o.startsWith("https://")?o:`http://${o}`;F=await fetch(k,$)}catch(k){return{stderr:`curl: (6) Could not resolve host: ${k instanceof Error?k.message:String(k)}`,exitCode:6}}if(w&&E.push(`< HTTP/1.1 ${F.status} ${F.statusText}`),m){let k=[`HTTP/1.1 ${F.status} ${F.statusText}`];for(let[V,b]of F.headers.entries())k.push(`${V}: ${b}`);return{stdout:`${k.join(`\r
33
+ `),exitCode:0}}};var Qe={name:"cd",description:"Change directory",category:"navigation",params:["[path]"],run:({authUser:r,shell:t,cwd:e,args:n,mode:i})=>{let s=S(e,n[0]??"/virtual-env-js");return D(r,s,"cd"),t.vfs.stat(s).type!=="directory"?{stderr:`cd: not a directory: ${s}`,exitCode:1}:{nextCwd:s,exitCode:0}}};function Vs(r,t){let e=/^([ugoa]*)([+\-=])([rwx]*)$/,n=t.split(","),i=r;for(let s of n){let o=s.trim().match(e);if(!o)return null;let[,a="a",l,c=""]=o,u=a===""||a==="a"?["u","g","o"]:a.split(""),d={u:{r:256,w:128,x:64},g:{r:32,w:16,x:8},o:{r:4,w:2,x:1}};for(let m of u)for(let p of c.split("")){let y=d[m]?.[p];if(y!==void 0){if(l==="+")i|=y;else if(l==="-")i&=~y;else if(l==="="){let g=Object.values(d[m]??{}).reduce((f,$)=>f|$,0);i=i&~g|y}}}}return i}var Ye={name:"chmod",description:"Change file permissions",category:"files",params:["<mode> <file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let[i,s]=n;if(!i||!s)return{stderr:"chmod: missing operand",exitCode:1};let o=S(e,s);try{if(D(r,o,"chmod"),!t.vfs.exists(o))return{stderr:`chmod: ${s}: No such file or directory`,exitCode:1};let a,l=parseInt(i,8);if(!Number.isNaN(l)&&/^[0-7]+$/.test(i))a=l;else{let c=t.vfs.stat(o).mode,u=Vs(c,i);if(u===null)return{stderr:`chmod: invalid mode: ${i}`,exitCode:1};a=u}return t.vfs.chmod(o,a),{exitCode:0}}catch(a){return{stderr:`chmod: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}}};var Xe={name:"clear",description:"Clear the terminal screen",category:"shell",params:[],run:()=>({clearScreen:!0,stdout:"",exitCode:0})};var tr={name:"cp",description:"Copy files or directories",category:"files",params:["[-r] <source> <dest>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=w(n,["-r","-R","--recursive"]),s=n.filter(u=>!u.startsWith("-")),[o,a]=s;if(!o||!a)return{stderr:"cp: missing operand",exitCode:1};let l=S(e,o),c=S(e,a);try{if(D(r,l,"cp"),D(r,c,"cp"),!t.vfs.exists(l))return{stderr:`cp: ${o}: No such file or directory`,exitCode:1};if(t.vfs.stat(l).type==="directory"){if(!i)return{stderr:`cp: ${o}: is a directory (use -r)`,exitCode:1};let d=(p,y)=>{t.vfs.mkdir(y,493);for(let g of t.vfs.list(p)){let f=`${p}/${g}`,$=`${y}/${g}`;if(t.vfs.stat(f).type==="directory")d(f,$);else{let M=t.vfs.readFileRaw(f);t.writeFileAsUser(r,$,M)}}},m=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c;d(l,m)}else{let d=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c,m=t.vfs.readFileRaw(l);t.writeFileAsUser(r,d,m)}return{exitCode:0}}catch(u){return{stderr:`cp: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}};var er={name:"curl",description:"Transfer data from or to a server (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:r,cwd:t,args:e,shell:n})=>{let{flagsWithValues:i,positionals:s}=st(e,{flagsWithValue:["-o","--output","-X","--request","-d","--data","-H","--header","-u","--user"]});if(w(e,["--help","-h"]))return{stdout:["Usage: curl [options] <url>"," -o, --output <file> Write to file"," -X, --request <method> HTTP method"," -d, --data <data> POST data"," -H, --header <hdr> Extra header"," -s, --silent Silent mode"," -I, --head Fetch headers only"," -L, --location Follow redirects"," -v, --verbose Verbose"].join(`
34
+ `),exitCode:0};let o=s[0];if(!o)return{stderr:"curl: no URL specified",exitCode:1};let a=i.get("-o")??i.get("--output")??null,l=(i.get("-X")??i.get("--request")??"GET").toUpperCase(),c=i.get("-d")??i.get("--data")??null,u=i.get("-H")??i.get("--header")??null,d=w(e,["-s","--silent"]),m=w(e,["-I","--head"]),p=w(e,["-L","--location"]),y=w(e,["-v","--verbose"]),g={"User-Agent":"curl/7.88.1"};if(u){let k=u.indexOf(":");k!==-1&&(g[u.slice(0,k).trim()]=u.slice(k+1).trim())}let f=c&&l==="GET"?"POST":l,$={method:f,headers:g,redirect:p?"follow":"manual"};c&&(g["Content-Type"]??="application/x-www-form-urlencoded",$.body=c);let N=[];y&&(N.push(`* Trying ${o}...`,"* Connected"),N.push(`> ${f} / HTTP/1.1`,`> Host: ${new URL(o).host}`));let M;try{let k=o.startsWith("http://")||o.startsWith("https://")?o:`http://${o}`;M=await fetch(k,$)}catch(k){return{stderr:`curl: (6) Could not resolve host: ${k instanceof Error?k.message:String(k)}`,exitCode:6}}if(y&&N.push(`< HTTP/1.1 ${M.status} ${M.statusText}`),m){let k=[`HTTP/1.1 ${M.status} ${M.statusText}`];for(let[A,b]of M.headers.entries())k.push(`${A}: ${b}`);return{stdout:`${k.join(`\r
35
35
  `)}\r
36
- `,exitCode:0}}let S;try{S=await F.text()}catch{return{stderr:"curl: failed to read response body",exitCode:1}}if(a){let k=x(t,a);return _(r,k,"curl"),n.writeFileAsUser(r,k,S),d||E.push(` % Total % Received
37
- 100 ${S.length} 100 ${S.length}`),{stderr:E.join(`
38
- `)||void 0,exitCode:F.ok?0:22}}return{stdout:S,stderr:E.length>0?E.join(`
39
- `):void 0,exitCode:F.ok?0:22}}};var Xe={name:"cut",description:"Remove sections from lines",category:"text",params:["-d <delim> -f <fields> [file]"],run:({args:r,stdin:t})=>{let e=st(r,["-d"])??" ",i=(st(r,["-f"])??"1").split(",").map(a=>{let[l,c]=a.split("-").map(Number);return c!==void 0?{from:(l??1)-1,to:c-1}:{from:(l??1)-1,to:(l??1)-1}});return{stdout:(t??"").split(`
36
+ `,exitCode:0}}let x;try{x=await M.text()}catch{return{stderr:"curl: failed to read response body",exitCode:1}}if(a){let k=S(t,a);return D(r,k,"curl"),n.writeFileAsUser(r,k,x),d||N.push(` % Total % Received
37
+ 100 ${x.length} 100 ${x.length}`),{stderr:N.join(`
38
+ `)||void 0,exitCode:M.ok?0:22}}return{stdout:x,stderr:N.length>0?N.join(`
39
+ `):void 0,exitCode:M.ok?0:22}}};var rr={name:"cut",description:"Remove sections from lines",category:"text",params:["-d <delim> -f <fields> [file]"],run:({args:r,stdin:t})=>{let e=it(r,["-d"])??" ",i=(it(r,["-f"])??"1").split(",").map(a=>{let[l,c]=a.split("-").map(Number);return c!==void 0?{from:(l??1)-1,to:c-1}:{from:(l??1)-1,to:(l??1)-1}});return{stdout:(t??"").split(`
40
40
  `).map(a=>{let l=a.split(e),c=[];for(let u of i)for(let d=u.from;d<=Math.min(u.to,l.length-1);d++)c.push(l[d]??"");return c.join(e)}).join(`
41
- `),exitCode:0}}};var tr={name:"date",description:"Print current date and time",category:"system",params:["[+format]"],run:({args:r})=>{let t=new Date,e=r[0];return e?.startsWith("+")?{stdout:e.slice(1).replace("%Y",String(t.getFullYear())).replace("%m",String(t.getMonth()+1).padStart(2,"0")).replace("%d",String(t.getDate()).padStart(2,"0")).replace("%H",String(t.getHours()).padStart(2,"0")).replace("%M",String(t.getMinutes()).padStart(2,"0")).replace("%S",String(t.getSeconds()).padStart(2,"0")).replace("%s",String(Math.floor(t.getTime()/1e3))),exitCode:0}:{stdout:t.toString(),exitCode:0}}};var er={name:"declare",aliases:["local","typeset"],description:"Declare variables and give them attributes",category:"shell",params:["[-i] [-r] [-x] [-a] [name[=value]...]"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};let e=y(r,["-i"]),n=y(r,["-r"]),i=y(r,["-x"]);if(r.filter(a=>!a.startsWith("-")).length===0)return{stdout:Object.entries(t.vars).map(([l,c])=>`declare -- ${l}="${c}"`).join(`
42
- `),exitCode:0};let o=r.filter(a=>!a.startsWith("-"));for(let a of o){let l=a.indexOf("=");if(l===-1)a in t.vars||(t.vars[a]="");else{let c=a.slice(0,l),u=a.slice(l+1);if(e){let d=parseInt(u,10);u=Number.isNaN(d)?"0":String(d)}t.vars[c]=u}}return{exitCode:0}}};var rr={name:"deluser",description:"Delete a user",category:"users",params:["[-f] <username>"],run:async({authUser:r,args:t,shell:e})=>{if(r!=="root")return{stderr:`deluser: permission denied
41
+ `),exitCode:0}}};var nr={name:"date",description:"Print current date and time",category:"system",params:["[+format]"],run:({args:r})=>{let t=new Date,e=r[0];return e?.startsWith("+")?{stdout:e.slice(1).replace("%Y",String(t.getFullYear())).replace("%m",String(t.getMonth()+1).padStart(2,"0")).replace("%d",String(t.getDate()).padStart(2,"0")).replace("%H",String(t.getHours()).padStart(2,"0")).replace("%M",String(t.getMinutes()).padStart(2,"0")).replace("%S",String(t.getSeconds()).padStart(2,"0")).replace("%s",String(Math.floor(t.getTime()/1e3))),exitCode:0}:{stdout:t.toString(),exitCode:0}}};var sr={name:"declare",aliases:["local","typeset"],description:"Declare variables and give them attributes",category:"shell",params:["[-i] [-r] [-x] [-a] [name[=value]...]"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};let e=w(r,["-i"]),n=w(r,["-r"]),i=w(r,["-x"]);if(r.filter(a=>!a.startsWith("-")).length===0)return{stdout:Object.entries(t.vars).map(([l,c])=>`declare -- ${l}="${c}"`).join(`
42
+ `),exitCode:0};let o=r.filter(a=>!a.startsWith("-"));for(let a of o){let l=a.indexOf("=");if(l===-1)a in t.vars||(t.vars[a]="");else{let c=a.slice(0,l),u=a.slice(l+1);if(e){let d=parseInt(u,10);u=Number.isNaN(d)?"0":String(d)}t.vars[c]=u}}return{exitCode:0}}};var ir={name:"deluser",description:"Delete a user",category:"users",params:["[-f] <username>"],run:async({authUser:r,args:t,shell:e})=>{if(r!=="root")return{stderr:`deluser: permission denied
43
43
  `,exitCode:1};let n=t.includes("-f")||t.includes("--force")||t.includes("-y"),i=t.find(o=>!o.startsWith("-"));if(!i)return{stderr:`Usage: deluser [-f] <username>
44
44
  `,exitCode:1};if(!e.users.listUsers().includes(i))return{stderr:`deluser: user '${i}' does not exist
45
45
  `,exitCode:1};if(i==="root")return{stderr:`deluser: cannot remove the root account
@@ -49,226 +49,233 @@ deluser: done.
49
49
  `,exitCode:1}}:(await a.users.deleteUser(i),{result:{stdout:`Removing user '${i}' ...
50
50
  deluser: done.
51
51
  `,exitCode:0}});return{sudoChallenge:{username:i,targetUser:i,commandLine:null,loginShell:!1,prompt:`Warning: deleting user '${i}'.
52
- Type the username to confirm: `,mode:"confirm",onPassword:s},exitCode:0}}};var nr={name:"df",description:"Report filesystem disk space usage",category:"system",params:["[-h]"],run:({shell:r})=>{let e=(r.vfs.getUsageBytes()/1024).toFixed(0),n="1048576",i=String(Number(n)-Number(e)),s=Math.round(Number(e)/Number(n)*100),o="Filesystem 1K-blocks Used Available Use% Mounted on",a=`virtual-fs ${n.padStart(9)} ${e.padStart(7)} ${i.padStart(9)} ${s}% /`;return{stdout:`${o}
53
- ${a}`,exitCode:0}}};var sr={name:"diff",description:"Compare files line by line",category:"text",params:["<file1> <file2>"],run:({shell:r,cwd:t,args:e})=>{let[n,i]=e;if(!n||!i)return{stderr:"diff: missing operand",exitCode:1};let s=x(t,n),o=x(t,i),a,l;try{a=r.vfs.readFile(s).split(`
52
+ Type the username to confirm: `,mode:"confirm",onPassword:s},exitCode:0}}};var or={name:"df",description:"Report filesystem disk space usage",category:"system",params:["[-h]"],run:({shell:r})=>{let e=(r.vfs.getUsageBytes()/1024).toFixed(0),n="1048576",i=String(Number(n)-Number(e)),s=Math.round(Number(e)/Number(n)*100),o="Filesystem 1K-blocks Used Available Use% Mounted on",a=`virtual-fs ${n.padStart(9)} ${e.padStart(7)} ${i.padStart(9)} ${s}% /`;return{stdout:`${o}
53
+ ${a}`,exitCode:0}}};var ar={name:"diff",description:"Compare files line by line",category:"text",params:["<file1> <file2>"],run:({shell:r,cwd:t,args:e})=>{let[n,i]=e;if(!n||!i)return{stderr:"diff: missing operand",exitCode:1};let s=S(t,n),o=S(t,i),a,l;try{a=r.vfs.readFile(s).split(`
54
54
  `)}catch{return{stderr:`diff: ${n}: No such file or directory`,exitCode:2}}try{l=r.vfs.readFile(o).split(`
55
55
  `)}catch{return{stderr:`diff: ${i}: No such file or directory`,exitCode:2}}let c=[],u=Math.max(a.length,l.length);for(let d=0;d<u;d++){let m=a[d],p=l[d];m!==p&&(m!==void 0&&c.push(`< ${m}`),p!==void 0&&c.push(`> ${p}`))}return{stdout:c.join(`
56
- `),exitCode:c.length>0?1:0}}};var ir={name:"dpkg",description:"Debian package manager low-level tool",category:"package",params:["[-l] [-s pkg] [-L pkg] [-i pkg] [--remove pkg]"],run:({args:r,authUser:t,shell:e})=>{let n=Pt(e);if(!n)return{stderr:"dpkg: package manager not initialised",exitCode:1};let i=y(r,["-l","--list"]),s=y(r,["-s","--status"]),o=y(r,["-L","--listfiles"]),a=y(r,["-r","--remove"]),l=y(r,["-P","--purge"]),{positionals:c}=nt(r,{flags:["-l","--list","-s","--status","-L","--listfiles","-r","--remove","-P","--purge"]});if(i){let u=n.listInstalled();if(u.length===0)return{stdout:["Desired=Unknown/Install/Remove/Purge/Hold","|Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend","|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)","||/ Name Version Architecture Description","+++-==============-===============-============-========================================","(no packages installed)"].join(`
57
- `),exitCode:0};let d=["Desired=Unknown/Install/Remove/Purge/Hold","|Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend","|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)","||/ Name Version Architecture Description","+++-==============-===============-============-========================================"],m=u.map(p=>{let w=p.name.padEnd(14).slice(0,14),g=p.version.padEnd(15).slice(0,15),f=p.architecture.padEnd(12).slice(0,12),$=(p.description||"").slice(0,40);return`ii ${w} ${g} ${f} ${$}`});return{stdout:[...d,...m].join(`
56
+ `),exitCode:c.length>0?1:0}}};var lr={name:"dpkg",description:"Debian package manager low-level tool",category:"package",params:["[-l] [-s pkg] [-L pkg] [-i pkg] [--remove pkg]"],run:({args:r,authUser:t,shell:e})=>{let n=Pt(e);if(!n)return{stderr:"dpkg: package manager not initialised",exitCode:1};let i=w(r,["-l","--list"]),s=w(r,["-s","--status"]),o=w(r,["-L","--listfiles"]),a=w(r,["-r","--remove"]),l=w(r,["-P","--purge"]),{positionals:c}=st(r,{flags:["-l","--list","-s","--status","-L","--listfiles","-r","--remove","-P","--purge"]});if(i){let u=n.listInstalled();if(u.length===0)return{stdout:["Desired=Unknown/Install/Remove/Purge/Hold","|Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend","|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)","||/ Name Version Architecture Description","+++-==============-===============-============-========================================","(no packages installed)"].join(`
57
+ `),exitCode:0};let d=["Desired=Unknown/Install/Remove/Purge/Hold","|Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend","|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)","||/ Name Version Architecture Description","+++-==============-===============-============-========================================"],m=u.map(p=>{let y=p.name.padEnd(14).slice(0,14),g=p.version.padEnd(15).slice(0,15),f=p.architecture.padEnd(12).slice(0,12),$=(p.description||"").slice(0,40);return`ii ${y} ${g} ${f} ${$}`});return{stdout:[...d,...m].join(`
58
58
  `),exitCode:0}}if(s){let u=c[0];if(!u)return{stderr:"dpkg: -s needs a package name",exitCode:1};let d=n.show(u);return d?{stdout:d,exitCode:0}:{stderr:`dpkg-query: package '${u}' is not installed and no information is available`,exitCode:1}}if(o){let u=c[0];if(!u)return{stderr:"dpkg: -L needs a package name",exitCode:1};let d=n.listInstalled().find(m=>m.name===u);return d?d.files.length===0?{stdout:"/.keep",exitCode:0}:{stdout:d.files.join(`
59
59
  `),exitCode:0}:{stderr:`dpkg-query: package '${u}' is not installed`,exitCode:1}}if(a||l){if(t!=="root")return{stderr:"dpkg: error: requested operation requires superuser privilege",exitCode:2};if(c.length===0)return{stderr:"dpkg: error: need an action option",exitCode:2};let{output:u,exitCode:d}=n.remove(c,{purge:l});return{stdout:u||void 0,exitCode:d}}return{stdout:["Usage: dpkg [<option>...] <command>","","Commands:"," -l, --list List packages matching given pattern"," -s, --status <pkg>... Report status of specified package"," -L, --listfiles <pkg>... List files owned by package"," -r, --remove <pkg>... Remove <pkg> but leave its configuration"," -P, --purge <pkg>... Remove <pkg> and its configuration"].join(`
60
- `),exitCode:0}}},or={name:"dpkg-query",description:"Show information about installed packages",category:"package",params:["-W [pkg] | -l [pattern]"],run:({args:r,shell:t})=>{let e=Pt(t);if(!e)return{stderr:"dpkg-query: package manager not initialised",exitCode:1};let n=y(r,["-l"]),i=y(r,["-W","--show"]),{positionals:s}=nt(r,{flags:["-l","-W","--show"]});if(n||i){let o=e.listInstalled(),a=s[0],l=a?o.filter(u=>u.name.includes(a)):o;return i?{stdout:l.map(u=>`${u.name} ${u.version}`).join(`
60
+ `),exitCode:0}}},cr={name:"dpkg-query",description:"Show information about installed packages",category:"package",params:["-W [pkg] | -l [pattern]"],run:({args:r,shell:t})=>{let e=Pt(t);if(!e)return{stderr:"dpkg-query: package manager not initialised",exitCode:1};let n=w(r,["-l"]),i=w(r,["-W","--show"]),{positionals:s}=st(r,{flags:["-l","-W","--show"]});if(n||i){let o=e.listInstalled(),a=s[0],l=a?o.filter(u=>u.name.includes(a)):o;return i?{stdout:l.map(u=>`${u.name} ${u.version}`).join(`
61
61
  `),exitCode:0}:{stdout:l.map(u=>{let d=u.name.padEnd(14).slice(0,14),m=u.version.padEnd(15).slice(0,15);return`ii ${d} ${m} amd64 ${(u.description||"").slice(0,40)}`}).join(`
62
- `)||"(no packages match)",exitCode:0}}return{stderr:"dpkg-query: need a flag (-l, -W)",exitCode:1}}};var ar={name:"du",description:"Estimate file space usage",category:"system",params:["[-h] [-s] [path]"],run:({shell:r,cwd:t,args:e})=>{let n=y(e,["-h"]),i=y(e,["-s"]),s=e.find(u=>!u.startsWith("-"))??".",o=x(t,s),a=u=>n?`${(u/1024).toFixed(1)}K`:String(Math.ceil(u/1024));if(!r.vfs.exists(o))return{stderr:`du: ${s}: No such file or directory`,exitCode:1};if(i||r.vfs.stat(o).type==="file")return{stdout:`${a(r.vfs.getUsageBytes(o))} ${s}`,exitCode:0};let l=[],c=(u,d)=>{let m=0;for(let p of r.vfs.list(u)){let w=`${u}/${p}`,g=`${d}/${p}`,f=r.vfs.stat(w);f.type==="directory"?m+=c(w,g):(m+=f.size,i||l.push(`${a(f.size)} ${g}`))}return l.push(`${a(m)} ${d}`),m};return c(o,s),{stdout:l.join(`
63
- `),exitCode:0}}};function Ps(r,t){let e=r.replace(/\b([A-Za-z_][A-Za-z0-9_]*)\b/g,(n,i)=>{let s=t[i];return s!==void 0&&s!==""?s:"0"});if(!/^[\d\s+\-*/%()^!&|<>=,. ]+$/.test(e))return NaN;try{let n=Function(`"use strict"; return (${e.replace(/\*\*/g,"**")});`)();return typeof n=="number"?Math.trunc(n):NaN}catch{return NaN}}function ks(r,t){let e=[],n=0;for(;n<r.length;){let i=r.indexOf("'",n);if(i===-1){e.push(t(r.slice(n)));break}e.push(t(r.slice(n,i)));let s=r.indexOf("'",i+1);if(s===-1){e.push(r.slice(i));break}e.push(r.slice(i,s+1)),n=s+1}return e.join("")}function he(r,t,e=0,n){let i=n??t.HOME??"/home/user";return ks(r,s=>{let o=s;return o=o.replace(/(^|[\s:])~(\/|$)/g,(a,l,c)=>`${l}${i}${c}`),o=o.replace(/\$\?/g,String(e)),o=o.replace(/\$\$/g,"1"),o=o.replace(/\$#/g,"0"),o=o.replace(/\$\(\(([^)]+(?:\([^)]*\)[^)]*)*)\)\)/g,(a,l)=>{let c=Ps(l,t);return Number.isNaN(c)?"0":String(c)}),o=o.replace(/\$\{#([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,l)=>String((t[l]??"").length)),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):-([^}]*)\}/g,(a,l,c)=>t[l]!==void 0&&t[l]!==""?t[l]:c),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):=([^}]*)\}/g,(a,l,c)=>((t[l]===void 0||t[l]==="")&&(t[l]=c),t[l])),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):\+([^}]*)\}/g,(a,l,c)=>t[l]!==void 0&&t[l]!==""?c:""),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,l)=>t[l]??""),o=o.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(a,l)=>t[l]??""),o})}async function qt(r,t,e,n){if(r.includes("$(")){let i="",s=!1,o=0;for(;o<r.length;){let a=r[o];if(a==="'"&&!s){s=!0,i+=a,o++;continue}if(a==="'"&&s){s=!1,i+=a,o++;continue}if(!s&&a==="$"&&r[o+1]==="("){if(r[o+2]==="("){i+=a,o++;continue}let l=0,c=o+1;for(;c<r.length;){if(r[c]==="(")l++;else if(r[c]===")"&&(l--,l===0))break;c++}let u=r.slice(o+2,c).trim(),d=(await n(u)).replace(/\n$/,"");i+=d,o=c+1;continue}i+=a,o++}r=i}return he(r,t,e)}function Ms(r){return r.replace(/\\n/g,`
64
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\").replace(/\\a/g,"\x07").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\v/g,"\v").replace(/\\0(\d{1,3})/g,(t,e)=>String.fromCharCode(parseInt(e,8)))}var lr={name:"echo",description:"Display text",category:"shell",params:["[-n] [-e] [text...]"],run:({args:r,stdin:t,env:e})=>{let{flags:n,positionals:i}=nt(r,{flags:["-n","-e","-E"]}),s=n.has("-n"),o=n.has("-e"),a=i.length>0?i.join(" "):t??"",l=he(a,e?.vars??{},e?.lastExitCode??0),c=o?Ms(l):l;return{stdout:s?c:`${c}
65
- `,exitCode:0}}};var cr={name:"env",description:"Print environment variables",category:"shell",params:[],run:({env:r,authUser:t})=>{let e={...r.vars,USER:t,HOME:`/home/${t}`};return{stdout:Object.entries(e).map(([n,i])=>`${n}=${i}`).join(`
66
- `),exitCode:0}}};var ur={name:"exit",aliases:["bye"],description:"Exit the shell session",category:"shell",params:["[code]"],run:({args:r})=>({closeSession:!0,exitCode:parseInt(r[0]??"0",10)||0})};var dr={name:"export",description:"Set shell environment variable",category:"shell",params:["[VAR=value]"],run:({args:r,env:t})=>{if(r.length===0)return{stdout:Object.entries(t.vars).map(([n,i])=>`declare -x ${n}="${i}"`).join(`
67
- `),exitCode:0};for(let e of r)if(e.includes("=")){let n=e.indexOf("="),i=e.slice(0,n),s=e.slice(n+1);t.vars[i]=s}return{exitCode:0}}};var mr={name:"find",description:"Search for files",category:"files",params:["[path] [-name <pattern>] [-type f|d]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=st(n,["-name"]),s=st(n,["-type"]),a=n.filter(m=>!m.startsWith("-")&&m!==i&&m!==s)[0]??".",l=x(e,a);try{if(_(r,l,"find"),!t.vfs.exists(l))return{stderr:`find: ${a}: No such file or directory`,exitCode:1}}catch(m){return{stderr:`find: ${m instanceof Error?m.message:String(m)}`,exitCode:1}}let c=i?new RegExp(`^${i.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`):null,u=[],d=(m,p)=>{let w=t.vfs.stat(m),g=!s||s==="f"&&w.type==="file"||s==="d"&&w.type==="directory",f=!c||c.test(m.split("/").pop()??"");if(g&&f&&u.push(p),w.type==="directory")for(let $ of t.vfs.list(m)){let E=`${m}/${$}`,F=`${p}/${$}`;d(E,F)}};return d(l,a),{stdout:u.join(`
68
- `),exitCode:0}}};import*as Kt from"node:os";var pr={name:"free",description:"Display amount of free and used memory",category:"system",params:["[-h] [-m] [-g]"],run:({args:r})=>{let t=y(r,["-h","--human"]),e=y(r,["-m"]),n=y(r,["-g"]),i=Kt.totalmem(),s=Kt.freemem(),o=i-s,a=Math.floor(i*.02),l=Math.floor(i*.05),c=Math.floor(s*.95),u=Math.floor(i*.5),d=g=>t?g>=1024*1024*1024?`${(g/(1024*1024*1024)).toFixed(1)}G`:g>=1024*1024?`${(g/(1024*1024)).toFixed(1)}M`:`${(g/1024).toFixed(1)}K`:String(Math.floor(n?g/(1024*1024*1024):e?g/(1024*1024):g/1024)),m=" total used free shared buff/cache available",p=`Mem: ${d(i).padStart(12)} ${d(o).padStart(11)} ${d(s).padStart(11)} ${d(a).padStart(11)} ${d(l).padStart(11)} ${d(c).padStart(11)}`,w=`Swap: ${d(u).padStart(12)} ${d(0).padStart(11)} ${d(u).padStart(11)}`;return{stdout:[m,p,w].join(`
69
- `),exitCode:0}}};var fr={name:"grep",description:"Search text patterns",category:"text",params:["[-i] [-v] [-n] [-r] <pattern> [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let{flags:s,positionals:o}=nt(n,{flags:["-i","-v","-n","-r","-c","-l","-L","-q","--quiet","--silent"]}),a=s.has("-i"),l=s.has("-v"),c=s.has("-n"),u=s.has("-r"),d=s.has("-c"),m=s.has("-l"),p=s.has("-q")||s.has("--quiet")||s.has("--silent"),w=o[0],g=o.slice(1);if(!w)return{stderr:"grep: no pattern specified",exitCode:1};let f;try{let S=a?"mi":"m";f=new RegExp(w,S)}catch{return{stderr:`grep: invalid regex: ${w}`,exitCode:1}}let $=(S,k="")=>{let V=S.split(`
70
- `),b=[];for(let P=0;P<V.length;P++){let R=V[P]??"",v=f.test(R);if(l?!v:v){let N=c?`${P+1}:`:"";b.push(`${k}${N}${R}`)}}return b},E=S=>{if(!t.vfs.exists(S))return[];if(t.vfs.stat(S).type==="file")return[S];if(!u)return[];let V=[],b=P=>{for(let R of t.vfs.list(P)){let v=`${P}/${R}`;t.vfs.stat(v).type==="file"?V.push(v):b(v)}};return b(S),V},F=[];if(g.length===0){if(!i)return{stdout:"",exitCode:1};let S=$(i);if(d)return{stdout:`${S.length}
71
- `,exitCode:S.length>0?0:1};if(p)return{exitCode:S.length>0?0:1};F.push(...S)}else{let S=g.flatMap(k=>{let V=x(e,k);return E(V).map(b=>({file:k,path:b}))});for(let{file:k,path:V}of S)try{_(r,V,"grep");let b=t.vfs.readFile(V),P=S.length>1?`${k}:`:"",R=$(b,P);d?F.push(S.length>1?`${k}:${R.length}`:String(R.length)):m?R.length>0&&F.push(k):F.push(...R)}catch{return{stderr:`grep: ${k}: No such file or directory`,exitCode:1}}}return{stdout:F.length>0?`${F.join(`
62
+ `)||"(no packages match)",exitCode:0}}return{stderr:"dpkg-query: need a flag (-l, -W)",exitCode:1}}};var ur={name:"du",description:"Estimate file space usage",category:"system",params:["[-h] [-s] [path]"],run:({shell:r,cwd:t,args:e})=>{let n=w(e,["-h"]),i=w(e,["-s"]),s=e.find(u=>!u.startsWith("-"))??".",o=S(t,s),a=u=>n?`${(u/1024).toFixed(1)}K`:String(Math.ceil(u/1024));if(!r.vfs.exists(o))return{stderr:`du: ${s}: No such file or directory`,exitCode:1};if(i||r.vfs.stat(o).type==="file")return{stdout:`${a(r.vfs.getUsageBytes(o))} ${s}`,exitCode:0};let l=[],c=(u,d)=>{let m=0;for(let p of r.vfs.list(u)){let y=`${u}/${p}`,g=`${d}/${p}`,f=r.vfs.stat(y);f.type==="directory"?m+=c(y,g):(m+=f.size,i||l.push(`${a(f.size)} ${g}`))}return l.push(`${a(m)} ${d}`),m};return c(o,s),{stdout:l.join(`
63
+ `),exitCode:0}}};kt();function _s(r){return r.replace(/\\n/g,`
64
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\").replace(/\\a/g,"\x07").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\v/g,"\v").replace(/\\0(\d{1,3})/g,(t,e)=>String.fromCharCode(parseInt(e,8)))}var mr={name:"echo",description:"Display text",category:"shell",params:["[-n] [-e] [text...]"],run:({args:r,stdin:t,env:e})=>{let{flags:n,positionals:i}=st(r,{flags:["-n","-e","-E"]}),s=n.has("-n"),o=n.has("-e"),a=i.length>0?i.join(" "):t??"",l=Zt(a,e?.vars??{},e?.lastExitCode??0),c=o?_s(l):l;return{stdout:s?c:`${c}
65
+ `,exitCode:0}}};var pr={name:"env",description:"Print environment variables",category:"shell",params:[],run:({env:r,authUser:t})=>{let e={...r.vars,USER:t,HOME:`/home/${t}`};return{stdout:Object.entries(e).map(([n,i])=>`${n}=${i}`).join(`
66
+ `),exitCode:0}}};var fr={name:"exit",aliases:["bye"],description:"Exit the shell session",category:"shell",params:["[code]"],run:({args:r})=>({closeSession:!0,exitCode:parseInt(r[0]??"0",10)||0})};var hr={name:"export",description:"Set shell environment variable",category:"shell",params:["[VAR=value]"],run:({args:r,env:t})=>{if(r.length===0||r.length===1&&r[0]==="-p"){let e=Object.entries(t.vars).filter(([n])=>n&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)).map(([n,i])=>`declare -x ${n}="${i}"`).join(`
67
+ `);return{stdout:e?`${e}
68
+ `:"",exitCode:0}}for(let e of r.filter(n=>n!=="-p"))if(e.includes("=")){let n=e.indexOf("="),i=e.slice(0,n),s=e.slice(n+1);t.vars[i]=s}return{exitCode:0}}};var gr={name:"find",description:"Search for files",category:"files",params:["[path] [-name <pattern>] [-type f|d]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=it(n,["-name"]),s=it(n,["-type"]),a=n.filter(m=>!m.startsWith("-")&&m!==i&&m!==s)[0]??".",l=S(e,a);try{if(D(r,l,"find"),!t.vfs.exists(l))return{stderr:`find: ${a}: No such file or directory`,exitCode:1}}catch(m){return{stderr:`find: ${m instanceof Error?m.message:String(m)}`,exitCode:1}}let c=i?new RegExp(`^${i.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`):null,u=[],d=(m,p)=>{let y=t.vfs.stat(m),g=!s||s==="f"&&y.type==="file"||s==="d"&&y.type==="directory",f=!c||c.test(m.split("/").pop()??"");if(g&&f&&u.push(p),y.type==="directory")for(let $ of t.vfs.list(m)){let N=`${m}/${$}`,M=`${p}/${$}`;d(N,M)}};return d(l,a),{stdout:u.join(`
69
+ `),exitCode:0}}};import*as Jt from"node:os";var yr={name:"free",description:"Display amount of free and used memory",category:"system",params:["[-h] [-m] [-g]"],run:({args:r})=>{let t=w(r,["-h","--human"]),e=w(r,["-m"]),n=w(r,["-g"]),i=Jt.totalmem(),s=Jt.freemem(),o=i-s,a=Math.floor(i*.02),l=Math.floor(i*.05),c=Math.floor(s*.95),u=Math.floor(i*.5),d=g=>t?g>=1024*1024*1024?`${(g/(1024*1024*1024)).toFixed(1)}G`:g>=1024*1024?`${(g/(1024*1024)).toFixed(1)}M`:`${(g/1024).toFixed(1)}K`:String(Math.floor(n?g/(1024*1024*1024):e?g/(1024*1024):g/1024)),m=" total used free shared buff/cache available",p=`Mem: ${d(i).padStart(12)} ${d(o).padStart(11)} ${d(s).padStart(11)} ${d(a).padStart(11)} ${d(l).padStart(11)} ${d(c).padStart(11)}`,y=`Swap: ${d(u).padStart(12)} ${d(0).padStart(11)} ${d(u).padStart(11)}`;return{stdout:[m,p,y].join(`
70
+ `),exitCode:0}}};var wr={name:"grep",description:"Search text patterns",category:"text",params:["[-i] [-v] [-n] [-r] <pattern> [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let{flags:s,positionals:o}=st(n,{flags:["-i","-v","-n","-r","-c","-l","-L","-q","--quiet","--silent"]}),a=s.has("-i"),l=s.has("-v"),c=s.has("-n"),u=s.has("-r"),d=s.has("-c"),m=s.has("-l"),p=s.has("-q")||s.has("--quiet")||s.has("--silent"),y=o[0],g=o.slice(1);if(!y)return{stderr:"grep: no pattern specified",exitCode:1};let f;try{let x=a?"mi":"m";f=new RegExp(y,x)}catch{return{stderr:`grep: invalid regex: ${y}`,exitCode:1}}let $=(x,k="")=>{let A=x.split(`
71
+ `),b=[];for(let P=0;P<A.length;P++){let R=A[P]??"",v=f.test(R);if(l?!v:v){let I=c?`${P+1}:`:"";b.push(`${k}${I}${R}`)}}return b},N=x=>{if(!t.vfs.exists(x))return[];if(t.vfs.stat(x).type==="file")return[x];if(!u)return[];let A=[],b=P=>{for(let R of t.vfs.list(P)){let v=`${P}/${R}`;t.vfs.stat(v).type==="file"?A.push(v):b(v)}};return b(x),A},M=[];if(g.length===0){if(!i)return{stdout:"",exitCode:1};let x=$(i);if(d)return{stdout:`${x.length}
72
+ `,exitCode:x.length>0?0:1};if(p)return{exitCode:x.length>0?0:1};M.push(...x)}else{let x=g.flatMap(k=>{let A=S(e,k);return N(A).map(b=>({file:k,path:b}))});for(let{file:k,path:A}of x)try{D(r,A,"grep");let b=t.vfs.readFile(A),P=x.length>1?`${k}:`:"",R=$(b,P);d?M.push(x.length>1?`${k}:${R.length}`:String(R.length)):m?R.length>0&&M.push(k):M.push(...R)}catch{return{stderr:`grep: ${k}: No such file or directory`,exitCode:1}}}return{stdout:M.length>0?`${M.join(`
72
73
  `)}
73
- `:"",exitCode:F.length>0?0:1}}};var hr={name:"groups",description:"Print group memberships",category:"system",params:["[user]"],run:({authUser:r,shell:t,args:e})=>{let n=e[0]??r;return{stdout:t.users.isSudoer(n)?`${n} sudo root`:n,exitCode:0}}};var gr={name:"gzip",description:"Compress files",category:"archive",params:["[-k] [-d] <file>"],run:({shell:r,cwd:t,args:e})=>{if(!r.packageManager.isInstalled("gzip"))return{stderr:`bash: gzip: command not found
74
+ `:"",exitCode:M.length>0?0:1}}};var Sr={name:"groups",description:"Print group memberships",category:"system",params:["[user]"],run:({authUser:r,shell:t,args:e})=>{let n=e[0]??r;return{stdout:t.users.isSudoer(n)?`${n} sudo root`:n,exitCode:0}}};var xr={name:"gzip",description:"Compress files",category:"archive",params:["[-k] [-d] <file>"],run:({shell:r,cwd:t,args:e})=>{if(!r.packageManager.isInstalled("gzip"))return{stderr:`bash: gzip: command not found
74
75
  Hint: install it with: apt install gzip
75
76
  `,exitCode:127};let n=e.includes("-k")||e.includes("--keep"),i=e.includes("-d"),s=e.find(c=>!c.startsWith("-"));if(!s)return{stderr:`gzip: no file specified
76
- `,exitCode:1};let o=x(t,s);if(i){if(!s.endsWith(".gz"))return{stderr:`gzip: ${s}: unknown suffix -- ignored
77
+ `,exitCode:1};let o=S(t,s);if(i){if(!s.endsWith(".gz"))return{stderr:`gzip: ${s}: unknown suffix -- ignored
77
78
  `,exitCode:1};if(!r.vfs.exists(o))return{stderr:`gzip: ${s}: No such file or directory
78
79
  `,exitCode:1};let c=r.vfs.readFile(o),u=o.slice(0,-3);return r.vfs.writeFile(u,c),n||r.vfs.remove(o),{exitCode:0}}if(!r.vfs.exists(o))return{stderr:`gzip: ${s}: No such file or directory
79
80
  `,exitCode:1};if(s.endsWith(".gz"))return{stderr:`gzip: ${s}: already has .gz suffix -- unchanged
80
- `,exitCode:1};let a=r.vfs.readFileRaw(o),l=`${o}.gz`;return r.vfs.writeFile(l,a,{compress:!0}),n||r.vfs.remove(o),{exitCode:0}}},yr={name:"gunzip",description:"Decompress files",category:"archive",aliases:["zcat"],params:["[-k] <file>"],run:({shell:r,cwd:t,args:e})=>{let n=e.includes("-k")||e.includes("--keep"),i=e.find(l=>!l.startsWith("-"));if(!i)return{stderr:`gunzip: no file specified
81
- `,exitCode:1};let s=x(t,i);if(!r.vfs.exists(s))return{stderr:`gunzip: ${i}: No such file or directory
81
+ `,exitCode:1};let a=r.vfs.readFileRaw(o),l=`${o}.gz`;return r.vfs.writeFile(l,a,{compress:!0}),n||r.vfs.remove(o),{exitCode:0}}},br={name:"gunzip",description:"Decompress files",category:"archive",aliases:["zcat"],params:["[-k] <file>"],run:({shell:r,cwd:t,args:e})=>{let n=e.includes("-k")||e.includes("--keep"),i=e.find(l=>!l.startsWith("-"));if(!i)return{stderr:`gunzip: no file specified
82
+ `,exitCode:1};let s=S(t,i);if(!r.vfs.exists(s))return{stderr:`gunzip: ${i}: No such file or directory
82
83
  `,exitCode:1};if(!i.endsWith(".gz"))return{stderr:`gunzip: ${i}: unknown suffix -- ignored
83
- `,exitCode:1};let o=r.vfs.readFile(s),a=s.slice(0,-3);return r.vfs.writeFile(a,o),n||r.vfs.remove(s),{exitCode:0}}};var wr={name:"head",description:"Output first lines",category:"text",params:["[-n <lines>] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=st(n,["-n"]),o=n.find(d=>/^-\d+$/.test(d)),a=typeof s=="string"?parseInt(s,10):o?parseInt(o.slice(1),10):10,l=n.filter(d=>!d.startsWith("-")&&d!==s&&d!==String(a)),c=d=>{let m=d.split(`
84
+ `,exitCode:1};let o=r.vfs.readFile(s),a=s.slice(0,-3);return r.vfs.writeFile(a,o),n||r.vfs.remove(s),{exitCode:0}}};var vr={name:"head",description:"Output first lines",category:"text",params:["[-n <lines>] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=it(n,["-n"]),o=n.find(d=>/^-\d+$/.test(d)),a=typeof s=="string"?parseInt(s,10):o?parseInt(o.slice(1),10):10,l=n.filter(d=>!d.startsWith("-")&&d!==s&&d!==String(a)),c=d=>{let m=d.split(`
84
85
  `),p=m.slice(0,a);return p.join(`
85
86
  `)+(d.endsWith(`
86
87
  `)&&p.length===m.slice(0,a).length?`
87
- `:"")};if(l.length===0)return{stdout:c(i??""),exitCode:0};let u=[];for(let d of l){let m=x(e,d);try{_(r,m,"head"),u.push(c(t.vfs.readFile(m)))}catch{return{stderr:`head: ${d}: No such file or directory`,exitCode:1}}}return{stdout:u.join(`
88
- `),exitCode:0}}};var Sr=["navigation","files","text","archive","system","package","network","shell","users","misc"],br={navigation:"Navigation",files:"Files & Filesystem",text:"Text Processing",archive:"Archive & Compression",system:"System",package:"Package Management",network:"Network",shell:"Shell & Scripting",users:"Users & Permissions",misc:"Miscellaneous"},Cr="\x1B[1m",dt="\x1B[0m",Fs="\x1B[36m",As="\x1B[33m",Vt="\x1B[2m",Es="\x1B[32m";function xr(r,t){return r.length>=t?r:r+" ".repeat(t-r.length)}function Ns(r){let t=r.aliases?.length?` ${Vt}(${r.aliases.join(", ")})${dt}`:"";return` ${Fs}${xr(r.name,16)}${dt}${t}${xr("",(r.aliases?.length,0))} ${r.description??""}`}function Is(r){let t={};for(let s of r){let o=s.category??"misc";t[o]||(t[o]=[]),t[o].push(s)}let e=[`${Cr}Available commands${dt}`,`${Vt}Type 'help <command>' for detailed usage.${dt}`,""],n=[...Sr.filter(s=>t[s]),...Object.keys(t).filter(s=>!Sr.includes(s)).sort()];for(let s of n){let o=t[s];if(!o?.length)continue;e.push(`${As}${br[s]??s}${dt}`);let a=[...o].sort((l,c)=>l.name.localeCompare(c.name));for(let l of a)e.push(Ns(l));e.push("")}let i=r.length;return e.push(`${Vt}${i} commands available.${dt}`),e.join(`
89
- `)}function Vs(r){let t=[];if(t.push(`${Cr}${r.name}${dt} \u2014 ${r.description??"no description"}`),r.aliases?.length&&t.push(`${Vt}Aliases: ${r.aliases.join(", ")}${dt}`),t.push(""),t.push(`${Es}Usage:${dt}`),r.params.length)for(let n of r.params)t.push(` ${r.name} ${n}`);else t.push(` ${r.name}`);let e=br[r.category??"misc"]??r.category??"misc";return t.push(""),t.push(`${Vt}Category: ${e}${dt}`),t.join(`
90
- `)}function vr(r){return{name:"help",description:"List all commands, or show usage for a specific command",category:"shell",params:["[command]"],run:({args:t})=>{let e=ge();if(t[0]){let n=t[0].toLowerCase(),i=e.find(s=>s.name===n||s.aliases?.includes(n));return i?{stdout:Vs(i),exitCode:0}:{stderr:`help: no help entry for '${t[0]}'`,exitCode:1}}return{stdout:Is(e),exitCode:0}}}}var $r={name:"history",description:"Display command history",category:"shell",params:["[n]"],run:({args:r,shell:t,authUser:e})=>{let n=`/home/${e}/.bash_history`;if(!t.vfs.exists(n))return{stdout:"",exitCode:0};let s=t.vfs.readFile(n).split(`
88
+ `:"")};if(l.length===0)return{stdout:c(i??""),exitCode:0};let u=[];for(let d of l){let m=S(e,d);try{D(r,m,"head"),u.push(c(t.vfs.readFile(m)))}catch{return{stderr:`head: ${d}: No such file or directory`,exitCode:1}}}return{stdout:u.join(`
89
+ `),exitCode:0}}};var Cr=["navigation","files","text","archive","system","package","network","shell","users","misc"],Pr={navigation:"Navigation",files:"Files & Filesystem",text:"Text Processing",archive:"Archive & Compression",system:"System",package:"Package Management",network:"Network",shell:"Shell & Scripting",users:"Users & Permissions",misc:"Miscellaneous"},kr="\x1B[1m",ft="\x1B[0m",Ds="\x1B[36m",zs="\x1B[33m",Dt="\x1B[2m",Ls="\x1B[32m";function $r(r,t){return r.length>=t?r:r+" ".repeat(t-r.length)}function Ts(r){let t=r.aliases?.length?` ${Dt}(${r.aliases.join(", ")})${ft}`:"";return` ${Ds}${$r(r.name,16)}${ft}${t}${$r("",(r.aliases?.length,0))} ${r.description??""}`}function Us(r){let t={};for(let s of r){let o=s.category??"misc";t[o]||(t[o]=[]),t[o].push(s)}let e=[`${kr}Available commands${ft}`,`${Dt}Type 'help <command>' for detailed usage.${ft}`,""],n=[...Cr.filter(s=>t[s]),...Object.keys(t).filter(s=>!Cr.includes(s)).sort()];for(let s of n){let o=t[s];if(!o?.length)continue;e.push(`${zs}${Pr[s]??s}${ft}`);let a=[...o].sort((l,c)=>l.name.localeCompare(c.name));for(let l of a)e.push(Ts(l));e.push("")}let i=r.length;return e.push(`${Dt}${i} commands available.${ft}`),e.join(`
90
+ `)}function Bs(r){let t=[];if(t.push(`${kr}${r.name}${ft} \u2014 ${r.description??"no description"}`),r.aliases?.length&&t.push(`${Dt}Aliases: ${r.aliases.join(", ")}${ft}`),t.push(""),t.push(`${Ls}Usage:${ft}`),r.params.length)for(let n of r.params)t.push(` ${r.name} ${n}`);else t.push(` ${r.name}`);let e=Pr[r.category??"misc"]??r.category??"misc";return t.push(""),t.push(`${Dt}Category: ${e}${ft}`),t.join(`
91
+ `)}function Mr(r){return{name:"help",description:"List all commands, or show usage for a specific command",category:"shell",params:["[command]"],run:({args:t})=>{let e=Se();if(t[0]){let n=t[0].toLowerCase(),i=e.find(s=>s.name===n||s.aliases?.includes(n));return i?{stdout:Bs(i),exitCode:0}:{stderr:`help: no help entry for '${t[0]}'`,exitCode:1}}return{stdout:Us(e),exitCode:0}}}}var Fr={name:"history",description:"Display command history",category:"shell",params:["[n]"],run:({args:r,shell:t,authUser:e})=>{let n=`/home/${e}/.bash_history`;if(!t.vfs.exists(n))return{stdout:"",exitCode:0};let s=t.vfs.readFile(n).split(`
91
92
  `).filter(Boolean),o=r[0],a=o?parseInt(o,10):null,l=a&&!Number.isNaN(a)?s.slice(-a):s,c=s.length-l.length+1;return{stdout:l.map((d,m)=>`${String(c+m).padStart(5)} ${d}`).join(`
92
- `),exitCode:0}}};var Pr={name:"hostname",description:"Print hostname",category:"system",params:[],run:({hostname:r})=>({stdout:r,exitCode:0})};var kr={name:"htop",description:"System monitor",category:"system",params:[],run:({mode:r})=>r==="exec"?{stderr:"htop: interactive terminal required",exitCode:1}:{openHtop:!0,exitCode:0}};var Mr={name:"id",description:"Print user identity",category:"system",params:["[user]"],run:({authUser:r,shell:t,args:e})=>{let n=e[0]??r,i=n==="root"?0:1e3,s=i,a=t.users.isSudoer(n)?`${s}(${n}),0(root)`:`${s}(${n})`;return{stdout:`uid=${i}(${n}) gid=${s}(${n}) groups=${a}`,exitCode:0}}};var Fr={name:"kill",description:"Send signal to process",category:"system",params:["[-9] <pid>"],run:({args:r})=>r.find(e=>!e.startsWith("-"))?{stdout:"",exitCode:0}:{stderr:"kill: no pid specified",exitCode:1}};var Ar={name:"ln",description:"Create links",category:"files",params:["[-s] <target> <link_name>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=y(n,["-s","--symbolic"]),s=n.filter(u=>!u.startsWith("-")),[o,a]=s;if(!o||!a)return{stderr:"ln: missing operand",exitCode:1};let l=x(e,a),c=i?o:x(e,o);try{if(_(r,l,"ln"),i)t.vfs.symlink(c,l);else{let u=x(e,o);if(_(r,u,"ln"),!t.vfs.exists(u))return{stderr:`ln: ${o}: No such file or directory`,exitCode:1};let d=t.vfs.readFile(u);t.writeFileAsUser(r,l,d)}return{exitCode:0}}catch(u){return{stderr:`ln: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}},Er={name:"readlink",description:"Print resolved path of symbolic link",category:"files",params:["[-f] <path>"],run:({shell:r,cwd:t,args:e})=>{let n=e.includes("-f")||e.includes("-e"),i=e.find(a=>!a.startsWith("-"));if(!i)return{stderr:`readlink: missing operand
93
- `,exitCode:1};let s=x(t,i);return r.vfs.exists(s)?r.vfs.isSymlink(s)?{stdout:`${r.vfs.resolveSymlink(s)}
93
+ `),exitCode:0}}};var Ar={name:"hostname",description:"Print hostname",category:"system",params:[],run:({hostname:r})=>({stdout:r,exitCode:0})};var Er={name:"htop",description:"System monitor",category:"system",params:[],run:({mode:r})=>r==="exec"?{stderr:"htop: interactive terminal required",exitCode:1}:{openHtop:!0,exitCode:0}};var Nr={name:"id",description:"Print user identity",category:"system",params:["[user]"],run:({authUser:r,shell:t,args:e})=>{let n=e[0]??r,i=n==="root"?0:1e3,s=i,a=t.users.isSudoer(n)?`${s}(${n}),0(root)`:`${s}(${n})`;return{stdout:`uid=${i}(${n}) gid=${s}(${n}) groups=${a}`,exitCode:0}}};var Ir={name:"kill",description:"Send signal to process",category:"system",params:["[-9] <pid>"],run:({args:r})=>r.find(e=>!e.startsWith("-"))?{stdout:"",exitCode:0}:{stderr:"kill: no pid specified",exitCode:1}};var Vr={name:"ln",description:"Create links",category:"files",params:["[-s] <target> <link_name>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=w(n,["-s","--symbolic"]),s=n.filter(u=>!u.startsWith("-")),[o,a]=s;if(!o||!a)return{stderr:"ln: missing operand",exitCode:1};let l=S(e,a),c=i?o:S(e,o);try{if(D(r,l,"ln"),i)t.vfs.symlink(c,l);else{let u=S(e,o);if(D(r,u,"ln"),!t.vfs.exists(u))return{stderr:`ln: ${o}: No such file or directory`,exitCode:1};let d=t.vfs.readFile(u);t.writeFileAsUser(r,l,d)}return{exitCode:0}}catch(u){return{stderr:`ln: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}},Rr={name:"readlink",description:"Print resolved path of symbolic link",category:"files",params:["[-f] <path>"],run:({shell:r,cwd:t,args:e})=>{let n=e.includes("-f")||e.includes("-e"),i=e.find(a=>!a.startsWith("-"));if(!i)return{stderr:`readlink: missing operand
94
+ `,exitCode:1};let s=S(t,i);return r.vfs.exists(s)?r.vfs.isSymlink(s)?{stdout:`${r.vfs.resolveSymlink(s)}
94
95
  `,exitCode:0}:{stderr:`readlink: ${i}: not a symbolic link
95
96
  `,exitCode:1}:{stderr:`readlink: ${i}: No such file or directory
96
- `,exitCode:1}}};var Nr={name:"stat",description:"Display file status",category:"files",params:["[-c <format>] <file>"],run:({shell:r,cwd:t,args:e})=>{let n=e.findIndex($=>$==="-c"||$==="--format"),i=n!==-1?e[n+1]:void 0,s=e.find($=>!$.startsWith("-")&&$!==i);if(!s)return{stderr:`stat: missing operand
97
- `,exitCode:1};let o=x(t,s);if(!r.vfs.exists(o))return{stderr:`stat: cannot stat '${s}': No such file or directory
98
- `,exitCode:1};let a=r.vfs.stat(o),l=a.type==="directory",c=r.vfs.isSymlink(o),u=r.vfs.isSymlink(o),d=$=>{let E=[256,128,64,32,16,8,4,2,1],F=["r","w","x","r","w","x","r","w","x"];return(l?"d":u?"l":"-")+E.map((S,k)=>$&S?F[k]:"-").join("")},m=a.mode.toString(8).padStart(4,"0"),p=d(a.mode),w="size"in a?a.size:0,g=$=>$.toISOString().replace("T"," ").replace(/\.\d+Z$/," +0000");return i?{stdout:`${i.replace("%n",s).replace("%s",String(w)).replace("%a",m.slice(1)).replace("%A",p).replace("%F",u?"symbolic link":l?"directory":"regular file").replace("%y",g(a.updatedAt)).replace("%z",g(a.updatedAt))}
99
- `,exitCode:0}:{stdout:`${[` File: ${s}${u?` -> ${r.vfs.resolveSymlink(o)}`:""}`,` Size: ${w}${" ".repeat(3)}${u?"symbolic link":l?"directory":"regular file"}`,`Access: (${m}/${p}) Uid: ( 0/ root) Gid: ( 0/ root)`,`Modify: ${g(a.updatedAt)}`,`Change: ${g(a.updatedAt)}`].join(`
97
+ `,exitCode:1}}};var _r={name:"seq",description:"Print a sequence of numbers",category:"text",params:["[FIRST [INCREMENT]] LAST"],run:({args:r})=>{let t=r.filter(d=>!d.startsWith("-")||/^-[\d.]/.test(d)).map(Number),e=(()=>{let d=r.indexOf("-s");return d!==-1?r[d+1]??`
98
+ `:`
99
+ `})(),n=(()=>{let d=r.indexOf("-f");return d!==-1?r[d+1]??"%g":null})(),i=r.includes("-w"),s=1,o=1,a;if(t.length===1?a=t[0]:t.length===2?(s=t[0],a=t[1]):(s=t[0],o=t[1],a=t[2]),o===0)return{stderr:`seq: zero increment
100
+ `,exitCode:1};if(o>0&&s>a||o<0&&s<a)return{stdout:"",exitCode:0};let l=[],c=1e5,u=0;for(let d=s;(o>0?d<=a:d>=a)&&!(++u>c);d=Math.round((d+o)*1e10)/1e10){let m;if(n?m=n.replace("%g",String(d)).replace("%f",d.toFixed(6)).replace("%d",String(Math.trunc(d))):m=Number.isInteger(d)?String(d):d.toPrecision(12).replace(/\.?0+$/,""),i){let p=String(Math.trunc(a)).length;m=m.padStart(p,"0")}l.push(m)}return{stdout:`${l.join(e)}
101
+ `,exitCode:0}}};var Dr={name:"stat",description:"Display file status",category:"files",params:["[-c <format>] <file>"],run:({shell:r,cwd:t,args:e})=>{let n=e.findIndex($=>$==="-c"||$==="--format"),i=n!==-1?e[n+1]:void 0,s=e.find($=>!$.startsWith("-")&&$!==i);if(!s)return{stderr:`stat: missing operand
102
+ `,exitCode:1};let o=S(t,s);if(!r.vfs.exists(o))return{stderr:`stat: cannot stat '${s}': No such file or directory
103
+ `,exitCode:1};let a=r.vfs.stat(o),l=a.type==="directory",c=r.vfs.isSymlink(o),u=r.vfs.isSymlink(o),d=$=>{let N=[256,128,64,32,16,8,4,2,1],M=["r","w","x","r","w","x","r","w","x"];return(l?"d":u?"l":"-")+N.map((x,k)=>$&x?M[k]:"-").join("")},m=a.mode.toString(8).padStart(4,"0"),p=d(a.mode),y="size"in a?a.size:0,g=$=>$.toISOString().replace("T"," ").replace(/\.\d+Z$/," +0000");return i?{stdout:`${i.replace("%n",s).replace("%s",String(y)).replace("%a",m.slice(1)).replace("%A",p).replace("%F",u?"symbolic link":l?"directory":"regular file").replace("%y",g(a.updatedAt)).replace("%z",g(a.updatedAt))}
104
+ `,exitCode:0}:{stdout:`${[` File: ${s}${u?` -> ${r.vfs.resolveSymlink(o)}`:""}`,` Size: ${y}${" ".repeat(3)}${u?"symbolic link":l?"directory":"regular file"}`,`Access: (${m}/${p}) Uid: ( 0/ root) Gid: ( 0/ root)`,`Modify: ${g(a.updatedAt)}`,`Change: ${g(a.updatedAt)}`].join(`
100
105
  `)}
101
- `,exitCode:0}}};function Ir(r,t){let e=t?"d":"-",i=[[256,"r"],[128,"w"],[64,"x"],[32,"r"],[16,"w"],[8,"x"],[4,"r"],[2,"w"],[1,"x"]].map(([s,o])=>r&s?o:"-").join("");return`${e}${i}`}function Vr(r){return r.toISOString().replace("T"," ").slice(0,16)}var Rr={name:"ls",description:"List directory contents",category:"navigation",params:["[-la] [path]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=y(n,["-l","--long"]),s=y(n,["-a","--all"]),o=St(n,0,{flags:["-l","--long","-a","--all","-la","-al"]}),a=x(e,o??e);if(_(r,a,"ls"),t.vfs.exists(a)){let u=t.vfs.stat(a);if(u.type==="file"||t.vfs.isSymlink(a)){if(i){let d=a.split("/").pop()??a,m=u.type==="file"?u.size:0;return{stdout:`${Ir(u.mode,!1)} 1 root root ${m} ${Vr(u.updatedAt)} ${d}
102
- `,exitCode:0}}return{stdout:a.split("/").pop()??a,exitCode:0}}}let l=t.vfs.list(a).filter(u=>s||!u.startsWith("."));return{stdout:i?l.map(u=>{let d=x(a,u),m=t.vfs.stat(d),p=m.type==="file"?m.size:m.childrenCount;return`${Ir(m.mode,m.type==="directory")} 1 ${p} ${Vr(m.updatedAt)} ${u}${m.type==="directory"?"/":""}`}).join(`
103
- `):We(a,l,u=>t.vfs.stat(u)),exitCode:0}}};var Dr={name:"lsb_release",description:"Print distribution-specific information",category:"system",params:["[-a] [-i] [-d] [-r] [-c]"],run:({args:r,shell:t})=>{let e=t.properties?.os??"Fortune GNU/Linux x64",n="aurora",i="1.0";try{let d=t.vfs.readFile("/etc/os-release");for(let m of d.split(`
104
- `))m.startsWith("PRETTY_NAME=")&&(e=m.slice(12).replace(/^"|"$/g,"").trim()),m.startsWith("VERSION_CODENAME=")&&(n=m.slice(17).trim()),m.startsWith("VERSION_ID=")&&(i=m.slice(11).replace(/^"|"$/g,"").trim())}catch{}let s=y(r,["-a","--all"]),o=y(r,["-i","--id"]),a=y(r,["-d","--description"]),l=y(r,["-r","--release"]),c=y(r,["-c","--codename"]);if(s||r.length===0)return{stdout:["Distributor ID: Fortune",`Description: ${e}`,`Release: ${i}`,`Codename: ${n}`].join(`
106
+ `,exitCode:0}}};function zr(r,t){let e=t?"d":"-",i=[[256,"r"],[128,"w"],[64,"x"],[32,"r"],[16,"w"],[8,"x"],[4,"r"],[2,"w"],[1,"x"]].map(([s,o])=>r&s?o:"-").join("");return`${e}${i}`}function Lr(r){return r.toISOString().replace("T"," ").slice(0,16)}var Tr={name:"ls",description:"List directory contents",category:"navigation",params:["[-la] [path]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=w(n,["-l","--long"]),s=w(n,["-a","--all"]),o=xt(n,0,{flags:["-l","--long","-a","--all","-la","-al"]}),a=S(e,o??e);if(D(r,a,"ls"),t.vfs.exists(a)){let u=t.vfs.stat(a);if(u.type==="file"||t.vfs.isSymlink(a)){if(i){let d=a.split("/").pop()??a,m=u.type==="file"?u.size:0;return{stdout:`${zr(u.mode,!1)} 1 root root ${m} ${Lr(u.updatedAt)} ${d}
107
+ `,exitCode:0}}return{stdout:a.split("/").pop()??a,exitCode:0}}}let l=t.vfs.list(a).filter(u=>s||!u.startsWith("."));return{stdout:i?l.map(u=>{let d=S(a,u),m=t.vfs.stat(d),p=m.type==="file"?m.size:m.childrenCount;return`${zr(m.mode,m.type==="directory")} 1 ${p} ${Lr(m.updatedAt)} ${u}${m.type==="directory"?"/":""}`}).join(`
108
+ `):He(a,l,u=>t.vfs.stat(u)),exitCode:0}}};var Ur={name:"lsb_release",description:"Print distribution-specific information",category:"system",params:["[-a] [-i] [-d] [-r] [-c]"],run:({args:r,shell:t})=>{let e=t.properties?.os??"Fortune GNU/Linux x64",n="aurora",i="1.0";try{let d=t.vfs.readFile("/etc/os-release");for(let m of d.split(`
109
+ `))m.startsWith("PRETTY_NAME=")&&(e=m.slice(12).replace(/^"|"$/g,"").trim()),m.startsWith("VERSION_CODENAME=")&&(n=m.slice(17).trim()),m.startsWith("VERSION_ID=")&&(i=m.slice(11).replace(/^"|"$/g,"").trim())}catch{}let s=w(r,["-a","--all"]),o=w(r,["-i","--id"]),a=w(r,["-d","--description"]),l=w(r,["-r","--release"]),c=w(r,["-c","--codename"]);if(s||r.length===0)return{stdout:["Distributor ID: Fortune",`Description: ${e}`,`Release: ${i}`,`Codename: ${n}`].join(`
105
110
  `),exitCode:0};let u=[];return o&&u.push("Distributor ID: Fortune"),a&&u.push(`Description: ${e}`),l&&u.push(`Release: ${i}`),c&&u.push(`Codename: ${n}`),{stdout:u.join(`
106
- `),exitCode:0}}};var Rs={gunzip:"gzip"},Gt=new Map,Ds=new URL("./manuals/",import.meta.url);async function _s(r){return new Function("moduleName","return import(moduleName)")(r)}async function zs(r){let t=r.toLowerCase(),e=Rs[t]??t,n=`builtin:${e}`;if(Gt.has(n))return Gt.get(n)??null;try{let i=await _s("node:fs/promises"),s=new URL(`${e}.txt`,Ds),a=(await i.readFile(s,"utf8")).replace(/\n$/,"");return Gt.set(n,a),a}catch{return Gt.set(n,null),null}}var _r={name:"man",description:"Interface to the system reference manuals",category:"shell",params:["<command>"],run:async({args:r,shell:t})=>{let e=r[0];if(!e)return{stderr:"What manual page do you want?",exitCode:1};let n=`/usr/share/man/man1/${e}.1`;if(t.vfs.exists(n))return{stdout:t.vfs.readFile(n),exitCode:0};let i=await zs(e);return i?{stdout:i,exitCode:0}:{stderr:`No manual entry for ${e}`,exitCode:16}}};var zr={name:"mkdir",description:"Make directories",category:"files",params:["<dir>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{if(n.length===0)return{stderr:"mkdir: missing operand",exitCode:1};for(let i=0;i<n.length;i++){let s=St(n,i);if(!s)return{stderr:"mkdir: missing operand",exitCode:1};let o=x(e,s);_(r,o,"mkdir"),t.vfs.mkdir(o)}return{exitCode:0}}};var Lr={name:"mv",description:"Move or rename files",category:"files",params:["<source> <dest>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=n.filter(c=>!c.startsWith("-")),[s,o]=i;if(!s||!o)return{stderr:"mv: missing operand",exitCode:1};let a=x(e,s),l=x(e,o);try{if(_(r,a,"mv"),_(r,l,"mv"),!t.vfs.exists(a))return{stderr:`mv: ${s}: No such file or directory`,exitCode:1};let c=t.vfs.exists(l)&&t.vfs.stat(l).type==="directory"?`${l}/${s.split("/").pop()}`:l;return t.vfs.move(a,c),{exitCode:0}}catch(c){return{stderr:`mv: ${c instanceof Error?c.message:String(c)}`,exitCode:1}}}};import*as Ur from"node:path";var Tr={name:"nano",description:"Text editor",category:"files",params:["<file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=n[0];if(!i)return{stderr:"nano: missing file operand",exitCode:1};let s=x(e,i);_(r,s,"nano");let o=t.vfs.exists(s)?t.vfs.readFile(s):"",a=Ur.posix.basename(s)||"buffer",l=`/tmp/sshmimic-nano-${Date.now()}-${a}.tmp`;return{openEditor:{targetPath:s,tempPath:l,initialContent:o},exitCode:0}}};import{existsSync as Kr,readdirSync as Ls,readFileSync as ye}from"node:fs";import*as tt from"node:os";import*as Gr from"node:path";function Us(r){let t=Math.max(1,Math.floor(r/60)),e=Math.floor(t/1440),n=Math.floor(t%1440/60),i=t%60,s=[];return e>0&&s.push(`${e} day${e>1?"s":""}`),n>0&&s.push(`${n} hour${n>1?"s":""}`),(i>0||s.length===0)&&s.push(`${i} min${i>1?"s":""}`),s.join(", ")}function Br(r){return`\x1B[${r}m \x1B[0m`}function Ts(){let r=[40,41,42,43,44,45,46,47].map(Br).join(""),t=[100,101,102,103,104,105,106,107].map(Br).join("");return[r,t]}function Wr(r,t,e){if(r.trim().length===0)return r;let n={r:255,g:255,b:255},i={r:168,g:85,b:247},s=e<=1?0:t/(e-1),o=Math.round(n.r+(i.r-n.r)*s),a=Math.round(n.g+(i.g-n.g)*s),l=Math.round(n.b+(i.b-n.b)*s);return`\x1B[38;2;${o};${a};${l}m${r}\x1B[0m`}function Bs(r){if(r.trim().length===0)return r;let t=r.indexOf(":");if(t===-1)return r.includes("@")?Or(r):r;let e=r.substring(0,t+1),n=r.substring(t+1);return Or(e)+n}function Or(r){let t=new RegExp("\x1B\\[[\\d;]*m","g"),e=r.replace(t,"");if(e.trim().length===0)return r;let n={r:255,g:255,b:255},i={r:168,g:85,b:247},s="";for(let o=0;o<e.length;o+=1){let a=e.length<=1?0:o/(e.length-1),l=Math.round(n.r+(i.r-n.r)*a),c=Math.round(n.g+(i.g-n.g)*a),u=Math.round(n.b+(i.b-n.b)*a);s+=`\x1B[38;2;${l};${c};${u}m${e[o]}\x1B[0m`}return s}function jr(r){return Math.max(0,Math.round(r/(1024*1024)))}function Hr(){try{let r=ye("/etc/os-release","utf8");for(let t of r.split(`
107
- `)){if(!t.startsWith("PRETTY_NAME="))continue;return t.slice(12).trim().replace(/^"|"$/g,"")}}catch{return}}function qr(r){try{let t=ye(r,"utf8").split(`
108
- `)[0]?.trim();return!t||t.length===0?void 0:t}catch{return}}function Ws(r){let t=qr("/sys/devices/virtual/dmi/id/sys_vendor"),e=qr("/sys/devices/virtual/dmi/id/product_name");return t&&e?`${t} ${e}`:e||r}function Os(){let r=["/var/lib/dpkg/status","/usr/local/var/lib/dpkg/status"];for(let t of r)if(Kr(t))try{return ye(t,"utf8").match(/^Package:\s+/gm)?.length??0}catch{}}function js(){let r=["/snap","/var/lib/snapd/snaps"];for(let t of r)if(Kr(t))try{return Ls(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).length}catch{}}function Hs(){let r=Os(),t=js();return r!==void 0&&t!==void 0?`${r} (dpkg), ${t} (snap)`:r!==void 0?`${r} (dpkg)`:t!==void 0?`${t} (snap)`:"n/a"}function qs(){let r=tt.cpus();if(r.length===0)return"unknown";let t=r[0];if(!t)return"unknown";let e=(t.speed/1e3).toFixed(2);return`${t.model} (${r.length}) @ ${e}GHz`}function Ks(r){return!r||r.trim().length===0?"unknown":Gr.posix.basename(r.trim())}function Gs(r){let t=tt.totalmem(),e=tt.freemem(),n=Math.max(0,t-e),i=r.shellProps,s=process.uptime();return r.uptimeSeconds===void 0&&(r.uptimeSeconds=Math.round(s)),{user:r.user,host:r.host,osName:i?.os??r.osName??`${Hr()??tt.type()} ${tt.arch()}`,kernel:i?.kernel??r.kernel??tt.release(),uptimeSeconds:r.uptimeSeconds??tt.uptime(),packages:r.packages??Hs(),shell:Ks(r.shell),shellProps:r.shellProps??{kernel:r.kernel??tt.release(),os:r.osName??`${Hr()??tt.type()} ${tt.arch()}`,arch:tt.arch()},resolution:r.resolution??"n/a (ssh)",terminal:r.terminal??"unknown",cpu:r.cpu??qs(),gpu:r.gpu??"n/a",memoryUsedMiB:r.memoryUsedMiB??jr(n),memoryTotalMiB:r.memoryTotalMiB??jr(t)}}function Zr(r){let t=Gs(r),e=Us(t.uptimeSeconds),n=Ts(),i=[" .. .:. "," .::.. .. .. ",". .... ... .. ",": .... .:. .. ",": .:.:........:. .. ",": .. ",". : ",". : ",".. : "," :. .. "," .. .. "," :-. :: "," .:. :. "," ..: ... "," ..: :.. "," :... :...."," .. ...."," . .. "," .:. .: "," :. .. "," ::. .. ","..... ..:... ","...:. .. ",".:...:. ::. .. "," ... ..:::::.. ..:::::::.. "],s=[`${t.user}@${t.host}`,"-------------------------",`OS: ${t.osName}`,`Host: ${Ws(t.host)}`,`Kernel: ${t.kernel}`,`Uptime: ${e}`,`Packages: ${t.packages}`,`Shell: ${t.shell}`,`Resolution: ${t.resolution}`,`Terminal: ${t.terminal}`,`CPU: ${t.cpu}`,`GPU: ${t.gpu}`,`Memory: ${t.memoryUsedMiB}MiB / ${t.memoryTotalMiB}MiB`,"",n[0],n[1]],o=Math.max(i.length,s.length),a=[];for(let l=0;l<o;l+=1){let c=i[l]??"",u=s[l]??"";if(u.length>0){let d=Wr(c.padEnd(31," "),l,i.length),m=Bs(u);a.push(`${d} ${m}`);continue}a.push(Wr(c,l,i.length))}return a.join(`
109
- `)}var Jr={name:"neofetch",description:"System info display",category:"system",params:["[--off]"],run:({args:r,authUser:t,hostname:e,shell:n,env:i})=>n.packageManager.isInstalled("neofetch")?y(r,"--help")?{stdout:"Usage: neofetch [--off]",exitCode:0}:y(r,"--off")?{stdout:`${t}@${e}`,exitCode:0}:{stdout:Zr({user:t,host:e,shell:i.vars.SHELL,shellProps:n.properties,terminal:i.vars.TERM,uptimeSeconds:Math.floor((Date.now()-n.startTime)/1e3),packages:`${n.packageManager?.installedCount()??0} (dpkg)`}),exitCode:0}:{stderr:`bash: neofetch: command not found
111
+ `),exitCode:0}}};var Os={gunzip:"gzip"},Qt=new Map,Ws=new URL("./manuals/",import.meta.url);async function js(r){return new Function("moduleName","return import(moduleName)")(r)}async function Hs(r){let t=r.toLowerCase(),e=Os[t]??t,n=`builtin:${e}`;if(Qt.has(n))return Qt.get(n)??null;try{let i=await js("node:fs/promises"),s=new URL(`${e}.txt`,Ws),a=(await i.readFile(s,"utf8")).replace(/\n$/,"");return Qt.set(n,a),a}catch{return Qt.set(n,null),null}}var Br={name:"man",description:"Interface to the system reference manuals",category:"shell",params:["<command>"],run:async({args:r,shell:t})=>{let e=r[0];if(!e)return{stderr:"What manual page do you want?",exitCode:1};let n=`/usr/share/man/man1/${e}.1`;if(t.vfs.exists(n))return{stdout:t.vfs.readFile(n),exitCode:0};let i=await Hs(e);return i?{stdout:i,exitCode:0}:{stderr:`No manual entry for ${e}`,exitCode:16}}};var Or={name:"mkdir",description:"Make directories",category:"files",params:["<dir>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{if(n.length===0)return{stderr:"mkdir: missing operand",exitCode:1};for(let i=0;i<n.length;i++){let s=xt(n,i);if(!s)return{stderr:"mkdir: missing operand",exitCode:1};let o=S(e,s);D(r,o,"mkdir"),t.vfs.mkdir(o)}return{exitCode:0}}};var Wr={name:"mv",description:"Move or rename files",category:"files",params:["<source> <dest>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=n.filter(c=>!c.startsWith("-")),[s,o]=i;if(!s||!o)return{stderr:"mv: missing operand",exitCode:1};let a=S(e,s),l=S(e,o);try{if(D(r,a,"mv"),D(r,l,"mv"),!t.vfs.exists(a))return{stderr:`mv: ${s}: No such file or directory`,exitCode:1};let c=t.vfs.exists(l)&&t.vfs.stat(l).type==="directory"?`${l}/${s.split("/").pop()}`:l;return t.vfs.move(a,c),{exitCode:0}}catch(c){return{stderr:`mv: ${c instanceof Error?c.message:String(c)}`,exitCode:1}}}};import*as jr from"node:path";var Hr={name:"nano",description:"Text editor",category:"files",params:["<file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=n[0];if(!i)return{stderr:"nano: missing file operand",exitCode:1};let s=S(e,i);D(r,s,"nano");let o=t.vfs.exists(s)?t.vfs.readFile(s):"",a=jr.posix.basename(s)||"buffer",l=`/tmp/sshmimic-nano-${Date.now()}-${a}.tmp`;return{openEditor:{targetPath:s,tempPath:l,initialContent:o},exitCode:0}}};import{existsSync as Yr,readdirSync as qs,readFileSync as xe}from"node:fs";import*as et from"node:os";import*as Xr from"node:path";function Ks(r){let t=Math.max(1,Math.floor(r/60)),e=Math.floor(t/1440),n=Math.floor(t%1440/60),i=t%60,s=[];return e>0&&s.push(`${e} day${e>1?"s":""}`),n>0&&s.push(`${n} hour${n>1?"s":""}`),(i>0||s.length===0)&&s.push(`${i} min${i>1?"s":""}`),s.join(", ")}function qr(r){return`\x1B[${r}m \x1B[0m`}function Gs(){let r=[40,41,42,43,44,45,46,47].map(qr).join(""),t=[100,101,102,103,104,105,106,107].map(qr).join("");return[r,t]}function Kr(r,t,e){if(r.trim().length===0)return r;let n={r:255,g:255,b:255},i={r:168,g:85,b:247},s=e<=1?0:t/(e-1),o=Math.round(n.r+(i.r-n.r)*s),a=Math.round(n.g+(i.g-n.g)*s),l=Math.round(n.b+(i.b-n.b)*s);return`\x1B[38;2;${o};${a};${l}m${r}\x1B[0m`}function Zs(r){if(r.trim().length===0)return r;let t=r.indexOf(":");if(t===-1)return r.includes("@")?Gr(r):r;let e=r.substring(0,t+1),n=r.substring(t+1);return Gr(e)+n}function Gr(r){let t=new RegExp("\x1B\\[[\\d;]*m","g"),e=r.replace(t,"");if(e.trim().length===0)return r;let n={r:255,g:255,b:255},i={r:168,g:85,b:247},s="";for(let o=0;o<e.length;o+=1){let a=e.length<=1?0:o/(e.length-1),l=Math.round(n.r+(i.r-n.r)*a),c=Math.round(n.g+(i.g-n.g)*a),u=Math.round(n.b+(i.b-n.b)*a);s+=`\x1B[38;2;${l};${c};${u}m${e[o]}\x1B[0m`}return s}function Zr(r){return Math.max(0,Math.round(r/(1024*1024)))}function Jr(){try{let r=xe("/etc/os-release","utf8");for(let t of r.split(`
112
+ `)){if(!t.startsWith("PRETTY_NAME="))continue;return t.slice(12).trim().replace(/^"|"$/g,"")}}catch{return}}function Qr(r){try{let t=xe(r,"utf8").split(`
113
+ `)[0]?.trim();return!t||t.length===0?void 0:t}catch{return}}function Js(r){let t=Qr("/sys/devices/virtual/dmi/id/sys_vendor"),e=Qr("/sys/devices/virtual/dmi/id/product_name");return t&&e?`${t} ${e}`:e||r}function Qs(){let r=["/var/lib/dpkg/status","/usr/local/var/lib/dpkg/status"];for(let t of r)if(Yr(t))try{return xe(t,"utf8").match(/^Package:\s+/gm)?.length??0}catch{}}function Ys(){let r=["/snap","/var/lib/snapd/snaps"];for(let t of r)if(Yr(t))try{return qs(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).length}catch{}}function Xs(){let r=Qs(),t=Ys();return r!==void 0&&t!==void 0?`${r} (dpkg), ${t} (snap)`:r!==void 0?`${r} (dpkg)`:t!==void 0?`${t} (snap)`:"n/a"}function ti(){let r=et.cpus();if(r.length===0)return"unknown";let t=r[0];if(!t)return"unknown";let e=(t.speed/1e3).toFixed(2);return`${t.model} (${r.length}) @ ${e}GHz`}function ei(r){return!r||r.trim().length===0?"unknown":Xr.posix.basename(r.trim())}function ri(r){let t=et.totalmem(),e=et.freemem(),n=Math.max(0,t-e),i=r.shellProps,s=process.uptime();return r.uptimeSeconds===void 0&&(r.uptimeSeconds=Math.round(s)),{user:r.user,host:r.host,osName:i?.os??r.osName??`${Jr()??et.type()} ${et.arch()}`,kernel:i?.kernel??r.kernel??et.release(),uptimeSeconds:r.uptimeSeconds??et.uptime(),packages:r.packages??Xs(),shell:ei(r.shell),shellProps:r.shellProps??{kernel:r.kernel??et.release(),os:r.osName??`${Jr()??et.type()} ${et.arch()}`,arch:et.arch()},resolution:r.resolution??"n/a (ssh)",terminal:r.terminal??"unknown",cpu:r.cpu??ti(),gpu:r.gpu??"n/a",memoryUsedMiB:r.memoryUsedMiB??Zr(n),memoryTotalMiB:r.memoryTotalMiB??Zr(t)}}function tn(r){let t=ri(r),e=Ks(t.uptimeSeconds),n=Gs(),i=[" .. .:. "," .::.. .. .. ",". .... ... .. ",": .... .:. .. ",": .:.:........:. .. ",": .. ",". : ",". : ",".. : "," :. .. "," .. .. "," :-. :: "," .:. :. "," ..: ... "," ..: :.. "," :... :...."," .. ...."," . .. "," .:. .: "," :. .. "," ::. .. ","..... ..:... ","...:. .. ",".:...:. ::. .. "," ... ..:::::.. ..:::::::.. "],s=[`${t.user}@${t.host}`,"-------------------------",`OS: ${t.osName}`,`Host: ${Js(t.host)}`,`Kernel: ${t.kernel}`,`Uptime: ${e}`,`Packages: ${t.packages}`,`Shell: ${t.shell}`,`Resolution: ${t.resolution}`,`Terminal: ${t.terminal}`,`CPU: ${t.cpu}`,`GPU: ${t.gpu}`,`Memory: ${t.memoryUsedMiB}MiB / ${t.memoryTotalMiB}MiB`,"",n[0],n[1]],o=Math.max(i.length,s.length),a=[];for(let l=0;l<o;l+=1){let c=i[l]??"",u=s[l]??"";if(u.length>0){let d=Kr(c.padEnd(31," "),l,i.length),m=Zs(u);a.push(`${d} ${m}`);continue}a.push(Kr(c,l,i.length))}return a.join(`
114
+ `)}var en={name:"neofetch",description:"System info display",category:"system",params:["[--off]"],run:({args:r,authUser:t,hostname:e,shell:n,env:i})=>n.packageManager.isInstalled("neofetch")?w(r,"--help")?{stdout:"Usage: neofetch [--off]",exitCode:0}:w(r,"--off")?{stdout:`${t}@${e}`,exitCode:0}:{stdout:tn({user:t,host:e,shell:i.vars.SHELL,shellProps:n.properties,terminal:i.vars.TERM,uptimeSeconds:Math.floor((Date.now()-n.startTime)/1e3),packages:`${n.packageManager?.installedCount()??0} (dpkg)`}),exitCode:0}:{stderr:`bash: neofetch: command not found
110
115
  Hint: install it with: apt install neofetch
111
- `,exitCode:127}};import Qr from"node:vm";var Zt="v18.19.0",Yr={node:Zt,npm:"9.2.0",v8:"10.2.154.26-node.22"};function Zs(r,t){let e={version:Zt,versions:Yr,platform:"linux",arch:"x64",env:{NODE_ENV:"production",HOME:"/root",PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["node"],stdout:{write:s=>(r.push(s),!0)},stderr:{write:s=>(t.push(s),!0)},exit:(s=0)=>{throw new Jt(s)},cwd:()=>"/root",hrtime:()=>[0,0]},n={log:(...s)=>r.push(s.map(mt).join(" ")),error:(...s)=>t.push(s.map(mt).join(" ")),warn:(...s)=>t.push(s.map(mt).join(" ")),info:(...s)=>r.push(s.map(mt).join(" ")),dir:s=>r.push(mt(s))},i=s=>{switch(s){case"path":return{join:(...o)=>o.join("/").replace(/\/+/g,"/"),resolve:(...o)=>`/${o.join("/").replace(/^\/+/,"")}`,dirname:o=>o.split("/").slice(0,-1).join("/")||"/",basename:o=>o.split("/").pop()??"",extname:o=>{let a=o.split("/").pop()??"",l=a.lastIndexOf(".");return l>0?a.slice(l):""},sep:"/",delimiter:":"};case"os":return{platform:()=>"linux",arch:()=>"x64",type:()=>"Linux",hostname:()=>"fortune-vm",homedir:()=>"/root",tmpdir:()=>"/tmp",EOL:`
112
- `};case"util":return{format:(...o)=>o.map(mt).join(" "),inspect:o=>mt(o)};case"fs":case"fs/promises":throw new Error(`Cannot require '${s}': filesystem access not available in virtual runtime`);case"child_process":case"net":case"http":case"https":throw new Error(`Cannot require '${s}': not available in virtual runtime`);default:throw new Error(`Cannot find module '${s}'`)}};return i.resolve=s=>{throw new Error(`Cannot resolve '${s}'`)},i.cache={},i.extensions={},Qr.createContext({console:n,process:e,require:i,Math,JSON,Object,Array,String,Number,Boolean,Symbol,Date,RegExp,Error,TypeError,RangeError,SyntaxError,Promise,Map,Set,WeakMap,WeakSet,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,setTimeout:()=>{},clearTimeout:()=>{},setInterval:()=>{},clearInterval:()=>{},queueMicrotask:()=>{},globalThis:void 0,undefined:void 0,Infinity:1/0,NaN:NaN})}var Jt=class{constructor(t){this.code=t}code};function mt(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="function")return`[Function: ${r.name||"(anonymous)"}]`;if(Array.isArray(r))return`[ ${r.map(mt).join(", ")} ]`;if(r instanceof Error)return`${r.name}: ${r.message}`;if(typeof r=="object")try{return`{ ${Object.entries(r).map(([e,n])=>`${e}: ${mt(n)}`).join(", ")} }`}catch{return"[Object]"}return String(r)}function Qt(r){let t=[],e=[],n=Zs(t,e),i=0;try{let s=Qr.runInContext(r,n,{timeout:5e3});s!==void 0&&t.length===0&&t.push(mt(s))}catch(s){s instanceof Jt?i=s.code:s instanceof Error?(e.push(`${s.name}: ${s.message}`),i=1):(e.push(String(s)),i=1)}return{stdout:t.length?`${t.join(`
116
+ `,exitCode:127}};import rn from"node:vm";var Yt="v18.19.0",nn={node:Yt,npm:"9.2.0",v8:"10.2.154.26-node.22"};function ni(r,t){let e={version:Yt,versions:nn,platform:"linux",arch:"x64",env:{NODE_ENV:"production",HOME:"/root",PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["node"],stdout:{write:s=>(r.push(s),!0)},stderr:{write:s=>(t.push(s),!0)},exit:(s=0)=>{throw new Xt(s)},cwd:()=>"/root",hrtime:()=>[0,0]},n={log:(...s)=>r.push(s.map(ht).join(" ")),error:(...s)=>t.push(s.map(ht).join(" ")),warn:(...s)=>t.push(s.map(ht).join(" ")),info:(...s)=>r.push(s.map(ht).join(" ")),dir:s=>r.push(ht(s))},i=s=>{switch(s){case"path":return{join:(...o)=>o.join("/").replace(/\/+/g,"/"),resolve:(...o)=>`/${o.join("/").replace(/^\/+/,"")}`,dirname:o=>o.split("/").slice(0,-1).join("/")||"/",basename:o=>o.split("/").pop()??"",extname:o=>{let a=o.split("/").pop()??"",l=a.lastIndexOf(".");return l>0?a.slice(l):""},sep:"/",delimiter:":"};case"os":return{platform:()=>"linux",arch:()=>"x64",type:()=>"Linux",hostname:()=>"fortune-vm",homedir:()=>"/root",tmpdir:()=>"/tmp",EOL:`
117
+ `};case"util":return{format:(...o)=>o.map(ht).join(" "),inspect:o=>ht(o)};case"fs":case"fs/promises":throw new Error(`Cannot require '${s}': filesystem access not available in virtual runtime`);case"child_process":case"net":case"http":case"https":throw new Error(`Cannot require '${s}': not available in virtual runtime`);default:throw new Error(`Cannot find module '${s}'`)}};return i.resolve=s=>{throw new Error(`Cannot resolve '${s}'`)},i.cache={},i.extensions={},rn.createContext({console:n,process:e,require:i,Math,JSON,Object,Array,String,Number,Boolean,Symbol,Date,RegExp,Error,TypeError,RangeError,SyntaxError,Promise,Map,Set,WeakMap,WeakSet,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,setTimeout:()=>{},clearTimeout:()=>{},setInterval:()=>{},clearInterval:()=>{},queueMicrotask:()=>{},globalThis:void 0,undefined:void 0,Infinity:1/0,NaN:NaN})}var Xt=class{constructor(t){this.code=t}code};function ht(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="function")return`[Function: ${r.name||"(anonymous)"}]`;if(Array.isArray(r))return`[ ${r.map(ht).join(", ")} ]`;if(r instanceof Error)return`${r.name}: ${r.message}`;if(typeof r=="object")try{return`{ ${Object.entries(r).map(([e,n])=>`${e}: ${ht(n)}`).join(", ")} }`}catch{return"[Object]"}return String(r)}function te(r){let t=[],e=[],n=ni(t,e),i=0;try{let s=rn.runInContext(r,n,{timeout:5e3});s!==void 0&&t.length===0&&t.push(ht(s))}catch(s){s instanceof Xt?i=s.code:s instanceof Error?(e.push(`${s.name}: ${s.message}`),i=1):(e.push(String(s)),i=1)}return{stdout:t.length?`${t.join(`
113
118
  `)}
114
119
  `:"",stderr:e.length?`${e.join(`
115
120
  `)}
116
- `:"",exitCode:i}}function Js(r){let t=r.trim();return!t.includes(`
117
- `)&&!t.startsWith("const ")&&!t.startsWith("let ")&&!t.startsWith("var ")&&!t.startsWith("function ")&&!t.startsWith("class ")&&!t.startsWith("if ")&&!t.startsWith("for ")&&!t.startsWith("while ")&&!t.startsWith("import ")&&!t.startsWith("//")?Qt(t):Qt(`(async () => { ${r} })()`)}var Xr={name:"node",description:"JavaScript runtime (virtual)",category:"system",params:["[--version] [-e <expr>] [-p <expr>] [file]"],run:({args:r,shell:t,cwd:e})=>{if(!t.packageManager.isInstalled("nodejs"))return{stderr:`bash: node: command not found
121
+ `:"",exitCode:i}}function si(r){let t=r.trim();return!t.includes(`
122
+ `)&&!t.startsWith("const ")&&!t.startsWith("let ")&&!t.startsWith("var ")&&!t.startsWith("function ")&&!t.startsWith("class ")&&!t.startsWith("if ")&&!t.startsWith("for ")&&!t.startsWith("while ")&&!t.startsWith("import ")&&!t.startsWith("//")?te(t):te(`(async () => { ${r} })()`)}var sn={name:"node",description:"JavaScript runtime (virtual)",category:"system",params:["[--version] [-e <expr>] [-p <expr>] [file]"],run:({args:r,shell:t,cwd:e})=>{if(!t.packageManager.isInstalled("nodejs"))return{stderr:`bash: node: command not found
118
123
  Hint: install it with: apt install nodejs
119
- `,exitCode:127};if(y(r,["--version","-v"]))return{stdout:`${Zt}
120
- `,exitCode:0};if(y(r,["--versions"]))return{stdout:`${JSON.stringify(Yr,null,2)}
124
+ `,exitCode:127};if(w(r,["--version","-v"]))return{stdout:`${Yt}
125
+ `,exitCode:0};if(w(r,["--versions"]))return{stdout:`${JSON.stringify(nn,null,2)}
121
126
  `,exitCode:0};let n=r.findIndex(o=>o==="-e"||o==="--eval");if(n!==-1){let o=r[n+1];if(!o)return{stderr:`node: -e requires an argument
122
- `,exitCode:1};let{stdout:a,stderr:l,exitCode:c}=Qt(o);return{stdout:a||void 0,stderr:l||void 0,exitCode:c}}let i=r.findIndex(o=>o==="-p"||o==="--print");if(i!==-1){let o=r[i+1];if(!o)return{stderr:`node: -p requires an argument
123
- `,exitCode:1};let{stdout:a,stderr:l,exitCode:c}=Qt(o);return{stdout:a||(c===0?`
124
- `:void 0),stderr:l||void 0,exitCode:c}}let s=r.find(o=>!o.startsWith("-"));if(s){let o=x(e,s);if(!t.vfs.exists(o))return{stderr:`node: cannot open file '${s}': No such file or directory
125
- `,exitCode:1};let a=t.vfs.readFile(o),{stdout:l,stderr:c,exitCode:u}=Js(a);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}return{stdout:[`Welcome to Node.js ${Zt}.`,'Type ".exit" to exit the REPL.',"> "].join(`
126
- `),exitCode:0}}};var Yt="9.2.0",Qs="18.19.0",tn={name:"npm",description:"Node.js package manager (virtual)",category:"system",params:["<command> [args]"],run:({args:r,shell:t})=>{if(!t.packageManager.isInstalled("npm"))return{stderr:`bash: npm: command not found
127
+ `,exitCode:1};let{stdout:a,stderr:l,exitCode:c}=te(o);return{stdout:a||void 0,stderr:l||void 0,exitCode:c}}let i=r.findIndex(o=>o==="-p"||o==="--print");if(i!==-1){let o=r[i+1];if(!o)return{stderr:`node: -p requires an argument
128
+ `,exitCode:1};let{stdout:a,stderr:l,exitCode:c}=te(o);return{stdout:a||(c===0?`
129
+ `:void 0),stderr:l||void 0,exitCode:c}}let s=r.find(o=>!o.startsWith("-"));if(s){let o=S(e,s);if(!t.vfs.exists(o))return{stderr:`node: cannot open file '${s}': No such file or directory
130
+ `,exitCode:1};let a=t.vfs.readFile(o),{stdout:l,stderr:c,exitCode:u}=si(a);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}return{stdout:[`Welcome to Node.js ${Yt}.`,'Type ".exit" to exit the REPL.',"> "].join(`
131
+ `),exitCode:0}}};var ee="9.2.0",ii="18.19.0",on={name:"npm",description:"Node.js package manager (virtual)",category:"system",params:["<command> [args]"],run:({args:r,shell:t})=>{if(!t.packageManager.isInstalled("npm"))return{stderr:`bash: npm: command not found
127
132
  Hint: install it with: apt install npm
128
- `,exitCode:127};if(y(r,["--version","-v"]))return{stdout:`${Yt}
129
- `,exitCode:0};let e=r[0]?.toLowerCase();switch(e){case"version":case"-version":return{stdout:`{ npm: '${Yt}', node: '${Qs}', v8: '10.2.154.26' }
133
+ `,exitCode:127};if(w(r,["--version","-v"]))return{stdout:`${ee}
134
+ `,exitCode:0};let e=r[0]?.toLowerCase();switch(e){case"version":case"-version":return{stdout:`{ npm: '${ee}', node: '${ii}', v8: '10.2.154.26' }
130
135
  `,exitCode:0};case"install":case"i":case"add":return{stderr:`npm warn: package installation is not available in the virtual runtime.
131
136
  npm warn: This environment simulates npm CLI behaviour only.
132
137
  `,exitCode:1};case"run":case"exec":case"x":return{stderr:`npm error: script execution is not available in the virtual runtime.
133
138
  `,exitCode:1};case"init":return{stdout:`Wrote to /home/user/package.json
134
139
  `,exitCode:0};case"list":case"ls":return{stdout:`${e==="ls"||e==="list"?"virtual-env@1.0.0":""}
135
140
  \u2514\u2500\u2500 (empty)
136
- `,exitCode:0};case"help":case void 0:return{stdout:`${[`npm ${Yt}`,"","Usage: npm <command>","","Commands:"," install (not available in virtual runtime)"," run (not available in virtual runtime)"," exec (not available in virtual runtime)"," list List installed packages"," version Print versions"," --version Print npm version"].join(`
141
+ `,exitCode:0};case"help":case void 0:return{stdout:`${[`npm ${ee}`,"","Usage: npm <command>","","Commands:"," install (not available in virtual runtime)"," run (not available in virtual runtime)"," exec (not available in virtual runtime)"," list List installed packages"," version Print versions"," --version Print npm version"].join(`
137
142
  `)}
138
143
  `,exitCode:0};default:return{stderr:`npm error: unknown command: ${e}
139
- `,exitCode:1}}}},en={name:"npx",description:"Node.js package runner (virtual)",category:"system",params:["<package> [args]"],run:({args:r,shell:t})=>t.packageManager.isInstalled("npm")?y(r,["--version"])?{stdout:`${Yt}
144
+ `,exitCode:1}}}},an={name:"npx",description:"Node.js package runner (virtual)",category:"system",params:["<package> [args]"],run:({args:r,shell:t})=>t.packageManager.isInstalled("npm")?w(r,["--version"])?{stdout:`${ee}
140
145
  `,exitCode:0}:{stderr:`npx: package execution is not available in the virtual runtime.
141
146
  `,exitCode:1}:{stderr:`bash: npx: command not found
142
147
  Hint: install it with: apt install npm
143
- `,exitCode:127}};var rn={name:"passwd",description:"Change user password",category:"users",params:["[username]"],run:async({authUser:r,args:t,shell:e,stdin:n})=>{let i=t[0]??r;if(r!=="root"&&r!==i)return{stderr:"passwd: permission denied",exitCode:1};if(!e.users.listUsers().includes(i))return{stderr:`passwd: user '${i}' does not exist`,exitCode:1};if(n!==void 0&&n.trim().length>0){let s=n.trim().split(`
148
+ `,exitCode:127}};var ln={name:"passwd",description:"Change user password",category:"users",params:["[username]"],run:async({authUser:r,args:t,shell:e,stdin:n})=>{let i=t[0]??r;if(r!=="root"&&r!==i)return{stderr:"passwd: permission denied",exitCode:1};if(!e.users.listUsers().includes(i))return{stderr:`passwd: user '${i}' does not exist`,exitCode:1};if(n!==void 0&&n.trim().length>0){let s=n.trim().split(`
144
149
  `)[0];return await e.users.setPassword(i,s),{stdout:`passwd: password updated successfully
145
- `,exitCode:0}}return{passwordChallenge:{prompt:"New password: ",confirmPrompt:"Retype new password: ",action:"passwd",targetUsername:i},exitCode:0}}};var nn={name:"ping",description:"Send ICMP ECHO_REQUEST (mock)",category:"network",params:["[-c <count>] <host>"],run:({args:r})=>{let{flagsWithValues:t,positionals:e}=nt(r,{flagsWithValue:["-c","-i","-W"]}),n=e[0]??"localhost",i=t.get("-c"),s=i?Math.max(1,parseInt(i,10)||4):4,o=[`PING ${n}: 56 data bytes`];for(let a=0;a<s;a++){let l=(Math.random()*10+1).toFixed(3);o.push(`64 bytes from ${n}: icmp_seq=${a} ttl=64 time=${l} ms`)}return o.push(`--- ${n} ping statistics ---`),o.push(`${s} packets transmitted, ${s} received, 0% packet loss`),{stdout:o.join(`
146
- `),exitCode:0}}};function Ys(r,t){let e=0,n="",i=0;for(;i<r.length;){if(r[i]==="\\"&&i+1<r.length)switch(r[i+1]){case"n":n+=`
147
- `,i+=2;continue;case"t":n+=" ",i+=2;continue;case"r":n+="\r",i+=2;continue;case"\\":n+="\\",i+=2;continue;case"a":n+="\x07",i+=2;continue;case"b":n+="\b",i+=2;continue;case"f":n+="\f",i+=2;continue;case"v":n+="\v",i+=2;continue;default:n+=r[i],i++;continue}if(r[i]==="%"&&i+1<r.length){let s=i+1,o=!1;r[s]==="-"&&(o=!0,s++);let a=!1;r[s]==="0"&&(a=!0,s++);let l=0;for(;s<r.length&&/\d/.test(r[s]);)l=l*10+parseInt(r[s],10),s++;let c=-1;if(r[s]===".")for(s++,c=0;s<r.length&&/\d/.test(r[s]);)c=c*10+parseInt(r[s],10),s++;let u=r[s],d=t[e++]??"",m=(p,w=" ")=>{if(l<=0||p.length>=l)return p;let g=w.repeat(l-p.length);return o?p+g:g+p};switch(u){case"s":{let p=String(d);c>=0&&(p=p.slice(0,c)),n+=m(p);break}case"d":case"i":n+=m(String(parseInt(d,10)||0),a?"0":" ");break;case"f":{let p=c>=0?c:6;n+=m((parseFloat(d)||0).toFixed(p));break}case"o":n+=m((parseInt(d,10)||0).toString(8),a?"0":" ");break;case"x":n+=m((parseInt(d,10)||0).toString(16),a?"0":" ");break;case"X":n+=m((parseInt(d,10)||0).toString(16).toUpperCase(),a?"0":" ");break;case"%":n+="%",e--;break;default:n+=r[i],i++;continue}i=s+1;continue}n+=r[i],i++}return n}var sn={name:"printf",description:"Format and print data",category:"shell",params:["<format> [args...]"],run:({args:r})=>{let t=r[0];return t?{stdout:Ys(t,r.slice(1)),exitCode:0}:{stderr:"printf: missing format string",exitCode:1}}};var on={name:"ps",description:"Report process status",category:"system",params:["[-a] [-u] [-x] [aux]"],run:({authUser:r,shell:t,args:e})=>{let n=t.users.listActiveSessions(),i=y(e,["-u"])||e.includes("u")||e.includes("aux")||e.includes("au"),s=y(e,["-a","-x"])||e.includes("a")||e.includes("aux");if(i){let u=["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND"],d=1e3;for(let m of n){let p=m.username.padEnd(10).slice(0,10),w=(Math.random()*.5).toFixed(1),g=Math.floor(Math.random()*2e4+5e3),f=Math.floor(Math.random()*5e3+1e3);u.push(`${p} ${String(d).padStart(6)} 0.0 ${w.padStart(4)} ${String(g).padStart(6)} ${String(f).padStart(5)} ${m.tty.padEnd(8)} Ss 00:00 0:00 bash`),d++}return u.push(`root ${String(d).padStart(6)} 0.0 0.0 0 0 ? S 00:00 0:00 ps`),{stdout:u.join(`
150
+ `,exitCode:0}}return{passwordChallenge:{prompt:"New password: ",confirmPrompt:"Retype new password: ",action:"passwd",targetUsername:i},exitCode:0}}};var cn={name:"ping",description:"Send ICMP ECHO_REQUEST (mock)",category:"network",params:["[-c <count>] <host>"],run:({args:r})=>{let{flagsWithValues:t,positionals:e}=st(r,{flagsWithValue:["-c","-i","-W"]}),n=e[0]??"localhost",i=t.get("-c"),s=i?Math.max(1,parseInt(i,10)||4):4,o=[`PING ${n}: 56 data bytes`];for(let a=0;a<s;a++){let l=(Math.random()*10+1).toFixed(3);o.push(`64 bytes from ${n}: icmp_seq=${a} ttl=64 time=${l} ms`)}return o.push(`--- ${n} ping statistics ---`),o.push(`${s} packets transmitted, ${s} received, 0% packet loss`),{stdout:o.join(`
151
+ `),exitCode:0}}};function oi(r,t){let e=0,n="",i=0;for(;i<r.length;){if(r[i]==="\\"&&i+1<r.length)switch(r[i+1]){case"n":n+=`
152
+ `,i+=2;continue;case"t":n+=" ",i+=2;continue;case"r":n+="\r",i+=2;continue;case"\\":n+="\\",i+=2;continue;case"a":n+="\x07",i+=2;continue;case"b":n+="\b",i+=2;continue;case"f":n+="\f",i+=2;continue;case"v":n+="\v",i+=2;continue;default:n+=r[i],i++;continue}if(r[i]==="%"&&i+1<r.length){let s=i+1,o=!1;r[s]==="-"&&(o=!0,s++);let a=!1;r[s]==="0"&&(a=!0,s++);let l=0;for(;s<r.length&&/\d/.test(r[s]);)l=l*10+parseInt(r[s],10),s++;let c=-1;if(r[s]===".")for(s++,c=0;s<r.length&&/\d/.test(r[s]);)c=c*10+parseInt(r[s],10),s++;let u=r[s],d=t[e++]??"",m=(p,y=" ")=>{if(l<=0||p.length>=l)return p;let g=y.repeat(l-p.length);return o?p+g:g+p};switch(u){case"s":{let p=String(d);c>=0&&(p=p.slice(0,c)),n+=m(p);break}case"d":case"i":n+=m(String(parseInt(d,10)||0),a?"0":" ");break;case"f":{let p=c>=0?c:6;n+=m((parseFloat(d)||0).toFixed(p));break}case"o":n+=m((parseInt(d,10)||0).toString(8),a?"0":" ");break;case"x":n+=m((parseInt(d,10)||0).toString(16),a?"0":" ");break;case"X":n+=m((parseInt(d,10)||0).toString(16).toUpperCase(),a?"0":" ");break;case"%":n+="%",e--;break;default:n+=r[i],i++;continue}i=s+1;continue}n+=r[i],i++}return n}var un={name:"printf",description:"Format and print data",category:"shell",params:["<format> [args...]"],run:({args:r})=>{let t=r[0];return t?{stdout:oi(t,r.slice(1)),exitCode:0}:{stderr:"printf: missing format string",exitCode:1}}};var dn={name:"ps",description:"Report process status",category:"system",params:["[-a] [-u] [-x] [aux]"],run:({authUser:r,shell:t,args:e})=>{let n=t.users.listActiveSessions(),i=w(e,["-u"])||e.includes("u")||e.includes("aux")||e.includes("au"),s=w(e,["-a","-x"])||e.includes("a")||e.includes("aux");if(i){let u=["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND"],d=1e3;for(let m of n){let p=m.username.padEnd(10).slice(0,10),y=(Math.random()*.5).toFixed(1),g=Math.floor(Math.random()*2e4+5e3),f=Math.floor(Math.random()*5e3+1e3);u.push(`${p} ${String(d).padStart(6)} 0.0 ${y.padStart(4)} ${String(g).padStart(6)} ${String(f).padStart(5)} ${m.tty.padEnd(8)} Ss 00:00 0:00 bash`),d++}return u.push(`root ${String(d).padStart(6)} 0.0 0.0 0 0 ? S 00:00 0:00 ps`),{stdout:u.join(`
148
153
  `),exitCode:0}}let a=[" PID TTY TIME CMD"],l=1e3;for(let c of n)!s&&c.username!==r||(a.push(`${String(l).padStart(5)} ${c.tty.padEnd(12)} 00:00:00 ${c.username===r?"bash":`bash (${c.username})`}`),l++);return a.push(`${String(l).padStart(5)} pts/0 00:00:00 ps`),{stdout:a.join(`
149
- `),exitCode:0}}};var an={name:"pwd",description:"Print working directory",category:"navigation",params:[],run:({cwd:r})=>({stdout:r,exitCode:0})};var Xs="Python 3.11.2";var Xt="3.11.2 (default, Mar 13 2023, 12:18:29) [GCC 12.2.0]",h={__pytype__:"none"};function j(r=[]){return{__pytype__:"dict",data:new Map(r)}}function we(r,t,e=1){return{__pytype__:"range",start:r,stop:t,step:e}}function W(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="dict"}function Mt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="range"}function pt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="func"}function Se(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="class"}function Rt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="instance"}function wt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="none"}function Q(r){return r===null||wt(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?`'${r.replace(/'/g,"\\'")}'`:Array.isArray(r)?`[${r.map(Q).join(", ")}]`:W(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${Q(e)}`).join(", ")}}`:Mt(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:pt(r)?`<function ${r.name} at 0x...>`:Se(r)?`<class '${r.name}'>`:Rt(r)?`<${r.cls.name} object at 0x...>`:String(r)}function I(r){return r===null||wt(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?r:Array.isArray(r)?`[${r.map(Q).join(", ")}]`:W(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${Q(e)}`).join(", ")}}`:Mt(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:Q(r)}function ot(r){return r===null||wt(r)?!1:typeof r=="boolean"?r:typeof r=="number"?r!==0:typeof r=="string"||Array.isArray(r)?r.length>0:W(r)?r.data.size>0:Mt(r)?cn(r)>0:!0}function cn(r){if(r.step===0)return 0;let t=Math.ceil((r.stop-r.start)/r.step);return Math.max(0,t)}function ti(r){let t=[];for(let e=r.start;(r.step>0?e<r.stop:e>r.stop)&&(t.push(e),!(t.length>1e4));e+=r.step);return t}function J(r){if(Array.isArray(r))return r;if(typeof r=="string")return[...r];if(Mt(r))return ti(r);if(W(r))return[...r.data.keys()];throw new O("TypeError",`'${Ct(r)}' object is not iterable`)}function Ct(r){return r===null||wt(r)?"NoneType":typeof r=="boolean"?"bool":typeof r=="number"?Number.isInteger(r)?"int":"float":typeof r=="string"?"str":Array.isArray(r)?"list":W(r)?"dict":Mt(r)?"range":pt(r)?"function":Se(r)?"type":Rt(r)?r.cls.name:"object"}var O=class{constructor(t,e){this.type=t;this.message=e}type;message;toString(){return`${this.type}: ${this.message}`}},kt=class{constructor(t){this.value=t}value},Dt=class{},_t=class{},zt=class{constructor(t){this.code=t}code};function ei(r){let t=new Map,e=j([["sep","/"],["linesep",`
150
- `],["curdir","."],["pardir",".."]]);return e.__methods__={getcwd:()=>r,getenv:n=>typeof n=="string"?process.env[n]??h:h,path:j([["join",h],["exists",h],["dirname",h],["basename",h]]),listdir:()=>[]},t.set("__builtins__",h),t.set("__name__","__main__"),t.set("__cwd__",r),t}function ri(r){let t=j([["sep","/"],["curdir","."]]),e=j([["sep","/"],["linesep",`
151
- `],["name","posix"]]);return e._cwd=r,t._cwd=r,e.path=t,e}function ni(){return j([["version",Xt],["version_info",j([["major",3],["minor",11],["micro",2]].map(([r,t])=>[r,t]))],["platform","linux"],["executable","/usr/bin/python3"],["prefix","/usr"],["path",["/usr/lib/python3.11","/usr/lib/python3.11/lib-dynload"]],["argv",[""]],["maxsize",9007199254740991]])}function si(){return j([["pi",Math.PI],["e",Math.E],["tau",Math.PI*2],["inf",1/0],["nan",NaN],["sqrt",h],["floor",h],["ceil",h],["log",h],["pow",h],["sin",h],["cos",h],["tan",h],["fabs",h],["factorial",h]])}function ii(){return j([["dumps",h],["loads",h]])}function oi(){return j([["match",h],["search",h],["findall",h],["sub",h],["split",h],["compile",h]])}var ln={os:ri,sys:()=>ni(),math:()=>si(),json:()=>ii(),re:()=>oi(),random:()=>j([["random",h],["randint",h],["choice",h],["shuffle",h]]),time:()=>j([["time",h],["sleep",h],["ctime",h]]),datetime:()=>j([["datetime",h],["date",h],["timedelta",h]]),collections:()=>j([["Counter",h],["defaultdict",h],["OrderedDict",h]]),itertools:()=>j([["chain",h],["product",h],["combinations",h],["permutations",h]]),functools:()=>j([["reduce",h],["partial",h],["lru_cache",h]]),string:()=>j([["ascii_letters","abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"],["digits","0123456789"],["punctuation","!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"]])},te=class{constructor(t){this.cwd=t}cwd;output=[];stderr=[];modules=new Map;getOutput(){return this.output.join(`
154
+ `),exitCode:0}}};var mn={name:"pwd",description:"Print working directory",category:"navigation",params:[],run:({cwd:r})=>({stdout:r,exitCode:0})};var ai="Python 3.11.2";var re="3.11.2 (default, Mar 13 2023, 12:18:29) [GCC 12.2.0]",h={__pytype__:"none"};function q(r=[]){return{__pytype__:"dict",data:new Map(r)}}function be(r,t,e=1){return{__pytype__:"range",start:r,stop:t,step:e}}function j(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="dict"}function Ft(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="range"}function gt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="func"}function ve(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="class"}function zt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="instance"}function St(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="none"}function Y(r){return r===null||St(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?`'${r.replace(/'/g,"\\'")}'`:Array.isArray(r)?`[${r.map(Y).join(", ")}]`:j(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${Y(e)}`).join(", ")}}`:Ft(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:gt(r)?`<function ${r.name} at 0x...>`:ve(r)?`<class '${r.name}'>`:zt(r)?`<${r.cls.name} object at 0x...>`:String(r)}function V(r){return r===null||St(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?r:Array.isArray(r)?`[${r.map(Y).join(", ")}]`:j(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${Y(e)}`).join(", ")}}`:Ft(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:Y(r)}function lt(r){return r===null||St(r)?!1:typeof r=="boolean"?r:typeof r=="number"?r!==0:typeof r=="string"||Array.isArray(r)?r.length>0:j(r)?r.data.size>0:Ft(r)?fn(r)>0:!0}function fn(r){if(r.step===0)return 0;let t=Math.ceil((r.stop-r.start)/r.step);return Math.max(0,t)}function li(r){let t=[];for(let e=r.start;(r.step>0?e<r.stop:e>r.stop)&&(t.push(e),!(t.length>1e4));e+=r.step);return t}function Q(r){if(Array.isArray(r))return r;if(typeof r=="string")return[...r];if(Ft(r))return li(r);if(j(r))return[...r.data.keys()];throw new H("TypeError",`'${$t(r)}' object is not iterable`)}function $t(r){return r===null||St(r)?"NoneType":typeof r=="boolean"?"bool":typeof r=="number"?Number.isInteger(r)?"int":"float":typeof r=="string"?"str":Array.isArray(r)?"list":j(r)?"dict":Ft(r)?"range":gt(r)?"function":ve(r)?"type":zt(r)?r.cls.name:"object"}var H=class{constructor(t,e){this.type=t;this.message=e}type;message;toString(){return`${this.type}: ${this.message}`}},Mt=class{constructor(t){this.value=t}value},Lt=class{},Tt=class{},Ut=class{constructor(t){this.code=t}code};function ci(r){let t=new Map,e=q([["sep","/"],["linesep",`
155
+ `],["curdir","."],["pardir",".."]]);return e.__methods__={getcwd:()=>r,getenv:n=>typeof n=="string"?process.env[n]??h:h,path:q([["join",h],["exists",h],["dirname",h],["basename",h]]),listdir:()=>[]},t.set("__builtins__",h),t.set("__name__","__main__"),t.set("__cwd__",r),t}function ui(r){let t=q([["sep","/"],["curdir","."]]),e=q([["sep","/"],["linesep",`
156
+ `],["name","posix"]]);return e._cwd=r,t._cwd=r,e.path=t,e}function di(){return q([["version",re],["version_info",q([["major",3],["minor",11],["micro",2]].map(([r,t])=>[r,t]))],["platform","linux"],["executable","/usr/bin/python3"],["prefix","/usr"],["path",["/usr/lib/python3.11","/usr/lib/python3.11/lib-dynload"]],["argv",[""]],["maxsize",9007199254740991]])}function mi(){return q([["pi",Math.PI],["e",Math.E],["tau",Math.PI*2],["inf",1/0],["nan",NaN],["sqrt",h],["floor",h],["ceil",h],["log",h],["pow",h],["sin",h],["cos",h],["tan",h],["fabs",h],["factorial",h]])}function pi(){return q([["dumps",h],["loads",h]])}function fi(){return q([["match",h],["search",h],["findall",h],["sub",h],["split",h],["compile",h]])}var pn={os:ui,sys:()=>di(),math:()=>mi(),json:()=>pi(),re:()=>fi(),random:()=>q([["random",h],["randint",h],["choice",h],["shuffle",h]]),time:()=>q([["time",h],["sleep",h],["ctime",h]]),datetime:()=>q([["datetime",h],["date",h],["timedelta",h]]),collections:()=>q([["Counter",h],["defaultdict",h],["OrderedDict",h]]),itertools:()=>q([["chain",h],["product",h],["combinations",h],["permutations",h]]),functools:()=>q([["reduce",h],["partial",h],["lru_cache",h]]),string:()=>q([["ascii_letters","abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"],["digits","0123456789"],["punctuation","!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"]])},ne=class{constructor(t){this.cwd=t}cwd;output=[];stderr=[];modules=new Map;getOutput(){return this.output.join(`
152
157
  `)+(this.output.length?`
153
158
  `:"")}getStderr(){return this.stderr.join(`
154
159
  `)+(this.stderr.length?`
155
160
  `:"")}splitArgs(t){let e=[],n=0,i="",s=!1,o="";for(let a=0;a<t.length;a++){let l=t[a];s?(i+=l,l===o&&t[a-1]!=="\\"&&(s=!1)):l==='"'||l==="'"?(s=!0,o=l,i+=l):"([{".includes(l)?(n++,i+=l):")]}".includes(l)?(n--,i+=l):l===","&&n===0?(e.push(i.trim()),i=""):i+=l}return i.trim()&&e.push(i.trim()),e}pyEval(t,e){if(t=t.trim(),!t||t==="None")return h;if(t==="True")return!0;if(t==="False")return!1;if(t==="...")return h;if(/^-?\d+$/.test(t))return parseInt(t,10);if(/^-?\d+\.\d*$/.test(t))return parseFloat(t);if(/^0x[0-9a-fA-F]+$/.test(t))return parseInt(t,16);if(/^0o[0-7]+$/.test(t))return parseInt(t.slice(2),8);if(/^('''[\s\S]*'''|"""[\s\S]*""")$/.test(t))return t.slice(3,-3);if(/^(['"])(.*)\1$/s.test(t))return t.slice(1,-1).replace(/\\n/g,`
156
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\").replace(/\\'/g,"'").replace(/\\"/g,'"');let n=t.match(/^f(['"])([\s\S]*)\1$/);if(n){let c=n[2];return c=c.replace(/\{([^{}]+)\}/g,(u,d)=>{try{return I(this.pyEval(d.trim(),e))}catch{return`{${d}}`}}),c}let i=t.match(/^b(['"])(.*)\1$/s);if(i)return i[2];if(t.startsWith("[")&&t.endsWith("]")){let c=t.slice(1,-1).trim();if(!c)return[];let u=c.match(/^(.+?)\s+for\s+(\w+)\s+in\s+(.+?)(?:\s+if\s+(.+))?$/);if(u){let[,d,m,p,w]=u,g=J(this.pyEval(p.trim(),e)),f=[];for(let $ of g){let E=new Map(e);E.set(m,$),!(w&&!ot(this.pyEval(w,E)))&&f.push(this.pyEval(d.trim(),E))}return f}return this.splitArgs(c).map(d=>this.pyEval(d,e))}if(t.startsWith("(")&&t.endsWith(")")){let c=t.slice(1,-1).trim();if(!c)return[];let u=this.splitArgs(c);return u.length===1&&!c.endsWith(",")?this.pyEval(u[0],e):u.map(d=>this.pyEval(d,e))}if(t.startsWith("{")&&t.endsWith("}")){let c=t.slice(1,-1).trim();if(!c)return j();let u=j();for(let d of this.splitArgs(c)){let m=d.indexOf(":");if(m===-1)continue;let p=I(this.pyEval(d.slice(0,m).trim(),e)),w=this.pyEval(d.slice(m+1).trim(),e);u.data.set(p,w)}return u}let s=t.match(/^not\s+(.+)$/);if(s)return!ot(this.pyEval(s[1],e));let o=[["or"],["and"],["in","not in","is not","is","==","!=","<=",">=","<",">"],["+","-"],["**"],["*","//","/","%"]];for(let c of o){let u=this.tryBinaryOp(t,c,e);if(u!==void 0)return u}if(t.startsWith("-")){let c=this.pyEval(t.slice(1),e);if(typeof c=="number")return-c}if(process.env.PY_DEBUG&&console.error("eval:",JSON.stringify(t)),t.endsWith("]")&&!t.startsWith("[")){let c=this.findMatchingBracket(t,"[");if(c!==-1){let u=this.pyEval(t.slice(0,c),e),d=t.slice(c+1,-1);return this.subscript(u,d,e)}}let a=t.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*\(([\s\S]*)\)$/);if(a){let[,c,u]=a,d=(u?.trim()?this.splitArgs(u):[]).map(m=>this.pyEval(m,e));return this.callBuiltin(c,d,e)}let l=this.findDotAccess(t);if(l){let{objExpr:c,attr:u,callPart:d}=l,m=this.pyEval(c,e);if(d!==void 0){let p=d.slice(1,-1),w=p.trim()?this.splitArgs(p).map(g=>this.pyEval(g,e)):[];return this.callMethod(m,u,w,e)}return this.getAttr(m,u,e)}if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)){if(e.has(t))return e.get(t);throw new O("NameError",`name '${t}' is not defined`)}if(/^[A-Za-z_][A-Za-z0-9_.]+$/.test(t)){let c=t.split("."),u=e.get(c[0])??(()=>{throw new O("NameError",`name '${c[0]}' is not defined`)})();for(let d of c.slice(1))u=this.getAttr(u,d,e);return u}return h}findMatchingBracket(t,e){let n=e==="["?"]":e==="("?")":"}",i=0;for(let s=t.length-1;s>=0;s--)if(t[s]===n&&i++,t[s]===e&&(i--,i===0))return s;return-1}findDotAccess(t){let e=0,n=!1,i="";for(let s=t.length-1;s>0;s--){let o=t[s];if(n){o===i&&t[s-1]!=="\\"&&(n=!1);continue}if(o==='"'||o==="'"){n=!0,i=o;continue}if(")]}".includes(o)){e++;continue}if("([{".includes(o)){e--;continue}if(e!==0||o!==".")continue;let a=t.slice(0,s).trim(),c=t.slice(s+1).match(/^(\w+)(\([\s\S]*\))?$/);if(c&&!/^-?\d+$/.test(a))return{objExpr:a,attr:c[1],callPart:c[2]}}return null}tryBinaryOp(t,e,n){let i=0,s=!1,o="";for(let a=t.length-1;a>=0;a--){let l=t[a];if(s){l===o&&t[a-1]!=="\\"&&(s=!1);continue}if(l==='"'||l==="'"){s=!0,o=l;continue}if(")]}".includes(l)){i++;continue}if("([{".includes(l)){i--;continue}if(i===0){for(let c of e)if(t.slice(a,a+c.length)===c){if(c==="*"&&(t[a+1]==="*"||t[a-1]==="*"))continue;let u=t[a-1],d=t[a+c.length];if(/^[a-z]/.test(c)&&(u&&/\w/.test(u)||d&&/\w/.test(d)))continue;let p=t.slice(0,a).trim(),w=t.slice(a+c.length).trim();if(!p||!w)continue;return this.applyBinaryOp(c,p,w,n)}}}}applyBinaryOp(t,e,n,i){if(t==="and"){let a=this.pyEval(e,i);return ot(a)?this.pyEval(n,i):a}if(t==="or"){let a=this.pyEval(e,i);return ot(a)?a:this.pyEval(n,i)}let s=this.pyEval(e,i),o=this.pyEval(n,i);switch(t){case"+":return typeof s=="string"&&typeof o=="string"?s+o:Array.isArray(s)&&Array.isArray(o)?[...s,...o]:s+o;case"-":return s-o;case"*":if(typeof s=="string"&&typeof o=="number")return s.repeat(o);if(Array.isArray(s)&&typeof o=="number"){let a=[];for(let l=0;l<o;l++)a.push(...s);return a}return s*o;case"/":{if(o===0)throw new O("ZeroDivisionError","division by zero");return s/o}case"//":{if(o===0)throw new O("ZeroDivisionError","integer division or modulo by zero");return Math.floor(s/o)}case"%":{if(typeof s=="string")return this.pyStringFormat(s,Array.isArray(o)?o:[o]);if(o===0)throw new O("ZeroDivisionError","integer division or modulo by zero");return s%o}case"**":return s**o;case"==":return Q(s)===Q(o)||s===o;case"!=":return Q(s)!==Q(o)&&s!==o;case"<":return s<o;case"<=":return s<=o;case">":return s>o;case">=":return s>=o;case"in":return this.pyIn(o,s);case"not in":return!this.pyIn(o,s);case"is":return s===o||wt(s)&&wt(o);case"is not":return!(s===o||wt(s)&&wt(o))}return h}pyIn(t,e){return typeof t=="string"?typeof e=="string"&&t.includes(e):Array.isArray(t)?t.some(n=>Q(n)===Q(e)):W(t)?t.data.has(I(e)):!1}subscript(t,e,n){if(e.includes(":")){let s=e.split(":").map(l=>l.trim()),o=s[0]?this.pyEval(s[0],n):void 0,a=s[1]?this.pyEval(s[1],n):void 0;return typeof t=="string"||Array.isArray(t)?t.slice(o,a):h}let i=this.pyEval(e,n);if(Array.isArray(t)){let s=i;return s<0&&(s=t.length+s),t[s]??h}if(typeof t=="string"){let s=i;return s<0&&(s=t.length+s),t[s]??h}if(W(t))return t.data.get(I(i))??h;throw new O("TypeError",`'${Ct(t)}' is not subscriptable`)}getAttr(t,e,n){return W(t)?t.data.has(e)?t.data.get(e):e==="path"&&t.path?t.path:h:Rt(t)?t.attrs.get(e)??h:typeof t=="string"?{__class__:{__pytype__:"class",name:"str"}}[e]??h:h}callMethod(t,e,n,i){if(typeof t=="string")switch(e){case"upper":return t.toUpperCase();case"lower":return t.toLowerCase();case"strip":return(n[0]?t.replace(new RegExp(`[${n[0]}]+`,"g"),""):t).trim();case"lstrip":return t.trimStart();case"rstrip":return t.trimEnd();case"split":return t.split(typeof n[0]=="string"?n[0]:/\s+/).filter((s,o)=>o>0||s!=="");case"splitlines":return t.split(`
157
- `);case"join":return J(n[0]??[]).map(I).join(t);case"replace":return t.replaceAll(I(n[0]??""),I(n[1]??""));case"startswith":return t.startsWith(I(n[0]??""));case"endswith":return t.endsWith(I(n[0]??""));case"find":return t.indexOf(I(n[0]??""));case"index":{let s=t.indexOf(I(n[0]??""));if(s===-1)throw new O("ValueError","substring not found");return s}case"count":return t.split(I(n[0]??"")).length-1;case"format":return this.pyStringFormat(t,n);case"encode":return t;case"decode":return t;case"isdigit":return/^\d+$/.test(t);case"isalpha":return/^[a-zA-Z]+$/.test(t);case"isalnum":return/^[a-zA-Z0-9]+$/.test(t);case"isspace":return/^\s+$/.test(t);case"isupper":return t===t.toUpperCase()&&t!==t.toLowerCase();case"islower":return t===t.toLowerCase()&&t!==t.toUpperCase();case"center":{let s=n[0]??0,o=I(n[1]??" ");return t.padStart(Math.floor((s+t.length)/2),o).padEnd(s,o)}case"ljust":return t.padEnd(n[0]??0,I(n[1]??" "));case"rjust":return t.padStart(n[0]??0,I(n[1]??" "));case"zfill":return t.padStart(n[0]??0,"0");case"title":return t.replace(/\b\w/g,s=>s.toUpperCase());case"capitalize":return t[0]?.toUpperCase()+t.slice(1).toLowerCase();case"swapcase":return[...t].map(s=>s===s.toUpperCase()?s.toLowerCase():s.toUpperCase()).join("")}if(Array.isArray(t))switch(e){case"append":return t.push(n[0]??h),h;case"extend":for(let s of J(n[0]??[]))t.push(s);return h;case"insert":return t.splice(n[0]??0,0,n[1]??h),h;case"pop":{let s=n[0]!==void 0?n[0]:-1,o=s<0?t.length+s:s;return t.splice(o,1)[0]??h}case"remove":{let s=t.findIndex(o=>Q(o)===Q(n[0]??h));return s!==-1&&t.splice(s,1),h}case"index":{let s=t.findIndex(o=>Q(o)===Q(n[0]??h));if(s===-1)throw new O("ValueError","is not in list");return s}case"count":return t.filter(s=>Q(s)===Q(n[0]??h)).length;case"sort":return t.sort((s,o)=>typeof s=="number"&&typeof o=="number"?s-o:I(s).localeCompare(I(o))),h;case"reverse":return t.reverse(),h;case"copy":return[...t];case"clear":return t.splice(0),h}if(W(t))switch(e){case"keys":return[...t.data.keys()];case"values":return[...t.data.values()];case"items":return[...t.data.entries()].map(([s,o])=>[s,o]);case"get":return t.data.get(I(n[0]??""))??n[1]??h;case"update":{if(W(n[0]??h))for(let[s,o]of n[0].data)t.data.set(s,o);return h}case"pop":{let s=I(n[0]??""),o=t.data.get(s)??n[1]??h;return t.data.delete(s),o}case"clear":return t.data.clear(),h;case"copy":return j([...t.data.entries()]);case"setdefault":{let s=I(n[0]??"");return t.data.has(s)||t.data.set(s,n[1]??h),t.data.get(s)??h}}if(W(t)&&t.data.has("name")&&t.data.get("name")==="posix")switch(e){case"getcwd":return this.cwd;case"getenv":return typeof n[0]=="string"?process.env[n[0]]??n[1]??h:h;case"listdir":return[];case"path":return t}if(W(t))switch(e){case"join":return n.map(I).join("/").replace(/\/+/g,"/");case"exists":return!1;case"dirname":return I(n[0]??"").split("/").slice(0,-1).join("/")||"/";case"basename":return I(n[0]??"").split("/").pop()??"";case"abspath":return I(n[0]??"");case"splitext":{let s=I(n[0]??""),o=s.lastIndexOf(".");return o>0?[s.slice(0,o),s.slice(o)]:[s,""]}case"isfile":return!1;case"isdir":return!1}if(W(t)&&t.data.has("version")&&t.data.get("version")===Xt&&e==="exit")throw new zt(n[0]??0);if(W(t)){let s={sqrt:Math.sqrt,floor:Math.floor,ceil:Math.ceil,fabs:Math.abs,log:Math.log,log2:Math.log2,log10:Math.log10,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,pow:Math.pow,exp:Math.exp,hypot:Math.hypot};if(e in s){let o=s[e];return o(...n.map(a=>a))}if(e==="factorial"){let o=n[0]??0,a=1;for(;o>1;)a*=o--;return a}if(e==="gcd"){let o=Math.abs(n[0]??0),a=Math.abs(n[1]??0);for(;a;)[o,a]=[a,o%a];return o}}if(W(t)){if(e==="dumps"){let s=W(n[1]??h)?n[1]:void 0,o=s?s.data.get("indent"):void 0;return JSON.stringify(this.pyToJs(n[0]??h),null,o)}if(e==="loads")return this.jsToPy(JSON.parse(I(n[0]??"")))}if(Rt(t)){let s=t.attrs.get(e)??t.cls.methods.get(e)??h;if(pt(s)){let o=new Map(s.closure);return o.set("self",t),s.params.slice(1).forEach((a,l)=>o.set(a,n[l]??h)),this.execBlock(s.body,o)}}throw new O("AttributeError",`'${Ct(t)}' object has no attribute '${e}'`)}pyStringFormat(t,e){let n=0;return t.replace(/%([diouxXeEfFgGcrs%])/g,(i,s)=>{if(s==="%")return"%";let o=e[n++];switch(s){case"d":case"i":return String(Math.trunc(o));case"f":return o.toFixed(6);case"s":return I(o??h);case"r":return Q(o??h);default:return String(o)}})}pyToJs(t){return wt(t)?null:W(t)?Object.fromEntries([...t.data.entries()].map(([e,n])=>[e,this.pyToJs(n)])):Array.isArray(t)?t.map(e=>this.pyToJs(e)):t}jsToPy(t){return t==null?h:typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:Array.isArray(t)?t.map(e=>this.jsToPy(e)):typeof t=="object"?j(Object.entries(t).map(([e,n])=>[e,this.jsToPy(n)])):h}callBuiltin(t,e,n){if(n.has(t)){let i=n.get(t)??h;return pt(i)?this.callFunc(i,e,n):Se(i)?this.instantiate(i,e,n):i}switch(t){case"print":return this.output.push(e.map(I).join(" ")+`
158
- `.replace(/\\n/g,"")),h;case"input":return this.output.push(I(e[0]??"")),"";case"int":{if(e.length===0)return 0;let i=e[1]??10,s=parseInt(I(e[0]??0),i);return Number.isNaN(s)?(()=>{throw new O("ValueError","invalid literal for int()")})():s}case"float":{if(e.length===0)return 0;let i=parseFloat(I(e[0]??0));return Number.isNaN(i)?(()=>{throw new O("ValueError","could not convert to float")})():i}case"str":return e.length===0?"":I(e[0]??h);case"bool":return e.length===0?!1:ot(e[0]??h);case"list":return e.length===0?[]:J(e[0]??[]);case"tuple":return e.length===0?[]:J(e[0]??[]);case"set":return e.length===0?[]:[...new Set(J(e[0]??[]).map(Q))].map(i=>J(e[0]??[]).find(o=>Q(o)===i)??h);case"dict":return e.length===0?j():W(e[0]??h)?e[0]:j();case"bytes":return typeof e[0]=="string"?e[0]:I(e[0]??"");case"bytearray":return e.length===0?"":I(e[0]??"");case"type":return e.length===1?`<class '${Ct(e[0]??h)}'>`:h;case"isinstance":return Ct(e[0]??h)===I(e[1]??"");case"issubclass":return!1;case"callable":return pt(e[0]??h);case"hasattr":return W(e[0]??h)?e[0].data.has(I(e[1]??"")):!1;case"getattr":return W(e[0]??h)?e[0].data.get(I(e[1]??""))??e[2]??h:e[2]??h;case"setattr":return W(e[0]??h)&&e[0].data.set(I(e[1]??""),e[2]??h),h;case"len":{let i=e[0]??h;if(typeof i=="string"||Array.isArray(i))return i.length;if(W(i))return i.data.size;if(Mt(i))return cn(i);throw new O("TypeError",`object of type '${Ct(i)}' has no len()`)}case"range":return e.length===1?we(0,e[0]):e.length===2?we(e[0],e[1]):we(e[0],e[1],e[2]);case"enumerate":{let i=e[1]??0;return J(e[0]??[]).map((s,o)=>[o+i,s])}case"zip":{let i=e.map(J),s=Math.min(...i.map(o=>o.length));return Array.from({length:s},(o,a)=>i.map(l=>l[a]??h))}case"map":{let i=e[0]??h;return J(e[1]??[]).map(s=>pt(i)?this.callFunc(i,[s],n):h)}case"filter":{let i=e[0]??h;return J(e[1]??[]).filter(s=>pt(i)?ot(this.callFunc(i,[s],n)):ot(s))}case"reduce":{let i=e[0]??h,s=J(e[1]??[]);if(s.length===0)return e[2]??h;let o=e[2]!==void 0?e[2]:s[0];for(let a of e[2]!==void 0?s:s.slice(1))o=pt(i)?this.callFunc(i,[o,a],n):h;return o}case"sorted":{let i=[...J(e[0]??[])],s=e[1]??h,o=W(s)?s.data.get("key")??h:s;return i.sort((a,l)=>{let c=pt(o)?this.callFunc(o,[a],n):a,u=pt(o)?this.callFunc(o,[l],n):l;return typeof c=="number"&&typeof u=="number"?c-u:I(c).localeCompare(I(u))}),i}case"reversed":return[...J(e[0]??[])].reverse();case"any":return J(e[0]??[]).some(ot);case"all":return J(e[0]??[]).every(ot);case"sum":return J(e[0]??[]).reduce((i,s)=>i+s,e[1]??0);case"max":return(e.length===1?J(e[0]??[]):e).reduce((s,o)=>s>=o?s:o);case"min":return(e.length===1?J(e[0]??[]):e).reduce((s,o)=>s<=o?s:o);case"abs":return Math.abs(e[0]??0);case"round":return e[1]!==void 0?parseFloat(e[0].toFixed(e[1])):Math.round(e[0]??0);case"divmod":{let i=e[0],s=e[1];return[Math.floor(i/s),i%s]}case"pow":return e[0]**e[1];case"hex":return`0x${e[0].toString(16)}`;case"oct":return`0o${e[0].toString(8)}`;case"bin":return`0b${e[0].toString(2)}`;case"ord":return I(e[0]??"").charCodeAt(0);case"chr":return String.fromCharCode(e[0]??0);case"id":return Math.floor(Math.random()*4294967295);case"hash":return typeof e[0]=="number"?e[0]:I(e[0]??"").split("").reduce((i,s)=>i*31+s.charCodeAt(0)|0,0);case"open":throw new O("PermissionError","open() not available in virtual runtime");case"repr":return Q(e[0]??h);case"iter":return e[0]??h;case"next":return Array.isArray(e[0])&&e[0].length>0?e[0].shift():e[1]??(()=>{throw new O("StopIteration","")})();case"vars":return j([...n.entries()].map(([i,s])=>[i,s]));case"globals":return j([...n.entries()].map(([i,s])=>[i,s]));case"locals":return j([...n.entries()].map(([i,s])=>[i,s]));case"dir":{if(e.length===0)return[...n.keys()];let i=e[0]??h;return typeof i=="string"?["upper","lower","strip","split","join","replace","find","format","encode","startswith","endswith","count","isdigit","isalpha","title","capitalize"]:Array.isArray(i)?["append","extend","insert","pop","remove","index","count","sort","reverse","copy","clear"]:W(i)?["keys","values","items","get","update","pop","clear","copy","setdefault"]:[]}case"Exception":case"ValueError":case"TypeError":case"KeyError":case"IndexError":case"AttributeError":case"NameError":case"RuntimeError":case"StopIteration":case"NotImplementedError":case"OSError":case"IOError":throw new O(t,I(e[0]??""));case"exec":return this.execScript(I(e[0]??""),n),h;case"eval":return this.pyEval(I(e[0]??""),n);default:throw new O("NameError",`name '${t}' is not defined`)}}callFunc(t,e,n){let i=new Map(t.closure);t.params.forEach((s,o)=>{if(s.startsWith("*")){i.set(s.slice(1),e.slice(o));return}i.set(s,e[o]??h)});try{return this.execBlock(t.body,i)}catch(s){if(s instanceof kt)return s.value;throw s}}instantiate(t,e,n){let i={__pytype__:"instance",cls:t,attrs:new Map};return t.methods.get("__init__")&&this.callMethod(i,"__init__",e,n),i}execScript(t,e){let n=t.split(`
159
- `);this.execLines(n,0,e)}execLines(t,e,n){let i=e;for(;i<t.length;){let s=t[i];if(!s.trim()||s.trim().startsWith("#")){i++;continue}i=this.execStatement(t,i,n)}return i}execBlock(t,e){try{this.execLines(t,0,e)}catch(n){if(n instanceof kt)return n.value;throw n}return h}getIndent(t){let e=0;for(let n of t)if(n===" ")e++;else if(n===" ")e+=4;else break;return e}collectBlock(t,e,n){let i=[];for(let s=e;s<t.length;s++){let o=t[s];if(!o.trim()){i.push("");continue}if(this.getIndent(o)<=n)break;i.push(o.slice(n+4))}return i}execStatement(t,e,n){let i=t[e],s=i.trim(),o=this.getIndent(i);if(s==="pass")return e+1;if(s==="break")throw new Dt;if(s==="continue")throw new _t;let a=s.match(/^return(?:\s+(.+))?$/);if(a)throw new kt(a[1]?this.pyEval(a[1],n):h);let l=s.match(/^raise(?:\s+(.+))?$/);if(l){if(l[1]){let b=this.pyEval(l[1],n);throw new O(typeof b=="string"?b:Ct(b),I(b))}throw new O("RuntimeError","")}let c=s.match(/^assert\s+(.+?)(?:,\s*(.+))?$/);if(c){if(!ot(this.pyEval(c[1],n)))throw new O("AssertionError",c[2]?I(this.pyEval(c[2],n)):"");return e+1}let u=s.match(/^del\s+(.+)$/);if(u)return n.delete(u[1].trim()),e+1;let d=s.match(/^import\s+(\w+)(?:\s+as\s+(\w+))?$/);if(d){let[,b,P]=d,R=ln[b];if(R){let v=R(this.cwd);this.modules.set(b,v),n.set(P??b,v)}return e+1}let m=s.match(/^from\s+(\w+)\s+import\s+(.+)$/);if(m){let[,b,P]=m,R=ln[b];if(R){let v=R(this.cwd);if(P?.trim()==="*")for(let[C,N]of v.data)n.set(C,N);else for(let C of P.split(",").map(N=>N.trim()))n.set(C,v.data.get(C)??h)}return e+1}let p=s.match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(p){let[,b,P]=p,R=P.split(",").map(N=>N.trim()).filter(Boolean),v=this.collectBlock(t,e+1,o),C={__pytype__:"func",name:b,params:R,body:v,closure:new Map(n)};return n.set(b,C),e+1+v.length}let w=s.match(/^class\s+(\w+)(?:\(([^)]*)\))?\s*:$/);if(w){let[,b,P]=w,R=P?P.split(",").map(G=>G.trim()):[],v=this.collectBlock(t,e+1,o),C={__pytype__:"class",name:b,methods:new Map,bases:R},N=0;for(;N<v.length;){let B=v[N].trim().match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(B){let[,Z,gt]=B,lt=gt.split(",").map(A=>A.trim()).filter(Boolean),yt=this.collectBlock(v,N+1,0);C.methods.set(Z,{__pytype__:"func",name:Z,params:lt,body:yt,closure:new Map(n)}),N+=1+yt.length}else N++}return n.set(b,C),e+1+v.length}if(s.startsWith("if ")&&s.endsWith(":")){let b=s.slice(3,-1).trim(),P=this.collectBlock(t,e+1,o),R=P.length+1;if(ot(this.pyEval(b,n))){this.execBlock(P,new Map(n).also?.(N=>{for(let[G,B]of n)N.set(G,B)})??n),this.runBlockInScope(P,n);let C=e+1+P.length;for(;C<t.length;){let N=t[C].trim();if(this.getIndent(t[C])<o||!N.startsWith("elif")&&!N.startsWith("else"))break;let G=this.collectBlock(t,C+1,o);C+=1+G.length}return C}let v=e+1+P.length;for(;v<t.length;){let C=t[v],N=C.trim();if(this.getIndent(C)!==o)break;let G=N.match(/^elif\s+(.+):$/);if(G){let B=this.collectBlock(t,v+1,o);if(ot(this.pyEval(G[1],n))){for(this.runBlockInScope(B,n),v+=1+B.length;v<t.length;){let Z=t[v].trim();if(this.getIndent(t[v])!==o||!Z.startsWith("elif")&&!Z.startsWith("else"))break;let gt=this.collectBlock(t,v+1,o);v+=1+gt.length}return v}v+=1+B.length;continue}if(N==="else:"){let B=this.collectBlock(t,v+1,o);return this.runBlockInScope(B,n),v+1+B.length}break}return v}let g=s.match(/^for\s+(.+?)\s+in\s+(.+?)\s*:$/);if(g){let[,b,P]=g,R=J(this.pyEval(P.trim(),n)),v=this.collectBlock(t,e+1,o),C=[],N=e+1+v.length;N<t.length&&t[N]?.trim()==="else:"&&(C=this.collectBlock(t,N+1,o),N+=1+C.length);let G=!1;for(let B of R){if(b.includes(",")){let Z=b.split(",").map(lt=>lt.trim()),gt=Array.isArray(B)?B:[B];Z.forEach((lt,yt)=>n.set(lt,gt[yt]??h))}else n.set(b.trim(),B);try{this.runBlockInScope(v,n)}catch(Z){if(Z instanceof Dt){G=!0;break}if(Z instanceof _t)continue;throw Z}}return!G&&C.length&&this.runBlockInScope(C,n),N}let f=s.match(/^while\s+(.+?)\s*:$/);if(f){let b=f[1],P=this.collectBlock(t,e+1,o),R=0;for(;ot(this.pyEval(b,n))&&R++<1e5;)try{this.runBlockInScope(P,n)}catch(v){if(v instanceof Dt)break;if(v instanceof _t)continue;throw v}return e+1+P.length}if(s==="try:"){let b=this.collectBlock(t,e+1,o),P=e+1+b.length,R=[],v=[],C=[];for(;P<t.length;){let G=t[P],B=G.trim();if(this.getIndent(G)!==o)break;if(B.startsWith("except")){let Z=B.match(/^except(?:\s+(\w+)(?:\s+as\s+(\w+))?)?\s*:$/),gt=Z?.[1]??null,lt=Z?.[2],yt=this.collectBlock(t,P+1,o);R.push({exc:gt,body:yt}),lt&&n.set(lt,""),P+=1+yt.length}else if(B==="else:")C=this.collectBlock(t,P+1,o),P+=1+C.length;else if(B==="finally:")v=this.collectBlock(t,P+1,o),P+=1+v.length;else break}let N=null;try{this.runBlockInScope(b,n),C.length&&this.runBlockInScope(C,n)}catch(G){if(G instanceof O){N=G;let B=!1;for(let Z of R)if(Z.exc===null||Z.exc===G.type||Z.exc==="Exception"){this.runBlockInScope(Z.body,n),B=!0;break}if(!B)throw G}else throw G}finally{v.length&&this.runBlockInScope(v,n)}return P}let $=s.match(/^with\s+(.+?)\s+as\s+(\w+)\s*:$/);if($){let b=this.collectBlock(t,e+1,o);return n.set($[2],h),this.runBlockInScope(b,n),e+1+b.length}let E=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(\+=|-=|\*=|\/\/=|\/=|%=|\*\*=|&=|\|=)\s*(.+)$/);if(E){let[,b,P,R]=E,v=n.get(b)??0,C=this.pyEval(R,n),N;switch(P){case"+=":N=typeof v=="string"?v+I(C):v+C;break;case"-=":N=v-C;break;case"*=":N=v*C;break;case"/=":N=v/C;break;case"//=":N=Math.floor(v/C);break;case"%=":N=v%C;break;case"**=":N=v**C;break;default:N=C}return n.set(b,N),e+1}let F=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\[(.+)\]\s*=\s*(.+)$/);if(F){let[,b,P,R]=F,v=n.get(b)??h,C=this.pyEval(R,n)??h,N=this.pyEval(P,n)??h;return Array.isArray(v)?v[N]=C:W(v)&&v.data.set(I(N),C),e+1}let S=s.match(/^([A-Za-z_][A-Za-z0-9_.]+)\s*=\s*(.+)$/);if(S){let b=S[1].lastIndexOf(".");if(b!==-1){let P=S[1].slice(0,b),R=S[1].slice(b+1),v=this.pyEval(S[2],n),C=this.pyEval(P,n);return W(C)?C.data.set(R,v):Rt(C)&&C.attrs.set(R,v),e+1}}let k=s.match(/^([A-Za-z_][A-Za-z0-9_,\s]*),\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$/);if(k){let b=this.pyEval(k[3],n),P=s.split("=")[0].split(",").map(v=>v.trim()),R=J(b);return P.forEach((v,C)=>n.set(v,R[C]??h)),e+1}let V=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=]+)?\s*=\s*(.+)$/);if(V){let[,b,P]=V;return n.set(b,this.pyEval(P,n)),e+1}try{this.pyEval(s,n)}catch(b){if(b instanceof O||b instanceof zt)throw b}return e+1}runBlockInScope(t,e){this.execLines(t,0,e)}run(t){let e=ei(this.cwd);try{this.execScript(t,e)}catch(n){return n instanceof zt?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:n.code}:n instanceof O?(this.stderr.push(n.toString()),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1}):n instanceof kt?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}:(this.stderr.push(`RuntimeError: ${n}`),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1})}return{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}}},un={name:"python3",aliases:["python"],description:"Python 3 interpreter (virtual)",category:"system",params:["[--version] [-c <code>] [-V] [file]"],run:({args:r,shell:t,cwd:e})=>{if(!t.packageManager.isInstalled("python3"))return{stderr:`bash: python3: command not found
161
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\").replace(/\\'/g,"'").replace(/\\"/g,'"');let n=t.match(/^f(['"])([\s\S]*)\1$/);if(n){let c=n[2];return c=c.replace(/\{([^{}]+)\}/g,(u,d)=>{try{return V(this.pyEval(d.trim(),e))}catch{return`{${d}}`}}),c}let i=t.match(/^b(['"])(.*)\1$/s);if(i)return i[2];if(t.startsWith("[")&&t.endsWith("]")){let c=t.slice(1,-1).trim();if(!c)return[];let u=c.match(/^(.+?)\s+for\s+(\w+)\s+in\s+(.+?)(?:\s+if\s+(.+))?$/);if(u){let[,d,m,p,y]=u,g=Q(this.pyEval(p.trim(),e)),f=[];for(let $ of g){let N=new Map(e);N.set(m,$),!(y&&!lt(this.pyEval(y,N)))&&f.push(this.pyEval(d.trim(),N))}return f}return this.splitArgs(c).map(d=>this.pyEval(d,e))}if(t.startsWith("(")&&t.endsWith(")")){let c=t.slice(1,-1).trim();if(!c)return[];let u=this.splitArgs(c);return u.length===1&&!c.endsWith(",")?this.pyEval(u[0],e):u.map(d=>this.pyEval(d,e))}if(t.startsWith("{")&&t.endsWith("}")){let c=t.slice(1,-1).trim();if(!c)return q();let u=q();for(let d of this.splitArgs(c)){let m=d.indexOf(":");if(m===-1)continue;let p=V(this.pyEval(d.slice(0,m).trim(),e)),y=this.pyEval(d.slice(m+1).trim(),e);u.data.set(p,y)}return u}let s=t.match(/^not\s+(.+)$/);if(s)return!lt(this.pyEval(s[1],e));let o=[["or"],["and"],["in","not in","is not","is","==","!=","<=",">=","<",">"],["+","-"],["**"],["*","//","/","%"]];for(let c of o){let u=this.tryBinaryOp(t,c,e);if(u!==void 0)return u}if(t.startsWith("-")){let c=this.pyEval(t.slice(1),e);if(typeof c=="number")return-c}if(process.env.PY_DEBUG&&console.error("eval:",JSON.stringify(t)),t.endsWith("]")&&!t.startsWith("[")){let c=this.findMatchingBracket(t,"[");if(c!==-1){let u=this.pyEval(t.slice(0,c),e),d=t.slice(c+1,-1);return this.subscript(u,d,e)}}let a=t.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*\(([\s\S]*)\)$/);if(a){let[,c,u]=a,d=(u?.trim()?this.splitArgs(u):[]).map(m=>this.pyEval(m,e));return this.callBuiltin(c,d,e)}let l=this.findDotAccess(t);if(l){let{objExpr:c,attr:u,callPart:d}=l,m=this.pyEval(c,e);if(d!==void 0){let p=d.slice(1,-1),y=p.trim()?this.splitArgs(p).map(g=>this.pyEval(g,e)):[];return this.callMethod(m,u,y,e)}return this.getAttr(m,u,e)}if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)){if(e.has(t))return e.get(t);throw new H("NameError",`name '${t}' is not defined`)}if(/^[A-Za-z_][A-Za-z0-9_.]+$/.test(t)){let c=t.split("."),u=e.get(c[0])??(()=>{throw new H("NameError",`name '${c[0]}' is not defined`)})();for(let d of c.slice(1))u=this.getAttr(u,d,e);return u}return h}findMatchingBracket(t,e){let n=e==="["?"]":e==="("?")":"}",i=0;for(let s=t.length-1;s>=0;s--)if(t[s]===n&&i++,t[s]===e&&(i--,i===0))return s;return-1}findDotAccess(t){let e=0,n=!1,i="";for(let s=t.length-1;s>0;s--){let o=t[s];if(n){o===i&&t[s-1]!=="\\"&&(n=!1);continue}if(o==='"'||o==="'"){n=!0,i=o;continue}if(")]}".includes(o)){e++;continue}if("([{".includes(o)){e--;continue}if(e!==0||o!==".")continue;let a=t.slice(0,s).trim(),c=t.slice(s+1).match(/^(\w+)(\([\s\S]*\))?$/);if(c&&!/^-?\d+$/.test(a))return{objExpr:a,attr:c[1],callPart:c[2]}}return null}tryBinaryOp(t,e,n){let i=0,s=!1,o="";for(let a=t.length-1;a>=0;a--){let l=t[a];if(s){l===o&&t[a-1]!=="\\"&&(s=!1);continue}if(l==='"'||l==="'"){s=!0,o=l;continue}if(")]}".includes(l)){i++;continue}if("([{".includes(l)){i--;continue}if(i===0){for(let c of e)if(t.slice(a,a+c.length)===c){if(c==="*"&&(t[a+1]==="*"||t[a-1]==="*"))continue;let u=t[a-1],d=t[a+c.length];if(/^[a-z]/.test(c)&&(u&&/\w/.test(u)||d&&/\w/.test(d)))continue;let p=t.slice(0,a).trim(),y=t.slice(a+c.length).trim();if(!p||!y)continue;return this.applyBinaryOp(c,p,y,n)}}}}applyBinaryOp(t,e,n,i){if(t==="and"){let a=this.pyEval(e,i);return lt(a)?this.pyEval(n,i):a}if(t==="or"){let a=this.pyEval(e,i);return lt(a)?a:this.pyEval(n,i)}let s=this.pyEval(e,i),o=this.pyEval(n,i);switch(t){case"+":return typeof s=="string"&&typeof o=="string"?s+o:Array.isArray(s)&&Array.isArray(o)?[...s,...o]:s+o;case"-":return s-o;case"*":if(typeof s=="string"&&typeof o=="number")return s.repeat(o);if(Array.isArray(s)&&typeof o=="number"){let a=[];for(let l=0;l<o;l++)a.push(...s);return a}return s*o;case"/":{if(o===0)throw new H("ZeroDivisionError","division by zero");return s/o}case"//":{if(o===0)throw new H("ZeroDivisionError","integer division or modulo by zero");return Math.floor(s/o)}case"%":{if(typeof s=="string")return this.pyStringFormat(s,Array.isArray(o)?o:[o]);if(o===0)throw new H("ZeroDivisionError","integer division or modulo by zero");return s%o}case"**":return s**o;case"==":return Y(s)===Y(o)||s===o;case"!=":return Y(s)!==Y(o)&&s!==o;case"<":return s<o;case"<=":return s<=o;case">":return s>o;case">=":return s>=o;case"in":return this.pyIn(o,s);case"not in":return!this.pyIn(o,s);case"is":return s===o||St(s)&&St(o);case"is not":return!(s===o||St(s)&&St(o))}return h}pyIn(t,e){return typeof t=="string"?typeof e=="string"&&t.includes(e):Array.isArray(t)?t.some(n=>Y(n)===Y(e)):j(t)?t.data.has(V(e)):!1}subscript(t,e,n){if(e.includes(":")){let s=e.split(":").map(l=>l.trim()),o=s[0]?this.pyEval(s[0],n):void 0,a=s[1]?this.pyEval(s[1],n):void 0;return typeof t=="string"||Array.isArray(t)?t.slice(o,a):h}let i=this.pyEval(e,n);if(Array.isArray(t)){let s=i;return s<0&&(s=t.length+s),t[s]??h}if(typeof t=="string"){let s=i;return s<0&&(s=t.length+s),t[s]??h}if(j(t))return t.data.get(V(i))??h;throw new H("TypeError",`'${$t(t)}' is not subscriptable`)}getAttr(t,e,n){return j(t)?t.data.has(e)?t.data.get(e):e==="path"&&t.path?t.path:h:zt(t)?t.attrs.get(e)??h:typeof t=="string"?{__class__:{__pytype__:"class",name:"str"}}[e]??h:h}callMethod(t,e,n,i){if(typeof t=="string")switch(e){case"upper":return t.toUpperCase();case"lower":return t.toLowerCase();case"strip":return(n[0]?t.replace(new RegExp(`[${n[0]}]+`,"g"),""):t).trim();case"lstrip":return t.trimStart();case"rstrip":return t.trimEnd();case"split":return t.split(typeof n[0]=="string"?n[0]:/\s+/).filter((s,o)=>o>0||s!=="");case"splitlines":return t.split(`
162
+ `);case"join":return Q(n[0]??[]).map(V).join(t);case"replace":return t.replaceAll(V(n[0]??""),V(n[1]??""));case"startswith":return t.startsWith(V(n[0]??""));case"endswith":return t.endsWith(V(n[0]??""));case"find":return t.indexOf(V(n[0]??""));case"index":{let s=t.indexOf(V(n[0]??""));if(s===-1)throw new H("ValueError","substring not found");return s}case"count":return t.split(V(n[0]??"")).length-1;case"format":return this.pyStringFormat(t,n);case"encode":return t;case"decode":return t;case"isdigit":return/^\d+$/.test(t);case"isalpha":return/^[a-zA-Z]+$/.test(t);case"isalnum":return/^[a-zA-Z0-9]+$/.test(t);case"isspace":return/^\s+$/.test(t);case"isupper":return t===t.toUpperCase()&&t!==t.toLowerCase();case"islower":return t===t.toLowerCase()&&t!==t.toUpperCase();case"center":{let s=n[0]??0,o=V(n[1]??" ");return t.padStart(Math.floor((s+t.length)/2),o).padEnd(s,o)}case"ljust":return t.padEnd(n[0]??0,V(n[1]??" "));case"rjust":return t.padStart(n[0]??0,V(n[1]??" "));case"zfill":return t.padStart(n[0]??0,"0");case"title":return t.replace(/\b\w/g,s=>s.toUpperCase());case"capitalize":return t[0]?.toUpperCase()+t.slice(1).toLowerCase();case"swapcase":return[...t].map(s=>s===s.toUpperCase()?s.toLowerCase():s.toUpperCase()).join("")}if(Array.isArray(t))switch(e){case"append":return t.push(n[0]??h),h;case"extend":for(let s of Q(n[0]??[]))t.push(s);return h;case"insert":return t.splice(n[0]??0,0,n[1]??h),h;case"pop":{let s=n[0]!==void 0?n[0]:-1,o=s<0?t.length+s:s;return t.splice(o,1)[0]??h}case"remove":{let s=t.findIndex(o=>Y(o)===Y(n[0]??h));return s!==-1&&t.splice(s,1),h}case"index":{let s=t.findIndex(o=>Y(o)===Y(n[0]??h));if(s===-1)throw new H("ValueError","is not in list");return s}case"count":return t.filter(s=>Y(s)===Y(n[0]??h)).length;case"sort":return t.sort((s,o)=>typeof s=="number"&&typeof o=="number"?s-o:V(s).localeCompare(V(o))),h;case"reverse":return t.reverse(),h;case"copy":return[...t];case"clear":return t.splice(0),h}if(j(t))switch(e){case"keys":return[...t.data.keys()];case"values":return[...t.data.values()];case"items":return[...t.data.entries()].map(([s,o])=>[s,o]);case"get":return t.data.get(V(n[0]??""))??n[1]??h;case"update":{if(j(n[0]??h))for(let[s,o]of n[0].data)t.data.set(s,o);return h}case"pop":{let s=V(n[0]??""),o=t.data.get(s)??n[1]??h;return t.data.delete(s),o}case"clear":return t.data.clear(),h;case"copy":return q([...t.data.entries()]);case"setdefault":{let s=V(n[0]??"");return t.data.has(s)||t.data.set(s,n[1]??h),t.data.get(s)??h}}if(j(t)&&t.data.has("name")&&t.data.get("name")==="posix")switch(e){case"getcwd":return this.cwd;case"getenv":return typeof n[0]=="string"?process.env[n[0]]??n[1]??h:h;case"listdir":return[];case"path":return t}if(j(t))switch(e){case"join":return n.map(V).join("/").replace(/\/+/g,"/");case"exists":return!1;case"dirname":return V(n[0]??"").split("/").slice(0,-1).join("/")||"/";case"basename":return V(n[0]??"").split("/").pop()??"";case"abspath":return V(n[0]??"");case"splitext":{let s=V(n[0]??""),o=s.lastIndexOf(".");return o>0?[s.slice(0,o),s.slice(o)]:[s,""]}case"isfile":return!1;case"isdir":return!1}if(j(t)&&t.data.has("version")&&t.data.get("version")===re&&e==="exit")throw new Ut(n[0]??0);if(j(t)){let s={sqrt:Math.sqrt,floor:Math.floor,ceil:Math.ceil,fabs:Math.abs,log:Math.log,log2:Math.log2,log10:Math.log10,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,pow:Math.pow,exp:Math.exp,hypot:Math.hypot};if(e in s){let o=s[e];return o(...n.map(a=>a))}if(e==="factorial"){let o=n[0]??0,a=1;for(;o>1;)a*=o--;return a}if(e==="gcd"){let o=Math.abs(n[0]??0),a=Math.abs(n[1]??0);for(;a;)[o,a]=[a,o%a];return o}}if(j(t)){if(e==="dumps"){let s=j(n[1]??h)?n[1]:void 0,o=s?s.data.get("indent"):void 0;return JSON.stringify(this.pyToJs(n[0]??h),null,o)}if(e==="loads")return this.jsToPy(JSON.parse(V(n[0]??"")))}if(zt(t)){let s=t.attrs.get(e)??t.cls.methods.get(e)??h;if(gt(s)){let o=new Map(s.closure);return o.set("self",t),s.params.slice(1).forEach((a,l)=>o.set(a,n[l]??h)),this.execBlock(s.body,o)}}throw new H("AttributeError",`'${$t(t)}' object has no attribute '${e}'`)}pyStringFormat(t,e){let n=0;return t.replace(/%([diouxXeEfFgGcrs%])/g,(i,s)=>{if(s==="%")return"%";let o=e[n++];switch(s){case"d":case"i":return String(Math.trunc(o));case"f":return o.toFixed(6);case"s":return V(o??h);case"r":return Y(o??h);default:return String(o)}})}pyToJs(t){return St(t)?null:j(t)?Object.fromEntries([...t.data.entries()].map(([e,n])=>[e,this.pyToJs(n)])):Array.isArray(t)?t.map(e=>this.pyToJs(e)):t}jsToPy(t){return t==null?h:typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:Array.isArray(t)?t.map(e=>this.jsToPy(e)):typeof t=="object"?q(Object.entries(t).map(([e,n])=>[e,this.jsToPy(n)])):h}callBuiltin(t,e,n){if(n.has(t)){let i=n.get(t)??h;return gt(i)?this.callFunc(i,e,n):ve(i)?this.instantiate(i,e,n):i}switch(t){case"print":return this.output.push(e.map(V).join(" ")+`
163
+ `.replace(/\\n/g,"")),h;case"input":return this.output.push(V(e[0]??"")),"";case"int":{if(e.length===0)return 0;let i=e[1]??10,s=parseInt(V(e[0]??0),i);return Number.isNaN(s)?(()=>{throw new H("ValueError","invalid literal for int()")})():s}case"float":{if(e.length===0)return 0;let i=parseFloat(V(e[0]??0));return Number.isNaN(i)?(()=>{throw new H("ValueError","could not convert to float")})():i}case"str":return e.length===0?"":V(e[0]??h);case"bool":return e.length===0?!1:lt(e[0]??h);case"list":return e.length===0?[]:Q(e[0]??[]);case"tuple":return e.length===0?[]:Q(e[0]??[]);case"set":return e.length===0?[]:[...new Set(Q(e[0]??[]).map(Y))].map(i=>Q(e[0]??[]).find(o=>Y(o)===i)??h);case"dict":return e.length===0?q():j(e[0]??h)?e[0]:q();case"bytes":return typeof e[0]=="string"?e[0]:V(e[0]??"");case"bytearray":return e.length===0?"":V(e[0]??"");case"type":return e.length===1?`<class '${$t(e[0]??h)}'>`:h;case"isinstance":return $t(e[0]??h)===V(e[1]??"");case"issubclass":return!1;case"callable":return gt(e[0]??h);case"hasattr":return j(e[0]??h)?e[0].data.has(V(e[1]??"")):!1;case"getattr":return j(e[0]??h)?e[0].data.get(V(e[1]??""))??e[2]??h:e[2]??h;case"setattr":return j(e[0]??h)&&e[0].data.set(V(e[1]??""),e[2]??h),h;case"len":{let i=e[0]??h;if(typeof i=="string"||Array.isArray(i))return i.length;if(j(i))return i.data.size;if(Ft(i))return fn(i);throw new H("TypeError",`object of type '${$t(i)}' has no len()`)}case"range":return e.length===1?be(0,e[0]):e.length===2?be(e[0],e[1]):be(e[0],e[1],e[2]);case"enumerate":{let i=e[1]??0;return Q(e[0]??[]).map((s,o)=>[o+i,s])}case"zip":{let i=e.map(Q),s=Math.min(...i.map(o=>o.length));return Array.from({length:s},(o,a)=>i.map(l=>l[a]??h))}case"map":{let i=e[0]??h;return Q(e[1]??[]).map(s=>gt(i)?this.callFunc(i,[s],n):h)}case"filter":{let i=e[0]??h;return Q(e[1]??[]).filter(s=>gt(i)?lt(this.callFunc(i,[s],n)):lt(s))}case"reduce":{let i=e[0]??h,s=Q(e[1]??[]);if(s.length===0)return e[2]??h;let o=e[2]!==void 0?e[2]:s[0];for(let a of e[2]!==void 0?s:s.slice(1))o=gt(i)?this.callFunc(i,[o,a],n):h;return o}case"sorted":{let i=[...Q(e[0]??[])],s=e[1]??h,o=j(s)?s.data.get("key")??h:s;return i.sort((a,l)=>{let c=gt(o)?this.callFunc(o,[a],n):a,u=gt(o)?this.callFunc(o,[l],n):l;return typeof c=="number"&&typeof u=="number"?c-u:V(c).localeCompare(V(u))}),i}case"reversed":return[...Q(e[0]??[])].reverse();case"any":return Q(e[0]??[]).some(lt);case"all":return Q(e[0]??[]).every(lt);case"sum":return Q(e[0]??[]).reduce((i,s)=>i+s,e[1]??0);case"max":return(e.length===1?Q(e[0]??[]):e).reduce((s,o)=>s>=o?s:o);case"min":return(e.length===1?Q(e[0]??[]):e).reduce((s,o)=>s<=o?s:o);case"abs":return Math.abs(e[0]??0);case"round":return e[1]!==void 0?parseFloat(e[0].toFixed(e[1])):Math.round(e[0]??0);case"divmod":{let i=e[0],s=e[1];return[Math.floor(i/s),i%s]}case"pow":return e[0]**e[1];case"hex":return`0x${e[0].toString(16)}`;case"oct":return`0o${e[0].toString(8)}`;case"bin":return`0b${e[0].toString(2)}`;case"ord":return V(e[0]??"").charCodeAt(0);case"chr":return String.fromCharCode(e[0]??0);case"id":return Math.floor(Math.random()*4294967295);case"hash":return typeof e[0]=="number"?e[0]:V(e[0]??"").split("").reduce((i,s)=>i*31+s.charCodeAt(0)|0,0);case"open":throw new H("PermissionError","open() not available in virtual runtime");case"repr":return Y(e[0]??h);case"iter":return e[0]??h;case"next":return Array.isArray(e[0])&&e[0].length>0?e[0].shift():e[1]??(()=>{throw new H("StopIteration","")})();case"vars":return q([...n.entries()].map(([i,s])=>[i,s]));case"globals":return q([...n.entries()].map(([i,s])=>[i,s]));case"locals":return q([...n.entries()].map(([i,s])=>[i,s]));case"dir":{if(e.length===0)return[...n.keys()];let i=e[0]??h;return typeof i=="string"?["upper","lower","strip","split","join","replace","find","format","encode","startswith","endswith","count","isdigit","isalpha","title","capitalize"]:Array.isArray(i)?["append","extend","insert","pop","remove","index","count","sort","reverse","copy","clear"]:j(i)?["keys","values","items","get","update","pop","clear","copy","setdefault"]:[]}case"Exception":case"ValueError":case"TypeError":case"KeyError":case"IndexError":case"AttributeError":case"NameError":case"RuntimeError":case"StopIteration":case"NotImplementedError":case"OSError":case"IOError":throw new H(t,V(e[0]??""));case"exec":return this.execScript(V(e[0]??""),n),h;case"eval":return this.pyEval(V(e[0]??""),n);default:throw new H("NameError",`name '${t}' is not defined`)}}callFunc(t,e,n){let i=new Map(t.closure);t.params.forEach((s,o)=>{if(s.startsWith("*")){i.set(s.slice(1),e.slice(o));return}i.set(s,e[o]??h)});try{return this.execBlock(t.body,i)}catch(s){if(s instanceof Mt)return s.value;throw s}}instantiate(t,e,n){let i={__pytype__:"instance",cls:t,attrs:new Map};return t.methods.get("__init__")&&this.callMethod(i,"__init__",e,n),i}execScript(t,e){let n=t.split(`
164
+ `);this.execLines(n,0,e)}execLines(t,e,n){let i=e;for(;i<t.length;){let s=t[i];if(!s.trim()||s.trim().startsWith("#")){i++;continue}i=this.execStatement(t,i,n)}return i}execBlock(t,e){try{this.execLines(t,0,e)}catch(n){if(n instanceof Mt)return n.value;throw n}return h}getIndent(t){let e=0;for(let n of t)if(n===" ")e++;else if(n===" ")e+=4;else break;return e}collectBlock(t,e,n){let i=[];for(let s=e;s<t.length;s++){let o=t[s];if(!o.trim()){i.push("");continue}if(this.getIndent(o)<=n)break;i.push(o.slice(n+4))}return i}execStatement(t,e,n){let i=t[e],s=i.trim(),o=this.getIndent(i);if(s==="pass")return e+1;if(s==="break")throw new Lt;if(s==="continue")throw new Tt;let a=s.match(/^return(?:\s+(.+))?$/);if(a)throw new Mt(a[1]?this.pyEval(a[1],n):h);let l=s.match(/^raise(?:\s+(.+))?$/);if(l){if(l[1]){let b=this.pyEval(l[1],n);throw new H(typeof b=="string"?b:$t(b),V(b))}throw new H("RuntimeError","")}let c=s.match(/^assert\s+(.+?)(?:,\s*(.+))?$/);if(c){if(!lt(this.pyEval(c[1],n)))throw new H("AssertionError",c[2]?V(this.pyEval(c[2],n)):"");return e+1}let u=s.match(/^del\s+(.+)$/);if(u)return n.delete(u[1].trim()),e+1;let d=s.match(/^import\s+(\w+)(?:\s+as\s+(\w+))?$/);if(d){let[,b,P]=d,R=pn[b];if(R){let v=R(this.cwd);this.modules.set(b,v),n.set(P??b,v)}return e+1}let m=s.match(/^from\s+(\w+)\s+import\s+(.+)$/);if(m){let[,b,P]=m,R=pn[b];if(R){let v=R(this.cwd);if(P?.trim()==="*")for(let[C,I]of v.data)n.set(C,I);else for(let C of P.split(",").map(I=>I.trim()))n.set(C,v.data.get(C)??h)}return e+1}let p=s.match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(p){let[,b,P]=p,R=P.split(",").map(I=>I.trim()).filter(Boolean),v=this.collectBlock(t,e+1,o),C={__pytype__:"func",name:b,params:R,body:v,closure:new Map(n)};return n.set(b,C),e+1+v.length}let y=s.match(/^class\s+(\w+)(?:\(([^)]*)\))?\s*:$/);if(y){let[,b,P]=y,R=P?P.split(",").map(Z=>Z.trim()):[],v=this.collectBlock(t,e+1,o),C={__pytype__:"class",name:b,methods:new Map,bases:R},I=0;for(;I<v.length;){let W=v[I].trim().match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(W){let[,J,yt]=W,dt=yt.split(",").map(E=>E.trim()).filter(Boolean),wt=this.collectBlock(v,I+1,0);C.methods.set(J,{__pytype__:"func",name:J,params:dt,body:wt,closure:new Map(n)}),I+=1+wt.length}else I++}return n.set(b,C),e+1+v.length}if(s.startsWith("if ")&&s.endsWith(":")){let b=s.slice(3,-1).trim(),P=this.collectBlock(t,e+1,o),R=P.length+1;if(lt(this.pyEval(b,n))){this.execBlock(P,new Map(n).also?.(I=>{for(let[Z,W]of n)I.set(Z,W)})??n),this.runBlockInScope(P,n);let C=e+1+P.length;for(;C<t.length;){let I=t[C].trim();if(this.getIndent(t[C])<o||!I.startsWith("elif")&&!I.startsWith("else"))break;let Z=this.collectBlock(t,C+1,o);C+=1+Z.length}return C}let v=e+1+P.length;for(;v<t.length;){let C=t[v],I=C.trim();if(this.getIndent(C)!==o)break;let Z=I.match(/^elif\s+(.+):$/);if(Z){let W=this.collectBlock(t,v+1,o);if(lt(this.pyEval(Z[1],n))){for(this.runBlockInScope(W,n),v+=1+W.length;v<t.length;){let J=t[v].trim();if(this.getIndent(t[v])!==o||!J.startsWith("elif")&&!J.startsWith("else"))break;let yt=this.collectBlock(t,v+1,o);v+=1+yt.length}return v}v+=1+W.length;continue}if(I==="else:"){let W=this.collectBlock(t,v+1,o);return this.runBlockInScope(W,n),v+1+W.length}break}return v}let g=s.match(/^for\s+(.+?)\s+in\s+(.+?)\s*:$/);if(g){let[,b,P]=g,R=Q(this.pyEval(P.trim(),n)),v=this.collectBlock(t,e+1,o),C=[],I=e+1+v.length;I<t.length&&t[I]?.trim()==="else:"&&(C=this.collectBlock(t,I+1,o),I+=1+C.length);let Z=!1;for(let W of R){if(b.includes(",")){let J=b.split(",").map(dt=>dt.trim()),yt=Array.isArray(W)?W:[W];J.forEach((dt,wt)=>n.set(dt,yt[wt]??h))}else n.set(b.trim(),W);try{this.runBlockInScope(v,n)}catch(J){if(J instanceof Lt){Z=!0;break}if(J instanceof Tt)continue;throw J}}return!Z&&C.length&&this.runBlockInScope(C,n),I}let f=s.match(/^while\s+(.+?)\s*:$/);if(f){let b=f[1],P=this.collectBlock(t,e+1,o),R=0;for(;lt(this.pyEval(b,n))&&R++<1e5;)try{this.runBlockInScope(P,n)}catch(v){if(v instanceof Lt)break;if(v instanceof Tt)continue;throw v}return e+1+P.length}if(s==="try:"){let b=this.collectBlock(t,e+1,o),P=e+1+b.length,R=[],v=[],C=[];for(;P<t.length;){let Z=t[P],W=Z.trim();if(this.getIndent(Z)!==o)break;if(W.startsWith("except")){let J=W.match(/^except(?:\s+(\w+)(?:\s+as\s+(\w+))?)?\s*:$/),yt=J?.[1]??null,dt=J?.[2],wt=this.collectBlock(t,P+1,o);R.push({exc:yt,body:wt}),dt&&n.set(dt,""),P+=1+wt.length}else if(W==="else:")C=this.collectBlock(t,P+1,o),P+=1+C.length;else if(W==="finally:")v=this.collectBlock(t,P+1,o),P+=1+v.length;else break}let I=null;try{this.runBlockInScope(b,n),C.length&&this.runBlockInScope(C,n)}catch(Z){if(Z instanceof H){I=Z;let W=!1;for(let J of R)if(J.exc===null||J.exc===Z.type||J.exc==="Exception"){this.runBlockInScope(J.body,n),W=!0;break}if(!W)throw Z}else throw Z}finally{v.length&&this.runBlockInScope(v,n)}return P}let $=s.match(/^with\s+(.+?)\s+as\s+(\w+)\s*:$/);if($){let b=this.collectBlock(t,e+1,o);return n.set($[2],h),this.runBlockInScope(b,n),e+1+b.length}let N=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(\+=|-=|\*=|\/\/=|\/=|%=|\*\*=|&=|\|=)\s*(.+)$/);if(N){let[,b,P,R]=N,v=n.get(b)??0,C=this.pyEval(R,n),I;switch(P){case"+=":I=typeof v=="string"?v+V(C):v+C;break;case"-=":I=v-C;break;case"*=":I=v*C;break;case"/=":I=v/C;break;case"//=":I=Math.floor(v/C);break;case"%=":I=v%C;break;case"**=":I=v**C;break;default:I=C}return n.set(b,I),e+1}let M=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\[(.+)\]\s*=\s*(.+)$/);if(M){let[,b,P,R]=M,v=n.get(b)??h,C=this.pyEval(R,n)??h,I=this.pyEval(P,n)??h;return Array.isArray(v)?v[I]=C:j(v)&&v.data.set(V(I),C),e+1}let x=s.match(/^([A-Za-z_][A-Za-z0-9_.]+)\s*=\s*(.+)$/);if(x){let b=x[1].lastIndexOf(".");if(b!==-1){let P=x[1].slice(0,b),R=x[1].slice(b+1),v=this.pyEval(x[2],n),C=this.pyEval(P,n);return j(C)?C.data.set(R,v):zt(C)&&C.attrs.set(R,v),e+1}}let k=s.match(/^([A-Za-z_][A-Za-z0-9_,\s]*),\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$/);if(k){let b=this.pyEval(k[3],n),P=s.split("=")[0].split(",").map(v=>v.trim()),R=Q(b);return P.forEach((v,C)=>n.set(v,R[C]??h)),e+1}let A=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=]+)?\s*=\s*(.+)$/);if(A){let[,b,P]=A;return n.set(b,this.pyEval(P,n)),e+1}try{this.pyEval(s,n)}catch(b){if(b instanceof H||b instanceof Ut)throw b}return e+1}runBlockInScope(t,e){this.execLines(t,0,e)}run(t){let e=ci(this.cwd);try{this.execScript(t,e)}catch(n){return n instanceof Ut?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:n.code}:n instanceof H?(this.stderr.push(n.toString()),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1}):n instanceof Mt?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}:(this.stderr.push(`RuntimeError: ${n}`),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1})}return{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}}},hn={name:"python3",aliases:["python"],description:"Python 3 interpreter (virtual)",category:"system",params:["[--version] [-c <code>] [-V] [file]"],run:({args:r,shell:t,cwd:e})=>{if(!t.packageManager.isInstalled("python3"))return{stderr:`bash: python3: command not found
160
165
  Hint: install it with: apt install python3
161
- `,exitCode:127};if(y(r,["--version","-V"]))return{stdout:`${Xs}
162
- `,exitCode:0};if(y(r,["--version-full"]))return{stdout:`${Xt}
166
+ `,exitCode:127};if(w(r,["--version","-V"]))return{stdout:`${ai}
167
+ `,exitCode:0};if(w(r,["--version-full"]))return{stdout:`${re}
163
168
  `,exitCode:0};let n=r.indexOf("-c");if(n!==-1){let s=r[n+1];if(!s)return{stderr:`python3: -c requires a code argument
164
169
  `,exitCode:1};let o=s.replace(/\\n/g,`
165
- `).replace(/\\t/g," "),a=new te(e),{stdout:l,stderr:c,exitCode:u}=a.run(o);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}let i=r.find(s=>!s.startsWith("-"));if(i){let s=x(e,i);if(!t.vfs.exists(s))return{stderr:`python3: can't open file '${i}': [Errno 2] No such file or directory
166
- `,exitCode:2};let o=t.vfs.readFile(s),a=new te(e),{stdout:l,stderr:c,exitCode:u}=a.run(o);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}return{stdout:`${Xt}
170
+ `).replace(/\\t/g," "),a=new ne(e),{stdout:l,stderr:c,exitCode:u}=a.run(o);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}let i=r.find(s=>!s.startsWith("-"));if(i){let s=S(e,i);if(!t.vfs.exists(s))return{stderr:`python3: can't open file '${i}': [Errno 2] No such file or directory
171
+ `,exitCode:2};let o=t.vfs.readFile(s),a=new ne(e),{stdout:l,stderr:c,exitCode:u}=a.run(o);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}return{stdout:`${re}
167
172
  Type "help", "copyright", "credits" or "license" for more information.
168
- >>> `,exitCode:0}}};var dn={name:"read",description:"Read a line from stdin into variables",category:"shell",params:["[-r] [-p prompt] <var...>"],run:({args:r,stdin:t,env:e})=>{let n=r.indexOf("-p"),i=r.filter((a,l)=>a!=="-r"&&a!=="-p"&&r[l-1]!=="-p"),s=(t??"").split(`
169
- `)[0]??"",o=y(r,["-r"])?s:s.replace(/\\(?:\r?\n|.)/g,a=>a[1]===`
170
- `||a[1]==="\r"?"":a[1]);if(!e)return{exitCode:0};if(i.length===0)e.vars.REPLY=o;else if(i.length===1)e.vars[i[0]]=o;else{let a=o.split(/\s+/);for(let l=0;l<i.length;l++)e.vars[i[l]]=l<i.length-1?a[l]??"":a.slice(l).join(" ")}return{exitCode:0}}};var mn={name:"rm",description:"Remove files or directories",category:"files",params:["[-r|-rf] <path>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{if(n.length===0)return{stderr:"rm: missing operand",exitCode:1};let i=y(n,["-r","-rf","-fr"]),s=[];for(let o=0;;o+=1){let a=St(n,o,{flags:["-r","-rf","-fr"]});if(!a)break;s.push(a)}if(s.length===0)return{stderr:"rm: missing operand",exitCode:1};for(let o of s){let a=x(e,o);_(r,a,"rm"),t.vfs.remove(a,{recursive:i})}return{exitCode:0}}};var pn={name:"sed",description:"Stream editor for filtering and transforming text",category:"text",params:["-e <expr> [file]","s/pattern/replace/[g]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=y(n,["-i"]),o=st(n,["-e"])??n.find(f=>!f.startsWith("-")),a=n.filter(f=>!f.startsWith("-")&&f!==o).pop();if(!o)return{stderr:"sed: no expression",exitCode:1};let l=i??"";if(a){let f=x(e,a);try{l=t.vfs.readFile(f)}catch{return{stderr:`sed: ${a}: No such file or directory`,exitCode:1}}}let c=o.match(/^s([^a-zA-Z0-9])(.+?)\1(.*?)\1([gi]*)$/);if(!c)return{stderr:`sed: unrecognized command: ${o}`,exitCode:1};let[,,u,d,m]=c,p=(m??"").includes("i")?"gi":(m??"").includes("g")?"g":"",w;try{w=new RegExp(u,p||"")}catch{return{stderr:`sed: invalid regex: ${u}`,exitCode:1}}let g=((m??"").includes("g")||p.includes("g"),l.replace(w,d??""));if(s&&a){let f=x(e,a);return t.writeFileAsUser(r,f,g),{exitCode:0}}return{stdout:g,exitCode:0}}};var fn={name:"set",description:"Display or set shell variables",category:"shell",params:["[VAR=value]"],run:({args:r,env:t})=>{if(r.length===0)return{stdout:Object.entries(t.vars).map(([n,i])=>`${n}=${i}`).join(`
171
- `),exitCode:0};for(let e of r)if(e.includes("=")){let n=e.indexOf("=");t.vars[e.slice(0,n)]=e.slice(n+1)}return{exitCode:0}}};async function hn(r,t,e,n,i,s,o){let a={exitCode:0},l=[],c=i,u=0;for(;u<r.length;){let m=r[u];if(a=await ai(m.pipeline,t,e,n,c,s,o),o.lastExitCode=a.exitCode??0,a.nextCwd&&(a.exitCode??0)===0&&(c=a.nextCwd),a.stdout&&l.push(a.stdout),a.closeSession||a.switchUser)return{...a,stdout:l.join("")||a.stdout};let p=m.op;if(!(!p||p===";")){if(p==="&&"){if((a.exitCode??0)!==0)for(;u<r.length&&r[u]?.op==="&&";)u++}else if(p==="||"&&(a.exitCode??0)===0)for(;u<r.length&&r[u]?.op==="||";)u++}u++}let d=l.join("");return{...a,stdout:d||a.stdout,nextCwd:c!==i?c:void 0}}async function ai(r,t,e,n,i,s,o){if(!r.isValid)return{stderr:r.error||"Syntax error",exitCode:1};if(r.commands.length===0)return{exitCode:0};let a=o??{vars:{},lastExitCode:0};return r.commands.length===1?li(r.commands[0],t,e,n,i,s,a):ci(r.commands,t,e,n,i,s,a)}async function li(r,t,e,n,i,s,o){let a;if(r.inputFile){let c=x(i,r.inputFile);try{a=s.vfs.readFile(c)}catch{return{stderr:`${r.inputFile}: No such file or directory`,exitCode:1}}}let l=await ee(r.name,r.args,t,e,n,i,s,a,o);if(r.outputFile){let c=x(i,r.outputFile),u=l.stdout||"";try{if(r.appendOutput){let d=(()=>{try{return s.vfs.readFile(c)}catch{return""}})();s.writeFileAsUser(t,c,d+u)}else s.writeFileAsUser(t,c,u);return{...l,stdout:""}}catch{return{...l,stderr:`Failed to write to ${r.outputFile}`,exitCode:1}}}return l}async function ci(r,t,e,n,i,s,o){let a="",l=0;for(let c=0;c<r.length;c++){let u=r[c];if(c===0&&u.inputFile){let m=x(i,u.inputFile);try{a=s.vfs.readFile(m)}catch{return{stderr:`${u.inputFile}: No such file or directory`,exitCode:1}}}let d=await ee(u.name,u.args,t,e,n,i,s,a,o);if(l=d.exitCode??0,c===r.length-1&&u.outputFile){let m=x(i,u.outputFile),p=d.stdout||"";try{if(u.appendOutput){let w=(()=>{try{return s.vfs.readFile(m)}catch{return""}})();s.writeFileAsUser(t,m,w+p)}else s.writeFileAsUser(t,m,p);a=""}catch{return{stderr:`Failed to write to ${u.outputFile}`,exitCode:1}}}else a=d.stdout||"";if(d.stderr&&l!==0)return{stderr:d.stderr,exitCode:l};if(d.closeSession||d.switchUser)return d}return{stdout:a,exitCode:l}}function Ut(r){let t=[],e="",n=!1,i="",s=0;for(;s<r.length;){let o=r[s],a=r[s+1];if((o==='"'||o==="'")&&!n){n=!0,i=o,s++;continue}if(n&&o===i){n=!1,i="",s++;continue}if(n){e+=o,s++;continue}if(o===" "){e&&(t.push(e),e=""),s++;continue}if((o===">"||o==="<")&&!n){e&&(t.push(e),e=""),o===">"&&a===">"?(t.push(">>"),s+=2):(t.push(o),s++);continue}e+=o,s++}return e&&t.push(e),t}function gn(r){let t=r.trim();if(!t)return{statements:[],isValid:!0};try{return{statements:ui(t),isValid:!0}}catch(e){return{statements:[],isValid:!1,error:e.message}}}function ui(r){let t=di(r),e=[];for(let n of t){let s={pipeline:{commands:mi(n.text.trim()),isValid:!0}};n.op&&(s.op=n.op),e.push(s)}return e}function di(r){let t=[],e="",n=0,i=!1,s="",o=0,a=l=>{e.trim()&&t.push({text:e,op:l}),e=""};for(;o<r.length;){let l=r[o],c=r.slice(o,o+2);if((l==='"'||l==="'")&&!i){i=!0,s=l,e+=l,o++;continue}if(i&&l===s){i=!1,e+=l,o++;continue}if(i){e+=l,o++;continue}if(l==="("){n++,e+=l,o++;continue}if(l===")"){n--,e+=l,o++;continue}if(n>0){e+=l,o++;continue}if(c==="&&"){a("&&"),o+=2;continue}if(c==="||"){a("||"),o+=2;continue}if(l===";"){a(";"),o++;continue}e+=l,o++}return a(),t}function mi(r){return pi(r).map(fi)}function pi(r){let t=[],e="",n=!1,i="";for(let o=0;o<r.length;o++){let a=r[o];if((a==='"'||a==="'")&&!n){n=!0,i=a,e+=a;continue}if(n&&a===i){n=!1,e+=a;continue}if(n){e+=a;continue}if(a==="|"&&r[o+1]!=="|"){if(!e.trim())throw new Error("Syntax error near unexpected token '|'");t.push(e.trim()),e=""}else e+=a}let s=e.trim();if(!s&&t.length>0)throw new Error("Syntax error near unexpected token '|'");return s&&t.push(s),t}function fi(r){let t=Ut(r);if(t.length===0)return{name:"",args:[]};let e=[],n,i,s=!1,o=0;for(;o<t.length;){let l=t[o];if(l==="<"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after <");n=t[o],o++}else if(l===">>"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >>");i=t[o],s=!0,o++}else if(l===">"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >");i=t[o],s=!1,o++}else e.push(l),o++}return{name:(e[0]??"").toLowerCase(),args:e.slice(1),inputFile:n,outputFile:i,appendOutput:s}}function Ft(r,t){return{vars:{PATH:"/usr/local/bin:/usr/bin:/bin",HOME:`/home/${r}`,USER:r,LOGNAME:r,SHELL:"/bin/sh",TERM:"xterm-256color",HOSTNAME:t,PS1:"\\u@\\h:\\w\\$ "},lastExitCode:0}}function yn(r,t,e,n){if(r.startsWith("/")){if(!e.vfs.exists(r))return null;try{let s=e.vfs.stat(r);return s.type!=="file"||!(s.mode&73)||(r.startsWith("/sbin/")||r.startsWith("/usr/sbin/"))&&n!=="root"?null:r}catch{return null}}let i=(t.vars.PATH??"/usr/local/bin:/usr/bin:/bin").split(":");for(let s of i){if((s==="/sbin"||s==="/usr/sbin")&&n!=="root")continue;let o=`${s}/${r}`;if(e.vfs.exists(o))try{let a=e.vfs.stat(o);if(a.type!=="file"||!(a.mode&73))continue;return o}catch{}}return null}async function ee(r,t,e,n,i,s,o,a,l){let c=l.vars[`__alias_${r}`];if(c)return H(`${c} ${t.join(" ")}`,e,n,i,s,o,a,l);let u=ft(r);if(!u){let d=yn(r,l,o,e);if(d){let m=o.vfs.readFile(d),p=m.match(/exec\s+builtin\s+(\S+)/);if(p){let g=ft(p[1]);if(g)return await g.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}let w=ft("sh");if(w)return await w.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(m)}`,mode:i,args:["-c",m,"--",...t],stdin:a,cwd:s,shell:o,env:l})}return{stderr:`${r}: command not found`,exitCode:127}}try{return await u.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}catch(d){return{stderr:d instanceof Error?d.message:"Command failed",exitCode:1}}}async function H(r,t,e,n,i,s,o,a){let l=r.trim();if(l.length===0)return{exitCode:0};let c=a??Ft(t,e),d=Ut(l)[0]?.toLowerCase()??"",m=c.vars[`__alias_${d}`],p=m?l.replace(d,m):l;if(/(?<![|&])[|](?![|])/.test(p)||p.includes(">")||p.includes("<")||p.includes("&&")||p.includes("||")||p.includes(";")){let S=gn(p);if(!S.isValid)return{stderr:S.error||"Syntax error",exitCode:1};try{return await hn(S.statements,t,e,n,i,s,c)}catch(k){return{stderr:k instanceof Error?k.message:"Execution failed",exitCode:1}}}let g=await qt(p,c.vars,c.lastExitCode,S=>H(S,t,e,n,i,s,void 0,c).then(k=>k.stdout??"")),f=Ut(g.trim()),$=f[0]?.toLowerCase()??"",E=f.slice(1),F=ft($);if(!F){let S=yn($,c,s,t);if(S){let k=s.vfs.readFile(S),V=k.match(/exec\s+builtin\s+(\S+)/);if(V){let P=V[1],R=ft(P);if(R)return await R.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:[$,...E].join(" "),mode:n,args:E,stdin:o,cwd:i,shell:s,env:c})}let b=ft("sh");if(b)return await b.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(k)}`,mode:n,args:["-c",k,"--",...E],stdin:o,cwd:i,shell:s,env:c})}return{stderr:`${$}: command not found`,exitCode:127}}try{return await F.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:g,mode:n,args:E,stdin:o,cwd:i,shell:s,env:c})}catch(S){return{stderr:S instanceof Error?S.message:"Command failed",exitCode:1}}}async function ve(r,t,e,n){return qt(r,t,e,i=>H(i,n.authUser,n.hostname,n.mode,n.cwd,n.shell,void 0,n.env).then(s=>s.stdout??""))}function vt(r){let t=[],e=0;for(;e<r.length;){let n=r[e].trim();if(!n||n.startsWith("#")){e++;continue}if(n.startsWith("if ")||n==="if"){let i=n.replace(/^if\s+/,"").replace(/;\s*then\s*$/,"").trim(),s=[],o=[],a=[],l="then",c="";for(e++;e<r.length&&r[e]?.trim()!=="fi";){let u=r[e].trim();u.startsWith("elif ")?(l="elif",c=u.replace(/^elif\s+/,"").replace(/;\s*then\s*$/,"").trim(),o.push({cond:c,body:[]})):u==="else"?l="else":u!=="then"&&(l==="then"?s.push(u):l==="elif"&&o.length>0?o[o.length-1].body.push(u):a.push(u)),e++}t.push({type:"if",cond:i,then_:s,elif:o,else_:a})}else if(n.startsWith("for ")){let i=n.match(/^for\s+(\w+)\s+in\s+(.+?)(?:\s*;\s*do)?$/);if(i){let s=[];for(e++;e<r.length&&r[e]?.trim()!=="done";){let o=r[e].trim().replace(/^do\s+/,"");o&&o!=="do"&&s.push(o),e++}t.push({type:"for",var:i[1],list:i[2],body:s})}else t.push({type:"cmd",line:n})}else if(n.startsWith("while ")){let i=n.replace(/^while\s+/,"").replace(/;\s*do\s*$/,"").trim(),s=[];for(e++;e<r.length&&r[e]?.trim()!=="done";){let o=r[e].trim().replace(/^do\s+/,"");o&&o!=="do"&&s.push(o),e++}t.push({type:"while",cond:i,body:s})}else t.push({type:"cmd",line:n});e++}return t}async function Ce(r,t){let e=await ve(r,t.env.vars,t.env.lastExitCode,t),n=e.match(/^\[?\s*(.+?)\s*\]?$/);if(n){let s=n[1],o=s.match(/^-([fdeznr])\s+(.+)$/);if(o){let[,c,u]=o,d=x(t.cwd,u);if(c==="f")return t.shell.vfs.exists(d)&&t.shell.vfs.stat(d).type==="file";if(c==="d")return t.shell.vfs.exists(d)&&t.shell.vfs.stat(d).type==="directory";if(c==="e")return t.shell.vfs.exists(d);if(c==="z")return(u??"").length===0;if(c==="n")return(u??"").length>0}let a=s.match(/^"?([^"]*)"?\s*(==|!=|=|<|>)\s*"?([^"]*)"?$/);if(a){let[,c,u,d]=a;if(u==="=="||u==="=")return c===d;if(u==="!=")return c!==d}let l=s.match(/^(\S+)\s+(-eq|-ne|-lt|-le|-gt|-ge)\s+(\S+)$/);if(l){let[,c,u,d]=l,m=Number(c),p=Number(d);if(u==="-eq")return m===p;if(u==="-ne")return m!==p;if(u==="-lt")return m<p;if(u==="-le")return m<=p;if(u==="-gt")return m>p;if(u==="-ge")return m>=p}}return((await H(e,t.authUser,t.hostname,t.mode,t.cwd,t.shell,void 0,t.env)).exitCode??0)===0}async function $t(r,t){let e={exitCode:0},n="";for(let i of r)if(i.type==="cmd"){let s=await ve(i.line,t.env.vars,t.env.lastExitCode,t),o=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)/,a=s.trim().split(/\s+/);if(a.length>0&&o.test(a[0])&&a.every(u=>o.test(u))){for(let u of a){let d=u.match(o);t.env.vars[d[1]]=d[2]}t.env.lastExitCode=0;continue}let l=await H(s,t.authUser,t.hostname,t.mode,t.cwd,t.shell,void 0,t.env);if(t.env.lastExitCode=l.exitCode??0,l.stdout&&(n+=`${l.stdout}
172
- `),l.stderr)return{...l,stdout:n.trim()};e=l}else if(i.type==="if"){let s=!1;if(await Ce(i.cond,t)){let o=await $t(vt(i.then_),t);o.stdout&&(n+=`${o.stdout}
173
- `),s=!0}else{for(let o of i.elif)if(await Ce(o.cond,t)){let a=await $t(vt(o.body),t);a.stdout&&(n+=`${a.stdout}
174
- `),s=!0;break}if(!s&&i.else_.length>0){let o=await $t(vt(i.else_),t);o.stdout&&(n+=`${o.stdout}
175
- `)}}}else if(i.type==="for"){let o=(await ve(i.list,t.env.vars,t.env.lastExitCode,t)).trim().split(/\s+/);for(let a of o){t.env.vars[i.var]=a;let l=await $t(vt(i.body),t);if(l.stdout&&(n+=`${l.stdout}
176
- `),l.closeSession)return l}}else if(i.type==="while"){let s=0;for(;s<1e3&&await Ce(i.cond,t);){let o=await $t(vt(i.body),t);if(o.stdout&&(n+=`${o.stdout}
177
- `),o.closeSession)return o;s++}}return{...e,stdout:n.trim()||e.stdout}}var wn={name:"sh",aliases:["bash"],description:"Execute shell script or command",category:"shell",params:["-c <script>","[<file>]"],run:async r=>{let{args:t,shell:e,cwd:n}=r;if(y(t,"-c")){let s=t[t.indexOf("-c")+1]??"";if(!s)return{stderr:"sh: -c requires a script",exitCode:1};let o=s.split(/[;\n]/).map(l=>l.trim()).filter(l=>l&&!l.startsWith("#")),a=vt(o);return $t(a,r)}let i=t[0];if(i){let s=x(n,i);if(!e.vfs.exists(s))return{stderr:`sh: ${i}: No such file or directory`,exitCode:1};let a=e.vfs.readFile(s).split(`
178
- `).map(c=>c.trim()).filter(c=>c&&!c.startsWith("#")),l=vt(a);return $t(l,r)}return{stderr:"sh: invalid usage. Use: sh -c 'cmd' or sh <file>",exitCode:1}}};var Sn={name:"shift",description:"Shift positional parameters",category:"shell",params:["[n]"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};let e=parseInt(r[0]??"1",10)||1,n=t.vars.__argv?.split("\0").filter(Boolean)??[];t.vars.__argv=n.slice(e).join("\0");let i=n.slice(e);for(let s=1;s<=9;s++)t.vars[String(s)]=i[s-1]??"";return{exitCode:0}}},xn={name:"trap",description:"Trap signals and events",category:"shell",params:["[action] [signal...]"],run:({args:r,env:t})=>{if(!t||r.length===0)return{exitCode:0};let e=r[0]??"",n=r.slice(1);for(let i of n)t.vars[`__trap_${i.toUpperCase()}`]=e;return{exitCode:0}}},bn={name:"return",description:"Return from a shell function",category:"shell",params:["[n]"],run:({args:r,env:t})=>{let e=parseInt(r[0]??"0",10);return t&&(t.lastExitCode=e),{exitCode:e}}};var Cn={name:"sleep",description:"Delay execution",category:"system",params:["<seconds>"],run:async({args:r})=>{let t=parseFloat(r[0]??"1");return Number.isNaN(t)||t<0?{stderr:"sleep: invalid time",exitCode:1}:(await new Promise(e=>setTimeout(e,t*1e3)),{exitCode:0})}};var vn={name:"sort",description:"Sort lines of text",category:"text",params:["[-r] [-n] [-u] [-k <col>] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=y(n,["-r"]),o=y(n,["-n"]),a=y(n,["-u"]),l=n.filter(w=>!w.startsWith("-")),d=[...(l.length>0?l.map(w=>{try{return _(r,x(e,w),"sort"),t.vfs.readFile(x(e,w))}catch{return""}}).join(`
173
+ >>> `,exitCode:0}}};var gn={name:"read",description:"Read a line from stdin into variables",category:"shell",params:["[-r] [-p prompt] <var...>"],run:({args:r,stdin:t,env:e})=>{let n=r.indexOf("-p"),i=r.filter((a,l)=>a!=="-r"&&a!=="-p"&&r[l-1]!=="-p"),s=(t??"").split(`
174
+ `)[0]??"",o=w(r,["-r"])?s:s.replace(/\\(?:\r?\n|.)/g,a=>a[1]===`
175
+ `||a[1]==="\r"?"":a[1]);if(!e)return{exitCode:0};if(i.length===0)e.vars.REPLY=o;else if(i.length===1)e.vars[i[0]]=o;else{let a=o.split(/\s+/);for(let l=0;l<i.length;l++)e.vars[i[l]]=l<i.length-1?a[l]??"":a.slice(l).join(" ")}return{exitCode:0}}};var yn={name:"rm",description:"Remove files or directories",category:"files",params:["[-r|-rf] <path>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{if(n.length===0)return{stderr:"rm: missing operand",exitCode:1};let i=w(n,["-r","-rf","-fr"]),s=[];for(let o=0;;o+=1){let a=xt(n,o,{flags:["-r","-rf","-fr"]});if(!a)break;s.push(a)}if(s.length===0)return{stderr:"rm: missing operand",exitCode:1};for(let o of s){let a=S(e,o);D(r,a,"rm"),t.vfs.remove(a,{recursive:i})}return{exitCode:0}}};var wn={name:"sed",description:"Stream editor for filtering and transforming text",category:"text",params:["-e <expr> [file]","s/pattern/replace/[g]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=w(n,["-i"]),o=it(n,["-e"])??n.find(f=>!f.startsWith("-")),a=n.filter(f=>!f.startsWith("-")&&f!==o).pop();if(!o)return{stderr:"sed: no expression",exitCode:1};let l=i??"";if(a){let f=S(e,a);try{l=t.vfs.readFile(f)}catch{return{stderr:`sed: ${a}: No such file or directory`,exitCode:1}}}let c=o.match(/^s([^a-zA-Z0-9])(.+?)\1(.*?)\1([gi]*)$/);if(!c)return{stderr:`sed: unrecognized command: ${o}`,exitCode:1};let[,,u,d,m]=c,p=(m??"").includes("i")?"gi":(m??"").includes("g")?"g":"",y;try{y=new RegExp(u,p||"")}catch{return{stderr:`sed: invalid regex: ${u}`,exitCode:1}}let g=((m??"").includes("g")||p.includes("g"),l.replace(y,d??""));if(s&&a){let f=S(e,a);return t.writeFileAsUser(r,f,g),{exitCode:0}}return{stdout:g,exitCode:0}}};var Sn={name:"set",description:"Display or set shell variables",category:"shell",params:["[VAR=value]"],run:({args:r,env:t})=>{if(r.length===0)return{stdout:Object.entries(t.vars).map(([n,i])=>`${n}=${i}`).join(`
176
+ `),exitCode:0};for(let e of r)if(e.includes("=")){let n=e.indexOf("=");t.vars[e.slice(0,n)]=e.slice(n+1)}return{exitCode:0}}};kt();async function xn(r,t,e,n,i,s,o){let a={exitCode:0},l=[],c=i,u=0;for(;u<r.length;){let m=r[u];if(a=await hi(m.pipeline,t,e,n,c,s,o),o.lastExitCode=a.exitCode??0,a.nextCwd&&(a.exitCode??0)===0&&(c=a.nextCwd),a.stdout&&l.push(a.stdout),a.closeSession||a.switchUser)return{...a,stdout:l.join("")||a.stdout};let p=m.op;if(!(!p||p===";")){if(p==="&&"){if((a.exitCode??0)!==0)for(;u<r.length&&r[u]?.op==="&&";)u++}else if(p==="||"&&(a.exitCode??0)===0)for(;u<r.length&&r[u]?.op==="||";)u++}u++}let d=l.join("");return{...a,stdout:d||a.stdout,nextCwd:c!==i?c:void 0}}async function hi(r,t,e,n,i,s,o){if(!r.isValid)return{stderr:r.error||"Syntax error",exitCode:1};if(r.commands.length===0)return{exitCode:0};let a=o??{vars:{},lastExitCode:0};return r.commands.length===1?gi(r.commands[0],t,e,n,i,s,a):yi(r.commands,t,e,n,i,s,a)}async function gi(r,t,e,n,i,s,o){let a;if(r.inputFile){let c=S(i,r.inputFile);try{a=s.vfs.readFile(c)}catch{return{stderr:`${r.inputFile}: No such file or directory`,exitCode:1}}}let l=await se(r.name,r.args,t,e,n,i,s,a,o);if(r.outputFile){let c=S(i,r.outputFile),u=l.stdout||"";try{if(r.appendOutput){let d=(()=>{try{return s.vfs.readFile(c)}catch{return""}})();s.writeFileAsUser(t,c,d+u)}else s.writeFileAsUser(t,c,u);return{...l,stdout:""}}catch{return{...l,stderr:`Failed to write to ${r.outputFile}`,exitCode:1}}}return l}async function yi(r,t,e,n,i,s,o){let a="",l=0;for(let c=0;c<r.length;c++){let u=r[c];if(c===0&&u.inputFile){let m=S(i,u.inputFile);try{a=s.vfs.readFile(m)}catch{return{stderr:`${u.inputFile}: No such file or directory`,exitCode:1}}}let d=await se(u.name,u.args,t,e,n,i,s,a,o);if(l=d.exitCode??0,c===r.length-1&&u.outputFile){let m=S(i,u.outputFile),p=d.stdout||"";try{if(u.appendOutput){let y=(()=>{try{return s.vfs.readFile(m)}catch{return""}})();s.writeFileAsUser(t,m,y+p)}else s.writeFileAsUser(t,m,p);a=""}catch{return{stderr:`Failed to write to ${u.outputFile}`,exitCode:1}}}else a=d.stdout||"";if(d.stderr&&l!==0)return{stderr:d.stderr,exitCode:l};if(d.closeSession||d.switchUser)return d}return{stdout:a,exitCode:l}}function Ot(r){let t=[],e="",n=!1,i="",s=0;for(;s<r.length;){let o=r[s],a=r[s+1];if((o==='"'||o==="'")&&!n){n=!0,i=o,s++;continue}if(n&&o===i){n=!1,i="",s++;continue}if(n){e+=o,s++;continue}if(o===" "){e&&(t.push(e),e=""),s++;continue}if(!n&&o==="2"&&a===">"){let l=r.slice(s+1);if(l.startsWith(">>&1")||l.startsWith(">> &1")){e&&(t.push(e),e=""),t.push("2>>&1"),s+=5;continue}if(l.startsWith(">&1")){e&&(t.push(e),e=""),t.push("2>&1"),s+=4;continue}if(l.startsWith(">>")){e&&(t.push(e),e=""),t.push("2>>"),s+=3;continue}if(l.startsWith(">")){e&&(t.push(e),e=""),t.push("2>"),s+=2;continue}}if((o===">"||o==="<")&&!n){e&&(t.push(e),e=""),o===">"&&a===">"?(t.push(">>"),s+=2):(t.push(o),s++);continue}e+=o,s++}return e&&t.push(e),t}function bn(r){let t=r.trim();if(!t)return{statements:[],isValid:!0};try{return{statements:wi(t),isValid:!0}}catch(e){return{statements:[],isValid:!1,error:e.message}}}function wi(r){let t=Si(r),e=[];for(let n of t){let s={pipeline:{commands:xi(n.text.trim()),isValid:!0}};n.op&&(s.op=n.op),e.push(s)}return e}function Si(r){let t=[],e="",n=0,i=!1,s="",o=0,a=l=>{e.trim()&&t.push({text:e,op:l}),e=""};for(;o<r.length;){let l=r[o],c=r.slice(o,o+2);if((l==='"'||l==="'")&&!i){i=!0,s=l,e+=l,o++;continue}if(i&&l===s){i=!1,e+=l,o++;continue}if(i){e+=l,o++;continue}if(l==="("){n++,e+=l,o++;continue}if(l===")"){n--,e+=l,o++;continue}if(n>0){e+=l,o++;continue}if(c==="&&"){a("&&"),o+=2;continue}if(c==="||"){a("||"),o+=2;continue}if(l===";"){a(";"),o++;continue}e+=l,o++}return a(),t}function xi(r){return bi(r).map(vi)}function bi(r){let t=[],e="",n=!1,i="";for(let o=0;o<r.length;o++){let a=r[o];if((a==='"'||a==="'")&&!n){n=!0,i=a,e+=a;continue}if(n&&a===i){n=!1,e+=a;continue}if(n){e+=a;continue}if(a==="|"&&r[o+1]!=="|"){if(!e.trim())throw new Error("Syntax error near unexpected token '|'");t.push(e.trim()),e=""}else e+=a}let s=e.trim();if(!s&&t.length>0)throw new Error("Syntax error near unexpected token '|'");return s&&t.push(s),t}function vi(r){let t=Ot(r);if(t.length===0)return{name:"",args:[]};let e=[],n,i,s=!1,o=0,a,l=!1,c=!1;for(;o<t.length;){let d=t[o];if(d==="<"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after <");n=t[o],o++}else if(d===">>"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >>");i=t[o],s=!0,o++}else if(d===">"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >");i=t[o],s=!1,o++}else if(d==="2>&1")c=!0,o++;else if(d==="2>>"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after 2>>");a=t[o],l=!0,o++}else if(d==="2>"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after 2>");a=t[o],l=!1,o++}else e.push(d),o++}return{name:(e[0]??"").toLowerCase(),args:e.slice(1),inputFile:n,outputFile:i,appendOutput:s,stderrFile:a,stderrAppend:l,stderrToStdout:c}}kt();function At(r,t){return{vars:{PATH:"/usr/local/bin:/usr/bin:/bin",HOME:`/home/${r}`,USER:r,LOGNAME:r,SHELL:"/bin/sh",TERM:"xterm-256color",HOSTNAME:t,PS1:"\\u@\\h:\\w\\$ "},lastExitCode:0}}function vn(r,t,e,n){if(r.startsWith("/")){if(!e.vfs.exists(r))return null;try{let s=e.vfs.stat(r);return s.type!=="file"||!(s.mode&73)||(r.startsWith("/sbin/")||r.startsWith("/usr/sbin/"))&&n!=="root"?null:r}catch{return null}}let i=(t.vars.PATH??"/usr/local/bin:/usr/bin:/bin").split(":");for(let s of i){if((s==="/sbin"||s==="/usr/sbin")&&n!=="root")continue;let o=`${s}/${r}`;if(e.vfs.exists(o))try{let a=e.vfs.stat(o);if(a.type!=="file"||!(a.mode&73))continue;return o}catch{}}return null}async function se(r,t,e,n,i,s,o,a,l){let c=l.vars[`__alias_${r}`];if(c)return K(`${c} ${t.join(" ")}`,e,n,i,s,o,a,l);let u=ut(r);if(!u){let d=vn(r,l,o,e);if(d){let m=o.vfs.readFile(d),p=m.match(/exec\s+builtin\s+(\S+)/);if(p){let g=ut(p[1]);if(g)return await g.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}let y=ut("sh");if(y)return await y.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(m)}`,mode:i,args:["-c",m,"--",...t],stdin:a,cwd:s,shell:o,env:l})}return{stderr:`${r}: command not found`,exitCode:127}}try{return await u.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}catch(d){return{stderr:d instanceof Error?d.message:"Command failed",exitCode:1}}}async function K(r,t,e,n,i,s,o,a){let l=r.trim();if(l.length===0)return{exitCode:0};let c=a??At(t,e),d=Ot(l)[0]?.toLowerCase()??"",m=c.vars[`__alias_${d}`],p=m?l.replace(d,m):l,y=/\bfor\s+\w+\s+in\b/.test(p)||/\bwhile\s+/.test(p)||/\bif\s+/.test(p)||/\w+\s*\(\s*\)\s*\{/.test(p)||/\bfunction\s+\w+/.test(p)||/\(\(\s*.+\s*\)\)/.test(p),g=/(?<![|&])[|](?![|])/.test(p)||p.includes(">")||p.includes("<")||p.includes("&&")||p.includes("||")||p.includes(";");if(y&&d!=="sh"&&d!=="bash"||g){if(y&&d!=="sh"&&d!=="bash"){let A=ut("sh");if(A)return await A.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:p,mode:n,args:["-c",p],stdin:void 0,cwd:i,shell:s,env:c})}let k=bn(p);if(!k.isValid)return{stderr:k.error||"Syntax error",exitCode:1};try{return await xn(k.statements,t,e,n,i,s,c)}catch(A){return{stderr:A instanceof Error?A.message:"Execution failed",exitCode:1}}}let f=await _t(p,c.vars,c.lastExitCode,k=>K(k,t,e,n,i,s,void 0,c).then(A=>A.stdout??"")),$=Ot(f.trim()),N=$[0]?.toLowerCase()??"",M=$.slice(1).flatMap(Rt),x=ut(N);if(!x){let k=vn(N,c,s,t);if(k){let A=s.vfs.readFile(k),b=A.match(/exec\s+builtin\s+(\S+)/);if(b){let R=b[1],v=ut(R);if(v)return await v.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:[N,...M].join(" "),mode:n,args:M,stdin:o,cwd:i,shell:s,env:c})}let P=ut("sh");if(P)return await P.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(A)}`,mode:n,args:["-c",A,"--",...M],stdin:o,cwd:i,shell:s,env:c})}return{stderr:`${N}: command not found`,exitCode:127}}try{return await x.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:f,mode:n,args:M,stdin:o,cwd:i,shell:s,env:c})}catch(k){return{stderr:k instanceof Error?k.message:"Command failed",exitCode:1}}}async function ke(r,t,e,n){return _t(r,t,e,i=>K(i,n.authUser,n.hostname,n.mode,n.cwd,n.shell,void 0,n.env).then(s=>s.stdout??""))}function bt(r){let t=[],e=0;for(;e<r.length;){let n=r[e].trim();if(!n||n.startsWith("#")){e++;continue}let i=n.match(/^(?:function\s+)?(\w+)\s*\(\s*\)\s*\{(.+)\}\s*$/),s=i??(n.match(/^(?:function\s+)?(\w+)\s*\(\s*\)\s*\{?\s*$/)||n.match(/^function\s+(\w+)\s*\{?\s*$/));if(s){let a=s[1],l=[];if(i){l.push(...i[2].split(";").map(c=>c.trim()).filter(Boolean)),t.push({type:"func",name:a,body:l}),e++;continue}for(e++;e<r.length&&r[e]?.trim()!=="}"&&e<r.length+1;){let c=r[e].trim().replace(/^do\s+/,"");c&&c!=="{"&&l.push(c),e++}e++,t.push({type:"func",name:a,body:l});continue}let o=n.match(/^\(\(\s*(.+?)\s*\)\)$/);if(o){t.push({type:"arith",expr:o[1]}),e++;continue}if(n.startsWith("if ")||n==="if"){let a=n.replace(/^if\s+/,"").replace(/;\s*then\s*$/,"").trim(),l=[],c=[],u=[],d="then",m="";for(e++;e<r.length&&r[e]?.trim()!=="fi";){let p=r[e].trim();p.startsWith("elif ")?(d="elif",m=p.replace(/^elif\s+/,"").replace(/;\s*then\s*$/,"").trim(),c.push({cond:m,body:[]})):p==="else"?d="else":p!=="then"&&(d==="then"?l.push(p):d==="elif"&&c.length>0?c[c.length-1].body.push(p):u.push(p)),e++}t.push({type:"if",cond:a,then_:l,elif:c,else_:u})}else if(n.startsWith("for ")){let a=n.match(/^for\s+(\w+)\s+in\s+(.+?)(?:\s*;\s*do)?$/);if(a){let l=[];for(e++;e<r.length&&r[e]?.trim()!=="done";){let c=r[e].trim().replace(/^do\s+/,"");c&&c!=="do"&&l.push(c),e++}t.push({type:"for",var:a[1],list:a[2],body:l})}else t.push({type:"cmd",line:n})}else if(n.startsWith("while ")){let a=n.replace(/^while\s+/,"").replace(/;\s*do\s*$/,"").trim(),l=[];for(e++;e<r.length&&r[e]?.trim()!=="done";){let c=r[e].trim().replace(/^do\s+/,"");c&&c!=="do"&&l.push(c),e++}t.push({type:"while",cond:a,body:l})}else t.push({type:"cmd",line:n});e++}return t}async function Pe(r,t){let e=await ke(r,t.env.vars,t.env.lastExitCode,t),n=e.match(/^\[?\s*(.+?)\s*\]?$/);if(n){let s=n[1],o=s.match(/^-([fdeznr])\s+(.+)$/);if(o){let[,c,u]=o,d=S(t.cwd,u);if(c==="f")return t.shell.vfs.exists(d)&&t.shell.vfs.stat(d).type==="file";if(c==="d")return t.shell.vfs.exists(d)&&t.shell.vfs.stat(d).type==="directory";if(c==="e")return t.shell.vfs.exists(d);if(c==="z")return(u??"").length===0;if(c==="n")return(u??"").length>0}let a=s.match(/^"?([^"]*)"?\s*(==|!=|=|<|>)\s*"?([^"]*)"?$/);if(a){let[,c,u,d]=a;if(u==="=="||u==="=")return c===d;if(u==="!=")return c!==d}let l=s.match(/^(\S+)\s+(-eq|-ne|-lt|-le|-gt|-ge)\s+(\S+)$/);if(l){let[,c,u,d]=l,m=Number(c),p=Number(d);if(u==="-eq")return m===p;if(u==="-ne")return m!==p;if(u==="-lt")return m<p;if(u==="-le")return m<=p;if(u==="-gt")return m>p;if(u==="-ge")return m>=p}}return((await K(e,t.authUser,t.hostname,t.mode,t.cwd,t.shell,void 0,t.env)).exitCode??0)===0}async function vt(r,t){let e={exitCode:0},n="";for(let i of r)if(i.type==="cmd"){let s=await ke(i.line,t.env.vars,t.env.lastExitCode,t),o=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)/,a=s.trim().split(/\s+/);if(a.length>0&&o.test(a[0])&&a.every(u=>o.test(u))){for(let u of a){let d=u.match(o);t.env.vars[d[1]]=d[2]}t.env.lastExitCode=0;continue}let l=await(async()=>{let c=s.trim().split(/\s+/)[0]??"",u=t.env.vars[`__func_${c}`];if(u){let d=s.trim().split(/\s+/).slice(1),m={...t.env.vars};d.forEach((g,f)=>{t.env.vars[String(f+1)]=g}),t.env.vars[0]=c;let p=u.split(`
177
+ `),y=await vt(bt(p),t);for(let g=1;g<=d.length;g++)delete t.env.vars[String(g)];return Object.assign(t.env.vars,{...m,...t.env.vars}),y}return K(s,t.authUser,t.hostname,t.mode,t.cwd,t.shell,void 0,t.env)})();if(t.env.lastExitCode=l.exitCode??0,l.stdout&&(n+=`${l.stdout}
178
+ `),l.stderr)return{...l,stdout:n.trim()};e=l}else if(i.type==="if"){let s=!1;if(await Pe(i.cond,t)){let o=await vt(bt(i.then_),t);o.stdout&&(n+=`${o.stdout}
179
+ `),s=!0}else{for(let o of i.elif)if(await Pe(o.cond,t)){let a=await vt(bt(o.body),t);a.stdout&&(n+=`${a.stdout}
180
+ `),s=!0;break}if(!s&&i.else_.length>0){let o=await vt(bt(i.else_),t);o.stdout&&(n+=`${o.stdout}
181
+ `)}}}else if(i.type==="func")t.env.vars[`__func_${i.name}`]=i.body.join(`
182
+ `);else if(i.type==="arith"){let{expandSync:s}=await Promise.resolve().then(()=>(kt(),we)),o=s(i.expr,t.env.vars,t.env.lastExitCode),a=o.match(/^(\w+)\s*(\+\+|--)$/);if(a){let l=parseInt(t.env.vars[a[1]]??"0",10);t.env.vars[a[1]]=String(a[2]==="++"?l+1:l-1)}else{let l=o.match(/^(\w+)\s*([+\-*/])=\s*(.+)$/);if(l){let c=parseInt(t.env.vars[l[1]]??"0",10),u=parseInt(l[3],10),d={"+":c+u,"-":c-u,"*":c*u,"/":Math.floor(c/u)};t.env.vars[l[1]]=String(d[l[2]]??c)}}}else if(i.type==="for"){let s=await ke(i.list,t.env.vars,t.env.lastExitCode,t),{expandBraces:o}=await Promise.resolve().then(()=>(kt(),we)),a=s.trim().split(/\s+/).flatMap(o);for(let l of a){t.env.vars[i.var]=l;let c=await vt(bt(i.body),t);if(c.stdout&&(n+=`${c.stdout}
183
+ `),c.closeSession)return c}}else if(i.type==="while"){let s=0;for(;s<1e3&&await Pe(i.cond,t);){let o=await vt(bt(i.body),t);if(o.stdout&&(n+=`${o.stdout}
184
+ `),o.closeSession)return o;s++}}return{...e,stdout:n.trim()||e.stdout}}function Cn(r){let t=[],e="",n=0,i=!1,s=!1,o=0;for(;o<r.length;){let l=r[o];if(!i&&!s){if(l==="'"){i=!0,e+=l,o++;continue}if(l==='"'){s=!0,e+=l,o++;continue}if(l==="{"){n++,e+=l,o++;continue}if(l==="}"){if(n--,e+=l,o++,n===0){let c=e.trim();for(c&&t.push(c),e="";o<r.length&&(r[o]===";"||r[o]===" ");)o++}continue}if(n===0&&(l===";"||l===`
185
+ `)){let c=e.trim();c&&!c.startsWith("#")&&t.push(c),e="",o++;continue}}else i&&l==="'"?i=!1:s&&l==='"'&&(s=!1);e+=l,o++}let a=e.trim();return a&&!a.startsWith("#")&&t.push(a),t}var $n={name:"sh",aliases:["bash"],description:"Execute shell script or command",category:"shell",params:["-c <script>","[<file>]"],run:async r=>{let{args:t,shell:e,cwd:n}=r;if(w(t,"-c")){let s=t[t.indexOf("-c")+1]??"";if(!s)return{stderr:"sh: -c requires a script",exitCode:1};let o=Cn(s),a=bt(o);return vt(a,r)}let i=t[0];if(i){let s=S(n,i);if(!e.vfs.exists(s))return{stderr:`sh: ${i}: No such file or directory`,exitCode:1};let o=e.vfs.readFile(s),a=Cn(o),l=bt(a);return vt(l,r)}return{stderr:"sh: invalid usage. Use: sh -c 'cmd' or sh <file>",exitCode:1}}};var Pn={name:"shift",description:"Shift positional parameters",category:"shell",params:["[n]"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};let e=parseInt(r[0]??"1",10)||1,n=t.vars.__argv?.split("\0").filter(Boolean)??[];t.vars.__argv=n.slice(e).join("\0");let i=n.slice(e);for(let s=1;s<=9;s++)t.vars[String(s)]=i[s-1]??"";return{exitCode:0}}},kn={name:"trap",description:"Trap signals and events",category:"shell",params:["[action] [signal...]"],run:({args:r,env:t})=>{if(!t||r.length===0)return{exitCode:0};let e=r[0]??"",n=r.slice(1);for(let i of n)t.vars[`__trap_${i.toUpperCase()}`]=e;return{exitCode:0}}},Mn={name:"return",description:"Return from a shell function",category:"shell",params:["[n]"],run:({args:r,env:t})=>{let e=parseInt(r[0]??"0",10);return t&&(t.lastExitCode=e),{exitCode:e}}};var Fn={name:"sleep",description:"Delay execution",category:"system",params:["<seconds>"],run:async({args:r})=>{let t=parseFloat(r[0]??"1");return Number.isNaN(t)||t<0?{stderr:"sleep: invalid time",exitCode:1}:(await new Promise(e=>setTimeout(e,t*1e3)),{exitCode:0})}};var An={name:"sort",description:"Sort lines of text",category:"text",params:["[-r] [-n] [-u] [-k <col>] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=w(n,["-r"]),o=w(n,["-n"]),a=w(n,["-u"]),l=n.filter(y=>!y.startsWith("-")),d=[...(l.length>0?l.map(y=>{try{return D(r,S(e,y),"sort"),t.vfs.readFile(S(e,y))}catch{return""}}).join(`
179
186
  `):i??"").split(`
180
- `).filter(Boolean)].sort((w,g)=>o?Number(w)-Number(g):w.localeCompare(g)),m=s?d.reverse():d;return{stdout:(a?[...new Set(m)]:m).join(`
181
- `),exitCode:0}}};var $n={name:"source",aliases:["."],description:"Execute commands from a file in the current shell environment",category:"shell",params:["<file> [args...]"],run:async({args:r,authUser:t,hostname:e,cwd:n,shell:i,env:s})=>{let o=r[0];if(!o)return{stderr:"source: missing filename",exitCode:1};let a=x(n,o);if(!i.vfs.exists(a))return{stderr:`source: ${o}: No such file or directory`,exitCode:1};let l=i.vfs.readFile(a),c=0;for(let u of l.split(`
182
- `)){let d=u.trim();if(!d||d.startsWith("#"))continue;let m=await H(d,t,e,"shell",n,i,void 0,s);if(c=m.exitCode??0,m.closeSession||m.switchUser)return m}return{exitCode:c}}};var Pn={name:"su",description:"Switch user",category:"users",params:["[-] [-c <cmd>] [username]"],run:async({authUser:r,shell:t,args:e,hostname:n,mode:i,cwd:s})=>{let o=e.includes("-")||e.includes("-l")||e.includes("--login"),a=e.indexOf("-c"),l=a!==-1?e[a+1]:void 0,u=e.filter((d,m)=>m!==a&&m!==a+1).filter(d=>d!=="-"&&d!=="-l"&&d!=="--login").find(d=>!d.startsWith("-"))??"root";return t.users.listUsers().includes(u)?r==="root"?l?H(l,u,n,i,o?`/home/${u}`:s,t):{switchUser:u,nextCwd:o?`/home/${u}`:void 0,exitCode:0}:t.users.isSudoer(r)?{sudoChallenge:{username:u,targetUser:u,commandLine:l??null,loginShell:o,prompt:"Password: "},exitCode:0}:{stderr:`su: permission denied
187
+ `).filter(Boolean)].sort((y,g)=>o?Number(y)-Number(g):y.localeCompare(g)),m=s?d.reverse():d;return{stdout:(a?[...new Set(m)]:m).join(`
188
+ `),exitCode:0}}};var En={name:"source",aliases:["."],description:"Execute commands from a file in the current shell environment",category:"shell",params:["<file> [args...]"],run:async({args:r,authUser:t,hostname:e,cwd:n,shell:i,env:s})=>{let o=r[0];if(!o)return{stderr:"source: missing filename",exitCode:1};let a=S(n,o);if(!i.vfs.exists(a))return{stderr:`source: ${o}: No such file or directory`,exitCode:1};let l=i.vfs.readFile(a),c=0;for(let u of l.split(`
189
+ `)){let d=u.trim();if(!d||d.startsWith("#"))continue;let m=await K(d,t,e,"shell",n,i,void 0,s);if(c=m.exitCode??0,m.closeSession||m.switchUser)return m}return{exitCode:c}}};var Nn={name:"su",description:"Switch user",category:"users",params:["[-] [-c <cmd>] [username]"],run:async({authUser:r,shell:t,args:e,hostname:n,mode:i,cwd:s})=>{let o=e.includes("-")||e.includes("-l")||e.includes("--login"),a=e.indexOf("-c"),l=a!==-1?e[a+1]:void 0,u=e.filter((d,m)=>m!==a&&m!==a+1).filter(d=>d!=="-"&&d!=="-l"&&d!=="--login").find(d=>!d.startsWith("-"))??"root";return t.users.listUsers().includes(u)?r==="root"?l?K(l,u,n,i,o?`/home/${u}`:s,t):{switchUser:u,nextCwd:o?`/home/${u}`:void 0,exitCode:0}:t.users.isSudoer(r)?{sudoChallenge:{username:u,targetUser:u,commandLine:l??null,loginShell:o,prompt:"Password: "},exitCode:0}:{stderr:`su: permission denied
183
190
  `,exitCode:1}:{stderr:`su: user '${u}' does not exist
184
- `,exitCode:1}}};function hi(r){let{flags:t,flagsWithValues:e,positionals:n}=nt(r,{flags:["-i","-S"],flagsWithValue:["-u","--user"]}),i=t.has("-i"),s=e.get("-u")||e.get("--user")||"root",o=n.length>0?n.join(" "):null;return{targetUser:s,loginShell:i,commandLine:o}}var kn={name:"sudo",description:"Execute as superuser",category:"users",params:["<command...>"],run:async({authUser:r,hostname:t,mode:e,cwd:n,shell:i,args:s})=>{let{targetUser:o,loginShell:a,commandLine:l}=hi(s);if(r!=="root"&&!i.users.isSudoer(r))return{stderr:"sudo: permission denied",exitCode:1};let c=o||"root",u=`[sudo] password for ${r}: `;return r==="root"?!l&&a?{switchUser:c,nextCwd:`/home/${c}`,exitCode:0}:l?H(l,c,t,e,a?`/home/${c}`:n,i):{stderr:"sudo: missing command",exitCode:1}:{sudoChallenge:{username:r,targetUser:c,commandLine:l,loginShell:a,prompt:u},exitCode:0}}};var Mn={name:"tail",description:"Output last lines",category:"text",params:["[-n <lines>] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=st(n,["-n"]),o=n.find(d=>/^-\d+$/.test(d)),a=typeof s=="string"?parseInt(s,10):o?parseInt(o.slice(1),10):10,l=n.filter(d=>!d.startsWith("-")&&d!==s&&d!==String(a)),c=d=>{let m=d.split(`
191
+ `,exitCode:1}}};function Ci(r){let{flags:t,flagsWithValues:e,positionals:n}=st(r,{flags:["-i","-S"],flagsWithValue:["-u","--user"]}),i=t.has("-i"),s=e.get("-u")||e.get("--user")||"root",o=n.length>0?n.join(" "):null;return{targetUser:s,loginShell:i,commandLine:o}}var In={name:"sudo",description:"Execute as superuser",category:"users",params:["<command...>"],run:async({authUser:r,hostname:t,mode:e,cwd:n,shell:i,args:s})=>{let{targetUser:o,loginShell:a,commandLine:l}=Ci(s);if(r!=="root"&&!i.users.isSudoer(r))return{stderr:"sudo: permission denied",exitCode:1};let c=o||"root",u=`[sudo] password for ${r}: `;return r==="root"?!l&&a?{switchUser:c,nextCwd:`/home/${c}`,exitCode:0}:l?K(l,c,t,e,a?`/home/${c}`:n,i):{stderr:"sudo: missing command",exitCode:1}:{sudoChallenge:{username:r,targetUser:c,commandLine:l,loginShell:a,prompt:u},exitCode:0}}};var Vn={name:"tail",description:"Output last lines",category:"text",params:["[-n <lines>] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=it(n,["-n"]),o=n.find(d=>/^-\d+$/.test(d)),a=typeof s=="string"?parseInt(s,10):o?parseInt(o.slice(1),10):10,l=n.filter(d=>!d.startsWith("-")&&d!==s&&d!==String(a)),c=d=>{let m=d.split(`
185
192
  `),p=d.endsWith(`
186
- `),w=p?m.slice(0,-1):m;return w.slice(Math.max(0,w.length-a)).join(`
193
+ `),y=p?m.slice(0,-1):m;return y.slice(Math.max(0,y.length-a)).join(`
187
194
  `)+(p?`
188
- `:"")};if(l.length===0)return{stdout:c(i??""),exitCode:0};let u=[];for(let d of l){let m=x(e,d);try{_(r,m,"tail"),u.push(c(t.vfs.readFile(m)))}catch{return{stderr:`tail: ${d}: No such file or directory`,exitCode:1}}}return{stdout:u.join(`
189
- `),exitCode:0}}};var Fn={name:"tar",description:"Archive utility",category:"archive",params:["[-czf|-xzf|-tf] <archive> [files...]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=[],s=!1;for(let m of n)if(/^-[a-zA-Z]{2,}$/.test(m))for(let p of m.slice(1))i.push(`-${p}`);else if(!s&&/^[cxtdru]{1,}[a-zA-Z]*$/.test(m)&&!m.includes("/")&&!m.startsWith("-")){s=!0;for(let p of m)i.push(`-${p}`)}else i.push(m);let o=i.includes("-c"),a=i.includes("-x"),l=i.includes("-t"),c=i.indexOf("-f"),u=c!==-1?i[c+1]:i.find(m=>m.endsWith(".tar")||m.endsWith(".tar.gz")||m.endsWith(".tgz"));if(!o&&!a&&!l)return{stderr:`tar: must specify -c, -x, or -t
195
+ `:"")};if(l.length===0)return{stdout:c(i??""),exitCode:0};let u=[];for(let d of l){let m=S(e,d);try{D(r,m,"tail"),u.push(c(t.vfs.readFile(m)))}catch{return{stderr:`tail: ${d}: No such file or directory`,exitCode:1}}}return{stdout:u.join(`
196
+ `),exitCode:0}}};var Rn={name:"tar",description:"Archive utility",category:"archive",params:["[-czf|-xzf|-tf] <archive> [files...]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=[],s=!1;for(let m of n)if(/^-[a-zA-Z]{2,}$/.test(m))for(let p of m.slice(1))i.push(`-${p}`);else if(!s&&/^[cxtdru]{1,}[a-zA-Z]*$/.test(m)&&!m.includes("/")&&!m.startsWith("-")){s=!0;for(let p of m)i.push(`-${p}`)}else i.push(m);let o=i.includes("-c"),a=i.includes("-x"),l=i.includes("-t"),c=i.indexOf("-f"),u=c!==-1?i[c+1]:i.find(m=>m.endsWith(".tar")||m.endsWith(".tar.gz")||m.endsWith(".tgz"));if(!o&&!a&&!l)return{stderr:`tar: must specify -c, -x, or -t
190
197
  `,exitCode:1};if(!u)return{stderr:`tar: no archive specified
191
- `,exitCode:1};let d=x(e,u);if(o){let m=new Set;c!==-1&&m.add(c+1);let p=i.filter((g,f)=>!g.startsWith("-")&&g!==u&&!m.has(f)),w={};for(let g of p){let f=x(e,g);try{if(t.vfs.stat(f).type==="file")w[g]=t.vfs.readFile(f);else{let E=(F,S)=>{for(let k of t.vfs.list(F)){let V=`${F}/${k}`,b=`${S}/${k}`;t.vfs.stat(V).type==="file"?w[b]=t.vfs.readFile(V):E(V,b)}};E(f,g)}}catch{return{stderr:`tar: ${g}: No such file or directory`,exitCode:1}}}return t.writeFileAsUser(r,d,JSON.stringify(w)),{exitCode:0}}if(l||a){let m;try{m=JSON.parse(t.vfs.readFile(d))}catch{return{stderr:`tar: ${u}: cannot open archive`,exitCode:1}}if(l)return{stdout:Object.keys(m).join(`
192
- `),exitCode:0};for(let[p,w]of Object.entries(m))t.writeFileAsUser(r,x(e,p),w);return{exitCode:0}}return{stderr:"tar: must specify -c, -x, or -t",exitCode:1}}};var An={name:"tee",description:"Read stdin, write to stdout and files",category:"text",params:["[-a] <file...>"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=y(n,["-a"]),o=n.filter(l=>!l.startsWith("-")),a=i??"";for(let l of o){let c=x(e,l);if(s){let u=(()=>{try{return t.vfs.readFile(c)}catch{return""}})();t.writeFileAsUser(r,c,u+a)}else t.writeFileAsUser(r,c,a)}return{stdout:a,exitCode:0}}};function At(r,t,e){if(r[r.length-1]==="]"&&(r=r.slice(0,-1)),r[0]==="["&&(r=r.slice(1)),r.length===0)return!1;if(r[0]==="!")return!At(r.slice(1),t,e);let n=r.indexOf("-a");if(n!==-1)return At(r.slice(0,n),t,e)&&At(r.slice(n+1),t,e);let i=r.indexOf("-o");if(i!==-1)return At(r.slice(0,i),t,e)||At(r.slice(i+1),t,e);if(r.length===2){let[s,o=""]=r,l=(c=>c.startsWith("/")?c:`${e}/${c}`.replace(/\/+/g,"/"))(o);switch(s){case"-e":return t.vfs.exists(l);case"-f":return t.vfs.exists(l)&&t.vfs.stat(l).type==="file";case"-d":return t.vfs.exists(l)&&t.vfs.stat(l).type==="directory";case"-r":return t.vfs.exists(l);case"-w":return t.vfs.exists(l);case"-x":return t.vfs.exists(l)&&!!(t.vfs.stat(l).mode&73);case"-s":return t.vfs.exists(l)&&t.vfs.stat(l).type==="file"&&t.vfs.stat(l).size>0;case"-z":return o.length===0;case"-n":return o.length>0;case"-L":return t.vfs.isSymlink(l)}}if(r.length===3){let[s="",o,a=""]=r,l=Number(s),c=Number(a);switch(o){case"=":case"==":return s===a;case"!=":return s!==a;case"<":return s<a;case">":return s>a;case"-eq":return l===c;case"-ne":return l!==c;case"-lt":return l<c;case"-le":return l<=c;case"-gt":return l>c;case"-ge":return l>=c}}return r.length===1?(r[0]??"").length>0:!1}var En={name:"test",aliases:["["],description:"Evaluate conditional expression",category:"shell",params:["<expression>"],run:({args:r,shell:t,cwd:e})=>{try{return{exitCode:At([...r],t,e)?0:1}}catch{return{stderr:"test: malformed expression",exitCode:2}}}};var Nn={name:"touch",description:"Create or update files",category:"files",params:["<file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{if(n.length===0)return{stderr:"touch: missing file operand",exitCode:1};for(let i of n){let s=x(e,i);_(r,s,"touch"),t.vfs.exists(s)||t.writeFileAsUser(r,s,"")}return{exitCode:0}}};function gi(r){return r.replace(/\\n/g,`
193
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function In(r){let t=[],e=gi(r),n=0;for(;n<e.length;){if(n+2<e.length&&e[n+1]==="-"){let i=e.charCodeAt(n),s=e.charCodeAt(n+2);if(i<=s){for(let o=i;o<=s;o++)t.push(String.fromCharCode(o));n+=3;continue}}t.push(e[n]),n++}return t}var Vn={name:"tr",description:"Translate or delete characters",category:"text",params:["[-d] [-s] <set1> [set2]"],run:({args:r,stdin:t})=>{let e=y(r,["-d"]),n=y(r,["-s"]),i=r.filter(l=>!l.startsWith("-")),s=In(i[0]??""),o=In(i[1]??""),a=t??"";if(e){let l=new Set(s);a=[...a].filter(c=>!l.has(c)).join("")}else if(o.length>0){let l=new Map;for(let c=0;c<s.length;c++)l.set(s[c],o[c]??o[o.length-1]??"");a=[...a].map(c=>l.get(c)??c).join("")}if(n&&o.length>0){let l=new Set(o);a=a.replace(/(.)\1+/g,(c,u)=>l.has(u)?u:c)}return{stdout:a,exitCode:0}}};var Rn={name:"tree",description:"Display directory tree",category:"navigation",params:["[path]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=x(e,St(n,0)??e);return _(r,i,"tree"),{stdout:t.vfs.tree(i),exitCode:0}}};var Dn={name:"true",description:"Return success exit code",category:"shell",params:[],run:()=>({exitCode:0})},_n={name:"false",description:"Return failure exit code",category:"shell",params:[],run:()=>({exitCode:1})};var zn={name:"type",description:"Describe how a command would be interpreted",category:"shell",params:["<command...>"],run:({args:r,shell:t,env:e})=>{if(r.length===0)return{stderr:"type: missing argument",exitCode:1};let n=(e?.vars?.PATH??"/usr/local/bin:/usr/bin:/bin").split(":"),i=[],s=0;for(let o of r){if(ft(o)){i.push(`${o} is a shell builtin`);continue}let a=!1;for(let l of n){let c=`${l}/${o}`;if(t.vfs.exists(c)){i.push(`${o} is ${c}`),a=!0;break}}a||(i.push(`${o}: not found`),s=1)}return{stdout:i.join(`
194
- `),exitCode:s}}};var Ln={name:"uname",description:"Print system information",category:"system",params:["[-a] [-s] [-r] [-m]"],run:({shell:r,args:t})=>{let e=y(t,["-a"]),n="Linux",i=r.properties?.kernel??"5.15.0",s=r.properties?.arch??"x86_64",o=r.hostname;return e?{stdout:`${n} ${o} ${i} #1 SMP ${s} GNU/Linux`,exitCode:0}:y(t,["-r"])?{stdout:i,exitCode:0}:y(t,["-m"])?{stdout:s,exitCode:0}:{stdout:n,exitCode:0}}};var Un={name:"uniq",description:"Report or filter out repeated lines",category:"text",params:["[-c] [-d] [-u] [file]"],run:({args:r,stdin:t})=>{let e=y(r,["-c"]),n=y(r,["-d"]),i=y(r,["-u"]),s=(t??"").split(`
198
+ `,exitCode:1};let d=S(e,u);if(o){let m=new Set;c!==-1&&m.add(c+1);let p=i.filter((g,f)=>!g.startsWith("-")&&g!==u&&!m.has(f)),y={};for(let g of p){let f=S(e,g);try{if(t.vfs.stat(f).type==="file")y[g]=t.vfs.readFile(f);else{let N=(M,x)=>{for(let k of t.vfs.list(M)){let A=`${M}/${k}`,b=`${x}/${k}`;t.vfs.stat(A).type==="file"?y[b]=t.vfs.readFile(A):N(A,b)}};N(f,g)}}catch{return{stderr:`tar: ${g}: No such file or directory`,exitCode:1}}}return t.writeFileAsUser(r,d,JSON.stringify(y)),{exitCode:0}}if(l||a){let m;try{m=JSON.parse(t.vfs.readFile(d))}catch{return{stderr:`tar: ${u}: cannot open archive`,exitCode:1}}if(l)return{stdout:Object.keys(m).join(`
199
+ `),exitCode:0};for(let[p,y]of Object.entries(m))t.writeFileAsUser(r,S(e,p),y);return{exitCode:0}}return{stderr:"tar: must specify -c, -x, or -t",exitCode:1}}};var _n={name:"tee",description:"Read stdin, write to stdout and files",category:"text",params:["[-a] <file...>"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=w(n,["-a"]),o=n.filter(l=>!l.startsWith("-")),a=i??"";for(let l of o){let c=S(e,l);if(s){let u=(()=>{try{return t.vfs.readFile(c)}catch{return""}})();t.writeFileAsUser(r,c,u+a)}else t.writeFileAsUser(r,c,a)}return{stdout:a,exitCode:0}}};function Et(r,t,e){if(r[r.length-1]==="]"&&(r=r.slice(0,-1)),r[0]==="["&&(r=r.slice(1)),r.length===0)return!1;if(r[0]==="!")return!Et(r.slice(1),t,e);let n=r.indexOf("-a");if(n!==-1)return Et(r.slice(0,n),t,e)&&Et(r.slice(n+1),t,e);let i=r.indexOf("-o");if(i!==-1)return Et(r.slice(0,i),t,e)||Et(r.slice(i+1),t,e);if(r.length===2){let[s,o=""]=r,l=(c=>c.startsWith("/")?c:`${e}/${c}`.replace(/\/+/g,"/"))(o);switch(s){case"-e":return t.vfs.exists(l);case"-f":return t.vfs.exists(l)&&t.vfs.stat(l).type==="file";case"-d":return t.vfs.exists(l)&&t.vfs.stat(l).type==="directory";case"-r":return t.vfs.exists(l);case"-w":return t.vfs.exists(l);case"-x":return t.vfs.exists(l)&&!!(t.vfs.stat(l).mode&73);case"-s":return t.vfs.exists(l)&&t.vfs.stat(l).type==="file"&&t.vfs.stat(l).size>0;case"-z":return o.length===0;case"-n":return o.length>0;case"-L":return t.vfs.isSymlink(l)}}if(r.length===3){let[s="",o,a=""]=r,l=Number(s),c=Number(a);switch(o){case"=":case"==":return s===a;case"!=":return s!==a;case"<":return s<a;case">":return s>a;case"-eq":return l===c;case"-ne":return l!==c;case"-lt":return l<c;case"-le":return l<=c;case"-gt":return l>c;case"-ge":return l>=c}}return r.length===1?(r[0]??"").length>0:!1}var Dn={name:"test",aliases:["["],description:"Evaluate conditional expression",category:"shell",params:["<expression>"],run:({args:r,shell:t,cwd:e})=>{try{return{exitCode:Et([...r],t,e)?0:1}}catch{return{stderr:"test: malformed expression",exitCode:2}}}};var zn={name:"touch",description:"Create or update files",category:"files",params:["<file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{if(n.length===0)return{stderr:"touch: missing file operand",exitCode:1};for(let i of n){let s=S(e,i);D(r,s,"touch"),t.vfs.exists(s)||t.writeFileAsUser(r,s,"")}return{exitCode:0}}};function $i(r){return r.replace(/\\n/g,`
200
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function Ln(r){let t=[],e=$i(r),n=0;for(;n<e.length;){if(n+2<e.length&&e[n+1]==="-"){let i=e.charCodeAt(n),s=e.charCodeAt(n+2);if(i<=s){for(let o=i;o<=s;o++)t.push(String.fromCharCode(o));n+=3;continue}}t.push(e[n]),n++}return t}var Tn={name:"tr",description:"Translate or delete characters",category:"text",params:["[-d] [-s] <set1> [set2]"],run:({args:r,stdin:t})=>{let e=w(r,["-d"]),n=w(r,["-s"]),i=r.filter(l=>!l.startsWith("-")),s=Ln(i[0]??""),o=Ln(i[1]??""),a=t??"";if(e){let l=new Set(s);a=[...a].filter(c=>!l.has(c)).join("")}else if(o.length>0){let l=new Map;for(let c=0;c<s.length;c++)l.set(s[c],o[c]??o[o.length-1]??"");a=[...a].map(c=>l.get(c)??c).join("")}if(n&&o.length>0){let l=new Set(o);a=a.replace(/(.)\1+/g,(c,u)=>l.has(u)?u:c)}return{stdout:a,exitCode:0}}};var Un={name:"tree",description:"Display directory tree",category:"navigation",params:["[path]"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=S(e,xt(n,0)??e);return D(r,i,"tree"),{stdout:t.vfs.tree(i),exitCode:0}}};var Bn={name:"true",description:"Return success exit code",category:"shell",params:[],run:()=>({exitCode:0})},On={name:"false",description:"Return failure exit code",category:"shell",params:[],run:()=>({exitCode:1})};var Wn={name:"type",description:"Describe how a command would be interpreted",category:"shell",params:["<command...>"],run:({args:r,shell:t,env:e})=>{if(r.length===0)return{stderr:"type: missing argument",exitCode:1};let n=(e?.vars?.PATH??"/usr/local/bin:/usr/bin:/bin").split(":"),i=[],s=0;for(let o of r){if(ut(o)){i.push(`${o} is a shell builtin`);continue}let a=!1;for(let l of n){let c=`${l}/${o}`;if(t.vfs.exists(c)){i.push(`${o} is ${c}`),a=!0;break}}a||(i.push(`${o}: not found`),s=1)}return{stdout:i.join(`
201
+ `),exitCode:s}}};var jn={name:"uname",description:"Print system information",category:"system",params:["[-a] [-s] [-r] [-m]"],run:({shell:r,args:t})=>{let e=w(t,["-a"]),n="Linux",i=r.properties?.kernel??"5.15.0",s=r.properties?.arch??"x86_64",o=r.hostname;return e?{stdout:`${n} ${o} ${i} #1 SMP ${s} GNU/Linux`,exitCode:0}:w(t,["-r"])?{stdout:i,exitCode:0}:w(t,["-m"])?{stdout:s,exitCode:0}:{stdout:n,exitCode:0}}};var Hn={name:"uniq",description:"Report or filter out repeated lines",category:"text",params:["[-c] [-d] [-u] [file]"],run:({args:r,stdin:t})=>{let e=w(r,["-c"]),n=w(r,["-d"]),i=w(r,["-u"]),s=(t??"").split(`
195
202
  `),o=[],a=0;for(;a<s.length;){let l=a;for(;l<s.length&&s[l]===s[a];)l++;let c=l-a,u=s[a];if(n&&c===1){a=l;continue}if(i&&c>1){a=l;continue}o.push(e?`${String(c).padStart(4)} ${u}`:u),a=l}return{stdout:o.join(`
196
- `),exitCode:0}}};var Tn={name:"unset",description:"Remove shell variable",category:"shell",params:["<VAR>"],run:({args:r,env:t})=>{for(let e of r)delete t.vars[e];return{exitCode:0}}};var Bn={name:"uptime",description:"Tell how long the system has been running",category:"system",params:["[-p] [-s]"],run:({args:r,shell:t})=>{let e=y(r,["-p"]),n=y(r,["-s"]),i=Math.floor((Date.now()-t.startTime)/1e3),s=Math.floor(i/86400),o=Math.floor(i%86400/3600),a=Math.floor(i%3600/60);if(n)return{stdout:new Date(t.startTime).toISOString().slice(0,19).replace("T"," "),exitCode:0};if(e){let m=[];return s>0&&m.push(`${s} day${s>1?"s":""}`),o>0&&m.push(`${o} hour${o>1?"s":""}`),m.push(`${a} minute${a!==1?"s":""}`),{stdout:`up ${m.join(", ")}`,exitCode:0}}let l=new Date().toTimeString().slice(0,8),c=s>0?`${s} day${s>1?"s":""}, ${String(o).padStart(2)}:${String(a).padStart(2,"0")}`:`${String(o).padStart(2)}:${String(a).padStart(2,"0")}`,u=t.users.listActiveSessions().length,d=(Math.random()*.5).toFixed(2);return{stdout:` ${l} up ${c}, ${u} user${u!==1?"s":""}, load average: ${d}, ${d}, ${d}`,exitCode:0}}};var Wn={name:"wc",description:"Count words/lines/bytes",category:"text",params:["[-l] [-w] [-c] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=y(n,["-l"]),o=y(n,["-w"]),a=y(n,["-c"]),l=!s&&!o&&!a,c=n.filter(m=>!m.startsWith("-")),u=(m,p)=>{let w=m.split(`
203
+ `),exitCode:0}}};var qn={name:"unset",description:"Remove shell variable",category:"shell",params:["<VAR>"],run:({args:r,env:t})=>{for(let e of r)delete t.vars[e];return{exitCode:0}}};var Kn={name:"uptime",description:"Tell how long the system has been running",category:"system",params:["[-p] [-s]"],run:({args:r,shell:t})=>{let e=w(r,["-p"]),n=w(r,["-s"]),i=Math.floor((Date.now()-t.startTime)/1e3),s=Math.floor(i/86400),o=Math.floor(i%86400/3600),a=Math.floor(i%3600/60);if(n)return{stdout:new Date(t.startTime).toISOString().slice(0,19).replace("T"," "),exitCode:0};if(e){let m=[];return s>0&&m.push(`${s} day${s>1?"s":""}`),o>0&&m.push(`${o} hour${o>1?"s":""}`),m.push(`${a} minute${a!==1?"s":""}`),{stdout:`up ${m.join(", ")}`,exitCode:0}}let l=new Date().toTimeString().slice(0,8),c=s>0?`${s} day${s>1?"s":""}, ${String(o).padStart(2)}:${String(a).padStart(2,"0")}`:`${String(o).padStart(2)}:${String(a).padStart(2,"0")}`,u=t.users.listActiveSessions().length,d=(Math.random()*.5).toFixed(2);return{stdout:` ${l} up ${c}, ${u} user${u!==1?"s":""}, load average: ${d}, ${d}, ${d}`,exitCode:0}}};var Gn={name:"wc",description:"Count words/lines/bytes",category:"text",params:["[-l] [-w] [-c] [file...]"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=w(n,["-l"]),o=w(n,["-w"]),a=w(n,["-c"]),l=!s&&!o&&!a,c=n.filter(m=>!m.startsWith("-")),u=(m,p)=>{let y=m.split(`
197
204
  `).length-(m.endsWith(`
198
- `)?1:0),g=m.trim().split(/\s+/).filter(Boolean).length,f=Buffer.byteLength(m,"utf8"),$=[];return(l||s)&&$.push(String(w).padStart(7)),(l||o)&&$.push(String(g).padStart(7)),(l||a)&&$.push(String(f).padStart(7)),p&&$.push(` ${p}`),$.join("")};if(c.length===0)return{stdout:u(i??"",""),exitCode:0};let d=[];for(let m of c){let p=x(e,m);try{_(r,p,"wc");let w=t.vfs.readFile(p);d.push(u(w,m))}catch{return{stderr:`wc: ${m}: No such file or directory`,exitCode:1}}}return{stdout:d.join(`
199
- `),exitCode:0}}};var On={name:"wget",description:"File downloader (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:r,cwd:t,args:e,shell:n})=>{let{flagsWithValues:i,positionals:s}=nt(e,{flagsWithValue:["-O","--output-document","-o","--output-file","-P","--directory-prefix","--tries","--timeout"]});if(y(e,["-h","--help"]))return{stdout:["Usage: wget [option]... [URL]..."," -O, --output-document=FILE Write to FILE ('-' for stdout)"," -P, --directory-prefix=DIR Save files in DIR"," -q, --quiet Quiet mode"," -v, --verbose Verbose output (default)"," -c, --continue Continue partial download"," --tries=N Retry N times"," --timeout=N Timeout in seconds"].join(`
200
- `),exitCode:0};if(y(e,["-V","--version"]))return{stdout:"GNU Wget 1.21.3 (virtual) built on Fortune GNU/Linux.",exitCode:0};let o=s[0];if(!o)return{stderr:`wget: missing URL
205
+ `)?1:0),g=m.trim().split(/\s+/).filter(Boolean).length,f=Buffer.byteLength(m,"utf8"),$=[];return(l||s)&&$.push(String(y).padStart(7)),(l||o)&&$.push(String(g).padStart(7)),(l||a)&&$.push(String(f).padStart(7)),p&&$.push(` ${p}`),$.join("")};if(c.length===0)return{stdout:u(i??"",""),exitCode:0};let d=[];for(let m of c){let p=S(e,m);try{D(r,p,"wc");let y=t.vfs.readFile(p);d.push(u(y,m))}catch{return{stderr:`wc: ${m}: No such file or directory`,exitCode:1}}}return{stdout:d.join(`
206
+ `),exitCode:0}}};var Zn={name:"wget",description:"File downloader (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:r,cwd:t,args:e,shell:n})=>{let{flagsWithValues:i,positionals:s}=st(e,{flagsWithValue:["-O","--output-document","-o","--output-file","-P","--directory-prefix","--tries","--timeout"]});if(w(e,["-h","--help"]))return{stdout:["Usage: wget [option]... [URL]..."," -O, --output-document=FILE Write to FILE ('-' for stdout)"," -P, --directory-prefix=DIR Save files in DIR"," -q, --quiet Quiet mode"," -v, --verbose Verbose output (default)"," -c, --continue Continue partial download"," --tries=N Retry N times"," --timeout=N Timeout in seconds"].join(`
207
+ `),exitCode:0};if(w(e,["-V","--version"]))return{stdout:"GNU Wget 1.21.3 (virtual) built on Fortune GNU/Linux.",exitCode:0};let o=s[0];if(!o)return{stderr:`wget: missing URL
201
208
  Usage: wget [OPTION]... [URL]...`,exitCode:1};let a=o.startsWith("http://")||o.startsWith("https://")?o:`http://${o}`;if(!a)return{stderr:`wget: missing URL
202
- Usage: wget [OPTION]... [URL]...`,exitCode:1};let l=i.get("-O")??i.get("--output-document")??null,c=i.get("-P")??i.get("--directory-prefix")??null,u=y(e,["-q","--quiet"]),d=l==="-"?null:l??Te(a),m=d?x(t,c?`${c}/${d}`:d):null;m&&_(r,m,"wget");let p=[];u||(p.push(`--${new Date().toISOString()}-- ${a}`),p.push(`Resolving ${new URL(a).host}...`),p.push(`Connecting to ${new URL(a).host}...`));let w;try{w=await fetch(a,{headers:{"User-Agent":"Wget/1.21.3 (Fortune GNU/Linux)"}})}catch(f){let $=f instanceof Error?f.message:String(f);return p.push(`wget: unable to resolve host: ${$}`),{stderr:p.join(`
203
- `),exitCode:4}}if(!w.ok)return p.push(`ERROR ${w.status}: ${w.statusText}`),{stderr:p.join(`
204
- `),exitCode:8};let g;try{g=await w.text()}catch{return{stderr:"wget: failed to read response",exitCode:1}}if(!u){let f=w.headers.get("content-type")??"application/octet-stream";p.push(`HTTP request sent, awaiting response... ${w.status} ${w.statusText}`),p.push(`Length: ${g.length} [${f}]`)}return l==="-"?{stdout:g,stderr:p.join(`
209
+ Usage: wget [OPTION]... [URL]...`,exitCode:1};let l=i.get("-O")??i.get("--output-document")??null,c=i.get("-P")??i.get("--directory-prefix")??null,u=w(e,["-q","--quiet"]),d=l==="-"?null:l??We(a),m=d?S(t,c?`${c}/${d}`:d):null;m&&D(r,m,"wget");let p=[];u||(p.push(`--${new Date().toISOString()}-- ${a}`),p.push(`Resolving ${new URL(a).host}...`),p.push(`Connecting to ${new URL(a).host}...`));let y;try{y=await fetch(a,{headers:{"User-Agent":"Wget/1.21.3 (Fortune GNU/Linux)"}})}catch(f){let $=f instanceof Error?f.message:String(f);return p.push(`wget: unable to resolve host: ${$}`),{stderr:p.join(`
210
+ `),exitCode:4}}if(!y.ok)return p.push(`ERROR ${y.status}: ${y.statusText}`),{stderr:p.join(`
211
+ `),exitCode:8};let g;try{g=await y.text()}catch{return{stderr:"wget: failed to read response",exitCode:1}}if(!u){let f=y.headers.get("content-type")??"application/octet-stream";p.push(`HTTP request sent, awaiting response... ${y.status} ${y.statusText}`),p.push(`Length: ${g.length} [${f}]`)}return l==="-"?{stdout:g,stderr:p.join(`
205
212
  `)||void 0,exitCode:0}:m?(n.writeFileAsUser(r,m,g),u||p.push(`Saving to: '${m}'
206
213
  ${m} 100%[==================>] ${g.length} B`),{stderr:p.join(`
207
- `)||void 0,exitCode:0}):{stdout:g,exitCode:0}}};var jn={name:"which",description:"Locate a command in PATH",category:"shell",params:["<command...>"],run:({args:r,shell:t,env:e})=>{if(r.length===0)return{stderr:"which: missing argument",exitCode:1};let n=(e?.vars?.PATH??"/usr/local/bin:/usr/bin:/bin").split(":"),i=[],s=!1;for(let o of r){let a=!1;for(let l of n){let c=`${l}/${o}`;if(t.vfs.exists(c)&&t.vfs.stat(c).type==="file"){i.push(c),a=!0;break}}a||(s=!0)}return i.length===0?{exitCode:1}:{stdout:i.join(`
208
- `),exitCode:s?1:0}}};function re(r){let t=r.toLocaleString("en-US",{weekday:"short"}),e=r.toLocaleString("en-US",{month:"short"}),n=r.getDate().toString().padStart(2,"0"),i=r.getHours().toString().padStart(2,"0"),s=r.getMinutes().toString().padStart(2,"0"),o=r.getSeconds().toString().padStart(2,"0"),a=r.getFullYear();return`${t} ${e} ${n} ${i}:${s}:${o} ${a}`}var Hn={name:"who",description:"Show active sessions",category:"system",params:[],run:({shell:r})=>({stdout:r.users.listActiveSessions().map(e=>{let n=new Date(e.startedAt),i=Number.isNaN(n.getTime())?e.startedAt:re(n);return`${e.username} ${e.tty} ${i} (${e.remoteAddress||"unknown"})`}).join(`
209
- `),exitCode:0})};var qn={name:"whoami",description:"Print current user",category:"system",params:[],run:({authUser:r})=>({stdout:r,exitCode:0})};var Kn={name:"xargs",description:"Build and execute command lines from stdin",category:"text",params:["[command] [args...]"],run:async({authUser:r,hostname:t,mode:e,cwd:n,args:i,stdin:s,shell:o,env:a})=>{let l=i[0]??"echo",c=i.slice(1),u=(s??"").trim().split(/\s+/).filter(Boolean);if(u.length===0)return{exitCode:0};let d=[l,...c,...u].join(" ");return H(d,r,t,e,n,o,void 0,a)}};var yi=[an,Ge,Rr,Rn,Ke,Nn,mn,zr,Qe,Lr,Ar,Er,Ze,Nr,mr,fr,pn,He,vn,Un,Wn,wr,Mn,Xe,Vn,An,Kn,sr,Fn,gr,yr,qe,qn,Hn,Pr,Mr,hr,Ln,on,Fr,nr,ar,tr,Cn,nn,lr,cr,dr,fn,Tn,wn,Je,ur,Tr,kr,Ye,On,_e,rn,rr,kn,Pn,Jr,Oe,je,ir,or,jn,zn,_r,Le,Ue,En,$n,$r,sn,dn,er,Sn,xn,bn,Dn,_n,tn,en,Xr,un,Bn,pr,Dr],Gn=[],Tt=new Map,ne=null,wi=vr(()=>Pe().map(r=>r.name));function $e(){Tt.clear();for(let r of Pe()){Tt.set(r.name,r);for(let t of r.aliases??[])Tt.set(t,r)}ne=Array.from(Tt.keys()).sort()}function Pe(){return[...yi,...Gn,wi]}function xe(r){let t={...r,name:r.name.trim().toLowerCase(),aliases:r.aliases?.map(n=>n.trim().toLowerCase())};if([t.name,...t.aliases??[]].some(n=>n.length===0||/\s/.test(n)))throw new Error("Command names must be non-empty and contain no spaces");Gn.push(t),$e()}function be(r,t,e){return{name:r,params:t,run:e}}function Lt(){return ne||$e(),ne}function ge(){return Pe()}function ft(r){return ne||$e(),Tt.get(r.toLowerCase())}import{spawn as xi}from"node:child_process";import{readFile as Si}from"node:fs/promises";import*as se from"node:path";function ke(r){return`'${r.replace(/'/g,"'\\''")}'`}function Bt(r){return r.replace(/\r\n/g,`
214
+ `)||void 0,exitCode:0}):{stdout:g,exitCode:0}}};var Jn={name:"which",description:"Locate a command in PATH",category:"shell",params:["<command...>"],run:({args:r,shell:t,env:e})=>{if(r.length===0)return{stderr:"which: missing argument",exitCode:1};let n=(e?.vars?.PATH??"/usr/local/bin:/usr/bin:/bin").split(":"),i=[],s=!1;for(let o of r){let a=!1;for(let l of n){let c=`${l}/${o}`;if(t.vfs.exists(c)&&t.vfs.stat(c).type==="file"){i.push(c),a=!0;break}}a||(s=!0)}return i.length===0?{exitCode:1}:{stdout:i.join(`
215
+ `),exitCode:s?1:0}}};function ie(r){let t=r.toLocaleString("en-US",{weekday:"short"}),e=r.toLocaleString("en-US",{month:"short"}),n=r.getDate().toString().padStart(2,"0"),i=r.getHours().toString().padStart(2,"0"),s=r.getMinutes().toString().padStart(2,"0"),o=r.getSeconds().toString().padStart(2,"0"),a=r.getFullYear();return`${t} ${e} ${n} ${i}:${s}:${o} ${a}`}var Qn={name:"who",description:"Show active sessions",category:"system",params:[],run:({shell:r})=>({stdout:r.users.listActiveSessions().map(e=>{let n=new Date(e.startedAt),i=Number.isNaN(n.getTime())?e.startedAt:ie(n);return`${e.username} ${e.tty} ${i} (${e.remoteAddress||"unknown"})`}).join(`
216
+ `),exitCode:0})};var Yn={name:"whoami",description:"Print current user",category:"system",params:[],run:({authUser:r})=>({stdout:r,exitCode:0})};var Xn={name:"xargs",description:"Build and execute command lines from stdin",category:"text",params:["[command] [args...]"],run:async({authUser:r,hostname:t,mode:e,cwd:n,args:i,stdin:s,shell:o,env:a})=>{let l=i[0]??"echo",c=i.slice(1),u=(s??"").trim().split(/\s+/).filter(Boolean);if(u.length===0)return{exitCode:0};let d=[l,...c,...u].join(" ");return K(d,r,t,e,n,o,void 0,a)}};var Pi=[mn,Qe,Tr,Un,Je,zn,yn,Or,tr,Wr,Vr,Rr,Ye,_r,Dr,gr,wr,wn,Ge,An,Hn,Gn,vr,Vn,rr,Tn,_n,Xn,ar,Rn,xr,br,Ze,Yn,Qn,Ar,Nr,Sr,jn,dn,Ir,or,ur,nr,Fn,cn,mr,pr,hr,Sn,qn,$n,Xe,fr,Hr,Er,er,Zn,Te,ln,ir,In,Nn,en,qe,Ke,lr,cr,Jn,Wn,Br,Be,Oe,Dn,En,Fr,un,gn,sr,Pn,kn,Mn,Bn,On,on,an,sn,hn,Kn,yr,Ur],ts=[],Wt=new Map,oe=null,ki=Mr(()=>Fe().map(r=>r.name));function Me(){Wt.clear();for(let r of Fe()){Wt.set(r.name,r);for(let t of r.aliases??[])Wt.set(t,r)}oe=Array.from(Wt.keys()).sort()}function Fe(){return[...Pi,...ts,ki]}function Ce(r){let t={...r,name:r.name.trim().toLowerCase(),aliases:r.aliases?.map(n=>n.trim().toLowerCase())};if([t.name,...t.aliases??[]].some(n=>n.length===0||/\s/.test(n)))throw new Error("Command names must be non-empty and contain no spaces");ts.push(t),Me()}function $e(r,t,e){return{name:r,params:t,run:e}}function Bt(){return oe||Me(),oe}function Se(){return Fe()}function ut(r){return oe||Me(),Wt.get(r.toLowerCase())}import{spawn as Fi}from"node:child_process";import{readFile as Mi}from"node:fs/promises";import*as ae from"node:path";function Ae(r){return`'${r.replace(/'/g,"'\\''")}'`}function jt(r){return r.replace(/\r\n/g,`
210
217
  `).replace(/\r/g,`
211
218
  `).replace(/\n/g,`\r
212
- `)}function Zn(r,t){let e=Number.isFinite(t.cols)&&t.cols>0?Math.floor(t.cols):80,n=Number.isFinite(t.rows)&&t.rows>0?Math.floor(t.rows):24;return`stty cols ${e} rows ${n} 2>/dev/null; ${r}`}function ie(r,t){return!t||t.trim()===""||t==="."?r:t.startsWith("/")?se.posix.normalize(t):se.posix.normalize(se.posix.join(r,t))}async function Jn(r){try{let e=(await Si(`/proc/${r}/task/${r}/children`,"utf8")).trim().split(/\s+/).filter(Boolean).map(i=>Number.parseInt(i,10)).filter(i=>Number.isInteger(i)&&i>0),n=await Promise.all(e.map(i=>Jn(i)));return[...e,...n.flat()]}catch{return[]}}async function Qn(r=process.pid){let t=await Jn(r),e=Array.from(new Set(t)).sort((n,i)=>n-i);return e.length===0?null:e.join(",")}function Yn(r,t,e){let n=Zn(r,t),i=xi("script",["-qfec",n,"/dev/null"],{stdio:["pipe","pipe","pipe"],env:{...process.env,TERM:process.env.TERM??"xterm-256color"}});return i.stdout.on("data",s=>{e.write(s.toString("utf8"))}),i.stderr.on("data",s=>{e.write(s.toString("utf8"))}),i}function oe(r,t,e){return Yn(`nano -- ${ke(r)}`,t,e)}function Xn(r,t,e){return Yn(`htop -p ${ke(r)}`,t,e)}function ae(r,t,e){let n=[`Linux ${r} ${t.kernel} ${t.arch}`,"","The programs included with the Fortune GNU/Linux system are free software;","the exact distribution terms for each program are described in the","individual files in /usr/share/doc/*/copyright.","","Fortune GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent","permitted by applicable law."];if(e){let i=new Date(e.at),s=Number.isNaN(i.getTime())?e.at:re(i);n.push(`Last login: ${s} from ${e.from||"unknown"}`)}return n.push(""),`${n.map(i=>`${i}\r
213
- `).join("")}`}function le(r,t,e){let n=r==="root",i=n?"\x1B[31;1m":"\x1B[35;1m",s="\x1B[37;1m",o="\x1B[34;1m",a="\x1B[0m";return`${s}[${i}${r}${s}@${o}${t}${a} ${e}${s}]${a}${n?"#":"$"} `}import{EventEmitter as ji}from"node:events";import*as Et from"node:os";function M(r,t,e=493){r.exists(t)||r.mkdir(t,e)}function T(r,t,e,n=420){r.exists(t)||r.writeFile(t,e,{mode:n})}function bi(r,t,e){M(r,"/etc"),T(r,"/etc/os-release",`${['NAME="Fortune GNU/Linux"',`PRETTY_NAME="${e.os}"`,"ID=fortune","ID_LIKE=debian",'HOME_URL="https://github.com/itsrealfortune/typescript-virtual-container"',"VERSION_CODENAME=aurora",'VERSION_ID="1.0"'].join(`
219
+ `)}function es(r,t){let e=Number.isFinite(t.cols)&&t.cols>0?Math.floor(t.cols):80,n=Number.isFinite(t.rows)&&t.rows>0?Math.floor(t.rows):24;return`stty cols ${e} rows ${n} 2>/dev/null; ${r}`}function le(r,t){return!t||t.trim()===""||t==="."?r:t.startsWith("/")?ae.posix.normalize(t):ae.posix.normalize(ae.posix.join(r,t))}async function rs(r){try{let e=(await Mi(`/proc/${r}/task/${r}/children`,"utf8")).trim().split(/\s+/).filter(Boolean).map(i=>Number.parseInt(i,10)).filter(i=>Number.isInteger(i)&&i>0),n=await Promise.all(e.map(i=>rs(i)));return[...e,...n.flat()]}catch{return[]}}async function ns(r=process.pid){let t=await rs(r),e=Array.from(new Set(t)).sort((n,i)=>n-i);return e.length===0?null:e.join(",")}function ss(r,t,e){let n=es(r,t),i=Fi("script",["-qfec",n,"/dev/null"],{stdio:["pipe","pipe","pipe"],env:{...process.env,TERM:process.env.TERM??"xterm-256color"}});return i.stdout.on("data",s=>{e.write(s.toString("utf8"))}),i.stderr.on("data",s=>{e.write(s.toString("utf8"))}),i}function ce(r,t,e){return ss(`nano -- ${Ae(r)}`,t,e)}function is(r,t,e){return ss(`htop -p ${Ae(r)}`,t,e)}function ue(r,t,e){let n=[`Linux ${r} ${t.kernel} ${t.arch}`,"","The programs included with the Fortune GNU/Linux system are free software;","the exact distribution terms for each program are described in the","individual files in /usr/share/doc/*/copyright.","","Fortune GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent","permitted by applicable law."];if(e){let i=new Date(e.at),s=Number.isNaN(i.getTime())?e.at:ie(i);n.push(`Last login: ${s} from ${e.from||"unknown"}`)}return n.push(""),`${n.map(i=>`${i}\r
220
+ `).join("")}`}function de(r,t,e){let n=r==="root",i=n?"\x1B[31;1m":"\x1B[35;1m",s="\x1B[37;1m",o="\x1B[34;1m",a="\x1B[0m";return`${s}[${i}${r}${s}@${o}${t}${a} ${e}${s}]${a}${n?"#":"$"} `}import{EventEmitter as Yi}from"node:events";import*as Nt from"node:os";function F(r,t,e=493){r.exists(t)||r.mkdir(t,e)}function U(r,t,e,n=420){r.exists(t)||r.writeFile(t,e,{mode:n})}function Ai(r,t,e){F(r,"/etc"),U(r,"/etc/os-release",`${['NAME="Fortune GNU/Linux"',`PRETTY_NAME="${e.os}"`,"ID=fortune","ID_LIKE=debian",'HOME_URL="https://github.com/itsrealfortune/typescript-virtual-container"',"VERSION_CODENAME=aurora",'VERSION_ID="1.0"'].join(`
214
221
  `)}
215
- `),T(r,"/etc/debian_version",`12.0
216
- `),T(r,"/etc/hostname",`${t}
217
- `),T(r,"/etc/shells",`/bin/sh
222
+ `),U(r,"/etc/debian_version",`12.0
223
+ `),U(r,"/etc/hostname",`${t}
224
+ `),U(r,"/etc/shells",`/bin/sh
218
225
  /bin/bash
219
226
  /usr/bin/bash
220
- `),T(r,"/etc/profile",`${["export PATH=/usr/local/bin:/usr/bin:/bin","export PS1='\\u@\\h:\\w\\$ '"].join(`
227
+ `),U(r,"/etc/profile",`${["export PATH=/usr/local/bin:/usr/bin:/bin","export PS1='\\u@\\h:\\w\\$ '"].join(`
221
228
  `)}
222
- `),T(r,"/etc/issue",`Fortune GNU/Linux 1.0 \\n \\l
223
- `),T(r,"/etc/motd",["",`Welcome to ${e.os}`,`Kernel: ${e.kernel}`,""].join(`
224
- `)),M(r,"/etc/apt"),M(r,"/etc/apt/sources.list.d"),T(r,"/etc/apt/sources.list",`${["# Fortune GNU/Linux package sources","deb [virtual] fortune://packages.fortune.local aurora main contrib","deb [virtual] fortune://security.fortune.local aurora-security main"].join(`
229
+ `),U(r,"/etc/issue",`Fortune GNU/Linux 1.0 \\n \\l
230
+ `),U(r,"/etc/motd",["",`Welcome to ${e.os}`,`Kernel: ${e.kernel}`,""].join(`
231
+ `)),F(r,"/etc/apt"),F(r,"/etc/apt/sources.list.d"),U(r,"/etc/apt/sources.list",`${["# Fortune GNU/Linux package sources","deb [virtual] fortune://packages.fortune.local aurora main contrib","deb [virtual] fortune://security.fortune.local aurora-security main"].join(`
225
232
  `)}
226
- `),M(r,"/etc/network"),T(r,"/etc/network/interfaces",`${["auto lo","iface lo inet loopback","","auto eth0","iface eth0 inet dhcp"].join(`
233
+ `),F(r,"/etc/network"),U(r,"/etc/network/interfaces",`${["auto lo","iface lo inet loopback","","auto eth0","iface eth0 inet dhcp"].join(`
227
234
  `)}
228
- `),T(r,"/etc/resolv.conf",`nameserver 1.1.1.1
235
+ `),U(r,"/etc/resolv.conf",`nameserver 1.1.1.1
229
236
  nameserver 8.8.8.8
230
- `),T(r,"/etc/hosts",`${["127.0.0.1 localhost",`127.0.1.1 ${t}`,"::1 localhost ip6-localhost ip6-loopback"].join(`
237
+ `),U(r,"/etc/hosts",`${["127.0.0.1 localhost",`127.0.1.1 ${t}`,"::1 localhost ip6-localhost ip6-loopback"].join(`
231
238
  `)}
232
- `),M(r,"/etc/cron.d"),M(r,"/etc/init.d"),M(r,"/etc/systemd"),M(r,"/etc/systemd/system")}function Me(r,t){let e=t.listUsers(),n=["root:x:0:0:root:/root:/bin/bash","daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin","www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin","nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin"],i=1e3;for(let a of e)a!=="root"&&(n.push(`${a}:x:${i}:${i}::/home/${a}:/bin/bash`),i++);r.writeFile("/etc/passwd",`${n.join(`
239
+ `),F(r,"/etc/cron.d"),F(r,"/etc/init.d"),F(r,"/etc/systemd"),F(r,"/etc/systemd/system")}function Ee(r,t){let e=t.listUsers(),n=["root:x:0:0:root:/root:/bin/bash","daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin","www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin","nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin"],i=1e3;for(let a of e)a!=="root"&&(n.push(`${a}:x:${i}:${i}::/home/${a}:/bin/bash`),i++);r.writeFile("/etc/passwd",`${n.join(`
233
240
  `)}
234
241
  `);let s=["root:x:0:","daemon:x:1:",`sudo:x:27:${e.filter(a=>t.isSudoer(a)).join(",")}`,`users:x:100:${e.filter(a=>a!=="root").join(",")}`,"nogroup:x:65534:"];r.writeFile("/etc/group",`${s.join(`
235
242
  `)}
236
243
  `);let o=["root:*:19000:0:99999:7:::","daemon:*:19000:0:99999:7:::"];for(let a of e)a!=="root"&&o.push(`${a}:!:19000:0:99999:7:::`);r.writeFile("/etc/shadow",`${o.join(`
237
244
  `)}
238
- `,{mode:416})}function ts(r){let t=r.match(/(\d+)$/);return 1e3+(t?.[1]?parseInt(t[1],10):0)}function es(r,t,e,n,i,s,o){let a=`/proc/${t}`;M(r,a),M(r,`${a}/fd`),M(r,`${a}/fdinfo`);let l=Math.floor((Date.now()-new Date(s).getTime())/1e3);r.writeFile(`${a}/cmdline`,`${i.replace(/\s+/g,"\0")}\0`),r.writeFile(`${a}/comm`,i.split(/\s+/)[0]??"bash"),r.writeFile(`${a}/status`,`${[`Name: ${i.split(/\s+/)[0]??"bash"}`,"State: S (sleeping)",`Pid: ${t}`,"PPid: 1","Uid: 0 0 0 0","Gid: 0 0 0 0","VmRSS: 4096 kB","VmSize: 16384 kB","Threads: 1"].join(`
245
+ `,{mode:416})}function os(r){let t=r.match(/(\d+)$/);return 1e3+(t?.[1]?parseInt(t[1],10):0)}function as(r,t,e,n,i,s,o){let a=`/proc/${t}`;F(r,a),F(r,`${a}/fd`),F(r,`${a}/fdinfo`);let l=Math.floor((Date.now()-new Date(s).getTime())/1e3);r.writeFile(`${a}/cmdline`,`${i.replace(/\s+/g,"\0")}\0`),r.writeFile(`${a}/comm`,i.split(/\s+/)[0]??"bash"),r.writeFile(`${a}/status`,`${[`Name: ${i.split(/\s+/)[0]??"bash"}`,"State: S (sleeping)",`Pid: ${t}`,"PPid: 1","Uid: 0 0 0 0","Gid: 0 0 0 0","VmRSS: 4096 kB","VmSize: 16384 kB","Threads: 1"].join(`
239
246
  `)}
240
247
  `),r.writeFile(`${a}/stat`,`${t} (${i.split(/\s+/)[0]??"bash"}) S 1 ${t} ${t} 0 -1 4194304 0 0 0 0 ${l} 0 0 0 20 0 1 0 0 16384 4096 0
241
- `),r.writeFile(`${a}/environ`,`${Object.entries(o).map(([c,u])=>`${c}=${u}`).join("\0")}\0`),r.writeFile(`${a}/cwd`,`/home/${e}\0`),r.writeFile(`${a}/exe`,"/bin/bash\0"),r.writeFile(`${a}/fd/0`,""),r.writeFile(`${a}/fd/1`,""),r.writeFile(`${a}/fd/2`,"")}function ce(r,t,e,n,i){M(r,"/proc");let s=Math.floor((Date.now()-n)/1e3);r.writeFile("/proc/uptime",`${s}.00 ${Math.floor(s*.9)}.00
242
- `);let o=Math.floor(Et.totalmem()/1024),a=Math.floor(Et.freemem()/1024),l=Math.floor(a*.95);r.writeFile("/proc/meminfo",`${[`MemTotal: ${String(o).padStart(10)} kB`,`MemFree: ${String(a).padStart(10)} kB`,`MemAvailable: ${String(l).padStart(10)} kB`,`Buffers: ${String(Math.floor(o*.02)).padStart(10)} kB`,`Cached: ${String(Math.floor(o*.15)).padStart(10)} kB`,`SwapTotal: ${String(Math.floor(o*.5)).padStart(10)} kB`,`SwapFree: ${String(Math.floor(o*.5)).padStart(10)} kB`].join(`
248
+ `),r.writeFile(`${a}/environ`,`${Object.entries(o).map(([c,u])=>`${c}=${u}`).join("\0")}\0`),r.writeFile(`${a}/cwd`,`/home/${e}\0`),r.writeFile(`${a}/exe`,"/bin/bash\0"),r.writeFile(`${a}/fd/0`,""),r.writeFile(`${a}/fd/1`,""),r.writeFile(`${a}/fd/2`,"")}function me(r,t,e,n,i){F(r,"/proc");let s=Math.floor((Date.now()-n)/1e3);r.writeFile("/proc/uptime",`${s}.00 ${Math.floor(s*.9)}.00
249
+ `);let o=Math.floor(Nt.totalmem()/1024),a=Math.floor(Nt.freemem()/1024),l=Math.floor(a*.95);r.writeFile("/proc/meminfo",`${[`MemTotal: ${String(o).padStart(10)} kB`,`MemFree: ${String(a).padStart(10)} kB`,`MemAvailable: ${String(l).padStart(10)} kB`,`Buffers: ${String(Math.floor(o*.02)).padStart(10)} kB`,`Cached: ${String(Math.floor(o*.15)).padStart(10)} kB`,`SwapTotal: ${String(Math.floor(o*.5)).padStart(10)} kB`,`SwapFree: ${String(Math.floor(o*.5)).padStart(10)} kB`].join(`
243
250
  `)}
244
- `);let c=Et.cpus(),u=[];for(let f=0;f<c.length;f++){let $=c[f];if(!$)continue;let E=$.speed.toFixed(3);u.push(`processor : ${f}`,`model name : ${$.model}`,`cpu MHz : ${E}`,"cache size : 8192 KB","")}r.writeFile("/proc/cpuinfo",`${u.join(`
251
+ `);let c=Nt.cpus(),u=[];for(let f=0;f<c.length;f++){let $=c[f];if(!$)continue;let N=$.speed.toFixed(3);u.push(`processor : ${f}`,`model name : ${$.model}`,`cpu MHz : ${N}`,"cache size : 8192 KB","")}r.writeFile("/proc/cpuinfo",`${u.join(`
245
252
  `)}
246
253
  `),r.writeFile("/proc/version",`Linux version ${t.kernel} (fortune@build) (gcc version 12.2.0) #1 SMP
247
254
  `),r.writeFile("/proc/hostname",`${e}
248
255
  `);let d=(Math.random()*.5).toFixed(2),m=1+(i?.length??0);r.writeFile("/proc/loadavg",`${d} ${d} ${d} ${m}/${m} 1
249
- `),M(r,"/proc/net"),T(r,"/proc/net/dev",`${["Inter-| Receive | Transmit"," face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed"," lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"," eth0: 131072 1024 0 0 0 0 0 0 65536 512 0 0 0 0 0 0"].join(`
256
+ `),F(r,"/proc/net"),U(r,"/proc/net/dev",`${["Inter-| Receive | Transmit"," face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed"," lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"," eth0: 131072 1024 0 0 0 0 0 0 65536 512 0 0 0 0 0 0"].join(`
250
257
  `)}
251
- `),es(r,1,"root","pts/0","/sbin/init",new Date(n).toISOString(),{});let p=i??[];for(let f of p){let $=ts(f.tty);es(r,$,f.username,f.tty,"bash",f.startedAt,{USER:f.username,HOME:`/home/${f.username}`,TERM:"xterm-256color",SHELL:"/bin/bash"})}let w=p.length>0?ts(p[p.length-1].tty):1;if(r.exists("/proc/self"))try{r.remove("/proc/self")}catch{}let g=`/proc/${w}`;if(r.exists(g)){M(r,"/proc/self"),M(r,"/proc/self/fd");for(let f of r.list(g)){let $=`${g}/${f}`,E=`/proc/self/${f}`;try{r.stat($).type==="file"&&r.writeFile(E,r.readFile($))}catch{}}r.writeFile("/proc/self/status",r.exists(`${g}/status`)?r.readFile(`${g}/status`):"")}else M(r,"/proc/self"),r.writeFile("/proc/self/cmdline","bash\0"),r.writeFile("/proc/self/comm","bash"),r.writeFile("/proc/self/status",`Name: bash
258
+ `),as(r,1,"root","pts/0","/sbin/init",new Date(n).toISOString(),{});let p=i??[];for(let f of p){let $=os(f.tty);as(r,$,f.username,f.tty,"bash",f.startedAt,{USER:f.username,HOME:`/home/${f.username}`,TERM:"xterm-256color",SHELL:"/bin/bash"})}let y=p.length>0?os(p[p.length-1].tty):1;if(r.exists("/proc/self"))try{r.remove("/proc/self")}catch{}let g=`/proc/${y}`;if(r.exists(g)){F(r,"/proc/self"),F(r,"/proc/self/fd");for(let f of r.list(g)){let $=`${g}/${f}`,N=`/proc/self/${f}`;try{r.stat($).type==="file"&&r.writeFile(N,r.readFile($))}catch{}}r.writeFile("/proc/self/status",r.exists(`${g}/status`)?r.readFile(`${g}/status`):"")}else F(r,"/proc/self"),r.writeFile("/proc/self/cmdline","bash\0"),r.writeFile("/proc/self/comm","bash"),r.writeFile("/proc/self/status",`Name: bash
252
259
  State: S (sleeping)
253
260
  Pid: 1
254
261
  PPid: 0
255
- `),r.writeFile("/proc/self/environ",""),r.writeFile("/proc/self/cwd","/root\0"),r.writeFile("/proc/self/exe","/bin/bash\0")}function Ci(r,t){M(r,"/sys"),M(r,"/sys/devices"),M(r,"/sys/devices/virtual"),M(r,"/sys/devices/virtual/dmi"),M(r,"/sys/devices/virtual/dmi/id"),T(r,"/sys/devices/virtual/dmi/id/sys_vendor",`Fortune Systems
256
- `),T(r,"/sys/devices/virtual/dmi/id/product_name",`VirtualContainer v1
257
- `),T(r,"/sys/devices/virtual/dmi/id/board_name",`fortune-board
258
- `),M(r,"/sys/class"),M(r,"/sys/class/net"),M(r,"/sys/kernel"),T(r,"/sys/kernel/hostname",`fortune-vm
259
- `),T(r,"/sys/kernel/osrelease",`${t.kernel}
260
- `),T(r,"/sys/kernel/ostype",`Linux
261
- `)}function vi(r){M(r,"/dev"),T(r,"/dev/null","",438),T(r,"/dev/zero","",438),T(r,"/dev/random","",292),T(r,"/dev/urandom","",292),M(r,"/dev/pts"),M(r,"/dev/shm")}function $i(r){M(r,"/usr"),M(r,"/usr/bin"),M(r,"/usr/sbin"),M(r,"/usr/local"),M(r,"/usr/local/bin"),M(r,"/usr/local/lib"),M(r,"/usr/local/share"),M(r,"/usr/share"),M(r,"/usr/share/doc"),M(r,"/usr/share/man"),M(r,"/usr/share/man/man1"),M(r,"/usr/lib");let t=["sh","bash","ls","cat","echo","grep","find","sort","head","tail","cut","tr","sed","awk","wc","tee","tar","gzip","gunzip","touch","mkdir","rm","mv","cp","chmod","ln","pwd","env","date","sleep","id","whoami","hostname","uname","ps","kill","df","du","curl","wget","nano","diff","uniq","xargs","base64"];for(let e of t)T(r,`/usr/bin/${e}`,`#!/bin/sh
262
+ `),r.writeFile("/proc/self/environ",""),r.writeFile("/proc/self/cwd","/root\0"),r.writeFile("/proc/self/exe","/bin/bash\0")}function Ei(r,t){F(r,"/sys"),F(r,"/sys/devices"),F(r,"/sys/devices/virtual"),F(r,"/sys/devices/virtual/dmi"),F(r,"/sys/devices/virtual/dmi/id"),U(r,"/sys/devices/virtual/dmi/id/sys_vendor",`Fortune Systems
263
+ `),U(r,"/sys/devices/virtual/dmi/id/product_name",`VirtualContainer v1
264
+ `),U(r,"/sys/devices/virtual/dmi/id/board_name",`fortune-board
265
+ `),F(r,"/sys/class"),F(r,"/sys/class/net"),F(r,"/sys/kernel"),U(r,"/sys/kernel/hostname",`fortune-vm
266
+ `),U(r,"/sys/kernel/osrelease",`${t.kernel}
267
+ `),U(r,"/sys/kernel/ostype",`Linux
268
+ `)}function Ni(r){F(r,"/dev"),U(r,"/dev/null","",438),U(r,"/dev/zero","",438),U(r,"/dev/random","",292),U(r,"/dev/urandom","",292),F(r,"/dev/pts"),F(r,"/dev/shm")}function Ii(r){F(r,"/usr"),F(r,"/usr/bin"),F(r,"/usr/sbin"),F(r,"/usr/local"),F(r,"/usr/local/bin"),F(r,"/usr/local/lib"),F(r,"/usr/local/share"),F(r,"/usr/share"),F(r,"/usr/share/doc"),F(r,"/usr/share/man"),F(r,"/usr/share/man/man1"),F(r,"/usr/lib");let t=["sh","bash","ls","cat","echo","grep","find","sort","head","tail","cut","tr","sed","awk","wc","tee","tar","gzip","gunzip","touch","mkdir","rm","mv","cp","chmod","ln","pwd","env","date","sleep","id","whoami","hostname","uname","ps","kill","df","du","curl","wget","nano","diff","uniq","xargs","base64"];for(let e of t)U(r,`/usr/bin/${e}`,`#!/bin/sh
262
269
  exec builtin ${e} "$@"
263
- `,493);T(r,"/usr/bin/lsb_release",`#!/bin/sh
270
+ `,493);U(r,"/usr/bin/lsb_release",`#!/bin/sh
264
271
  exec lsb_release "$@"
265
- `,493)}function Pi(r){M(r,"/var"),M(r,"/var/log"),M(r,"/var/tmp"),M(r,"/var/run"),M(r,"/var/cache"),M(r,"/var/cache/apt"),M(r,"/var/cache/apt/archives"),M(r,"/var/lib"),M(r,"/var/lib/apt"),M(r,"/var/lib/apt/lists"),M(r,"/var/lib/dpkg"),M(r,"/var/lib/dpkg/info"),T(r,"/var/lib/dpkg/status",""),T(r,"/var/lib/dpkg/available",""),T(r,"/var/log/syslog",`${new Date().toUTCString()} fortune kernel: Virtual container started
266
- `),T(r,"/var/log/auth.log",""),T(r,"/var/log/dpkg.log",""),T(r,"/var/log/apt/history.log",""),T(r,"/var/log/apt/term.log","")}function ki(r){r.exists("/bin")||r.symlink("/usr/bin","/bin"),r.exists("/sbin")||r.symlink("/usr/sbin","/sbin"),r.exists("/lib")||M(r,"/lib"),r.exists("/lib64")||M(r,"/lib64")}function Mi(r){M(r,"/tmp",1023)}function Fi(r){M(r,"/root",448),T(r,"/home/root/.bashrc",`${["# root .bashrc","export PS1='\\[\\033[0;31m\\]\\u@\\h\\[\\033[0m\\]:\\[\\033[0;34m\\]\\w\\[\\033[0m\\]# '","export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","alias ll='ls -la'","alias la='ls -A'"].join(`
272
+ `,493)}function Vi(r){F(r,"/var"),F(r,"/var/log"),F(r,"/var/tmp"),F(r,"/var/run"),F(r,"/var/cache"),F(r,"/var/cache/apt"),F(r,"/var/cache/apt/archives"),F(r,"/var/lib"),F(r,"/var/lib/apt"),F(r,"/var/lib/apt/lists"),F(r,"/var/lib/dpkg"),F(r,"/var/lib/dpkg/info"),U(r,"/var/lib/dpkg/status",""),U(r,"/var/lib/dpkg/available",""),U(r,"/var/log/syslog",`${new Date().toUTCString()} fortune kernel: Virtual container started
273
+ `),U(r,"/var/log/auth.log",""),U(r,"/var/log/dpkg.log",""),U(r,"/var/log/apt/history.log",""),U(r,"/var/log/apt/term.log","")}function Ri(r){r.exists("/bin")||r.symlink("/usr/bin","/bin"),r.exists("/sbin")||r.symlink("/usr/sbin","/sbin"),r.exists("/lib")||F(r,"/lib"),r.exists("/lib64")||F(r,"/lib64")}function _i(r){F(r,"/tmp",1023)}function Di(r){F(r,"/root",448),U(r,"/home/root/.bashrc",`${["# root .bashrc","export PS1='\\[\\033[0;31m\\]\\u@\\h\\[\\033[0m\\]:\\[\\033[0;34m\\]\\w\\[\\033[0m\\]# '","export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","alias ll='ls -la'","alias la='ls -A'"].join(`
267
274
  `)}
268
- `),T(r,"/home/root/.profile",`[ -f ~/.bashrc ] && . ~/.bashrc
269
- `)}function Ai(r){M(r,"/opt"),M(r,"/srv"),M(r,"/mnt"),M(r,"/media")}function rs(r,t,e,n,i){bi(r,e,n),Ci(r,n),vi(r),$i(r),Pi(r),ki(r),Mi(r),Fi(r),Ai(r),ce(r,n,e,i,[]),Me(r,t)}function ns(r){return r==="1"||r==="true"}function ss(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ei(){return ns(process.env.DEV_MODE)||ns(process.env.RENDER_PERF)}function ue(r){let t=Ei();if(!t)return{enabled:t,mark:()=>{},done:()=>{}};let e=ss(),n=s=>{let o=ss()-e;console.log(`[perf][${r}] ${s}: ${o.toFixed(1)}ms`)};return{enabled:t,mark:n,done:(s="done")=>{n(s)}}}import{EventEmitter as Vi}from"node:events";import*as xt from"node:fs";import*as ht from"node:path";import{gunzipSync as Ne,gzipSync as ms}from"node:zlib";var Ee=Buffer.from([86,70,83,33]),Ni=1,is=1,os=2,Fe=class{chunks=[];write(t){this.chunks.push(t)}writeUint8(t){let e=Buffer.allocUnsafe(1);e.writeUInt8(t,0),this.chunks.push(e)}writeUint16(t){let e=Buffer.allocUnsafe(2);e.writeUInt16LE(t,0),this.chunks.push(e)}writeUint32(t){let e=Buffer.allocUnsafe(4);e.writeUInt32LE(t,0),this.chunks.push(e)}writeFloat64(t){let e=Buffer.allocUnsafe(8);e.writeDoubleBE(t,0),this.chunks.push(e)}writeString(t){let e=Buffer.from(t,"utf8");this.writeUint16(e.length),this.chunks.push(e)}writeBytes(t){this.writeUint32(t.length),this.chunks.push(t)}toBuffer(){return Buffer.concat(this.chunks)}};function as(r,t){if(t.type==="file"){let e=t;r.writeUint8(is),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime()),r.writeUint8(e.compressed?1:0),r.writeBytes(e.content)}else{let e=t;r.writeUint8(os),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime());let n=Array.from(e.children.values());r.writeUint32(n.length);for(let i of n)as(r,i)}}function ls(r){let t=new Fe;return t.write(Ee),t.writeUint8(Ni),as(t,r),t.toBuffer()}var Ae=class{constructor(t){this.buf=t}buf;pos=0;readUint8(){return this.buf.readUInt8(this.pos++)}readUint16(){let t=this.buf.readUInt16LE(this.pos);return this.pos+=2,t}readUint32(){let t=this.buf.readUInt32LE(this.pos);return this.pos+=4,t}readFloat64(){let t=this.buf.readDoubleBE(this.pos);return this.pos+=8,t}readString(){let t=this.readUint16(),e=this.buf.toString("utf8",this.pos,this.pos+t);return this.pos+=t,e}readBytes(){let t=this.readUint32(),e=this.buf.slice(this.pos,this.pos+t);return this.pos+=t,e}remaining(){return this.buf.length-this.pos}};function cs(r){let t=r.readUint8(),e=r.readString(),n=r.readUint32(),i=new Date(r.readFloat64()),s=new Date(r.readFloat64());if(t===is){let o=r.readUint8()===1,a=r.readBytes();return{type:"file",name:e,mode:n,createdAt:i,updatedAt:s,compressed:o,content:a}}if(t===os){let o=r.readUint32(),a=new Map;for(let l=0;l<o;l++){let c=cs(r);a.set(c.name,c)}return{type:"directory",name:e,mode:n,createdAt:i,updatedAt:s,children:a}}throw new Error(`[VFS binary] Unknown node type: 0x${t.toString(16)}`)}function us(r){if(r.length<5)throw new Error("[VFS binary] Buffer too short");if(!r.slice(0,4).equals(Ee))throw new Error("[VFS binary] Invalid magic \u2014 not a VFS binary snapshot");let e=new Ae(r);for(let i=0;i<5;i++)e.readUint8();let n=cs(e);if(n.type!=="directory")throw new Error("[VFS binary] Root node must be a directory");return n}function ds(r){return r.length>=4&&r.slice(0,4).equals(Ee)}import*as de from"node:path";function q(r){if(!r||r.trim()==="")return"/";let t=de.posix.normalize(r.startsWith("/")?r:`/${r}`);return t===""?"/":t}function Ii(r){return r.split("/").filter(Boolean)}function et(r,t){let e=q(t);if(e==="/")return r;let n=Ii(e),i=r;for(let s of n){if(i.type!=="directory")throw new Error(`Path '${e}' does not exist.`);let o=i.children.get(s);if(!o)throw new Error(`Path '${e}' does not exist.`);i=o}return i}function Nt(r,t,e,n){let i=q(t);if(i==="/")throw new Error("Root path has no parent directory.");let s=de.posix.dirname(i),o=de.posix.basename(i);if(!o)throw new Error(`Invalid path '${t}'.`);e&&n(s);let a=et(r,s);if(a.type!=="directory")throw new Error(`Parent path '${s}' is not a directory.`);return{parent:a,name:o}}var Ie=class r extends Vi{root;mode;snapshotFile;constructor(t={}){if(super(),this.mode=t.mode??"memory",this.mode==="fs"){if(!t.snapshotPath)throw new Error('VirtualFileSystem: "snapshotPath" is required when mode is "fs".');this.snapshotFile=ht.resolve(t.snapshotPath,"vfs-snapshot.vfsb")}else this.snapshotFile=null;this.root=this.makeDir("",493)}makeDir(t,e){let n=new Date;return{type:"directory",name:t,mode:e,createdAt:n,updatedAt:n,children:new Map}}makeFile(t,e,n,i){let s=new Date;return{type:"file",name:t,content:e,mode:n,compressed:i,createdAt:s,updatedAt:s}}mkdirRecursive(t,e){let n=q(t);if(n==="/")return;let i=n.split("/").filter(Boolean),s=this.root,o="";for(let a of i){o+=`/${a}`;let l=s.children.get(a);if(!l)l=this.makeDir(a,e),s.children.set(a,l),this.emit("dir:create",{path:o,mode:e});else if(l.type!=="directory")throw new Error(`Cannot create directory '${o}': path is a file.`);s=l}}async restoreMirror(){if(!(this.mode!=="fs"||!this.snapshotFile)&&xt.existsSync(this.snapshotFile))try{let t=xt.readFileSync(this.snapshotFile);if(ds(t))this.root=us(t);else{let e=JSON.parse(t.toString("utf8"));this.root=this.deserializeDir(e.root,""),console.info("[VirtualFileSystem] Migrating legacy JSON snapshot to binary format.")}this.emit("snapshot:restore",{path:this.snapshotFile})}catch(t){console.warn(`[VirtualFileSystem] Could not restore snapshot from ${this.snapshotFile}:`,t instanceof Error?t.message:String(t))}}async flushMirror(){if(this.mode!=="fs"||!this.snapshotFile){this.emit("mirror:flush");return}let t=ht.dirname(this.snapshotFile);xt.mkdirSync(t,{recursive:!0});let e=ls(this.root);xt.writeFileSync(this.snapshotFile,e),this.emit("mirror:flush",{path:this.snapshotFile})}getMode(){return this.mode}getSnapshotPath(){return this.snapshotFile}mkdir(t,e=493){let n=q(t),i=(()=>{try{return et(this.root,n)}catch{return null}})();if(i&&i.type!=="directory")throw new Error(`Cannot create directory '${n}': path is a file.`);this.mkdirRecursive(n,e)}writeFile(t,e,n={}){let i=q(t),{parent:s,name:o}=Nt(this.root,i,!0,m=>this.mkdirRecursive(m,493)),a=s.children.get(o);if(a?.type==="directory")throw new Error(`Cannot write file '${i}': path is a directory.`);let l=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),c=n.compress??!1,u=c?ms(l):l,d=n.mode??420;if(a){let m=a;m.content=u,m.compressed=c,m.mode=d,m.updatedAt=new Date}else s.children.set(o,this.makeFile(o,u,d,c));this.emit("file:write",{path:i,size:u.length})}readFile(t){let e=q(t),n=et(this.root,e);if(n.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let i=n,s=i.compressed?Ne(i.content):i.content;return this.emit("file:read",{path:e,size:s.length}),s.toString("utf8")}readFileRaw(t){let e=q(t),n=et(this.root,e);if(n.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let i=n,s=i.compressed?Ne(i.content):i.content;return this.emit("file:read",{path:e,size:s.length}),s}exists(t){try{return et(this.root,q(t)),!0}catch{return!1}}chmod(t,e){et(this.root,q(t)).mode=e}stat(t){let e=q(t),n=et(this.root,e),i=e==="/"?"":ht.posix.basename(e);if(n.type==="file"){let o=n;return{type:"file",name:i,path:e,mode:o.mode,createdAt:o.createdAt,updatedAt:o.updatedAt,compressed:o.compressed,size:o.content.length}}let s=n;return{type:"directory",name:i,path:e,mode:s.mode,createdAt:s.createdAt,updatedAt:s.updatedAt,childrenCount:s.children.size}}list(t="/"){let e=q(t),n=et(this.root,e);if(n.type!=="directory")throw new Error(`Cannot list '${t}': not a directory.`);return Array.from(n.children.keys()).sort()}tree(t="/"){let e=q(t),n=et(this.root,e);if(n.type!=="directory")throw new Error(`Cannot render tree for '${t}': not a directory.`);let i=t==="/"?"/":ht.posix.basename(e);return this.renderTreeLines(n,i)}renderTreeLines(t,e){let n=[e],i=Array.from(t.children.keys()).sort();for(let s=0;s<i.length;s++){let o=i[s],a=t.children.get(o),l=s===i.length-1,c=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=l?" ":"\u2502 ";if(n.push(`${c}${o}`),a.type==="directory"){let d=this.renderTreeLines(a,"").split(`
275
+ `),U(r,"/home/root/.profile",`[ -f ~/.bashrc ] && . ~/.bashrc
276
+ `)}function zi(r){F(r,"/opt"),F(r,"/srv"),F(r,"/mnt"),F(r,"/media")}function ls(r,t,e,n,i){Ai(r,e,n),Ei(r,n),Ni(r),Ii(r),Vi(r),Ri(r),_i(r),Di(r),zi(r),me(r,n,e,i,[]),Ee(r,t)}function cs(r){return r==="1"||r==="true"}function us(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Li(){return cs(process.env.DEV_MODE)||cs(process.env.RENDER_PERF)}function pe(r){let t=Li();if(!t)return{enabled:t,mark:()=>{},done:()=>{}};let e=us(),n=s=>{let o=us()-e;console.log(`[perf][${r}] ${s}: ${o.toFixed(1)}ms`)};return{enabled:t,mark:n,done:(s="done")=>{n(s)}}}import{EventEmitter as Bi}from"node:events";import*as B from"node:fs";import*as ot from"node:path";import{gunzipSync as Re,gzipSync as ws}from"node:zlib";var Ve=Buffer.from([86,70,83,33]),Ti=1,ds=1,ms=2,Ne=class{chunks=[];write(t){this.chunks.push(t)}writeUint8(t){let e=Buffer.allocUnsafe(1);e.writeUInt8(t,0),this.chunks.push(e)}writeUint16(t){let e=Buffer.allocUnsafe(2);e.writeUInt16LE(t,0),this.chunks.push(e)}writeUint32(t){let e=Buffer.allocUnsafe(4);e.writeUInt32LE(t,0),this.chunks.push(e)}writeFloat64(t){let e=Buffer.allocUnsafe(8);e.writeDoubleBE(t,0),this.chunks.push(e)}writeString(t){let e=Buffer.from(t,"utf8");this.writeUint16(e.length),this.chunks.push(e)}writeBytes(t){this.writeUint32(t.length),this.chunks.push(t)}toBuffer(){return Buffer.concat(this.chunks)}};function ps(r,t){if(t.type==="file"){let e=t;r.writeUint8(ds),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime()),r.writeUint8(e.compressed?1:0),r.writeBytes(e.content)}else{let e=t;r.writeUint8(ms),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime());let n=Array.from(e.children.values());r.writeUint32(n.length);for(let i of n)ps(r,i)}}function fs(r){let t=new Ne;return t.write(Ve),t.writeUint8(Ti),ps(t,r),t.toBuffer()}var Ie=class{constructor(t){this.buf=t}buf;pos=0;readUint8(){return this.buf.readUInt8(this.pos++)}readUint16(){let t=this.buf.readUInt16LE(this.pos);return this.pos+=2,t}readUint32(){let t=this.buf.readUInt32LE(this.pos);return this.pos+=4,t}readFloat64(){let t=this.buf.readDoubleBE(this.pos);return this.pos+=8,t}readString(){let t=this.readUint16(),e=this.buf.toString("utf8",this.pos,this.pos+t);return this.pos+=t,e}readBytes(){let t=this.readUint32(),e=this.buf.slice(this.pos,this.pos+t);return this.pos+=t,e}remaining(){return this.buf.length-this.pos}};function hs(r){let t=r.readUint8(),e=r.readString(),n=r.readUint32(),i=new Date(r.readFloat64()),s=new Date(r.readFloat64());if(t===ds){let o=r.readUint8()===1,a=r.readBytes();return{type:"file",name:e,mode:n,createdAt:i,updatedAt:s,compressed:o,content:a}}if(t===ms){let o=r.readUint32(),a=new Map;for(let l=0;l<o;l++){let c=hs(r);a.set(c.name,c)}return{type:"directory",name:e,mode:n,createdAt:i,updatedAt:s,children:a}}throw new Error(`[VFS binary] Unknown node type: 0x${t.toString(16)}`)}function gs(r){if(r.length<5)throw new Error("[VFS binary] Buffer too short");if(!r.slice(0,4).equals(Ve))throw new Error("[VFS binary] Invalid magic \u2014 not a VFS binary snapshot");let e=new Ie(r);for(let i=0;i<5;i++)e.readUint8();let n=hs(e);if(n.type!=="directory")throw new Error("[VFS binary] Root node must be a directory");return n}function ys(r){return r.length>=4&&r.slice(0,4).equals(Ve)}import*as fe from"node:path";function O(r){if(!r||r.trim()==="")return"/";let t=fe.posix.normalize(r.startsWith("/")?r:`/${r}`);return t===""?"/":t}function Ui(r){return r.split("/").filter(Boolean)}function rt(r,t){let e=O(t);if(e==="/")return r;let n=Ui(e),i=r;for(let s of n){if(i.type!=="directory")throw new Error(`Path '${e}' does not exist.`);let o=i.children.get(s);if(!o)throw new Error(`Path '${e}' does not exist.`);i=o}return i}function It(r,t,e,n){let i=O(t);if(i==="/")throw new Error("Root path has no parent directory.");let s=fe.posix.dirname(i),o=fe.posix.basename(i);if(!o)throw new Error(`Invalid path '${t}'.`);e&&n(s);let a=rt(r,s);if(a.type!=="directory")throw new Error(`Parent path '${s}' is not a directory.`);return{parent:a,name:o}}var _e=class r extends Bi{root;mode;snapshotFile;mounts=new Map;static isBrowser=typeof process>"u"||typeof process.versions?.node>"u";constructor(t={}){if(super(),this.mode=t.mode??"memory",this.mode==="fs"){if(!t.snapshotPath)throw new Error('VirtualFileSystem: "snapshotPath" is required when mode is "fs".');this.snapshotFile=ot.resolve(t.snapshotPath,"vfs-snapshot.vfsb")}else this.snapshotFile=null;this.root=this.makeDir("",493)}makeDir(t,e){let n=new Date;return{type:"directory",name:t,mode:e,createdAt:n,updatedAt:n,children:new Map}}makeFile(t,e,n,i){let s=new Date;return{type:"file",name:t,content:e,mode:n,compressed:i,createdAt:s,updatedAt:s}}mkdirRecursive(t,e){let n=O(t);if(n==="/")return;let i=n.split("/").filter(Boolean),s=this.root,o="";for(let a of i){o+=`/${a}`;let l=s.children.get(a);if(!l)l=this.makeDir(a,e),s.children.set(a,l),this.emit("dir:create",{path:o,mode:e});else if(l.type!=="directory")throw new Error(`Cannot create directory '${o}': path is a file.`);s=l}}async restoreMirror(){if(!(this.mode!=="fs"||!this.snapshotFile)&&B.existsSync(this.snapshotFile))try{let t=B.readFileSync(this.snapshotFile);if(ys(t))this.root=gs(t);else{let e=JSON.parse(t.toString("utf8"));this.root=this.deserializeDir(e.root,""),console.info("[VirtualFileSystem] Migrating legacy JSON snapshot to binary format.")}this.emit("snapshot:restore",{path:this.snapshotFile})}catch(t){console.warn(`[VirtualFileSystem] Could not restore snapshot from ${this.snapshotFile}:`,t instanceof Error?t.message:String(t))}}async flushMirror(){if(this.mode!=="fs"||!this.snapshotFile){this.emit("mirror:flush");return}let t=ot.dirname(this.snapshotFile);B.mkdirSync(t,{recursive:!0});let e=fs(this.root);B.writeFileSync(this.snapshotFile,e),this.emit("mirror:flush",{path:this.snapshotFile})}getMode(){return this.mode}getSnapshotPath(){return this.snapshotFile}mount(t,e,{readOnly:n=!0}={}){if(r.isBrowser)return;let i=O(t),s=ot.resolve(e);if(!B.existsSync(s))throw new Error(`VirtualFileSystem.mount: host path does not exist: "${s}"`);if(!B.statSync(s).isDirectory())throw new Error(`VirtualFileSystem.mount: host path is not a directory: "${s}"`);this.mkdir(i),this.mounts.set(i,{hostPath:s,readOnly:n}),this.emit("mount",{vPath:i,hostPath:s,readOnly:n})}unmount(t){let e=O(t);this.mounts.delete(e)&&this.emit("unmount",{vPath:e})}getMounts(){return[...this.mounts.entries()].map(([t,e])=>({vPath:t,...e}))}resolveMount(t){let e=O(t),n=[...this.mounts.entries()].sort(([i],[s])=>s.length-i.length);for(let[i,s]of n)if(e===i||e.startsWith(`${i}/`)){let o=e.slice(i.length).replace(/^\//,""),a=o?ot.join(s.hostPath,o):s.hostPath;return{hostPath:s.hostPath,readOnly:s.readOnly,relPath:o,fullHostPath:a}}return null}mkdir(t,e=493){let n=O(t),i=(()=>{try{return rt(this.root,n)}catch{return null}})();if(i&&i.type!=="directory")throw new Error(`Cannot create directory '${n}': path is a file.`);this.mkdirRecursive(n,e)}writeFile(t,e,n={}){let i=this.resolveMount(t);if(i){if(i.readOnly)throw new Error(`EROFS: read-only file system, open '${i.fullHostPath}'`);let p=ot.dirname(i.fullHostPath);B.existsSync(p)||B.mkdirSync(p,{recursive:!0}),B.writeFileSync(i.fullHostPath,Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"));return}let s=O(t),{parent:o,name:a}=It(this.root,s,!0,p=>this.mkdirRecursive(p,493)),l=o.children.get(a);if(l?.type==="directory")throw new Error(`Cannot write file '${s}': path is a directory.`);let c=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),u=n.compress??!1,d=u?ws(c):c,m=n.mode??420;if(l){let p=l;p.content=d,p.compressed=u,p.mode=m,p.updatedAt=new Date}else o.children.set(a,this.makeFile(a,d,m,u));this.emit("file:write",{path:s,size:d.length})}readFile(t){let e=this.resolveMount(t);if(e){if(!B.existsSync(e.fullHostPath))throw new Error(`ENOENT: no such file or directory, open '${e.fullHostPath}'`);return B.readFileSync(e.fullHostPath,"utf8")}let n=O(t),i=rt(this.root,n);if(i.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let s=i,o=s.compressed?Re(s.content):s.content;return this.emit("file:read",{path:n,size:o.length}),o.toString("utf8")}readFileRaw(t){let e=this.resolveMount(t);if(e){if(!B.existsSync(e.fullHostPath))throw new Error(`ENOENT: no such file or directory, open '${e.fullHostPath}'`);return B.readFileSync(e.fullHostPath)}let n=O(t),i=rt(this.root,n);if(i.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let s=i,o=s.compressed?Re(s.content):s.content;return this.emit("file:read",{path:n,size:o.length}),o}exists(t){let e=this.resolveMount(t);if(e)return B.existsSync(e.fullHostPath);try{return rt(this.root,O(t)),!0}catch{return!1}}chmod(t,e){rt(this.root,O(t)).mode=e}stat(t){let e=this.resolveMount(t);if(e){if(!B.existsSync(e.fullHostPath))throw new Error(`ENOENT: stat '${e.fullHostPath}'`);let a=B.statSync(e.fullHostPath),l=e.relPath.split("/").pop()??e.fullHostPath.split("/").pop()??"",c=a.mtime;return a.isDirectory()?{type:"directory",name:l,path:O(t),mode:493,createdAt:a.birthtime,updatedAt:c,childrenCount:B.readdirSync(e.fullHostPath).length}:{type:"file",name:l,path:O(t),mode:e.readOnly?292:420,createdAt:a.birthtime,updatedAt:c,compressed:!1,size:a.size}}let n=O(t),i=rt(this.root,n),s=n==="/"?"":ot.posix.basename(n);if(i.type==="file"){let a=i;return{type:"file",name:s,path:n,mode:a.mode,createdAt:a.createdAt,updatedAt:a.updatedAt,compressed:a.compressed,size:a.content.length}}let o=i;return{type:"directory",name:s,path:n,mode:o.mode,createdAt:o.createdAt,updatedAt:o.updatedAt,childrenCount:o.children.size}}list(t="/"){let e=this.resolveMount(t);if(e){if(!B.existsSync(e.fullHostPath))return[];try{return B.readdirSync(e.fullHostPath).sort()}catch{return[]}}let n=O(t),i=rt(this.root,n);if(i.type!=="directory")throw new Error(`Cannot list '${t}': not a directory.`);return Array.from(i.children.keys()).sort()}tree(t="/"){let e=O(t),n=rt(this.root,e);if(n.type!=="directory")throw new Error(`Cannot render tree for '${t}': not a directory.`);let i=t==="/"?"/":ot.posix.basename(e);return this.renderTreeLines(n,i)}renderTreeLines(t,e){let n=[e],i=Array.from(t.children.keys()).sort();for(let s=0;s<i.length;s++){let o=i[s],a=t.children.get(o),l=s===i.length-1,c=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=l?" ":"\u2502 ";if(n.push(`${c}${o}`),a.type==="directory"){let d=this.renderTreeLines(a,"").split(`
270
277
  `).slice(1).map(m=>`${u}${m}`);n.push(...d)}}return n.join(`
271
- `)}getUsageBytes(t="/"){return this.computeUsage(et(this.root,q(t)))}computeUsage(t){if(t.type==="file")return t.content.length;let e=0;for(let n of t.children.values())e+=this.computeUsage(n);return e}compressFile(t){let e=et(this.root,q(t));if(e.type!=="file")throw new Error(`Cannot compress '${t}': not a file.`);let n=e;n.compressed||(n.content=ms(n.content),n.compressed=!0,n.updatedAt=new Date)}decompressFile(t){let e=et(this.root,q(t));if(e.type!=="file")throw new Error(`Cannot decompress '${t}': not a file.`);let n=e;n.compressed&&(n.content=Ne(n.content),n.compressed=!1,n.updatedAt=new Date)}symlink(t,e){let n=q(e),i=t.startsWith("/")?q(t):t,{parent:s,name:o}=Nt(this.root,n,!0,l=>this.mkdirRecursive(l,493)),a={type:"file",name:o,content:Buffer.from(i,"utf8"),mode:41471,compressed:!1,createdAt:new Date,updatedAt:new Date};s.children.set(o,a),this.emit("symlink:create",{link:n,target:i})}isSymlink(t){try{let e=et(this.root,q(t));return e.type==="file"&&e.mode===41471}catch{return!1}}resolveSymlink(t,e=8){let n=q(t);for(let i=0;i<e;i++){try{let s=et(this.root,n);if(s.type==="file"&&s.mode===41471){let o=s.content.toString("utf8");n=o.startsWith("/")?o:q(ht.posix.join(ht.posix.dirname(n),o));continue}}catch{break}return n}throw new Error(`Too many levels of symbolic links: ${t}`)}remove(t,e={}){let n=q(t);if(n==="/")throw new Error("Cannot remove root directory.");let i=et(this.root,n);if(i.type==="directory"){let a=i;if(!e.recursive&&a.children.size>0)throw new Error(`Directory '${n}' is not empty. Use recursive option.`)}let{parent:s,name:o}=Nt(this.root,n,!1,()=>{});s.children.delete(o),this.emit("node:remove",{path:n})}move(t,e){let n=q(t),i=q(e);if(n==="/"||i==="/")throw new Error("Cannot move root directory.");let s=et(this.root,n);if(this.exists(i))throw new Error(`Destination '${i}' already exists.`);this.mkdirRecursive(ht.posix.dirname(i),493);let{parent:o,name:a}=Nt(this.root,i,!1,()=>{}),{parent:l,name:c}=Nt(this.root,n,!1,()=>{});l.children.delete(c),s.name=a,o.children.set(a,s)}toSnapshot(){return{root:this.serializeDir(this.root)}}serializeDir(t){let e=[];for(let n of t.children.values())e.push(n.type==="file"?this.serializeFile(n):this.serializeDir(n));return{type:"directory",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),children:e}}serializeFile(t){return{type:"file",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),compressed:t.compressed,contentBase64:t.content.toString("base64")}}static fromSnapshot(t){let e=new r;return e.root=e.deserializeDir(t.root,""),e}importSnapshot(t){this.root=this.deserializeDir(t.root,""),this.emit("snapshot:import")}deserializeDir(t,e){let n={type:"directory",name:e,mode:t.mode,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),children:new Map};for(let i of t.children)if(i.type==="file"){let s=i;n.children.set(s.name,{type:"file",name:s.name,mode:s.mode,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt),compressed:s.compressed,content:Buffer.from(s.contentBase64,"base64")})}else{let s=this.deserializeDir(i,i.name);n.children.set(i.name,s)}return n}},ps=Ie;var Ve=[{name:"vim",version:"2:9.0.1378-2",section:"editors",description:"Vi IMproved - enhanced vi editor",shortDesc:"Vi IMproved",installedSizeKb:3812,files:[{path:"/usr/bin/vim",content:`#!/bin/sh
278
+ `)}getUsageBytes(t="/"){return this.computeUsage(rt(this.root,O(t)))}computeUsage(t){if(t.type==="file")return t.content.length;let e=0;for(let n of t.children.values())e+=this.computeUsage(n);return e}compressFile(t){let e=rt(this.root,O(t));if(e.type!=="file")throw new Error(`Cannot compress '${t}': not a file.`);let n=e;n.compressed||(n.content=ws(n.content),n.compressed=!0,n.updatedAt=new Date)}decompressFile(t){let e=rt(this.root,O(t));if(e.type!=="file")throw new Error(`Cannot decompress '${t}': not a file.`);let n=e;n.compressed&&(n.content=Re(n.content),n.compressed=!1,n.updatedAt=new Date)}symlink(t,e){let n=O(e),i=t.startsWith("/")?O(t):t,{parent:s,name:o}=It(this.root,n,!0,l=>this.mkdirRecursive(l,493)),a={type:"file",name:o,content:Buffer.from(i,"utf8"),mode:41471,compressed:!1,createdAt:new Date,updatedAt:new Date};s.children.set(o,a),this.emit("symlink:create",{link:n,target:i})}isSymlink(t){try{let e=rt(this.root,O(t));return e.type==="file"&&e.mode===41471}catch{return!1}}resolveSymlink(t,e=8){let n=O(t);for(let i=0;i<e;i++){try{let s=rt(this.root,n);if(s.type==="file"&&s.mode===41471){let o=s.content.toString("utf8");n=o.startsWith("/")?o:O(ot.posix.join(ot.posix.dirname(n),o));continue}}catch{break}return n}throw new Error(`Too many levels of symbolic links: ${t}`)}remove(t,e={}){let n=this.resolveMount(t);if(n){if(n.readOnly)throw new Error(`EROFS: read-only file system, unlink '${n.fullHostPath}'`);if(!B.existsSync(n.fullHostPath))throw new Error(`ENOENT: no such file or directory, unlink '${n.fullHostPath}'`);B.statSync(n.fullHostPath).isDirectory()?B.rmSync(n.fullHostPath,{recursive:e.recursive??!1}):B.unlinkSync(n.fullHostPath);return}let i=O(t);if(i==="/")throw new Error("Cannot remove root directory.");let s=rt(this.root,i);if(s.type==="directory"){let l=s;if(!e.recursive&&l.children.size>0)throw new Error(`Directory '${i}' is not empty. Use recursive option.`)}let{parent:o,name:a}=It(this.root,i,!1,()=>{});o.children.delete(a),this.emit("node:remove",{path:i})}move(t,e){let n=O(t),i=O(e);if(n==="/"||i==="/")throw new Error("Cannot move root directory.");let s=rt(this.root,n);if(this.exists(i))throw new Error(`Destination '${i}' already exists.`);this.mkdirRecursive(ot.posix.dirname(i),493);let{parent:o,name:a}=It(this.root,i,!1,()=>{}),{parent:l,name:c}=It(this.root,n,!1,()=>{});l.children.delete(c),s.name=a,o.children.set(a,s)}toSnapshot(){return{root:this.serializeDir(this.root)}}serializeDir(t){let e=[];for(let n of t.children.values())e.push(n.type==="file"?this.serializeFile(n):this.serializeDir(n));return{type:"directory",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),children:e}}serializeFile(t){return{type:"file",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),compressed:t.compressed,contentBase64:t.content.toString("base64")}}static fromSnapshot(t){let e=new r;return e.root=e.deserializeDir(t.root,""),e}importSnapshot(t){this.root=this.deserializeDir(t.root,""),this.emit("snapshot:import")}deserializeDir(t,e){let n={type:"directory",name:e,mode:t.mode,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),children:new Map};for(let i of t.children)if(i.type==="file"){let s=i;n.children.set(s.name,{type:"file",name:s.name,mode:s.mode,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt),compressed:s.compressed,content:Buffer.from(s.contentBase64,"base64")})}else{let s=this.deserializeDir(i,i.name);n.children.set(i.name,s)}return n}},Ss=_e;var De=[{name:"vim",version:"2:9.0.1378-2",section:"editors",description:"Vi IMproved - enhanced vi editor",shortDesc:"Vi IMproved",installedSizeKb:3812,files:[{path:"/usr/bin/vim",content:`#!/bin/sh
272
279
  echo 'vim: use nano for editing in this environment'
273
280
  `,mode:493},{path:"/usr/bin/vi",content:`#!/bin/sh
274
281
  exec vim "$@"
@@ -357,19 +364,19 @@ echo 'journalctl: virtual stub'
357
364
  echo 'gzip: virtual stub'
358
365
  `,mode:493}]},{name:"neofetch",version:"7.1.0-1",section:"utils",description:"A command-line system information tool written in bash 3.2+",shortDesc:"command-line system information tool",installedSizeKb:256,files:[{path:"/usr/bin/neofetch",content:`#!/bin/sh
359
366
  echo 'neofetch: virtual stub'
360
- `,mode:493}]}],me=class{constructor(t,e){this.vfs=t;this.users=e}vfs;users;installed=new Map;registryPath="/var/lib/dpkg/status";logPath="/var/log/dpkg.log";aptLogPath="/var/log/apt/history.log";load(){if(!this.vfs.exists(this.registryPath))return;let t=this.vfs.readFile(this.registryPath);if(!t.trim())return;let e=t.split(/\n\n+/);for(let n of e){if(!n.trim())continue;let i=this.parseFields(n),s=i.Package;s&&this.installed.set(s,{name:s,version:i.Version??"unknown",architecture:i.Architecture??"amd64",maintainer:i.Maintainer??"Fortune Maintainers",description:i.Description??"",section:i.Section??"misc",installedSizeKb:Number(i["Installed-Size"]??0),installedAt:i["X-Installed-At"]??new Date().toISOString(),files:(i["X-Files"]??"").split("|").filter(Boolean)})}}persist(){let t=[];for(let e of this.installed.values())t.push([`Package: ${e.name}`,"Status: install ok installed","Priority: optional",`Section: ${e.section}`,`Installed-Size: ${e.installedSizeKb}`,`Maintainer: ${e.maintainer}`,`Architecture: ${e.architecture}`,`Version: ${e.version}`,`Description: ${e.description}`,`X-Installed-At: ${e.installedAt}`,`X-Files: ${e.files.join("|")}`].join(`
367
+ `,mode:493}]}],he=class{constructor(t,e){this.vfs=t;this.users=e}vfs;users;installed=new Map;registryPath="/var/lib/dpkg/status";logPath="/var/log/dpkg.log";aptLogPath="/var/log/apt/history.log";load(){if(!this.vfs.exists(this.registryPath))return;let t=this.vfs.readFile(this.registryPath);if(!t.trim())return;let e=t.split(/\n\n+/);for(let n of e){if(!n.trim())continue;let i=this.parseFields(n),s=i.Package;s&&this.installed.set(s,{name:s,version:i.Version??"unknown",architecture:i.Architecture??"amd64",maintainer:i.Maintainer??"Fortune Maintainers",description:i.Description??"",section:i.Section??"misc",installedSizeKb:Number(i["Installed-Size"]??0),installedAt:i["X-Installed-At"]??new Date().toISOString(),files:(i["X-Files"]??"").split("|").filter(Boolean)})}}persist(){let t=[];for(let e of this.installed.values())t.push([`Package: ${e.name}`,"Status: install ok installed","Priority: optional",`Section: ${e.section}`,`Installed-Size: ${e.installedSizeKb}`,`Maintainer: ${e.maintainer}`,`Architecture: ${e.architecture}`,`Version: ${e.version}`,`Description: ${e.description}`,`X-Installed-At: ${e.installedAt}`,`X-Files: ${e.files.join("|")}`].join(`
361
368
  `));this.vfs.writeFile(this.registryPath,`${t.join(`
362
369
 
363
370
  `)}
364
371
  `)}parseFields(t){let e={};for(let n of t.split(`
365
372
  `)){let i=n.indexOf(": ");i!==-1&&(e[n.slice(0,i)]=n.slice(i+2))}return e}log(t){let n=`${new Date().toISOString().replace("T"," ").slice(0,19)} ${t}
366
373
  `,i=this.vfs.exists(this.logPath)?this.vfs.readFile(this.logPath):"";this.vfs.writeFile(this.logPath,i+n)}aptLog(t,e){let n=new Date().toISOString(),i=this.vfs.exists(this.aptLogPath)?this.vfs.readFile(this.aptLogPath):"",s=[`Start-Date: ${n}`,`Commandline: apt-get ${t} ${e.join(" ")}`,`${t==="install"?"Install":"Remove"}: ${e.join(", ")}`,`End-Date: ${n}`,""].join(`
367
- `);this.vfs.writeFile(this.aptLogPath,i+s)}findInRegistry(t){return Ve.find(e=>e.name.toLowerCase()===t.toLowerCase())}listAvailable(){return[...Ve].sort((t,e)=>t.name.localeCompare(e.name))}listInstalled(){return[...this.installed.values()].sort((t,e)=>t.name.localeCompare(e.name))}isInstalled(t){return this.installed.has(t.toLowerCase())}installedCount(){return this.installed.size}install(t,e={}){let n=[],i=[],s=[],o=(l,c=new Set)=>{if(c.has(l)||(c.add(l),this.isInstalled(l)))return;let u=this.findInRegistry(l);if(!u){s.push(l);return}for(let d of u.depends??[])o(d,c);i.find(d=>d.name===u.name)||i.push(u)};for(let l of t)o(l);if(s.length>0)return{output:`E: Unable to locate package ${s.join(", ")}`,exitCode:100};if(i.length===0)return{output:t.map(l=>`${l} is already the newest version.`).join(`
374
+ `);this.vfs.writeFile(this.aptLogPath,i+s)}findInRegistry(t){return De.find(e=>e.name.toLowerCase()===t.toLowerCase())}listAvailable(){return[...De].sort((t,e)=>t.name.localeCompare(e.name))}listInstalled(){return[...this.installed.values()].sort((t,e)=>t.name.localeCompare(e.name))}isInstalled(t){return this.installed.has(t.toLowerCase())}installedCount(){return this.installed.size}install(t,e={}){let n=[],i=[],s=[],o=(l,c=new Set)=>{if(c.has(l)||(c.add(l),this.isInstalled(l)))return;let u=this.findInRegistry(l);if(!u){s.push(l);return}for(let d of u.depends??[])o(d,c);i.find(d=>d.name===u.name)||i.push(u)};for(let l of t)o(l);if(s.length>0)return{output:`E: Unable to locate package ${s.join(", ")}`,exitCode:100};if(i.length===0)return{output:t.map(l=>`${l} is already the newest version.`).join(`
368
375
  `),exitCode:0};let a=i.reduce((l,c)=>l+(c.installedSizeKb??0),0);e.quiet||n.push("Reading package lists... Done","Building dependency tree... Done","Reading state information... Done","The following NEW packages will be installed:",` ${i.map(l=>l.name).join(" ")}`,`0 upgraded, ${i.length} newly installed, 0 to remove and 0 not upgraded.`,`Need to get 0 B/${a} kB of archives.`,`After this operation, ${a} kB of additional disk space will be used.`,"");for(let l of i){e.quiet||(n.push(`Selecting previously unselected package ${l.name}.`),n.push("(Reading database ... 12345 files and directories currently installed.)"),n.push(`Preparing to unpack .../archives/${l.name}_${l.version}_amd64.deb ...`),n.push(`Unpacking ${l.name} (${l.version}) ...`));for(let u of l.files??[]){let d=u.path.slice(0,u.path.lastIndexOf("/"));d&&!this.vfs.exists(d)&&this.vfs.mkdir(d,493),this.vfs.writeFile(u.path,u.content,{mode:u.mode??420})}l.onInstall?.(this.vfs,this.users),e.quiet||n.push(`Setting up ${l.name} (${l.version}) ...`);let c=new Date().toISOString();this.installed.set(l.name,{name:l.name,version:l.version,architecture:l.architecture??"amd64",maintainer:l.maintainer??"Fortune Maintainers <pkg@fortune.local>",description:l.description,section:l.section??"misc",installedSizeKb:l.installedSizeKb??0,installedAt:c,files:(l.files??[]).map(u=>u.path)}),this.log(`install ${l.name} ${l.version}`)}return this.aptLog("install",i.map(l=>l.name)),this.persist(),e.quiet||n.push("Processing triggers for man-db (2.11.2-2) ..."),{output:n.join(`
369
376
  `),exitCode:0}}remove(t,e={}){let n=[],i=[];for(let s of t){let o=this.installed.get(s.toLowerCase());o?i.push(o):n.push(`Package '${s}' is not installed, so not removed`)}if(i.length===0)return{output:n.join(`
370
377
  `)||"Nothing to remove.",exitCode:0};e.quiet||n.push("Reading package lists... Done","Building dependency tree... Done","The following packages will be REMOVED:",` ${i.map(s=>s.name).join(" ")}`,`0 upgraded, 0 newly installed, ${i.length} to remove and 0 not upgraded.`);for(let s of i){e.quiet||n.push(`Removing ${s.name} (${s.version}) ...`);for(let a of s.files)if(!(!e.purge&&(a.startsWith("/etc/")||a.endsWith(".conf"))))try{this.vfs.exists(a)&&this.vfs.remove(a)}catch{}this.findInRegistry(s.name)?.onRemove?.(this.vfs),this.installed.delete(s.name),this.log(`remove ${s.name} ${s.version}`)}return this.aptLog("remove",i.map(s=>s.name)),this.persist(),{output:n.join(`
371
- `),exitCode:0}}search(t){let e=t.toLowerCase();return Ve.filter(n=>n.name.includes(e)||n.description.toLowerCase().includes(e)||(n.shortDesc??"").toLowerCase().includes(e)).sort((n,i)=>n.name.localeCompare(i.name))}show(t){let e=this.findInRegistry(t);if(!e)return null;let n=this.installed.get(t);return[`Package: ${e.name}`,`Version: ${e.version}`,`Architecture: ${e.architecture??"amd64"}`,`Maintainer: ${e.maintainer??"Fortune Maintainers <pkg@fortune.local>"}`,`Installed-Size: ${e.installedSizeKb??0}`,`Depends: ${(e.depends??[]).join(", ")||"(none)"}`,`Section: ${e.section??"misc"}`,"Priority: optional",`Description: ${e.description}`,`Status: ${n?"install ok installed":"install ok not-installed"}`].join(`
372
- `)}};import{createHash as fs,randomBytes as Ri,randomUUID as Di,scryptSync as _i,timingSafeEqual as zi}from"node:crypto";import{EventEmitter as Li}from"node:events";import*as gs from"node:path";function Ui(){let r=process.env.SSH_MIMIC_FAST_PASSWORD_HASH;return!!r&&!["0","false","no","off"].includes(r.toLowerCase())}var Y=ue("VirtualUserManager"),pe=class r extends Li{constructor(e,n=!0){super();this.vfs=e;this.autoSudoForNewUsers=n;Y.mark("constructor")}vfs;autoSudoForNewUsers;static recordCache=new Map;static fastPasswordHash=Ui();usersPath="/etc/htpasswd";sudoersPath="/etc/sudoers";quotasPath="/etc/quotas";authDirPath="/.virtual-env-js/.auth";users=new Map;sudoers=new Set;quotas=new Map;activeSessions=new Map;nextTty=0;async initialize(){Y.mark("initialize"),this.loadFromVfs(),this.loadSudoersFromVfs(),this.loadQuotasFromVfs();let e=!1;this.users.has("root")||(this.users.set("root",this.createRecord("root","")),e=!0),this.sudoers.add("root"),e&&await this.persist(),this.emit("initialized")}async setQuotaBytes(e,n){if(Y.mark("setQuotaBytes"),this.validateUsername(e),!this.users.has(e))throw new Error(`quota: user '${e}' does not exist`);if(!Number.isFinite(n)||n<0)throw new Error("quota: maxBytes must be a non-negative number");this.quotas.set(e,Math.floor(n)),await this.persist()}async clearQuota(e){Y.mark("clearQuota"),this.validateUsername(e),this.quotas.delete(e),await this.persist()}getQuotaBytes(e){return Y.mark("getQuotaBytes"),this.quotas.get(e)??null}getUsageBytes(e){Y.mark("getUsageBytes");let n=`/home/${e}`;return this.vfs.exists(n)?this.vfs.getUsageBytes(n):0}assertWriteWithinQuota(e,n,i){Y.mark("assertWriteWithinQuota");let s=this.quotas.get(e);if(s===void 0)return;let o=hs(n),a=hs(`/home/${e}`);if(!(o===a||o.startsWith(`${a}/`)))return;let c=this.getUsageBytes(e),u=0;if(this.vfs.exists(o)){let p=this.vfs.stat(o);p.type==="file"&&(u=p.size)}let d=Buffer.isBuffer(i)?i.length:Buffer.byteLength(i,"utf8"),m=c-u+d;if(m>s)throw new Error(`quota exceeded for '${e}': ${m}/${s} bytes`)}verifyPassword(e,n){Y.mark("verifyPassword");let i=this.users.get(e);if(!i)return this.hashPassword(n,""),!1;let s=this.hashPassword(n,i.salt),o=i.passwordHash;try{let a=Buffer.from(s,"hex"),l=Buffer.from(o,"hex");return a.length!==l.length?!1:zi(a,l)}catch{return s===o}}async addUser(e,n){if(Y.mark("addUser"),this.validateUsername(e),this.validatePassword(n),this.users.has(e))return;this.users.set(e,this.createRecord(e,n)),this.autoSudoForNewUsers&&this.sudoers.add(e);let i=`/home/${e}`;this.vfs.exists(i)||(this.vfs.mkdir(i,493),this.vfs.writeFile(`${i}/README.txt`,`Welcome to the virtual environment, ${e}`)),await this.persist(),this.emit("user:add",{username:e})}getPasswordHash(e){Y.mark("getPasswordHash");let n=this.users.get(e);return n?n.passwordHash:null}async setPassword(e,n){if(Y.mark("setPassword"),this.validateUsername(e),this.validatePassword(n),!this.users.has(e))throw new Error(`passwd: user '${e}' does not exist`);this.users.set(e,this.createRecord(e,n)),await this.persist()}async deleteUser(e){if(Y.mark("deleteUser"),this.validateUsername(e),e==="root")throw new Error("deluser: cannot delete root");if(!this.users.delete(e))throw new Error(`deluser: user '${e}' does not exist`);this.sudoers.delete(e),this.emit("user:delete",{username:e}),await this.persist()}isSudoer(e){return Y.mark("isSudoer"),this.sudoers.has(e)}async addSudoer(e){if(Y.mark("addSudoer"),this.validateUsername(e),!this.users.has(e))throw new Error(`sudoers: user '${e}' does not exist`);this.sudoers.add(e),await this.persist()}async removeSudoer(e){if(Y.mark("removeSudoer"),this.validateUsername(e),e==="root")throw new Error("sudoers: cannot remove root");this.sudoers.delete(e),await this.persist()}registerSession(e,n){Y.mark("registerSession");let i={id:Di(),username:e,tty:`pts/${this.nextTty++}`,remoteAddress:n,startedAt:new Date().toISOString()};return this.activeSessions.set(i.id,i),this.emit("session:register",{sessionId:i.id,username:e,remoteAddress:n}),i}unregisterSession(e){if(Y.mark("unregisterSession"),!e)return;let n=this.activeSessions.get(e);this.activeSessions.delete(e),n&&this.emit("session:unregister",{sessionId:e,username:n.username}),this.activeSessions.delete(e)}updateSession(e,n,i){if(Y.mark("updateSession"),!e)return;let s=this.activeSessions.get(e);s&&this.activeSessions.set(e,{...s,username:n,remoteAddress:i})}listActiveSessions(){return Y.mark("listActiveSessions"),Array.from(this.activeSessions.values()).sort((e,n)=>e.startedAt.localeCompare(n.startedAt))}listUsers(){return Array.from(this.users.keys()).sort()}loadFromVfs(){if(this.users.clear(),!this.vfs.exists(this.usersPath))return;let e=this.vfs.readFile(this.usersPath);for(let n of e.split(`
378
+ `),exitCode:0}}search(t){let e=t.toLowerCase();return De.filter(n=>n.name.includes(e)||n.description.toLowerCase().includes(e)||(n.shortDesc??"").toLowerCase().includes(e)).sort((n,i)=>n.name.localeCompare(i.name))}show(t){let e=this.findInRegistry(t);if(!e)return null;let n=this.installed.get(t);return[`Package: ${e.name}`,`Version: ${e.version}`,`Architecture: ${e.architecture??"amd64"}`,`Maintainer: ${e.maintainer??"Fortune Maintainers <pkg@fortune.local>"}`,`Installed-Size: ${e.installedSizeKb??0}`,`Depends: ${(e.depends??[]).join(", ")||"(none)"}`,`Section: ${e.section??"misc"}`,"Priority: optional",`Description: ${e.description}`,`Status: ${n?"install ok installed":"install ok not-installed"}`].join(`
379
+ `)}};import{createHash as xs,randomBytes as Oi,randomUUID as Wi,scryptSync as ji,timingSafeEqual as Hi}from"node:crypto";import{EventEmitter as qi}from"node:events";import*as vs from"node:path";function Ki(){let r=process.env.SSH_MIMIC_FAST_PASSWORD_HASH;return!!r&&!["0","false","no","off"].includes(r.toLowerCase())}var X=pe("VirtualUserManager"),ge=class r extends qi{constructor(e,n=!0){super();this.vfs=e;this.autoSudoForNewUsers=n;X.mark("constructor")}vfs;autoSudoForNewUsers;static recordCache=new Map;static fastPasswordHash=Ki();usersPath="/etc/htpasswd";sudoersPath="/etc/sudoers";quotasPath="/etc/quotas";authDirPath="/.virtual-env-js/.auth";users=new Map;sudoers=new Set;quotas=new Map;activeSessions=new Map;nextTty=0;async initialize(){X.mark("initialize"),this.loadFromVfs(),this.loadSudoersFromVfs(),this.loadQuotasFromVfs();let e=!1;this.users.has("root")||(this.users.set("root",this.createRecord("root","")),e=!0),this.sudoers.add("root"),e&&await this.persist(),this.emit("initialized")}async setQuotaBytes(e,n){if(X.mark("setQuotaBytes"),this.validateUsername(e),!this.users.has(e))throw new Error(`quota: user '${e}' does not exist`);if(!Number.isFinite(n)||n<0)throw new Error("quota: maxBytes must be a non-negative number");this.quotas.set(e,Math.floor(n)),await this.persist()}async clearQuota(e){X.mark("clearQuota"),this.validateUsername(e),this.quotas.delete(e),await this.persist()}getQuotaBytes(e){return X.mark("getQuotaBytes"),this.quotas.get(e)??null}getUsageBytes(e){X.mark("getUsageBytes");let n=`/home/${e}`;return this.vfs.exists(n)?this.vfs.getUsageBytes(n):0}assertWriteWithinQuota(e,n,i){X.mark("assertWriteWithinQuota");let s=this.quotas.get(e);if(s===void 0)return;let o=bs(n),a=bs(`/home/${e}`);if(!(o===a||o.startsWith(`${a}/`)))return;let c=this.getUsageBytes(e),u=0;if(this.vfs.exists(o)){let p=this.vfs.stat(o);p.type==="file"&&(u=p.size)}let d=Buffer.isBuffer(i)?i.length:Buffer.byteLength(i,"utf8"),m=c-u+d;if(m>s)throw new Error(`quota exceeded for '${e}': ${m}/${s} bytes`)}verifyPassword(e,n){X.mark("verifyPassword");let i=this.users.get(e);if(!i)return this.hashPassword(n,""),!1;let s=this.hashPassword(n,i.salt),o=i.passwordHash;try{let a=Buffer.from(s,"hex"),l=Buffer.from(o,"hex");return a.length!==l.length?!1:Hi(a,l)}catch{return s===o}}async addUser(e,n){if(X.mark("addUser"),this.validateUsername(e),this.validatePassword(n),this.users.has(e))return;this.users.set(e,this.createRecord(e,n)),this.autoSudoForNewUsers&&this.sudoers.add(e);let i=`/home/${e}`;this.vfs.exists(i)||(this.vfs.mkdir(i,493),this.vfs.writeFile(`${i}/README.txt`,`Welcome to the virtual environment, ${e}`)),await this.persist(),this.emit("user:add",{username:e})}getPasswordHash(e){X.mark("getPasswordHash");let n=this.users.get(e);return n?n.passwordHash:null}async setPassword(e,n){if(X.mark("setPassword"),this.validateUsername(e),this.validatePassword(n),!this.users.has(e))throw new Error(`passwd: user '${e}' does not exist`);this.users.set(e,this.createRecord(e,n)),await this.persist()}async deleteUser(e){if(X.mark("deleteUser"),this.validateUsername(e),e==="root")throw new Error("deluser: cannot delete root");if(!this.users.delete(e))throw new Error(`deluser: user '${e}' does not exist`);this.sudoers.delete(e),this.emit("user:delete",{username:e}),await this.persist()}isSudoer(e){return X.mark("isSudoer"),this.sudoers.has(e)}async addSudoer(e){if(X.mark("addSudoer"),this.validateUsername(e),!this.users.has(e))throw new Error(`sudoers: user '${e}' does not exist`);this.sudoers.add(e),await this.persist()}async removeSudoer(e){if(X.mark("removeSudoer"),this.validateUsername(e),e==="root")throw new Error("sudoers: cannot remove root");this.sudoers.delete(e),await this.persist()}registerSession(e,n){X.mark("registerSession");let i={id:Wi(),username:e,tty:`pts/${this.nextTty++}`,remoteAddress:n,startedAt:new Date().toISOString()};return this.activeSessions.set(i.id,i),this.emit("session:register",{sessionId:i.id,username:e,remoteAddress:n}),i}unregisterSession(e){if(X.mark("unregisterSession"),!e)return;let n=this.activeSessions.get(e);this.activeSessions.delete(e),n&&this.emit("session:unregister",{sessionId:e,username:n.username}),this.activeSessions.delete(e)}updateSession(e,n,i){if(X.mark("updateSession"),!e)return;let s=this.activeSessions.get(e);s&&this.activeSessions.set(e,{...s,username:n,remoteAddress:i})}listActiveSessions(){return X.mark("listActiveSessions"),Array.from(this.activeSessions.values()).sort((e,n)=>e.startedAt.localeCompare(n.startedAt))}listUsers(){return Array.from(this.users.keys()).sort()}loadFromVfs(){if(this.users.clear(),!this.vfs.exists(this.usersPath))return;let e=this.vfs.readFile(this.usersPath);for(let n of e.split(`
373
380
  `)){let i=n.trim();if(i.length===0)continue;let s=i.split(":");if(s.length<3)continue;let[o,a,l]=s;!o||!a||!l||this.users.set(o,{username:o,salt:a,passwordHash:l})}}loadSudoersFromVfs(){if(this.sudoers.clear(),!this.vfs.exists(this.sudoersPath))return;let e=this.vfs.readFile(this.sudoersPath);for(let n of e.split(`
374
381
  `)){let i=n.trim();i.length>0&&this.sudoers.add(i)}}loadQuotasFromVfs(){if(this.quotas.clear(),!this.vfs.exists(this.quotasPath))return;let e=this.vfs.readFile(this.quotasPath);for(let n of e.split(`
375
382
  `)){let i=n.trim();if(i.length===0)continue;let[s,o]=i.split(":"),a=Number.parseInt(o??"",10);!s||!Number.isFinite(a)||a<0||this.quotas.set(s,a)}}async persist(){this.vfs.exists(this.authDirPath)||this.vfs.mkdir(this.authDirPath,448);let e=Array.from(this.users.values()).sort((o,a)=>o.username.localeCompare(a.username)).map(o=>[o.username,o.salt,o.passwordHash].join(":")).join(`
@@ -378,55 +385,55 @@ echo 'neofetch: virtual stub'
378
385
  `),s=!1;s=this.writeIfChanged(this.usersPath,e.length>0?`${e}
379
386
  `:"",384)||s,s=this.writeIfChanged(this.sudoersPath,n.length>0?`${n}
380
387
  `:"",384)||s,s=this.writeIfChanged(this.quotasPath,i.length>0?`${i}
381
- `:"",384)||s,s&&await this.vfs.flushMirror()}writeIfChanged(e,n,i){return this.vfs.exists(e)&&this.vfs.readFile(e)===n?(this.vfs.chmod(e,i),!1):(this.vfs.writeFile(e,n,{mode:i}),!0)}createRecord(e,n){let i=fs("sha256").update(e).update(":").update(n).digest("hex"),s=r.recordCache.get(i);if(s)return s;let o=Ri(16).toString("hex"),a={username:e,salt:o,passwordHash:this.hashPassword(n,o)};return r.recordCache.set(i,a),a}hasPassword(e){Y.mark("hasPassword");let n=this.users.get(e);if(!n)return!1;let i=this.hashPassword("",n.salt);return n.passwordHash===i?!1:!!n.passwordHash}hashPassword(e,n=""){return r.fastPasswordHash?fs("sha256").update(n).update(e).digest("hex"):_i(e,n||"",32).toString("hex")}validateUsername(e){if(!e||e.trim()==="")throw new Error("invalid username");if(!/^[a-z_][a-z0-9_-]{0,31}$/i.test(e))throw new Error("invalid username")}validatePassword(e){if(!e||e.trim()==="")throw new Error("invalid password")}authorizedKeys=new Map;addAuthorizedKey(e,n,i){Y.mark("addAuthorizedKey");let s=this.authorizedKeys.get(e)??[];s.push({algo:n,data:i}),this.authorizedKeys.set(e,s),this.emit("key:add",{username:e,algo:n})}removeAuthorizedKeys(e){this.authorizedKeys.delete(e),this.emit("key:remove",{username:e})}getAuthorizedKeys(e){return this.authorizedKeys.get(e)??[]}};function hs(r){let t=gs.posix.normalize(r);return t.startsWith("/")?t:`/${t}`}import{readFile as Ti,unlink as Bi,writeFile as Wi}from"node:fs/promises";import*as Re from"node:path";function ys(r,t,e,n,i,s="unknown",o={cols:80,rows:24},a){let l="",c=0,u=Oi(a.vfs,e),d=null,m="",p=`/home/${e}`,w=Ft(e,n),g=null,f=null,$=()=>{let A=`/home/${e}`,z=p===A?"~":Re.posix.basename(p)||"/";return le(e,n,z)},E=Array.from(new Set(Lt())).sort();console.log(`[${i}] Shell started for user '${e}' at ${s}`),(async()=>{let A=`/home/${e}/.bashrc`;if(a.vfs.exists(A))try{let z=a.vfs.readFile(A);for(let U of z.split(`
382
- `)){let D=U.trim();!D||D.startsWith("#")||await H(D,e,n,"shell",p,a,void 0,w)}}catch{}})();function F(){let A=$();t.write(`\r${A}${l}\x1B[K`);let z=l.length-c;z>0&&t.write(`\x1B[${z}D`)}function S(){t.write("\r\x1B[K")}function k(A){f={...A,buffer:""},S(),t.write(A.prompt)}async function V(A){if(!f)return;let z=f;if(f=null,!A){t.write(`\r
388
+ `:"",384)||s,s&&await this.vfs.flushMirror()}writeIfChanged(e,n,i){return this.vfs.exists(e)&&this.vfs.readFile(e)===n?(this.vfs.chmod(e,i),!1):(this.vfs.writeFile(e,n,{mode:i}),!0)}createRecord(e,n){let i=xs("sha256").update(e).update(":").update(n).digest("hex"),s=r.recordCache.get(i);if(s)return s;let o=Oi(16).toString("hex"),a={username:e,salt:o,passwordHash:this.hashPassword(n,o)};return r.recordCache.set(i,a),a}hasPassword(e){X.mark("hasPassword");let n=this.users.get(e);if(!n)return!1;let i=this.hashPassword("",n.salt);return n.passwordHash===i?!1:!!n.passwordHash}hashPassword(e,n=""){return r.fastPasswordHash?xs("sha256").update(n).update(e).digest("hex"):ji(e,n||"",32).toString("hex")}validateUsername(e){if(!e||e.trim()==="")throw new Error("invalid username");if(!/^[a-z_][a-z0-9_-]{0,31}$/i.test(e))throw new Error("invalid username")}validatePassword(e){if(!e||e.trim()==="")throw new Error("invalid password")}authorizedKeys=new Map;addAuthorizedKey(e,n,i){X.mark("addAuthorizedKey");let s=this.authorizedKeys.get(e)??[];s.push({algo:n,data:i}),this.authorizedKeys.set(e,s),this.emit("key:add",{username:e,algo:n})}removeAuthorizedKeys(e){this.authorizedKeys.delete(e),this.emit("key:remove",{username:e})}getAuthorizedKeys(e){return this.authorizedKeys.get(e)??[]}};function bs(r){let t=vs.posix.normalize(r);return t.startsWith("/")?t:`/${t}`}import{readFile as Gi,unlink as Zi,writeFile as Ji}from"node:fs/promises";import*as ze from"node:path";function Cs(r,t,e,n,i,s="unknown",o={cols:80,rows:24},a){let l="",c=0,u=Qi(a.vfs,e),d=null,m="",p=`/home/${e}`,y=At(e,n),g=null,f=null,$=()=>{let E=`/home/${e}`,z=p===E?"~":ze.posix.basename(p)||"/";return de(e,n,z)},N=Array.from(new Set(Bt())).sort();console.log(`[${i}] Shell started for user '${e}' at ${s}`),(async()=>{let E=`/home/${e}/.bashrc`;if(a.vfs.exists(E))try{let z=a.vfs.readFile(E);for(let T of z.split(`
389
+ `)){let _=T.trim();!_||_.startsWith("#")||await K(_,e,n,"shell",p,a,void 0,y)}}catch{}})();function M(){let E=$();t.write(`\r${E}${l}\x1B[K`);let z=l.length-c;z>0&&t.write(`\x1B[${z}D`)}function x(){t.write("\r\x1B[K")}function k(E){f={...E,buffer:""},x(),t.write(E.prompt)}async function A(E){if(!f)return;let z=f;if(f=null,!E){t.write(`\r
383
390
  Sorry, try again.\r
384
- `),F();return}if(!z.commandLine){e=z.targetUser,z.loginShell&&(p=`/home/${e}`),a.users.updateSession(i,e,s),t.write(`\r
385
- `),F();return}let U=z.loginShell?`/home/${z.targetUser}`:p,D=await Promise.resolve(H(z.commandLine,z.targetUser,n,"shell",U,a));if(t.write(`\r
386
- `),D.openEditor){await P(D.openEditor.targetPath,D.openEditor.initialContent,D.openEditor.tempPath);return}if(D.openHtop){await R();return}D.clearScreen&&t.write("\x1B[2J\x1B[H"),D.stdout&&t.write(`${Bt(D.stdout)}\r
387
- `),D.stderr&&t.write(`${Bt(D.stderr)}\r
388
- `),D.switchUser?(e=D.switchUser,p=D.nextCwd??`/home/${e}`,a.users.updateSession(i,e,s)):D.nextCwd&&(p=D.nextCwd),await a.vfs.flushMirror(),F()}async function b(){if(!g)return;let A=g;if(A.kind==="nano"){try{let z=await Ti(A.tempPath,"utf8");a.writeFileAsUser(e,A.targetPath,z),await a.vfs.flushMirror()}catch{}await Bi(A.tempPath).catch(()=>{})}g=null,l="",c=0,t.write(`\r
389
- `),F()}async function P(A,z,U){a.vfs.exists(A)&&await Wi(U,z,"utf8");let D=oe(U,o,t);D.on("error",X=>{t.write(`nano: ${X.message}\r
390
- `),b()}),D.on("close",()=>{b()}),g={kind:"nano",targetPath:A,tempPath:U,process:D}}async function R(){let A=await Qn();if(!A){t.write(`htop: no child_process processes to display\r
391
- `);return}let z=Xn(A,o,t);z.on("error",U=>{t.write(`htop: ${U.message}\r
392
- `),b()}),z.on("close",()=>{b()}),g={kind:"htop",targetPath:"",tempPath:"",process:z}}function v(A){l=A,c=l.length,F()}function C(A){l=`${l.slice(0,c)}${A}${l.slice(c)}`,c+=A.length,F()}function N(A,z){let U=z;for(;U>0&&!/\s/.test(A[U-1]);)U-=1;let D=z;for(;D<A.length&&!/\s/.test(A[D]);)D+=1;return{start:U,end:D}}function G(A){let z=A.lastIndexOf("/"),U=z>=0?A.slice(0,z+1):"",D=z>=0?A.slice(z+1):A,X=ie(p,U||".");try{return a.vfs.list(X).filter(L=>!L.startsWith(".")).filter(L=>L.startsWith(D)).map(L=>{let ct=Re.posix.join(X,L),bt=a.vfs.stat(ct).type==="directory"?"/":"";return`${U}${L}${bt}`}).sort()}catch{return[]}}function B(){let{start:A,end:z}=N(l,c),U=l.slice(A,c);if(U.length===0)return;let X=l.slice(0,A).trim().length===0?E.filter(at=>at.startsWith(U)):[],L=G(U),ct=Array.from(new Set([...X,...L])).sort();if(ct.length!==0){if(ct.length===1){let at=ct[0],bt=at.endsWith("/")?"":" ";l=`${l.slice(0,A)}${at}${bt}${l.slice(z)}`,c=A+at.length+bt.length,F();return}t.write(`\r
393
- `),t.write(`${ct.join(" ")}\r
394
- `),F()}}function Z(A){if(A.length===0)return;u.push(A),u.length>500&&(u=u.slice(u.length-500));let z=u.length>0?`${u.join(`
391
+ `),M();return}if(!z.commandLine){e=z.targetUser,z.loginShell&&(p=`/home/${e}`),a.users.updateSession(i,e,s),t.write(`\r
392
+ `),M();return}let T=z.loginShell?`/home/${z.targetUser}`:p,_=await Promise.resolve(K(z.commandLine,z.targetUser,n,"shell",T,a));if(t.write(`\r
393
+ `),_.openEditor){await P(_.openEditor.targetPath,_.openEditor.initialContent,_.openEditor.tempPath);return}if(_.openHtop){await R();return}_.clearScreen&&t.write("\x1B[2J\x1B[H"),_.stdout&&t.write(`${jt(_.stdout)}\r
394
+ `),_.stderr&&t.write(`${jt(_.stderr)}\r
395
+ `),_.switchUser?(e=_.switchUser,p=_.nextCwd??`/home/${e}`,a.users.updateSession(i,e,s)):_.nextCwd&&(p=_.nextCwd),await a.vfs.flushMirror(),M()}async function b(){if(!g)return;let E=g;if(E.kind==="nano"){try{let z=await Gi(E.tempPath,"utf8");a.writeFileAsUser(e,E.targetPath,z),await a.vfs.flushMirror()}catch{}await Zi(E.tempPath).catch(()=>{})}g=null,l="",c=0,t.write(`\r
396
+ `),M()}async function P(E,z,T){a.vfs.exists(E)&&await Ji(T,z,"utf8");let _=ce(T,o,t);_.on("error",tt=>{t.write(`nano: ${tt.message}\r
397
+ `),b()}),_.on("close",()=>{b()}),g={kind:"nano",targetPath:E,tempPath:T,process:_}}async function R(){let E=await ns();if(!E){t.write(`htop: no child_process processes to display\r
398
+ `);return}let z=is(E,o,t);z.on("error",T=>{t.write(`htop: ${T.message}\r
399
+ `),b()}),z.on("close",()=>{b()}),g={kind:"htop",targetPath:"",tempPath:"",process:z}}function v(E){l=E,c=l.length,M()}function C(E){l=`${l.slice(0,c)}${E}${l.slice(c)}`,c+=E.length,M()}function I(E,z){let T=z;for(;T>0&&!/\s/.test(E[T-1]);)T-=1;let _=z;for(;_<E.length&&!/\s/.test(E[_]);)_+=1;return{start:T,end:_}}function Z(E){let z=E.lastIndexOf("/"),T=z>=0?E.slice(0,z+1):"",_=z>=0?E.slice(z+1):E,tt=le(p,T||".");try{return a.vfs.list(tt).filter(L=>!L.startsWith(".")).filter(L=>L.startsWith(_)).map(L=>{let mt=ze.posix.join(tt,L),Ct=a.vfs.stat(mt).type==="directory"?"/":"";return`${T}${L}${Ct}`}).sort()}catch{return[]}}function W(){let{start:E,end:z}=I(l,c),T=l.slice(E,c);if(T.length===0)return;let tt=l.slice(0,E).trim().length===0?N.filter(ct=>ct.startsWith(T)):[],L=Z(T),mt=Array.from(new Set([...tt,...L])).sort();if(mt.length!==0){if(mt.length===1){let ct=mt[0],Ct=ct.endsWith("/")?"":" ";l=`${l.slice(0,E)}${ct}${Ct}${l.slice(z)}`,c=E+ct.length+Ct.length,M();return}t.write(`\r
400
+ `),t.write(`${mt.join(" ")}\r
401
+ `),M()}}function J(E){if(E.length===0)return;u.push(E),u.length>500&&(u=u.slice(u.length-500));let z=u.length>0?`${u.join(`
395
402
  `)}
396
- `:"";a.vfs.writeFile(`/home/${e}/.bash_history`,z)}function gt(){let A=`/home/${e}/.lastlog.json`;if(!a.vfs.exists(A))return null;try{return JSON.parse(a.vfs.readFile(A))}catch{return null}}function lt(A){let z=`/home/${e}/.lastlog`;a.vfs.writeFile(z,JSON.stringify({at:A,from:s}))}function yt(){let A=gt(),z=new Date().toISOString();t.write(ae(n,r,A)),lt(z)}yt(),F(),t.on("data",async A=>{if(g){g.process.stdin.write(A);return}if(f){let U=A.toString("utf8");for(let D=0;D<U.length;D+=1){let X=U[D];if(X===""){f=null,t.write(`^C\r
397
- `),F();return}if(X==="\x7F"||X==="\b"){f.buffer=f.buffer.slice(0,-1);continue}if(X==="\r"||X===`
398
- `){let L=f.buffer;if(f.buffer="",f.onPassword){let{result:at,nextPrompt:bt}=await f.onPassword(L,a);t.write(`\r
399
- `),at!==null?(f=null,at.stdout&&t.write(at.stdout.replace(/\n/g,`\r
400
- `)),at.stderr&&t.write(at.stderr.replace(/\n/g,`\r
401
- `)),F()):(bt&&(f.prompt=bt),t.write(f.prompt));return}let ct=a.users.verifyPassword(f.username,L);await V(ct);return}X>=" "&&(f.buffer+=X)}return}let z=A.toString("utf8");for(let U=0;U<z.length;U+=1){let D=z[U];if(D===""){l="",c=0,d=null,m="",t.write(`bye\r
402
- `),Z("bye"),await a.vfs.flushMirror(),t.write(`logout\r
403
- `),t.exit(0),t.end();return}if(D===" "){B();continue}if(D==="\x1B"){let X=z[U+1],L=z[U+2],ct=z[U+3];if(X==="["&&L){if(L==="A"){U+=2,u.length>0&&(d===null?(m=l,d=u.length-1):d>0&&(d-=1),v(u[d]??""));continue}if(L==="B"){U+=2,d!==null&&(d<u.length-1?(d+=1,v(u[d]??"")):(d=null,v(m)));continue}if(L==="C"){U+=2,c<l.length&&(c+=1,t.write("\x1B[C"));continue}if(L==="D"){U+=2,c>0&&(c-=1,t.write("\x1B[D"));continue}if(L==="3"&&ct==="~"){U+=3,c<l.length&&(l=`${l.slice(0,c)}${l.slice(c+1)}`,F());continue}}}if(D===""){l="",c=0,d=null,m="",t.write(`^C\r
404
- `),F();continue}if(D==="\r"||D===`
405
- `){let X=l.trim();if(l="",c=0,d=null,m="",t.write(`\r
406
- `),X.length>0){let L=await Promise.resolve(H(X,e,n,"shell",p,a,void 0,w));if(Z(X),L.openEditor){await P(L.openEditor.targetPath,L.openEditor.initialContent,L.openEditor.tempPath);return}if(L.openHtop){await R();return}if(L.sudoChallenge){k(L.sudoChallenge);return}if(L.clearScreen&&t.write("\x1B[2J\x1B[H"),L.stdout&&t.write(`${Bt(L.stdout)}\r
407
- `),L.stderr&&t.write(`${Bt(L.stderr)}\r
403
+ `:"";a.vfs.writeFile(`/home/${e}/.bash_history`,z)}function yt(){let E=`/home/${e}/.lastlog.json`;if(!a.vfs.exists(E))return null;try{return JSON.parse(a.vfs.readFile(E))}catch{return null}}function dt(E){let z=`/home/${e}/.lastlog`;a.vfs.writeFile(z,JSON.stringify({at:E,from:s}))}function wt(){let E=yt(),z=new Date().toISOString();t.write(ue(n,r,E)),dt(z)}wt(),M(),t.on("data",async E=>{if(g){g.process.stdin.write(E);return}if(f){let T=E.toString("utf8");for(let _=0;_<T.length;_+=1){let tt=T[_];if(tt===""){f=null,t.write(`^C\r
404
+ `),M();return}if(tt==="\x7F"||tt==="\b"){f.buffer=f.buffer.slice(0,-1);continue}if(tt==="\r"||tt===`
405
+ `){let L=f.buffer;if(f.buffer="",f.onPassword){let{result:ct,nextPrompt:Ct}=await f.onPassword(L,a);t.write(`\r
406
+ `),ct!==null?(f=null,ct.stdout&&t.write(ct.stdout.replace(/\n/g,`\r
407
+ `)),ct.stderr&&t.write(ct.stderr.replace(/\n/g,`\r
408
+ `)),M()):(Ct&&(f.prompt=Ct),t.write(f.prompt));return}let mt=a.users.verifyPassword(f.username,L);await A(mt);return}tt>=" "&&(f.buffer+=tt)}return}let z=E.toString("utf8");for(let T=0;T<z.length;T+=1){let _=z[T];if(_===""){l="",c=0,d=null,m="",t.write(`bye\r
409
+ `),J("bye"),await a.vfs.flushMirror(),t.write(`logout\r
410
+ `),t.exit(0),t.end();return}if(_===" "){W();continue}if(_==="\x1B"){let tt=z[T+1],L=z[T+2],mt=z[T+3];if(tt==="["&&L){if(L==="A"){T+=2,u.length>0&&(d===null?(m=l,d=u.length-1):d>0&&(d-=1),v(u[d]??""));continue}if(L==="B"){T+=2,d!==null&&(d<u.length-1?(d+=1,v(u[d]??"")):(d=null,v(m)));continue}if(L==="C"){T+=2,c<l.length&&(c+=1,t.write("\x1B[C"));continue}if(L==="D"){T+=2,c>0&&(c-=1,t.write("\x1B[D"));continue}if(L==="3"&&mt==="~"){T+=3,c<l.length&&(l=`${l.slice(0,c)}${l.slice(c+1)}`,M());continue}}}if(_===""){l="",c=0,d=null,m="",t.write(`^C\r
411
+ `),M();continue}if(_==="\r"||_===`
412
+ `){let tt=l.trim();if(l="",c=0,d=null,m="",t.write(`\r
413
+ `),tt.length>0){let L=await Promise.resolve(K(tt,e,n,"shell",p,a,void 0,y));if(J(tt),L.openEditor){await P(L.openEditor.targetPath,L.openEditor.initialContent,L.openEditor.tempPath);return}if(L.openHtop){await R();return}if(L.sudoChallenge){k(L.sudoChallenge);return}if(L.clearScreen&&t.write("\x1B[2J\x1B[H"),L.stdout&&t.write(`${jt(L.stdout)}\r
414
+ `),L.stderr&&t.write(`${jt(L.stderr)}\r
408
415
  `),L.closeSession){t.write(`logout\r
409
- `),t.exit(L.exitCode??0),t.end();return}L.nextCwd&&(p=L.nextCwd),L.switchUser&&(e=L.switchUser,p=L.nextCwd??`/home/${e}`,a.users.updateSession(i,e,s),l="",c=0),await a.vfs.flushMirror()}F();continue}if(D==="\x7F"||D==="\b"){c>0&&(l=`${l.slice(0,c-1)}${l.slice(c)}`,c-=1,F());continue}C(D)}}),t.on("close",()=>{g&&(g.process.kill("SIGTERM"),g=null)})}function Oi(r,t){let e=`/home/${t}/.bash_history`;return r.exists(e)?r.readFile(e).split(`
410
- `).map(i=>i.trim()).filter(i=>i.length>0):(r.writeFile(e,""),[])}function Hi(r){return typeof r=="object"&&r!==null&&"vfsInstance"in r&&ws(r.vfsInstance)}function ws(r){if(typeof r!="object"||r===null)return!1;let t=r;return typeof t.restoreMirror=="function"&&typeof t.flushMirror=="function"&&typeof t.writeFile=="function"&&typeof t.readFile=="function"&&typeof t.mkdir=="function"&&typeof t.exists=="function"&&typeof t.stat=="function"&&typeof t.list=="function"&&typeof t.remove=="function"&&typeof t.copy=="function"&&typeof t.move=="function"&&typeof t.touch=="function"}var qi={kernel:"1.0.0+itsrealfortune+1-amd64",os:"Fortune GNU/Linux x64",arch:"x86_64"},Wt=ue("VirtualShell");function Ki(){let r=process.env.SSH_MIMIC_AUTO_SUDO_NEW_USERS;return r?!["0","false","no","off"].includes(r.toLowerCase()):!0}var fe=class extends ji{vfs;users;packageManager;hostname;properties;startTime;initialized;constructor(t,e,n){super(),Wt.mark("constructor"),this.hostname=t,this.properties=e||qi,this.startTime=Date.now(),ws(n)?this.vfs=n:Hi(n)?this.vfs=n.vfsInstance:this.vfs=new ps(n??{}),this.users=new pe(this.vfs,Ki()),this.packageManager=new me(this.vfs,this.users);let i=this.vfs,s=this.users,o=this.packageManager,a=this.properties,l=this.hostname,c=this.startTime;this.initialized=(async()=>{await i.restoreMirror(),await s.initialize(),rs(i,s,l,a,c),o.load(),this.emit("initialized")})()}async ensureInitialized(){Wt.mark("ensureInitialized"),await this.initialized}addCommand(t,e,n){let i=t.trim().toLowerCase();if(i.length===0||/\s/.test(i))throw new Error("Command name must be non-empty and contain no spaces");xe(be(i,e,n))}executeCommand(t,e,n){Wt.mark("executeCommand"),H(t,e,this.hostname,"shell",n,this),this.emit("command",{command:t,user:e,cwd:n})}startInteractiveSession(t,e,n,i,s){Wt.mark("startInteractiveSession"),this.emit("session:start",{user:e,sessionId:n,remoteAddress:i}),ys(this.properties,t,e,this.hostname,n,i,s,this),this.refreshProcSessions()}refreshProcFs(){ce(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}refreshProcSessions(){ce(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}syncPasswd(){Me(this.vfs,this.users)}getVfs(){return this?.vfs??null}getUsers(){return this?.users??null}getHostname(){return this?.hostname}writeFileAsUser(t,e,n){Wt.mark("writeFileAsUser"),this.users.assertWriteWithinQuota(t,e,n),this.vfs.writeFile(e,n)}};var It=process.env.SSH_MIMIC_HOSTNAME??"typescript-vm",De=process.argv.slice(2);function Xi(){for(let r=0;r<De.length;r+=1){let t=De[r];if(t==="--user"){let e=De[r+1];if(!e||e.startsWith("--"))throw new Error("self-standalone: --user requires a value");return e}if(t?.startsWith("--user="))return t.slice(7)||"root"}return"root"}var to=Xi(),K=new fe(It,void 0,{mode:"fs",snapshotPath:".vfs"});function eo(r){let t=`/home/${r}/.lastlog`;if(!K.vfs.exists(t))return null;try{return JSON.parse(K.vfs.readFile(t))}catch{return null}}function ro(r,t){K.vfs.writeFile(`/home/${r}/.lastlog`,JSON.stringify({at:new Date().toISOString(),from:t}))}async function Ot(){await K.vfs.flushMirror()}function no(r){let t=`/home/${r}/.bash_history`;return K.vfs.exists(t)?K.vfs.readFile(t).split(`
411
- `).map(e=>e.trim()).filter(e=>e.length>0):(K.vfs.writeFile(t,""),[])}function so(r,t){let e=r.length>0?`${r.join(`
416
+ `),t.exit(L.exitCode??0),t.end();return}L.nextCwd&&(p=L.nextCwd),L.switchUser&&(e=L.switchUser,p=L.nextCwd??`/home/${e}`,a.users.updateSession(i,e,s),l="",c=0),await a.vfs.flushMirror()}M();continue}if(_==="\x7F"||_==="\b"){c>0&&(l=`${l.slice(0,c-1)}${l.slice(c)}`,c-=1,M());continue}C(_)}}),t.on("close",()=>{g&&(g.process.kill("SIGTERM"),g=null)})}function Qi(r,t){let e=`/home/${t}/.bash_history`;return r.exists(e)?r.readFile(e).split(`
417
+ `).map(i=>i.trim()).filter(i=>i.length>0):(r.writeFile(e,""),[])}function Xi(r){return typeof r=="object"&&r!==null&&"vfsInstance"in r&&$s(r.vfsInstance)}function $s(r){if(typeof r!="object"||r===null)return!1;let t=r;return typeof t.restoreMirror=="function"&&typeof t.flushMirror=="function"&&typeof t.writeFile=="function"&&typeof t.readFile=="function"&&typeof t.mkdir=="function"&&typeof t.exists=="function"&&typeof t.stat=="function"&&typeof t.list=="function"&&typeof t.remove=="function"&&typeof t.copy=="function"&&typeof t.move=="function"&&typeof t.touch=="function"}var to={kernel:"1.0.0+itsrealfortune+1-amd64",os:"Fortune GNU/Linux x64",arch:"x86_64"},Ht=pe("VirtualShell");function eo(){let r=process.env.SSH_MIMIC_AUTO_SUDO_NEW_USERS;return r?!["0","false","no","off"].includes(r.toLowerCase()):!0}var ye=class extends Yi{vfs;users;packageManager;hostname;properties;startTime;initialized;constructor(t,e,n){super(),Ht.mark("constructor"),this.hostname=t,this.properties=e||to,this.startTime=Date.now(),$s(n)?this.vfs=n:Xi(n)?this.vfs=n.vfsInstance:this.vfs=new Ss(n??{}),this.users=new ge(this.vfs,eo()),this.packageManager=new he(this.vfs,this.users);let i=this.vfs,s=this.users,o=this.packageManager,a=this.properties,l=this.hostname,c=this.startTime;this.initialized=(async()=>{await i.restoreMirror(),await s.initialize(),ls(i,s,l,a,c),o.load(),this.emit("initialized")})()}async ensureInitialized(){Ht.mark("ensureInitialized"),await this.initialized}addCommand(t,e,n){let i=t.trim().toLowerCase();if(i.length===0||/\s/.test(i))throw new Error("Command name must be non-empty and contain no spaces");Ce($e(i,e,n))}executeCommand(t,e,n){Ht.mark("executeCommand"),K(t,e,this.hostname,"shell",n,this),this.emit("command",{command:t,user:e,cwd:n})}startInteractiveSession(t,e,n,i,s){Ht.mark("startInteractiveSession"),this.emit("session:start",{user:e,sessionId:n,remoteAddress:i}),Cs(this.properties,t,e,this.hostname,n,i,s,this),this.refreshProcSessions()}refreshProcFs(){me(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}mount(t,e,n={}){this.vfs.mount(t,e,n)}unmount(t){this.vfs.unmount(t)}getMounts(){return this.vfs.getMounts()}refreshProcSessions(){me(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}syncPasswd(){Ee(this.vfs,this.users)}getVfs(){return this?.vfs??null}getUsers(){return this?.users??null}getHostname(){return this?.hostname}writeFileAsUser(t,e,n){Ht.mark("writeFileAsUser"),this.users.assertWriteWithinQuota(t,e,n),this.vfs.writeFile(e,n)}};var Vt=process.env.SSH_MIMIC_HOSTNAME??"typescript-vm",Le=process.argv.slice(2);function ao(){for(let r=0;r<Le.length;r+=1){let t=Le[r];if(t==="--user"){let e=Le[r+1];if(!e||e.startsWith("--"))throw new Error("self-standalone: --user requires a value");return e}if(t?.startsWith("--user="))return t.slice(7)||"root"}return"root"}var lo=ao(),G=new ye(Vt,void 0,{mode:"fs",snapshotPath:".vfs"});function co(r){let t=`/home/${r}/.lastlog`;if(!G.vfs.exists(t))return null;try{return JSON.parse(G.vfs.readFile(t))}catch{return null}}function uo(r,t){G.vfs.writeFile(`/home/${r}/.lastlog`,JSON.stringify({at:new Date().toISOString(),from:t}))}async function qt(){await G.vfs.flushMirror()}function mo(r){let t=`/home/${r}/.bash_history`;return G.vfs.exists(t)?G.vfs.readFile(t).split(`
418
+ `).map(e=>e.trim()).filter(e=>e.length>0):(G.vfs.writeFile(t,""),[])}function po(r,t){let e=r.length>0?`${r.join(`
412
419
  `)}
413
- `:"";K.vfs.writeFile(`/home/${t}/.bash_history`,e)}function io(r,t,e){let n=e.lastIndexOf("/"),i=n>=0?e.slice(0,n+1):"",s=n>=0?e.slice(n+1):e,o=ie(t,i||".");try{return r.list(o).filter(a=>!a.startsWith(".")&&a.startsWith(s)).map(a=>{let l=Ss.posix.join(o,a),c=r.stat(l);return`${i}${a}${c.type==="directory"?"/":""}`}).sort()}catch{return[]}}function oo(r){let t=Array.from(new Set(Lt())).sort();return(e,n)=>{let{cwd:i}=r(),s=e.split(/\s+/).at(-1)??"",a=e.trimStart()===s?t.filter(u=>u.startsWith(s)):[],l=io(K.vfs,i,s),c=Array.from(new Set([...a,...l])).sort();n(null,[c,s])}}function jt(r,t){return new Promise(e=>{if(!it.isTTY||!rt.isTTY){r.question(t,e);return}let n=!!it.isRaw,i="",s=()=>{it.off("data",a),n||it.setRawMode(!1)},o=l=>{s(),rt.write(`
420
+ `:"";G.vfs.writeFile(`/home/${t}/.bash_history`,e)}function fo(r,t,e){let n=e.lastIndexOf("/"),i=n>=0?e.slice(0,n+1):"",s=n>=0?e.slice(n+1):e,o=le(t,i||".");try{return r.list(o).filter(a=>!a.startsWith(".")&&a.startsWith(s)).map(a=>{let l=Ps.posix.join(o,a),c=r.stat(l);return`${i}${a}${c.type==="directory"?"/":""}`}).sort()}catch{return[]}}function ho(r){let t=Array.from(new Set(Bt())).sort();return(e,n)=>{let{cwd:i}=r(),s=e.split(/\s+/).at(-1)??"",a=e.trimStart()===s?t.filter(u=>u.startsWith(s)):[],l=fo(G.vfs,i,s),c=Array.from(new Set([...a,...l])).sort();n(null,[c,s])}}function Kt(r,t){return new Promise(e=>{if(!at.isTTY||!nt.isTTY){r.question(t,e);return}let n=!!at.isRaw,i="",s=()=>{at.off("data",a),n||at.setRawMode(!1)},o=l=>{s(),nt.write(`
414
421
  `),e(l)},a=l=>{let c=l.toString("utf8");for(let u=0;u<c.length;u+=1){let d=c[u];if(d==="\r"||d===`
415
- `){o(i);return}if(d==="\x7F"||d==="\b"){i=i.slice(0,-1);continue}d>=" "&&(i+=d)}};r.pause(),rt.write(t),n||it.setRawMode(!0),it.resume(),it.on("data",a)})}function ao(r,t,e,n){let i=r,s=t;return e.switchUser?(i=e.switchUser,s=e.nextCwd??`/home/${i}`,n.vars.USER=i,n.vars.LOGNAME=i,n.vars.HOME=`/home/${i}`,n.vars.PWD=s):e.nextCwd&&(s=e.nextCwd,n.vars.PWD=s),{authUser:i,cwd:s}}K.addCommand("demo",[],()=>({stdout:"This is a demo command. It does nothing useful.",exitCode:0}));async function lo(){await K.ensureInitialized();let r=to.trim()||"root";K.users.getPasswordHash(r)===null&&(process.stderr.write(`self-standalone: user '${r}' does not exist
416
- `),process.exit(1));let t=Ft(r,It),e=r,n=`/home/${e}`;t.vars.PWD=n;let i="localhost",s={cols:rt.columns??80,rows:rt.rows??24},o=no(e),a=Yi({input:it,output:rt,terminal:!0,completer:oo(()=>({cwd:n}))}),l=a;l.history=[...o].reverse();async function c(f,$,E){K.vfs.exists(f)&&await Ji(E,$,"utf8"),a.pause();let F=oe(E,s,{write:rt.write.bind(rt),exit:()=>{},end:()=>{}}),S=!!it.isRaw,k=V=>{F.stdin.write(V)};it.resume(),S||it.setRawMode(!0),it.on("data",k),await new Promise(V=>{let b=()=>{it.off("data",k),S||it.setRawMode(!1),a.resume()};F.on("error",P=>{b(),rt.write(`nano: ${P.message}\r
417
- `),V()}),F.on("close",async()=>{b(),a.write("",{ctrl:!0,name:"u"});try{let P=await Gi(E,"utf8");K.writeFileAsUser(e,f,P),await Ot()}catch{}await Zi(E).catch(()=>{}),rt.write(`\r
418
- `),V()})})}async function u(f){if(f.onPassword){let S=f.prompt;for(;;){let k=await jt(a,S),V=await f.onPassword(k,K);if(V.result===null){S=V.nextPrompt??S;continue}await m(V.result);return}}let $=await jt(a,f.prompt);if(!K.users.verifyPassword(f.username,$)){process.stderr.write(`Sorry, try again.
419
- `);return}if(!f.commandLine){e=f.targetUser,n=`/home/${e}`,t.vars.USER=e,t.vars.LOGNAME=e,t.vars.HOME=`/home/${e}`,t.vars.PWD=n;return}let E=f.loginShell?`/home/${f.targetUser}`:n,F=await H(f.commandLine,f.targetUser,It,"shell",E,K,void 0,t);await m(F)}async function d(f){let $=await jt(a,f.prompt);if(f.confirmPrompt&&await jt(a,f.confirmPrompt)!==$){process.stderr.write(`passwords do not match
420
- `);return}switch(f.action){case"passwd":await K.users.setPassword(f.targetUsername,$),rt.write(`passwd: password updated successfully
422
+ `){o(i);return}if(d==="\x7F"||d==="\b"){i=i.slice(0,-1);continue}d>=" "&&(i+=d)}};r.pause(),nt.write(t),n||at.setRawMode(!0),at.resume(),at.on("data",a)})}function go(r,t,e,n){let i=r,s=t;return e.switchUser?(i=e.switchUser,s=e.nextCwd??`/home/${i}`,n.vars.USER=i,n.vars.LOGNAME=i,n.vars.HOME=`/home/${i}`,n.vars.PWD=s):e.nextCwd&&(s=e.nextCwd,n.vars.PWD=s),{authUser:i,cwd:s}}G.addCommand("demo",[],()=>({stdout:"This is a demo command. It does nothing useful.",exitCode:0}));async function yo(){await G.ensureInitialized();let r=lo.trim()||"root";G.users.getPasswordHash(r)===null&&(process.stderr.write(`self-standalone: user '${r}' does not exist
423
+ `),process.exit(1));let t=At(r,Vt),e=r,n=`/home/${e}`;t.vars.PWD=n;let i="localhost",s={cols:nt.columns??80,rows:nt.rows??24},o=mo(e),a=oo({input:at,output:nt,terminal:!0,completer:ho(()=>({cwd:n}))}),l=a;l.history=[...o].reverse();async function c(f,$,N){G.vfs.exists(f)&&await so(N,$,"utf8"),a.pause();let M=ce(N,s,{write:nt.write.bind(nt),exit:()=>{},end:()=>{}}),x=!!at.isRaw,k=A=>{M.stdin.write(A)};at.resume(),x||at.setRawMode(!0),at.on("data",k),await new Promise(A=>{let b=()=>{at.off("data",k),x||at.setRawMode(!1),a.resume()};M.on("error",P=>{b(),nt.write(`nano: ${P.message}\r
424
+ `),A()}),M.on("close",async()=>{b(),a.write("",{ctrl:!0,name:"u"});try{let P=await ro(N,"utf8");G.writeFileAsUser(e,f,P),await qt()}catch{}await no(N).catch(()=>{}),nt.write(`\r
425
+ `),A()})})}async function u(f){if(f.onPassword){let x=f.prompt;for(;;){let k=await Kt(a,x),A=await f.onPassword(k,G);if(A.result===null){x=A.nextPrompt??x;continue}await m(A.result);return}}let $=await Kt(a,f.prompt);if(!G.users.verifyPassword(f.username,$)){process.stderr.write(`Sorry, try again.
426
+ `);return}if(!f.commandLine){e=f.targetUser,n=`/home/${e}`,t.vars.USER=e,t.vars.LOGNAME=e,t.vars.HOME=`/home/${e}`,t.vars.PWD=n;return}let N=f.loginShell?`/home/${f.targetUser}`:n,M=await K(f.commandLine,f.targetUser,Vt,"shell",N,G,void 0,t);await m(M)}async function d(f){let $=await Kt(a,f.prompt);if(f.confirmPrompt&&await Kt(a,f.confirmPrompt)!==$){process.stderr.write(`passwords do not match
427
+ `);return}switch(f.action){case"passwd":await G.users.setPassword(f.targetUsername,$),nt.write(`passwd: password updated successfully
421
428
  `);break;case"adduser":if(!f.newUsername){process.stderr.write(`adduser: missing username
422
- `);return}await K.users.addUser(f.newUsername,$),rt.write(`adduser: user '${f.newUsername}' created
423
- `);break;case"deluser":await K.users.deleteUser(f.targetUsername),rt.write(`Removing user '${f.targetUsername}' ...
429
+ `);return}await G.users.addUser(f.newUsername,$),nt.write(`adduser: user '${f.newUsername}' created
430
+ `);break;case"deluser":await G.users.deleteUser(f.targetUsername),nt.write(`Removing user '${f.targetUsername}' ...
424
431
  deluser: done.
425
- `);break;case"su":e=f.targetUsername,n=`/home/${e}`,t.vars.USER=e,t.vars.LOGNAME=e,t.vars.HOME=`/home/${e}`,t.vars.PWD=n;break}}async function m(f){if(f.openEditor){await c(f.openEditor.targetPath,f.openEditor.initialContent,f.openEditor.tempPath);return}if(f.sudoChallenge){await u(f.sudoChallenge);return}if(f.passwordChallenge){await d(f.passwordChallenge);return}f.clearScreen&&(rt.write("\x1B[2J\x1B[H"),console.clear()),f.stdout&&rt.write(f.stdout.endsWith(`
432
+ `);break;case"su":e=f.targetUsername,n=`/home/${e}`,t.vars.USER=e,t.vars.LOGNAME=e,t.vars.HOME=`/home/${e}`,t.vars.PWD=n;break}}async function m(f){if(f.openEditor){await c(f.openEditor.targetPath,f.openEditor.initialContent,f.openEditor.tempPath);return}if(f.sudoChallenge){await u(f.sudoChallenge);return}if(f.passwordChallenge){await d(f.passwordChallenge);return}f.clearScreen&&(nt.write("\x1B[2J\x1B[H"),console.clear()),f.stdout&&nt.write(f.stdout.endsWith(`
426
433
  `)?f.stdout:`${f.stdout}
427
434
  `),f.stderr&&process.stderr.write(f.stderr.endsWith(`
428
435
  `)?f.stderr:`${f.stderr}
429
- `);let $=ao(e,n,f,t);e=$.authUser,n=$.cwd,f.closeSession&&(await Ot(),a.close(),process.exit(f.exitCode??0))}let p=()=>{let f=n===`/home/${e}`?"~":Qi(n)||"/";return le(e,It,f)},w=()=>{a.setPrompt(p()),a.prompt()};if(process.env.USER!=="root"&&K.users.hasPassword(e)){let f=await jt(a,`Password for ${e}: `);K.users.verifyPassword(e,f)||(process.stderr.write(`self-standalone: authentication failed
430
- `),process.exit(1))}rt.write(ae(It,K.properties,eo(e))),ro(e,i),await Ot();let g=!1;a.on("line",async f=>{if(g)return;g=!0,a.pause(),f.trim().length>0&&(o.push(f),o.length>500&&(o=o.slice(o.length-500)),so(o,e),l.history=[...o].reverse());let E=await H(f,e,It,"shell",n,K,void 0,t);await m(E),await Ot(),g=!1,a.resume(),w()}),a.on("SIGINT",()=>{rt.write(`^C
431
- `),a.write("",{ctrl:!0,name:"u"}),w()}),a.on("close",()=>{Ot().then(()=>{console.log(""),process.exit(0)})}),w()}lo().catch(r=>{console.error("Failed to start readline SSH emulation:",r),process.exit(1)});process.on("uncaughtException",r=>{console.error("Uncaught exception:",r)});process.on("unhandledRejection",(r,t)=>{console.error("Unhandled rejection at:",t,"error:",r)});
436
+ `);let $=go(e,n,f,t);e=$.authUser,n=$.cwd,f.closeSession&&(await qt(),a.close(),process.exit(f.exitCode??0))}let p=()=>{let f=n===`/home/${e}`?"~":io(n)||"/";return de(e,Vt,f)},y=()=>{a.setPrompt(p()),a.prompt()};if(process.env.USER!=="root"&&G.users.hasPassword(e)){let f=await Kt(a,`Password for ${e}: `);G.users.verifyPassword(e,f)||(process.stderr.write(`self-standalone: authentication failed
437
+ `),process.exit(1))}nt.write(ue(Vt,G.properties,co(e))),uo(e,i),await qt();let g=!1;a.on("line",async f=>{if(g)return;g=!0,a.pause(),f.trim().length>0&&(o.push(f),o.length>500&&(o=o.slice(o.length-500)),po(o,e),l.history=[...o].reverse());let N=await K(f,e,Vt,"shell",n,G,void 0,t);await m(N),await qt(),g=!1,a.resume(),y()}),a.on("SIGINT",()=>{nt.write(`^C
438
+ `),a.write("",{ctrl:!0,name:"u"}),y()}),a.on("close",()=>{qt().then(()=>{console.log(""),process.exit(0)})}),y()}yo().catch(r=>{console.error("Failed to start readline SSH emulation:",r),process.exit(1)});process.on("uncaughtException",r=>{console.error("Uncaught exception:",r)});process.on("unhandledRejection",(r,t)=>{console.error("Unhandled rejection at:",t,"error:",r)});
432
439
  //# sourceMappingURL=self-standalone.js.map