typescript-virtual-container 1.4.4 → 1.4.5

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 (892) hide show
  1. package/builds/self-standalone.js +321 -272
  2. package/builds/self-standalone.js.map +4 -4
  3. package/builds/standalone-wo-sftp.js +261 -212
  4. package/builds/standalone-wo-sftp.js.map +4 -4
  5. package/builds/standalone.js +265 -216
  6. package/builds/standalone.js.map +4 -4
  7. package/builds/web-full-api.min.js +5 -5
  8. package/builds/web-full-api.min.js.map +3 -3
  9. package/builds/web.min.js +5 -5
  10. package/builds/web.min.js.map +3 -3
  11. package/bun.lock +97 -0
  12. package/dist/Honeypot/index.d.ts.map +1 -0
  13. package/dist/Honeypot/index.js +299 -0
  14. package/dist/Honeypot/index.js.map +1 -0
  15. package/dist/SSHClient/index.d.ts.map +1 -0
  16. package/dist/SSHClient/index.js +238 -0
  17. package/dist/SSHClient/index.js.map +1 -0
  18. package/dist/SSHMimic/exec.d.ts.map +1 -0
  19. package/dist/SSHMimic/exec.js +28 -0
  20. package/dist/SSHMimic/exec.js.map +1 -0
  21. package/dist/SSHMimic/executor.d.ts.map +1 -0
  22. package/dist/SSHMimic/executor.js +161 -0
  23. package/dist/SSHMimic/executor.js.map +1 -0
  24. package/dist/SSHMimic/hostKey.d.ts.map +1 -0
  25. package/dist/SSHMimic/hostKey.js +18 -0
  26. package/dist/SSHMimic/hostKey.js.map +1 -0
  27. package/dist/SSHMimic/index.d.ts.map +1 -0
  28. package/dist/SSHMimic/index.js +250 -0
  29. package/dist/SSHMimic/index.js.map +1 -0
  30. package/dist/SSHMimic/loginBanner.d.ts.map +1 -0
  31. package/dist/SSHMimic/loginBanner.js +23 -0
  32. package/dist/SSHMimic/loginBanner.js.map +1 -0
  33. package/dist/SSHMimic/loginFormat.d.ts.map +1 -0
  34. package/dist/SSHMimic/loginFormat.js +11 -0
  35. package/dist/SSHMimic/loginFormat.js.map +1 -0
  36. package/dist/SSHMimic/prompt.d.ts.map +1 -0
  37. package/dist/SSHMimic/prompt.js +10 -0
  38. package/dist/SSHMimic/prompt.js.map +1 -0
  39. package/dist/SSHMimic/sftp.d.ts.map +1 -0
  40. package/dist/SSHMimic/sftp.js +620 -0
  41. package/dist/SSHMimic/sftp.js.map +1 -0
  42. package/dist/VirtualFileSystem/binaryPack.d.ts.map +1 -0
  43. package/dist/VirtualFileSystem/binaryPack.js +217 -0
  44. package/dist/VirtualFileSystem/binaryPack.js.map +1 -0
  45. package/dist/VirtualFileSystem/index.d.ts.map +1 -0
  46. package/dist/VirtualFileSystem/index.js +690 -0
  47. package/dist/VirtualFileSystem/index.js.map +1 -0
  48. package/dist/VirtualFileSystem/internalTypes.d.ts.map +1 -0
  49. package/dist/VirtualFileSystem/internalTypes.js +1 -0
  50. package/dist/VirtualFileSystem/internalTypes.js.map +1 -0
  51. package/dist/VirtualFileSystem/path.d.ts.map +1 -0
  52. package/dist/VirtualFileSystem/path.js +50 -0
  53. package/dist/VirtualFileSystem/path.js.map +1 -0
  54. package/dist/VirtualPackageManager/index.d.ts.map +1 -0
  55. package/dist/VirtualPackageManager/index.js +854 -0
  56. package/dist/VirtualPackageManager/index.js.map +1 -0
  57. package/dist/VirtualShell/index.d.ts.map +1 -0
  58. package/dist/VirtualShell/index.js +285 -0
  59. package/dist/VirtualShell/index.js.map +1 -0
  60. package/dist/VirtualShell/shell.d.ts.map +1 -0
  61. package/dist/VirtualShell/shell.js +503 -0
  62. package/dist/VirtualShell/shell.js.map +1 -0
  63. package/dist/VirtualShell/shellParser.d.ts.map +1 -0
  64. package/dist/VirtualShell/shellParser.js +266 -0
  65. package/dist/VirtualShell/shellParser.js.map +1 -0
  66. package/dist/VirtualUserManager/index.d.ts.map +1 -0
  67. package/dist/VirtualUserManager/index.js +608 -0
  68. package/dist/VirtualUserManager/index.js.map +1 -0
  69. package/dist/commands/adduser.d.ts.map +1 -0
  70. package/dist/commands/adduser.js +90 -0
  71. package/dist/commands/adduser.js.map +1 -0
  72. package/dist/commands/alias.d.ts.map +1 -0
  73. package/dist/commands/alias.js +69 -0
  74. package/dist/commands/alias.js.map +1 -0
  75. package/dist/commands/apt.d.ts.map +1 -0
  76. package/dist/commands/apt.js +211 -0
  77. package/dist/commands/apt.js.map +1 -0
  78. package/dist/commands/awk.d.ts.map +1 -0
  79. package/dist/commands/awk.js +170 -0
  80. package/dist/commands/awk.js.map +1 -0
  81. package/dist/commands/base64.d.ts.map +1 -0
  82. package/dist/commands/base64.js +29 -0
  83. package/dist/commands/base64.js.map +1 -0
  84. package/dist/commands/cat.d.ts.map +1 -0
  85. package/dist/commands/cat.js +45 -0
  86. package/dist/commands/cat.js.map +1 -0
  87. package/dist/commands/cd.d.ts.map +1 -0
  88. package/dist/commands/cd.js +22 -0
  89. package/dist/commands/cd.js.map +1 -0
  90. package/dist/commands/chmod.d.ts.map +1 -0
  91. package/dist/commands/chmod.js +88 -0
  92. package/dist/commands/chmod.js.map +1 -0
  93. package/dist/commands/clear.d.ts.map +1 -0
  94. package/dist/commands/clear.js +14 -0
  95. package/dist/commands/clear.js.map +1 -0
  96. package/dist/commands/command-helpers.d.ts.map +1 -0
  97. package/dist/commands/command-helpers.js +222 -0
  98. package/dist/commands/command-helpers.js.map +1 -0
  99. package/dist/commands/cp.d.ts.map +1 -0
  100. package/dist/commands/cp.js +76 -0
  101. package/dist/commands/cp.js.map +1 -0
  102. package/dist/commands/curl.d.ts.map +1 -0
  103. package/dist/commands/curl.js +128 -0
  104. package/dist/commands/curl.js.map +1 -0
  105. package/dist/commands/cut.d.ts.map +1 -0
  106. package/dist/commands/cut.js +35 -0
  107. package/dist/commands/cut.js.map +1 -0
  108. package/dist/commands/date.d.ts.map +1 -0
  109. package/dist/commands/date.js +29 -0
  110. package/dist/commands/date.js.map +1 -0
  111. package/dist/commands/declare.d.ts.map +1 -0
  112. package/dist/commands/declare.js +45 -0
  113. package/dist/commands/declare.js.map +1 -0
  114. package/dist/commands/deluser.d.ts.map +1 -0
  115. package/dist/commands/deluser.js +84 -0
  116. package/dist/commands/deluser.js.map +1 -0
  117. package/dist/commands/df.d.ts.map +1 -0
  118. package/dist/commands/df.js +22 -0
  119. package/dist/commands/df.js.map +1 -0
  120. package/dist/commands/diff.d.ts.map +1 -0
  121. package/dist/commands/diff.js +46 -0
  122. package/dist/commands/diff.js.map +1 -0
  123. package/dist/commands/dpkg.d.ts.map +1 -0
  124. package/dist/commands/dpkg.js +162 -0
  125. package/dist/commands/dpkg.js.map +1 -0
  126. package/dist/commands/du.d.ts.map +1 -0
  127. package/dist/commands/du.js +51 -0
  128. package/dist/commands/du.js.map +1 -0
  129. package/dist/commands/echo.d.ts.map +1 -0
  130. package/dist/commands/echo.js +46 -0
  131. package/dist/commands/echo.js.map +1 -0
  132. package/dist/commands/env.d.ts.map +1 -0
  133. package/dist/commands/env.js +21 -0
  134. package/dist/commands/env.js.map +1 -0
  135. package/dist/commands/exit.d.ts.map +1 -0
  136. package/dist/commands/exit.js +17 -0
  137. package/dist/commands/exit.js.map +1 -0
  138. package/dist/commands/export.d.ts.map +1 -0
  139. package/dist/commands/export.js +34 -0
  140. package/dist/commands/export.js.map +1 -0
  141. package/dist/commands/find.d.ts.map +1 -0
  142. package/dist/commands/find.js +56 -0
  143. package/dist/commands/find.js.map +1 -0
  144. package/dist/commands/free.d.ts.map +1 -0
  145. package/dist/commands/free.js +44 -0
  146. package/dist/commands/free.js.map +1 -0
  147. package/dist/commands/grep.d.ts.map +1 -0
  148. package/dist/commands/grep.js +121 -0
  149. package/dist/commands/grep.js.map +1 -0
  150. package/dist/commands/groups.d.ts.map +1 -0
  151. package/dist/commands/groups.js +18 -0
  152. package/dist/commands/groups.js.map +1 -0
  153. package/dist/commands/gzip.d.ts.map +1 -0
  154. package/dist/commands/gzip.js +83 -0
  155. package/dist/commands/gzip.js.map +1 -0
  156. package/dist/commands/head.d.ts.map +1 -0
  157. package/dist/commands/head.js +47 -0
  158. package/dist/commands/head.js.map +1 -0
  159. package/dist/commands/help.d.ts.map +1 -0
  160. package/dist/commands/help.js +124 -0
  161. package/dist/commands/help.js.map +1 -0
  162. package/dist/commands/helpers.d.ts.map +1 -0
  163. package/dist/commands/helpers.js +167 -0
  164. package/dist/commands/helpers.js.map +1 -0
  165. package/dist/commands/history.d.ts.map +1 -0
  166. package/dist/commands/history.js +27 -0
  167. package/dist/commands/history.js.map +1 -0
  168. package/dist/commands/hostname.d.ts.map +1 -0
  169. package/dist/commands/hostname.js +13 -0
  170. package/dist/commands/hostname.js.map +1 -0
  171. package/dist/commands/htop.d.ts.map +1 -0
  172. package/dist/commands/htop.js +18 -0
  173. package/dist/commands/htop.js.map +1 -0
  174. package/dist/commands/id.d.ts.map +1 -0
  175. package/dist/commands/id.js +18 -0
  176. package/dist/commands/id.js.map +1 -0
  177. package/dist/commands/index.d.ts.map +1 -0
  178. package/dist/commands/index.js +3 -0
  179. package/dist/commands/index.js.map +1 -0
  180. package/dist/commands/kill.d.ts.map +1 -0
  181. package/dist/commands/kill.js +19 -0
  182. package/dist/commands/kill.js.map +1 -0
  183. package/dist/commands/ln.d.ts.map +1 -0
  184. package/dist/commands/ln.js +67 -0
  185. package/dist/commands/ln.js.map +1 -0
  186. package/dist/commands/ls.d.ts.map +1 -0
  187. package/dist/commands/ls.js +201 -0
  188. package/dist/commands/ls.js.map +1 -0
  189. package/dist/commands/lsb-release.d.ts.map +1 -0
  190. package/dist/commands/lsb-release.js +62 -0
  191. package/dist/commands/lsb-release.js.map +1 -0
  192. package/dist/commands/man.d.ts.map +1 -0
  193. package/dist/commands/man.js +50 -0
  194. package/dist/commands/man.js.map +1 -0
  195. package/dist/commands/mkdir.d.ts.map +1 -0
  196. package/dist/commands/mkdir.js +29 -0
  197. package/dist/commands/mkdir.js.map +1 -0
  198. package/dist/commands/mv.d.ts.map +1 -0
  199. package/dist/commands/mv.js +43 -0
  200. package/dist/commands/mv.js.map +1 -0
  201. package/dist/commands/nano.d.ts.map +1 -0
  202. package/dist/commands/nano.js +35 -0
  203. package/dist/commands/nano.js.map +1 -0
  204. package/dist/commands/neofetch.d.ts.map +1 -0
  205. package/dist/commands/neofetch.js +49 -0
  206. package/dist/commands/neofetch.js.map +1 -0
  207. package/dist/commands/node.d.ts.map +1 -0
  208. package/dist/commands/node.js +317 -0
  209. package/dist/commands/node.js.map +1 -0
  210. package/dist/commands/npm.d.ts.map +1 -0
  211. package/dist/commands/npm.js +110 -0
  212. package/dist/commands/npm.js.map +1 -0
  213. package/dist/commands/passwd.d.ts.map +1 -0
  214. package/dist/commands/passwd.js +45 -0
  215. package/dist/commands/passwd.js.map +1 -0
  216. package/dist/commands/ping.d.ts.map +1 -0
  217. package/dist/commands/ping.js +29 -0
  218. package/dist/commands/ping.js.map +1 -0
  219. package/dist/commands/printf.d.ts.map +1 -0
  220. package/dist/commands/printf.js +145 -0
  221. package/dist/commands/printf.js.map +1 -0
  222. package/dist/commands/ps.d.ts.map +1 -0
  223. package/dist/commands/ps.js +47 -0
  224. package/dist/commands/ps.js.map +1 -0
  225. package/dist/commands/pwd.d.ts.map +1 -0
  226. package/dist/commands/pwd.js +8 -0
  227. package/dist/commands/pwd.js.map +1 -0
  228. package/dist/commands/python.d.ts.map +1 -0
  229. package/dist/commands/python.js +2059 -0
  230. package/dist/commands/python.js.map +1 -0
  231. package/dist/commands/read.d.ts.map +1 -0
  232. package/dist/commands/read.js +40 -0
  233. package/dist/commands/read.js.map +1 -0
  234. package/dist/commands/registry.d.ts.map +1 -0
  235. package/dist/commands/registry.js +235 -0
  236. package/dist/commands/registry.js.map +1 -0
  237. package/dist/commands/rm.d.ts.map +1 -0
  238. package/dist/commands/rm.js +37 -0
  239. package/dist/commands/rm.js.map +1 -0
  240. package/dist/commands/runtime.d.ts.map +1 -0
  241. package/dist/commands/runtime.js +286 -0
  242. package/dist/commands/runtime.js.map +1 -0
  243. package/dist/commands/sed.d.ts.map +1 -0
  244. package/dist/commands/sed.js +61 -0
  245. package/dist/commands/sed.js.map +1 -0
  246. package/dist/commands/seq.d.ts.map +1 -0
  247. package/dist/commands/seq.js +51 -0
  248. package/dist/commands/seq.js.map +1 -0
  249. package/dist/commands/set.d.ts.map +1 -0
  250. package/dist/commands/set.js +27 -0
  251. package/dist/commands/set.js.map +1 -0
  252. package/dist/commands/sh.d.ts.map +1 -0
  253. package/dist/commands/sh.js +432 -0
  254. package/dist/commands/sh.js.map +1 -0
  255. package/dist/commands/shift.d.ts.map +1 -0
  256. package/dist/commands/shift.js +63 -0
  257. package/dist/commands/shift.js.map +1 -0
  258. package/dist/commands/sleep.d.ts.map +1 -0
  259. package/dist/commands/sleep.js +19 -0
  260. package/dist/commands/sleep.js.map +1 -0
  261. package/dist/commands/sort.d.ts.map +1 -0
  262. package/dist/commands/sort.js +45 -0
  263. package/dist/commands/sort.js.map +1 -0
  264. package/dist/commands/source.d.ts.map +1 -0
  265. package/dist/commands/source.js +40 -0
  266. package/dist/commands/source.js.map +1 -0
  267. package/dist/commands/stat.d.ts.map +1 -0
  268. package/dist/commands/stat.js +57 -0
  269. package/dist/commands/stat.js.map +1 -0
  270. package/dist/commands/su.d.ts.map +1 -0
  271. package/dist/commands/su.js +58 -0
  272. package/dist/commands/su.js.map +1 -0
  273. package/dist/commands/sudo.d.ts.map +1 -0
  274. package/dist/commands/sudo.js +55 -0
  275. package/dist/commands/sudo.js.map +1 -0
  276. package/dist/commands/tail.d.ts.map +1 -0
  277. package/dist/commands/tail.js +48 -0
  278. package/dist/commands/tail.js.map +1 -0
  279. package/dist/commands/tar.d.ts.map +1 -0
  280. package/dist/commands/tar.js +103 -0
  281. package/dist/commands/tar.js.map +1 -0
  282. package/dist/commands/tee.d.ts.map +1 -0
  283. package/dist/commands/tee.js +37 -0
  284. package/dist/commands/tee.js.map +1 -0
  285. package/dist/commands/test.d.ts.map +1 -0
  286. package/dist/commands/test.js +115 -0
  287. package/dist/commands/test.js.map +1 -0
  288. package/dist/commands/touch.d.ts.map +1 -0
  289. package/dist/commands/touch.js +26 -0
  290. package/dist/commands/touch.js.map +1 -0
  291. package/dist/commands/tr.d.ts.map +1 -0
  292. package/dist/commands/tr.js +62 -0
  293. package/dist/commands/tr.js.map +1 -0
  294. package/dist/commands/tree.d.ts.map +1 -0
  295. package/dist/commands/tree.js +19 -0
  296. package/dist/commands/tree.js.map +1 -0
  297. package/dist/commands/true.d.ts.map +1 -0
  298. package/dist/commands/true.js +25 -0
  299. package/dist/commands/true.js.map +1 -0
  300. package/dist/commands/type.d.ts.map +1 -0
  301. package/dist/commands/type.js +40 -0
  302. package/dist/commands/type.js.map +1 -0
  303. package/dist/commands/uname.d.ts.map +1 -0
  304. package/dist/commands/uname.js +30 -0
  305. package/dist/commands/uname.js.map +1 -0
  306. package/dist/commands/uniq.d.ts.map +1 -0
  307. package/dist/commands/uniq.js +39 -0
  308. package/dist/commands/uniq.js.map +1 -0
  309. package/dist/commands/unset.d.ts.map +1 -0
  310. package/dist/commands/unset.js +17 -0
  311. package/dist/commands/unset.js.map +1 -0
  312. package/dist/commands/uptime.d.ts.map +1 -0
  313. package/dist/commands/uptime.js +49 -0
  314. package/dist/commands/uptime.js.map +1 -0
  315. package/dist/commands/wc.d.ts.map +1 -0
  316. package/dist/commands/wc.js +56 -0
  317. package/dist/commands/wc.js.map +1 -0
  318. package/dist/commands/wget.d.ts.map +1 -0
  319. package/dist/commands/wget.js +127 -0
  320. package/dist/commands/wget.js.map +1 -0
  321. package/dist/commands/which.d.ts.map +1 -0
  322. package/dist/commands/which.js +33 -0
  323. package/dist/commands/which.js.map +1 -0
  324. package/dist/commands/who.d.ts.map +1 -0
  325. package/dist/commands/who.js +23 -0
  326. package/dist/commands/who.js.map +1 -0
  327. package/dist/commands/whoami.d.ts.map +1 -0
  328. package/dist/commands/whoami.js +13 -0
  329. package/dist/commands/whoami.js.map +1 -0
  330. package/dist/commands/xargs.d.ts.map +1 -0
  331. package/dist/commands/xargs.js +22 -0
  332. package/dist/commands/xargs.js.map +1 -0
  333. package/dist/index.d.ts.map +1 -0
  334. package/dist/index.js +10 -0
  335. package/dist/index.js.map +1 -0
  336. package/dist/modules/linuxRootfs.d.ts.map +1 -0
  337. package/dist/modules/linuxRootfs.js +620 -0
  338. package/dist/modules/linuxRootfs.js.map +1 -0
  339. package/dist/modules/neofetch.d.ts.map +1 -0
  340. package/dist/modules/neofetch.js +285 -0
  341. package/dist/modules/neofetch.js.map +1 -0
  342. package/dist/modules/shellInteractive.d.ts.map +1 -0
  343. package/dist/modules/shellInteractive.js +27 -0
  344. package/dist/modules/shellInteractive.js.map +1 -0
  345. package/dist/modules/shellRuntime.d.ts.map +1 -0
  346. package/dist/modules/shellRuntime.js +53 -0
  347. package/dist/modules/shellRuntime.js.map +1 -0
  348. package/dist/self-standalone.d.ts.map +1 -0
  349. package/dist/self-standalone.js +419 -0
  350. package/dist/self-standalone.js.map +1 -0
  351. package/dist/standalone-wo-sftp.d.ts.map +1 -0
  352. package/dist/standalone-wo-sftp.js +31 -0
  353. package/dist/standalone-wo-sftp.js.map +1 -0
  354. package/dist/standalone.d.ts.map +1 -0
  355. package/dist/standalone.js +36 -0
  356. package/dist/standalone.js.map +1 -0
  357. package/dist/types/commands.d.ts.map +1 -0
  358. package/dist/types/commands.js +1 -0
  359. package/dist/types/commands.js.map +1 -0
  360. package/dist/types/pipeline.d.ts.map +1 -0
  361. package/dist/types/pipeline.js +1 -0
  362. package/dist/types/pipeline.js.map +1 -0
  363. package/dist/types/streams.d.ts.map +1 -0
  364. package/dist/types/streams.js +1 -0
  365. package/dist/types/streams.js.map +1 -0
  366. package/dist/types/vfs.d.ts.map +1 -0
  367. package/dist/types/vfs.js +1 -0
  368. package/dist/types/vfs.js.map +1 -0
  369. package/dist/utils/expand.d.ts.map +1 -0
  370. package/dist/utils/expand.js +477 -0
  371. package/dist/utils/expand.js.map +1 -0
  372. package/dist/utils/perfLogger.d.ts.map +1 -0
  373. package/dist/utils/perfLogger.js +50 -0
  374. package/dist/utils/perfLogger.js.map +1 -0
  375. package/dist/utils/tokenize.d.ts.map +1 -0
  376. package/dist/utils/tokenize.js +115 -0
  377. package/dist/utils/tokenize.js.map +1 -0
  378. package/dist/utils/vfsDiff.d.ts.map +1 -0
  379. package/dist/utils/vfsDiff.js +178 -0
  380. package/dist/utils/vfsDiff.js.map +1 -0
  381. package/dist/web-api.d.ts.map +1 -0
  382. package/dist/web-api.js +47 -0
  383. package/dist/web-api.js.map +1 -0
  384. package/dist/web-full.d.ts.map +1 -0
  385. package/dist/web-full.js +9 -0
  386. package/dist/web-full.js.map +1 -0
  387. package/dist/web.d.ts.map +1 -0
  388. package/dist/web.js +774 -0
  389. package/dist/web.js.map +1 -0
  390. package/docs/.nojekyll +1 -0
  391. package/docs/assets/hierarchy.js +1 -0
  392. package/docs/assets/highlight.css +162 -0
  393. package/docs/assets/icons.js +18 -0
  394. package/docs/assets/icons.svg +1 -0
  395. package/docs/assets/main.js +60 -0
  396. package/docs/assets/navigation.js +1 -0
  397. package/docs/assets/search.js +1 -0
  398. package/docs/assets/style.css +1633 -0
  399. package/docs/classes/HoneyPot.html +31 -0
  400. package/docs/classes/SshClient.html +66 -0
  401. package/docs/classes/VirtualFileSystem.html +262 -0
  402. package/docs/classes/VirtualPackageManager.html +63 -0
  403. package/docs/classes/VirtualSftpServer.html +169 -0
  404. package/docs/classes/VirtualShell.html +265 -0
  405. package/docs/classes/VirtualSshServer.html +177 -0
  406. package/docs/classes/VirtualUserManager.html +276 -0
  407. package/docs/docs/.nojekyll +1 -0
  408. package/docs/docs/assets/hierarchy.js +1 -0
  409. package/docs/docs/assets/highlight.css +162 -0
  410. package/docs/docs/assets/icons.js +18 -0
  411. package/docs/docs/assets/icons.svg +1 -0
  412. package/docs/docs/assets/main.js +60 -0
  413. package/docs/docs/assets/navigation.js +1 -0
  414. package/docs/docs/assets/search.js +1 -0
  415. package/docs/docs/assets/style.css +1633 -0
  416. package/docs/docs/hierarchy.html +1 -0
  417. package/docs/docs/index.html +1842 -0
  418. package/docs/docs/media/LICENSE +21 -0
  419. package/docs/docs/modules.html +1 -0
  420. package/docs/functions/assertDiff.html +6 -0
  421. package/docs/functions/diffSnapshots.html +7 -0
  422. package/docs/functions/formatDiff.html +6 -0
  423. package/docs/functions/getArg.html +13 -0
  424. package/docs/functions/getFlag.html +15 -0
  425. package/docs/functions/ifFlag.html +11 -0
  426. package/docs/hierarchy.html +1 -0
  427. package/docs/index.html +1842 -0
  428. package/docs/interfaces/AuditLogEntry.html +6 -0
  429. package/docs/interfaces/CommandContext.html +22 -0
  430. package/docs/interfaces/CommandResult.html +26 -0
  431. package/docs/interfaces/ExecStream.html +11 -0
  432. package/docs/interfaces/HoneyPotStats.html +14 -0
  433. package/docs/interfaces/InstalledPackage.html +20 -0
  434. package/docs/interfaces/NanoEditorSession.html +8 -0
  435. package/docs/interfaces/PackageDefinition.html +30 -0
  436. package/docs/interfaces/PackageFile.html +8 -0
  437. package/docs/interfaces/RemoveOptions.html +4 -0
  438. package/docs/interfaces/ShellEnv.html +6 -0
  439. package/docs/interfaces/ShellModule.html +14 -0
  440. package/docs/interfaces/ShellProperties.html +14 -0
  441. package/docs/interfaces/ShellStream.html +11 -0
  442. package/docs/interfaces/SudoChallenge.html +24 -0
  443. package/docs/interfaces/VfsBaseNode.html +12 -0
  444. package/docs/interfaces/VfsDiff.html +10 -0
  445. package/docs/interfaces/VfsDiffEntry.html +6 -0
  446. package/docs/interfaces/VfsDiffModified.html +10 -0
  447. package/docs/interfaces/VfsDirectoryNode.html +15 -0
  448. package/docs/interfaces/VfsFileNode.html +17 -0
  449. package/docs/interfaces/VfsOptions.html +12 -0
  450. package/docs/interfaces/VfsSnapshot.html +3 -0
  451. package/docs/interfaces/VfsSnapshotBaseNode.html +8 -0
  452. package/docs/interfaces/VfsSnapshotDirectoryNode.html +10 -0
  453. package/docs/interfaces/VfsSnapshotFileNode.html +12 -0
  454. package/docs/interfaces/WriteFileOptions.html +6 -0
  455. package/docs/media/LICENSE +21 -0
  456. package/docs/modules.html +1 -0
  457. package/docs/types/CommandMode.html +2 -0
  458. package/docs/types/CommandOutcome.html +2 -0
  459. package/docs/types/VfsNodeStats.html +2 -0
  460. package/docs/types/VfsNodeType.html +2 -0
  461. package/docs/types/VfsPersistenceMode.html +5 -0
  462. package/docs/types/VfsSnapshotNode.html +2 -0
  463. package/examples/web.min.js +5 -5
  464. package/package.json +4 -2
  465. package/tsconfig.json +7 -2
  466. package/typedoc.json +8 -0
  467. package/src/Honeypot/index.d.ts.map +0 -1
  468. package/src/Honeypot/index.js +0 -298
  469. package/src/SSHClient/index.d.ts.map +0 -1
  470. package/src/SSHClient/index.js +0 -237
  471. package/src/SSHMimic/exec.d.ts.map +0 -1
  472. package/src/SSHMimic/exec.js +0 -27
  473. package/src/SSHMimic/executor.d.ts.map +0 -1
  474. package/src/SSHMimic/executor.js +0 -160
  475. package/src/SSHMimic/hostKey.d.ts.map +0 -1
  476. package/src/SSHMimic/hostKey.js +0 -17
  477. package/src/SSHMimic/index.d.ts.map +0 -1
  478. package/src/SSHMimic/index.js +0 -249
  479. package/src/SSHMimic/loginBanner.d.ts.map +0 -1
  480. package/src/SSHMimic/loginBanner.js +0 -22
  481. package/src/SSHMimic/loginFormat.d.ts.map +0 -1
  482. package/src/SSHMimic/loginFormat.js +0 -10
  483. package/src/SSHMimic/prompt.d.ts.map +0 -1
  484. package/src/SSHMimic/prompt.js +0 -9
  485. package/src/SSHMimic/sftp.d.ts.map +0 -1
  486. package/src/SSHMimic/sftp.js +0 -619
  487. package/src/VirtualFileSystem/binaryPack.d.ts.map +0 -1
  488. package/src/VirtualFileSystem/binaryPack.js +0 -216
  489. package/src/VirtualFileSystem/index.d.ts.map +0 -1
  490. package/src/VirtualFileSystem/index.js +0 -689
  491. package/src/VirtualFileSystem/internalTypes.d.ts.map +0 -1
  492. package/src/VirtualFileSystem/internalTypes.js +0 -0
  493. package/src/VirtualFileSystem/path.d.ts.map +0 -1
  494. package/src/VirtualFileSystem/path.js +0 -49
  495. package/src/VirtualPackageManager/index.d.ts.map +0 -1
  496. package/src/VirtualPackageManager/index.js +0 -853
  497. package/src/VirtualShell/index.d.ts.map +0 -1
  498. package/src/VirtualShell/index.js +0 -284
  499. package/src/VirtualShell/shell.d.ts.map +0 -1
  500. package/src/VirtualShell/shell.js +0 -502
  501. package/src/VirtualShell/shellParser.d.ts.map +0 -1
  502. package/src/VirtualShell/shellParser.js +0 -265
  503. package/src/VirtualUserManager/index.d.ts.map +0 -1
  504. package/src/VirtualUserManager/index.js +0 -607
  505. package/src/commands/adduser.d.ts.map +0 -1
  506. package/src/commands/adduser.js +0 -89
  507. package/src/commands/alias.d.ts.map +0 -1
  508. package/src/commands/alias.js +0 -68
  509. package/src/commands/apt.d.ts.map +0 -1
  510. package/src/commands/apt.js +0 -210
  511. package/src/commands/awk.d.ts.map +0 -1
  512. package/src/commands/awk.js +0 -169
  513. package/src/commands/base64.d.ts.map +0 -1
  514. package/src/commands/base64.js +0 -28
  515. package/src/commands/cat.d.ts.map +0 -1
  516. package/src/commands/cat.js +0 -44
  517. package/src/commands/cd.d.ts.map +0 -1
  518. package/src/commands/cd.js +0 -21
  519. package/src/commands/chmod.d.ts.map +0 -1
  520. package/src/commands/chmod.js +0 -87
  521. package/src/commands/clear.d.ts.map +0 -1
  522. package/src/commands/clear.js +0 -13
  523. package/src/commands/command-helpers.d.ts.map +0 -1
  524. package/src/commands/command-helpers.js +0 -221
  525. package/src/commands/cp.d.ts.map +0 -1
  526. package/src/commands/cp.js +0 -75
  527. package/src/commands/curl.d.ts.map +0 -1
  528. package/src/commands/curl.js +0 -127
  529. package/src/commands/cut.d.ts.map +0 -1
  530. package/src/commands/cut.js +0 -34
  531. package/src/commands/date.d.ts.map +0 -1
  532. package/src/commands/date.js +0 -28
  533. package/src/commands/declare.d.ts.map +0 -1
  534. package/src/commands/declare.js +0 -44
  535. package/src/commands/deluser.d.ts.map +0 -1
  536. package/src/commands/deluser.js +0 -83
  537. package/src/commands/df.d.ts.map +0 -1
  538. package/src/commands/df.js +0 -21
  539. package/src/commands/diff.d.ts.map +0 -1
  540. package/src/commands/diff.js +0 -45
  541. package/src/commands/dpkg.d.ts.map +0 -1
  542. package/src/commands/dpkg.js +0 -161
  543. package/src/commands/du.d.ts.map +0 -1
  544. package/src/commands/du.js +0 -50
  545. package/src/commands/echo.d.ts.map +0 -1
  546. package/src/commands/echo.js +0 -45
  547. package/src/commands/env.d.ts.map +0 -1
  548. package/src/commands/env.js +0 -20
  549. package/src/commands/exit.d.ts.map +0 -1
  550. package/src/commands/exit.js +0 -16
  551. package/src/commands/export.d.ts.map +0 -1
  552. package/src/commands/export.js +0 -33
  553. package/src/commands/find.d.ts.map +0 -1
  554. package/src/commands/find.js +0 -55
  555. package/src/commands/free.d.ts.map +0 -1
  556. package/src/commands/free.js +0 -43
  557. package/src/commands/grep.d.ts.map +0 -1
  558. package/src/commands/grep.js +0 -120
  559. package/src/commands/groups.d.ts.map +0 -1
  560. package/src/commands/groups.js +0 -17
  561. package/src/commands/gzip.d.ts.map +0 -1
  562. package/src/commands/gzip.js +0 -82
  563. package/src/commands/head.d.ts.map +0 -1
  564. package/src/commands/head.js +0 -46
  565. package/src/commands/help.d.ts.map +0 -1
  566. package/src/commands/help.js +0 -123
  567. package/src/commands/helpers.d.ts.map +0 -1
  568. package/src/commands/helpers.js +0 -166
  569. package/src/commands/history.d.ts.map +0 -1
  570. package/src/commands/history.js +0 -26
  571. package/src/commands/hostname.d.ts.map +0 -1
  572. package/src/commands/hostname.js +0 -12
  573. package/src/commands/htop.d.ts.map +0 -1
  574. package/src/commands/htop.js +0 -17
  575. package/src/commands/id.d.ts.map +0 -1
  576. package/src/commands/id.js +0 -17
  577. package/src/commands/index.d.ts.map +0 -1
  578. package/src/commands/index.js +0 -2
  579. package/src/commands/kill.d.ts.map +0 -1
  580. package/src/commands/kill.js +0 -18
  581. package/src/commands/ln.d.ts.map +0 -1
  582. package/src/commands/ln.js +0 -66
  583. package/src/commands/ls.d.ts.map +0 -1
  584. package/src/commands/ls.js +0 -200
  585. package/src/commands/lsb-release.d.ts.map +0 -1
  586. package/src/commands/lsb-release.js +0 -61
  587. package/src/commands/man.d.ts.map +0 -1
  588. package/src/commands/man.js +0 -49
  589. package/src/commands/mkdir.d.ts.map +0 -1
  590. package/src/commands/mkdir.js +0 -28
  591. package/src/commands/mv.d.ts.map +0 -1
  592. package/src/commands/mv.js +0 -42
  593. package/src/commands/nano.d.ts.map +0 -1
  594. package/src/commands/nano.js +0 -34
  595. package/src/commands/neofetch.d.ts.map +0 -1
  596. package/src/commands/neofetch.js +0 -48
  597. package/src/commands/node.d.ts.map +0 -1
  598. package/src/commands/node.js +0 -316
  599. package/src/commands/npm.d.ts.map +0 -1
  600. package/src/commands/npm.js +0 -109
  601. package/src/commands/passwd.d.ts.map +0 -1
  602. package/src/commands/passwd.js +0 -44
  603. package/src/commands/ping.d.ts.map +0 -1
  604. package/src/commands/ping.js +0 -28
  605. package/src/commands/printf.d.ts.map +0 -1
  606. package/src/commands/printf.js +0 -144
  607. package/src/commands/ps.d.ts.map +0 -1
  608. package/src/commands/ps.js +0 -46
  609. package/src/commands/pwd.d.ts.map +0 -1
  610. package/src/commands/pwd.js +0 -7
  611. package/src/commands/python.d.ts.map +0 -1
  612. package/src/commands/python.js +0 -2058
  613. package/src/commands/read.d.ts.map +0 -1
  614. package/src/commands/read.js +0 -39
  615. package/src/commands/registry.d.ts.map +0 -1
  616. package/src/commands/registry.js +0 -234
  617. package/src/commands/rm.d.ts.map +0 -1
  618. package/src/commands/rm.js +0 -36
  619. package/src/commands/runtime.d.ts.map +0 -1
  620. package/src/commands/runtime.js +0 -285
  621. package/src/commands/sed.d.ts.map +0 -1
  622. package/src/commands/sed.js +0 -60
  623. package/src/commands/seq.d.ts.map +0 -1
  624. package/src/commands/seq.js +0 -50
  625. package/src/commands/set.d.ts.map +0 -1
  626. package/src/commands/set.js +0 -26
  627. package/src/commands/sh.d.ts.map +0 -1
  628. package/src/commands/sh.js +0 -431
  629. package/src/commands/shift.d.ts.map +0 -1
  630. package/src/commands/shift.js +0 -62
  631. package/src/commands/sleep.d.ts.map +0 -1
  632. package/src/commands/sleep.js +0 -18
  633. package/src/commands/sort.d.ts.map +0 -1
  634. package/src/commands/sort.js +0 -44
  635. package/src/commands/source.d.ts.map +0 -1
  636. package/src/commands/source.js +0 -39
  637. package/src/commands/stat.d.ts.map +0 -1
  638. package/src/commands/stat.js +0 -56
  639. package/src/commands/su.d.ts.map +0 -1
  640. package/src/commands/su.js +0 -57
  641. package/src/commands/sudo.d.ts.map +0 -1
  642. package/src/commands/sudo.js +0 -54
  643. package/src/commands/tail.d.ts.map +0 -1
  644. package/src/commands/tail.js +0 -47
  645. package/src/commands/tar.d.ts.map +0 -1
  646. package/src/commands/tar.js +0 -102
  647. package/src/commands/tee.d.ts.map +0 -1
  648. package/src/commands/tee.js +0 -36
  649. package/src/commands/test.d.ts.map +0 -1
  650. package/src/commands/test.js +0 -114
  651. package/src/commands/touch.d.ts.map +0 -1
  652. package/src/commands/touch.js +0 -25
  653. package/src/commands/tr.d.ts.map +0 -1
  654. package/src/commands/tr.js +0 -61
  655. package/src/commands/tree.d.ts.map +0 -1
  656. package/src/commands/tree.js +0 -18
  657. package/src/commands/true.d.ts.map +0 -1
  658. package/src/commands/true.js +0 -24
  659. package/src/commands/type.d.ts.map +0 -1
  660. package/src/commands/type.js +0 -39
  661. package/src/commands/uname.d.ts.map +0 -1
  662. package/src/commands/uname.js +0 -29
  663. package/src/commands/uniq.d.ts.map +0 -1
  664. package/src/commands/uniq.js +0 -38
  665. package/src/commands/unset.d.ts.map +0 -1
  666. package/src/commands/unset.js +0 -16
  667. package/src/commands/uptime.d.ts.map +0 -1
  668. package/src/commands/uptime.js +0 -48
  669. package/src/commands/wc.d.ts.map +0 -1
  670. package/src/commands/wc.js +0 -55
  671. package/src/commands/wget.d.ts.map +0 -1
  672. package/src/commands/wget.js +0 -126
  673. package/src/commands/which.d.ts.map +0 -1
  674. package/src/commands/which.js +0 -32
  675. package/src/commands/who.d.ts.map +0 -1
  676. package/src/commands/who.js +0 -22
  677. package/src/commands/whoami.d.ts.map +0 -1
  678. package/src/commands/whoami.js +0 -12
  679. package/src/commands/xargs.d.ts.map +0 -1
  680. package/src/commands/xargs.js +0 -21
  681. package/src/index.d.ts.map +0 -1
  682. package/src/index.js +0 -9
  683. package/src/modules/linuxRootfs.d.ts.map +0 -1
  684. package/src/modules/linuxRootfs.js +0 -619
  685. package/src/modules/neofetch.d.ts.map +0 -1
  686. package/src/modules/neofetch.js +0 -284
  687. package/src/modules/shellInteractive.d.ts.map +0 -1
  688. package/src/modules/shellInteractive.js +0 -26
  689. package/src/modules/shellRuntime.d.ts.map +0 -1
  690. package/src/modules/shellRuntime.js +0 -52
  691. package/src/self-standalone.d.ts.map +0 -1
  692. package/src/self-standalone.js +0 -418
  693. package/src/standalone-wo-sftp.d.ts.map +0 -1
  694. package/src/standalone-wo-sftp.js +0 -30
  695. package/src/standalone.d.ts.map +0 -1
  696. package/src/standalone.js +0 -35
  697. package/src/types/commands.d.ts.map +0 -1
  698. package/src/types/commands.js +0 -0
  699. package/src/types/pipeline.d.ts.map +0 -1
  700. package/src/types/pipeline.js +0 -0
  701. package/src/types/streams.d.ts.map +0 -1
  702. package/src/types/streams.js +0 -0
  703. package/src/types/vfs.d.ts.map +0 -1
  704. package/src/types/vfs.js +0 -0
  705. package/src/utils/expand.d.ts.map +0 -1
  706. package/src/utils/expand.js +0 -476
  707. package/src/utils/perfLogger.d.ts.map +0 -1
  708. package/src/utils/perfLogger.js +0 -49
  709. package/src/utils/tokenize.d.ts.map +0 -1
  710. package/src/utils/tokenize.js +0 -114
  711. package/src/utils/vfsDiff.d.ts.map +0 -1
  712. package/src/utils/vfsDiff.js +0 -177
  713. package/src/web-api.d.ts.map +0 -1
  714. package/src/web-api.js +0 -46
  715. package/src/web-full.d.ts.map +0 -1
  716. package/src/web-full.js +0 -8
  717. package/src/web.d.ts.map +0 -1
  718. package/src/web.js +0 -773
  719. package/tests/command-helpers.test.d.ts +0 -2
  720. package/tests/command-helpers.test.d.ts.map +0 -1
  721. package/tests/command-helpers.test.js +0 -92
  722. package/tests/commands-admin-net.test.d.ts +0 -2
  723. package/tests/commands-admin-net.test.d.ts.map +0 -1
  724. package/tests/commands-admin-net.test.js +0 -353
  725. package/tests/commands-advanced.test.d.ts +0 -2
  726. package/tests/commands-advanced.test.d.ts.map +0 -1
  727. package/tests/commands-advanced.test.js +0 -378
  728. package/tests/commands-core.test.d.ts +0 -2
  729. package/tests/commands-core.test.d.ts.map +0 -1
  730. package/tests/commands-core.test.js +0 -477
  731. package/tests/commands-missing.test.d.ts +0 -2
  732. package/tests/commands-missing.test.d.ts.map +0 -1
  733. package/tests/commands-missing.test.js +0 -470
  734. package/tests/commands-specific-units.test.d.ts +0 -2
  735. package/tests/commands-specific-units.test.d.ts.map +0 -1
  736. package/tests/commands-specific-units.test.js +0 -264
  737. package/tests/commands-text-sys.test.d.ts +0 -2
  738. package/tests/commands-text-sys.test.d.ts.map +0 -1
  739. package/tests/commands-text-sys.test.js +0 -366
  740. package/tests/expand.test.d.ts +0 -2
  741. package/tests/expand.test.d.ts.map +0 -1
  742. package/tests/expand.test.js +0 -138
  743. package/tests/helpers.test.d.ts +0 -2
  744. package/tests/helpers.test.d.ts.map +0 -1
  745. package/tests/helpers.test.js +0 -52
  746. package/tests/new-features.test.d.ts +0 -2
  747. package/tests/new-features.test.d.ts.map +0 -1
  748. package/tests/new-features.test.js +0 -850
  749. package/tests/parser-executor.test.d.ts +0 -2
  750. package/tests/parser-executor.test.d.ts.map +0 -1
  751. package/tests/parser-executor.test.js +0 -25
  752. package/tests/sftp.test.d.ts +0 -2
  753. package/tests/sftp.test.d.ts.map +0 -1
  754. package/tests/sftp.test.js +0 -246
  755. package/tests/ssh-exec.test.d.ts +0 -2
  756. package/tests/ssh-exec.test.d.ts.map +0 -1
  757. package/tests/ssh-exec.test.js +0 -39
  758. package/tests/test-helper.d.ts +0 -56
  759. package/tests/test-helper.d.ts.map +0 -1
  760. package/tests/test-helper.js +0 -71
  761. package/tests/users.test.d.ts +0 -2
  762. package/tests/users.test.d.ts.map +0 -1
  763. package/tests/users.test.js +0 -71
  764. package/tests/web.test.d.ts +0 -2
  765. package/tests/web.test.d.ts.map +0 -1
  766. package/tests/web.test.js +0 -149
  767. /package/{src → dist}/Honeypot/index.d.ts +0 -0
  768. /package/{src → dist}/SSHClient/index.d.ts +0 -0
  769. /package/{src → dist}/SSHMimic/exec.d.ts +0 -0
  770. /package/{src → dist}/SSHMimic/executor.d.ts +0 -0
  771. /package/{src → dist}/SSHMimic/hostKey.d.ts +0 -0
  772. /package/{src → dist}/SSHMimic/index.d.ts +0 -0
  773. /package/{src → dist}/SSHMimic/loginBanner.d.ts +0 -0
  774. /package/{src → dist}/SSHMimic/loginFormat.d.ts +0 -0
  775. /package/{src → dist}/SSHMimic/prompt.d.ts +0 -0
  776. /package/{src → dist}/SSHMimic/sftp.d.ts +0 -0
  777. /package/{src → dist}/VirtualFileSystem/binaryPack.d.ts +0 -0
  778. /package/{src → dist}/VirtualFileSystem/index.d.ts +0 -0
  779. /package/{src → dist}/VirtualFileSystem/internalTypes.d.ts +0 -0
  780. /package/{src → dist}/VirtualFileSystem/path.d.ts +0 -0
  781. /package/{src → dist}/VirtualPackageManager/index.d.ts +0 -0
  782. /package/{src → dist}/VirtualShell/index.d.ts +0 -0
  783. /package/{src → dist}/VirtualShell/shell.d.ts +0 -0
  784. /package/{src → dist}/VirtualShell/shellParser.d.ts +0 -0
  785. /package/{src → dist}/VirtualUserManager/index.d.ts +0 -0
  786. /package/{src → dist}/commands/adduser.d.ts +0 -0
  787. /package/{src → dist}/commands/alias.d.ts +0 -0
  788. /package/{src → dist}/commands/apt.d.ts +0 -0
  789. /package/{src → dist}/commands/awk.d.ts +0 -0
  790. /package/{src → dist}/commands/base64.d.ts +0 -0
  791. /package/{src → dist}/commands/cat.d.ts +0 -0
  792. /package/{src → dist}/commands/cd.d.ts +0 -0
  793. /package/{src → dist}/commands/chmod.d.ts +0 -0
  794. /package/{src → dist}/commands/clear.d.ts +0 -0
  795. /package/{src → dist}/commands/command-helpers.d.ts +0 -0
  796. /package/{src → dist}/commands/cp.d.ts +0 -0
  797. /package/{src → dist}/commands/curl.d.ts +0 -0
  798. /package/{src → dist}/commands/cut.d.ts +0 -0
  799. /package/{src → dist}/commands/date.d.ts +0 -0
  800. /package/{src → dist}/commands/declare.d.ts +0 -0
  801. /package/{src → dist}/commands/deluser.d.ts +0 -0
  802. /package/{src → dist}/commands/df.d.ts +0 -0
  803. /package/{src → dist}/commands/diff.d.ts +0 -0
  804. /package/{src → dist}/commands/dpkg.d.ts +0 -0
  805. /package/{src → dist}/commands/du.d.ts +0 -0
  806. /package/{src → dist}/commands/echo.d.ts +0 -0
  807. /package/{src → dist}/commands/env.d.ts +0 -0
  808. /package/{src → dist}/commands/exit.d.ts +0 -0
  809. /package/{src → dist}/commands/export.d.ts +0 -0
  810. /package/{src → dist}/commands/find.d.ts +0 -0
  811. /package/{src → dist}/commands/free.d.ts +0 -0
  812. /package/{src → dist}/commands/grep.d.ts +0 -0
  813. /package/{src → dist}/commands/groups.d.ts +0 -0
  814. /package/{src → dist}/commands/gzip.d.ts +0 -0
  815. /package/{src → dist}/commands/head.d.ts +0 -0
  816. /package/{src → dist}/commands/help.d.ts +0 -0
  817. /package/{src → dist}/commands/helpers.d.ts +0 -0
  818. /package/{src → dist}/commands/history.d.ts +0 -0
  819. /package/{src → dist}/commands/hostname.d.ts +0 -0
  820. /package/{src → dist}/commands/htop.d.ts +0 -0
  821. /package/{src → dist}/commands/id.d.ts +0 -0
  822. /package/{src → dist}/commands/index.d.ts +0 -0
  823. /package/{src → dist}/commands/kill.d.ts +0 -0
  824. /package/{src → dist}/commands/ln.d.ts +0 -0
  825. /package/{src → dist}/commands/ls.d.ts +0 -0
  826. /package/{src → dist}/commands/lsb-release.d.ts +0 -0
  827. /package/{src → dist}/commands/man.d.ts +0 -0
  828. /package/{src → dist}/commands/mkdir.d.ts +0 -0
  829. /package/{src → dist}/commands/mv.d.ts +0 -0
  830. /package/{src → dist}/commands/nano.d.ts +0 -0
  831. /package/{src → dist}/commands/neofetch.d.ts +0 -0
  832. /package/{src → dist}/commands/node.d.ts +0 -0
  833. /package/{src → dist}/commands/npm.d.ts +0 -0
  834. /package/{src → dist}/commands/passwd.d.ts +0 -0
  835. /package/{src → dist}/commands/ping.d.ts +0 -0
  836. /package/{src → dist}/commands/printf.d.ts +0 -0
  837. /package/{src → dist}/commands/ps.d.ts +0 -0
  838. /package/{src → dist}/commands/pwd.d.ts +0 -0
  839. /package/{src → dist}/commands/python.d.ts +0 -0
  840. /package/{src → dist}/commands/read.d.ts +0 -0
  841. /package/{src → dist}/commands/registry.d.ts +0 -0
  842. /package/{src → dist}/commands/rm.d.ts +0 -0
  843. /package/{src → dist}/commands/runtime.d.ts +0 -0
  844. /package/{src → dist}/commands/sed.d.ts +0 -0
  845. /package/{src → dist}/commands/seq.d.ts +0 -0
  846. /package/{src → dist}/commands/set.d.ts +0 -0
  847. /package/{src → dist}/commands/sh.d.ts +0 -0
  848. /package/{src → dist}/commands/shift.d.ts +0 -0
  849. /package/{src → dist}/commands/sleep.d.ts +0 -0
  850. /package/{src → dist}/commands/sort.d.ts +0 -0
  851. /package/{src → dist}/commands/source.d.ts +0 -0
  852. /package/{src → dist}/commands/stat.d.ts +0 -0
  853. /package/{src → dist}/commands/su.d.ts +0 -0
  854. /package/{src → dist}/commands/sudo.d.ts +0 -0
  855. /package/{src → dist}/commands/tail.d.ts +0 -0
  856. /package/{src → dist}/commands/tar.d.ts +0 -0
  857. /package/{src → dist}/commands/tee.d.ts +0 -0
  858. /package/{src → dist}/commands/test.d.ts +0 -0
  859. /package/{src → dist}/commands/touch.d.ts +0 -0
  860. /package/{src → dist}/commands/tr.d.ts +0 -0
  861. /package/{src → dist}/commands/tree.d.ts +0 -0
  862. /package/{src → dist}/commands/true.d.ts +0 -0
  863. /package/{src → dist}/commands/type.d.ts +0 -0
  864. /package/{src → dist}/commands/uname.d.ts +0 -0
  865. /package/{src → dist}/commands/uniq.d.ts +0 -0
  866. /package/{src → dist}/commands/unset.d.ts +0 -0
  867. /package/{src → dist}/commands/uptime.d.ts +0 -0
  868. /package/{src → dist}/commands/wc.d.ts +0 -0
  869. /package/{src → dist}/commands/wget.d.ts +0 -0
  870. /package/{src → dist}/commands/which.d.ts +0 -0
  871. /package/{src → dist}/commands/who.d.ts +0 -0
  872. /package/{src → dist}/commands/whoami.d.ts +0 -0
  873. /package/{src → dist}/commands/xargs.d.ts +0 -0
  874. /package/{src → dist}/index.d.ts +0 -0
  875. /package/{src → dist}/modules/linuxRootfs.d.ts +0 -0
  876. /package/{src → dist}/modules/neofetch.d.ts +0 -0
  877. /package/{src → dist}/modules/shellInteractive.d.ts +0 -0
  878. /package/{src → dist}/modules/shellRuntime.d.ts +0 -0
  879. /package/{src → dist}/self-standalone.d.ts +0 -0
  880. /package/{src → dist}/standalone-wo-sftp.d.ts +0 -0
  881. /package/{src → dist}/standalone.d.ts +0 -0
  882. /package/{src → dist}/types/commands.d.ts +0 -0
  883. /package/{src → dist}/types/pipeline.d.ts +0 -0
  884. /package/{src → dist}/types/streams.d.ts +0 -0
  885. /package/{src → dist}/types/vfs.d.ts +0 -0
  886. /package/{src → dist}/utils/expand.d.ts +0 -0
  887. /package/{src → dist}/utils/perfLogger.d.ts +0 -0
  888. /package/{src → dist}/utils/tokenize.d.ts +0 -0
  889. /package/{src → dist}/utils/vfsDiff.d.ts +0 -0
  890. /package/{src → dist}/web-api.d.ts +0 -0
  891. /package/{src → dist}/web-full.d.ts +0 -0
  892. /package/{src → dist}/web.d.ts +0 -0
@@ -1,281 +1,330 @@
1
1
  #!/usr/bin/env node
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
- `,exitCode:1};let n=e[0];if(!n)return{stderr:`Usage: adduser <username>
4
- `,exitCode:1};if(t.users.listUsers().includes(n))return{stderr:`adduser: user '${n}' already exists
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
- `,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
- `,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(`
2
+ import{readFile as gi,unlink as yi,writeFile as Si}from"node:fs/promises";import*as ks from"node:path";import{basename as wi}from"node:path";import{stdin as ct,stdout as st}from"node:process";import{createInterface as xi}from"node:readline";var We={name:"adduser",description:"Add a new user",category:"users",params:["<username>"],run:({authUser:e,shell:t,args:n})=>{if(e!=="root")return{stderr:`adduser: permission denied
3
+ `,exitCode:1};let r=n[0];if(!r)return{stderr:`Usage: adduser <username>
4
+ `,exitCode:1};if(t.users.listUsers().includes(r))return{stderr:`adduser: user '${r}' already exists
5
+ `,exitCode:1};let o="",s="new";return{sudoChallenge:{username:r,targetUser:r,commandLine:null,loginShell:!1,prompt:"New password: ",mode:"passwd",onPassword:async(a,c)=>s==="new"?a.length<1?{result:{stderr:`adduser: password cannot be empty
6
+ `,exitCode:1}}:(o=a,s="retype",{result:null,nextPrompt:"Retype new password: "}):a!==o?{result:{stderr:`adduser: passwords do not match \u2014 user not created
7
+ `,exitCode:1}}:(await c.users.addUser(r,o),{result:{stdout:`${[`Adding user '${r}' ...`,`Adding new group '${r}' (1001) ...`,`Adding new user '${r}' (1001) with group '${r}' ...`,`Creating home directory '/home/${r}' ...`,`passwd: password set for '${r}'`,"adduser: done."].join(`
8
8
  `)}
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
- `)||"",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}}},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
- 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(`
9
+ `,exitCode:0}})},exitCode:0}}};function je(e){return Array.isArray(e)?e:[e]}function Gt(e,t){if(e===t)return{matched:!0,inlineValue:null};let n=`${t}=`;return e.startsWith(n)?{matched:!0,inlineValue:e.slice(n.length)}:t.length===2&&t.startsWith("-")&&!t.startsWith("--")&&e.startsWith(t)&&e.length>t.length?{matched:!0,inlineValue:e.slice(t.length)}:{matched:!1,inlineValue:null}}function Ms(e,t={}){let n=new Set(t.flags??[]),r=new Set(t.flagsWithValue??[]),o=[],s=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(s){o.push(a);continue}if(a==="--"){s=!0;continue}let c=!1;for(let l of n){let{matched:u}=Gt(a,l);if(u){c=!0;break}}if(!c){for(let l of r){let u=Gt(a,l);if(u.matched){c=!0,u.inlineValue===null&&i+1<e.length&&(i+=1);break}}c||o.push(a)}}return o}function w(e,t){let n=je(t);for(let r of e)for(let o of n)if(Gt(r,o).matched)return!0;return!1}function it(e,t){let n=je(t);for(let r=0;r<e.length;r+=1){let o=e[r];for(let s of n){let i=Gt(o,s);if(!i.matched)continue;if(i.inlineValue!==null)return i.inlineValue;let a=e[r+1];return a!==void 0&&a!=="--"?a:!0}}}function bt(e,t,n={}){return Ms(e,n)[t]}function ot(e,t={}){let n=new Set,r=new Map,o=[],s=new Set(t.flags??[]),i=new Set(t.flagsWithValue??[]),a=!1;for(let c=0;c<e.length;c+=1){let l=e[c];if(a){o.push(l);continue}if(l==="--"){a=!0;continue}if(s.has(l)){n.add(l);continue}if(i.has(l)){let d=e[c+1];d&&!d.startsWith("-")?(r.set(l,d),c+=1):r.set(l,"");continue}let u=Array.from(i).find(d=>l.startsWith(`${d}=`));if(u){r.set(u,l.slice(u.length+1));continue}o.push(l)}return{flags:n,flagsWithValues:r,positionals:o}}var He={name:"alias",description:"Define or display aliases",category:"shell",params:["[name[=value] ...]"],run:({args:e,env:t})=>{if(!t)return{exitCode:0};if(e.length===0)return{stdout:Object.entries(t.vars).filter(([o])=>o.startsWith("__alias_")).map(([o,s])=>`alias ${o.slice(8)}='${s}'`).join(`
10
+ `)||"",exitCode:0};let n=[];for(let r of e){let o=r.indexOf("=");if(o===-1){let s=t.vars[`__alias_${r}`];if(s)n.push(`alias ${r}='${s}'`);else return{stderr:`alias: ${r}: not found`,exitCode:1}}else{let s=r.slice(0,o),i=r.slice(o+1).replace(/^['"]|['"]$/g,"");t.vars[`__alias_${s}`]=i}}return{stdout:n.join(`
11
+ `)||void 0,exitCode:0}}},qe={name:"unalias",description:"Remove alias definitions",category:"shell",params:["<name...> | -a"],run:({args:e,env:t})=>{if(!t)return{exitCode:0};if(w(e,["-a"])){for(let n of Object.keys(t.vars))n.startsWith("__alias_")&&delete t.vars[n];return{exitCode:0}}for(let n of e)delete t.vars[`__alias_${n}`];return{exitCode:0}}};import*as dt from"node:path";var As=["/.virtual-env-js/.auth","/etc/htpasswd"];function k(e,t){return!t||t.trim()===""?e:t.startsWith("~")?dt.posix.normalize(`/home/${t.slice(1)}`):t.startsWith("/")?dt.posix.normalize(t):dt.posix.normalize(dt.posix.join(e,t))}function Es(e){let t=e.startsWith("/")?dt.posix.normalize(e):dt.posix.normalize(`/${e}`);return As.some(n=>t===n||t.startsWith(`${n}/`))}function z(e,t,n){if(e!=="root"&&Es(t))throw new Error(`${n}: permission denied: ${t}`)}function Ke(e){let n=(e.split("?")[0]?.split("#")[0]??e).split("/").filter(Boolean).pop();return n&&n.length>0?n:"index.html"}function Fs(e,t){let n=Array.from({length:e.length+1},()=>Array(t.length+1).fill(0));for(let r=0;r<=e.length;r+=1)n[r][0]=r;for(let r=0;r<=t.length;r+=1)n[0][r]=r;for(let r=1;r<=e.length;r+=1)for(let o=1;o<=t.length;o+=1){let s=e[r-1]===t[o-1]?0:1;n[r][o]=Math.min(n[r-1][o]+1,n[r][o-1]+1,n[r-1][o-1]+s)}return n[e.length][t.length]}function Ge(e,t,n){let r=k(t,n);if(e.exists(r))return r;let o=dt.posix.dirname(r),s=dt.posix.basename(r),i=e.list(o),a=i.filter(l=>l.toLowerCase()===s.toLowerCase());if(a.length===1)return dt.posix.join(o,a[0]);let c=i.filter(l=>Fs(l.toLowerCase(),s.toLowerCase())<=1);return c.length===1?dt.posix.join(o,c[0]):r}function Mt(e){return e.packageManager}var Ze={name:"apt",aliases:["apt-get"],description:"Package manager",category:"package",params:["<install|remove|update|upgrade|search|show|list> [pkg...]"],run:({args:e,shell:t,authUser:n})=>{let r=Mt(t);if(!r)return{stderr:"apt: package manager not initialised",exitCode:1};let o=e[0]?.toLowerCase(),s=e.slice(1),i=w(s,["-q","--quiet","-qq"]),a=w(s,["--purge"]),c=s.filter(u=>!u.startsWith("-"));if(["install","remove","purge","upgrade","update"].includes(o??"")&&n!=="root")return{stderr:`E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
12
+ E: Unable to acquire the dpkg frontend lock, are you root?`,exitCode:100};switch(o){case"install":{if(c.length===0)return{stderr:"apt: no packages specified",exitCode:1};let{output:u,exitCode:d}=r.install(c,{quiet:i});return{stdout:u||void 0,exitCode:d}}case"remove":case"purge":{if(c.length===0)return{stderr:"apt: no packages specified",exitCode:1};let{output:u,exitCode:d}=r.remove(c,{purge:o==="purge"||a,quiet:i});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
- `),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
14
+ `),exitCode:0};case"search":{let u=c[0];if(!u)return{stderr:"apt: search requires a term",exitCode:1};let d=r.search(u);return d.length===0?{stdout:`Sorting... Done
15
15
  Full Text Search... Done
16
16
  (no results)`,exitCode:0}:{stdout:`Sorting... 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(w(s,["--installed"])){let p=n.listInstalled();return p.length===0?{stdout:`Listing... Done
20
+ `)}`,exitCode:0}}case"show":{let u=c[0];if(!u)return{stderr:"apt: show requires a package name",exitCode:1};let d=r.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=r.listInstalled();return p.length===0?{stdout:`Listing... Done
21
21
  (no packages installed)`,exitCode:0}:{stdout:`Listing... Done
22
- ${p.map(g=>`${g.name}/${g.section} ${g.version} ${g.architecture} [installed]`).join(`
22
+ ${p.map(y=>`${y.name}/${y.section} ${y.version} ${y.architecture} [installed]`).join(`
23
23
  `)}`,exitCode:0}}return{stdout:`Listing... Done
24
- ${n.listAvailable().map(p=>`${p.name}/${p.section??"misc"} ${p.version} amd64`).join(`
24
+ ${r.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}}}},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
- `)||"(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 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(`
26
+ `),exitCode:0}}}},Je={name:"apt-cache",description:"Query the package cache",category:"package",params:["<search|show|policy> [pkg]"],run:({args:e,shell:t})=>{let n=Mt(t);if(!n)return{stderr:"apt-cache: package manager not initialised",exitCode:1};let r=e[0]?.toLowerCase(),o=e[1];switch(r){case"search":return o?{stdout:n.search(o).map(i=>`${i.name} - ${i.shortDesc??i.description}`).join(`
27
+ `)||"(no results)",exitCode:0}:{stderr:"Need a search term",exitCode:1};case"show":{if(!o)return{stderr:"Need a package name",exitCode:1};let s=n.show(o);return s?{stdout:s,exitCode:0}:{stderr:`N: Unable to locate package ${o}`,exitCode:100}}case"policy":{if(!o)return{stderr:"Need a package name",exitCode:1};let s=n.findInRegistry(o);if(!s)return{stderr:`N: Unable to locate package ${o}`,exitCode:100};let i=n.isInstalled(o);return{stdout:[`${o}:`,` Installed: ${i?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 '${r??""}'`,exitCode:1}}}};var Ye={name:"awk",description:"Pattern scanning and processing language",category:"text",params:["[-F <sep>] '<program>' [file]"],run:({authUser:e,args:t,stdin:n,cwd:r,shell:o})=>{let s=it(t,["-F"])??" ",i=t.filter(x=>!x.startsWith("-")&&x!==s),a=i[0],c=i[1];if(!a)return{stderr:"awk: no program",exitCode:1};let l=n??"";if(c){let x=k(r,c);try{z(e,x,"awk"),l=o.vfs.readFile(x)}catch{return{stderr:`awk: ${c}: No such file or directory`,exitCode:1}}}let u=l.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,A=x.exec(m);for(;A!==null;)d.push({pattern:A[1].trim(),action:A[2].trim()}),A=x.exec(m);d.length===0&&d.push({pattern:"",action:m.replace(/[{}]/g,"").trim()})}let p=[],h=d.find(x=>x.pattern==="BEGIN"),y=d.find(x=>x.pattern==="END"),f=d.filter(x=>x.pattern!=="BEGIN"&&x.pattern!=="END");function S(x){return s===" "?x.trim().split(/\s+/).filter(Boolean):x.split(s)}function F(x,A,N){let b=S(A),M=b.length,R=C=>{if(C=C.trim(),C==="NR")return String(N);if(C==="NF")return String(M);if(C==="$0")return A;if(C==="$NF")return b[M-1]??"";if(/^\$\d+$/.test(C))return b[parseInt(C.slice(1),10)-1]??"";let I=C.replace(/\bNR\b/g,String(N)).replace(/\bNF\b/g,String(M));if(/^[\d\s+\-*/()]+$/.test(I))try{return String(Function(`"use strict"; return (${I});`)())}catch{}return C.replace(/"/g,"")},P=x.split(";").map(C=>C.trim()).filter(Boolean);for(let C of P)if(C==="print"||C==="print $0")p.push(A);else if(C.startsWith("print ")){let I=C.slice(6).split(/\s*,\s*/);p.push(I.map(R).join(" "))}}function E(x,A,N){if(!x||x==="1")return!0;let b=x.match(/^NR\s*([=!<>]=?|==)\s*(\d+)$/);if(b){let P=b[1],C=parseInt(b[2],10);switch(P){case"==":return N===C;case"!=":return N!==C;case">":return N>C;case">=":return N>=C;case"<":return N<C;case"<=":return N<=C}}let M=x.match(/^NR%(\d+)==(\d+)$/);if(M)return N%parseInt(M[1],10)===parseInt(M[2],10);if(x.startsWith("/")&&x.endsWith("/"))try{return new RegExp(x.slice(1,-1)).test(A)}catch{return!1}let R=x.match(/^\$(\d+)~\/(.*)\/$/);if(R){let C=S(A)[parseInt(R[1],10)-1]??"";try{return new RegExp(R[2]).test(C)}catch{return!1}}return!1}h&&F(h.action,"",0);for(let x=1;x<=u.length;x++){let A=u[x-1];for(let N of f)E(N.pattern,A,x)&&F(N.action,A,x)}return y&&F(y.action,"",u.length+1),{stdout:p.join(`
30
30
  `)+(p.length>0?`
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
- `).map(m=>o&&m.trim()===""?m:`${String(u++).padStart(6)} ${m}`).join(`
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
31
+ `:""),exitCode:0}}};var Qe={name:"base64",description:"Encode/decode base64",category:"text",params:["[-d] [file]"],run:({args:e,stdin:t})=>{let n=w(e,["-d","--decode"]),r=t??"";if(n)try{return{stdout:Buffer.from(r.trim(),"base64").toString("utf8"),exitCode:0}}catch{return{stderr:"base64: invalid input",exitCode:1}}return{stdout:Buffer.from(r).toString("base64"),exitCode:0}}};var Xe={name:"cat",description:"Concatenate and print files",category:"files",params:["[-n] [-b] <file...>"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let s=w(r,["-n","--number"]),i=w(r,["-b","--number-nonblank"]),a=r.filter(m=>!m.startsWith("-"));if(a.length===0&&o!==void 0)return{stdout:o,exitCode:0};if(a.length===0)return{stderr:"cat: missing file operand",exitCode:1};let c=[];for(let m of a){let p=Ge(t.vfs,n,m);z(e,p,"cat"),c.push(t.vfs.readFile(p))}let l=c.join("");if(!s&&!i)return{stdout:l,exitCode:0};let u=1;return{stdout:l.split(`
32
+ `).map(m=>i&&m.trim()===""?m:`${String(u++).padStart(6)} ${m}`).join(`
33
+ `),exitCode:0}}};var tn={name:"cd",description:"Change directory",category:"navigation",params:["[path]"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=k(n,r[0]??"~");return z(e,o,"cd"),t.vfs.stat(o).type!=="directory"?{stderr:`cd: not a directory: ${o}`,exitCode:1}:{nextCwd:o,exitCode:0}}};function Ns(e,t){let n=/^([ugoa]*)([+\-=])([rwx]*)$/,r=t.split(","),o=e;for(let s of r){let i=s.trim().match(n);if(!i)return null;let[,a="a",c,l=""]=i,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 l.split("")){let h=d[m]?.[p];if(h!==void 0){if(c==="+")o|=h;else if(c==="-")o&=~h;else if(c==="="){let y=Object.values(d[m]??{}).reduce((f,S)=>f|S,0);o=o&~y|h}}}}return o}var en={name:"chmod",description:"Change file permissions",category:"files",params:["<mode> <file>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let[o,s]=r;if(!o||!s)return{stderr:"chmod: missing operand",exitCode:1};let i=k(n,s);try{if(z(e,i,"chmod"),!t.vfs.exists(i))return{stderr:`chmod: ${s}: No such file or directory`,exitCode:1};let a,c=parseInt(o,8);if(!Number.isNaN(c)&&/^[0-7]+$/.test(o))a=c;else{let l=t.vfs.stat(i).mode,u=Ns(l,o);if(u===null)return{stderr:`chmod: invalid mode: ${o}`,exitCode:1};a=u}return t.vfs.chmod(i,a),{exitCode:0}}catch(a){return{stderr:`chmod: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}}};var nn={name:"clear",description:"Clear the terminal screen",category:"shell",params:[],run:()=>({clearScreen:!0,stdout:"",exitCode:0})};var rn={name:"cp",description:"Copy files or directories",category:"files",params:["[-r] <source> <dest>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=w(r,["-r","-R","--recursive"]),s=r.filter(u=>!u.startsWith("-")),[i,a]=s;if(!i||!a)return{stderr:"cp: missing operand",exitCode:1};let c=k(n,i),l=k(n,a);try{if(z(e,c,"cp"),z(e,l,"cp"),!t.vfs.exists(c))return{stderr:`cp: ${i}: No such file or directory`,exitCode:1};if(t.vfs.stat(c).type==="directory"){if(!o)return{stderr:`cp: ${i}: is a directory (use -r)`,exitCode:1};let d=(p,h)=>{t.vfs.mkdir(h,493);for(let y of t.vfs.list(p)){let f=`${p}/${y}`,S=`${h}/${y}`;if(t.vfs.stat(f).type==="directory")d(f,S);else{let E=t.vfs.readFileRaw(f);t.writeFileAsUser(e,S,E)}}},m=t.vfs.exists(l)&&t.vfs.stat(l).type==="directory"?`${l}/${i.split("/").pop()}`:l;d(c,m)}else{let d=t.vfs.exists(l)&&t.vfs.stat(l).type==="directory"?`${l}/${i.split("/").pop()}`:l,m=t.vfs.readFileRaw(c);t.writeFileAsUser(e,d,m)}return{exitCode:0}}catch(u){return{stderr:`cp: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}};var sn={name:"curl",description:"Transfer data from or to a server (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:e,cwd:t,args:n,shell:r})=>{let{flagsWithValues:o,positionals:s}=ot(n,{flagsWithValue:["-o","--output","-X","--request","-d","--data","-H","--header","-u","--user"]});if(w(n,["--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 i=s[0];if(!i)return{stderr:"curl: no URL specified",exitCode:1};let a=o.get("-o")??o.get("--output")??null,c=(o.get("-X")??o.get("--request")??"GET").toUpperCase(),l=o.get("-d")??o.get("--data")??null,u=o.get("-H")??o.get("--header")??null,d=w(n,["-s","--silent"]),m=w(n,["-I","--head"]),p=w(n,["-L","--location"]),h=w(n,["-v","--verbose"]),y={"User-Agent":"curl/7.88.1"};if(u){let A=u.indexOf(":");A!==-1&&(y[u.slice(0,A).trim()]=u.slice(A+1).trim())}let f=l&&c==="GET"?"POST":c,S={method:f,headers:y,redirect:p?"follow":"manual"};l&&(y["Content-Type"]??="application/x-www-form-urlencoded",S.body=l);let F=[];h&&(F.push(`* Trying ${i}...`,"* Connected"),F.push(`> ${f} / HTTP/1.1`,`> Host: ${new URL(i).host}`));let E;try{let A=i.startsWith("http://")||i.startsWith("https://")?i:`http://${i}`;E=await fetch(A,S)}catch(A){return{stderr:`curl: (6) Could not resolve host: ${A instanceof Error?A.message:String(A)}`,exitCode:6}}if(h&&F.push(`< HTTP/1.1 ${E.status} ${E.statusText}`),m){let A=[`HTTP/1.1 ${E.status} ${E.statusText}`];for(let[N,b]of E.headers.entries())A.push(`${N}: ${b}`);return{stdout:`${A.join(`\r
35
35
  `)}\r
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
- `).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 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
- `,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
- `,exitCode:1};if(!e.users.listUsers().includes(i))return{stderr:`deluser: user '${i}' does not exist
45
- `,exitCode:1};if(i==="root")return{stderr:`deluser: cannot remove the root account
46
- `,exitCode:1};if(n)return await e.users.deleteUser(i),{stdout:`Removing user '${i}' ...
36
+ `,exitCode:0}}let x;try{x=await E.text()}catch{return{stderr:"curl: failed to read response body",exitCode:1}}if(a){let A=k(t,a);return z(e,A,"curl"),r.writeFileAsUser(e,A,x),d||F.push(` % Total % Received
37
+ 100 ${x.length} 100 ${x.length}`),{stderr:F.join(`
38
+ `)||void 0,exitCode:E.ok?0:22}}return{stdout:x,stderr:F.length>0?F.join(`
39
+ `):void 0,exitCode:E.ok?0:22}}};var on={name:"cut",description:"Remove sections from lines",category:"text",params:["-d <delim> -f <fields> [file]"],run:({args:e,stdin:t})=>{let n=it(e,["-d"])??" ",o=(it(e,["-f"])??"1").split(",").map(a=>{let[c,l]=a.split("-").map(Number);return l!==void 0?{from:(c??1)-1,to:l-1}:{from:(c??1)-1,to:(c??1)-1}});return{stdout:(t??"").split(`
40
+ `).map(a=>{let c=a.split(n),l=[];for(let u of o)for(let d=u.from;d<=Math.min(u.to,c.length-1);d++)l.push(c[d]??"");return l.join(n)}).join(`
41
+ `),exitCode:0}}};var an={name:"date",description:"Print current date and time",category:"system",params:["[+format]"],run:({args:e})=>{let t=new Date,n=e[0];return n?.startsWith("+")?{stdout:n.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 cn={name:"declare",aliases:["local","typeset"],description:"Declare variables and give them attributes",category:"shell",params:["[-i] [-r] [-x] [-a] [name[=value]...]"],run:({args:e,env:t})=>{if(!t)return{exitCode:0};let n=w(e,["-i"]),r=w(e,["-r"]),o=w(e,["-x"]);if(e.filter(a=>!a.startsWith("-")).length===0)return{stdout:Object.entries(t.vars).map(([c,l])=>`declare -- ${c}="${l}"`).join(`
42
+ `),exitCode:0};let i=e.filter(a=>!a.startsWith("-"));for(let a of i){let c=a.indexOf("=");if(c===-1)a in t.vars||(t.vars[a]="");else{let l=a.slice(0,c),u=a.slice(c+1);if(n){let d=parseInt(u,10);u=Number.isNaN(d)?"0":String(d)}t.vars[l]=u}}return{exitCode:0}}};var ln={name:"deluser",description:"Delete a user",category:"users",params:["[-f] <username>"],run:async({authUser:e,args:t,shell:n})=>{if(e!=="root")return{stderr:`deluser: permission denied
43
+ `,exitCode:1};let r=t.includes("-f")||t.includes("--force")||t.includes("-y"),o=t.find(i=>!i.startsWith("-"));if(!o)return{stderr:`Usage: deluser [-f] <username>
44
+ `,exitCode:1};if(!n.users.listUsers().includes(o))return{stderr:`deluser: user '${o}' does not exist
45
+ `,exitCode:1};if(o==="root")return{stderr:`deluser: cannot remove the root account
46
+ `,exitCode:1};if(r)return await n.users.deleteUser(o),{stdout:`Removing user '${o}' ...
47
47
  deluser: done.
48
- `,exitCode:0};let s=async(o,a)=>o.trim()!==i?{result:{stderr:`deluser: confirmation did not match \u2014 user not deleted
49
- `,exitCode:1}}:(await a.users.deleteUser(i),{result:{stdout:`Removing user '${i}' ...
48
+ `,exitCode:0};let s=async(i,a)=>i.trim()!==o?{result:{stderr:`deluser: confirmation did not match \u2014 user not deleted
49
+ `,exitCode:1}}:(await a.users.deleteUser(o),{result:{stdout:`Removing user '${o}' ...
50
50
  deluser: done.
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 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
- `)}catch{return{stderr:`diff: ${n}: No such file or directory`,exitCode:2}}try{l=r.vfs.readFile(o).split(`
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 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
- `),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
- `),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}}},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
- `),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 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(`
51
+ `,exitCode:0}});return{sudoChallenge:{username:o,targetUser:o,commandLine:null,loginShell:!1,prompt:`Warning: deleting user '${o}'.
52
+ Type the username to confirm: `,mode:"confirm",onPassword:s},exitCode:0}}};var un={name:"df",description:"Report filesystem disk space usage",category:"system",params:["[-h]"],run:({shell:e})=>{let n=(e.vfs.getUsageBytes()/1024).toFixed(0),r="1048576",o=String(Number(r)-Number(n)),s=Math.round(Number(n)/Number(r)*100),i="Filesystem 1K-blocks Used Available Use% Mounted on",a=`virtual-fs ${r.padStart(9)} ${n.padStart(7)} ${o.padStart(9)} ${s}% /`;return{stdout:`${i}
53
+ ${a}`,exitCode:0}}};var dn={name:"diff",description:"Compare files line by line",category:"text",params:["<file1> <file2>"],run:({shell:e,cwd:t,args:n})=>{let[r,o]=n;if(!r||!o)return{stderr:"diff: missing operand",exitCode:1};let s=k(t,r),i=k(t,o),a,c;try{a=e.vfs.readFile(s).split(`
54
+ `)}catch{return{stderr:`diff: ${r}: No such file or directory`,exitCode:2}}try{c=e.vfs.readFile(i).split(`
55
+ `)}catch{return{stderr:`diff: ${o}: No such file or directory`,exitCode:2}}let l=[],u=Math.max(a.length,c.length);for(let d=0;d<u;d++){let m=a[d],p=c[d];m!==p&&(m!==void 0&&l.push(`< ${m}`),p!==void 0&&l.push(`> ${p}`))}return{stdout:l.join(`
56
+ `),exitCode:l.length>0?1:0}}};var mn={name:"dpkg",description:"Debian package manager low-level tool",category:"package",params:["[-l] [-s pkg] [-L pkg] [-i pkg] [--remove pkg]"],run:({args:e,authUser:t,shell:n})=>{let r=Mt(n);if(!r)return{stderr:"dpkg: package manager not initialised",exitCode:1};let o=w(e,["-l","--list"]),s=w(e,["-s","--status"]),i=w(e,["-L","--listfiles"]),a=w(e,["-r","--remove"]),c=w(e,["-P","--purge"]),{positionals:l}=ot(e,{flags:["-l","--list","-s","--status","-L","--listfiles","-r","--remove","-P","--purge"]});if(o){let u=r.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 h=p.name.padEnd(14).slice(0,14),y=p.version.padEnd(15).slice(0,15),f=p.architecture.padEnd(12).slice(0,12),S=(p.description||"").slice(0,40);return`ii ${h} ${y} ${f} ${S}`});return{stdout:[...d,...m].join(`
58
+ `),exitCode:0}}if(s){let u=l[0];if(!u)return{stderr:"dpkg: -s needs a package name",exitCode:1};let d=r.show(u);return d?{stdout:d,exitCode:0}:{stderr:`dpkg-query: package '${u}' is not installed and no information is available`,exitCode:1}}if(i){let u=l[0];if(!u)return{stderr:"dpkg: -L needs a package name",exitCode:1};let d=r.listInstalled().find(m=>m.name===u);return d?d.files.length===0?{stdout:"/.keep",exitCode:0}:{stdout:d.files.join(`
59
+ `),exitCode:0}:{stderr:`dpkg-query: package '${u}' is not installed`,exitCode:1}}if(a||c){if(t!=="root")return{stderr:"dpkg: error: requested operation requires superuser privilege",exitCode:2};if(l.length===0)return{stderr:"dpkg: error: need an action option",exitCode:2};let{output:u,exitCode:d}=r.remove(l,{purge:c});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}}},pn={name:"dpkg-query",description:"Show information about installed packages",category:"package",params:["-W [pkg] | -l [pattern]"],run:({args:e,shell:t})=>{let n=Mt(t);if(!n)return{stderr:"dpkg-query: package manager not initialised",exitCode:1};let r=w(e,["-l"]),o=w(e,["-W","--show"]),{positionals:s}=ot(e,{flags:["-l","-W","--show"]});if(r||o){let i=n.listInstalled(),a=s[0],c=a?i.filter(u=>u.name.includes(a)):i;return o?{stdout:c.map(u=>`${u.name} ${u.version}`).join(`
61
+ `),exitCode:0}:{stdout:c.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 fn={name:"du",description:"Estimate file space usage",category:"system",params:["[-h] [-s] [path]"],run:({shell:e,cwd:t,args:n})=>{let r=w(n,["-h"]),o=w(n,["-s"]),s=n.find(u=>!u.startsWith("-"))??".",i=k(t,s),a=u=>r?`${(u/1024).toFixed(1)}K`:String(Math.ceil(u/1024));if(!e.vfs.exists(i))return{stderr:`du: ${s}: No such file or directory`,exitCode:1};if(o||e.vfs.stat(i).type==="file")return{stdout:`${a(e.vfs.getUsageBytes(i))} ${s}`,exitCode:0};let c=[],l=(u,d)=>{let m=0;for(let p of e.vfs.list(u)){let h=`${u}/${p}`,y=`${d}/${p}`,f=e.vfs.stat(h);f.type==="directory"?m+=l(h,y):(m+=f.size,o||c.push(`${a(f.size)} ${y}`))}return c.push(`${a(m)} ${d}`),m};return l(i,s),{stdout:c.join(`
63
+ `),exitCode:0}}};function _s(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(/\s/.test(o)){r++;continue}if(o==="+"){n.push({type:"plus"}),r++;continue}if(o==="-"){n.push({type:"minus"}),r++;continue}if(o==="*"){if(e[r+1]==="*"){n.push({type:"pow"}),r+=2;continue}n.push({type:"mul"}),r++;continue}if(o==="/"){n.push({type:"div"}),r++;continue}if(o==="%"){n.push({type:"mod"}),r++;continue}if(o==="("){n.push({type:"lparen"}),r++;continue}if(o===")"){n.push({type:"rparen"}),r++;continue}if(/\d/.test(o)){let s=r+1;for(;s<e.length&&/\d/.test(e[s]);)s++;n.push({type:"number",value:Number(e.slice(r,s))}),r=s;continue}if(/[A-Za-z_]/.test(o)){let s=r+1;for(;s<e.length&&/[A-Za-z0-9_]/.test(e[s]);)s++;let i=e.slice(r,s),a=t[i],c=a===void 0||a===""?0:Number(a);n.push({type:"number",value:Number.isFinite(c)?c:0}),r=s;continue}return[]}return n}function xe(e,t){let n=e.trim();if(n.length===0||n.length>1024)return NaN;let r=_s(n,t);if(r.length===0)return NaN;let o=0,s=()=>r[o],i=()=>r[o++],a=()=>{let p=i();if(!p)return NaN;if(p.type==="number")return p.value;if(p.type==="lparen"){let h=d();return r[o]?.type!=="rparen"?NaN:(o++,h)}return NaN},c=()=>{let p=s();return p?.type==="plus"?(i(),c()):p?.type==="minus"?(i(),-c()):a()},l=()=>{let p=c();for(;s()?.type==="pow";){i();let h=c();p=p**h}return p},u=()=>{let p=l();for(;;){let h=s();if(h?.type==="mul"){i(),p*=l();continue}if(h?.type==="div"){i();let y=l();p=y===0?NaN:p/y;continue}if(h?.type==="mod"){i();let y=l();p=y===0?NaN:p%y;continue}return p}},d=()=>{let p=u();for(;;){let h=s();if(h?.type==="plus"){i(),p+=u();continue}if(h?.type==="minus"){i(),p-=u();continue}return p}},m=d();return!Number.isFinite(m)||o!==r.length?NaN:Math.trunc(m)}function Is(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("'",r);if(o===-1){n.push(t(e.slice(r)));break}n.push(t(e.slice(r,o)));let s=e.indexOf("'",o+1);if(s===-1){n.push(e.slice(o));break}n.push(e.slice(o,s+1)),r=s+1}return n.join("")}function Jt(e){function r(o,s){if(s>8)return[o];let i=0,a=-1;for(let c=0;c<o.length;c++){let l=o[c];if(l==="{"&&o[c-1]!=="$")i===0&&(a=c),i++;else if(l==="}"&&(i--,i===0&&a!==-1)){let u=o.slice(0,a),d=o.slice(a+1,c),m=o.slice(c+1),p=d.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.-?(\d+))?$/)||d.match(/^([a-z])\.\.([a-z])$/);if(p){let S=[];if(/\d/.test(p[1])){let x=parseInt(p[1],10),A=parseInt(p[2],10),N=p[3]?parseInt(p[3],10):1,b=x<=A?N:-N;for(let M=x;x<=A?M<=A:M>=A;M+=b)S.push(String(M))}else{let x=p[1].charCodeAt(0),A=p[2].charCodeAt(0),N=x<=A?1:-1;for(let b=x;x<=A?b<=A:b>=A;b+=N)S.push(String.fromCharCode(b))}let F=S.map(x=>`${u}${x}${m}`),E=[];for(let x of F)if(E.push(...r(x,s+1)),E.length>256)return[o];return E}let h=[],y="",f=0;for(let S of d)S==="{"?(f++,y+=S):S==="}"?(f--,y+=S):S===","&&f===0?(h.push(y),y=""):y+=S;if(h.push(y),h.length>1){let S=[];for(let F of h)if(S.push(...r(`${u}${F}${m}`,s+1)),S.length>256)return[o];return S}break}}return[o]}return r(e,0)}function Vs(e,t){let n="",r=0;for(;r<e.length;){if(e[r]==="$"&&e[r+1]==="("&&e[r+2]==="("){let o=r+3,s=0;for(;o<e.length;){let i=e[o];if(i==="(")s++;else if(i===")"){if(s>0)s--;else if(e[o+1]===")"){let a=e.slice(r+3,o),c=xe(a,t);n+=Number.isNaN(c)?"0":String(c),r=o+2;break}}o++}if(o>=e.length){n+=e.slice(r);break}continue}n+=e[r],r++}return n}function Zt(e,t,n=0,r){let o=r??t.HOME??"/home/user";return Is(e,s=>{let i=s;return i=i.replace(/(^|[\s:])~(\/|$)/g,(a,c,l)=>`${c}${o}${l}`),i=i.replace(/\$\?/g,String(n)),i=i.replace(/\$\$/g,"1"),i=i.replace(/\$#/g,"0"),i=Vs(i,t),i=i.replace(/\$\{#([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,c)=>String((t[c]??"").length)),i=i.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):-([^}]*)\}/g,(a,c,l)=>t[c]!==void 0&&t[c]!==""?t[c]:l),i=i.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):=([^}]*)\}/g,(a,c,l)=>((t[c]===void 0||t[c]==="")&&(t[c]=l),t[c])),i=i.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):\+([^}]*)\}/g,(a,c,l)=>t[c]!==void 0&&t[c]!==""?l:""),i=i.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,c)=>t[c]??""),i=i.replace(/\$([A-Za-z_][A-Za-z0-9_]*|\d+)/g,(a,c)=>t[c]??""),i})}async function Yt(e,t,n,r){let o="__shellExpandDepth",i=Number(t[o]??"0");if(i>=8)return Zt(e,t,n);t[o]=String(i+1);try{if(e.includes("$(")){let a="",c=!1,l=0;for(;l<e.length;){let u=e[l];if(u==="'"&&!c){c=!0,a+=u,l++;continue}if(u==="'"&&c){c=!1,a+=u,l++;continue}if(!c&&u==="$"&&e[l+1]==="("){if(e[l+2]==="("){a+=u,l++;continue}let d=0,m=l+1;for(;m<e.length;){if(e[m]==="(")d++;else if(e[m]===")"&&(d--,d===0))break;m++}let p=e.slice(l+2,m).trim(),h=(await r(p)).replace(/\n$/,"");a+=h,l=m+1;continue}a+=u,l++}e=a}return Zt(e,t,n)}finally{i<=0?delete t[o]:t[o]=String(i)}}function Rs(e){return e.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,n)=>String.fromCharCode(parseInt(n,8)))}var hn={name:"echo",description:"Display text",category:"shell",params:["[-n] [-e] [text...]"],run:({args:e,stdin:t,env:n})=>{let{flags:r,positionals:o}=ot(e,{flags:["-n","-e","-E"]}),s=r.has("-n"),i=r.has("-e"),a=o.length>0?o.join(" "):t??"",c=Zt(a,n?.vars??{},n?.lastExitCode??0),l=i?Rs(c):c;return{stdout:s?l:`${l}
65
+ `,exitCode:0}}};var gn={name:"env",description:"Print environment variables",category:"shell",params:[],run:({env:e,authUser:t})=>{let n={...e.vars,USER:t,HOME:`/home/${t}`};return{stdout:Object.entries(n).map(([r,o])=>`${r}=${o}`).join(`
66
+ `),exitCode:0}}};var yn={name:"exit",aliases:["bye"],description:"Exit the shell session",category:"shell",params:["[code]"],run:({args:e})=>({closeSession:!0,exitCode:parseInt(e[0]??"0",10)||0})};var Sn={name:"export",description:"Set shell environment variable",category:"shell",params:["[VAR=value]"],run:({args:e,env:t})=>{if(e.length===0||e.length===1&&e[0]==="-p"){let n=Object.entries(t.vars).filter(([r])=>r&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(r)).map(([r,o])=>`declare -x ${r}="${o}"`).join(`
67
+ `);return{stdout:n?`${n}
68
+ `:"",exitCode:0}}for(let n of e.filter(r=>r!=="-p"))if(n.includes("=")){let r=n.indexOf("="),o=n.slice(0,r),s=n.slice(r+1);t.vars[o]=s}return{exitCode:0}}};var wn={name:"find",description:"Search for files",category:"files",params:["[path] [-name <pattern>] [-type f|d]"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=it(r,["-name"]),s=it(r,["-type"]),a=r.filter(m=>!m.startsWith("-")&&m!==o&&m!==s)[0]??".",c=k(n,a);try{if(z(e,c,"find"),!t.vfs.exists(c))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 l=o?new RegExp(`^${o.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`):null,u=[],d=(m,p)=>{let h=t.vfs.stat(m),y=!s||s==="f"&&h.type==="file"||s==="d"&&h.type==="directory",f=!l||l.test(m.split("/").pop()??"");if(y&&f&&u.push(p),h.type==="directory")for(let S of t.vfs.list(m)){let F=`${m}/${S}`,E=`${p}/${S}`;d(F,E)}};return d(c,a),{stdout:u.join(`
69
+ `),exitCode:0}}};import*as Qt from"node:os";var xn={name:"free",description:"Display amount of free and used memory",category:"system",params:["[-h] [-m] [-g]"],run:({args:e})=>{let t=w(e,["-h","--human"]),n=w(e,["-m"]),r=w(e,["-g"]),o=Qt.totalmem(),s=Qt.freemem(),i=o-s,a=Math.floor(o*.02),c=Math.floor(o*.05),l=Math.floor(s*.95),u=Math.floor(o*.5),d=y=>t?y>=1024*1024*1024?`${(y/(1024*1024*1024)).toFixed(1)}G`:y>=1024*1024?`${(y/(1024*1024)).toFixed(1)}M`:`${(y/1024).toFixed(1)}K`:String(Math.floor(r?y/(1024*1024*1024):n?y/(1024*1024):y/1024)),m=" total used free shared buff/cache available",p=`Mem: ${d(o).padStart(12)} ${d(i).padStart(11)} ${d(s).padStart(11)} ${d(a).padStart(11)} ${d(c).padStart(11)} ${d(l).padStart(11)}`,h=`Swap: ${d(u).padStart(12)} ${d(0).padStart(11)} ${d(u).padStart(11)}`;return{stdout:[m,p,h].join(`
70
+ `),exitCode:0}}};var bn={name:"grep",description:"Search text patterns",category:"text",params:["[-i] [-v] [-n] [-r] <pattern> [file...]"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let{flags:s,positionals:i}=ot(r,{flags:["-i","-v","-n","-r","-c","-l","-L","-q","--quiet","--silent"]}),a=s.has("-i"),c=s.has("-v"),l=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"),h=i[0],y=i.slice(1);if(!h)return{stderr:"grep: no pattern specified",exitCode:1};let f;try{let x=a?"mi":"m";f=new RegExp(h,x)}catch{return{stderr:`grep: invalid regex: ${h}`,exitCode:1}}let S=(x,A="")=>{let N=x.split(`
71
+ `),b=[];for(let M=0;M<N.length;M++){let R=N[M]??"",P=f.test(R);if(c?!P:P){let I=l?`${M+1}:`:"";b.push(`${A}${I}${R}`)}}return b},F=x=>{if(!t.vfs.exists(x))return[];if(t.vfs.stat(x).type==="file")return[x];if(!u)return[];let N=[],b=M=>{for(let R of t.vfs.list(M)){let P=`${M}/${R}`;t.vfs.stat(P).type==="file"?N.push(P):b(P)}};return b(x),N},E=[];if(y.length===0){if(!o)return{stdout:"",exitCode:1};let x=S(o);if(d)return{stdout:`${x.length}
72
+ `,exitCode:x.length>0?0:1};if(p)return{exitCode:x.length>0?0:1};E.push(...x)}else{let x=y.flatMap(A=>{let N=k(n,A);return F(N).map(b=>({file:A,path:b}))});for(let{file:A,path:N}of x)try{z(e,N,"grep");let b=t.vfs.readFile(N),M=x.length>1?`${A}:`:"",R=S(b,M);d?E.push(x.length>1?`${A}:${R.length}`:String(R.length)):m?R.length>0&&E.push(A):E.push(...R)}catch{return{stderr:`grep: ${A}: No such file or directory`,exitCode:1}}}return{stdout:E.length>0?`${E.join(`
73
73
  `)}
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
+ `:"",exitCode:E.length>0?0:1}}};var $n={name:"groups",description:"Print group memberships",category:"system",params:["[user]"],run:({authUser:e,shell:t,args:n})=>{let r=n[0]??e;return{stdout:t.users.isSudoer(r)?`${r} sudo root`:r,exitCode:0}}};var vn={name:"gzip",description:"Compress files",category:"archive",params:["[-k] [-d] <file>"],run:({shell:e,cwd:t,args:n})=>{if(!e.packageManager.isInstalled("gzip"))return{stderr:`bash: gzip: command not found
75
75
  Hint: install it with: apt install gzip
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
77
- `,exitCode:1};let o=S(t,s);if(i){if(!s.endsWith(".gz"))return{stderr:`gzip: ${s}: unknown suffix -- ignored
78
- `,exitCode:1};if(!r.vfs.exists(o))return{stderr:`gzip: ${s}: No such file or directory
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
76
+ `,exitCode:127};let r=n.includes("-k")||n.includes("--keep"),o=n.includes("-d"),s=n.find(l=>!l.startsWith("-"));if(!s)return{stderr:`gzip: no file specified
77
+ `,exitCode:1};let i=k(t,s);if(o){if(!s.endsWith(".gz"))return{stderr:`gzip: ${s}: unknown suffix -- ignored
78
+ `,exitCode:1};if(!e.vfs.exists(i))return{stderr:`gzip: ${s}: No such file or directory
79
+ `,exitCode:1};let l=e.vfs.readFile(i),u=i.slice(0,-3);return e.vfs.writeFile(u,l),r||e.vfs.remove(i),{exitCode:0}}if(!e.vfs.exists(i))return{stderr:`gzip: ${s}: No such file or directory
80
80
  `,exitCode:1};if(s.endsWith(".gz"))return{stderr:`gzip: ${s}: already has .gz suffix -- unchanged
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
83
- `,exitCode:1};if(!i.endsWith(".gz"))return{stderr:`gunzip: ${i}: unknown suffix -- ignored
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(`
81
+ `,exitCode:1};let a=e.vfs.readFileRaw(i),c=`${i}.gz`;return e.vfs.writeFile(c,a,{compress:!0}),r||e.vfs.remove(i),{exitCode:0}}},Cn={name:"gunzip",description:"Decompress files",category:"archive",aliases:["zcat"],params:["[-k] <file>"],run:({shell:e,cwd:t,args:n})=>{let r=n.includes("-k")||n.includes("--keep"),o=n.find(c=>!c.startsWith("-"));if(!o)return{stderr:`gunzip: no file specified
82
+ `,exitCode:1};let s=k(t,o);if(!e.vfs.exists(s))return{stderr:`gunzip: ${o}: No such file or directory
83
+ `,exitCode:1};if(!o.endsWith(".gz"))return{stderr:`gunzip: ${o}: unknown suffix -- ignored
84
+ `,exitCode:1};let i=e.vfs.readFile(s),a=s.slice(0,-3);return e.vfs.writeFile(a,i),r||e.vfs.remove(s),{exitCode:0}}};var Pn={name:"head",description:"Output first lines",category:"text",params:["[-n <lines>] [file...]"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let s=it(r,["-n"]),i=r.find(d=>/^-\d+$/.test(d)),a=typeof s=="string"?parseInt(s,10):i?parseInt(i.slice(1),10):10,c=r.filter(d=>!d.startsWith("-")&&d!==s&&d!==String(a)),l=d=>{let m=d.split(`
85
85
  `),p=m.slice(0,a);return p.join(`
86
86
  `)+(d.endsWith(`
87
87
  `)&&p.length===m.slice(0,a).length?`
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(`
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(`
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)}
95
- `,exitCode:0}:{stderr:`readlink: ${i}: not a symbolic link
96
- `,exitCode:1}:{stderr:`readlink: ${i}: No such file or directory
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]??`
88
+ `:"")};if(c.length===0)return{stdout:l(o??""),exitCode:0};let u=[];for(let d of c){let m=k(n,d);try{z(e,m,"head"),u.push(l(t.vfs.readFile(m)))}catch{return{stderr:`head: ${d}: No such file or directory`,exitCode:1}}}return{stdout:u.join(`
89
+ `),exitCode:0}}};var kn=["navigation","files","text","archive","system","package","network","shell","users","misc"],An={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"},En="\x1B[1m",ht="\x1B[0m",Ds="\x1B[36m",zs="\x1B[33m",Dt="\x1B[2m",Ls="\x1B[32m";function Mn(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Ts(e){let t=e.aliases?.length?` ${Dt}(${e.aliases.join(", ")})${ht}`:"";return` ${Ds}${Mn(e.name,16)}${ht}${t}${Mn("",(e.aliases?.length,0))} ${e.description??""}`}function Us(e){let t={};for(let s of e){let i=s.category??"misc";t[i]||(t[i]=[]),t[i].push(s)}let n=[`${En}Available commands${ht}`,`${Dt}Type 'help <command>' for detailed usage.${ht}`,""],r=[...kn.filter(s=>t[s]),...Object.keys(t).filter(s=>!kn.includes(s)).sort()];for(let s of r){let i=t[s];if(!i?.length)continue;n.push(`${zs}${An[s]??s}${ht}`);let a=[...i].sort((c,l)=>c.name.localeCompare(l.name));for(let c of a)n.push(Ts(c));n.push("")}let o=e.length;return n.push(`${Dt}${o} commands available.${ht}`),n.join(`
90
+ `)}function Bs(e){let t=[];if(t.push(`${En}${e.name}${ht} \u2014 ${e.description??"no description"}`),e.aliases?.length&&t.push(`${Dt}Aliases: ${e.aliases.join(", ")}${ht}`),t.push(""),t.push(`${Ls}Usage:${ht}`),e.params.length)for(let r of e.params)t.push(` ${e.name} ${r}`);else t.push(` ${e.name}`);let n=An[e.category??"misc"]??e.category??"misc";return t.push(""),t.push(`${Dt}Category: ${n}${ht}`),t.join(`
91
+ `)}function Fn(e){return{name:"help",description:"List all commands, or show usage for a specific command",category:"shell",params:["[command]"],run:({args:t})=>{let n=be();if(t[0]){let r=t[0].toLowerCase(),o=n.find(s=>s.name===r||s.aliases?.includes(r));return o?{stdout:Bs(o),exitCode:0}:{stderr:`help: no help entry for '${t[0]}'`,exitCode:1}}return{stdout:Us(n),exitCode:0}}}}var Nn={name:"history",description:"Display command history",category:"shell",params:["[n]"],run:({args:e,shell:t,authUser:n})=>{let r=`/home/${n}/.bash_history`;if(!t.vfs.exists(r))return{stdout:"",exitCode:0};let s=t.vfs.readFile(r).split(`
92
+ `).filter(Boolean),i=e[0],a=i?parseInt(i,10):null,c=a&&!Number.isNaN(a)?s.slice(-a):s,l=s.length-c.length+1;return{stdout:c.map((d,m)=>`${String(l+m).padStart(5)} ${d}`).join(`
93
+ `),exitCode:0}}};var _n={name:"hostname",description:"Print hostname",category:"system",params:[],run:({hostname:e})=>({stdout:e,exitCode:0})};var In={name:"htop",description:"System monitor",category:"system",params:[],run:({mode:e})=>e==="exec"?{stderr:"htop: interactive terminal required",exitCode:1}:{openHtop:!0,exitCode:0}};var Vn={name:"id",description:"Print user identity",category:"system",params:["[user]"],run:({authUser:e,shell:t,args:n})=>{let r=n[0]??e,o=r==="root"?0:1e3,s=o,a=t.users.isSudoer(r)?`${s}(${r}),0(root)`:`${s}(${r})`;return{stdout:`uid=${o}(${r}) gid=${s}(${r}) groups=${a}`,exitCode:0}}};var Rn={name:"kill",description:"Send signal to process",category:"system",params:["[-9] <pid>"],run:({args:e})=>e.find(n=>!n.startsWith("-"))?{stdout:"",exitCode:0}:{stderr:"kill: no pid specified",exitCode:1}};var Dn={name:"ln",description:"Create links",category:"files",params:["[-s] <target> <link_name>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=w(r,["-s","--symbolic"]),s=r.filter(u=>!u.startsWith("-")),[i,a]=s;if(!i||!a)return{stderr:"ln: missing operand",exitCode:1};let c=k(n,a),l=o?i:k(n,i);try{if(z(e,c,"ln"),o)t.vfs.symlink(l,c);else{let u=k(n,i);if(z(e,u,"ln"),!t.vfs.exists(u))return{stderr:`ln: ${i}: No such file or directory`,exitCode:1};let d=t.vfs.readFile(u);t.writeFileAsUser(e,c,d)}return{exitCode:0}}catch(u){return{stderr:`ln: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}},zn={name:"readlink",description:"Print resolved path of symbolic link",category:"files",params:["[-f] <path>"],run:({shell:e,cwd:t,args:n})=>{let r=n.includes("-f")||n.includes("-e"),o=n.find(a=>!a.startsWith("-"));if(!o)return{stderr:`readlink: missing operand
94
+ `,exitCode:1};let s=k(t,o);return e.vfs.exists(s)?e.vfs.isSymlink(s)?{stdout:`${e.vfs.resolveSymlink(s)}
95
+ `,exitCode:0}:{stderr:`readlink: ${o}: not a symbolic link
96
+ `,exitCode:1}:{stderr:`readlink: ${o}: No such file or directory
97
+ `,exitCode:1}}};var Ln={name:"seq",description:"Print a sequence of numbers",category:"text",params:["[FIRST [INCREMENT]] LAST"],run:({args:e})=>{let t=e.filter(d=>!d.startsWith("-")||/^-[\d.]/.test(d)).map(Number),n=(()=>{let d=e.indexOf("-s");return d!==-1?e[d+1]??`
98
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(`
99
+ `})(),r=(()=>{let d=e.indexOf("-f");return d!==-1?e[d+1]??"%g":null})(),o=e.includes("-w"),s=1,i=1,a;if(t.length===1?a=t[0]:t.length===2?(s=t[0],a=t[1]):(s=t[0],i=t[1],a=t[2]),i===0)return{stderr:`seq: zero increment
100
+ `,exitCode:1};if(i>0&&s>a||i<0&&s<a)return{stdout:"",exitCode:0};let c=[],l=1e5,u=0;for(let d=s;(i>0?d<=a:d>=a)&&!(++u>l);d=Math.round((d+i)*1e10)/1e10){let m;if(r?m=r.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+$/,""),o){let p=String(Math.trunc(a)).length;m=m.padStart(p,"0")}c.push(m)}return{stdout:`${c.join(n)}
101
+ `,exitCode:0}}};var Tn={name:"stat",description:"Display file status",category:"files",params:["[-c <format>] <file>"],run:({shell:e,cwd:t,args:n})=>{let r=n.findIndex(S=>S==="-c"||S==="--format"),o=r!==-1?n[r+1]:void 0,s=n.find(S=>!S.startsWith("-")&&S!==o);if(!s)return{stderr:`stat: missing operand
102
+ `,exitCode:1};let i=k(t,s);if(!e.vfs.exists(i))return{stderr:`stat: cannot stat '${s}': No such file or directory
103
+ `,exitCode:1};let a=e.vfs.stat(i),c=a.type==="directory",l=e.vfs.isSymlink(i),u=e.vfs.isSymlink(i),d=S=>{let F=[256,128,64,32,16,8,4,2,1],E=["r","w","x","r","w","x","r","w","x"];return(c?"d":u?"l":"-")+F.map((x,A)=>S&x?E[A]:"-").join("")},m=a.mode.toString(8).padStart(4,"0"),p=d(a.mode),h="size"in a?a.size:0,y=S=>S.toISOString().replace("T"," ").replace(/\.\d+Z$/," +0000");return o?{stdout:`${o.replace("%n",s).replace("%s",String(h)).replace("%a",m.slice(1)).replace("%A",p).replace("%F",u?"symbolic link":c?"directory":"regular file").replace("%y",y(a.updatedAt)).replace("%z",y(a.updatedAt))}
104
+ `,exitCode:0}:{stdout:`${[` File: ${s}${u?` -> ${e.vfs.resolveSymlink(i)}`:""}`,` Size: ${h}${" ".repeat(3)}${u?"symbolic link":c?"directory":"regular file"}`,`Access: (${m}/${p}) Uid: ( 0/ root) Gid: ( 0/ root)`,`Modify: ${y(a.updatedAt)}`,`Change: ${y(a.updatedAt)}`].join(`
105
105
  `)}
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(`
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(`
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
106
+ `,exitCode:0}}};var Os="\x1B[0m",Ws="\x1B[1;34m",js="\x1B[1;36m",Hs="\x1B[1;32m",qs="",Ks="\x1B[30;42m",Gs="\x1B[37;44m",Zs="\x1B[34;42m";function At(e,t){return t?`${t}${e}${Os}`:e}function ve(e,t,n){if(n)return js;if(t==="directory"){let r=!!(e&512),o=!!(e&2);return r&&o?Ks:r?Gs:o?Zs:Ws}return e&73?Hs:qs}function Un(e,t,n){let r;n?r="l":t==="directory"?r="d":r="-";let o=l=>e&l?"r":"-",s=l=>e&l?"w":"-",i=(()=>{let l=!!(e&64);return e&2048?l?"s":"S":l?"x":"-"})(),a=(()=>{let l=!!(e&8);return e&1024?l?"s":"S":l?"x":"-"})(),c=(()=>{let l=!!(e&1);return t==="directory"&&e&512?l?"t":"T":l?"x":"-"})();return`${r}${o(256)}${s(128)}${i}${o(32)}${s(16)}${a}${o(4)}${s(2)}${c}`}var Js=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function $e(e){let t=new Date,n=4320*3600*1e3,r=Math.abs(t.getTime()-e.getTime())<n,o=String(e.getDate()).padStart(2," "),s=Js[e.getMonth()]??"";if(r){let i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0");return`${o} ${s.padEnd(3)} ${i}:${a}`}return`${o} ${s.padEnd(3)} ${e.getFullYear()}`}function Xt(e,t){try{return e.readFile(t)}catch{return"?"}}function Ys(e,t,n){let r=t==="/"?"":t;return n.map(o=>{let s=`${r}/${o}`,i=e.isSymlink(s),a;try{a=e.stat(s)}catch{return o}let c=ve(a.mode,a.type,i);return At(o,c)}).join(" ")}function Qs(e,t,n){let r=t==="/"?"":t,o=n.map(d=>{let m=`${r}/${d}`,p=e.isSymlink(m),h;try{h=e.stat(m)}catch{return{perms:"----------",nlink:"1",size:"0",date:$e(new Date),label:d}}let y=p?41471:h.mode,f=Un(y,h.type,p),S=h.type==="directory"?String((h.childrenCount??0)+2):"1",F=p?Xt(e,m).length:h.type==="file"?h.size??0:(h.childrenCount??0)*4096,E=String(F),x=$e(h.updatedAt),A=ve(y,h.type,p),N=p?`${At(d,A)} -> ${Xt(e,m)}`:At(d,A);return{perms:f,nlink:S,size:E,date:x,label:N}}),s=Math.max(...o.map(d=>d.nlink.length)),i=Math.max(...o.map(d=>d.size.length)),a="root",c="root",l=n.length*8,u=o.map(d=>`${d.perms} ${d.nlink.padStart(s)} ${a} ${c} ${d.size.padStart(i)} ${d.date} ${d.label}`);return`total ${l}
107
+ ${u.join(`
108
+ `)}`}var Bn={name:"ls",description:"List directory contents",category:"navigation",params:["[-la] [path]"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=w(r,["-l","--long","-la","-al"]),s=w(r,["-a","--all","-la","-al"]),i=bt(r,0,{flags:["-l","--long","-a","--all","-la","-al"]}),a=k(n,i??n);if(z(e,a,"ls"),t.vfs.exists(a)){let u=t.vfs.stat(a),d=t.vfs.isSymlink(a);if(u.type==="file"||d){let m=a.split("/").pop()??a,p=ve(d?41471:u.mode,u.type,d);if(o){let h=d?41471:u.mode,y=d?Xt(t.vfs,a).length:u.size??0,f=Un(h,u.type,d),S=d?`${At(m,p)} -> ${Xt(t.vfs,a)}`:At(m,p);return{stdout:`${f} 1 root root ${y} ${$e(u.updatedAt)} ${S}
109
+ `,exitCode:0}}return{stdout:`${At(m,p)}
110
+ `,exitCode:0}}}let c=t.vfs.list(a).filter(u=>s||!u.startsWith("."));return{stdout:`${o?Qs(t.vfs,a,c):Ys(t.vfs,a,c)}
111
+ `,exitCode:0}}};var On={name:"lsb_release",description:"Print distribution-specific information",category:"system",params:["[-a] [-i] [-d] [-r] [-c]"],run:({args:e,shell:t})=>{let n=t.properties?.os??"Fortune GNU/Linux x64",r="aurora",o="1.0";try{let d=t.vfs.readFile("/etc/os-release");for(let m of d.split(`
112
+ `))m.startsWith("PRETTY_NAME=")&&(n=m.slice(12).replace(/^"|"$/g,"").trim()),m.startsWith("VERSION_CODENAME=")&&(r=m.slice(17).trim()),m.startsWith("VERSION_ID=")&&(o=m.slice(11).replace(/^"|"$/g,"").trim())}catch{}let s=w(e,["-a","--all"]),i=w(e,["-i","--id"]),a=w(e,["-d","--description"]),c=w(e,["-r","--release"]),l=w(e,["-c","--codename"]);if(s||e.length===0)return{stdout:["Distributor ID: Fortune",`Description: ${n}`,`Release: ${o}`,`Codename: ${r}`].join(`
113
+ `),exitCode:0};let u=[];return i&&u.push("Distributor ID: Fortune"),a&&u.push(`Description: ${n}`),c&&u.push(`Release: ${o}`),l&&u.push(`Codename: ${r}`),{stdout:u.join(`
114
+ `),exitCode:0}}};var Xs={gunzip:"gzip"},te=new Map,to=new URL("./manuals/",import.meta.url);async function eo(e){return new Function("moduleName","return import(moduleName)")(e)}async function no(e){let t=e.toLowerCase(),n=Xs[t]??t,r=`builtin:${n}`;if(te.has(r))return te.get(r)??null;try{let o=await eo("node:fs/promises"),s=new URL(`${n}.txt`,to),a=(await o.readFile(s,"utf8")).replace(/\n$/,"");return te.set(r,a),a}catch{return te.set(r,null),null}}var Wn={name:"man",description:"Interface to the system reference manuals",category:"shell",params:["<command>"],run:async({args:e,shell:t})=>{let n=e[0];if(!n)return{stderr:"What manual page do you want?",exitCode:1};let r=`/usr/share/man/man1/${n}.1`;if(t.vfs.exists(r))return{stdout:t.vfs.readFile(r),exitCode:0};let o=await no(n);return o?{stdout:o,exitCode:0}:{stderr:`No manual entry for ${n}`,exitCode:16}}};var jn={name:"mkdir",description:"Make directories",category:"files",params:["<dir>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{if(r.length===0)return{stderr:"mkdir: missing operand",exitCode:1};for(let o=0;o<r.length;o++){let s=bt(r,o);if(!s)return{stderr:"mkdir: missing operand",exitCode:1};let i=k(n,s);z(e,i,"mkdir"),t.vfs.mkdir(i)}return{exitCode:0}}};var Hn={name:"mv",description:"Move or rename files",category:"files",params:["<source> <dest>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=r.filter(l=>!l.startsWith("-")),[s,i]=o;if(!s||!i)return{stderr:"mv: missing operand",exitCode:1};let a=k(n,s),c=k(n,i);try{if(z(e,a,"mv"),z(e,c,"mv"),!t.vfs.exists(a))return{stderr:`mv: ${s}: No such file or directory`,exitCode:1};let l=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${s.split("/").pop()}`:c;return t.vfs.move(a,l),{exitCode:0}}catch(l){return{stderr:`mv: ${l instanceof Error?l.message:String(l)}`,exitCode:1}}}};import*as qn from"node:path";var Kn={name:"nano",description:"Text editor",category:"files",params:["<file>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=r[0];if(!o)return{stderr:"nano: missing file operand",exitCode:1};let s=k(n,o);z(e,s,"nano");let i=t.vfs.exists(s)?t.vfs.readFile(s):"",a=qn.posix.basename(s)||"buffer",c=`/tmp/sshmimic-nano-${Date.now()}-${a}.tmp`;return{openEditor:{targetPath:s,tempPath:c,initialContent:i},exitCode:0}}};import{existsSync as tr,readdirSync as ro,readFileSync as Ce}from"node:fs";import*as nt from"node:os";import*as er from"node:path";function so(e){let t=Math.max(1,Math.floor(e/60)),n=Math.floor(t/1440),r=Math.floor(t%1440/60),o=t%60,s=[];return n>0&&s.push(`${n} day${n>1?"s":""}`),r>0&&s.push(`${r} hour${r>1?"s":""}`),(o>0||s.length===0)&&s.push(`${o} min${o>1?"s":""}`),s.join(", ")}function Gn(e){return`\x1B[${e}m \x1B[0m`}function oo(){let e=[40,41,42,43,44,45,46,47].map(Gn).join(""),t=[100,101,102,103,104,105,106,107].map(Gn).join("");return[e,t]}function Zn(e,t,n){if(e.trim().length===0)return e;let r={r:255,g:255,b:255},o={r:168,g:85,b:247},s=n<=1?0:t/(n-1),i=Math.round(r.r+(o.r-r.r)*s),a=Math.round(r.g+(o.g-r.g)*s),c=Math.round(r.b+(o.b-r.b)*s);return`\x1B[38;2;${i};${a};${c}m${e}\x1B[0m`}function io(e){if(e.trim().length===0)return e;let t=e.indexOf(":");if(t===-1)return e.includes("@")?Jn(e):e;let n=e.substring(0,t+1),r=e.substring(t+1);return Jn(n)+r}function Jn(e){let t=new RegExp("\x1B\\[[\\d;]*m","g"),n=e.replace(t,"");if(n.trim().length===0)return e;let r={r:255,g:255,b:255},o={r:168,g:85,b:247},s="";for(let i=0;i<n.length;i+=1){let a=n.length<=1?0:i/(n.length-1),c=Math.round(r.r+(o.r-r.r)*a),l=Math.round(r.g+(o.g-r.g)*a),u=Math.round(r.b+(o.b-r.b)*a);s+=`\x1B[38;2;${c};${l};${u}m${n[i]}\x1B[0m`}return s}function Yn(e){return Math.max(0,Math.round(e/(1024*1024)))}function Qn(){try{let e=Ce("/etc/os-release","utf8");for(let t of e.split(`
115
+ `)){if(!t.startsWith("PRETTY_NAME="))continue;return t.slice(12).trim().replace(/^"|"$/g,"")}}catch{return}}function Xn(e){try{let t=Ce(e,"utf8").split(`
116
+ `)[0]?.trim();return!t||t.length===0?void 0:t}catch{return}}function ao(e){let t=Xn("/sys/devices/virtual/dmi/id/sys_vendor"),n=Xn("/sys/devices/virtual/dmi/id/product_name");return t&&n?`${t} ${n}`:n||e}function co(){let e=["/var/lib/dpkg/status","/usr/local/var/lib/dpkg/status"];for(let t of e)if(tr(t))try{return Ce(t,"utf8").match(/^Package:\s+/gm)?.length??0}catch{}}function lo(){let e=["/snap","/var/lib/snapd/snaps"];for(let t of e)if(tr(t))try{return ro(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).length}catch{}}function uo(){let e=co(),t=lo();return e!==void 0&&t!==void 0?`${e} (dpkg), ${t} (snap)`:e!==void 0?`${e} (dpkg)`:t!==void 0?`${t} (snap)`:"n/a"}function mo(){let e=nt.cpus();if(e.length===0)return"unknown";let t=e[0];if(!t)return"unknown";let n=(t.speed/1e3).toFixed(2);return`${t.model} (${e.length}) @ ${n}GHz`}function po(e){return!e||e.trim().length===0?"unknown":er.posix.basename(e.trim())}function fo(e){let t=nt.totalmem(),n=nt.freemem(),r=Math.max(0,t-n),o=e.shellProps,s=process.uptime();return e.uptimeSeconds===void 0&&(e.uptimeSeconds=Math.round(s)),{user:e.user,host:e.host,osName:o?.os??e.osName??`${Qn()??nt.type()} ${nt.arch()}`,kernel:o?.kernel??e.kernel??nt.release(),uptimeSeconds:e.uptimeSeconds??nt.uptime(),packages:e.packages??uo(),shell:po(e.shell),shellProps:e.shellProps??{kernel:e.kernel??nt.release(),os:e.osName??`${Qn()??nt.type()} ${nt.arch()}`,arch:nt.arch()},resolution:e.resolution??"n/a (ssh)",terminal:e.terminal??"unknown",cpu:e.cpu??mo(),gpu:e.gpu??"n/a",memoryUsedMiB:e.memoryUsedMiB??Yn(r),memoryTotalMiB:e.memoryTotalMiB??Yn(t)}}function nr(e){let t=fo(e),n=so(t.uptimeSeconds),r=oo(),o=[" .. .:. "," .::.. .. .. ",". .... ... .. ",": .... .:. .. ",": .:.:........:. .. ",": .. ",". : ",". : ",".. : "," :. .. "," .. .. "," :-. :: "," .:. :. "," ..: ... "," ..: :.. "," :... :...."," .. ...."," . .. "," .:. .: "," :. .. "," ::. .. ","..... ..:... ","...:. .. ",".:...:. ::. .. "," ... ..:::::.. ..:::::::.. "],s=[`${t.user}@${t.host}`,"-------------------------",`OS: ${t.osName}`,`Host: ${ao(t.host)}`,`Kernel: ${t.kernel}`,`Uptime: ${n}`,`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`,"",r[0],r[1]],i=Math.max(o.length,s.length),a=[];for(let c=0;c<i;c+=1){let l=o[c]??"",u=s[c]??"";if(u.length>0){let d=Zn(l.padEnd(31," "),c,o.length),m=io(u);a.push(`${d} ${m}`);continue}a.push(Zn(l,c,o.length))}return a.join(`
117
+ `)}var rr={name:"neofetch",description:"System info display",category:"system",params:["[--off]"],run:({args:e,authUser:t,hostname:n,shell:r,env:o})=>r.packageManager.isInstalled("neofetch")?w(e,"--help")?{stdout:"Usage: neofetch [--off]",exitCode:0}:w(e,"--off")?{stdout:`${t}@${n}`,exitCode:0}:{stdout:nr({user:t,host:n,shell:o.vars.SHELL,shellProps:r.properties,terminal:o.vars.TERM,uptimeSeconds:Math.floor((Date.now()-r.startTime)/1e3),packages:`${r.packageManager?.installedCount()??0} (dpkg)`}),exitCode:0}:{stderr:`bash: neofetch: command not found
115
118
  Hint: install it with: apt install neofetch
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(`
119
+ `,exitCode:127}};import sr from"node:vm";var ee="v18.19.0",or={node:ee,npm:"9.2.0",v8:"10.2.154.26-node.22"};function ho(e,t){let n={version:ee,versions:or,platform:"linux",arch:"x64",env:{NODE_ENV:"production",HOME:"/root",PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["node"],stdout:{write:s=>(e.push(s),!0)},stderr:{write:s=>(t.push(s),!0)},exit:(s=0)=>{throw new ne(s)},cwd:()=>"/root",hrtime:()=>[0,0]},r={log:(...s)=>e.push(s.map(gt).join(" ")),error:(...s)=>t.push(s.map(gt).join(" ")),warn:(...s)=>t.push(s.map(gt).join(" ")),info:(...s)=>e.push(s.map(gt).join(" ")),dir:s=>e.push(gt(s))},o=s=>{switch(s){case"path":return{join:(...i)=>i.join("/").replace(/\/+/g,"/"),resolve:(...i)=>`/${i.join("/").replace(/^\/+/,"")}`,dirname:i=>i.split("/").slice(0,-1).join("/")||"/",basename:i=>i.split("/").pop()??"",extname:i=>{let a=i.split("/").pop()??"",c=a.lastIndexOf(".");return c>0?a.slice(c):""},sep:"/",delimiter:":"};case"os":return{platform:()=>"linux",arch:()=>"x64",type:()=>"Linux",hostname:()=>"fortune-vm",homedir:()=>"/root",tmpdir:()=>"/tmp",EOL:`
120
+ `};case"util":return{format:(...i)=>i.map(gt).join(" "),inspect:i=>gt(i)};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 o.resolve=s=>{throw new Error(`Cannot resolve '${s}'`)},o.cache={},o.extensions={},sr.createContext({console:r,process:n,require:o,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 ne=class{constructor(t){this.code=t}code};function gt(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="function")return`[Function: ${e.name||"(anonymous)"}]`;if(Array.isArray(e))return`[ ${e.map(gt).join(", ")} ]`;if(e instanceof Error)return`${e.name}: ${e.message}`;if(typeof e=="object")try{return`{ ${Object.entries(e).map(([n,r])=>`${n}: ${gt(r)}`).join(", ")} }`}catch{return"[Object]"}return String(e)}function re(e){let t=[],n=[],r=ho(t,n),o=0;try{let s=sr.runInContext(e,r,{timeout:5e3});s!==void 0&&t.length===0&&t.push(gt(s))}catch(s){s instanceof ne?o=s.code:s instanceof Error?(n.push(`${s.name}: ${s.message}`),o=1):(n.push(String(s)),o=1)}return{stdout:t.length?`${t.join(`
118
121
  `)}
119
- `:"",stderr:e.length?`${e.join(`
122
+ `:"",stderr:n.length?`${n.join(`
120
123
  `)}
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
124
+ `:"",exitCode:o}}function go(e){let t=e.trim();return!t.includes(`
125
+ `)&&!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("//")?re(t):re(`(async () => { ${e} })()`)}var ir={name:"node",description:"JavaScript runtime (virtual)",category:"system",params:["[--version] [-e <expr>] [-p <expr>] [file]"],run:({args:e,shell:t,cwd:n})=>{if(!t.packageManager.isInstalled("nodejs"))return{stderr:`bash: node: command not found
123
126
  Hint: install it with: apt install nodejs
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)}
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
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
+ `,exitCode:127};if(w(e,["--version","-v"]))return{stdout:`${ee}
128
+ `,exitCode:0};if(w(e,["--versions"]))return{stdout:`${JSON.stringify(or,null,2)}
129
+ `,exitCode:0};let r=e.findIndex(i=>i==="-e"||i==="--eval");if(r!==-1){let i=e[r+1];if(!i)return{stderr:`node: -e requires an argument
130
+ `,exitCode:1};let{stdout:a,stderr:c,exitCode:l}=re(i);return{stdout:a||void 0,stderr:c||void 0,exitCode:l}}let o=e.findIndex(i=>i==="-p"||i==="--print");if(o!==-1){let i=e[o+1];if(!i)return{stderr:`node: -p requires an argument
131
+ `,exitCode:1};let{stdout:a,stderr:c,exitCode:l}=re(i);return{stdout:a||(l===0?`
132
+ `:void 0),stderr:c||void 0,exitCode:l}}let s=e.find(i=>!i.startsWith("-"));if(s){let i=k(n,s);if(!t.vfs.exists(i))return{stderr:`node: cannot open file '${s}': No such file or directory
133
+ `,exitCode:1};let a=t.vfs.readFile(i),{stdout:c,stderr:l,exitCode:u}=go(a);return{stdout:c||void 0,stderr:l||void 0,exitCode:u}}return{stdout:[`Welcome to Node.js ${ee}.`,'Type ".exit" to exit the REPL.',"> "].join(`
134
+ `),exitCode:0}}};var se="9.2.0",yo="18.19.0",ar={name:"npm",description:"Node.js package manager (virtual)",category:"system",params:["<command> [args]"],run:({args:e,shell:t})=>{if(!t.packageManager.isInstalled("npm"))return{stderr:`bash: npm: command not found
132
135
  Hint: install it with: apt install npm
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' }
136
+ `,exitCode:127};if(w(e,["--version","-v"]))return{stdout:`${se}
137
+ `,exitCode:0};let n=e[0]?.toLowerCase();switch(n){case"version":case"-version":return{stdout:`{ npm: '${se}', node: '${yo}', v8: '10.2.154.26' }
135
138
  `,exitCode:0};case"install":case"i":case"add":return{stderr:`npm warn: package installation is not available in the virtual runtime.
136
139
  npm warn: This environment simulates npm CLI behaviour only.
137
140
  `,exitCode:1};case"run":case"exec":case"x":return{stderr:`npm error: script execution is not available in the virtual runtime.
138
141
  `,exitCode:1};case"init":return{stdout:`Wrote to /home/user/package.json
139
- `,exitCode:0};case"list":case"ls":return{stdout:`${e==="ls"||e==="list"?"virtual-env@1.0.0":""}
142
+ `,exitCode:0};case"list":case"ls":return{stdout:`${n==="ls"||n==="list"?"virtual-env@1.0.0":""}
140
143
  \u2514\u2500\u2500 (empty)
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(`
144
+ `,exitCode:0};case"help":case void 0:return{stdout:`${[`npm ${se}`,"","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(`
142
145
  `)}
143
- `,exitCode:0};default:return{stderr:`npm error: unknown command: ${e}
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}
146
+ `,exitCode:0};default:return{stderr:`npm error: unknown command: ${n}
147
+ `,exitCode:1}}}},cr={name:"npx",description:"Node.js package runner (virtual)",category:"system",params:["<package> [args]"],run:({args:e,shell:t})=>t.packageManager.isInstalled("npm")?w(e,["--version"])?{stdout:`${se}
145
148
  `,exitCode:0}:{stderr:`npx: package execution is not available in the virtual runtime.
146
149
  `,exitCode:1}:{stderr:`bash: npx: command not found
147
150
  Hint: install it with: apt install npm
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(`
149
- `)[0];return await e.users.setPassword(i,s),{stdout:`passwd: password updated successfully
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(`
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(`
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(`
151
+ `,exitCode:127}};var lr={name:"passwd",description:"Change user password",category:"users",params:["[username]"],run:async({authUser:e,args:t,shell:n,stdin:r})=>{let o=t[0]??e;if(e!=="root"&&e!==o)return{stderr:"passwd: permission denied",exitCode:1};if(!n.users.listUsers().includes(o))return{stderr:`passwd: user '${o}' does not exist`,exitCode:1};if(r!==void 0&&r.trim().length>0){let s=r.trim().split(`
152
+ `)[0];return await n.users.setPassword(o,s),{stdout:`passwd: password updated successfully
153
+ `,exitCode:0}}return{passwordChallenge:{prompt:"New password: ",confirmPrompt:"Retype new password: ",action:"passwd",targetUsername:o},exitCode:0}}};var ur={name:"ping",description:"Send ICMP ECHO_REQUEST (mock)",category:"network",params:["[-c <count>] <host>"],run:({args:e})=>{let{flagsWithValues:t,positionals:n}=ot(e,{flagsWithValue:["-c","-i","-W"]}),r=n[0]??"localhost",o=t.get("-c"),s=o?Math.max(1,parseInt(o,10)||4):4,i=[`PING ${r}: 56 data bytes`];for(let a=0;a<s;a++){let c=(Math.random()*10+1).toFixed(3);i.push(`64 bytes from ${r}: icmp_seq=${a} ttl=64 time=${c} ms`)}return i.push(`--- ${r} ping statistics ---`),i.push(`${s} packets transmitted, ${s} received, 0% packet loss`),{stdout:i.join(`
154
+ `),exitCode:0}}};function So(e,t){let n=0,r="",o=0;for(;o<e.length;){if(e[o]==="\\"&&o+1<e.length)switch(e[o+1]){case"n":r+=`
155
+ `,o+=2;continue;case"t":r+=" ",o+=2;continue;case"r":r+="\r",o+=2;continue;case"\\":r+="\\",o+=2;continue;case"a":r+="\x07",o+=2;continue;case"b":r+="\b",o+=2;continue;case"f":r+="\f",o+=2;continue;case"v":r+="\v",o+=2;continue;default:r+=e[o],o++;continue}if(e[o]==="%"&&o+1<e.length){let s=o+1,i=!1;e[s]==="-"&&(i=!0,s++);let a=!1;e[s]==="0"&&(a=!0,s++);let c=0;for(;s<e.length&&/\d/.test(e[s]);)c=c*10+parseInt(e[s],10),s++;let l=-1;if(e[s]===".")for(s++,l=0;s<e.length&&/\d/.test(e[s]);)l=l*10+parseInt(e[s],10),s++;let u=e[s],d=t[n++]??"",m=(p,h=" ")=>{if(c<=0||p.length>=c)return p;let y=h.repeat(c-p.length);return i?p+y:y+p};switch(u){case"s":{let p=String(d);l>=0&&(p=p.slice(0,l)),r+=m(p);break}case"d":case"i":r+=m(String(parseInt(d,10)||0),a?"0":" ");break;case"f":{let p=l>=0?l:6;r+=m((parseFloat(d)||0).toFixed(p));break}case"o":r+=m((parseInt(d,10)||0).toString(8),a?"0":" ");break;case"x":r+=m((parseInt(d,10)||0).toString(16),a?"0":" ");break;case"X":r+=m((parseInt(d,10)||0).toString(16).toUpperCase(),a?"0":" ");break;case"%":r+="%",n--;break;default:r+=e[o],o++;continue}o=s+1;continue}r+=e[o],o++}return r}var dr={name:"printf",description:"Format and print data",category:"shell",params:["<format> [args...]"],run:({args:e})=>{let t=e[0];return t?{stdout:So(t,e.slice(1)),exitCode:0}:{stderr:"printf: missing format string",exitCode:1}}};var mr={name:"ps",description:"Report process status",category:"system",params:["[-a] [-u] [-x] [aux]"],run:({authUser:e,shell:t,args:n})=>{let r=t.users.listActiveSessions(),o=w(n,["-u"])||n.includes("u")||n.includes("aux")||n.includes("au"),s=w(n,["-a","-x"])||n.includes("a")||n.includes("aux");if(o){let u=["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND"],d=1e3;for(let m of r){let p=m.username.padEnd(10).slice(0,10),h=(Math.random()*.5).toFixed(1),y=Math.floor(Math.random()*2e4+5e3),f=Math.floor(Math.random()*5e3+1e3);u.push(`${p} ${String(d).padStart(6)} 0.0 ${h.padStart(4)} ${String(y).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(`
156
+ `),exitCode:0}}let a=[" PID TTY TIME CMD"],c=1e3;for(let l of r)!s&&l.username!==e||(a.push(`${String(c).padStart(5)} ${l.tty.padEnd(12)} 00:00:00 ${l.username===e?"bash":`bash (${l.username})`}`),c++);return a.push(`${String(c).padStart(5)} pts/0 00:00:00 ps`),{stdout:a.join(`
157
+ `),exitCode:0}}};var pr={name:"pwd",description:"Print working directory",category:"navigation",params:[],run:({cwd:e})=>({stdout:e,exitCode:0})};var wo="Python 3.11.2";var oe="3.11.2 (default, Mar 13 2023, 12:18:29) [GCC 12.2.0]",g={__pytype__:"none"};function q(e=[]){return{__pytype__:"dict",data:new Map(e)}}function Pe(e,t,n=1){return{__pytype__:"range",start:e,stop:t,step:n}}function j(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.__pytype__==="dict"}function Ft(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.__pytype__==="range"}function yt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.__pytype__==="func"}function ke(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.__pytype__==="class"}function zt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.__pytype__==="instance"}function xt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.__pytype__==="none"}function X(e){return e===null||xt(e)?"None":e===!0?"True":e===!1?"False":typeof e=="number"?Number.isInteger(e)?String(e):e.toPrecision(12).replace(/\.?0+$/,""):typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:Array.isArray(e)?`[${e.map(X).join(", ")}]`:j(e)?`{${[...e.data.entries()].map(([t,n])=>`'${t}': ${X(n)}`).join(", ")}}`:Ft(e)?`range(${e.start}, ${e.stop}${e.step!==1?`, ${e.step}`:""})`:yt(e)?`<function ${e.name} at 0x...>`:ke(e)?`<class '${e.name}'>`:zt(e)?`<${e.cls.name} object at 0x...>`:String(e)}function V(e){return e===null||xt(e)?"None":e===!0?"True":e===!1?"False":typeof e=="number"?Number.isInteger(e)?String(e):e.toPrecision(12).replace(/\.?0+$/,""):typeof e=="string"?e:Array.isArray(e)?`[${e.map(X).join(", ")}]`:j(e)?`{${[...e.data.entries()].map(([t,n])=>`'${t}': ${X(n)}`).join(", ")}}`:Ft(e)?`range(${e.start}, ${e.stop}${e.step!==1?`, ${e.step}`:""})`:X(e)}function lt(e){return e===null||xt(e)?!1:typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"||Array.isArray(e)?e.length>0:j(e)?e.data.size>0:Ft(e)?hr(e)>0:!0}function hr(e){if(e.step===0)return 0;let t=Math.ceil((e.stop-e.start)/e.step);return Math.max(0,t)}function xo(e){let t=[];for(let n=e.start;(e.step>0?n<e.stop:n>e.stop)&&(t.push(n),!(t.length>1e4));n+=e.step);return t}function Q(e){if(Array.isArray(e))return e;if(typeof e=="string")return[...e];if(Ft(e))return xo(e);if(j(e))return[...e.data.keys()];throw new H("TypeError",`'${Pt(e)}' object is not iterable`)}function Pt(e){return e===null||xt(e)?"NoneType":typeof e=="boolean"?"bool":typeof e=="number"?Number.isInteger(e)?"int":"float":typeof e=="string"?"str":Array.isArray(e)?"list":j(e)?"dict":Ft(e)?"range":yt(e)?"function":ke(e)?"type":zt(e)?e.cls.name:"object"}var H=class{constructor(t,n){this.type=t;this.message=n}type;message;toString(){return`${this.type}: ${this.message}`}},Et=class{constructor(t){this.value=t}value},Lt=class{},Tt=class{},Ut=class{constructor(t){this.code=t}code};function bo(e){let t=new Map,n=q([["sep","/"],["linesep",`
158
+ `],["curdir","."],["pardir",".."]]);return n.__methods__={getcwd:()=>e,getenv:r=>typeof r=="string"?process.env[r]??g:g,path:q([["join",g],["exists",g],["dirname",g],["basename",g]]),listdir:()=>[]},t.set("__builtins__",g),t.set("__name__","__main__"),t.set("__cwd__",e),t}function $o(e){let t=q([["sep","/"],["curdir","."]]),n=q([["sep","/"],["linesep",`
159
+ `],["name","posix"]]);return n._cwd=e,t._cwd=e,n.path=t,n}function vo(){return q([["version",oe],["version_info",q([["major",3],["minor",11],["micro",2]].map(([e,t])=>[e,t]))],["platform","linux"],["executable","/usr/bin/python3"],["prefix","/usr"],["path",["/usr/lib/python3.11","/usr/lib/python3.11/lib-dynload"]],["argv",[""]],["maxsize",9007199254740991]])}function Co(){return q([["pi",Math.PI],["e",Math.E],["tau",Math.PI*2],["inf",1/0],["nan",NaN],["sqrt",g],["floor",g],["ceil",g],["log",g],["pow",g],["sin",g],["cos",g],["tan",g],["fabs",g],["factorial",g]])}function Po(){return q([["dumps",g],["loads",g]])}function ko(){return q([["match",g],["search",g],["findall",g],["sub",g],["split",g],["compile",g]])}var fr={os:$o,sys:()=>vo(),math:()=>Co(),json:()=>Po(),re:()=>ko(),random:()=>q([["random",g],["randint",g],["choice",g],["shuffle",g]]),time:()=>q([["time",g],["sleep",g],["ctime",g]]),datetime:()=>q([["datetime",g],["date",g],["timedelta",g]]),collections:()=>q([["Counter",g],["defaultdict",g],["OrderedDict",g]]),itertools:()=>q([["chain",g],["product",g],["combinations",g],["permutations",g]]),functools:()=>q([["reduce",g],["partial",g],["lru_cache",g]]),string:()=>q([["ascii_letters","abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"],["digits","0123456789"],["punctuation","!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"]])},ie=class{constructor(t){this.cwd=t}cwd;output=[];stderr=[];modules=new Map;getOutput(){return this.output.join(`
157
160
  `)+(this.output.length?`
158
161
  `:"")}getStderr(){return this.stderr.join(`
159
162
  `)+(this.stderr.length?`
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,`
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
163
+ `:"")}splitArgs(t){let n=[],r=0,o="",s=!1,i="";for(let a=0;a<t.length;a++){let c=t[a];s?(o+=c,c===i&&t[a-1]!=="\\"&&(s=!1)):c==='"'||c==="'"?(s=!0,i=c,o+=c):"([{".includes(c)?(r++,o+=c):")]}".includes(c)?(r--,o+=c):c===","&&r===0?(n.push(o.trim()),o=""):o+=c}return o.trim()&&n.push(o.trim()),n}pyEval(t,n){if(t=t.trim(),!t||t==="None")return g;if(t==="True")return!0;if(t==="False")return!1;if(t==="...")return g;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,`
164
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\").replace(/\\'/g,"'").replace(/\\"/g,'"');let r=t.match(/^f(['"])([\s\S]*)\1$/);if(r){let l=r[2];return l=l.replace(/\{([^{}]+)\}/g,(u,d)=>{try{return V(this.pyEval(d.trim(),n))}catch{return`{${d}}`}}),l}let o=t.match(/^b(['"])(.*)\1$/s);if(o)return o[2];if(t.startsWith("[")&&t.endsWith("]")){let l=t.slice(1,-1).trim();if(!l)return[];let u=l.match(/^(.+?)\s+for\s+(\w+)\s+in\s+(.+?)(?:\s+if\s+(.+))?$/);if(u){let[,d,m,p,h]=u,y=Q(this.pyEval(p.trim(),n)),f=[];for(let S of y){let F=new Map(n);F.set(m,S),!(h&&!lt(this.pyEval(h,F)))&&f.push(this.pyEval(d.trim(),F))}return f}return this.splitArgs(l).map(d=>this.pyEval(d,n))}if(t.startsWith("(")&&t.endsWith(")")){let l=t.slice(1,-1).trim();if(!l)return[];let u=this.splitArgs(l);return u.length===1&&!l.endsWith(",")?this.pyEval(u[0],n):u.map(d=>this.pyEval(d,n))}if(t.startsWith("{")&&t.endsWith("}")){let l=t.slice(1,-1).trim();if(!l)return q();let u=q();for(let d of this.splitArgs(l)){let m=d.indexOf(":");if(m===-1)continue;let p=V(this.pyEval(d.slice(0,m).trim(),n)),h=this.pyEval(d.slice(m+1).trim(),n);u.data.set(p,h)}return u}let s=t.match(/^not\s+(.+)$/);if(s)return!lt(this.pyEval(s[1],n));let i=[["or"],["and"],["in","not in","is not","is","==","!=","<=",">=","<",">"],["+","-"],["**"],["*","//","/","%"]];for(let l of i){let u=this.tryBinaryOp(t,l,n);if(u!==void 0)return u}if(t.startsWith("-")){let l=this.pyEval(t.slice(1),n);if(typeof l=="number")return-l}if(process.env.PY_DEBUG&&console.error("eval:",JSON.stringify(t)),t.endsWith("]")&&!t.startsWith("[")){let l=this.findMatchingBracket(t,"[");if(l!==-1){let u=this.pyEval(t.slice(0,l),n),d=t.slice(l+1,-1);return this.subscript(u,d,n)}}let a=t.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*\(([\s\S]*)\)$/);if(a){let[,l,u]=a,d=(u?.trim()?this.splitArgs(u):[]).map(m=>this.pyEval(m,n));return this.callBuiltin(l,d,n)}let c=this.findDotAccess(t);if(c){let{objExpr:l,attr:u,callPart:d}=c,m=this.pyEval(l,n);if(d!==void 0){let p=d.slice(1,-1),h=p.trim()?this.splitArgs(p).map(y=>this.pyEval(y,n)):[];return this.callMethod(m,u,h,n)}return this.getAttr(m,u,n)}if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)){if(n.has(t))return n.get(t);throw new H("NameError",`name '${t}' is not defined`)}if(/^[A-Za-z_][A-Za-z0-9_.]+$/.test(t)){let l=t.split("."),u=n.get(l[0])??(()=>{throw new H("NameError",`name '${l[0]}' is not defined`)})();for(let d of l.slice(1))u=this.getAttr(u,d,n);return u}return g}findMatchingBracket(t,n){let r=n==="["?"]":n==="("?")":"}",o=0;for(let s=t.length-1;s>=0;s--)if(t[s]===r&&o++,t[s]===n&&(o--,o===0))return s;return-1}findDotAccess(t){let n=0,r=!1,o="";for(let s=t.length-1;s>0;s--){let i=t[s];if(r){i===o&&t[s-1]!=="\\"&&(r=!1);continue}if(i==='"'||i==="'"){r=!0,o=i;continue}if(")]}".includes(i)){n++;continue}if("([{".includes(i)){n--;continue}if(n!==0||i!==".")continue;let a=t.slice(0,s).trim(),l=t.slice(s+1).match(/^(\w+)(\([\s\S]*\))?$/);if(l&&!/^-?\d+$/.test(a))return{objExpr:a,attr:l[1],callPart:l[2]}}return null}tryBinaryOp(t,n,r){let o=0,s=!1,i="";for(let a=t.length-1;a>=0;a--){let c=t[a];if(s){c===i&&t[a-1]!=="\\"&&(s=!1);continue}if(c==='"'||c==="'"){s=!0,i=c;continue}if(")]}".includes(c)){o++;continue}if("([{".includes(c)){o--;continue}if(o===0){for(let l of n)if(t.slice(a,a+l.length)===l){if(l==="*"&&(t[a+1]==="*"||t[a-1]==="*"))continue;let u=t[a-1],d=t[a+l.length];if(/^[a-z]/.test(l)&&(u&&/\w/.test(u)||d&&/\w/.test(d)))continue;let p=t.slice(0,a).trim(),h=t.slice(a+l.length).trim();if(!p||!h)continue;return this.applyBinaryOp(l,p,h,r)}}}}applyBinaryOp(t,n,r,o){if(t==="and"){let a=this.pyEval(n,o);return lt(a)?this.pyEval(r,o):a}if(t==="or"){let a=this.pyEval(n,o);return lt(a)?a:this.pyEval(r,o)}let s=this.pyEval(n,o),i=this.pyEval(r,o);switch(t){case"+":return typeof s=="string"&&typeof i=="string"?s+i:Array.isArray(s)&&Array.isArray(i)?[...s,...i]:s+i;case"-":return s-i;case"*":if(typeof s=="string"&&typeof i=="number")return s.repeat(i);if(Array.isArray(s)&&typeof i=="number"){let a=[];for(let c=0;c<i;c++)a.push(...s);return a}return s*i;case"/":{if(i===0)throw new H("ZeroDivisionError","division by zero");return s/i}case"//":{if(i===0)throw new H("ZeroDivisionError","integer division or modulo by zero");return Math.floor(s/i)}case"%":{if(typeof s=="string")return this.pyStringFormat(s,Array.isArray(i)?i:[i]);if(i===0)throw new H("ZeroDivisionError","integer division or modulo by zero");return s%i}case"**":return s**i;case"==":return X(s)===X(i)||s===i;case"!=":return X(s)!==X(i)&&s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;case"in":return this.pyIn(i,s);case"not in":return!this.pyIn(i,s);case"is":return s===i||xt(s)&&xt(i);case"is not":return!(s===i||xt(s)&&xt(i))}return g}pyIn(t,n){return typeof t=="string"?typeof n=="string"&&t.includes(n):Array.isArray(t)?t.some(r=>X(r)===X(n)):j(t)?t.data.has(V(n)):!1}subscript(t,n,r){if(n.includes(":")){let s=n.split(":").map(c=>c.trim()),i=s[0]?this.pyEval(s[0],r):void 0,a=s[1]?this.pyEval(s[1],r):void 0;return typeof t=="string"||Array.isArray(t)?t.slice(i,a):g}let o=this.pyEval(n,r);if(Array.isArray(t)){let s=o;return s<0&&(s=t.length+s),t[s]??g}if(typeof t=="string"){let s=o;return s<0&&(s=t.length+s),t[s]??g}if(j(t))return t.data.get(V(o))??g;throw new H("TypeError",`'${Pt(t)}' is not subscriptable`)}getAttr(t,n,r){return j(t)?t.data.has(n)?t.data.get(n):n==="path"&&t.path?t.path:g:zt(t)?t.attrs.get(n)??g:typeof t=="string"?{__class__:{__pytype__:"class",name:"str"}}[n]??g:g}callMethod(t,n,r,o){if(typeof t=="string")switch(n){case"upper":return t.toUpperCase();case"lower":return t.toLowerCase();case"strip":return(r[0]?t.replace(new RegExp(`[${r[0]}]+`,"g"),""):t).trim();case"lstrip":return t.trimStart();case"rstrip":return t.trimEnd();case"split":return t.split(typeof r[0]=="string"?r[0]:/\s+/).filter((s,i)=>i>0||s!=="");case"splitlines":return t.split(`
165
+ `);case"join":return Q(r[0]??[]).map(V).join(t);case"replace":return t.replaceAll(V(r[0]??""),V(r[1]??""));case"startswith":return t.startsWith(V(r[0]??""));case"endswith":return t.endsWith(V(r[0]??""));case"find":return t.indexOf(V(r[0]??""));case"index":{let s=t.indexOf(V(r[0]??""));if(s===-1)throw new H("ValueError","substring not found");return s}case"count":return t.split(V(r[0]??"")).length-1;case"format":return this.pyStringFormat(t,r);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=r[0]??0,i=V(r[1]??" ");return t.padStart(Math.floor((s+t.length)/2),i).padEnd(s,i)}case"ljust":return t.padEnd(r[0]??0,V(r[1]??" "));case"rjust":return t.padStart(r[0]??0,V(r[1]??" "));case"zfill":return t.padStart(r[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(n){case"append":return t.push(r[0]??g),g;case"extend":for(let s of Q(r[0]??[]))t.push(s);return g;case"insert":return t.splice(r[0]??0,0,r[1]??g),g;case"pop":{let s=r[0]!==void 0?r[0]:-1,i=s<0?t.length+s:s;return t.splice(i,1)[0]??g}case"remove":{let s=t.findIndex(i=>X(i)===X(r[0]??g));return s!==-1&&t.splice(s,1),g}case"index":{let s=t.findIndex(i=>X(i)===X(r[0]??g));if(s===-1)throw new H("ValueError","is not in list");return s}case"count":return t.filter(s=>X(s)===X(r[0]??g)).length;case"sort":return t.sort((s,i)=>typeof s=="number"&&typeof i=="number"?s-i:V(s).localeCompare(V(i))),g;case"reverse":return t.reverse(),g;case"copy":return[...t];case"clear":return t.splice(0),g}if(j(t))switch(n){case"keys":return[...t.data.keys()];case"values":return[...t.data.values()];case"items":return[...t.data.entries()].map(([s,i])=>[s,i]);case"get":return t.data.get(V(r[0]??""))??r[1]??g;case"update":{if(j(r[0]??g))for(let[s,i]of r[0].data)t.data.set(s,i);return g}case"pop":{let s=V(r[0]??""),i=t.data.get(s)??r[1]??g;return t.data.delete(s),i}case"clear":return t.data.clear(),g;case"copy":return q([...t.data.entries()]);case"setdefault":{let s=V(r[0]??"");return t.data.has(s)||t.data.set(s,r[1]??g),t.data.get(s)??g}}if(j(t)&&t.data.has("name")&&t.data.get("name")==="posix")switch(n){case"getcwd":return this.cwd;case"getenv":return typeof r[0]=="string"?process.env[r[0]]??r[1]??g:g;case"listdir":return[];case"path":return t}if(j(t))switch(n){case"join":return r.map(V).join("/").replace(/\/+/g,"/");case"exists":return!1;case"dirname":return V(r[0]??"").split("/").slice(0,-1).join("/")||"/";case"basename":return V(r[0]??"").split("/").pop()??"";case"abspath":return V(r[0]??"");case"splitext":{let s=V(r[0]??""),i=s.lastIndexOf(".");return i>0?[s.slice(0,i),s.slice(i)]:[s,""]}case"isfile":return!1;case"isdir":return!1}if(j(t)&&t.data.has("version")&&t.data.get("version")===oe&&n==="exit")throw new Ut(r[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(n in s){let i=s[n];return i(...r.map(a=>a))}if(n==="factorial"){let i=r[0]??0,a=1;for(;i>1;)a*=i--;return a}if(n==="gcd"){let i=Math.abs(r[0]??0),a=Math.abs(r[1]??0);for(;a;)[i,a]=[a,i%a];return i}}if(j(t)){if(n==="dumps"){let s=j(r[1]??g)?r[1]:void 0,i=s?s.data.get("indent"):void 0;return JSON.stringify(this.pyToJs(r[0]??g),null,i)}if(n==="loads")return this.jsToPy(JSON.parse(V(r[0]??"")))}if(zt(t)){let s=t.attrs.get(n)??t.cls.methods.get(n)??g;if(yt(s)){let i=new Map(s.closure);return i.set("self",t),s.params.slice(1).forEach((a,c)=>i.set(a,r[c]??g)),this.execBlock(s.body,i)}}throw new H("AttributeError",`'${Pt(t)}' object has no attribute '${n}'`)}pyStringFormat(t,n){let r=0;return t.replace(/%([diouxXeEfFgGcrs%])/g,(o,s)=>{if(s==="%")return"%";let i=n[r++];switch(s){case"d":case"i":return String(Math.trunc(i));case"f":return i.toFixed(6);case"s":return V(i??g);case"r":return X(i??g);default:return String(i)}})}pyToJs(t){return xt(t)?null:j(t)?Object.fromEntries([...t.data.entries()].map(([n,r])=>[n,this.pyToJs(r)])):Array.isArray(t)?t.map(n=>this.pyToJs(n)):t}jsToPy(t){return t==null?g:typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:Array.isArray(t)?t.map(n=>this.jsToPy(n)):typeof t=="object"?q(Object.entries(t).map(([n,r])=>[n,this.jsToPy(r)])):g}callBuiltin(t,n,r){if(r.has(t)){let o=r.get(t)??g;return yt(o)?this.callFunc(o,n,r):ke(o)?this.instantiate(o,n,r):o}switch(t){case"print":return this.output.push(n.map(V).join(" ")+`
166
+ `.replace(/\\n/g,"")),g;case"input":return this.output.push(V(n[0]??"")),"";case"int":{if(n.length===0)return 0;let o=n[1]??10,s=parseInt(V(n[0]??0),o);return Number.isNaN(s)?(()=>{throw new H("ValueError","invalid literal for int()")})():s}case"float":{if(n.length===0)return 0;let o=parseFloat(V(n[0]??0));return Number.isNaN(o)?(()=>{throw new H("ValueError","could not convert to float")})():o}case"str":return n.length===0?"":V(n[0]??g);case"bool":return n.length===0?!1:lt(n[0]??g);case"list":return n.length===0?[]:Q(n[0]??[]);case"tuple":return n.length===0?[]:Q(n[0]??[]);case"set":return n.length===0?[]:[...new Set(Q(n[0]??[]).map(X))].map(o=>Q(n[0]??[]).find(i=>X(i)===o)??g);case"dict":return n.length===0?q():j(n[0]??g)?n[0]:q();case"bytes":return typeof n[0]=="string"?n[0]:V(n[0]??"");case"bytearray":return n.length===0?"":V(n[0]??"");case"type":return n.length===1?`<class '${Pt(n[0]??g)}'>`:g;case"isinstance":return Pt(n[0]??g)===V(n[1]??"");case"issubclass":return!1;case"callable":return yt(n[0]??g);case"hasattr":return j(n[0]??g)?n[0].data.has(V(n[1]??"")):!1;case"getattr":return j(n[0]??g)?n[0].data.get(V(n[1]??""))??n[2]??g:n[2]??g;case"setattr":return j(n[0]??g)&&n[0].data.set(V(n[1]??""),n[2]??g),g;case"len":{let o=n[0]??g;if(typeof o=="string"||Array.isArray(o))return o.length;if(j(o))return o.data.size;if(Ft(o))return hr(o);throw new H("TypeError",`object of type '${Pt(o)}' has no len()`)}case"range":return n.length===1?Pe(0,n[0]):n.length===2?Pe(n[0],n[1]):Pe(n[0],n[1],n[2]);case"enumerate":{let o=n[1]??0;return Q(n[0]??[]).map((s,i)=>[i+o,s])}case"zip":{let o=n.map(Q),s=Math.min(...o.map(i=>i.length));return Array.from({length:s},(i,a)=>o.map(c=>c[a]??g))}case"map":{let o=n[0]??g;return Q(n[1]??[]).map(s=>yt(o)?this.callFunc(o,[s],r):g)}case"filter":{let o=n[0]??g;return Q(n[1]??[]).filter(s=>yt(o)?lt(this.callFunc(o,[s],r)):lt(s))}case"reduce":{let o=n[0]??g,s=Q(n[1]??[]);if(s.length===0)return n[2]??g;let i=n[2]!==void 0?n[2]:s[0];for(let a of n[2]!==void 0?s:s.slice(1))i=yt(o)?this.callFunc(o,[i,a],r):g;return i}case"sorted":{let o=[...Q(n[0]??[])],s=n[1]??g,i=j(s)?s.data.get("key")??g:s;return o.sort((a,c)=>{let l=yt(i)?this.callFunc(i,[a],r):a,u=yt(i)?this.callFunc(i,[c],r):c;return typeof l=="number"&&typeof u=="number"?l-u:V(l).localeCompare(V(u))}),o}case"reversed":return[...Q(n[0]??[])].reverse();case"any":return Q(n[0]??[]).some(lt);case"all":return Q(n[0]??[]).every(lt);case"sum":return Q(n[0]??[]).reduce((o,s)=>o+s,n[1]??0);case"max":return(n.length===1?Q(n[0]??[]):n).reduce((s,i)=>s>=i?s:i);case"min":return(n.length===1?Q(n[0]??[]):n).reduce((s,i)=>s<=i?s:i);case"abs":return Math.abs(n[0]??0);case"round":return n[1]!==void 0?parseFloat(n[0].toFixed(n[1])):Math.round(n[0]??0);case"divmod":{let o=n[0],s=n[1];return[Math.floor(o/s),o%s]}case"pow":return n[0]**n[1];case"hex":return`0x${n[0].toString(16)}`;case"oct":return`0o${n[0].toString(8)}`;case"bin":return`0b${n[0].toString(2)}`;case"ord":return V(n[0]??"").charCodeAt(0);case"chr":return String.fromCharCode(n[0]??0);case"id":return Math.floor(Math.random()*4294967295);case"hash":return typeof n[0]=="number"?n[0]:V(n[0]??"").split("").reduce((o,s)=>o*31+s.charCodeAt(0)|0,0);case"open":throw new H("PermissionError","open() not available in virtual runtime");case"repr":return X(n[0]??g);case"iter":return n[0]??g;case"next":return Array.isArray(n[0])&&n[0].length>0?n[0].shift():n[1]??(()=>{throw new H("StopIteration","")})();case"vars":return q([...r.entries()].map(([o,s])=>[o,s]));case"globals":return q([...r.entries()].map(([o,s])=>[o,s]));case"locals":return q([...r.entries()].map(([o,s])=>[o,s]));case"dir":{if(n.length===0)return[...r.keys()];let o=n[0]??g;return typeof o=="string"?["upper","lower","strip","split","join","replace","find","format","encode","startswith","endswith","count","isdigit","isalpha","title","capitalize"]:Array.isArray(o)?["append","extend","insert","pop","remove","index","count","sort","reverse","copy","clear"]:j(o)?["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(n[0]??""));case"exec":return this.execScript(V(n[0]??""),r),g;case"eval":return this.pyEval(V(n[0]??""),r);default:throw new H("NameError",`name '${t}' is not defined`)}}callFunc(t,n,r){let o=new Map(t.closure);t.params.forEach((s,i)=>{if(s.startsWith("*")){o.set(s.slice(1),n.slice(i));return}o.set(s,n[i]??g)});try{return this.execBlock(t.body,o)}catch(s){if(s instanceof Et)return s.value;throw s}}instantiate(t,n,r){let o={__pytype__:"instance",cls:t,attrs:new Map};return t.methods.get("__init__")&&this.callMethod(o,"__init__",n,r),o}execScript(t,n){let r=t.split(`
167
+ `);this.execLines(r,0,n)}execLines(t,n,r){let o=n;for(;o<t.length;){let s=t[o];if(!s.trim()||s.trim().startsWith("#")){o++;continue}o=this.execStatement(t,o,r)}return o}execBlock(t,n){try{this.execLines(t,0,n)}catch(r){if(r instanceof Et)return r.value;throw r}return g}getIndent(t){let n=0;for(let r of t)if(r===" ")n++;else if(r===" ")n+=4;else break;return n}collectBlock(t,n,r){let o=[];for(let s=n;s<t.length;s++){let i=t[s];if(!i.trim()){o.push("");continue}if(this.getIndent(i)<=r)break;o.push(i.slice(r+4))}return o}execStatement(t,n,r){let o=t[n],s=o.trim(),i=this.getIndent(o);if(s==="pass")return n+1;if(s==="break")throw new Lt;if(s==="continue")throw new Tt;let a=s.match(/^return(?:\s+(.+))?$/);if(a)throw new Et(a[1]?this.pyEval(a[1],r):g);let c=s.match(/^raise(?:\s+(.+))?$/);if(c){if(c[1]){let b=this.pyEval(c[1],r);throw new H(typeof b=="string"?b:Pt(b),V(b))}throw new H("RuntimeError","")}let l=s.match(/^assert\s+(.+?)(?:,\s*(.+))?$/);if(l){if(!lt(this.pyEval(l[1],r)))throw new H("AssertionError",l[2]?V(this.pyEval(l[2],r)):"");return n+1}let u=s.match(/^del\s+(.+)$/);if(u)return r.delete(u[1].trim()),n+1;let d=s.match(/^import\s+(\w+)(?:\s+as\s+(\w+))?$/);if(d){let[,b,M]=d,R=fr[b];if(R){let P=R(this.cwd);this.modules.set(b,P),r.set(M??b,P)}return n+1}let m=s.match(/^from\s+(\w+)\s+import\s+(.+)$/);if(m){let[,b,M]=m,R=fr[b];if(R){let P=R(this.cwd);if(M?.trim()==="*")for(let[C,I]of P.data)r.set(C,I);else for(let C of M.split(",").map(I=>I.trim()))r.set(C,P.data.get(C)??g)}return n+1}let p=s.match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(p){let[,b,M]=p,R=M.split(",").map(I=>I.trim()).filter(Boolean),P=this.collectBlock(t,n+1,i),C={__pytype__:"func",name:b,params:R,body:P,closure:new Map(r)};return r.set(b,C),n+1+P.length}let h=s.match(/^class\s+(\w+)(?:\(([^)]*)\))?\s*:$/);if(h){let[,b,M]=h,R=M?M.split(",").map(J=>J.trim()):[],P=this.collectBlock(t,n+1,i),C={__pytype__:"class",name:b,methods:new Map,bases:R},I=0;for(;I<P.length;){let W=P[I].trim().match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(W){let[,Y,St]=W,pt=St.split(",").map(_=>_.trim()).filter(Boolean),wt=this.collectBlock(P,I+1,0);C.methods.set(Y,{__pytype__:"func",name:Y,params:pt,body:wt,closure:new Map(r)}),I+=1+wt.length}else I++}return r.set(b,C),n+1+P.length}if(s.startsWith("if ")&&s.endsWith(":")){let b=s.slice(3,-1).trim(),M=this.collectBlock(t,n+1,i),R=M.length+1;if(lt(this.pyEval(b,r))){this.execBlock(M,new Map(r).also?.(I=>{for(let[J,W]of r)I.set(J,W)})??r),this.runBlockInScope(M,r);let C=n+1+M.length;for(;C<t.length;){let I=t[C].trim();if(this.getIndent(t[C])<i||!I.startsWith("elif")&&!I.startsWith("else"))break;let J=this.collectBlock(t,C+1,i);C+=1+J.length}return C}let P=n+1+M.length;for(;P<t.length;){let C=t[P],I=C.trim();if(this.getIndent(C)!==i)break;let J=I.match(/^elif\s+(.+):$/);if(J){let W=this.collectBlock(t,P+1,i);if(lt(this.pyEval(J[1],r))){for(this.runBlockInScope(W,r),P+=1+W.length;P<t.length;){let Y=t[P].trim();if(this.getIndent(t[P])!==i||!Y.startsWith("elif")&&!Y.startsWith("else"))break;let St=this.collectBlock(t,P+1,i);P+=1+St.length}return P}P+=1+W.length;continue}if(I==="else:"){let W=this.collectBlock(t,P+1,i);return this.runBlockInScope(W,r),P+1+W.length}break}return P}let y=s.match(/^for\s+(.+?)\s+in\s+(.+?)\s*:$/);if(y){let[,b,M]=y,R=Q(this.pyEval(M.trim(),r)),P=this.collectBlock(t,n+1,i),C=[],I=n+1+P.length;I<t.length&&t[I]?.trim()==="else:"&&(C=this.collectBlock(t,I+1,i),I+=1+C.length);let J=!1;for(let W of R){if(b.includes(",")){let Y=b.split(",").map(pt=>pt.trim()),St=Array.isArray(W)?W:[W];Y.forEach((pt,wt)=>r.set(pt,St[wt]??g))}else r.set(b.trim(),W);try{this.runBlockInScope(P,r)}catch(Y){if(Y instanceof Lt){J=!0;break}if(Y instanceof Tt)continue;throw Y}}return!J&&C.length&&this.runBlockInScope(C,r),I}let f=s.match(/^while\s+(.+?)\s*:$/);if(f){let b=f[1],M=this.collectBlock(t,n+1,i),R=0;for(;lt(this.pyEval(b,r))&&R++<1e5;)try{this.runBlockInScope(M,r)}catch(P){if(P instanceof Lt)break;if(P instanceof Tt)continue;throw P}return n+1+M.length}if(s==="try:"){let b=this.collectBlock(t,n+1,i),M=n+1+b.length,R=[],P=[],C=[];for(;M<t.length;){let J=t[M],W=J.trim();if(this.getIndent(J)!==i)break;if(W.startsWith("except")){let Y=W.match(/^except(?:\s+(\w+)(?:\s+as\s+(\w+))?)?\s*:$/),St=Y?.[1]??null,pt=Y?.[2],wt=this.collectBlock(t,M+1,i);R.push({exc:St,body:wt}),pt&&r.set(pt,""),M+=1+wt.length}else if(W==="else:")C=this.collectBlock(t,M+1,i),M+=1+C.length;else if(W==="finally:")P=this.collectBlock(t,M+1,i),M+=1+P.length;else break}let I=null;try{this.runBlockInScope(b,r),C.length&&this.runBlockInScope(C,r)}catch(J){if(J instanceof H){I=J;let W=!1;for(let Y of R)if(Y.exc===null||Y.exc===J.type||Y.exc==="Exception"){this.runBlockInScope(Y.body,r),W=!0;break}if(!W)throw J}else throw J}finally{P.length&&this.runBlockInScope(P,r)}return M}let S=s.match(/^with\s+(.+?)\s+as\s+(\w+)\s*:$/);if(S){let b=this.collectBlock(t,n+1,i);return r.set(S[2],g),this.runBlockInScope(b,r),n+1+b.length}let F=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(\+=|-=|\*=|\/\/=|\/=|%=|\*\*=|&=|\|=)\s*(.+)$/);if(F){let[,b,M,R]=F,P=r.get(b)??0,C=this.pyEval(R,r),I;switch(M){case"+=":I=typeof P=="string"?P+V(C):P+C;break;case"-=":I=P-C;break;case"*=":I=P*C;break;case"/=":I=P/C;break;case"//=":I=Math.floor(P/C);break;case"%=":I=P%C;break;case"**=":I=P**C;break;default:I=C}return r.set(b,I),n+1}let E=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\[(.+)\]\s*=\s*(.+)$/);if(E){let[,b,M,R]=E,P=r.get(b)??g,C=this.pyEval(R,r)??g,I=this.pyEval(M,r)??g;return Array.isArray(P)?P[I]=C:j(P)&&P.data.set(V(I),C),n+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 M=x[1].slice(0,b),R=x[1].slice(b+1),P=this.pyEval(x[2],r),C=this.pyEval(M,r);return j(C)?C.data.set(R,P):zt(C)&&C.attrs.set(R,P),n+1}}let A=s.match(/^([A-Za-z_][A-Za-z0-9_,\s]*),\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$/);if(A){let b=this.pyEval(A[3],r),M=s.split("=")[0].split(",").map(P=>P.trim()),R=Q(b);return M.forEach((P,C)=>r.set(P,R[C]??g)),n+1}let N=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=]+)?\s*=\s*(.+)$/);if(N){let[,b,M]=N;return r.set(b,this.pyEval(M,r)),n+1}try{this.pyEval(s,r)}catch(b){if(b instanceof H||b instanceof Ut)throw b}return n+1}runBlockInScope(t,n){this.execLines(t,0,n)}run(t){let n=bo(this.cwd);try{this.execScript(t,n)}catch(r){return r instanceof Ut?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:r.code}:r instanceof H?(this.stderr.push(r.toString()),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1}):r instanceof Et?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}:(this.stderr.push(`RuntimeError: ${r}`),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1})}return{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}}},gr={name:"python3",aliases:["python"],description:"Python 3 interpreter (virtual)",category:"system",params:["[--version] [-c <code>] [-V] [file]"],run:({args:e,shell:t,cwd:n})=>{if(!t.packageManager.isInstalled("python3"))return{stderr:`bash: python3: command not found
165
168
  Hint: install it with: apt install python3
166
- `,exitCode:127};if(w(r,["--version","-V"]))return{stdout:`${ai}
167
- `,exitCode:0};if(w(r,["--version-full"]))return{stdout:`${re}
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
169
- `,exitCode:1};let o=s.replace(/\\n/g,`
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}
169
+ `,exitCode:127};if(w(e,["--version","-V"]))return{stdout:`${wo}
170
+ `,exitCode:0};if(w(e,["--version-full"]))return{stdout:`${oe}
171
+ `,exitCode:0};let r=e.indexOf("-c");if(r!==-1){let s=e[r+1];if(!s)return{stderr:`python3: -c requires a code argument
172
+ `,exitCode:1};let i=s.replace(/\\n/g,`
173
+ `).replace(/\\t/g," "),a=new ie(n),{stdout:c,stderr:l,exitCode:u}=a.run(i);return{stdout:c||void 0,stderr:l||void 0,exitCode:u}}let o=e.find(s=>!s.startsWith("-"));if(o){let s=k(n,o);if(!t.vfs.exists(s))return{stderr:`python3: can't open file '${o}': [Errno 2] No such file or directory
174
+ `,exitCode:2};let i=t.vfs.readFile(s),a=new ie(n),{stdout:c,stderr:l,exitCode:u}=a.run(i);return{stdout:c||void 0,stderr:l||void 0,exitCode:u}}return{stdout:`${oe}
172
175
  Type "help", "copyright", "credits" or "license" for more information.
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(`
186
- `):i??"").split(`
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
176
+ >>> `,exitCode:0}}};var yr={name:"read",description:"Read a line from stdin into variables",category:"shell",params:["[-r] [-p prompt] <var...>"],run:({args:e,stdin:t,env:n})=>{let r=e.indexOf("-p"),o=e.filter((a,c)=>a!=="-r"&&a!=="-p"&&e[c-1]!=="-p"),s=(t??"").split(`
177
+ `)[0]??"",i=w(e,["-r"])?s:s.replace(/\\(?:\r?\n|.)/g,a=>a[1]===`
178
+ `||a[1]==="\r"?"":a[1]);if(!n)return{exitCode:0};if(o.length===0)n.vars.REPLY=i;else if(o.length===1)n.vars[o[0]]=i;else{let a=i.split(/\s+/);for(let c=0;c<o.length;c++)n.vars[o[c]]=c<o.length-1?a[c]??"":a.slice(c).join(" ")}return{exitCode:0}}};var Sr={name:"rm",description:"Remove files or directories",category:"files",params:["[-r|-rf] <path>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{if(r.length===0)return{stderr:"rm: missing operand",exitCode:1};let o=w(r,["-r","-rf","-fr"]),s=[];for(let i=0;;i+=1){let a=bt(r,i,{flags:["-r","-rf","-fr"]});if(!a)break;s.push(a)}if(s.length===0)return{stderr:"rm: missing operand",exitCode:1};for(let i of s){let a=k(n,i);z(e,a,"rm"),t.vfs.remove(a,{recursive:o})}return{exitCode:0}}};var wr={name:"sed",description:"Stream editor for filtering and transforming text",category:"text",params:["-e <expr> [file]","s/pattern/replace/[g]"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let s=w(r,["-i"]),i=it(r,["-e"])??r.find(f=>!f.startsWith("-")),a=r.filter(f=>!f.startsWith("-")&&f!==i).pop();if(!i)return{stderr:"sed: no expression",exitCode:1};let c=o??"";if(a){let f=k(n,a);try{c=t.vfs.readFile(f)}catch{return{stderr:`sed: ${a}: No such file or directory`,exitCode:1}}}let l=i.match(/^s([^a-zA-Z0-9])(.+?)\1(.*?)\1([gi]*)$/);if(!l)return{stderr:`sed: unrecognized command: ${i}`,exitCode:1};let[,,u,d,m]=l,p=(m??"").includes("i")?"gi":(m??"").includes("g")?"g":"",h;try{h=new RegExp(u,p||"")}catch{return{stderr:`sed: invalid regex: ${u}`,exitCode:1}}let y=((m??"").includes("g")||p.includes("g"),c.replace(h,d??""));if(s&&a){let f=k(n,a);return t.writeFileAsUser(e,f,y),{exitCode:0}}return{stdout:y,exitCode:0}}};var xr={name:"set",description:"Display or set shell variables",category:"shell",params:["[VAR=value]"],run:({args:e,env:t})=>{if(e.length===0)return{stdout:Object.entries(t.vars).map(([r,o])=>`${r}=${o}`).join(`
179
+ `),exitCode:0};for(let n of e)if(n.includes("=")){let r=n.indexOf("=");t.vars[n.slice(0,r)]=n.slice(r+1)}return{exitCode:0}}};async function br(e,t,n,r,o,s,i){let a={exitCode:0},c=[],l=o,u=0;for(;u<e.length;){let m=e[u];if(a=await Mo(m.pipeline,t,n,r,l,s,i),i.lastExitCode=a.exitCode??0,a.nextCwd&&(a.exitCode??0)===0&&(l=a.nextCwd),a.stdout&&c.push(a.stdout),a.closeSession||a.switchUser)return{...a,stdout:c.join("")||a.stdout};let p=m.op;if(!(!p||p===";")){if(p==="&&"){if((a.exitCode??0)!==0)for(;u<e.length&&e[u]?.op==="&&";)u++}else if(p==="||"&&(a.exitCode??0)===0)for(;u<e.length&&e[u]?.op==="||";)u++}u++}let d=c.join("");return{...a,stdout:d||a.stdout,nextCwd:l!==o?l:void 0}}async function Mo(e,t,n,r,o,s,i){if(!e.isValid)return{stderr:e.error||"Syntax error",exitCode:1};if(e.commands.length===0)return{exitCode:0};let a=i??{vars:{},lastExitCode:0};return e.commands.length===1?Ao(e.commands[0],t,n,r,o,s,a):Eo(e.commands,t,n,r,o,s,a)}async function Ao(e,t,n,r,o,s,i){let a;if(e.inputFile){let l=k(o,e.inputFile);try{a=s.vfs.readFile(l)}catch{return{stderr:`${e.inputFile}: No such file or directory`,exitCode:1}}}let c=await _t(e.name,e.args,t,n,r,o,s,a,i);if(e.outputFile){let l=k(o,e.outputFile),u=c.stdout||"";try{if(e.appendOutput){let d=(()=>{try{return s.vfs.readFile(l)}catch{return""}})();s.writeFileAsUser(t,l,d+u)}else s.writeFileAsUser(t,l,u);return{...c,stdout:""}}catch{return{...c,stderr:`Failed to write to ${e.outputFile}`,exitCode:1}}}return c}async function Eo(e,t,n,r,o,s,i){let a="",c=0;for(let l=0;l<e.length;l++){let u=e[l];if(l===0&&u.inputFile){let m=k(o,u.inputFile);try{a=s.vfs.readFile(m)}catch{return{stderr:`${u.inputFile}: No such file or directory`,exitCode:1}}}let d=await _t(u.name,u.args,t,n,r,o,s,a,i);if(c=d.exitCode??0,l===e.length-1&&u.outputFile){let m=k(o,u.outputFile),p=d.stdout||"";try{if(u.appendOutput){let h=(()=>{try{return s.vfs.readFile(m)}catch{return""}})();s.writeFileAsUser(t,m,h+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&&c!==0)return{stderr:d.stderr,exitCode:c};if(d.closeSession||d.switchUser)return d}return{stdout:a,exitCode:c}}function Ot(e){let t=[],n="",r=!1,o="",s=0;for(;s<e.length;){let i=e[s],a=e[s+1];if((i==='"'||i==="'")&&!r){r=!0,o=i,s++;continue}if(r&&i===o){r=!1,o="",s++;continue}if(r){n+=i,s++;continue}if(i===" "){n&&(t.push(n),n=""),s++;continue}if(!r&&i==="2"&&a===">"){let c=e.slice(s+1);if(c.startsWith(">>&1")||c.startsWith(">> &1")){n&&(t.push(n),n=""),t.push("2>>&1"),s+=5;continue}if(c.startsWith(">&1")){n&&(t.push(n),n=""),t.push("2>&1"),s+=4;continue}if(c.startsWith(">>")){n&&(t.push(n),n=""),t.push("2>>"),s+=3;continue}if(c.startsWith(">")){n&&(t.push(n),n=""),t.push("2>"),s+=2;continue}}if((i===">"||i==="<")&&!r){n&&(t.push(n),n=""),i===">"&&a===">"?(t.push(">>"),s+=2):(t.push(i),s++);continue}n+=i,s++}return n&&t.push(n),t}function $r(e){let t=e.trim();if(!t)return{statements:[],isValid:!0};try{return{statements:Fo(t),isValid:!0}}catch(n){return{statements:[],isValid:!1,error:n.message}}}function Fo(e){let t=No(e),n=[];for(let r of t){let s={pipeline:{commands:_o(r.text.trim()),isValid:!0}};r.op&&(s.op=r.op),n.push(s)}return n}function No(e){let t=[],n="",r=0,o=!1,s="",i=0,a=c=>{n.trim()&&t.push({text:n,op:c}),n=""};for(;i<e.length;){let c=e[i],l=e.slice(i,i+2);if((c==='"'||c==="'")&&!o){o=!0,s=c,n+=c,i++;continue}if(o&&c===s){o=!1,n+=c,i++;continue}if(o){n+=c,i++;continue}if(c==="("){r++,n+=c,i++;continue}if(c===")"){r--,n+=c,i++;continue}if(r>0){n+=c,i++;continue}if(l==="&&"){a("&&"),i+=2;continue}if(l==="||"){a("||"),i+=2;continue}if(c===";"){a(";"),i++;continue}n+=c,i++}return a(),t}function _o(e){return Io(e).map(Vo)}function Io(e){let t=[],n="",r=!1,o="";for(let i=0;i<e.length;i++){let a=e[i];if((a==='"'||a==="'")&&!r){r=!0,o=a,n+=a;continue}if(r&&a===o){r=!1,n+=a;continue}if(r){n+=a;continue}if(a==="|"&&e[i+1]!=="|"){if(!n.trim())throw new Error("Syntax error near unexpected token '|'");t.push(n.trim()),n=""}else n+=a}let s=n.trim();if(!s&&t.length>0)throw new Error("Syntax error near unexpected token '|'");return s&&t.push(s),t}function Vo(e){let t=Ot(e);if(t.length===0)return{name:"",args:[]};let n=[],r,o,s=!1,i=0,a,c=!1,l=!1;for(;i<t.length;){let m=t[i];if(m==="<"){if(i++,i>=t.length)throw new Error("Syntax error: expected filename after <");r=t[i],i++}else if(m===">>"){if(i++,i>=t.length)throw new Error("Syntax error: expected filename after >>");o=t[i],s=!0,i++}else if(m===">"){if(i++,i>=t.length)throw new Error("Syntax error: expected filename after >");o=t[i],s=!1,i++}else if(m==="2>&1")l=!0,i++;else if(m==="2>>"){if(i++,i>=t.length)throw new Error("Syntax error: expected filename after 2>>");a=t[i],c=!0,i++}else if(m==="2>"){if(i++,i>=t.length)throw new Error("Syntax error: expected filename after 2>");a=t[i],c=!1,i++}else n.push(m),i++}let u=n[0]??"";return{name:/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.test(u)?u:u.toLowerCase(),args:n.slice(1),inputFile:r,outputFile:o,appendOutput:s,stderrFile:a,stderrAppend:c,stderrToStdout:l}}function Nt(e,t){return{vars:{PATH:"/usr/local/bin:/usr/bin:/bin",HOME:`/home/${e}`,USER:e,LOGNAME:e,SHELL:"/bin/sh",TERM:"xterm-256color",HOSTNAME:t,PS1:"\\u@\\h:\\w\\$ "},lastExitCode:0}}function vr(e,t,n,r){if(e.startsWith("/")){if(!n.vfs.exists(e))return null;try{let s=n.vfs.stat(e);return s.type!=="file"||!(s.mode&73)||(e.startsWith("/sbin/")||e.startsWith("/usr/sbin/"))&&r!=="root"?null:e}catch{return null}}let o=(t.vars.PATH??"/usr/local/bin:/usr/bin:/bin").split(":");for(let s of o){if((s==="/sbin"||s==="/usr/sbin")&&r!=="root")continue;let i=`${s}/${e}`;if(n.vfs.exists(i))try{let a=n.vfs.stat(i);if(a.type!=="file"||!(a.mode&73))continue;return i}catch{}}return null}async function _t(e,t,n,r,o,s,i,a,c){let l=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/,u=[e,...t],d=0;for(;d<u.length&&l.test(u[d]);)d+=1;if(d>0){let h=u.slice(0,d).map(S=>S.match(l)),y=u.slice(d),f=[];for(let[,S,F]of h)f.push([S,c.vars[S]]),c.vars[S]=F;if(y.length===0)return{exitCode:0};try{return await _t(y[0],y.slice(1),n,r,o,s,i,a,c)}finally{for(let[S,F]of f)F===void 0?delete c.vars[S]:c.vars[S]=F}}let m=c.vars[`__alias_${e}`];if(m)return G(`${m} ${t.join(" ")}`,n,r,o,s,i,a,c);let p=mt(e);if(!p){let h=vr(e,c,i,n);if(h){let y=i.vfs.readFile(h),f=y.match(/exec\s+builtin\s+(\S+)/);if(f){let F=mt(f[1]);if(F)return await F.run({authUser:n,hostname:r,activeSessions:i.users.listActiveSessions(),rawInput:[e,...t].join(" "),mode:o,args:t,stdin:a,cwd:s,shell:i,env:c})}let S=mt("sh");if(S)return await S.run({authUser:n,hostname:r,activeSessions:i.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(y)}`,mode:o,args:["-c",y,"--",...t],stdin:a,cwd:s,shell:i,env:c})}return{stderr:`${e}: command not found`,exitCode:127}}try{return await p.run({authUser:n,hostname:r,activeSessions:i.users.listActiveSessions(),rawInput:[e,...t].join(" "),mode:o,args:t,stdin:a,cwd:s,shell:i,env:c})}catch(h){return{stderr:h instanceof Error?h.message:"Command failed",exitCode:1}}}async function G(e,t,n,r,o,s,i,a){let c=e.trim();if(c.length===0)return{exitCode:0};let l=a??Nt(t,n),d=Ot(c)[0]?.toLowerCase()??"",m=l.vars[`__alias_${d}`],p=m?c.replace(d,m):c,h=/\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),y=/(?<![|&])[|](?![|])/.test(p)||p.includes(">")||p.includes("<")||p.includes("&&")||p.includes("||")||p.includes(";");if(h&&d!=="sh"&&d!=="bash"||y){if(h&&d!=="sh"&&d!=="bash"){let b=mt("sh");if(b)return await b.run({authUser:t,hostname:n,activeSessions:s.users.listActiveSessions(),rawInput:p,mode:r,args:["-c",p],stdin:void 0,cwd:o,shell:s,env:l})}let N=$r(p);if(!N.isValid)return{stderr:N.error||"Syntax error",exitCode:1};try{return await br(N.statements,t,n,r,o,s,l)}catch(b){return{stderr:b instanceof Error?b.message:"Execution failed",exitCode:1}}}let f=await Yt(p,l.vars,l.lastExitCode,N=>G(N,t,n,r,o,s,void 0,l).then(b=>b.stdout??"")),S=Ot(f.trim());if(S.length===0)return{exitCode:0};if(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.test(S[0]))return _t(S[0],S.slice(1),t,n,r,o,s,i,l);let E=S[0]?.toLowerCase()??"",x=S.slice(1).flatMap(Jt),A=mt(E);if(!A){let N=vr(E,l,s,t);if(N){let b=s.vfs.readFile(N),M=b.match(/exec\s+builtin\s+(\S+)/);if(M){let P=M[1],C=mt(P);if(C)return await C.run({authUser:t,hostname:n,activeSessions:s.users.listActiveSessions(),rawInput:[E,...x].join(" "),mode:r,args:x,stdin:i,cwd:o,shell:s,env:l})}let R=mt("sh");if(R)return await R.run({authUser:t,hostname:n,activeSessions:s.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(b)}`,mode:r,args:["-c",b,"--",...x],stdin:i,cwd:o,shell:s,env:l})}return{stderr:`${E}: command not found`,exitCode:127}}try{return await A.run({authUser:t,hostname:n,activeSessions:s.users.listActiveSessions(),rawInput:f,mode:r,args:x,stdin:i,cwd:o,shell:s,env:l})}catch(N){return{stderr:N instanceof Error?N.message:"Command failed",exitCode:1}}}async function Fe(e,t,n,r){return Yt(e,t,n,o=>G(o,r.authUser,r.hostname,r.mode,r.cwd,r.shell,void 0,r.env).then(s=>s.stdout??""))}function $t(e){let t=[],n=0;for(;n<e.length;){let r=e[n].trim();if(!r||r.startsWith("#")){n++;continue}let o=r.match(/^(?:function\s+)?(\w+)\s*\(\s*\)\s*\{(.+)\}\s*$/),s=o??(r.match(/^(?:function\s+)?(\w+)\s*\(\s*\)\s*\{?\s*$/)||r.match(/^function\s+(\w+)\s*\{?\s*$/));if(s){let a=s[1],c=[];if(o){c.push(...o[2].split(";").map(l=>l.trim()).filter(Boolean)),t.push({type:"func",name:a,body:c}),n++;continue}for(n++;n<e.length&&e[n]?.trim()!=="}"&&n<e.length+1;){let l=e[n].trim().replace(/^do\s+/,"");l&&l!=="{"&&c.push(l),n++}n++,t.push({type:"func",name:a,body:c});continue}let i=r.match(/^\(\(\s*(.+?)\s*\)\)$/);if(i){t.push({type:"arith",expr:i[1]}),n++;continue}if(r.startsWith("if ")||r==="if"){let a=r.replace(/^if\s+/,"").replace(/;\s*then\s*$/,"").trim(),c=[],l=[],u=[],d="then",m="";for(n++;n<e.length&&e[n]?.trim()!=="fi";){let p=e[n].trim();p.startsWith("elif ")?(d="elif",m=p.replace(/^elif\s+/,"").replace(/;\s*then\s*$/,"").trim(),l.push({cond:m,body:[]})):p==="else"?d="else":p!=="then"&&(d==="then"?c.push(p):d==="elif"&&l.length>0?l[l.length-1].body.push(p):u.push(p)),n++}t.push({type:"if",cond:a,then_:c,elif:l,else_:u})}else if(r.startsWith("for ")){let a=r.match(/^for\s+(\w+)\s+in\s+(.+?)(?:\s*;\s*do)?$/);if(a){let c=[];for(n++;n<e.length&&e[n]?.trim()!=="done";){let l=e[n].trim().replace(/^do\s+/,"");l&&l!=="do"&&c.push(l),n++}t.push({type:"for",var:a[1],list:a[2],body:c})}else t.push({type:"cmd",line:r})}else if(r.startsWith("while ")){let a=r.replace(/^while\s+/,"").replace(/;\s*do\s*$/,"").trim(),c=[];for(n++;n<e.length&&e[n]?.trim()!=="done";){let l=e[n].trim().replace(/^do\s+/,"");l&&l!=="do"&&c.push(l),n++}t.push({type:"while",cond:a,body:c})}else t.push({type:"cmd",line:r});n++}return t}async function Ee(e,t){let n=await Fe(e,t.env.vars,t.env.lastExitCode,t),r=n.match(/^\[?\s*(.+?)\s*\]?$/);if(r){let s=r[1],i=s.match(/^-([fdeznr])\s+(.+)$/);if(i){let[,l,u]=i,d=k(t.cwd,u);if(l==="f")return t.shell.vfs.exists(d)&&t.shell.vfs.stat(d).type==="file";if(l==="d")return t.shell.vfs.exists(d)&&t.shell.vfs.stat(d).type==="directory";if(l==="e")return t.shell.vfs.exists(d);if(l==="z")return(u??"").length===0;if(l==="n")return(u??"").length>0}let a=s.match(/^"?([^"]*)"?\s*(==|!=|=|<|>)\s*"?([^"]*)"?$/);if(a){let[,l,u,d]=a;if(u==="=="||u==="=")return l===d;if(u==="!=")return l!==d}let c=s.match(/^(\S+)\s+(-eq|-ne|-lt|-le|-gt|-ge)\s+(\S+)$/);if(c){let[,l,u,d]=c,m=Number(l),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 G(n,t.authUser,t.hostname,t.mode,t.cwd,t.shell,void 0,t.env)).exitCode??0)===0}async function vt(e,t){let n={exitCode:0},r="";for(let o of e)if(o.type==="cmd"){let s=await Fe(o.line,t.env.vars,t.env.lastExitCode,t),i=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)/,a=s.trim().split(/\s+/);if(a.length>0&&i.test(a[0])&&a.every(u=>i.test(u))){for(let u of a){let d=u.match(i);t.env.vars[d[1]]=d[2]}t.env.lastExitCode=0;continue}let c=await(async()=>{let l=s.trim().split(/\s+/)[0]??"",u=t.env.vars[`__func_${l}`];if(u){let d=s.trim().split(/\s+/).slice(1),m={...t.env.vars};d.forEach((y,f)=>{t.env.vars[String(f+1)]=y}),t.env.vars[0]=l;let p=u.split(`
180
+ `),h=await vt($t(p),t);for(let y=1;y<=d.length;y++)delete t.env.vars[String(y)];return Object.assign(t.env.vars,{...m,...t.env.vars}),h}return G(s,t.authUser,t.hostname,t.mode,t.cwd,t.shell,void 0,t.env)})();if(t.env.lastExitCode=c.exitCode??0,c.stdout&&(r+=`${c.stdout}
181
+ `),c.stderr)return{...c,stdout:r.trim()};n=c}else if(o.type==="if"){let s=!1;if(await Ee(o.cond,t)){let i=await vt($t(o.then_),t);i.stdout&&(r+=`${i.stdout}
182
+ `),s=!0}else{for(let i of o.elif)if(await Ee(i.cond,t)){let a=await vt($t(i.body),t);a.stdout&&(r+=`${a.stdout}
183
+ `),s=!0;break}if(!s&&o.else_.length>0){let i=await vt($t(o.else_),t);i.stdout&&(r+=`${i.stdout}
184
+ `)}}}else if(o.type==="func")t.env.vars[`__func_${o.name}`]=o.body.join(`
185
+ `);else if(o.type==="arith"){let s=o.expr.trim(),i=s.match(/^(\w+)\s*(\+\+|--)$/);if(i){let a=parseInt(t.env.vars[i[1]]??"0",10);t.env.vars[i[1]]=String(i[2]==="++"?a+1:a-1)}else{let a=s.match(/^(\w+)\s*([+\-*/])=\s*(.+)$/);if(a){let c=parseInt(t.env.vars[a[1]]??"0",10),l=parseInt(a[3],10),u={"+":c+l,"-":c-l,"*":c*l,"/":Math.floor(c/l)};t.env.vars[a[1]]=String(u[a[2]]??c)}else{let c=xe(s,t.env.vars);Number.isNaN(c)||(t.env.lastExitCode=c===0?1:0)}}}else if(o.type==="for"){let i=(await Fe(o.list,t.env.vars,t.env.lastExitCode,t)).trim().split(/\s+/).flatMap(Jt);for(let a of i){t.env.vars[o.var]=a;let c=await vt($t(o.body),t);if(c.stdout&&(r+=`${c.stdout}
186
+ `),c.closeSession)return c}}else if(o.type==="while"){let s=0;for(;s<1e3&&await Ee(o.cond,t);){let i=await vt($t(o.body),t);if(i.stdout&&(r+=`${i.stdout}
187
+ `),i.closeSession)return i;s++}}return{...n,stdout:r.trim()||n.stdout}}function Cr(e){let t=[],n="",r=0,o=!1,s=!1,i=0;for(;i<e.length;){let c=e[i];if(!o&&!s){if(c==="'"){o=!0,n+=c,i++;continue}if(c==='"'){s=!0,n+=c,i++;continue}if(c==="{"){r++,n+=c,i++;continue}if(c==="}"){if(r--,n+=c,i++,r===0){let l=n.trim();for(l&&t.push(l),n="";i<e.length&&(e[i]===";"||e[i]===" ");)i++}continue}if(r===0&&(c===";"||c===`
188
+ `)){let l=n.trim();l&&!l.startsWith("#")&&t.push(l),n="",i++;continue}}else o&&c==="'"?o=!1:s&&c==='"'&&(s=!1);n+=c,i++}let a=n.trim();return a&&!a.startsWith("#")&&t.push(a),t}var Pr={name:"sh",aliases:["bash"],description:"Execute shell script or command",category:"shell",params:["-c <script>","[<file>]"],run:async e=>{let{args:t,shell:n,cwd:r}=e;if(w(t,"-c")){let s=t[t.indexOf("-c")+1]??"";if(!s)return{stderr:"sh: -c requires a script",exitCode:1};let i=Cr(s),a=$t(i);return vt(a,e)}let o=t[0];if(o){let s=k(r,o);if(!n.vfs.exists(s))return{stderr:`sh: ${o}: No such file or directory`,exitCode:1};let i=n.vfs.readFile(s),a=Cr(i),c=$t(a);return vt(c,e)}return{stderr:"sh: invalid usage. Use: sh -c 'cmd' or sh <file>",exitCode:1}}};var kr={name:"shift",description:"Shift positional parameters",category:"shell",params:["[n]"],run:({args:e,env:t})=>{if(!t)return{exitCode:0};let n=parseInt(e[0]??"1",10)||1,r=t.vars.__argv?.split("\0").filter(Boolean)??[];t.vars.__argv=r.slice(n).join("\0");let o=r.slice(n);for(let s=1;s<=9;s++)t.vars[String(s)]=o[s-1]??"";return{exitCode:0}}},Mr={name:"trap",description:"Trap signals and events",category:"shell",params:["[action] [signal...]"],run:({args:e,env:t})=>{if(!t||e.length===0)return{exitCode:0};let n=e[0]??"",r=e.slice(1);for(let o of r)t.vars[`__trap_${o.toUpperCase()}`]=n;return{exitCode:0}}},Ar={name:"return",description:"Return from a shell function",category:"shell",params:["[n]"],run:({args:e,env:t})=>{let n=parseInt(e[0]??"0",10);return t&&(t.lastExitCode=n),{exitCode:n}}};var Er={name:"sleep",description:"Delay execution",category:"system",params:["<seconds>"],run:async({args:e})=>{let t=parseFloat(e[0]??"1");return Number.isNaN(t)||t<0?{stderr:"sleep: invalid time",exitCode:1}:(await new Promise(n=>setTimeout(n,t*1e3)),{exitCode:0})}};var Fr={name:"sort",description:"Sort lines of text",category:"text",params:["[-r] [-n] [-u] [-k <col>] [file...]"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let s=w(r,["-r"]),i=w(r,["-n"]),a=w(r,["-u"]),c=r.filter(h=>!h.startsWith("-")),d=[...(c.length>0?c.map(h=>{try{return z(e,k(n,h),"sort"),t.vfs.readFile(k(n,h))}catch{return""}}).join(`
189
+ `):o??"").split(`
190
+ `).filter(Boolean)].sort((h,y)=>i?Number(h)-Number(y):h.localeCompare(y)),m=s?d.reverse():d;return{stdout:(a?[...new Set(m)]:m).join(`
191
+ `),exitCode:0}}};var Nr={name:"source",aliases:["."],description:"Execute commands from a file in the current shell environment",category:"shell",params:["<file> [args...]"],run:async({args:e,authUser:t,hostname:n,cwd:r,shell:o,env:s})=>{let i=e[0];if(!i)return{stderr:"source: missing filename",exitCode:1};let a=k(r,i);if(!o.vfs.exists(a))return{stderr:`source: ${i}: No such file or directory`,exitCode:1};let c=o.vfs.readFile(a),l=0;for(let u of c.split(`
192
+ `)){let d=u.trim();if(!d||d.startsWith("#"))continue;let m=await G(d,t,n,"shell",r,o,void 0,s);if(l=m.exitCode??0,m.closeSession||m.switchUser)return m}return{exitCode:l}}};var _r={name:"su",description:"Switch user",category:"users",params:["[-] [-c <cmd>] [username]"],run:async({authUser:e,shell:t,args:n,hostname:r,mode:o,cwd:s})=>{let i=n.includes("-")||n.includes("-l")||n.includes("--login"),a=n.indexOf("-c"),c=a!==-1?n[a+1]:void 0,u=n.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)?e==="root"?c?G(c,u,r,o,i?`/home/${u}`:s,t):{switchUser:u,nextCwd:i?`/home/${u}`:void 0,exitCode:0}:t.users.isSudoer(e)?{sudoChallenge:{username:u,targetUser:u,commandLine:c??null,loginShell:i,prompt:"Password: "},exitCode:0}:{stderr:`su: permission denied
190
193
  `,exitCode:1}:{stderr:`su: user '${u}' does not exist
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(`
194
+ `,exitCode:1}}};function Ro(e){let{flags:t,flagsWithValues:n,positionals:r}=ot(e,{flags:["-i","-S"],flagsWithValue:["-u","--user"]}),o=t.has("-i"),s=n.get("-u")||n.get("--user")||"root",i=r.length>0?r.join(" "):null;return{targetUser:s,loginShell:o,commandLine:i}}var Ir={name:"sudo",description:"Execute as superuser",category:"users",params:["<command...>"],run:async({authUser:e,hostname:t,mode:n,cwd:r,shell:o,args:s})=>{let{targetUser:i,loginShell:a,commandLine:c}=Ro(s);if(e!=="root"&&!o.users.isSudoer(e))return{stderr:"sudo: permission denied",exitCode:1};let l=i||"root",u=`[sudo] password for ${e}: `;return e==="root"?!c&&a?{switchUser:l,nextCwd:`/home/${l}`,exitCode:0}:c?G(c,l,t,n,a?`/home/${l}`:r,o):{stderr:"sudo: missing command",exitCode:1}:{sudoChallenge:{username:e,targetUser:l,commandLine:c,loginShell:a,prompt:u},exitCode:0}}};var Vr={name:"tail",description:"Output last lines",category:"text",params:["[-n <lines>] [file...]"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let s=it(r,["-n"]),i=r.find(d=>/^-\d+$/.test(d)),a=typeof s=="string"?parseInt(s,10):i?parseInt(i.slice(1),10):10,c=r.filter(d=>!d.startsWith("-")&&d!==s&&d!==String(a)),l=d=>{let m=d.split(`
192
195
  `),p=d.endsWith(`
193
- `),y=p?m.slice(0,-1):m;return y.slice(Math.max(0,y.length-a)).join(`
196
+ `),h=p?m.slice(0,-1):m;return h.slice(Math.max(0,h.length-a)).join(`
194
197
  `)+(p?`
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
198
+ `:"")};if(c.length===0)return{stdout:l(o??""),exitCode:0};let u=[];for(let d of c){let m=k(n,d);try{z(e,m,"tail"),u.push(l(t.vfs.readFile(m)))}catch{return{stderr:`tail: ${d}: No such file or directory`,exitCode:1}}}return{stdout:u.join(`
199
+ `),exitCode:0}}};var Rr={name:"tar",description:"Archive utility",category:"archive",params:["[-czf|-xzf|-tf] <archive> [files...]"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=[],s=!1;for(let m of r)if(/^-[a-zA-Z]{2,}$/.test(m))for(let p of m.slice(1))o.push(`-${p}`);else if(!s&&/^[cxtdru]{1,}[a-zA-Z]*$/.test(m)&&!m.includes("/")&&!m.startsWith("-")){s=!0;for(let p of m)o.push(`-${p}`)}else o.push(m);let i=o.includes("-c"),a=o.includes("-x"),c=o.includes("-t"),l=o.indexOf("-f"),u=l!==-1?o[l+1]:o.find(m=>m.endsWith(".tar")||m.endsWith(".tar.gz")||m.endsWith(".tgz"));if(!i&&!a&&!c)return{stderr:`tar: must specify -c, -x, or -t
197
200
  `,exitCode:1};if(!u)return{stderr:`tar: no archive specified
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(`
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(`
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(`
204
- `).length-(m.endsWith(`
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
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
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(`
212
- `)||void 0,exitCode:0}:m?(n.writeFileAsUser(r,m,g),u||p.push(`Saving to: '${m}'
213
- ${m} 100%[==================>] ${g.length} B`),{stderr:p.join(`
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,`
201
+ `,exitCode:1};let d=k(n,u);if(i){let m=new Set;l!==-1&&m.add(l+1);let p=o.filter((y,f)=>!y.startsWith("-")&&y!==u&&!m.has(f)),h={};for(let y of p){let f=k(n,y);try{if(t.vfs.stat(f).type==="file")h[y]=t.vfs.readFile(f);else{let F=(E,x)=>{for(let A of t.vfs.list(E)){let N=`${E}/${A}`,b=`${x}/${A}`;t.vfs.stat(N).type==="file"?h[b]=t.vfs.readFile(N):F(N,b)}};F(f,y)}}catch{return{stderr:`tar: ${y}: No such file or directory`,exitCode:1}}}return t.writeFileAsUser(e,d,JSON.stringify(h)),{exitCode:0}}if(c||a){let m;try{m=JSON.parse(t.vfs.readFile(d))}catch{return{stderr:`tar: ${u}: cannot open archive`,exitCode:1}}if(c)return{stdout:Object.keys(m).join(`
202
+ `),exitCode:0};for(let[p,h]of Object.entries(m))t.writeFileAsUser(e,k(n,p),h);return{exitCode:0}}return{stderr:"tar: must specify -c, -x, or -t",exitCode:1}}};var Dr={name:"tee",description:"Read stdin, write to stdout and files",category:"text",params:["[-a] <file...>"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let s=w(r,["-a"]),i=r.filter(c=>!c.startsWith("-")),a=o??"";for(let c of i){let l=k(n,c);if(s){let u=(()=>{try{return t.vfs.readFile(l)}catch{return""}})();t.writeFileAsUser(e,l,u+a)}else t.writeFileAsUser(e,l,a)}return{stdout:a,exitCode:0}}};function It(e,t,n){if(e[e.length-1]==="]"&&(e=e.slice(0,-1)),e[0]==="["&&(e=e.slice(1)),e.length===0)return!1;if(e[0]==="!")return!It(e.slice(1),t,n);let r=e.indexOf("-a");if(r!==-1)return It(e.slice(0,r),t,n)&&It(e.slice(r+1),t,n);let o=e.indexOf("-o");if(o!==-1)return It(e.slice(0,o),t,n)||It(e.slice(o+1),t,n);if(e.length===2){let[s,i=""]=e,c=(l=>l.startsWith("/")?l:`${n}/${l}`.replace(/\/+/g,"/"))(i);switch(s){case"-e":return t.vfs.exists(c);case"-f":return t.vfs.exists(c)&&t.vfs.stat(c).type==="file";case"-d":return t.vfs.exists(c)&&t.vfs.stat(c).type==="directory";case"-r":return t.vfs.exists(c);case"-w":return t.vfs.exists(c);case"-x":return t.vfs.exists(c)&&!!(t.vfs.stat(c).mode&73);case"-s":return t.vfs.exists(c)&&t.vfs.stat(c).type==="file"&&t.vfs.stat(c).size>0;case"-z":return i.length===0;case"-n":return i.length>0;case"-L":return t.vfs.isSymlink(c)}}if(e.length===3){let[s="",i,a=""]=e,c=Number(s),l=Number(a);switch(i){case"=":case"==":return s===a;case"!=":return s!==a;case"<":return s<a;case">":return s>a;case"-eq":return c===l;case"-ne":return c!==l;case"-lt":return c<l;case"-le":return c<=l;case"-gt":return c>l;case"-ge":return c>=l}}return e.length===1?(e[0]??"").length>0:!1}var zr={name:"test",aliases:["["],description:"Evaluate conditional expression",category:"shell",params:["<expression>"],run:({args:e,shell:t,cwd:n})=>{try{return{exitCode:It([...e],t,n)?0:1}}catch{return{stderr:"test: malformed expression",exitCode:2}}}};var Lr={name:"touch",description:"Create or update files",category:"files",params:["<file>"],run:({authUser:e,shell:t,cwd:n,args:r})=>{if(r.length===0)return{stderr:"touch: missing file operand",exitCode:1};for(let o of r){let s=k(n,o);z(e,s,"touch"),t.vfs.exists(s)||t.writeFileAsUser(e,s,"")}return{exitCode:0}}};function Do(e){return e.replace(/\\n/g,`
203
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function Tr(e){let t=[],n=Do(e),r=0;for(;r<n.length;){if(r+2<n.length&&n[r+1]==="-"){let o=n.charCodeAt(r),s=n.charCodeAt(r+2);if(o<=s){for(let i=o;i<=s;i++)t.push(String.fromCharCode(i));r+=3;continue}}t.push(n[r]),r++}return t}var Ur={name:"tr",description:"Translate or delete characters",category:"text",params:["[-d] [-s] <set1> [set2]"],run:({args:e,stdin:t})=>{let n=w(e,["-d"]),r=w(e,["-s"]),o=e.filter(c=>!c.startsWith("-")),s=Tr(o[0]??""),i=Tr(o[1]??""),a=t??"";if(n){let c=new Set(s);a=[...a].filter(l=>!c.has(l)).join("")}else if(i.length>0){let c=new Map;for(let l=0;l<s.length;l++)c.set(s[l],i[l]??i[i.length-1]??"");a=[...a].map(l=>c.get(l)??l).join("")}if(r&&i.length>0){let c=new Set(i);a=a.replace(/(.)\1+/g,(l,u)=>c.has(u)?u:l)}return{stdout:a,exitCode:0}}};var Br={name:"tree",description:"Display directory tree",category:"navigation",params:["[path]"],run:({authUser:e,shell:t,cwd:n,args:r})=>{let o=k(n,bt(r,0)??n);return z(e,o,"tree"),{stdout:t.vfs.tree(o),exitCode:0}}};var Or={name:"true",description:"Return success exit code",category:"shell",params:[],run:()=>({exitCode:0})},Wr={name:"false",description:"Return failure exit code",category:"shell",params:[],run:()=>({exitCode:1})};var jr={name:"type",description:"Describe how a command would be interpreted",category:"shell",params:["<command...>"],run:({args:e,shell:t,env:n})=>{if(e.length===0)return{stderr:"type: missing argument",exitCode:1};let r=(n?.vars?.PATH??"/usr/local/bin:/usr/bin:/bin").split(":"),o=[],s=0;for(let i of e){if(mt(i)){o.push(`${i} is a shell builtin`);continue}let a=!1;for(let c of r){let l=`${c}/${i}`;if(t.vfs.exists(l)){o.push(`${i} is ${l}`),a=!0;break}}a||(o.push(`${i}: not found`),s=1)}return{stdout:o.join(`
204
+ `),exitCode:s}}};var Hr={name:"uname",description:"Print system information",category:"system",params:["[-a] [-s] [-r] [-m]"],run:({shell:e,args:t})=>{let n=w(t,["-a"]),r="Linux",o=e.properties?.kernel??"5.15.0",s=e.properties?.arch??"x86_64",i=e.hostname;return n?{stdout:`${r} ${i} ${o} #1 SMP ${s} GNU/Linux`,exitCode:0}:w(t,["-r"])?{stdout:o,exitCode:0}:w(t,["-m"])?{stdout:s,exitCode:0}:{stdout:r,exitCode:0}}};var qr={name:"uniq",description:"Report or filter out repeated lines",category:"text",params:["[-c] [-d] [-u] [file]"],run:({args:e,stdin:t})=>{let n=w(e,["-c"]),r=w(e,["-d"]),o=w(e,["-u"]),s=(t??"").split(`
205
+ `),i=[],a=0;for(;a<s.length;){let c=a;for(;c<s.length&&s[c]===s[a];)c++;let l=c-a,u=s[a];if(r&&l===1){a=c;continue}if(o&&l>1){a=c;continue}i.push(n?`${String(l).padStart(4)} ${u}`:u),a=c}return{stdout:i.join(`
206
+ `),exitCode:0}}};var Kr={name:"unset",description:"Remove shell variable",category:"shell",params:["<VAR>"],run:({args:e,env:t})=>{for(let n of e)delete t.vars[n];return{exitCode:0}}};var Gr={name:"uptime",description:"Tell how long the system has been running",category:"system",params:["[-p] [-s]"],run:({args:e,shell:t})=>{let n=w(e,["-p"]),r=w(e,["-s"]),o=Math.floor((Date.now()-t.startTime)/1e3),s=Math.floor(o/86400),i=Math.floor(o%86400/3600),a=Math.floor(o%3600/60);if(r)return{stdout:new Date(t.startTime).toISOString().slice(0,19).replace("T"," "),exitCode:0};if(n){let m=[];return s>0&&m.push(`${s} day${s>1?"s":""}`),i>0&&m.push(`${i} hour${i>1?"s":""}`),m.push(`${a} minute${a!==1?"s":""}`),{stdout:`up ${m.join(", ")}`,exitCode:0}}let c=new Date().toTimeString().slice(0,8),l=s>0?`${s} day${s>1?"s":""}, ${String(i).padStart(2)}:${String(a).padStart(2,"0")}`:`${String(i).padStart(2)}:${String(a).padStart(2,"0")}`,u=t.users.listActiveSessions().length,d=(Math.random()*.5).toFixed(2);return{stdout:` ${c} up ${l}, ${u} user${u!==1?"s":""}, load average: ${d}, ${d}, ${d}`,exitCode:0}}};var Zr={name:"wc",description:"Count words/lines/bytes",category:"text",params:["[-l] [-w] [-c] [file...]"],run:({authUser:e,shell:t,cwd:n,args:r,stdin:o})=>{let s=w(r,["-l"]),i=w(r,["-w"]),a=w(r,["-c"]),c=!s&&!i&&!a,l=r.filter(m=>!m.startsWith("-")),u=(m,p)=>{let h=m.length===0?0:m.trim().split(`
207
+ `).length,y=m.trim().split(/\s+/).filter(Boolean).length,f=Buffer.byteLength(m,"utf8"),S=[];return(c||s)&&S.push(String(h).padStart(7)),(c||i)&&S.push(String(y).padStart(7)),(c||a)&&S.push(String(f).padStart(7)),p&&S.push(` ${p}`),S.join("")};if(l.length===0)return{stdout:u(o??"",""),exitCode:0};let d=[];for(let m of l){let p=k(n,m);try{z(e,p,"wc");let h=t.vfs.readFile(p);d.push(u(h,m))}catch{return{stderr:`wc: ${m}: No such file or directory`,exitCode:1}}}return{stdout:d.join(`
208
+ `),exitCode:0}}};var Jr={name:"wget",description:"File downloader (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:e,cwd:t,args:n,shell:r})=>{let{flagsWithValues:o,positionals:s}=ot(n,{flagsWithValue:["-O","--output-document","-o","--output-file","-P","--directory-prefix","--tries","--timeout"]});if(w(n,["-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(`
209
+ `),exitCode:0};if(w(n,["-V","--version"]))return{stdout:"GNU Wget 1.21.3 (virtual) built on Fortune GNU/Linux.",exitCode:0};let i=s[0];if(!i)return{stderr:`wget: missing URL
210
+ Usage: wget [OPTION]... [URL]...`,exitCode:1};let a=i.startsWith("http://")||i.startsWith("https://")?i:`http://${i}`;if(!a)return{stderr:`wget: missing URL
211
+ Usage: wget [OPTION]... [URL]...`,exitCode:1};let c=o.get("-O")??o.get("--output-document")??null,l=o.get("-P")??o.get("--directory-prefix")??null,u=w(n,["-q","--quiet"]),d=c==="-"?null:c??Ke(a),m=d?k(t,l?`${l}/${d}`:d):null;m&&z(e,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 h;try{h=await fetch(a,{headers:{"User-Agent":"Wget/1.21.3 (Fortune GNU/Linux)"}})}catch(f){let S=f instanceof Error?f.message:String(f);return p.push(`wget: unable to resolve host: ${S}`),{stderr:p.join(`
212
+ `),exitCode:4}}if(!h.ok)return p.push(`ERROR ${h.status}: ${h.statusText}`),{stderr:p.join(`
213
+ `),exitCode:8};let y;try{y=await h.text()}catch{return{stderr:"wget: failed to read response",exitCode:1}}if(!u){let f=h.headers.get("content-type")??"application/octet-stream";p.push(`HTTP request sent, awaiting response... ${h.status} ${h.statusText}`),p.push(`Length: ${y.length} [${f}]`)}return c==="-"?{stdout:y,stderr:p.join(`
214
+ `)||void 0,exitCode:0}:m?(r.writeFileAsUser(e,m,y),u||p.push(`Saving to: '${m}'
215
+ ${m} 100%[==================>] ${y.length} B`),{stderr:p.join(`
216
+ `)||void 0,exitCode:0}):{stdout:y,exitCode:0}}};var Yr={name:"which",description:"Locate a command in PATH",category:"shell",params:["<command...>"],run:({args:e,shell:t,env:n})=>{if(e.length===0)return{stderr:"which: missing argument",exitCode:1};let r=(n?.vars?.PATH??"/usr/local/bin:/usr/bin:/bin").split(":"),o=[],s=!1;for(let i of e){let a=!1;for(let c of r){let l=`${c}/${i}`;if(t.vfs.exists(l)&&t.vfs.stat(l).type==="file"){o.push(l),a=!0;break}}a||(s=!0)}return o.length===0?{exitCode:1}:{stdout:o.join(`
217
+ `),exitCode:s?1:0}}};function ae(e){let t=e.toLocaleString("en-US",{weekday:"short"}),n=e.toLocaleString("en-US",{month:"short"}),r=e.getDate().toString().padStart(2,"0"),o=e.getHours().toString().padStart(2,"0"),s=e.getMinutes().toString().padStart(2,"0"),i=e.getSeconds().toString().padStart(2,"0"),a=e.getFullYear();return`${t} ${n} ${r} ${o}:${s}:${i} ${a}`}var Qr={name:"who",description:"Show active sessions",category:"system",params:[],run:({shell:e})=>({stdout:e.users.listActiveSessions().map(n=>{let r=new Date(n.startedAt),o=Number.isNaN(r.getTime())?n.startedAt:ae(r);return`${n.username} ${n.tty} ${o} (${n.remoteAddress||"unknown"})`}).join(`
218
+ `),exitCode:0})};var Xr={name:"whoami",description:"Print current user",category:"system",params:[],run:({authUser:e})=>({stdout:e,exitCode:0})};var ts={name:"xargs",description:"Build and execute command lines from stdin",category:"text",params:["[command] [args...]"],run:async({authUser:e,hostname:t,mode:n,cwd:r,args:o,stdin:s,shell:i,env:a})=>{let c=o[0]??"echo",l=o.slice(1),u=(s??"").trim().split(/\s+/).filter(Boolean);if(u.length===0)return{exitCode:0};let d=[c,...l,...u].join(" ");return G(d,e,t,n,r,i,void 0,a)}};var zo=[pr,tn,Bn,Br,Xe,Lr,Sr,jn,rn,Hn,Dn,zn,en,Ln,Tn,wn,bn,wr,Ye,Fr,qr,Zr,Pn,Vr,on,Ur,Dr,ts,dn,Rr,vn,Cn,Qe,Xr,Qr,_n,Vn,$n,Hr,mr,Rn,un,fn,an,Er,ur,hn,gn,Sn,xr,Kr,Pr,nn,yn,Kn,In,sn,Jr,We,lr,ln,Ir,_r,rr,Ze,Je,mn,pn,Yr,jr,Wn,He,qe,zr,Nr,Nn,dr,yr,cn,kr,Mr,Ar,Or,Wr,ar,cr,ir,gr,Gr,xn,On],es=[],Wt=new Map,ce=null,Lo=Fn(()=>_e().map(e=>e.name));function Ne(){Wt.clear();for(let e of _e()){Wt.set(e.name,e);for(let t of e.aliases??[])Wt.set(t,e)}ce=Array.from(Wt.keys()).sort()}function _e(){return[...zo,...es,Lo]}function Me(e){let t={...e,name:e.name.trim().toLowerCase(),aliases:e.aliases?.map(r=>r.trim().toLowerCase())};if([t.name,...t.aliases??[]].some(r=>r.length===0||/\s/.test(r)))throw new Error("Command names must be non-empty and contain no spaces");es.push(t),Ne()}function Ae(e,t,n){return{name:e,params:t,run:n}}function Bt(){return ce||Ne(),ce}function be(){return _e()}function mt(e){return ce||Ne(),Wt.get(e.toLowerCase())}import{spawn as Uo}from"node:child_process";import{readFile as To}from"node:fs/promises";import*as le from"node:path";function Ie(e){return`'${e.replace(/'/g,"'\\''")}'`}function jt(e){return e.replace(/\r\n/g,`
217
219
  `).replace(/\r/g,`
218
220
  `).replace(/\n/g,`\r
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(`
221
+ `)}function ns(e,t){let n=Number.isFinite(t.cols)&&t.cols>0?Math.floor(t.cols):80,r=Number.isFinite(t.rows)&&t.rows>0?Math.floor(t.rows):24;return`stty cols ${n} rows ${r} 2>/dev/null; ${e}`}function ue(e,t){return!t||t.trim()===""||t==="."?e:t.startsWith("/")?le.posix.normalize(t):le.posix.normalize(le.posix.join(e,t))}async function rs(e){try{let n=(await To(`/proc/${e}/task/${e}/children`,"utf8")).trim().split(/\s+/).filter(Boolean).map(o=>Number.parseInt(o,10)).filter(o=>Number.isInteger(o)&&o>0),r=await Promise.all(n.map(o=>rs(o)));return[...n,...r.flat()]}catch{return[]}}async function ss(e=process.pid){let t=await rs(e),n=Array.from(new Set(t)).sort((r,o)=>r-o);return n.length===0?null:n.join(",")}function os(e,t,n){let r=ns(e,t),o=Uo("script",["-qfec",r,"/dev/null"],{stdio:["pipe","pipe","pipe"],env:{...process.env,TERM:process.env.TERM??"xterm-256color"}});return o.stdout.on("data",s=>{n.write(s.toString("utf8"))}),o.stderr.on("data",s=>{n.write(s.toString("utf8"))}),o}function de(e,t,n){return os(`nano -- ${Ie(e)}`,t,n)}function is(e,t,n){return os(`htop -p ${Ie(e)}`,t,n)}function me(e,t,n){let r=[`Linux ${e} ${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(n){let o=new Date(n.at),s=Number.isNaN(o.getTime())?n.at:ae(o);r.push(`Last login: ${s} from ${n.from||"unknown"}`)}return r.push(""),`${r.map(o=>`${o}\r
222
+ `).join("")}`}function pe(e,t,n){let r=e==="root",o=r?"\x1B[31;1m":"\x1B[35;1m",s="\x1B[37;1m",i="\x1B[34;1m",a="\x1B[0m";return`${s}[${o}${e}${s}@${i}${t}${a} ${n}${s}]${a}${r?"#":"$"} `}import{EventEmitter as mi}from"node:events";import*as kt from"node:os";function $(e,t,n=493){e.exists(t)||e.mkdir(t,n)}function v(e,t,n,r=420){e.exists(t)||e.writeFile(t,n,{mode:r})}function K(e,t,n){e.writeFile(t,n)}function Bo(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function Oo(e,t,n){$(e,"/etc"),v(e,"/etc/os-release",`${['NAME="Fortune GNU/Linux"',`PRETTY_NAME="${n.os}"`,"ID=fortune","ID_LIKE=debian",'HOME_URL="https://github.com/itsrealfortune/typescript-virtual-container"',"VERSION_CODENAME=aurora",'VERSION_ID="1.0"'].join(`
221
223
  `)}
222
- `),U(r,"/etc/debian_version",`12.0
223
- `),U(r,"/etc/hostname",`${t}
224
- `),U(r,"/etc/shells",`/bin/sh
224
+ `),v(e,"/etc/debian_version",`12.0
225
+ `),v(e,"/etc/hostname",`${t}
226
+ `),v(e,"/etc/shells",`/bin/sh
225
227
  /bin/bash
226
228
  /usr/bin/bash
227
- `),U(r,"/etc/profile",`${["export PATH=/usr/local/bin:/usr/bin:/bin","export PS1='\\u@\\h:\\w\\$ '"].join(`
229
+ `),v(e,"/etc/profile",`${["export PATH=/usr/local/bin:/usr/bin:/bin","export PS1='\\u@\\h:\\w\\$ '"].join(`
228
230
  `)}
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(`
231
+ `),v(e,"/etc/issue",`Fortune GNU/Linux 1.0 \\n \\l
232
+ `),v(e,"/etc/motd",["",`Welcome to ${n.os}`,`Kernel: ${n.kernel}`,""].join(`
233
+ `)),$(e,"/etc/apt"),$(e,"/etc/apt/sources.list.d"),v(e,"/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(`
232
234
  `)}
233
- `),F(r,"/etc/network"),U(r,"/etc/network/interfaces",`${["auto lo","iface lo inet loopback","","auto eth0","iface eth0 inet dhcp"].join(`
235
+ `),$(e,"/etc/network"),v(e,"/etc/network/interfaces",`${["auto lo","iface lo inet loopback","","auto eth0","iface eth0 inet dhcp"].join(`
234
236
  `)}
235
- `),U(r,"/etc/resolv.conf",`nameserver 1.1.1.1
237
+ `),v(e,"/etc/resolv.conf",`nameserver 1.1.1.1
236
238
  nameserver 8.8.8.8
237
- `),U(r,"/etc/hosts",`${["127.0.0.1 localhost",`127.0.1.1 ${t}`,"::1 localhost ip6-localhost ip6-loopback"].join(`
239
+ `),v(e,"/etc/hosts",`${["127.0.0.1 localhost",`127.0.1.1 ${t}`,"::1 localhost ip6-localhost ip6-loopback"].join(`
238
240
  `)}
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(`
241
+ `),$(e,"/etc/cron.d"),$(e,"/etc/init.d"),$(e,"/etc/systemd"),$(e,"/etc/systemd/system"),v(e,"/etc/fstab",`${["# <file system> <mount point> <type> <options> <dump> <pass>","UUID=00000000-0000-0000-0000-000000000001 / ext4 errors=remount-ro 0 1","UUID=00000000-0000-0000-0000-000000000002 /boot ext4 defaults 0 2","UUID=00000000-0000-0000-0000-000000000003 none swap sw 0 0","tmpfs /tmp tmpfs defaults,noatime 0 0","tmpfs /run tmpfs defaults,noatime 0 0"].join(`
240
242
  `)}
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(`
243
+ `),v(e,"/etc/login.defs",`${["MAIL_DIR /var/mail","PASS_MAX_DAYS 99999","PASS_MIN_DAYS 0","PASS_WARN_AGE 7","UID_MIN 1000","UID_MAX 60000","GID_MIN 1000","GID_MAX 60000","CREATE_HOME yes","UMASK 022","USERGROUPS_ENAB yes","ENCRYPT_METHOD SHA512"].join(`
242
244
  `)}
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(`
245
+ `),$(e,"/etc/security"),v(e,"/etc/security/limits.conf",`# /etc/security/limits.conf
246
+ `),v(e,"/etc/security/access.conf",`# /etc/security/access.conf
247
+ `),$(e,"/etc/pam.d"),v(e,"/etc/pam.d/common-auth",`auth required pam_unix.so
248
+ `),v(e,"/etc/pam.d/common-account",`account required pam_unix.so
249
+ `),v(e,"/etc/pam.d/common-password",`password required pam_unix.so obscure sha512
250
+ `),v(e,"/etc/pam.d/common-session",`session required pam_unix.so
251
+ `),v(e,"/etc/pam.d/sshd",`@include common-auth
252
+ @include common-account
253
+ @include common-session
254
+ `),$(e,"/etc/sudoers.d"),v(e,"/etc/sudoers",`root ALL=(ALL:ALL) ALL
255
+ %sudo ALL=(ALL:ALL) ALL
256
+ `,288),v(e,"/etc/ld.so.conf",`include /etc/ld.so.conf.d/*.conf
257
+ `),$(e,"/etc/ld.so.conf.d"),v(e,"/etc/ld.so.conf.d/x86_64-linux-gnu.conf",`/lib/x86_64-linux-gnu
258
+ /usr/lib/x86_64-linux-gnu
259
+ `),v(e,"/etc/locale.conf",`LANG=en_US.UTF-8
260
+ `),v(e,"/etc/timezone",`UTC
261
+ `),v(e,"/etc/localtime",`UTC
262
+ `)}function Ve(e,t){let n=t.listUsers(),r=["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"],o=1e3;for(let a of n)a!=="root"&&(r.push(`${a}:x:${o}:${o}::/home/${a}:/bin/bash`),o++);e.writeFile("/etc/passwd",`${r.join(`
263
+ `)}
264
+ `);let s=["root:x:0:","daemon:x:1:",`sudo:x:27:${n.filter(a=>t.isSudoer(a)).join(",")}`,`users:x:100:${n.filter(a=>a!=="root").join(",")}`,"nogroup:x:65534:"];e.writeFile("/etc/group",`${s.join(`
265
+ `)}
266
+ `);let i=["root:*:19000:0:99999:7:::","daemon:*:19000:0:99999:7:::"];for(let a of n)a!=="root"&&i.push(`${a}:!:19000:0:99999:7:::`);e.writeFile("/etc/shadow",`${i.join(`
267
+ `)}
268
+ `,{mode:416})}function as(e){let t=e.match(/(\d+)$/);return 1e3+(t?.[1]?parseInt(t[1],10):0)}function cs(e,t,n,r,o,s,i){let a=`/proc/${t}`;$(e,a),$(e,`${a}/fd`),$(e,`${a}/fdinfo`);let c=Math.floor((Date.now()-new Date(s).getTime())/1e3),l=o.split(/\s+/)[0]??"bash";K(e,`${a}/cmdline`,`${o.replace(/\s+/g,"\0")}\0`),K(e,`${a}/comm`,l),K(e,`${a}/status`,`${[`Name: ${l}`,"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(`
244
269
  `)}
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(`
270
+ `),K(e,`${a}/stat`,`${t} (${l}) S 1 ${t} ${t} 0 -1 4194304 0 0 0 0 ${c} 0 0 0 20 0 1 0 0 16384 4096 0
271
+ `),K(e,`${a}/environ`,`${Object.entries(i).map(([u,d])=>`${u}=${d}`).join("\0")}\0`),K(e,`${a}/cwd`,`/home/${n}\0`),K(e,`${a}/exe`,"/bin/bash\0");for(let u of["0","1","2"])v(e,`${a}/fd/${u}`,"")}function Wo(e,t){$(e,"/proc/boot"),v(e,"/proc/boot/log",`${["[ 0.000000] Linux virtual kernel booting...","[ 0.000120] init memory subsystem","[ 0.000240] mount /proc /sys /dev","[ 0.000420] start init","[ 0.000680] system ready"].join(`
246
272
  `)}
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
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(`
273
+ `),v(e,"/proc/boot/version",`Linux ${t.kernel} (virtual)
274
+ `)}function fe(e,t,n,r,o=[]){$(e,"/proc");let s=Math.floor((Date.now()-r)/1e3),i=Math.floor(s*.9);K(e,"/proc/uptime",`${s}.00 ${i}.00
275
+ `);let a=Math.floor(kt.totalmem()/1024),c=Math.floor(kt.freemem()/1024),l=Math.floor(c*.95);K(e,"/proc/meminfo",`${[`MemTotal: ${String(a).padStart(10)} kB`,`MemFree: ${String(c).padStart(10)} kB`,`MemAvailable: ${String(l).padStart(10)} kB`,`Buffers: ${String(Math.floor(a*.02)).padStart(10)} kB`,`Cached: ${String(Math.floor(a*.15)).padStart(10)} kB`,`SwapTotal: ${String(Math.floor(a*.5)).padStart(10)} kB`,`SwapFree: ${String(Math.floor(a*.5)).padStart(10)} kB`].join(`
250
276
  `)}
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(`
277
+ `);let u=kt.cpus(),d=[];for(let S=0;S<u.length;S++){let F=u[S];F&&d.push(`processor : ${S}`,`model name : ${F.model}`,`cpu MHz : ${F.speed.toFixed(3)}`,"cache size : 8192 KB","")}K(e,"/proc/cpuinfo",`${d.join(`
252
278
  `)}
253
- `),r.writeFile("/proc/version",`Linux version ${t.kernel} (fortune@build) (gcc version 12.2.0) #1 SMP
254
- `),r.writeFile("/proc/hostname",`${e}
255
- `);let d=(Math.random()*.5).toFixed(2),m=1+(i?.length??0);r.writeFile("/proc/loadavg",`${d} ${d} ${d} ${m}/${m} 1
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(`
279
+ `),K(e,"/proc/version",`Linux version ${t.kernel} (fortune@build) (gcc version 12.2.0) #1 SMP
280
+ `),K(e,"/proc/hostname",`${n}
281
+ `);let m=(Math.random()*.5).toFixed(2),p=1+o.length;K(e,"/proc/loadavg",`${m} ${m} ${m} ${p}/${p} 1
282
+ `),$(e,"/proc/net"),v(e,"/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(`
257
283
  `)}
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
284
+ `),v(e,"/proc/net/if_inet6",""),v(e,"/proc/net/tcp",` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
285
+ `),v(e,"/proc/net/tcp6",` sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
286
+ `),K(e,"/proc/cmdline",`BOOT_IMAGE=/boot/vmlinuz-${t.kernel} root=/dev/sda2 ro quiet splash
287
+ `),v(e,"/proc/filesystems",`${["nodev sysfs","nodev tmpfs","nodev proc","nodev devtmpfs"," ext4"," vfat","nodev squashfs","nodev overlay"].join(`
288
+ `)}
289
+ `);let h=`${["sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0","proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0","devtmpfs /dev devtmpfs rw,nosuid,size=8192k,nr_inodes=4096,mode=755 0 0","tmpfs /run tmpfs rw,nosuid,nodev,noexec,relatime,size=204800k,mode=755 0 0","tmpfs /tmp tmpfs rw,nosuid,nodev,noatime 0 0","/dev/sda2 / ext4 rw,relatime,errors=remount-ro 0 0","/dev/sda1 /boot ext4 rw,relatime 0 0","tmpfs /dev/shm tmpfs rw,nosuid,nodev 0 0","devpts /dev/pts devpts rw,nosuid,noexec,relatime,mode=620,ptmxmode=000 0 0","squashfs /snap/core squashfs ro,nodev,relatime 0 0"].join(`
290
+ `)}
291
+ `;K(e,"/proc/mounts",h),$(e,"/proc/self"),K(e,"/proc/self/mounts",h),K(e,"/proc/partitions",`${["major minor #blocks name",""," 8 0 41943040 sda"," 8 1 524288 sda1"," 8 2 41417216 sda2"," 7 0 10485760 loop0"].join(`
292
+ `)}
293
+ `),K(e,"/proc/swaps",`Filename Type Size Used Priority
294
+ /dev/sda3 partition ${Math.floor(kt.totalmem()/2048)} 0 -2
295
+ `),$(e,"/proc/sys"),$(e,"/proc/sys/kernel"),$(e,"/proc/sys/net"),$(e,"/proc/sys/vm"),v(e,"/proc/sys/kernel/hostname",`${n}
296
+ `),v(e,"/proc/sys/kernel/ostype",`Linux
297
+ `),v(e,"/proc/sys/kernel/osrelease",`${t.kernel}
298
+ `),v(e,"/proc/sys/kernel/pid_max",`32768
299
+ `),v(e,"/proc/sys/kernel/threads-max",`65536
300
+ `),v(e,"/proc/sys/kernel/randomize_va_space",`2
301
+ `),v(e,"/proc/sys/kernel/dmesg_restrict",`0
302
+ `),v(e,"/proc/sys/net/ipv4/ip_forward",`0
303
+ `),v(e,"/proc/sys/vm/swappiness",`60
304
+ `),v(e,"/proc/sys/vm/overcommit_memory",`0
305
+ `),cs(e,1,"root","pts/0","/sbin/init",new Date(r).toISOString(),{});for(let S of o){let F=as(S.tty);cs(e,F,S.username,S.tty,"bash",S.startedAt,{USER:S.username,HOME:`/home/${S.username}`,TERM:"xterm-256color",SHELL:"/bin/bash"})}let y=o.length>0?as(o[o.length-1].tty):1;if(e.exists("/proc/self"))try{e.remove("/proc/self")}catch{}let f=`/proc/${y}`;if($(e,"/proc/self"),$(e,"/proc/self/fd"),e.exists(f))for(let S of e.list(f)){let F=`${f}/${S}`,E=`/proc/self/${S}`;try{e.stat(F).type==="file"&&K(e,E,e.readFile(F))}catch{}}else K(e,"/proc/self/cmdline","bash\0"),K(e,"/proc/self/comm","bash"),K(e,"/proc/self/status",`Name: bash
259
306
  State: S (sleeping)
260
307
  Pid: 1
261
308
  PPid: 0
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
269
- exec builtin ${e} "$@"
270
- `,493);U(r,"/usr/bin/lsb_release",`#!/bin/sh
309
+ `),K(e,"/proc/self/environ",""),K(e,"/proc/self/cwd","/root\0"),K(e,"/proc/self/exe","/bin/bash\0")}function jo(e,t,n){$(e,"/sys"),$(e,"/sys/devices"),$(e,"/sys/devices/virtual"),$(e,"/sys/devices/virtual/dmi"),$(e,"/sys/devices/virtual/dmi/id");let r=Bo(t),o=`VirtualNode-${(r%1e4).toString().padStart(4,"0")}`,s={bios_vendor:"Virtual BIOS",bios_version:"1.0",bios_date:"01/01/2025",sys_vendor:"Fortune Systems",product_name:o,product_family:"VirtualContainer",product_version:"v1",product_uuid:`${r.toString(16).padStart(8,"0")}-0000-0000-0000-000000000000`,product_serial:`SN-${r}`,chassis_type:"3",chassis_vendor:"Virtual",chassis_version:"v1",board_name:"fortune-board",modalias:`dmi:bvnVirtual:bvr1.0:svnFortune:pn${o}`};for(let[i,a]of Object.entries(s))v(e,`/sys/devices/virtual/dmi/id/${i}`,`${a}
310
+ `);$(e,"/sys/class"),$(e,"/sys/class/net"),$(e,"/sys/kernel"),v(e,"/sys/kernel/hostname",`${t}
311
+ `),v(e,"/sys/kernel/osrelease",`${n.kernel}
312
+ `),v(e,"/sys/kernel/ostype",`Linux
313
+ `)}function Ho(e){$(e,"/dev"),v(e,"/dev/null","",438),v(e,"/dev/zero","",438),v(e,"/dev/full","",438),v(e,"/dev/random","",292),v(e,"/dev/urandom","",292),v(e,"/dev/mem","",416),v(e,"/dev/console","",384),v(e,"/dev/tty","",438),v(e,"/dev/tty0","",400),v(e,"/dev/tty1","",400),v(e,"/dev/ttyS0","",432);for(let t=0;t<8;t++)v(e,`/dev/loop${t}`,"",432);$(e,"/dev/loop-control"),v(e,"/dev/sda","",432),v(e,"/dev/sda1","",432),v(e,"/dev/sda2","",432),$(e,"/dev/pts"),$(e,"/dev/shm"),v(e,"/dev/stdin","",438),v(e,"/dev/stdout","",438),v(e,"/dev/stderr","",438)}function qo(e){$(e,"/usr"),$(e,"/usr/bin"),$(e,"/usr/sbin"),$(e,"/usr/local"),$(e,"/usr/local/bin"),$(e,"/usr/local/lib"),$(e,"/usr/local/share"),$(e,"/usr/share"),$(e,"/usr/share/doc"),$(e,"/usr/share/man"),$(e,"/usr/share/man/man1"),$(e,"/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 n of t)v(e,`/usr/bin/${n}`,`#!/bin/sh
314
+ exec builtin ${n} "$@"
315
+ `,493);v(e,"/usr/bin/lsb_release",`#!/bin/sh
271
316
  exec lsb_release "$@"
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(`
317
+ `,493)}function Ko(e){$(e,"/var"),$(e,"/var/log"),$(e,"/var/log/apt"),$(e,"/var/tmp"),$(e,"/var/cache"),$(e,"/var/cache/apt"),$(e,"/var/cache/apt/archives"),$(e,"/var/lib"),$(e,"/var/lib/apt"),$(e,"/var/lib/apt/lists"),$(e,"/var/lib/dpkg"),$(e,"/var/lib/dpkg/info"),$(e,"/var/lib/misc"),$(e,"/var/spool"),$(e,"/var/spool/cron"),$(e,"/var/mail"),v(e,"/var/lib/dpkg/status",""),v(e,"/var/lib/dpkg/available",""),v(e,"/var/log/syslog",`${new Date().toUTCString()} fortune kernel: Virtual container started
318
+ `),v(e,"/var/log/auth.log",""),v(e,"/var/log/kern.log",""),v(e,"/var/log/dpkg.log",""),v(e,"/var/log/apt/history.log",""),v(e,"/var/log/apt/term.log",""),$(e,"/run"),$(e,"/run/lock"),$(e,"/run/systemd"),$(e,"/run/user"),v(e,"/run/utmp","")}function Go(e){e.exists("/bin")||e.symlink("/usr/bin","/bin"),e.exists("/sbin")||e.symlink("/usr/sbin","/sbin"),e.exists("/var/run")||e.symlink("/run","/var/run"),$(e,"/lib"),$(e,"/lib64"),$(e,"/lib/x86_64-linux-gnu"),$(e,"/lib/modules")}function Zo(e){$(e,"/tmp",1023)}function Jo(e){$(e,"/root",448),v(e,"/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(`
319
+ `)}
320
+ `),v(e,"/root/.profile",`[ -f ~/.bashrc ] && . ~/.bashrc
321
+ `)}function Yo(e,t){$(e,"/opt"),$(e,"/srv"),$(e,"/mnt"),$(e,"/media"),$(e,"/home"),$(e,"/boot"),$(e,"/boot/grub"),$(e,"/boot/grub/grub.cfg.d"),v(e,"/boot/grub/grub.cfg",`${["# GRUB configuration (virtual)","set default=0","set timeout=5","",'menuentry "Fortune GNU/Linux" {'," linux /vmlinuz root=/dev/sda2 ro quiet splash"," initrd /initrd.img","}"].join(`
274
322
  `)}
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(`
277
- `).slice(1).map(m=>`${u}${m}`);n.push(...d)}}return n.join(`
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
323
+ `);let n=t.kernel;v(e,`/boot/vmlinuz-${n}`,"",420),v(e,`/boot/initrd.img-${n}`,"",420),v(e,`/boot/System.map-${n}`,`${n} virtual
324
+ `,420),v(e,`/boot/config-${n}`,`# Linux kernel config ${n}
325
+ `,420),e.exists("/vmlinuz")||e.symlink(`/boot/vmlinuz-${n}`,"/vmlinuz"),e.exists("/vmlinuz.old")||e.symlink(`/boot/vmlinuz-${n}`,"/vmlinuz.old"),e.exists("/initrd.img")||e.symlink(`/boot/initrd.img-${n}`,"/initrd.img"),e.exists("/initrd.img.old")||e.symlink(`/boot/initrd.img-${n}`,"/initrd.img.old"),$(e,"/snap"),$(e,"/snap/bin"),$(e,"/lost+found",448)}function ls(e,t,n,r,o,s=[]){Oo(e,n,r),jo(e,n,r),Ho(e),qo(e),Ko(e),Go(e),Zo(e),Jo(e),Yo(e,r),Wo(e,r),fe(e,r,n,o,s),Ve(e,t)}function us(e){return e==="1"||e==="true"}function ds(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Qo(){return us(process.env.DEV_MODE)||us(process.env.RENDER_PERF)}function he(e){let t=Qo();if(!t)return{enabled:t,mark:()=>{},done:()=>{}};let n=ds(),r=s=>{let i=ds()-n;console.log(`[perf][${e}] ${s}: ${i.toFixed(1)}ms`)};return{enabled:t,mark:r,done:(s="done")=>{r(s)}}}import{EventEmitter as ei}from"node:events";import*as B from"node:fs";import*as at from"node:path";import{gunzipSync as Le,gzipSync as ws}from"node:zlib";var ze=Buffer.from([86,70,83,33]),Xo=1,ms=1,ps=2,Re=class{chunks=[];write(t){this.chunks.push(t)}writeUint8(t){let n=Buffer.allocUnsafe(1);n.writeUInt8(t,0),this.chunks.push(n)}writeUint16(t){let n=Buffer.allocUnsafe(2);n.writeUInt16LE(t,0),this.chunks.push(n)}writeUint32(t){let n=Buffer.allocUnsafe(4);n.writeUInt32LE(t,0),this.chunks.push(n)}writeFloat64(t){let n=Buffer.allocUnsafe(8);n.writeDoubleBE(t,0),this.chunks.push(n)}writeString(t){let n=Buffer.from(t,"utf8");this.writeUint16(n.length),this.chunks.push(n)}writeBytes(t){this.writeUint32(t.length),this.chunks.push(t)}toBuffer(){return Buffer.concat(this.chunks)}};function fs(e,t){if(t.type==="file"){let n=t;e.writeUint8(ms),e.writeString(n.name),e.writeUint32(n.mode),e.writeFloat64(n.createdAt.getTime()),e.writeFloat64(n.updatedAt.getTime()),e.writeUint8(n.compressed?1:0),e.writeBytes(n.content)}else{let n=t;e.writeUint8(ps),e.writeString(n.name),e.writeUint32(n.mode),e.writeFloat64(n.createdAt.getTime()),e.writeFloat64(n.updatedAt.getTime());let r=Array.from(n.children.values());e.writeUint32(r.length);for(let o of r)fs(e,o)}}function hs(e){let t=new Re;return t.write(ze),t.writeUint8(Xo),fs(t,e),t.toBuffer()}var De=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(),n=this.buf.toString("utf8",this.pos,this.pos+t);return this.pos+=t,n}readBytes(){let t=this.readUint32(),n=this.buf.slice(this.pos,this.pos+t);return this.pos+=t,n}remaining(){return this.buf.length-this.pos}};function gs(e){let t=e.readUint8(),n=e.readString(),r=e.readUint32(),o=new Date(e.readFloat64()),s=new Date(e.readFloat64());if(t===ms){let i=e.readUint8()===1,a=e.readBytes();return{type:"file",name:n,mode:r,createdAt:o,updatedAt:s,compressed:i,content:a}}if(t===ps){let i=e.readUint32(),a=new Map;for(let c=0;c<i;c++){let l=gs(e);a.set(l.name,l)}return{type:"directory",name:n,mode:r,createdAt:o,updatedAt:s,children:a}}throw new Error(`[VFS binary] Unknown node type: 0x${t.toString(16)}`)}function ys(e){if(e.length<5)throw new Error("[VFS binary] Buffer too short");if(!e.slice(0,4).equals(ze))throw new Error("[VFS binary] Invalid magic \u2014 not a VFS binary snapshot");let n=new De(e);for(let o=0;o<5;o++)n.readUint8();let r=gs(n);if(r.type!=="directory")throw new Error("[VFS binary] Root node must be a directory");return r}function Ss(e){return e.length>=4&&e.slice(0,4).equals(ze)}import*as ge from"node:path";function O(e){if(!e||e.trim()==="")return"/";let t=ge.posix.normalize(e.startsWith("/")?e:`/${e}`);return t===""?"/":t}function ti(e){return e.split("/").filter(Boolean)}function rt(e,t){let n=O(t);if(n==="/")return e;let r=ti(n),o=e;for(let s of r){if(o.type!=="directory")throw new Error(`Path '${n}' does not exist.`);let i=o.children.get(s);if(!i)throw new Error(`Path '${n}' does not exist.`);o=i}return o}function Vt(e,t,n,r){let o=O(t);if(o==="/")throw new Error("Root path has no parent directory.");let s=ge.posix.dirname(o),i=ge.posix.basename(o);if(!i)throw new Error(`Invalid path '${t}'.`);n&&r(s);let a=rt(e,s);if(a.type!=="directory")throw new Error(`Parent path '${s}' is not a directory.`);return{parent:a,name:i}}var Te=class e extends ei{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=at.resolve(t.snapshotPath,"vfs-snapshot.vfsb")}else this.snapshotFile=null;this.root=this.makeDir("",493)}makeDir(t,n){let r=new Date;return{type:"directory",name:t,mode:n,createdAt:r,updatedAt:r,children:new Map}}makeFile(t,n,r,o){let s=new Date;return{type:"file",name:t,content:n,mode:r,compressed:o,createdAt:s,updatedAt:s}}mkdirRecursive(t,n){let r=O(t);if(r==="/")return;let o=r.split("/").filter(Boolean),s=this.root,i="";for(let a of o){i+=`/${a}`;let c=s.children.get(a);if(!c)c=this.makeDir(a,n),s.children.set(a,c),this.emit("dir:create",{path:i,mode:n});else if(c.type!=="directory")throw new Error(`Cannot create directory '${i}': path is a file.`);s=c}}async restoreMirror(){if(!(this.mode!=="fs"||!this.snapshotFile)&&B.existsSync(this.snapshotFile))try{let t=B.readFileSync(this.snapshotFile);if(Ss(t))this.root=ys(t);else{let n=JSON.parse(t.toString("utf8"));this.root=this.deserializeDir(n.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=at.dirname(this.snapshotFile);B.mkdirSync(t,{recursive:!0});let n=hs(this.root);B.writeFileSync(this.snapshotFile,n),this.emit("mirror:flush",{path:this.snapshotFile})}getMode(){return this.mode}getSnapshotPath(){return this.snapshotFile}mount(t,n,{readOnly:r=!0}={}){if(e.isBrowser)return;let o=O(t),s=at.resolve(n);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(o),this.mounts.set(o,{hostPath:s,readOnly:r}),this.emit("mount",{vPath:o,hostPath:s,readOnly:r})}unmount(t){let n=O(t);this.mounts.delete(n)&&this.emit("unmount",{vPath:n})}getMounts(){return[...this.mounts.entries()].map(([t,n])=>({vPath:t,...n}))}resolveMount(t){let n=O(t),r=[...this.mounts.entries()].sort(([o],[s])=>s.length-o.length);for(let[o,s]of r)if(n===o||n.startsWith(`${o}/`)){let i=n.slice(o.length).replace(/^\//,""),a=i?at.join(s.hostPath,i):s.hostPath;return{hostPath:s.hostPath,readOnly:s.readOnly,relPath:i,fullHostPath:a}}return null}mkdir(t,n=493){let r=O(t),o=(()=>{try{return rt(this.root,r)}catch{return null}})();if(o&&o.type!=="directory")throw new Error(`Cannot create directory '${r}': path is a file.`);this.mkdirRecursive(r,n)}writeFile(t,n,r={}){let o=this.resolveMount(t);if(o){if(o.readOnly)throw new Error(`EROFS: read-only file system, open '${o.fullHostPath}'`);let p=at.dirname(o.fullHostPath);B.existsSync(p)||B.mkdirSync(p,{recursive:!0}),B.writeFileSync(o.fullHostPath,Buffer.isBuffer(n)?n:Buffer.from(n,"utf8"));return}let s=O(t),{parent:i,name:a}=Vt(this.root,s,!0,p=>this.mkdirRecursive(p,493)),c=i.children.get(a);if(c?.type==="directory")throw new Error(`Cannot write file '${s}': path is a directory.`);let l=Buffer.isBuffer(n)?n:Buffer.from(n,"utf8"),u=r.compress??!1,d=u?ws(l):l,m=r.mode??420;if(c){let p=c;p.content=d,p.compressed=u,p.mode=m,p.updatedAt=new Date}else i.children.set(a,this.makeFile(a,d,m,u));this.emit("file:write",{path:s,size:d.length})}readFile(t){let n=this.resolveMount(t);if(n){if(!B.existsSync(n.fullHostPath))throw new Error(`ENOENT: no such file or directory, open '${n.fullHostPath}'`);return B.readFileSync(n.fullHostPath,"utf8")}let r=O(t),o=rt(this.root,r);if(o.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let s=o,i=s.compressed?Le(s.content):s.content;return this.emit("file:read",{path:r,size:i.length}),i.toString("utf8")}readFileRaw(t){let n=this.resolveMount(t);if(n){if(!B.existsSync(n.fullHostPath))throw new Error(`ENOENT: no such file or directory, open '${n.fullHostPath}'`);return B.readFileSync(n.fullHostPath)}let r=O(t),o=rt(this.root,r);if(o.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let s=o,i=s.compressed?Le(s.content):s.content;return this.emit("file:read",{path:r,size:i.length}),i}exists(t){let n=this.resolveMount(t);if(n)return B.existsSync(n.fullHostPath);try{return rt(this.root,O(t)),!0}catch{return!1}}chmod(t,n){rt(this.root,O(t)).mode=n}stat(t){let n=this.resolveMount(t);if(n){if(!B.existsSync(n.fullHostPath))throw new Error(`ENOENT: stat '${n.fullHostPath}'`);let a=B.statSync(n.fullHostPath),c=n.relPath.split("/").pop()??n.fullHostPath.split("/").pop()??"",l=a.mtime;return a.isDirectory()?{type:"directory",name:c,path:O(t),mode:493,createdAt:a.birthtime,updatedAt:l,childrenCount:B.readdirSync(n.fullHostPath).length}:{type:"file",name:c,path:O(t),mode:n.readOnly?292:420,createdAt:a.birthtime,updatedAt:l,compressed:!1,size:a.size}}let r=O(t),o=rt(this.root,r),s=r==="/"?"":at.posix.basename(r);if(o.type==="file"){let a=o;return{type:"file",name:s,path:r,mode:a.mode,createdAt:a.createdAt,updatedAt:a.updatedAt,compressed:a.compressed,size:a.content.length}}let i=o;return{type:"directory",name:s,path:r,mode:i.mode,createdAt:i.createdAt,updatedAt:i.updatedAt,childrenCount:i.children.size}}list(t="/"){let n=this.resolveMount(t);if(n){if(!B.existsSync(n.fullHostPath))return[];try{return B.readdirSync(n.fullHostPath).sort()}catch{return[]}}let r=O(t),o=rt(this.root,r);if(o.type!=="directory")throw new Error(`Cannot list '${t}': not a directory.`);return Array.from(o.children.keys()).sort()}tree(t="/"){let n=O(t),r=rt(this.root,n);if(r.type!=="directory")throw new Error(`Cannot render tree for '${t}': not a directory.`);let o=t==="/"?"/":at.posix.basename(n);return this.renderTreeLines(r,o)}renderTreeLines(t,n){let r=[n],o=Array.from(t.children.keys()).sort();for(let s=0;s<o.length;s++){let i=o[s],a=t.children.get(i),c=s===o.length-1,l=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=c?" ":"\u2502 ";if(r.push(`${l}${i}`),a.type==="directory"){let d=this.renderTreeLines(a,"").split(`
326
+ `).slice(1).map(m=>`${u}${m}`);r.push(...d)}}return r.join(`
327
+ `)}getUsageBytes(t="/"){return this.computeUsage(rt(this.root,O(t)))}computeUsage(t){if(t.type==="file")return t.content.length;let n=0;for(let r of t.children.values())n+=this.computeUsage(r);return n}compressFile(t){let n=rt(this.root,O(t));if(n.type!=="file")throw new Error(`Cannot compress '${t}': not a file.`);let r=n;r.compressed||(r.content=ws(r.content),r.compressed=!0,r.updatedAt=new Date)}decompressFile(t){let n=rt(this.root,O(t));if(n.type!=="file")throw new Error(`Cannot decompress '${t}': not a file.`);let r=n;r.compressed&&(r.content=Le(r.content),r.compressed=!1,r.updatedAt=new Date)}symlink(t,n){let r=O(n),o=t.startsWith("/")?O(t):t,{parent:s,name:i}=Vt(this.root,r,!0,c=>this.mkdirRecursive(c,493)),a={type:"file",name:i,content:Buffer.from(o,"utf8"),mode:41471,compressed:!1,createdAt:new Date,updatedAt:new Date};s.children.set(i,a),this.emit("symlink:create",{link:r,target:o})}isSymlink(t){try{let n=rt(this.root,O(t));return n.type==="file"&&n.mode===41471}catch{return!1}}resolveSymlink(t,n=8){let r=O(t);for(let o=0;o<n;o++){try{let s=rt(this.root,r);if(s.type==="file"&&s.mode===41471){let i=s.content.toString("utf8");r=i.startsWith("/")?i:O(at.posix.join(at.posix.dirname(r),i));continue}}catch{break}return r}throw new Error(`Too many levels of symbolic links: ${t}`)}remove(t,n={}){let r=this.resolveMount(t);if(r){if(r.readOnly)throw new Error(`EROFS: read-only file system, unlink '${r.fullHostPath}'`);if(!B.existsSync(r.fullHostPath))throw new Error(`ENOENT: no such file or directory, unlink '${r.fullHostPath}'`);B.statSync(r.fullHostPath).isDirectory()?B.rmSync(r.fullHostPath,{recursive:n.recursive??!1}):B.unlinkSync(r.fullHostPath);return}let o=O(t);if(o==="/")throw new Error("Cannot remove root directory.");let s=rt(this.root,o);if(s.type==="directory"){let c=s;if(!n.recursive&&c.children.size>0)throw new Error(`Directory '${o}' is not empty. Use recursive option.`)}let{parent:i,name:a}=Vt(this.root,o,!1,()=>{});i.children.delete(a),this.emit("node:remove",{path:o})}move(t,n){let r=O(t),o=O(n);if(r==="/"||o==="/")throw new Error("Cannot move root directory.");let s=rt(this.root,r);if(this.exists(o))throw new Error(`Destination '${o}' already exists.`);this.mkdirRecursive(at.posix.dirname(o),493);let{parent:i,name:a}=Vt(this.root,o,!1,()=>{}),{parent:c,name:l}=Vt(this.root,r,!1,()=>{});c.children.delete(l),s.name=a,i.children.set(a,s)}toSnapshot(){return{root:this.serializeDir(this.root)}}serializeDir(t){let n=[];for(let r of t.children.values())n.push(r.type==="file"?this.serializeFile(r):this.serializeDir(r));return{type:"directory",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),children:n}}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 n=new e;return n.root=n.deserializeDir(t.root,""),n}importSnapshot(t){this.root=this.deserializeDir(t.root,""),this.emit("snapshot:import")}deserializeDir(t,n){let r={type:"directory",name:n,mode:t.mode,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),children:new Map};for(let o of t.children)if(o.type==="file"){let s=o;r.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(o,o.name);r.children.set(o.name,s)}return r}},xs=Te;var Ue=[{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
279
328
  echo 'vim: use nano for editing in this environment'
280
329
  `,mode:493},{path:"/usr/bin/vi",content:`#!/bin/sh
281
330
  exec vim "$@"
@@ -348,7 +397,7 @@ echo 'rsync: virtual stub'
348
397
  echo 'tmux: terminal multiplexer (virtual stub)'
349
398
  `,mode:493}]},{name:"tree",version:"2.1.0-1",section:"utils",description:"Displays an indented directory tree, in color",shortDesc:"list files in tree format",installedSizeKb:108,files:[{path:"/usr/bin/tree",content:`#!/bin/sh
350
399
  exec builtin tree "$@"
351
- `,mode:493}]},{name:"ca-certificates",version:"20230311",section:"misc",description:"Common CA certificates",shortDesc:"common CA certificates",installedSizeKb:388,files:[{path:"/etc/ssl/certs/.keep",content:""},{path:"/etc/ssl/private/.keep",content:""},{path:"/usr/share/ca-certificates/.keep",content:""}],onInstall:r=>{r.exists("/etc/ssl")||r.mkdir("/etc/ssl",493),r.exists("/etc/ssl/certs")||r.mkdir("/etc/ssl/certs",493)}},{name:"locales",version:"2.36-9+deb12u3",section:"localization",description:"GNU C Library: National Language (locale) data",shortDesc:"locale data",installedSizeKb:16484,files:[{path:"/etc/locale.gen",content:`en_US.UTF-8 UTF-8
400
+ `,mode:493}]},{name:"ca-certificates",version:"20230311",section:"misc",description:"Common CA certificates",shortDesc:"common CA certificates",installedSizeKb:388,files:[{path:"/etc/ssl/certs/.keep",content:""},{path:"/etc/ssl/private/.keep",content:""},{path:"/usr/share/ca-certificates/.keep",content:""}],onInstall:e=>{e.exists("/etc/ssl")||e.mkdir("/etc/ssl",493),e.exists("/etc/ssl/certs")||e.mkdir("/etc/ssl/certs",493)}},{name:"locales",version:"2.36-9+deb12u3",section:"localization",description:"GNU C Library: National Language (locale) data",shortDesc:"locale data",installedSizeKb:16484,files:[{path:"/etc/locale.gen",content:`en_US.UTF-8 UTF-8
352
401
  `},{path:"/etc/default/locale",content:`LANG=en_US.UTF-8
353
402
  LANGUAGE=en_US:en
354
403
  `}]},{name:"sudo",version:"1.9.13p3-1+deb12u1",section:"admin",description:"Provide limited super user privileges to specific users",shortDesc:"super user privilege execution",installedSizeKb:2304,files:[{path:"/usr/bin/sudo",content:`#!/bin/sh
@@ -364,76 +413,76 @@ echo 'journalctl: virtual stub'
364
413
  echo 'gzip: virtual stub'
365
414
  `,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
366
415
  echo 'neofetch: virtual stub'
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(`
416
+ `,mode:493}]}],ye=class{constructor(t,n){this.vfs=t;this.users=n}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 n=t.split(/\n\n+/);for(let r of n){if(!r.trim())continue;let o=this.parseFields(r),s=o.Package;s&&this.installed.set(s,{name:s,version:o.Version??"unknown",architecture:o.Architecture??"amd64",maintainer:o.Maintainer??"Fortune Maintainers",description:o.Description??"",section:o.Section??"misc",installedSizeKb:Number(o["Installed-Size"]??0),installedAt:o["X-Installed-At"]??new Date().toISOString(),files:(o["X-Files"]??"").split("|").filter(Boolean)})}}persist(){let t=[];for(let n of this.installed.values())t.push([`Package: ${n.name}`,"Status: install ok installed","Priority: optional",`Section: ${n.section}`,`Installed-Size: ${n.installedSizeKb}`,`Maintainer: ${n.maintainer}`,`Architecture: ${n.architecture}`,`Version: ${n.version}`,`Description: ${n.description}`,`X-Installed-At: ${n.installedAt}`,`X-Files: ${n.files.join("|")}`].join(`
368
417
  `));this.vfs.writeFile(this.registryPath,`${t.join(`
369
418
 
370
419
  `)}
371
- `)}parseFields(t){let e={};for(let n of t.split(`
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}
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(`
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(`
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(`
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(`
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(`
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(`
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(`
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(`
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(`
383
- `),n=Array.from(this.sudoers.values()).sort().join(`
384
- `),i=Array.from(this.quotas.entries()).sort(([o],[a])=>o.localeCompare(a)).map(([o,a])=>`${o}:${a}`).join(`
385
- `),s=!1;s=this.writeIfChanged(this.usersPath,e.length>0?`${e}
386
- `:"",384)||s,s=this.writeIfChanged(this.sudoersPath,n.length>0?`${n}
387
- `:"",384)||s,s=this.writeIfChanged(this.quotasPath,i.length>0?`${i}
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
420
+ `)}parseFields(t){let n={};for(let r of t.split(`
421
+ `)){let o=r.indexOf(": ");o!==-1&&(n[r.slice(0,o)]=r.slice(o+2))}return n}log(t){let r=`${new Date().toISOString().replace("T"," ").slice(0,19)} ${t}
422
+ `,o=this.vfs.exists(this.logPath)?this.vfs.readFile(this.logPath):"";this.vfs.writeFile(this.logPath,o+r)}aptLog(t,n){let r=new Date().toISOString(),o=this.vfs.exists(this.aptLogPath)?this.vfs.readFile(this.aptLogPath):"",s=[`Start-Date: ${r}`,`Commandline: apt-get ${t} ${n.join(" ")}`,`${t==="install"?"Install":"Remove"}: ${n.join(", ")}`,`End-Date: ${r}`,""].join(`
423
+ `);this.vfs.writeFile(this.aptLogPath,o+s)}findInRegistry(t){return Ue.find(n=>n.name.toLowerCase()===t.toLowerCase())}listAvailable(){return[...Ue].sort((t,n)=>t.name.localeCompare(n.name))}listInstalled(){return[...this.installed.values()].sort((t,n)=>t.name.localeCompare(n.name))}isInstalled(t){return this.installed.has(t.toLowerCase())}installedCount(){return this.installed.size}install(t,n={}){let r=[],o=[],s=[],i=(c,l=new Set)=>{if(l.has(c)||(l.add(c),this.isInstalled(c)))return;let u=this.findInRegistry(c);if(!u){s.push(c);return}for(let d of u.depends??[])i(d,l);o.find(d=>d.name===u.name)||o.push(u)};for(let c of t)i(c);if(s.length>0)return{output:`E: Unable to locate package ${s.join(", ")}`,exitCode:100};if(o.length===0)return{output:t.map(c=>`${c} is already the newest version.`).join(`
424
+ `),exitCode:0};let a=o.reduce((c,l)=>c+(l.installedSizeKb??0),0);n.quiet||r.push("Reading package lists... Done","Building dependency tree... Done","Reading state information... Done","The following NEW packages will be installed:",` ${o.map(c=>c.name).join(" ")}`,`0 upgraded, ${o.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 c of o){n.quiet||(r.push(`Selecting previously unselected package ${c.name}.`),r.push("(Reading database ... 12345 files and directories currently installed.)"),r.push(`Preparing to unpack .../archives/${c.name}_${c.version}_amd64.deb ...`),r.push(`Unpacking ${c.name} (${c.version}) ...`));for(let u of c.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})}c.onInstall?.(this.vfs,this.users),n.quiet||r.push(`Setting up ${c.name} (${c.version}) ...`);let l=new Date().toISOString();this.installed.set(c.name,{name:c.name,version:c.version,architecture:c.architecture??"amd64",maintainer:c.maintainer??"Fortune Maintainers <pkg@fortune.local>",description:c.description,section:c.section??"misc",installedSizeKb:c.installedSizeKb??0,installedAt:l,files:(c.files??[]).map(u=>u.path)}),this.log(`install ${c.name} ${c.version}`)}return this.aptLog("install",o.map(c=>c.name)),this.persist(),n.quiet||r.push("Processing triggers for man-db (2.11.2-2) ..."),{output:r.join(`
425
+ `),exitCode:0}}remove(t,n={}){let r=[],o=[];for(let s of t){let i=this.installed.get(s.toLowerCase());i?o.push(i):r.push(`Package '${s}' is not installed, so not removed`)}if(o.length===0)return{output:r.join(`
426
+ `)||"Nothing to remove.",exitCode:0};n.quiet||r.push("Reading package lists... Done","Building dependency tree... Done","The following packages will be REMOVED:",` ${o.map(s=>s.name).join(" ")}`,`0 upgraded, 0 newly installed, ${o.length} to remove and 0 not upgraded.`);for(let s of o){n.quiet||r.push(`Removing ${s.name} (${s.version}) ...`);for(let a of s.files)if(!(!n.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",o.map(s=>s.name)),this.persist(),{output:r.join(`
427
+ `),exitCode:0}}search(t){let n=t.toLowerCase();return Ue.filter(r=>r.name.includes(n)||r.description.toLowerCase().includes(n)||(r.shortDesc??"").toLowerCase().includes(n)).sort((r,o)=>r.name.localeCompare(o.name))}show(t){let n=this.findInRegistry(t);if(!n)return null;let r=this.installed.get(t);return[`Package: ${n.name}`,`Version: ${n.version}`,`Architecture: ${n.architecture??"amd64"}`,`Maintainer: ${n.maintainer??"Fortune Maintainers <pkg@fortune.local>"}`,`Installed-Size: ${n.installedSizeKb??0}`,`Depends: ${(n.depends??[]).join(", ")||"(none)"}`,`Section: ${n.section??"misc"}`,"Priority: optional",`Description: ${n.description}`,`Status: ${r?"install ok installed":"install ok not-installed"}`].join(`
428
+ `)}};import{createHash as bs,randomBytes as ni,randomUUID as ri,scryptSync as si,timingSafeEqual as oi}from"node:crypto";import{EventEmitter as ii}from"node:events";import*as vs from"node:path";function ai(){let e=process.env.SSH_MIMIC_FAST_PASSWORD_HASH;return!!e&&!["0","false","no","off"].includes(e.toLowerCase())}var tt=he("VirtualUserManager"),Se=class e extends ii{constructor(n,r=!0){super();this.vfs=n;this.autoSudoForNewUsers=r;tt.mark("constructor")}vfs;autoSudoForNewUsers;static recordCache=new Map;static fastPasswordHash=ai();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(){tt.mark("initialize"),this.loadFromVfs(),this.loadSudoersFromVfs(),this.loadQuotasFromVfs();let n=!1;this.users.has("root")||(this.users.set("root",this.createRecord("root","")),n=!0),this.sudoers.add("root"),n&&await this.persist(),this.emit("initialized")}async setQuotaBytes(n,r){if(tt.mark("setQuotaBytes"),this.validateUsername(n),!this.users.has(n))throw new Error(`quota: user '${n}' does not exist`);if(!Number.isFinite(r)||r<0)throw new Error("quota: maxBytes must be a non-negative number");this.quotas.set(n,Math.floor(r)),await this.persist()}async clearQuota(n){tt.mark("clearQuota"),this.validateUsername(n),this.quotas.delete(n),await this.persist()}getQuotaBytes(n){return tt.mark("getQuotaBytes"),this.quotas.get(n)??null}getUsageBytes(n){tt.mark("getUsageBytes");let r=`/home/${n}`;return this.vfs.exists(r)?this.vfs.getUsageBytes(r):0}assertWriteWithinQuota(n,r,o){tt.mark("assertWriteWithinQuota");let s=this.quotas.get(n);if(s===void 0)return;let i=$s(r),a=$s(`/home/${n}`);if(!(i===a||i.startsWith(`${a}/`)))return;let l=this.getUsageBytes(n),u=0;if(this.vfs.exists(i)){let p=this.vfs.stat(i);p.type==="file"&&(u=p.size)}let d=Buffer.isBuffer(o)?o.length:Buffer.byteLength(o,"utf8"),m=l-u+d;if(m>s)throw new Error(`quota exceeded for '${n}': ${m}/${s} bytes`)}verifyPassword(n,r){tt.mark("verifyPassword");let o=this.users.get(n);if(!o)return this.hashPassword(r,""),!1;let s=this.hashPassword(r,o.salt),i=o.passwordHash;try{let a=Buffer.from(s,"hex"),c=Buffer.from(i,"hex");return a.length!==c.length?!1:oi(a,c)}catch{return s===i}}async addUser(n,r){if(tt.mark("addUser"),this.validateUsername(n),this.validatePassword(r),this.users.has(n))return;this.users.set(n,this.createRecord(n,r)),this.autoSudoForNewUsers&&this.sudoers.add(n);let o=`/home/${n}`;this.vfs.exists(o)||(this.vfs.mkdir(o,493),this.vfs.writeFile(`${o}/README.txt`,`Welcome to the virtual environment, ${n}`)),await this.persist(),this.emit("user:add",{username:n})}getPasswordHash(n){tt.mark("getPasswordHash");let r=this.users.get(n);return r?r.passwordHash:null}async setPassword(n,r){if(tt.mark("setPassword"),this.validateUsername(n),this.validatePassword(r),!this.users.has(n))throw new Error(`passwd: user '${n}' does not exist`);this.users.set(n,this.createRecord(n,r)),await this.persist()}async deleteUser(n){if(tt.mark("deleteUser"),this.validateUsername(n),n==="root")throw new Error("deluser: cannot delete root");if(!this.users.delete(n))throw new Error(`deluser: user '${n}' does not exist`);this.sudoers.delete(n),this.emit("user:delete",{username:n}),await this.persist()}isSudoer(n){return tt.mark("isSudoer"),this.sudoers.has(n)}async addSudoer(n){if(tt.mark("addSudoer"),this.validateUsername(n),!this.users.has(n))throw new Error(`sudoers: user '${n}' does not exist`);this.sudoers.add(n),await this.persist()}async removeSudoer(n){if(tt.mark("removeSudoer"),this.validateUsername(n),n==="root")throw new Error("sudoers: cannot remove root");this.sudoers.delete(n),await this.persist()}registerSession(n,r){tt.mark("registerSession");let o={id:ri(),username:n,tty:`pts/${this.nextTty++}`,remoteAddress:r,startedAt:new Date().toISOString()};return this.activeSessions.set(o.id,o),this.emit("session:register",{sessionId:o.id,username:n,remoteAddress:r}),o}unregisterSession(n){if(tt.mark("unregisterSession"),!n)return;let r=this.activeSessions.get(n);this.activeSessions.delete(n),r&&this.emit("session:unregister",{sessionId:n,username:r.username}),this.activeSessions.delete(n)}updateSession(n,r,o){if(tt.mark("updateSession"),!n)return;let s=this.activeSessions.get(n);s&&this.activeSessions.set(n,{...s,username:r,remoteAddress:o})}listActiveSessions(){return tt.mark("listActiveSessions"),Array.from(this.activeSessions.values()).sort((n,r)=>n.startedAt.localeCompare(r.startedAt))}listUsers(){return Array.from(this.users.keys()).sort()}loadFromVfs(){if(this.users.clear(),!this.vfs.exists(this.usersPath))return;let n=this.vfs.readFile(this.usersPath);for(let r of n.split(`
429
+ `)){let o=r.trim();if(o.length===0)continue;let s=o.split(":");if(s.length<3)continue;let[i,a,c]=s;!i||!a||!c||this.users.set(i,{username:i,salt:a,passwordHash:c})}}loadSudoersFromVfs(){if(this.sudoers.clear(),!this.vfs.exists(this.sudoersPath))return;let n=this.vfs.readFile(this.sudoersPath);for(let r of n.split(`
430
+ `)){let o=r.trim();o.length>0&&this.sudoers.add(o)}}loadQuotasFromVfs(){if(this.quotas.clear(),!this.vfs.exists(this.quotasPath))return;let n=this.vfs.readFile(this.quotasPath);for(let r of n.split(`
431
+ `)){let o=r.trim();if(o.length===0)continue;let[s,i]=o.split(":"),a=Number.parseInt(i??"",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 n=Array.from(this.users.values()).sort((i,a)=>i.username.localeCompare(a.username)).map(i=>[i.username,i.salt,i.passwordHash].join(":")).join(`
432
+ `),r=Array.from(this.sudoers.values()).sort().join(`
433
+ `),o=Array.from(this.quotas.entries()).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}:${a}`).join(`
434
+ `),s=!1;s=this.writeIfChanged(this.usersPath,n.length>0?`${n}
435
+ `:"",384)||s,s=this.writeIfChanged(this.sudoersPath,r.length>0?`${r}
436
+ `:"",384)||s,s=this.writeIfChanged(this.quotasPath,o.length>0?`${o}
437
+ `:"",384)||s,s&&await this.vfs.flushMirror()}writeIfChanged(n,r,o){return this.vfs.exists(n)&&this.vfs.readFile(n)===r?(this.vfs.chmod(n,o),!1):(this.vfs.writeFile(n,r,{mode:o}),!0)}createRecord(n,r){let o=bs("sha256").update(n).update(":").update(r).digest("hex"),s=e.recordCache.get(o);if(s)return s;let i=ni(16).toString("hex"),a={username:n,salt:i,passwordHash:this.hashPassword(r,i)};return e.recordCache.set(o,a),a}hasPassword(n){tt.mark("hasPassword");let r=this.users.get(n);if(!r)return!1;let o=this.hashPassword("",r.salt);return r.passwordHash===o?!1:!!r.passwordHash}hashPassword(n,r=""){return e.fastPasswordHash?bs("sha256").update(r).update(n).digest("hex"):si(n,r||"",32).toString("hex")}validateUsername(n){if(!n||n.trim()==="")throw new Error("invalid username");if(!/^[a-z_][a-z0-9_-]{0,31}$/i.test(n))throw new Error("invalid username")}validatePassword(n){if(!n||n.trim()==="")throw new Error("invalid password")}authorizedKeys=new Map;addAuthorizedKey(n,r,o){tt.mark("addAuthorizedKey");let s=this.authorizedKeys.get(n)??[];s.push({algo:r,data:o}),this.authorizedKeys.set(n,s),this.emit("key:add",{username:n,algo:r})}removeAuthorizedKeys(n){this.authorizedKeys.delete(n),this.emit("key:remove",{username:n})}getAuthorizedKeys(n){return this.authorizedKeys.get(n)??[]}};function $s(e){let t=vs.posix.normalize(e);return t.startsWith("/")?t:`/${t}`}import{readFile as ci,unlink as li,writeFile as ui}from"node:fs/promises";import*as Be from"node:path";function Cs(e,t,n,r,o,s="unknown",i={cols:80,rows:24},a){let c="",l=0,u=di(a.vfs,n),d=null,m="",p=`/home/${n}`,h=Nt(n,r),y=null,f=null,S=()=>{let _=`/home/${n}`,L=p===_?"~":Be.posix.basename(p)||"/";return pe(n,r,L)},F=Array.from(new Set(Bt())).sort();console.log(`[${o}] Shell started for user '${n}' at ${s}`),(async()=>{let _=`/home/${n}/.bashrc`;if(a.vfs.exists(_))try{let L=a.vfs.readFile(_);for(let U of L.split(`
438
+ `)){let D=U.trim();!D||D.startsWith("#")||await G(D,n,r,"shell",p,a,void 0,h)}}catch{}})();function E(){let _=S();t.write(`\r${_}${c}\x1B[K`);let L=c.length-l;L>0&&t.write(`\x1B[${L}D`)}function x(){t.write("\r\x1B[K")}function A(_){f={..._,buffer:""},x(),t.write(_.prompt)}async function N(_){if(!f)return;let L=f;if(f=null,!_){t.write(`\r
390
439
  Sorry, try again.\r
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(`
440
+ `),E();return}if(!L.commandLine){n=L.targetUser,L.loginShell&&(p=`/home/${n}`),a.users.updateSession(o,n,s),t.write(`\r
441
+ `),E();return}let U=L.loginShell?`/home/${L.targetUser}`:p,D=await Promise.resolve(G(L.commandLine,L.targetUser,r,"shell",U,a));if(t.write(`\r
442
+ `),D.openEditor){await M(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(`${jt(D.stdout)}\r
443
+ `),D.stderr&&t.write(`${jt(D.stderr)}\r
444
+ `),D.switchUser?(n=D.switchUser,p=D.nextCwd??`/home/${n}`,a.users.updateSession(o,n,s)):D.nextCwd&&(p=D.nextCwd),await a.vfs.flushMirror(),E()}async function b(){if(!y)return;let _=y;if(_.kind==="nano"){try{let L=await ci(_.tempPath,"utf8");a.writeFileAsUser(n,_.targetPath,L),await a.vfs.flushMirror()}catch{}await li(_.tempPath).catch(()=>{})}y=null,c="",l=0,t.write(`\r
445
+ `),E()}async function M(_,L,U){a.vfs.exists(_)&&await ui(U,L,"utf8");let D=de(U,i,t);D.on("error",et=>{t.write(`nano: ${et.message}\r
446
+ `),b()}),D.on("close",()=>{b()}),y={kind:"nano",targetPath:_,tempPath:U,process:D}}async function R(){let _=await ss();if(!_){t.write(`htop: no child_process processes to display\r
447
+ `);return}let L=is(_,i,t);L.on("error",U=>{t.write(`htop: ${U.message}\r
448
+ `),b()}),L.on("close",()=>{b()}),y={kind:"htop",targetPath:"",tempPath:"",process:L}}function P(_){c=_,l=c.length,E()}function C(_){c=`${c.slice(0,l)}${_}${c.slice(l)}`,l+=_.length,E()}function I(_,L){let U=L;for(;U>0&&!/\s/.test(_[U-1]);)U-=1;let D=L;for(;D<_.length&&!/\s/.test(_[D]);)D+=1;return{start:U,end:D}}function J(_){let L=_.lastIndexOf("/"),U=L>=0?_.slice(0,L+1):"",D=L>=0?_.slice(L+1):_,et=ue(p,U||".");try{return a.vfs.list(et).filter(T=>!T.startsWith(".")).filter(T=>T.startsWith(D)).map(T=>{let ft=Be.posix.join(et,T),Ct=a.vfs.stat(ft).type==="directory"?"/":"";return`${U}${T}${Ct}`}).sort()}catch{return[]}}function W(){let{start:_,end:L}=I(c,l),U=c.slice(_,l);if(U.length===0)return;let et=c.slice(0,_).trim().length===0?F.filter(ut=>ut.startsWith(U)):[],T=J(U),ft=Array.from(new Set([...et,...T])).sort();if(ft.length!==0){if(ft.length===1){let ut=ft[0],Ct=ut.endsWith("/")?"":" ";c=`${c.slice(0,_)}${ut}${Ct}${c.slice(L)}`,l=_+ut.length+Ct.length,E();return}t.write(`\r
449
+ `),t.write(`${ft.join(" ")}\r
450
+ `),E()}}function Y(_){if(_.length===0)return;u.push(_),u.length>500&&(u=u.slice(u.length-500));let L=u.length>0?`${u.join(`
402
451
  `)}
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
415
- `),L.closeSession){t.write(`logout\r
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(`
452
+ `:"";a.vfs.writeFile(`/home/${n}/.bash_history`,L)}function St(){let _=`/home/${n}/.lastlog.json`;if(!a.vfs.exists(_))return null;try{return JSON.parse(a.vfs.readFile(_))}catch{return null}}function pt(_){let L=`/home/${n}/.lastlog`;a.vfs.writeFile(L,JSON.stringify({at:_,from:s}))}function wt(){let _=St(),L=new Date().toISOString();t.write(me(r,e,_)),pt(L)}wt(),E(),t.on("data",async _=>{if(y){y.process.stdin.write(_);return}if(f){let U=_.toString("utf8");for(let D=0;D<U.length;D+=1){let et=U[D];if(et===""){f=null,t.write(`^C\r
453
+ `),E();return}if(et==="\x7F"||et==="\b"){f.buffer=f.buffer.slice(0,-1);continue}if(et==="\r"||et===`
454
+ `){let T=f.buffer;if(f.buffer="",f.onPassword){let{result:ut,nextPrompt:Ct}=await f.onPassword(T,a);t.write(`\r
455
+ `),ut!==null?(f=null,ut.stdout&&t.write(ut.stdout.replace(/\n/g,`\r
456
+ `)),ut.stderr&&t.write(ut.stderr.replace(/\n/g,`\r
457
+ `)),E()):(Ct&&(f.prompt=Ct),t.write(f.prompt));return}let ft=a.users.verifyPassword(f.username,T);await N(ft);return}et>=" "&&(f.buffer+=et)}return}let L=_.toString("utf8");for(let U=0;U<L.length;U+=1){let D=L[U];if(D===""){c="",l=0,d=null,m="",t.write(`bye\r
458
+ `),Y("bye"),await a.vfs.flushMirror(),t.write(`logout\r
459
+ `),t.exit(0),t.end();return}if(D===" "){W();continue}if(D==="\x1B"){let et=L[U+1],T=L[U+2],ft=L[U+3];if(et==="["&&T){if(T==="A"){U+=2,u.length>0&&(d===null?(m=c,d=u.length-1):d>0&&(d-=1),P(u[d]??""));continue}if(T==="B"){U+=2,d!==null&&(d<u.length-1?(d+=1,P(u[d]??"")):(d=null,P(m)));continue}if(T==="C"){U+=2,l<c.length&&(l+=1,t.write("\x1B[C"));continue}if(T==="D"){U+=2,l>0&&(l-=1,t.write("\x1B[D"));continue}if(T==="3"&&ft==="~"){U+=3,l<c.length&&(c=`${c.slice(0,l)}${c.slice(l+1)}`,E());continue}}}if(D===""){c="",l=0,d=null,m="",t.write(`^C\r
460
+ `),E();continue}if(D==="\r"||D===`
461
+ `){let et=c.trim();if(c="",l=0,d=null,m="",t.write(`\r
462
+ `),et.length>0){let T=await Promise.resolve(G(et,n,r,"shell",p,a,void 0,h));if(Y(et),T.openEditor){await M(T.openEditor.targetPath,T.openEditor.initialContent,T.openEditor.tempPath);return}if(T.openHtop){await R();return}if(T.sudoChallenge){A(T.sudoChallenge);return}if(T.clearScreen&&t.write("\x1B[2J\x1B[H"),T.stdout&&t.write(`${jt(T.stdout)}\r
463
+ `),T.stderr&&t.write(`${jt(T.stderr)}\r
464
+ `),T.closeSession){t.write(`logout\r
465
+ `),t.exit(T.exitCode??0),t.end();return}T.nextCwd&&(p=T.nextCwd),T.switchUser&&(n=T.switchUser,p=T.nextCwd??`/home/${n}`,a.users.updateSession(o,n,s),c="",l=0),await a.vfs.flushMirror()}E();continue}if(D==="\x7F"||D==="\b"){l>0&&(c=`${c.slice(0,l-1)}${c.slice(l)}`,l-=1,E());continue}C(D)}}),t.on("close",()=>{y&&(y.process.kill("SIGTERM"),y=null)})}function di(e,t){let n=`/home/${t}/.bash_history`;return e.exists(n)?e.readFile(n).split(`
466
+ `).map(o=>o.trim()).filter(o=>o.length>0):(e.writeFile(n,""),[])}function pi(e){return typeof e=="object"&&e!==null&&"vfsInstance"in e&&Ps(e.vfsInstance)}function Ps(e){if(typeof e!="object"||e===null)return!1;let t=e;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 fi={kernel:"1.0.0+itsrealfortune+1-amd64",os:"Fortune GNU/Linux x64",arch:"x86_64"},Ht=he("VirtualShell");function hi(){let e=process.env.SSH_MIMIC_AUTO_SUDO_NEW_USERS;return e?!["0","false","no","off"].includes(e.toLowerCase()):!0}var we=class extends mi{vfs;users;packageManager;hostname;properties;startTime;initialized;constructor(t,n,r){super(),Ht.mark("constructor"),this.hostname=t,this.properties=n||fi,this.startTime=Date.now(),Ps(r)?this.vfs=r:pi(r)?this.vfs=r.vfsInstance:this.vfs=new xs(r??{}),this.users=new Se(this.vfs,hi()),this.packageManager=new ye(this.vfs,this.users);let o=this.vfs,s=this.users,i=this.packageManager,a=this.properties,c=this.hostname,l=this.startTime;this.initialized=(async()=>{await o.restoreMirror(),await s.initialize(),ls(o,s,c,a,l),i.load(),this.emit("initialized")})()}async ensureInitialized(){Ht.mark("ensureInitialized"),await this.initialized}addCommand(t,n,r){let o=t.trim().toLowerCase();if(o.length===0||/\s/.test(o))throw new Error("Command name must be non-empty and contain no spaces");Me(Ae(o,n,r))}executeCommand(t,n,r){Ht.mark("executeCommand"),G(t,n,this.hostname,"shell",r,this),this.emit("command",{command:t,user:n,cwd:r})}startInteractiveSession(t,n,r,o,s){Ht.mark("startInteractiveSession"),this.emit("session:start",{user:n,sessionId:r,remoteAddress:o}),Cs(this.properties,t,n,this.hostname,r,o,s,this),this.refreshProcSessions()}refreshProcFs(){fe(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}mount(t,n,r={}){this.vfs.mount(t,n,r)}unmount(t){this.vfs.unmount(t)}getMounts(){return this.vfs.getMounts()}refreshProcSessions(){fe(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}syncPasswd(){Ve(this.vfs,this.users)}getVfs(){return this?.vfs??null}getUsers(){return this?.users??null}getHostname(){return this?.hostname}writeFileAsUser(t,n,r){Ht.mark("writeFileAsUser"),this.users.assertWriteWithinQuota(t,n,r),this.vfs.writeFile(n,r)}};var Rt=process.env.SSH_MIMIC_HOSTNAME??"typescript-vm",Oe=process.argv.slice(2);function bi(){for(let e=0;e<Oe.length;e+=1){let t=Oe[e];if(t==="--user"){let n=Oe[e+1];if(!n||n.startsWith("--"))throw new Error("self-standalone: --user requires a value");return n}if(t?.startsWith("--user="))return t.slice(7)||"root"}return"root"}var $i=bi(),Z=new we(Rt,void 0,{mode:"fs",snapshotPath:".vfs"});function vi(e){let t=`/home/${e}/.lastlog`;if(!Z.vfs.exists(t))return null;try{return JSON.parse(Z.vfs.readFile(t))}catch{return null}}function Ci(e,t){Z.vfs.writeFile(`/home/${e}/.lastlog`,JSON.stringify({at:new Date().toISOString(),from:t}))}async function qt(){await Z.vfs.flushMirror()}function Pi(e){let t=`/home/${e}/.bash_history`;return Z.vfs.exists(t)?Z.vfs.readFile(t).split(`
467
+ `).map(n=>n.trim()).filter(n=>n.length>0):(Z.vfs.writeFile(t,""),[])}function ki(e,t){let n=e.length>0?`${e.join(`
419
468
  `)}
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(`
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===`
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
469
+ `:"";Z.vfs.writeFile(`/home/${t}/.bash_history`,n)}function Mi(e,t,n){let r=n.lastIndexOf("/"),o=r>=0?n.slice(0,r+1):"",s=r>=0?n.slice(r+1):n,i=ue(t,o||".");try{return e.list(i).filter(a=>!a.startsWith(".")&&a.startsWith(s)).map(a=>{let c=ks.posix.join(i,a),l=e.stat(c);return`${o}${a}${l.type==="directory"?"/":""}`}).sort()}catch{return[]}}function Ai(e){let t=Array.from(new Set(Bt())).sort();return(n,r)=>{let{cwd:o}=e(),s=n.split(/\s+/).at(-1)??"",a=n.trimStart()===s?t.filter(u=>u.startsWith(s)):[],c=Mi(Z.vfs,o,s),l=Array.from(new Set([...a,...c])).sort();r(null,[l,s])}}function Kt(e,t){return new Promise(n=>{if(!ct.isTTY||!st.isTTY){e.question(t,n);return}let r=!!ct.isRaw,o="",s=()=>{ct.off("data",a),r||ct.setRawMode(!1)},i=c=>{s(),st.write(`
470
+ `),n(c)},a=c=>{let l=c.toString("utf8");for(let u=0;u<l.length;u+=1){let d=l[u];if(d==="\r"||d===`
471
+ `){i(o);return}if(d==="\x7F"||d==="\b"){o=o.slice(0,-1);continue}d>=" "&&(o+=d)}};e.pause(),st.write(t),r||ct.setRawMode(!0),ct.resume(),ct.on("data",a)})}function Ei(e,t,n,r){let o=e,s=t;return n.switchUser?(o=n.switchUser,s=n.nextCwd??`/home/${o}`,r.vars.USER=o,r.vars.LOGNAME=o,r.vars.HOME=`/home/${o}`,r.vars.PWD=s):n.nextCwd&&(s=n.nextCwd,r.vars.PWD=s),{authUser:o,cwd:s}}Z.addCommand("demo",[],()=>({stdout:"This is a demo command. It does nothing useful.",exitCode:0}));async function Fi(){await Z.ensureInitialized();let e=$i.trim()||"root";Z.users.getPasswordHash(e)===null&&(process.stderr.write(`self-standalone: user '${e}' does not exist
472
+ `),process.exit(1));let t=Nt(e,Rt),n=e,r=`/home/${n}`;t.vars.PWD=r;let o="localhost",s={cols:st.columns??80,rows:st.rows??24},i=Pi(n),a=xi({input:ct,output:st,terminal:!0,completer:Ai(()=>({cwd:r}))}),c=a;c.history=[...i].reverse();async function l(f,S,F){Z.vfs.exists(f)&&await Si(F,S,"utf8"),a.pause();let E=de(F,s,{write:st.write.bind(st),exit:()=>{},end:()=>{}}),x=!!ct.isRaw,A=N=>{E.stdin.write(N)};ct.resume(),x||ct.setRawMode(!0),ct.on("data",A),await new Promise(N=>{let b=()=>{ct.off("data",A),x||ct.setRawMode(!1),a.resume()};E.on("error",M=>{b(),st.write(`nano: ${M.message}\r
473
+ `),N()}),E.on("close",async()=>{b(),a.write("",{ctrl:!0,name:"u"});try{let M=await gi(F,"utf8");Z.writeFileAsUser(n,f,M),await qt()}catch{}await yi(F).catch(()=>{}),st.write(`\r
474
+ `),N()})})}async function u(f){if(f.onPassword){let x=f.prompt;for(;;){let A=await Kt(a,x),N=await f.onPassword(A,Z);if(N.result===null){x=N.nextPrompt??x;continue}await m(N.result);return}}let S=await Kt(a,f.prompt);if(!Z.users.verifyPassword(f.username,S)){process.stderr.write(`Sorry, try again.
475
+ `);return}if(!f.commandLine){n=f.targetUser,r=`/home/${n}`,t.vars.USER=n,t.vars.LOGNAME=n,t.vars.HOME=`/home/${n}`,t.vars.PWD=r;return}let F=f.loginShell?`/home/${f.targetUser}`:r,E=await G(f.commandLine,f.targetUser,Rt,"shell",F,Z,void 0,t);await m(E)}async function d(f){let S=await Kt(a,f.prompt);if(f.confirmPrompt&&await Kt(a,f.confirmPrompt)!==S){process.stderr.write(`passwords do not match
476
+ `);return}switch(f.action){case"passwd":await Z.users.setPassword(f.targetUsername,S),st.write(`passwd: password updated successfully
428
477
  `);break;case"adduser":if(!f.newUsername){process.stderr.write(`adduser: missing username
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}' ...
478
+ `);return}await Z.users.addUser(f.newUsername,S),st.write(`adduser: user '${f.newUsername}' created
479
+ `);break;case"deluser":await Z.users.deleteUser(f.targetUsername),st.write(`Removing user '${f.targetUsername}' ...
431
480
  deluser: done.
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(`
481
+ `);break;case"su":n=f.targetUsername,r=`/home/${n}`,t.vars.USER=n,t.vars.LOGNAME=n,t.vars.HOME=`/home/${n}`,t.vars.PWD=r;break}}async function m(f){if(f.openEditor){await l(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&&(st.write("\x1B[2J\x1B[H"),console.clear()),f.stdout&&st.write(f.stdout.endsWith(`
433
482
  `)?f.stdout:`${f.stdout}
434
483
  `),f.stderr&&process.stderr.write(f.stderr.endsWith(`
435
484
  `)?f.stderr:`${f.stderr}
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)});
485
+ `);let S=Ei(n,r,f,t);n=S.authUser,r=S.cwd,f.closeSession&&(await qt(),a.close(),process.exit(f.exitCode??0))}let p=()=>{let f=r===`/home/${n}`?"~":wi(r)||"/";return pe(n,Rt,f)},h=()=>{a.setPrompt(p()),a.prompt()};if(process.env.USER!=="root"&&Z.users.hasPassword(n)){let f=await Kt(a,`Password for ${n}: `);Z.users.verifyPassword(n,f)||(process.stderr.write(`self-standalone: authentication failed
486
+ `),process.exit(1))}st.write(me(Rt,Z.properties,vi(n))),Ci(n,o),await qt();let y=!1;a.on("line",async f=>{if(y)return;y=!0,a.pause(),f.trim().length>0&&(i.push(f),i.length>500&&(i=i.slice(i.length-500)),ki(i,n),c.history=[...i].reverse());let F=await G(f,n,Rt,"shell",r,Z,void 0,t);await m(F),await qt(),y=!1,a.resume(),h()}),a.on("SIGINT",()=>{st.write(`^C
487
+ `),a.write("",{ctrl:!0,name:"u"}),h()}),a.on("close",()=>{qt().then(()=>{console.log(""),process.exit(0)})}),h()}Fi().catch(e=>{console.error("Failed to start readline SSH emulation:",e),process.exit(1)});process.on("uncaughtException",e=>{console.error("Uncaught exception:",e)});process.on("unhandledRejection",(e,t)=>{console.error("Unhandled rejection at:",t,"error:",e)});
439
488
  //# sourceMappingURL=self-standalone.js.map